repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/EditorFeatures/TestUtilities/Completion/AbstractCompletionProviderTests.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.Security; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using Moq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using RoslynCompletion = Microsoft.CodeAnalysis.Completion; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Completion { [UseExportProvider] public abstract class AbstractCompletionProviderTests<TWorkspaceFixture> : TestBase where TWorkspaceFixture : TestWorkspaceFixture, new() { private static readonly TestComposition s_baseComposition = EditorTestCompositions.EditorFeatures.AddExcludedPartTypes(typeof(CompletionProvider)); private readonly TestFixtureHelper<TWorkspaceFixture> _fixtureHelper = new(); protected readonly Mock<ICompletionSession> MockCompletionSession; private ExportProvider _lazyExportProvider; protected bool? TargetTypedCompletionFilterFeatureFlag { get; set; } protected bool? TypeImportCompletionFeatureFlag { get; set; } protected AbstractCompletionProviderTests() { MockCompletionSession = new Mock<ICompletionSession>(MockBehavior.Strict); } protected ExportProvider ExportProvider => _lazyExportProvider ??= GetComposition().ExportProviderFactory.CreateExportProvider(); protected virtual TestComposition GetComposition() => s_baseComposition.AddParts(GetCompletionProviderType()); private protected ReferenceCountedDisposable<TWorkspaceFixture> GetOrCreateWorkspaceFixture() => _fixtureHelper.GetOrCreateFixture(); protected static async Task<bool> CanUseSpeculativeSemanticModelAsync(Document document, int position) { var service = document.GetLanguageService<ISyntaxFactsService>(); var node = (await document.GetSyntaxRootAsync()).FindToken(position).Parent; return !service.GetMemberBodySpanForSpeculativeBinding(node).IsEmpty; } internal virtual CompletionServiceWithProviders GetCompletionService(Project project) { var completionService = project.LanguageServices.GetRequiredService<CompletionService>(); var completionServiceWithProviders = Assert.IsAssignableFrom<CompletionServiceWithProviders>(completionService); var completionProviders = ((IMefHostExportProvider)project.Solution.Workspace.Services.HostServices).GetExports<CompletionProvider>(); var completionProvider = Assert.Single(completionProviders).Value; Assert.IsType(GetCompletionProviderType(), completionProvider); return completionServiceWithProviders; } internal static ImmutableHashSet<string> GetRoles(Document document) => document.SourceCodeKind == SourceCodeKind.Regular ? ImmutableHashSet<string>.Empty : ImmutableHashSet.Create(PredefinedInteractiveTextViewRoles.InteractiveTextViewRole); protected abstract string ItemPartiallyWritten(string expectedItemOrNull); protected abstract TestWorkspace CreateWorkspace(string fileContents); private protected abstract Task BaseVerifyWorkerAsync( string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List<CompletionFilter> matchingFilters, CompletionItemFlags? flags); internal static Task<RoslynCompletion.CompletionList> GetCompletionListAsync( CompletionService service, Document document, int position, RoslynCompletion.CompletionTrigger triggerInfo, OptionSet options = null) { return service.GetCompletionsAsync(document, position, triggerInfo, GetRoles(document), options); } private protected async Task CheckResultsAsync( Document document, int position, string expectedItemOrNull, string expectedDescriptionOrNull, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionModeItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List<CompletionFilter> matchingFilters, CompletionItemFlags? flags) { var code = (await document.GetTextAsync()).ToString(); var trigger = RoslynCompletion.CompletionTrigger.Invoke; if (usePreviousCharAsTrigger) { trigger = RoslynCompletion.CompletionTrigger.CreateInsertionTrigger(insertedCharacter: code.ElementAt(position - 1)); } var completionService = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(completionService, document, position, trigger); var items = completionList == null ? ImmutableArray<RoslynCompletion.CompletionItem>.Empty : completionList.Items; if (hasSuggestionModeItem != null) { Assert.Equal(hasSuggestionModeItem.Value, completionList.SuggestionModeItem != null); } if (checkForAbsence) { if (items == null) { return; } if (expectedItemOrNull == null) { Assert.Empty(items); } else { AssertEx.None( items, c => CompareItems(c.DisplayText, expectedItemOrNull) && CompareItems(c.DisplayTextSuffix, displayTextSuffix ?? "") && CompareItems(c.DisplayTextPrefix, displayTextPrefix ?? "") && CompareItems(c.InlineDescription, inlineDescription ?? "") && (expectedDescriptionOrNull != null ? completionService.GetDescriptionAsync(document, c).Result.Text == expectedDescriptionOrNull : true)); } } else { if (expectedItemOrNull == null) { Assert.NotEmpty(items); } else { AssertEx.Any(items, Predicate); } } bool Predicate(RoslynCompletion.CompletionItem c) { if (!CompareItems(c.DisplayText, expectedItemOrNull)) return false; if (!CompareItems(c.DisplayTextSuffix, displayTextSuffix ?? "")) return false; if (!CompareItems(c.DisplayTextPrefix, displayTextPrefix ?? "")) return false; if (!CompareItems(c.InlineDescription, inlineDescription ?? "")) return false; if (expectedDescriptionOrNull != null && completionService.GetDescriptionAsync(document, c).Result.Text != expectedDescriptionOrNull) return false; if (glyph.HasValue && !c.Tags.SequenceEqual(GlyphTags.GetTags((Glyph)glyph.Value))) return false; if (matchPriority.HasValue && c.Rules.MatchPriority != matchPriority.Value) return false; if (matchingFilters != null && !FiltersMatch(matchingFilters, c)) return false; if (flags != null && flags.Value != c.Flags) return false; if (isComplexTextEdit is bool textEdit && textEdit != c.IsComplexTextEdit) return false; return true; } } private static bool FiltersMatch(List<CompletionFilter> expectedMatchingFilters, RoslynCompletion.CompletionItem item) { var matchingFilters = FilterSet.GetFilters(item); // Check that the list has no duplicates. Assert.Equal(matchingFilters.Count, matchingFilters.Distinct().Count()); return expectedMatchingFilters.SetEquals(matchingFilters); } private async Task VerifyAsync( string markup, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind? sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionModeItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List<CompletionFilter> matchingFilters, CompletionItemFlags? flags) { foreach (var sourceKind in sourceCodeKind.HasValue ? new[] { sourceCodeKind.Value } : new[] { SourceCodeKind.Regular, SourceCodeKind.Script }) { using var workspaceFixture = GetOrCreateWorkspaceFixture(); var workspace = workspaceFixture.Target.GetWorkspace(markup, ExportProvider); var code = workspaceFixture.Target.Code; var position = workspaceFixture.Target.Position; var newOptions = WithChangedOptions(workspace.Options); if (TargetTypedCompletionFilterFeatureFlag.HasValue) { newOptions = newOptions.WithChangedOption(CompletionOptions.TargetTypedCompletionFilterFeatureFlag, TargetTypedCompletionFilterFeatureFlag.Value); } if (TypeImportCompletionFeatureFlag.HasValue) { newOptions = newOptions.WithChangedOption(CompletionOptions.TypeImportCompletionFeatureFlag, TypeImportCompletionFeatureFlag.Value); } workspace.SetOptions(newOptions); await VerifyWorkerAsync( code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority, hasSuggestionModeItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags).ConfigureAwait(false); } } protected async Task<CompletionList> GetCompletionListAsync(string markup, string workspaceKind = null) { using var workspaceFixture = GetOrCreateWorkspaceFixture(); var workspace = workspaceFixture.Target.GetWorkspace(markup, ExportProvider, workspaceKind: workspaceKind); var currentDocument = workspace.CurrentSolution.GetDocument(workspaceFixture.Target.CurrentDocument.Id); var position = workspaceFixture.Target.Position; currentDocument = WithChangedOptions(currentDocument); return await GetCompletionListAsync(GetCompletionService(currentDocument.Project), currentDocument, position, RoslynCompletion.CompletionTrigger.Invoke, options: workspace.Options).ConfigureAwait(false); } protected async Task VerifyCustomCommitProviderAsync(string markupBeforeCommit, string itemToCommit, string expectedCodeAfterCommit, SourceCodeKind? sourceCodeKind = null, char? commitChar = null) { using var workspaceFixture = GetOrCreateWorkspaceFixture(); using (workspaceFixture.Target.GetWorkspace(markupBeforeCommit, ExportProvider)) { var code = workspaceFixture.Target.Code; var position = workspaceFixture.Target.Position; if (sourceCodeKind.HasValue) { await VerifyCustomCommitProviderWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, sourceCodeKind.Value, commitChar); } else { await VerifyCustomCommitProviderWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, SourceCodeKind.Regular, commitChar); await VerifyCustomCommitProviderWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, SourceCodeKind.Script, commitChar); } } } protected async Task VerifyProviderCommitAsync( string markupBeforeCommit, string itemToCommit, string expectedCodeAfterCommit, char? commitChar, SourceCodeKind? sourceCodeKind = null) { using var workspaceFixture = GetOrCreateWorkspaceFixture(); workspaceFixture.Target.GetWorkspace(markupBeforeCommit, ExportProvider); var code = workspaceFixture.Target.Code; var position = workspaceFixture.Target.Position; expectedCodeAfterCommit = expectedCodeAfterCommit.NormalizeLineEndings(); if (sourceCodeKind.HasValue) { await VerifyProviderCommitWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, commitChar, sourceCodeKind.Value); } else { await VerifyProviderCommitWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, commitChar, SourceCodeKind.Regular); await VerifyProviderCommitWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, commitChar, SourceCodeKind.Script); } } protected bool CompareItems(string actualItem, string expectedItem) => GetStringComparer().Equals(actualItem, expectedItem); protected virtual IEqualityComparer<string> GetStringComparer() => StringComparer.Ordinal; private protected async Task VerifyItemExistsAsync( string markup, string expectedItem, string expectedDescriptionOrNull = null, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false, int? glyph = null, int? matchPriority = null, bool? hasSuggestionModeItem = null, string displayTextSuffix = null, string displayTextPrefix = null, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence: false, glyph: glyph, matchPriority: matchPriority, hasSuggestionModeItem: hasSuggestionModeItem, displayTextSuffix: displayTextSuffix, displayTextPrefix: displayTextPrefix, inlineDescription: inlineDescription, isComplexTextEdit: isComplexTextEdit, matchingFilters: matchingFilters, flags: flags); } private protected async Task VerifyItemIsAbsentAsync( string markup, string expectedItem, string expectedDescriptionOrNull = null, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false, bool? hasSuggestionModeItem = null, string displayTextSuffix = null, string displayTextPrefix = null, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence: true, glyph: null, matchPriority: null, hasSuggestionModeItem: hasSuggestionModeItem, displayTextSuffix: displayTextSuffix, displayTextPrefix: displayTextPrefix, inlineDescription: inlineDescription, isComplexTextEdit: isComplexTextEdit, matchingFilters: matchingFilters, flags: flags); } protected async Task VerifyAnyItemExistsAsync( string markup, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false, bool? hasSuggestionModeItem = null, string displayTextSuffix = null, string displayTextPrefix = null, string inlineDescription = null) { await VerifyAsync(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: false, glyph: null, matchPriority: null, hasSuggestionModeItem: hasSuggestionModeItem, displayTextSuffix: displayTextSuffix, displayTextPrefix: displayTextPrefix, inlineDescription: inlineDescription, isComplexTextEdit: null, matchingFilters: null, flags: null); } protected async Task VerifyNoItemsExistAsync( string markup, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false, bool? hasSuggestionModeItem = null, string displayTextSuffix = null, string inlineDescription = null) { await VerifyAsync( markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: true, glyph: null, matchPriority: null, hasSuggestionModeItem: hasSuggestionModeItem, displayTextSuffix: displayTextSuffix, displayTextPrefix: null, inlineDescription: inlineDescription, isComplexTextEdit: null, matchingFilters: null, flags: null); } internal abstract Type GetCompletionProviderType(); /// <summary> /// Override this to change parameters or return without verifying anything, e.g. for script sources. Or to test in other code contexts. /// </summary> /// <param name="code">The source code (not markup).</param> /// <param name="expectedItemOrNull">The expected item. If this is null, verifies that *any* item shows up for this CompletionProvider (or no items show up if checkForAbsence is true).</param> /// <param name="expectedDescriptionOrNull">If this is null, the Description for the item is ignored.</param> /// <param name="usePreviousCharAsTrigger">Whether or not the previous character in markup should be used to trigger IntelliSense for this provider. If false, invokes it through the invoke IntelliSense command.</param> /// <param name="checkForAbsence">If true, checks for absence of a specific item (or that no items are returned from this CompletionProvider)</param> private protected virtual async Task VerifyWorkerAsync( string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionModeItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List<CompletionFilter> matchingFilters, CompletionItemFlags? flags) { using var workspaceFixture = GetOrCreateWorkspaceFixture(); workspaceFixture.Target.GetWorkspace(ExportProvider); var document1 = workspaceFixture.Target.UpdateDocument(code, sourceCodeKind); await CheckResultsAsync( document1, position, expectedItemOrNull, expectedDescriptionOrNull, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority, hasSuggestionModeItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags); if (await CanUseSpeculativeSemanticModelAsync(document1, position)) { var document2 = workspaceFixture.Target.UpdateDocument(code, sourceCodeKind, cleanBeforeUpdate: false); await CheckResultsAsync( document2, position, expectedItemOrNull, expectedDescriptionOrNull, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority, hasSuggestionModeItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags); } } /// <summary> /// Override this to change parameters or return without verifying anything, e.g. for script sources. Or to test in other code contexts. /// </summary> /// <param name="codeBeforeCommit">The source code (not markup).</param> /// <param name="position">Position where intellisense is invoked.</param> /// <param name="itemToCommit">The item to commit from the completion provider.</param> /// <param name="expectedCodeAfterCommit">The expected code after commit.</param> protected virtual async Task VerifyCustomCommitProviderWorkerAsync(string codeBeforeCommit, int position, string itemToCommit, string expectedCodeAfterCommit, SourceCodeKind sourceCodeKind, char? commitChar = null) { using var workspaceFixture = GetOrCreateWorkspaceFixture(); var document1 = workspaceFixture.Target.UpdateDocument(codeBeforeCommit, sourceCodeKind); await VerifyCustomCommitProviderCheckResultsAsync(document1, codeBeforeCommit, position, itemToCommit, expectedCodeAfterCommit, commitChar); if (await CanUseSpeculativeSemanticModelAsync(document1, position)) { var document2 = workspaceFixture.Target.UpdateDocument(codeBeforeCommit, sourceCodeKind, cleanBeforeUpdate: false); await VerifyCustomCommitProviderCheckResultsAsync(document2, codeBeforeCommit, position, itemToCommit, expectedCodeAfterCommit, commitChar); } } private async Task VerifyCustomCommitProviderCheckResultsAsync(Document document, string codeBeforeCommit, int position, string itemToCommit, string expectedCodeAfterCommit, char? commitChar) { document = WithChangedOptions(document); var service = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(service, document, position, RoslynCompletion.CompletionTrigger.Invoke); var items = completionList.Items; Assert.Contains(itemToCommit, items.Select(x => x.DisplayText), GetStringComparer()); var firstItem = items.First(i => CompareItems(i.DisplayText, itemToCommit)); if (service.GetProvider(firstItem) is ICustomCommitCompletionProvider customCommitCompletionProvider) { VerifyCustomCommitWorker(service, customCommitCompletionProvider, firstItem, codeBeforeCommit, expectedCodeAfterCommit, commitChar); } else { await VerifyCustomCommitWorkerAsync(service, document, firstItem, codeBeforeCommit, expectedCodeAfterCommit, commitChar); } } protected virtual OptionSet WithChangedOptions(OptionSet options) => options; private Document WithChangedOptions(Document document) { var workspace = document.Project.Solution.Workspace; var newOptions = WithChangedOptions(workspace.Options); workspace.TryApplyChanges(document.Project.Solution.WithOptions(newOptions)); return workspace.CurrentSolution.GetDocument(document.Id); } private static Document WithChangedOption(Document document, OptionKey optionKey, object value) { var workspace = document.Project.Solution.Workspace; var newOptions = workspace.Options.WithChangedOption(optionKey, value); workspace.TryApplyChanges(document.Project.Solution.WithOptions(newOptions)); return workspace.CurrentSolution.GetDocument(document.Id); } private async Task VerifyCustomCommitWorkerAsync( CompletionServiceWithProviders service, Document document, RoslynCompletion.CompletionItem completionItem, string codeBeforeCommit, string expectedCodeAfterCommit, char? commitChar = null) { using var workspaceFixture = GetOrCreateWorkspaceFixture(); MarkupTestFile.GetPosition(expectedCodeAfterCommit, out var actualExpectedCode, out int expectedCaretPosition); if (commitChar.HasValue && !CommitManager.IsCommitCharacter(service.GetRules(), completionItem, commitChar.Value)) { Assert.Equal(codeBeforeCommit, actualExpectedCode); return; } // textview is created lazily, so need to access it before making // changes to document, so the cursor position is tracked correctly. var textView = workspaceFixture.Target.CurrentDocument.GetTextView(); var options = await document.GetOptionsAsync().ConfigureAwait(false); var commit = await service.GetChangeAsync(document, completionItem, commitChar, CancellationToken.None); var text = await document.GetTextAsync(); var newText = text.WithChanges(commit.TextChange); var newDoc = document.WithText(newText); document.Project.Solution.Workspace.TryApplyChanges(newDoc.Project.Solution); var textBuffer = workspaceFixture.Target.CurrentDocument.GetTextBuffer(); var actualCodeAfterCommit = textBuffer.CurrentSnapshot.AsText().ToString(); var caretPosition = commit.NewPosition ?? textView.Caret.Position.BufferPosition.Position; AssertEx.EqualOrDiff(actualExpectedCode, actualCodeAfterCommit); Assert.Equal(expectedCaretPosition, caretPosition); } private void VerifyCustomCommitWorker( CompletionService service, ICustomCommitCompletionProvider customCommitCompletionProvider, RoslynCompletion.CompletionItem completionItem, string codeBeforeCommit, string expectedCodeAfterCommit, char? commitChar = null) { using var workspaceFixture = GetOrCreateWorkspaceFixture(); MarkupTestFile.GetPosition(expectedCodeAfterCommit, out var actualExpectedCode, out int expectedCaretPosition); if (commitChar.HasValue && !CommitManager.IsCommitCharacter(service.GetRules(), completionItem, commitChar.Value)) { Assert.Equal(codeBeforeCommit, actualExpectedCode); return; } // textview is created lazily, so need to access it before making // changes to document, so the cursor position is tracked correctly. var textView = workspaceFixture.Target.CurrentDocument.GetTextView(); var textBuffer = workspaceFixture.Target.CurrentDocument.GetTextBuffer(); customCommitCompletionProvider.Commit(completionItem, textView, textBuffer, textView.TextSnapshot, commitChar); var actualCodeAfterCommit = textBuffer.CurrentSnapshot.AsText().ToString(); var caretPosition = textView.Caret.Position.BufferPosition.Position; Assert.Equal(actualExpectedCode, actualCodeAfterCommit); Assert.Equal(expectedCaretPosition, caretPosition); } /// <summary> /// Override this to change parameters or return without verifying anything, e.g. for script sources. Or to test in other code contexts. /// </summary> /// <param name="codeBeforeCommit">The source code (not markup).</param> /// <param name="position">Position where intellisense is invoked.</param> /// <param name="itemToCommit">The item to commit from the completion provider.</param> /// <param name="expectedCodeAfterCommit">The expected code after commit.</param> private async Task VerifyProviderCommitWorkerAsync(string codeBeforeCommit, int position, string itemToCommit, string expectedCodeAfterCommit, char? commitChar, SourceCodeKind sourceCodeKind) { using var workspaceFixture = GetOrCreateWorkspaceFixture(); var document1 = workspaceFixture.Target.UpdateDocument(codeBeforeCommit, sourceCodeKind); await VerifyProviderCommitCheckResultsAsync(document1, position, itemToCommit, expectedCodeAfterCommit, commitChar); if (await CanUseSpeculativeSemanticModelAsync(document1, position)) { var document2 = workspaceFixture.Target.UpdateDocument(codeBeforeCommit, sourceCodeKind, cleanBeforeUpdate: false); await VerifyProviderCommitCheckResultsAsync(document2, position, itemToCommit, expectedCodeAfterCommit, commitChar); } } private async Task VerifyProviderCommitCheckResultsAsync( Document document, int position, string itemToCommit, string expectedCodeAfterCommit, char? commitCharOpt) { document = WithChangedOptions(document); var service = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(service, document, position, RoslynCompletion.CompletionTrigger.Invoke); var items = completionList.Items; var firstItem = items.First(i => CompareItems(i.DisplayText + i.DisplayTextSuffix, itemToCommit)); var commitChar = commitCharOpt ?? '\t'; var text = await document.GetTextAsync(); if (commitChar == '\t' || CommitManager.IsCommitCharacter(service.GetRules(), firstItem, commitChar)) { var textChange = (await service.GetChangeAsync(document, firstItem, commitChar, CancellationToken.None)).TextChange; // Adjust TextChange to include commit character, so long as it isn't TAB. if (commitChar != '\t') { textChange = new TextChange(textChange.Span, textChange.NewText.TrimEnd(commitChar) + commitChar); } text = text.WithChanges(textChange); } else { // nothing was committed, but we should insert the commit character. var textChange = new TextChange(new TextSpan(firstItem.Span.End, 0), commitChar.ToString()); text = text.WithChanges(textChange); } Assert.Equal(expectedCodeAfterCommit, text.ToString()); } protected async Task VerifyItemInEditorBrowsableContextsAsync( string markup, string referencedCode, string item, int expectedSymbolsSameSolution, int expectedSymbolsMetadataReference, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers = false) { await VerifyItemWithMetadataReferenceAsync(markup, referencedCode, item, expectedSymbolsMetadataReference, sourceLanguage, referencedLanguage, hideAdvancedMembers); await VerifyItemWithProjectReferenceAsync(markup, referencedCode, item, expectedSymbolsSameSolution, sourceLanguage, referencedLanguage, hideAdvancedMembers); // If the source and referenced languages are different, then they cannot be in the same project if (sourceLanguage == referencedLanguage) { await VerifyItemInSameProjectAsync(markup, referencedCode, item, expectedSymbolsSameSolution, sourceLanguage, hideAdvancedMembers); } } protected Task VerifyItemWithMetadataReferenceAsync(string markup, string metadataReferenceCode, string expectedItem, int expectedSymbols, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) { var xmlString = CreateMarkupForProjectWithMetadataReference(markup, metadataReferenceCode, sourceLanguage, referencedLanguage); return VerifyItemWithReferenceWorkerAsync(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } protected static string GetMarkupWithReference(string currentFile, string referencedFile, string sourceLanguage, string referenceLanguage, bool isProjectReference) { return isProjectReference ? CreateMarkupForProjectWithProjectReference(currentFile, referencedFile, sourceLanguage, referenceLanguage) : CreateMarkupForProjectWithMetadataReference(currentFile, referencedFile, sourceLanguage, referenceLanguage); } protected static string CreateMarkupForProjectWithMetadataReference(string markup, string metadataReferenceCode, string sourceLanguage, string referencedLanguage) { return string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true"" AssemblyName=""Project1""> <Document FilePath=""SourceDocument"">{1}</Document> <MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument"">{3}</Document> </MetadataReferenceFromSource> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(metadataReferenceCode)); } protected Task VerifyItemWithAliasedMetadataReferencesAsync(string markup, string metadataAlias, string expectedItem, int expectedSymbols, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) { var xmlString = CreateMarkupForProjectWithAliasedMetadataReference(markup, metadataAlias, "", sourceLanguage, referencedLanguage); return VerifyItemWithReferenceWorkerAsync(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } protected static string CreateMarkupForProjectWithAliasedMetadataReference(string markup, string metadataAlias, string referencedCode, string sourceLanguage, string referencedLanguage, bool hasGlobalAlias = true) { var aliases = hasGlobalAlias ? $"{metadataAlias},{MetadataReferenceProperties.GlobalAlias}" : $"{metadataAlias}"; return string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true"" AssemblyName=""Project1""> <Document FilePath=""SourceDocument"">{1}</Document> <MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"" Aliases=""{3}"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument"">{4}</Document> </MetadataReferenceFromSource> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(aliases), SecurityElement.Escape(referencedCode)); } protected Task VerifyItemWithProjectReferenceAsync(string markup, string referencedCode, string expectedItem, int expectedSymbols, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) { var xmlString = CreateMarkupForProjectWithProjectReference(markup, referencedCode, sourceLanguage, referencedLanguage); return VerifyItemWithReferenceWorkerAsync(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } protected static string CreateMarkupForProjectWithAliasedProjectReference(string markup, string projectAlias, string referencedCode, string sourceLanguage, string referencedLanguage) { return string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true"" AssemblyName=""Project1""> <ProjectReference Alias=""{4}"">ReferencedProject</ProjectReference> <Document FilePath=""SourceDocument"">{1}</Document> </Project> <Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument"">{3}</Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(referencedCode), SecurityElement.Escape(projectAlias)); } protected static string CreateMarkupForProjectWithProjectReference(string markup, string referencedCode, string sourceLanguage, string referencedLanguage) { return string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true"" AssemblyName=""Project1""> <ProjectReference>ReferencedProject</ProjectReference> <Document FilePath=""SourceDocument"">{1}</Document> </Project> <Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument"">{3}</Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(referencedCode)); } protected static string CreateMarkupForProjectWithMultupleProjectReferences(string sourceText, string sourceLanguage, string referencedLanguage, string[] referencedTexts) { return $@" <Workspace> <Project Language=""{sourceLanguage}"" CommonReferences=""true"" AssemblyName=""Project1""> {GetProjectReferenceElements(referencedTexts)} <Document FilePath=""SourceDocument"">{SecurityElement.Escape(sourceText)}</Document> </Project> {GetReferencedProjectElements(referencedLanguage, referencedTexts)} </Workspace>"; static string GetProjectReferenceElements(string[] referencedTexts) { var builder = new StringBuilder(); for (var i = 0; i < referencedTexts.Length; ++i) { builder.AppendLine($"<ProjectReference>ReferencedProject{i}</ProjectReference>"); } return builder.ToString(); } static string GetReferencedProjectElements(string language, string[] referencedTexts) { var builder = new StringBuilder(); for (var i = 0; i < referencedTexts.Length; ++i) { builder.Append($@" <Project Language=""{language}"" CommonReferences=""true"" AssemblyName=""ReferencedProject{i}"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument{i}"">{SecurityElement.Escape(referencedTexts[i])}</Document> </Project>"); } return builder.ToString(); } } protected static string CreateMarkupForProjecWithVBProjectReference(string markup, string referencedCode, string sourceLanguage, string rootNamespace = "") { return string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true"" AssemblyName=""Project1""> <ProjectReference>ReferencedProject</ProjectReference> <Document FilePath=""SourceDocument"">{1}</Document> </Project> <Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument"">{3}</Document> <CompilationOptions RootNamespace=""{4}""/> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), LanguageNames.VisualBasic, SecurityElement.Escape(referencedCode), rootNamespace); } private Task VerifyItemInSameProjectAsync(string markup, string referencedCode, string expectedItem, int expectedSymbols, string sourceLanguage, bool hideAdvancedMembers) { var xmlString = CreateMarkupForSingleProject(markup, referencedCode, sourceLanguage); return VerifyItemWithReferenceWorkerAsync(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } protected static string CreateMarkupForSingleProject(string markup, string referencedCode, string sourceLanguage) { return string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument"">{1}</Document> <Document FilePath=""ReferencedDocument"">{2}</Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), SecurityElement.Escape(referencedCode)); } private async Task VerifyItemWithReferenceWorkerAsync( string xmlString, string expectedItem, int expectedSymbols, bool hideAdvancedMembers) { using (var testWorkspace = TestWorkspace.Create(xmlString, exportProvider: ExportProvider)) { var position = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value; var solution = testWorkspace.CurrentSolution; var documentId = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").Id; var document = solution.GetDocument(documentId); var optionKey = new OptionKey(CompletionOptions.HideAdvancedMembers, document.Project.Language); document = WithChangedOption(document, optionKey, hideAdvancedMembers); var triggerInfo = RoslynCompletion.CompletionTrigger.Invoke; var completionService = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(completionService, document, position, triggerInfo); if (expectedSymbols >= 1) { Assert.NotNull(completionList); AssertEx.Any(completionList.Items, c => CompareItems(c.DisplayText, expectedItem)); var item = completionList.Items.First(c => CompareItems(c.DisplayText, expectedItem)); var description = await completionService.GetDescriptionAsync(document, item); if (expectedSymbols == 1) { Assert.DoesNotContain("+", description.Text, StringComparison.Ordinal); } else { Assert.Contains(GetExpectedOverloadSubstring(expectedSymbols), description.Text, StringComparison.Ordinal); } } else { if (completionList != null) { AssertEx.None(completionList.Items, c => CompareItems(c.DisplayText, expectedItem)); } } } } protected Task VerifyItemWithMscorlib45Async(string markup, string expectedItem, string expectedDescription, string sourceLanguage) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferencesNet45=""true""> <Document FilePath=""SourceDocument""> {1} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup)); return VerifyItemWithMscorlib45WorkerAsync(xmlString, expectedItem, expectedDescription); } private async Task VerifyItemWithMscorlib45WorkerAsync( string xmlString, string expectedItem, string expectedDescription) { using (var testWorkspace = TestWorkspace.Create(xmlString, exportProvider: ExportProvider)) { var position = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value; var solution = testWorkspace.CurrentSolution; var documentId = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").Id; var document = solution.GetDocument(documentId); var triggerInfo = RoslynCompletion.CompletionTrigger.Invoke; var completionService = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(completionService, document, position, triggerInfo); var item = completionList.Items.FirstOrDefault(i => i.DisplayText == expectedItem); Assert.Equal(expectedDescription, (await completionService.GetDescriptionAsync(document, item)).Text); } } private const char NonBreakingSpace = (char)0x00A0; private static string GetExpectedOverloadSubstring(int expectedSymbols) { if (expectedSymbols <= 1) { throw new ArgumentOutOfRangeException(nameof(expectedSymbols)); } return "+" + NonBreakingSpace + (expectedSymbols - 1) + NonBreakingSpace + FeaturesResources.overload; } protected async Task VerifyItemInLinkedFilesAsync(string xmlString, string expectedItem, string expectedDescription) { using (var testWorkspace = TestWorkspace.Create(xmlString, exportProvider: ExportProvider)) { var position = testWorkspace.Documents.First().CursorPosition.Value; var solution = testWorkspace.CurrentSolution; var textContainer = testWorkspace.Documents.First().GetTextBuffer().AsTextContainer(); var currentContextDocumentId = testWorkspace.GetDocumentIdInCurrentContext(textContainer); var document = solution.GetDocument(currentContextDocumentId); var triggerInfo = RoslynCompletion.CompletionTrigger.Invoke; var completionService = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(completionService, document, position, triggerInfo); var item = completionList.Items.Single(c => c.DisplayText == expectedItem); Assert.NotNull(item); if (expectedDescription != null) { var actualDescription = (await completionService.GetDescriptionAsync(document, item)).Text; Assert.Equal(expectedDescription, actualDescription); } } } private protected Task VerifyAtPositionAsync( string code, int position, string insertText, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { code = code.Substring(0, position) + insertText + code.Substring(position); position += insertText.Length; return BaseVerifyWorkerAsync(code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags); } private protected Task VerifyAtPositionAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { return VerifyAtPositionAsync( code, position, string.Empty, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags); } private protected async Task VerifyAtEndOfFileAsync( string code, int position, string insertText, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { // only do this if the placeholder was at the end of the text. if (code.Length != position) { return; } code = code.Substring(startIndex: 0, length: position) + insertText; position += insertText.Length; await BaseVerifyWorkerAsync( code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags); } private protected Task VerifyAtPosition_ItemPartiallyWrittenAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { return VerifyAtPositionAsync( code, position, ItemPartiallyWritten(expectedItemOrNull), usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags); } private protected Task VerifyAtEndOfFileAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { return VerifyAtEndOfFileAsync(code, position, string.Empty, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags); } private protected Task VerifyAtEndOfFile_ItemPartiallyWrittenAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { return VerifyAtEndOfFileAsync( code, position, ItemPartiallyWritten(expectedItemOrNull), usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags); } protected void VerifyTextualTriggerCharacter( string markup, bool shouldTriggerWithTriggerOnLettersEnabled, bool shouldTriggerWithTriggerOnLettersDisabled, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular, bool showCompletionInArgumentLists = true) { VerifyTextualTriggerCharacterWorker(markup, expectedTriggerCharacter: shouldTriggerWithTriggerOnLettersEnabled, triggerOnLetter: true, sourceCodeKind, showCompletionInArgumentLists); VerifyTextualTriggerCharacterWorker(markup, expectedTriggerCharacter: shouldTriggerWithTriggerOnLettersDisabled, triggerOnLetter: false, sourceCodeKind, showCompletionInArgumentLists: false); } private void VerifyTextualTriggerCharacterWorker( string markup, bool expectedTriggerCharacter, bool triggerOnLetter, SourceCodeKind sourceCodeKind, bool showCompletionInArgumentLists) { using (var workspace = CreateWorkspace(markup)) { var hostDocument = workspace.DocumentWithCursor; workspace.OnDocumentSourceCodeKindChanged(hostDocument.Id, sourceCodeKind); Assert.Same(hostDocument, workspace.Documents.Single()); var position = hostDocument.CursorPosition.Value; var text = hostDocument.GetTextBuffer().CurrentSnapshot.AsText(); var options = workspace.Options .WithChangedOption(CompletionOptions.TriggerOnTypingLetters2, hostDocument.Project.Language, triggerOnLetter) .WithChangedOption(CompletionOptions.TriggerInArgumentLists, hostDocument.Project.Language, showCompletionInArgumentLists); var trigger = RoslynCompletion.CompletionTrigger.CreateInsertionTrigger(text[position]); var document = workspace.CurrentSolution.GetDocument(hostDocument.Id); var service = GetCompletionService(document.Project); var isTextualTriggerCharacterResult = service.ShouldTriggerCompletion(text, position + 1, trigger, GetRoles(document), options); if (expectedTriggerCharacter) { var assertText = "'" + text.ToString(new TextSpan(position, 1)) + "' expected to be textual trigger character"; Assert.True(isTextualTriggerCharacterResult, assertText); } else { var assertText = "'" + text.ToString(new TextSpan(position, 1)) + "' expected to NOT be textual trigger character"; Assert.False(isTextualTriggerCharacterResult, assertText); } } } protected async Task VerifyCommonCommitCharactersAsync(string initialMarkup, string textTypedSoFar) { var commitCharacters = new[] { ' ', '{', '}', '[', ']', '(', ')', '.', ',', ':', ';', '+', '-', '*', '/', '%', '&', '|', '^', '!', '~', '=', '<', '>', '?', '@', '#', '\'', '\"', '\\' }; await VerifyCommitCharactersAsync(initialMarkup, textTypedSoFar, commitCharacters); } protected async Task VerifyCommitCharactersAsync(string initialMarkup, string textTypedSoFar, char[] validChars, char[] invalidChars = null, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular) { Assert.NotNull(validChars); invalidChars = invalidChars ?? new[] { 'x' }; using (var workspace = CreateWorkspace(initialMarkup)) { var hostDocument = workspace.DocumentWithCursor; workspace.OnDocumentSourceCodeKindChanged(hostDocument.Id, sourceCodeKind); var documentId = workspace.GetDocumentId(hostDocument); var document = workspace.CurrentSolution.GetDocument(documentId); var position = hostDocument.CursorPosition.Value; var service = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(service, document, position, RoslynCompletion.CompletionTrigger.Invoke); var item = completionList.Items.First(i => i.DisplayText.StartsWith(textTypedSoFar)); foreach (var ch in validChars) { Assert.True(CommitManager.IsCommitCharacter( service.GetRules(), item, ch), $"Expected '{ch}' to be a commit character"); } foreach (var ch in invalidChars) { Assert.False(CommitManager.IsCommitCharacter( service.GetRules(), item, ch), $"Expected '{ch}' NOT to be a commit character"); } } } protected async Task<ImmutableArray<RoslynCompletion.CompletionItem>> GetCompletionItemsAsync( string markup, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger = false) { using var workspaceFixture = GetOrCreateWorkspaceFixture(); workspaceFixture.Target.GetWorkspace(markup, ExportProvider); var code = workspaceFixture.Target.Code; var position = workspaceFixture.Target.Position; var document = workspaceFixture.Target.UpdateDocument(code, sourceCodeKind); var trigger = usePreviousCharAsTrigger ? RoslynCompletion.CompletionTrigger.CreateInsertionTrigger(insertedCharacter: code.ElementAt(position - 1)) : RoslynCompletion.CompletionTrigger.Invoke; var completionService = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(completionService, document, position, trigger); return completionList == null ? ImmutableArray<RoslynCompletion.CompletionItem>.Empty : completionList.Items; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Security; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using Moq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using RoslynCompletion = Microsoft.CodeAnalysis.Completion; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Completion { [UseExportProvider] public abstract class AbstractCompletionProviderTests<TWorkspaceFixture> : TestBase where TWorkspaceFixture : TestWorkspaceFixture, new() { private static readonly TestComposition s_baseComposition = EditorTestCompositions.EditorFeatures.AddExcludedPartTypes(typeof(CompletionProvider)); private readonly TestFixtureHelper<TWorkspaceFixture> _fixtureHelper = new(); protected readonly Mock<ICompletionSession> MockCompletionSession; private ExportProvider _lazyExportProvider; protected bool? TargetTypedCompletionFilterFeatureFlag { get; set; } protected bool? TypeImportCompletionFeatureFlag { get; set; } protected AbstractCompletionProviderTests() { MockCompletionSession = new Mock<ICompletionSession>(MockBehavior.Strict); } protected ExportProvider ExportProvider => _lazyExportProvider ??= GetComposition().ExportProviderFactory.CreateExportProvider(); protected virtual TestComposition GetComposition() => s_baseComposition.AddParts(GetCompletionProviderType()); private protected ReferenceCountedDisposable<TWorkspaceFixture> GetOrCreateWorkspaceFixture() => _fixtureHelper.GetOrCreateFixture(); protected static async Task<bool> CanUseSpeculativeSemanticModelAsync(Document document, int position) { var service = document.GetLanguageService<ISyntaxFactsService>(); var node = (await document.GetSyntaxRootAsync()).FindToken(position).Parent; return !service.GetMemberBodySpanForSpeculativeBinding(node).IsEmpty; } internal virtual CompletionServiceWithProviders GetCompletionService(Project project) { var completionService = project.LanguageServices.GetRequiredService<CompletionService>(); var completionServiceWithProviders = Assert.IsAssignableFrom<CompletionServiceWithProviders>(completionService); var completionProviders = ((IMefHostExportProvider)project.Solution.Workspace.Services.HostServices).GetExports<CompletionProvider>(); var completionProvider = Assert.Single(completionProviders).Value; Assert.IsType(GetCompletionProviderType(), completionProvider); return completionServiceWithProviders; } internal static ImmutableHashSet<string> GetRoles(Document document) => document.SourceCodeKind == SourceCodeKind.Regular ? ImmutableHashSet<string>.Empty : ImmutableHashSet.Create(PredefinedInteractiveTextViewRoles.InteractiveTextViewRole); protected abstract string ItemPartiallyWritten(string expectedItemOrNull); protected abstract TestWorkspace CreateWorkspace(string fileContents); private protected abstract Task BaseVerifyWorkerAsync( string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List<CompletionFilter> matchingFilters, CompletionItemFlags? flags); internal static Task<RoslynCompletion.CompletionList> GetCompletionListAsync( CompletionService service, Document document, int position, RoslynCompletion.CompletionTrigger triggerInfo, OptionSet options = null) { return service.GetCompletionsAsync(document, position, triggerInfo, GetRoles(document), options); } private protected async Task CheckResultsAsync( Document document, int position, string expectedItemOrNull, string expectedDescriptionOrNull, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionModeItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List<CompletionFilter> matchingFilters, CompletionItemFlags? flags) { var code = (await document.GetTextAsync()).ToString(); var trigger = RoslynCompletion.CompletionTrigger.Invoke; if (usePreviousCharAsTrigger) { trigger = RoslynCompletion.CompletionTrigger.CreateInsertionTrigger(insertedCharacter: code.ElementAt(position - 1)); } var completionService = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(completionService, document, position, trigger); var items = completionList == null ? ImmutableArray<RoslynCompletion.CompletionItem>.Empty : completionList.Items; if (hasSuggestionModeItem != null) { Assert.Equal(hasSuggestionModeItem.Value, completionList.SuggestionModeItem != null); } if (checkForAbsence) { if (items == null) { return; } if (expectedItemOrNull == null) { Assert.Empty(items); } else { AssertEx.None( items, c => CompareItems(c.DisplayText, expectedItemOrNull) && CompareItems(c.DisplayTextSuffix, displayTextSuffix ?? "") && CompareItems(c.DisplayTextPrefix, displayTextPrefix ?? "") && CompareItems(c.InlineDescription, inlineDescription ?? "") && (expectedDescriptionOrNull != null ? completionService.GetDescriptionAsync(document, c).Result.Text == expectedDescriptionOrNull : true)); } } else { if (expectedItemOrNull == null) { Assert.NotEmpty(items); } else { AssertEx.Any(items, Predicate); } } bool Predicate(RoslynCompletion.CompletionItem c) { if (!CompareItems(c.DisplayText, expectedItemOrNull)) return false; if (!CompareItems(c.DisplayTextSuffix, displayTextSuffix ?? "")) return false; if (!CompareItems(c.DisplayTextPrefix, displayTextPrefix ?? "")) return false; if (!CompareItems(c.InlineDescription, inlineDescription ?? "")) return false; if (expectedDescriptionOrNull != null && completionService.GetDescriptionAsync(document, c).Result.Text != expectedDescriptionOrNull) return false; if (glyph.HasValue && !c.Tags.SequenceEqual(GlyphTags.GetTags((Glyph)glyph.Value))) return false; if (matchPriority.HasValue && c.Rules.MatchPriority != matchPriority.Value) return false; if (matchingFilters != null && !FiltersMatch(matchingFilters, c)) return false; if (flags != null && flags.Value != c.Flags) return false; if (isComplexTextEdit is bool textEdit && textEdit != c.IsComplexTextEdit) return false; return true; } } private static bool FiltersMatch(List<CompletionFilter> expectedMatchingFilters, RoslynCompletion.CompletionItem item) { var matchingFilters = FilterSet.GetFilters(item); // Check that the list has no duplicates. Assert.Equal(matchingFilters.Count, matchingFilters.Distinct().Count()); return expectedMatchingFilters.SetEquals(matchingFilters); } private async Task VerifyAsync( string markup, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind? sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionModeItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List<CompletionFilter> matchingFilters, CompletionItemFlags? flags) { foreach (var sourceKind in sourceCodeKind.HasValue ? new[] { sourceCodeKind.Value } : new[] { SourceCodeKind.Regular, SourceCodeKind.Script }) { using var workspaceFixture = GetOrCreateWorkspaceFixture(); var workspace = workspaceFixture.Target.GetWorkspace(markup, ExportProvider); var code = workspaceFixture.Target.Code; var position = workspaceFixture.Target.Position; var newOptions = WithChangedOptions(workspace.Options); if (TargetTypedCompletionFilterFeatureFlag.HasValue) { newOptions = newOptions.WithChangedOption(CompletionOptions.TargetTypedCompletionFilterFeatureFlag, TargetTypedCompletionFilterFeatureFlag.Value); } if (TypeImportCompletionFeatureFlag.HasValue) { newOptions = newOptions.WithChangedOption(CompletionOptions.TypeImportCompletionFeatureFlag, TypeImportCompletionFeatureFlag.Value); } workspace.SetOptions(newOptions); await VerifyWorkerAsync( code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority, hasSuggestionModeItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags).ConfigureAwait(false); } } protected async Task<CompletionList> GetCompletionListAsync(string markup, string workspaceKind = null) { using var workspaceFixture = GetOrCreateWorkspaceFixture(); var workspace = workspaceFixture.Target.GetWorkspace(markup, ExportProvider, workspaceKind: workspaceKind); var currentDocument = workspace.CurrentSolution.GetDocument(workspaceFixture.Target.CurrentDocument.Id); var position = workspaceFixture.Target.Position; currentDocument = WithChangedOptions(currentDocument); return await GetCompletionListAsync(GetCompletionService(currentDocument.Project), currentDocument, position, RoslynCompletion.CompletionTrigger.Invoke, options: workspace.Options).ConfigureAwait(false); } protected async Task VerifyCustomCommitProviderAsync(string markupBeforeCommit, string itemToCommit, string expectedCodeAfterCommit, SourceCodeKind? sourceCodeKind = null, char? commitChar = null) { using var workspaceFixture = GetOrCreateWorkspaceFixture(); using (workspaceFixture.Target.GetWorkspace(markupBeforeCommit, ExportProvider)) { var code = workspaceFixture.Target.Code; var position = workspaceFixture.Target.Position; if (sourceCodeKind.HasValue) { await VerifyCustomCommitProviderWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, sourceCodeKind.Value, commitChar); } else { await VerifyCustomCommitProviderWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, SourceCodeKind.Regular, commitChar); await VerifyCustomCommitProviderWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, SourceCodeKind.Script, commitChar); } } } protected async Task VerifyProviderCommitAsync( string markupBeforeCommit, string itemToCommit, string expectedCodeAfterCommit, char? commitChar, SourceCodeKind? sourceCodeKind = null) { using var workspaceFixture = GetOrCreateWorkspaceFixture(); workspaceFixture.Target.GetWorkspace(markupBeforeCommit, ExportProvider); var code = workspaceFixture.Target.Code; var position = workspaceFixture.Target.Position; expectedCodeAfterCommit = expectedCodeAfterCommit.NormalizeLineEndings(); if (sourceCodeKind.HasValue) { await VerifyProviderCommitWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, commitChar, sourceCodeKind.Value); } else { await VerifyProviderCommitWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, commitChar, SourceCodeKind.Regular); await VerifyProviderCommitWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, commitChar, SourceCodeKind.Script); } } protected bool CompareItems(string actualItem, string expectedItem) => GetStringComparer().Equals(actualItem, expectedItem); protected virtual IEqualityComparer<string> GetStringComparer() => StringComparer.Ordinal; private protected async Task VerifyItemExistsAsync( string markup, string expectedItem, string expectedDescriptionOrNull = null, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false, int? glyph = null, int? matchPriority = null, bool? hasSuggestionModeItem = null, string displayTextSuffix = null, string displayTextPrefix = null, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence: false, glyph: glyph, matchPriority: matchPriority, hasSuggestionModeItem: hasSuggestionModeItem, displayTextSuffix: displayTextSuffix, displayTextPrefix: displayTextPrefix, inlineDescription: inlineDescription, isComplexTextEdit: isComplexTextEdit, matchingFilters: matchingFilters, flags: flags); } private protected async Task VerifyItemIsAbsentAsync( string markup, string expectedItem, string expectedDescriptionOrNull = null, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false, bool? hasSuggestionModeItem = null, string displayTextSuffix = null, string displayTextPrefix = null, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence: true, glyph: null, matchPriority: null, hasSuggestionModeItem: hasSuggestionModeItem, displayTextSuffix: displayTextSuffix, displayTextPrefix: displayTextPrefix, inlineDescription: inlineDescription, isComplexTextEdit: isComplexTextEdit, matchingFilters: matchingFilters, flags: flags); } protected async Task VerifyAnyItemExistsAsync( string markup, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false, bool? hasSuggestionModeItem = null, string displayTextSuffix = null, string displayTextPrefix = null, string inlineDescription = null) { await VerifyAsync(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: false, glyph: null, matchPriority: null, hasSuggestionModeItem: hasSuggestionModeItem, displayTextSuffix: displayTextSuffix, displayTextPrefix: displayTextPrefix, inlineDescription: inlineDescription, isComplexTextEdit: null, matchingFilters: null, flags: null); } protected async Task VerifyNoItemsExistAsync( string markup, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false, bool? hasSuggestionModeItem = null, string displayTextSuffix = null, string inlineDescription = null) { await VerifyAsync( markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: true, glyph: null, matchPriority: null, hasSuggestionModeItem: hasSuggestionModeItem, displayTextSuffix: displayTextSuffix, displayTextPrefix: null, inlineDescription: inlineDescription, isComplexTextEdit: null, matchingFilters: null, flags: null); } internal abstract Type GetCompletionProviderType(); /// <summary> /// Override this to change parameters or return without verifying anything, e.g. for script sources. Or to test in other code contexts. /// </summary> /// <param name="code">The source code (not markup).</param> /// <param name="expectedItemOrNull">The expected item. If this is null, verifies that *any* item shows up for this CompletionProvider (or no items show up if checkForAbsence is true).</param> /// <param name="expectedDescriptionOrNull">If this is null, the Description for the item is ignored.</param> /// <param name="usePreviousCharAsTrigger">Whether or not the previous character in markup should be used to trigger IntelliSense for this provider. If false, invokes it through the invoke IntelliSense command.</param> /// <param name="checkForAbsence">If true, checks for absence of a specific item (or that no items are returned from this CompletionProvider)</param> private protected virtual async Task VerifyWorkerAsync( string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionModeItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List<CompletionFilter> matchingFilters, CompletionItemFlags? flags) { using var workspaceFixture = GetOrCreateWorkspaceFixture(); workspaceFixture.Target.GetWorkspace(ExportProvider); var document1 = workspaceFixture.Target.UpdateDocument(code, sourceCodeKind); await CheckResultsAsync( document1, position, expectedItemOrNull, expectedDescriptionOrNull, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority, hasSuggestionModeItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags); if (await CanUseSpeculativeSemanticModelAsync(document1, position)) { var document2 = workspaceFixture.Target.UpdateDocument(code, sourceCodeKind, cleanBeforeUpdate: false); await CheckResultsAsync( document2, position, expectedItemOrNull, expectedDescriptionOrNull, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority, hasSuggestionModeItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags); } } /// <summary> /// Override this to change parameters or return without verifying anything, e.g. for script sources. Or to test in other code contexts. /// </summary> /// <param name="codeBeforeCommit">The source code (not markup).</param> /// <param name="position">Position where intellisense is invoked.</param> /// <param name="itemToCommit">The item to commit from the completion provider.</param> /// <param name="expectedCodeAfterCommit">The expected code after commit.</param> protected virtual async Task VerifyCustomCommitProviderWorkerAsync(string codeBeforeCommit, int position, string itemToCommit, string expectedCodeAfterCommit, SourceCodeKind sourceCodeKind, char? commitChar = null) { using var workspaceFixture = GetOrCreateWorkspaceFixture(); var document1 = workspaceFixture.Target.UpdateDocument(codeBeforeCommit, sourceCodeKind); await VerifyCustomCommitProviderCheckResultsAsync(document1, codeBeforeCommit, position, itemToCommit, expectedCodeAfterCommit, commitChar); if (await CanUseSpeculativeSemanticModelAsync(document1, position)) { var document2 = workspaceFixture.Target.UpdateDocument(codeBeforeCommit, sourceCodeKind, cleanBeforeUpdate: false); await VerifyCustomCommitProviderCheckResultsAsync(document2, codeBeforeCommit, position, itemToCommit, expectedCodeAfterCommit, commitChar); } } private async Task VerifyCustomCommitProviderCheckResultsAsync(Document document, string codeBeforeCommit, int position, string itemToCommit, string expectedCodeAfterCommit, char? commitChar) { document = WithChangedOptions(document); var service = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(service, document, position, RoslynCompletion.CompletionTrigger.Invoke); var items = completionList.Items; Assert.Contains(itemToCommit, items.Select(x => x.DisplayText), GetStringComparer()); var firstItem = items.First(i => CompareItems(i.DisplayText, itemToCommit)); if (service.GetProvider(firstItem) is ICustomCommitCompletionProvider customCommitCompletionProvider) { VerifyCustomCommitWorker(service, customCommitCompletionProvider, firstItem, codeBeforeCommit, expectedCodeAfterCommit, commitChar); } else { await VerifyCustomCommitWorkerAsync(service, document, firstItem, codeBeforeCommit, expectedCodeAfterCommit, commitChar); } } protected virtual OptionSet WithChangedOptions(OptionSet options) => options; private Document WithChangedOptions(Document document) { var workspace = document.Project.Solution.Workspace; var newOptions = WithChangedOptions(workspace.Options); workspace.TryApplyChanges(document.Project.Solution.WithOptions(newOptions)); return workspace.CurrentSolution.GetDocument(document.Id); } private static Document WithChangedOption(Document document, OptionKey optionKey, object value) { var workspace = document.Project.Solution.Workspace; var newOptions = workspace.Options.WithChangedOption(optionKey, value); workspace.TryApplyChanges(document.Project.Solution.WithOptions(newOptions)); return workspace.CurrentSolution.GetDocument(document.Id); } private async Task VerifyCustomCommitWorkerAsync( CompletionServiceWithProviders service, Document document, RoslynCompletion.CompletionItem completionItem, string codeBeforeCommit, string expectedCodeAfterCommit, char? commitChar = null) { using var workspaceFixture = GetOrCreateWorkspaceFixture(); MarkupTestFile.GetPosition(expectedCodeAfterCommit, out var actualExpectedCode, out int expectedCaretPosition); if (commitChar.HasValue && !CommitManager.IsCommitCharacter(service.GetRules(), completionItem, commitChar.Value)) { Assert.Equal(codeBeforeCommit, actualExpectedCode); return; } // textview is created lazily, so need to access it before making // changes to document, so the cursor position is tracked correctly. var textView = workspaceFixture.Target.CurrentDocument.GetTextView(); var options = await document.GetOptionsAsync().ConfigureAwait(false); var commit = await service.GetChangeAsync(document, completionItem, commitChar, CancellationToken.None); var text = await document.GetTextAsync(); var newText = text.WithChanges(commit.TextChange); var newDoc = document.WithText(newText); document.Project.Solution.Workspace.TryApplyChanges(newDoc.Project.Solution); var textBuffer = workspaceFixture.Target.CurrentDocument.GetTextBuffer(); var actualCodeAfterCommit = textBuffer.CurrentSnapshot.AsText().ToString(); var caretPosition = commit.NewPosition ?? textView.Caret.Position.BufferPosition.Position; AssertEx.EqualOrDiff(actualExpectedCode, actualCodeAfterCommit); Assert.Equal(expectedCaretPosition, caretPosition); } private void VerifyCustomCommitWorker( CompletionService service, ICustomCommitCompletionProvider customCommitCompletionProvider, RoslynCompletion.CompletionItem completionItem, string codeBeforeCommit, string expectedCodeAfterCommit, char? commitChar = null) { using var workspaceFixture = GetOrCreateWorkspaceFixture(); MarkupTestFile.GetPosition(expectedCodeAfterCommit, out var actualExpectedCode, out int expectedCaretPosition); if (commitChar.HasValue && !CommitManager.IsCommitCharacter(service.GetRules(), completionItem, commitChar.Value)) { Assert.Equal(codeBeforeCommit, actualExpectedCode); return; } // textview is created lazily, so need to access it before making // changes to document, so the cursor position is tracked correctly. var textView = workspaceFixture.Target.CurrentDocument.GetTextView(); var textBuffer = workspaceFixture.Target.CurrentDocument.GetTextBuffer(); customCommitCompletionProvider.Commit(completionItem, textView, textBuffer, textView.TextSnapshot, commitChar); var actualCodeAfterCommit = textBuffer.CurrentSnapshot.AsText().ToString(); var caretPosition = textView.Caret.Position.BufferPosition.Position; Assert.Equal(actualExpectedCode, actualCodeAfterCommit); Assert.Equal(expectedCaretPosition, caretPosition); } /// <summary> /// Override this to change parameters or return without verifying anything, e.g. for script sources. Or to test in other code contexts. /// </summary> /// <param name="codeBeforeCommit">The source code (not markup).</param> /// <param name="position">Position where intellisense is invoked.</param> /// <param name="itemToCommit">The item to commit from the completion provider.</param> /// <param name="expectedCodeAfterCommit">The expected code after commit.</param> private async Task VerifyProviderCommitWorkerAsync(string codeBeforeCommit, int position, string itemToCommit, string expectedCodeAfterCommit, char? commitChar, SourceCodeKind sourceCodeKind) { using var workspaceFixture = GetOrCreateWorkspaceFixture(); var document1 = workspaceFixture.Target.UpdateDocument(codeBeforeCommit, sourceCodeKind); await VerifyProviderCommitCheckResultsAsync(document1, position, itemToCommit, expectedCodeAfterCommit, commitChar); if (await CanUseSpeculativeSemanticModelAsync(document1, position)) { var document2 = workspaceFixture.Target.UpdateDocument(codeBeforeCommit, sourceCodeKind, cleanBeforeUpdate: false); await VerifyProviderCommitCheckResultsAsync(document2, position, itemToCommit, expectedCodeAfterCommit, commitChar); } } private async Task VerifyProviderCommitCheckResultsAsync( Document document, int position, string itemToCommit, string expectedCodeAfterCommit, char? commitCharOpt) { document = WithChangedOptions(document); var service = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(service, document, position, RoslynCompletion.CompletionTrigger.Invoke); var items = completionList.Items; var firstItem = items.First(i => CompareItems(i.DisplayText + i.DisplayTextSuffix, itemToCommit)); var commitChar = commitCharOpt ?? '\t'; var text = await document.GetTextAsync(); if (commitChar == '\t' || CommitManager.IsCommitCharacter(service.GetRules(), firstItem, commitChar)) { var textChange = (await service.GetChangeAsync(document, firstItem, commitChar, CancellationToken.None)).TextChange; // Adjust TextChange to include commit character, so long as it isn't TAB. if (commitChar != '\t') { textChange = new TextChange(textChange.Span, textChange.NewText.TrimEnd(commitChar) + commitChar); } text = text.WithChanges(textChange); } else { // nothing was committed, but we should insert the commit character. var textChange = new TextChange(new TextSpan(firstItem.Span.End, 0), commitChar.ToString()); text = text.WithChanges(textChange); } Assert.Equal(expectedCodeAfterCommit, text.ToString()); } protected async Task VerifyItemInEditorBrowsableContextsAsync( string markup, string referencedCode, string item, int expectedSymbolsSameSolution, int expectedSymbolsMetadataReference, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers = false) { await VerifyItemWithMetadataReferenceAsync(markup, referencedCode, item, expectedSymbolsMetadataReference, sourceLanguage, referencedLanguage, hideAdvancedMembers); await VerifyItemWithProjectReferenceAsync(markup, referencedCode, item, expectedSymbolsSameSolution, sourceLanguage, referencedLanguage, hideAdvancedMembers); // If the source and referenced languages are different, then they cannot be in the same project if (sourceLanguage == referencedLanguage) { await VerifyItemInSameProjectAsync(markup, referencedCode, item, expectedSymbolsSameSolution, sourceLanguage, hideAdvancedMembers); } } protected async Task VerifyItemWithMetadataReferenceAsync(string markup, string metadataReferenceCode, string expectedItem, int expectedSymbols, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) { var xmlString = CreateMarkupForProjectWithMetadataReference(markup, metadataReferenceCode, sourceLanguage, referencedLanguage); await VerifyItemWithReferenceWorkerAsync(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } protected static string GetMarkupWithReference(string currentFile, string referencedFile, string sourceLanguage, string referenceLanguage, bool isProjectReference) { return isProjectReference ? CreateMarkupForProjectWithProjectReference(currentFile, referencedFile, sourceLanguage, referenceLanguage) : CreateMarkupForProjectWithMetadataReference(currentFile, referencedFile, sourceLanguage, referenceLanguage); } protected static string CreateMarkupForProjectWithMetadataReference(string markup, string metadataReferenceCode, string sourceLanguage, string referencedLanguage) { return string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true"" AssemblyName=""Project1""> <Document FilePath=""SourceDocument"">{1}</Document> <MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument"">{3}</Document> </MetadataReferenceFromSource> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(metadataReferenceCode)); } protected async Task VerifyItemWithAliasedMetadataReferencesAsync(string markup, string metadataAlias, string expectedItem, int expectedSymbols, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) { var xmlString = CreateMarkupForProjectWithAliasedMetadataReference(markup, metadataAlias, "", sourceLanguage, referencedLanguage); await VerifyItemWithReferenceWorkerAsync(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } protected static string CreateMarkupForProjectWithAliasedMetadataReference(string markup, string metadataAlias, string referencedCode, string sourceLanguage, string referencedLanguage, bool hasGlobalAlias = true) { var aliases = hasGlobalAlias ? $"{metadataAlias},{MetadataReferenceProperties.GlobalAlias}" : $"{metadataAlias}"; return string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true"" AssemblyName=""Project1""> <Document FilePath=""SourceDocument"">{1}</Document> <MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"" Aliases=""{3}"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument"">{4}</Document> </MetadataReferenceFromSource> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(aliases), SecurityElement.Escape(referencedCode)); } protected async Task VerifyItemWithProjectReferenceAsync(string markup, string referencedCode, string expectedItem, int expectedSymbols, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) { var xmlString = CreateMarkupForProjectWithProjectReference(markup, referencedCode, sourceLanguage, referencedLanguage); await VerifyItemWithReferenceWorkerAsync(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } protected static string CreateMarkupForProjectWithAliasedProjectReference(string markup, string projectAlias, string referencedCode, string sourceLanguage, string referencedLanguage) { return string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true"" AssemblyName=""Project1""> <ProjectReference Alias=""{4}"">ReferencedProject</ProjectReference> <Document FilePath=""SourceDocument"">{1}</Document> </Project> <Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument"">{3}</Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(referencedCode), SecurityElement.Escape(projectAlias)); } protected static string CreateMarkupForProjectWithProjectReference(string markup, string referencedCode, string sourceLanguage, string referencedLanguage) { return string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true"" AssemblyName=""Project1""> <ProjectReference>ReferencedProject</ProjectReference> <Document FilePath=""SourceDocument"">{1}</Document> </Project> <Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument"">{3}</Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(referencedCode)); } protected static string CreateMarkupForProjectWithMultupleProjectReferences(string sourceText, string sourceLanguage, string referencedLanguage, string[] referencedTexts) { return $@" <Workspace> <Project Language=""{sourceLanguage}"" CommonReferences=""true"" AssemblyName=""Project1""> {GetProjectReferenceElements(referencedTexts)} <Document FilePath=""SourceDocument"">{SecurityElement.Escape(sourceText)}</Document> </Project> {GetReferencedProjectElements(referencedLanguage, referencedTexts)} </Workspace>"; static string GetProjectReferenceElements(string[] referencedTexts) { var builder = new StringBuilder(); for (var i = 0; i < referencedTexts.Length; ++i) { builder.AppendLine($"<ProjectReference>ReferencedProject{i}</ProjectReference>"); } return builder.ToString(); } static string GetReferencedProjectElements(string language, string[] referencedTexts) { var builder = new StringBuilder(); for (var i = 0; i < referencedTexts.Length; ++i) { builder.Append($@" <Project Language=""{language}"" CommonReferences=""true"" AssemblyName=""ReferencedProject{i}"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument{i}"">{SecurityElement.Escape(referencedTexts[i])}</Document> </Project>"); } return builder.ToString(); } } protected static string CreateMarkupForProjecWithVBProjectReference(string markup, string referencedCode, string sourceLanguage, string rootNamespace = "") { return string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true"" AssemblyName=""Project1""> <ProjectReference>ReferencedProject</ProjectReference> <Document FilePath=""SourceDocument"">{1}</Document> </Project> <Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument"">{3}</Document> <CompilationOptions RootNamespace=""{4}""/> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), LanguageNames.VisualBasic, SecurityElement.Escape(referencedCode), rootNamespace); } private Task VerifyItemInSameProjectAsync(string markup, string referencedCode, string expectedItem, int expectedSymbols, string sourceLanguage, bool hideAdvancedMembers) { var xmlString = CreateMarkupForSingleProject(markup, referencedCode, sourceLanguage); return VerifyItemWithReferenceWorkerAsync(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } protected static string CreateMarkupForSingleProject(string markup, string referencedCode, string sourceLanguage) { return string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument"">{1}</Document> <Document FilePath=""ReferencedDocument"">{2}</Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), SecurityElement.Escape(referencedCode)); } private async Task VerifyItemWithReferenceWorkerAsync( string xmlString, string expectedItem, int expectedSymbols, bool hideAdvancedMembers) { using (var testWorkspace = TestWorkspace.Create(xmlString, exportProvider: ExportProvider)) { var position = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value; var solution = testWorkspace.CurrentSolution; var documentId = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").Id; var document = solution.GetDocument(documentId); var optionKey = new OptionKey(CompletionOptions.HideAdvancedMembers, document.Project.Language); document = WithChangedOption(document, optionKey, hideAdvancedMembers); var triggerInfo = RoslynCompletion.CompletionTrigger.Invoke; var completionService = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(completionService, document, position, triggerInfo); if (expectedSymbols >= 1) { Assert.NotNull(completionList); AssertEx.Any(completionList.Items, c => CompareItems(c.DisplayText, expectedItem)); var item = completionList.Items.First(c => CompareItems(c.DisplayText, expectedItem)); var description = await completionService.GetDescriptionAsync(document, item); if (expectedSymbols == 1) { Assert.DoesNotContain("+", description.Text, StringComparison.Ordinal); } else { Assert.Contains(GetExpectedOverloadSubstring(expectedSymbols), description.Text, StringComparison.Ordinal); } } else { if (completionList != null) { AssertEx.None(completionList.Items, c => CompareItems(c.DisplayText, expectedItem)); } } } } protected async Task VerifyItemWithMscorlib45Async(string markup, string expectedItem, string expectedDescription, string sourceLanguage) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferencesNet45=""true""> <Document FilePath=""SourceDocument""> {1} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup)); await VerifyItemWithMscorlib45WorkerAsync(xmlString, expectedItem, expectedDescription); } private async Task VerifyItemWithMscorlib45WorkerAsync( string xmlString, string expectedItem, string expectedDescription) { using (var testWorkspace = TestWorkspace.Create(xmlString, exportProvider: ExportProvider)) { var position = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value; var solution = testWorkspace.CurrentSolution; var documentId = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").Id; var document = solution.GetDocument(documentId); var triggerInfo = RoslynCompletion.CompletionTrigger.Invoke; var completionService = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(completionService, document, position, triggerInfo); var item = completionList.Items.FirstOrDefault(i => i.DisplayText == expectedItem); Assert.Equal(expectedDescription, (await completionService.GetDescriptionAsync(document, item)).Text); } } private const char NonBreakingSpace = (char)0x00A0; private static string GetExpectedOverloadSubstring(int expectedSymbols) { if (expectedSymbols <= 1) { throw new ArgumentOutOfRangeException(nameof(expectedSymbols)); } return "+" + NonBreakingSpace + (expectedSymbols - 1) + NonBreakingSpace + FeaturesResources.overload; } protected async Task VerifyItemInLinkedFilesAsync(string xmlString, string expectedItem, string expectedDescription) { using (var testWorkspace = TestWorkspace.Create(xmlString, exportProvider: ExportProvider)) { var position = testWorkspace.Documents.First().CursorPosition.Value; var solution = testWorkspace.CurrentSolution; var textContainer = testWorkspace.Documents.First().GetTextBuffer().AsTextContainer(); var currentContextDocumentId = testWorkspace.GetDocumentIdInCurrentContext(textContainer); var document = solution.GetDocument(currentContextDocumentId); var triggerInfo = RoslynCompletion.CompletionTrigger.Invoke; var completionService = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(completionService, document, position, triggerInfo); var item = completionList.Items.Single(c => c.DisplayText == expectedItem); Assert.NotNull(item); if (expectedDescription != null) { var actualDescription = (await completionService.GetDescriptionAsync(document, item)).Text; Assert.Equal(expectedDescription, actualDescription); } } } private protected async Task VerifyAtPositionAsync( string code, int position, string insertText, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { code = code.Substring(0, position) + insertText + code.Substring(position); position += insertText.Length; await BaseVerifyWorkerAsync(code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags); } private protected async Task VerifyAtPositionAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { await VerifyAtPositionAsync( code, position, string.Empty, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags); } private protected async Task VerifyAtEndOfFileAsync( string code, int position, string insertText, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { // only do this if the placeholder was at the end of the text. if (code.Length != position) { return; } code = code.Substring(startIndex: 0, length: position) + insertText; position += insertText.Length; await BaseVerifyWorkerAsync( code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags); } private protected async Task VerifyAtPosition_ItemPartiallyWrittenAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { await VerifyAtPositionAsync( code, position, ItemPartiallyWritten(expectedItemOrNull), usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags); } private protected async Task VerifyAtEndOfFileAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { await VerifyAtEndOfFileAsync(code, position, string.Empty, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags); } private protected async Task VerifyAtEndOfFile_ItemPartiallyWrittenAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { await VerifyAtEndOfFileAsync( code, position, ItemPartiallyWritten(expectedItemOrNull), usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags); } protected void VerifyTextualTriggerCharacter( string markup, bool shouldTriggerWithTriggerOnLettersEnabled, bool shouldTriggerWithTriggerOnLettersDisabled, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular, bool showCompletionInArgumentLists = true) { VerifyTextualTriggerCharacterWorker(markup, expectedTriggerCharacter: shouldTriggerWithTriggerOnLettersEnabled, triggerOnLetter: true, sourceCodeKind, showCompletionInArgumentLists); VerifyTextualTriggerCharacterWorker(markup, expectedTriggerCharacter: shouldTriggerWithTriggerOnLettersDisabled, triggerOnLetter: false, sourceCodeKind, showCompletionInArgumentLists: false); } private void VerifyTextualTriggerCharacterWorker( string markup, bool expectedTriggerCharacter, bool triggerOnLetter, SourceCodeKind sourceCodeKind, bool showCompletionInArgumentLists) { using (var workspace = CreateWorkspace(markup)) { var hostDocument = workspace.DocumentWithCursor; workspace.OnDocumentSourceCodeKindChanged(hostDocument.Id, sourceCodeKind); Assert.Same(hostDocument, workspace.Documents.Single()); var position = hostDocument.CursorPosition.Value; var text = hostDocument.GetTextBuffer().CurrentSnapshot.AsText(); var options = workspace.Options .WithChangedOption(CompletionOptions.TriggerOnTypingLetters2, hostDocument.Project.Language, triggerOnLetter) .WithChangedOption(CompletionOptions.TriggerInArgumentLists, hostDocument.Project.Language, showCompletionInArgumentLists); var trigger = RoslynCompletion.CompletionTrigger.CreateInsertionTrigger(text[position]); var document = workspace.CurrentSolution.GetDocument(hostDocument.Id); var service = GetCompletionService(document.Project); var isTextualTriggerCharacterResult = service.ShouldTriggerCompletion(text, position + 1, trigger, GetRoles(document), options); if (expectedTriggerCharacter) { var assertText = "'" + text.ToString(new TextSpan(position, 1)) + "' expected to be textual trigger character"; Assert.True(isTextualTriggerCharacterResult, assertText); } else { var assertText = "'" + text.ToString(new TextSpan(position, 1)) + "' expected to NOT be textual trigger character"; Assert.False(isTextualTriggerCharacterResult, assertText); } } } protected async Task VerifyCommonCommitCharactersAsync(string initialMarkup, string textTypedSoFar) { var commitCharacters = new[] { ' ', '{', '}', '[', ']', '(', ')', '.', ',', ':', ';', '+', '-', '*', '/', '%', '&', '|', '^', '!', '~', '=', '<', '>', '?', '@', '#', '\'', '\"', '\\' }; await VerifyCommitCharactersAsync(initialMarkup, textTypedSoFar, commitCharacters); } protected async Task VerifyCommitCharactersAsync(string initialMarkup, string textTypedSoFar, char[] validChars, char[] invalidChars = null, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular) { Assert.NotNull(validChars); invalidChars = invalidChars ?? new[] { 'x' }; using (var workspace = CreateWorkspace(initialMarkup)) { var hostDocument = workspace.DocumentWithCursor; workspace.OnDocumentSourceCodeKindChanged(hostDocument.Id, sourceCodeKind); var documentId = workspace.GetDocumentId(hostDocument); var document = workspace.CurrentSolution.GetDocument(documentId); var position = hostDocument.CursorPosition.Value; var service = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(service, document, position, RoslynCompletion.CompletionTrigger.Invoke); var item = completionList.Items.First(i => i.DisplayText.StartsWith(textTypedSoFar)); foreach (var ch in validChars) { Assert.True(CommitManager.IsCommitCharacter( service.GetRules(), item, ch), $"Expected '{ch}' to be a commit character"); } foreach (var ch in invalidChars) { Assert.False(CommitManager.IsCommitCharacter( service.GetRules(), item, ch), $"Expected '{ch}' NOT to be a commit character"); } } } protected async Task<ImmutableArray<RoslynCompletion.CompletionItem>> GetCompletionItemsAsync( string markup, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger = false) { using var workspaceFixture = GetOrCreateWorkspaceFixture(); workspaceFixture.Target.GetWorkspace(markup, ExportProvider); var code = workspaceFixture.Target.Code; var position = workspaceFixture.Target.Position; var document = workspaceFixture.Target.UpdateDocument(code, sourceCodeKind); var trigger = usePreviousCharAsTrigger ? RoslynCompletion.CompletionTrigger.CreateInsertionTrigger(insertedCharacter: code.ElementAt(position - 1)) : RoslynCompletion.CompletionTrigger.Invoke; var completionService = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(completionService, document, position, trigger); return completionList == null ? ImmutableArray<RoslynCompletion.CompletionItem>.Empty : completionList.Items; } } }
1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Workspaces/CSharp/Portable/Recommendations/CSharpRecommendationServiceRunner.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Recommendations; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Recommendations { internal partial class CSharpRecommendationServiceRunner : AbstractRecommendationServiceRunner<CSharpSyntaxContext> { public CSharpRecommendationServiceRunner( CSharpSyntaxContext context, bool filterOutOfScopeLocals, CancellationToken cancellationToken) : base(context, filterOutOfScopeLocals, cancellationToken) { } public override RecommendedSymbols GetRecommendedSymbols() { if (_context.IsInNonUserCode || _context.IsPreProcessorDirectiveContext) { return default; } if (!_context.IsRightOfNameSeparator) return new RecommendedSymbols(GetSymbolsForCurrentContext()); return GetSymbolsOffOfContainer(); } public override bool TryGetExplicitTypeOfLambdaParameter(SyntaxNode lambdaSyntax, int ordinalInLambda, [NotNullWhen(true)] out ITypeSymbol? explicitLambdaParameterType) { if (lambdaSyntax.IsKind<ParenthesizedLambdaExpressionSyntax>(SyntaxKind.ParenthesizedLambdaExpression, out var parenthesizedLambdaSyntax)) { var parameters = parenthesizedLambdaSyntax.ParameterList.Parameters; if (parameters.Count > ordinalInLambda) { var parameter = parameters[ordinalInLambda]; if (parameter.Type != null) { explicitLambdaParameterType = _context.SemanticModel.GetTypeInfo(parameter.Type, _cancellationToken).Type; return explicitLambdaParameterType != null; } } } // Non-parenthesized lambdas cannot explicitly specify the type of the single parameter explicitLambdaParameterType = null; return false; } private ImmutableArray<ISymbol> GetSymbolsForCurrentContext() { if (_context.IsGlobalStatementContext) { // Script and interactive return GetSymbolsForGlobalStatementContext(); } else if (_context.IsAnyExpressionContext || _context.IsStatementContext || _context.SyntaxTree.IsDefiniteCastTypeContext(_context.Position, _context.LeftToken)) { // GitHub #717: With automatic brace completion active, typing '(i' produces "(i)", which gets parsed as // as cast. The user might be trying to type a parenthesized expression, so even though a cast // is a type-only context, we'll show all symbols anyway. return GetSymbolsForExpressionOrStatementContext(); } else if (_context.IsTypeContext || _context.IsNamespaceContext) { return GetSymbolsForTypeOrNamespaceContext(); } else if (_context.IsLabelContext) { return GetSymbolsForLabelContext(); } else if (_context.IsTypeArgumentOfConstraintContext) { return GetSymbolsForTypeArgumentOfConstraintClause(); } else if (_context.IsDestructorTypeContext) { var symbol = _context.SemanticModel.GetDeclaredSymbol(_context.ContainingTypeOrEnumDeclaration!, _cancellationToken); return symbol == null ? ImmutableArray<ISymbol>.Empty : ImmutableArray.Create<ISymbol>(symbol); } else if (_context.IsNamespaceDeclarationNameContext) { return GetSymbolsForNamespaceDeclarationNameContext<BaseNamespaceDeclarationSyntax>(); } return ImmutableArray<ISymbol>.Empty; } private RecommendedSymbols GetSymbolsOffOfContainer() { // Ensure that we have the correct token in A.B| case var node = _context.TargetToken.GetRequiredParent(); return node switch { MemberAccessExpressionSyntax(SyntaxKind.SimpleMemberAccessExpression) memberAccess => GetSymbolsOffOfExpression(memberAccess.Expression), MemberAccessExpressionSyntax(SyntaxKind.PointerMemberAccessExpression) memberAccess => GetSymbolsOffOfDereferencedExpression(memberAccess.Expression), // This code should be executing only if the cursor is between two dots in a dotdot token. RangeExpressionSyntax rangeExpression => GetSymbolsOffOfExpression(rangeExpression.LeftOperand), QualifiedNameSyntax qualifiedName => GetSymbolsOffOfName(qualifiedName.Left), AliasQualifiedNameSyntax aliasName => GetSymbolsOffOffAlias(aliasName.Alias), MemberBindingExpressionSyntax _ => GetSymbolsOffOfConditionalReceiver(node.GetParentConditionalAccessExpression()!.Expression), _ => default, }; } private ImmutableArray<ISymbol> GetSymbolsForGlobalStatementContext() { var syntaxTree = _context.SyntaxTree; var position = _context.Position; var token = _context.LeftToken; // The following code is a hack to get around a binding problem when asking binding // questions immediately after a using directive. This is special-cased in the binder // factory to ensure that using directives are not within scope inside other using // directives. That generally works fine for .cs, but it's a problem for interactive // code in this case: // // using System; // | if (token.Kind() == SyntaxKind.SemicolonToken && token.Parent.IsKind(SyntaxKind.UsingDirective) && position >= token.Span.End) { var compUnit = (CompilationUnitSyntax)syntaxTree.GetRoot(_cancellationToken); if (compUnit.Usings.Count > 0 && compUnit.Usings.Last().GetLastToken() == token) { token = token.GetNextToken(includeZeroWidth: true); } } var symbols = _context.SemanticModel.LookupSymbols(token.SpanStart); return symbols; } private ImmutableArray<ISymbol> GetSymbolsForTypeArgumentOfConstraintClause() { var enclosingSymbol = _context.LeftToken.GetRequiredParent() .AncestorsAndSelf() .Select(n => _context.SemanticModel.GetDeclaredSymbol(n, _cancellationToken)) .WhereNotNull() .FirstOrDefault(); var symbols = enclosingSymbol != null ? enclosingSymbol.GetTypeArguments() : ImmutableArray<ITypeSymbol>.Empty; return ImmutableArray<ISymbol>.CastUp(symbols); } private RecommendedSymbols GetSymbolsOffOffAlias(IdentifierNameSyntax alias) { var aliasSymbol = _context.SemanticModel.GetAliasInfo(alias, _cancellationToken); if (aliasSymbol == null) return default; return new RecommendedSymbols(_context.SemanticModel.LookupNamespacesAndTypes( alias.SpanStart, aliasSymbol.Target)); } private ImmutableArray<ISymbol> GetSymbolsForLabelContext() { var allLabels = _context.SemanticModel.LookupLabels(_context.LeftToken.SpanStart); // Exclude labels (other than 'default') that come from case switch statements return allLabels .WhereAsArray(label => label.DeclaringSyntaxReferences.First().GetSyntax(_cancellationToken) .IsKind(SyntaxKind.LabeledStatement, SyntaxKind.DefaultSwitchLabel)); } private ImmutableArray<ISymbol> GetSymbolsForTypeOrNamespaceContext() { var symbols = _context.SemanticModel.LookupNamespacesAndTypes(_context.LeftToken.SpanStart); if (_context.TargetToken.IsUsingKeywordInUsingDirective()) { return symbols.WhereAsArray(s => s.IsNamespace()); } if (_context.TargetToken.IsStaticKeywordInUsingDirective()) { return symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType()); } return symbols; } private ImmutableArray<ISymbol> GetSymbolsForExpressionOrStatementContext() { // Check if we're in an interesting situation like this: // // i // <-- here // I = 0; // The problem is that "i I = 0" causes a local to be in scope called "I". So, later when // we look up symbols, it masks any other 'I's in scope (i.e. if there's a field with that // name). If this is the case, we do not want to filter out inaccessible locals. var filterOutOfScopeLocals = _filterOutOfScopeLocals; if (filterOutOfScopeLocals) filterOutOfScopeLocals = !_context.LeftToken.GetRequiredParent().IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type); var symbols = !_context.IsNameOfContext && _context.LeftToken.GetRequiredParent().IsInStaticContext() ? _context.SemanticModel.LookupStaticMembers(_context.LeftToken.SpanStart) : _context.SemanticModel.LookupSymbols(_context.LeftToken.SpanStart); // Filter out any extension methods that might be imported by a using static directive. // But include extension methods declared in the context's type or it's parents var contextOuterTypes = _context.GetOuterTypes(_cancellationToken); var contextEnclosingNamedType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken); symbols = symbols.WhereAsArray(symbol => !symbol.IsExtensionMethod() || Equals(contextEnclosingNamedType, symbol.ContainingType) || contextOuterTypes.Any(outerType => outerType.Equals(symbol.ContainingType))); // The symbols may include local variables that are declared later in the method and // should not be included in the completion list, so remove those. Filter them away, // unless we're in the debugger, where we show all locals in scope. if (filterOutOfScopeLocals) { symbols = symbols.WhereAsArray(symbol => !symbol.IsInaccessibleLocal(_context.Position)); } return symbols; } private RecommendedSymbols GetSymbolsOffOfName(NameSyntax name) { // Using an is pattern on an enum is a qualified name, but normal symbol processing works fine if (_context.IsEnumTypeMemberAccessContext) return GetSymbolsOffOfExpression(name); if (ShouldBeTreatedAsTypeInsteadOfExpression(name, out var nameBinding, out var container)) return GetSymbolsOffOfBoundExpression(name, name, nameBinding, container, unwrapNullable: false); // We're in a name-only context, since if we were an expression we'd be a // MemberAccessExpressionSyntax. Thus, let's do other namespaces and types. nameBinding = _context.SemanticModel.GetSymbolInfo(name, _cancellationToken); if (nameBinding.Symbol is not INamespaceOrTypeSymbol symbol) return default; if (_context.IsNameOfContext) return new RecommendedSymbols(_context.SemanticModel.LookupSymbols(position: name.SpanStart, container: symbol)); var symbols = _context.SemanticModel.LookupNamespacesAndTypes( position: name.SpanStart, container: symbol); if (_context.IsNamespaceDeclarationNameContext) { var declarationSyntax = name.GetAncestorOrThis<BaseNamespaceDeclarationSyntax>(); return new RecommendedSymbols(symbols.WhereAsArray(s => IsNonIntersectingNamespace(s, declarationSyntax))); } // Filter the types when in a using directive, but not an alias. // // Cases: // using | -- Show namespaces // using A.| -- Show namespaces // using static | -- Show namespace and types // using A = B.| -- Show namespace and types var usingDirective = name.GetAncestorOrThis<UsingDirectiveSyntax>(); if (usingDirective != null && usingDirective.Alias == null) { return new RecommendedSymbols(usingDirective.StaticKeyword.IsKind(SyntaxKind.StaticKeyword) ? symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType()) : symbols.WhereAsArray(s => s.IsNamespace())); } return new RecommendedSymbols(symbols); } /// <summary> /// DeterminesCheck if we're in an interesting situation like this: /// <code> /// int i = 5; /// i. // -- here /// List ml = new List(); /// </code> /// The problem is that "i.List" gets parsed as a type. In this case we need to try binding again as if "i" is /// an expression and not a type. In order to do that, we need to speculate as to what 'i' meant if it wasn't /// part of a local declaration's type. /// <para/> /// Another interesting case is something like: /// <code> /// stringList. /// await Test2(); /// </code> /// Here "stringList.await" is thought of as the return type of a local function. /// </summary> private bool ShouldBeTreatedAsTypeInsteadOfExpression( ExpressionSyntax name, out SymbolInfo leftHandBinding, out ITypeSymbol? container) { if (name.IsFoundUnder<LocalFunctionStatementSyntax>(d => d.ReturnType) || name.IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type) || name.IsFoundUnder<FieldDeclarationSyntax>(d => d.Declaration.Type)) { leftHandBinding = _context.SemanticModel.GetSpeculativeSymbolInfo( name.SpanStart, name, SpeculativeBindingOption.BindAsExpression); container = _context.SemanticModel.GetSpeculativeTypeInfo( name.SpanStart, name, SpeculativeBindingOption.BindAsExpression).Type; return true; } leftHandBinding = default; container = null; return false; } private RecommendedSymbols GetSymbolsOffOfExpression(ExpressionSyntax? originalExpression) { if (originalExpression == null) return default; // In case of 'await x$$', we want to move to 'x' to get it's members. // To run GetSymbolInfo, we also need to get rid of parenthesis. var expression = originalExpression is AwaitExpressionSyntax awaitExpression ? awaitExpression.Expression.WalkDownParentheses() : originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; var result = GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false); // Check for the Color Color case. if (originalExpression.CanAccessInstanceAndStaticMembersOffOf(_context.SemanticModel, _cancellationToken)) { var speculativeSymbolInfo = _context.SemanticModel.GetSpeculativeSymbolInfo(expression.SpanStart, expression, SpeculativeBindingOption.BindAsTypeOrNamespace); var typeMembers = GetSymbolsOffOfBoundExpression(originalExpression, expression, speculativeSymbolInfo, container, unwrapNullable: false); result = new RecommendedSymbols( result.NamedSymbols.Concat(typeMembers.NamedSymbols), result.UnnamedSymbols); } return result; } private RecommendedSymbols GetSymbolsOffOfDereferencedExpression(ExpressionSyntax originalExpression) { var expression = originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; if (container is IPointerTypeSymbol pointerType) { container = pointerType.PointedAtType; } return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false); } private RecommendedSymbols GetSymbolsOffOfConditionalReceiver(ExpressionSyntax originalExpression) { // Given ((T?)t)?.|, the '.' will behave as if the expression was actually ((T)t).|. More plainly, // a member access off of a conditional receiver of nullable type binds to the unwrapped nullable // type. This is not exposed via the binding information for the LHS, so repeat this work here. var expression = originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; // If the thing on the left is a type, namespace, or alias, we shouldn't show anything in // IntelliSense. if (leftHandBinding.GetBestOrAllSymbols().FirstOrDefault().MatchesKind(SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Alias)) return default; return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: true); } private RecommendedSymbols GetSymbolsOffOfBoundExpression( ExpressionSyntax originalExpression, ExpressionSyntax expression, SymbolInfo leftHandBinding, ITypeSymbol? containerType, bool unwrapNullable) { var abstractsOnly = false; var excludeInstance = false; var excludeStatic = true; ISymbol? containerSymbol = containerType; var symbol = leftHandBinding.GetAnySymbol(); if (symbol != null) { // If the thing on the left is a lambda expression, we shouldn't show anything. if (symbol is IMethodSymbol { MethodKind: MethodKind.AnonymousFunction }) return default; var originalExpressionKind = originalExpression.Kind(); // If the thing on the left is a type, namespace or alias and the original // expression was parenthesized, we shouldn't show anything in IntelliSense. if (originalExpressionKind is SyntaxKind.ParenthesizedExpression && symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.Alias) { return default; } // If the thing on the left is a method name identifier, we shouldn't show anything. if (symbol.Kind is SymbolKind.Method && originalExpressionKind is SyntaxKind.IdentifierName or SyntaxKind.GenericName) { return default; } // If the thing on the left is an event that can't be used as a field, we shouldn't show anything if (symbol is IEventSymbol ev && !_context.SemanticModel.IsEventUsableAsField(originalExpression.SpanStart, ev)) { return default; } if (symbol is IAliasSymbol alias) symbol = alias.Target; if (symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.TypeParameter) { // For named typed, namespaces, and type parameters (potentially constrainted to interface with statics), we flip things around. // We only want statics and not instance members. excludeInstance = true; excludeStatic = false; abstractsOnly = symbol.Kind == SymbolKind.TypeParameter; containerSymbol = symbol; } // Special case parameters. If we have a normal (non this/base) parameter, then that's what we want to // lookup symbols off of as we have a lot of special logic for determining member symbols of lambda // parameters. // // If it is a this/base parameter and we're in a static context, we shouldn't show anything if (symbol is IParameterSymbol parameter) { if (parameter.IsThis && expression.IsInStaticContext()) return default; containerSymbol = symbol; } } else if (containerType != null) { // Otherwise, if it wasn't a symbol on the left, but it was something that had a type, // then include instance members for it. excludeStatic = true; } if (containerSymbol == null) return default; Debug.Assert(!excludeInstance || !excludeStatic); Debug.Assert(!abstractsOnly || (abstractsOnly && !excludeStatic && excludeInstance)); // nameof(X.| // Show static and instance members. if (_context.IsNameOfContext) { excludeInstance = false; excludeStatic = false; } var useBaseReferenceAccessibility = symbol is IParameterSymbol { IsThis: true } p && !p.Type.Equals(containerType); var symbols = GetMemberSymbols(containerSymbol, position: originalExpression.SpanStart, excludeInstance, useBaseReferenceAccessibility, unwrapNullable); // If we're showing instance members, don't include nested types var namedSymbols = excludeStatic ? symbols.WhereAsArray(s => !(s.IsStatic || s is ITypeSymbol)) : (abstractsOnly ? symbols.WhereAsArray(s => s.IsAbstract) : symbols); // if we're dotting off an instance, then add potential operators/indexers/conversions that may be // applicable to it as well. var unnamedSymbols = _context.IsNameOfContext || excludeInstance ? default : GetUnnamedSymbols(originalExpression); return new RecommendedSymbols(namedSymbols, unnamedSymbols); } private ImmutableArray<ISymbol> GetUnnamedSymbols(ExpressionSyntax originalExpression) { var semanticModel = _context.SemanticModel; var container = GetContainerForUnnamedSymbols(semanticModel, originalExpression); if (container == null) return ImmutableArray<ISymbol>.Empty; // In a case like `x?.Y` if we bind the type of `.Y` we will get a value type back (like `int`), and not // `int?`. However, we want to think of the constructed type as that's the type of the overall expression // that will be casted. if (originalExpression.GetRootConditionalAccessExpression() != null) container = TryMakeNullable(semanticModel.Compilation, container); using var _ = ArrayBuilder<ISymbol>.GetInstance(out var symbols); AddIndexers(container, symbols); AddOperators(container, symbols); AddConversions(container, symbols); return symbols.ToImmutable(); } private ITypeSymbol? GetContainerForUnnamedSymbols(SemanticModel semanticModel, ExpressionSyntax originalExpression) { return ShouldBeTreatedAsTypeInsteadOfExpression(originalExpression, out _, out var container) ? container : semanticModel.GetTypeInfo(originalExpression, _cancellationToken).Type; } private void AddIndexers(ITypeSymbol container, ArrayBuilder<ISymbol> symbols) { var containingType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken); if (containingType == null) return; foreach (var member in container.RemoveNullableIfPresent().GetAccessibleMembersInThisAndBaseTypes<IPropertySymbol>(containingType)) { if (member.IsIndexer) symbols.Add(member); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Recommendations; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Recommendations { internal partial class CSharpRecommendationServiceRunner : AbstractRecommendationServiceRunner<CSharpSyntaxContext> { public CSharpRecommendationServiceRunner( CSharpSyntaxContext context, bool filterOutOfScopeLocals, CancellationToken cancellationToken) : base(context, filterOutOfScopeLocals, cancellationToken) { } public override RecommendedSymbols GetRecommendedSymbols() { if (_context.IsInNonUserCode || _context.IsPreProcessorDirectiveContext) { return default; } if (!_context.IsRightOfNameSeparator) return new RecommendedSymbols(GetSymbolsForCurrentContext()); return GetSymbolsOffOfContainer(); } public override bool TryGetExplicitTypeOfLambdaParameter(SyntaxNode lambdaSyntax, int ordinalInLambda, [NotNullWhen(true)] out ITypeSymbol? explicitLambdaParameterType) { if (lambdaSyntax.IsKind<ParenthesizedLambdaExpressionSyntax>(SyntaxKind.ParenthesizedLambdaExpression, out var parenthesizedLambdaSyntax)) { var parameters = parenthesizedLambdaSyntax.ParameterList.Parameters; if (parameters.Count > ordinalInLambda) { var parameter = parameters[ordinalInLambda]; if (parameter.Type != null) { explicitLambdaParameterType = _context.SemanticModel.GetTypeInfo(parameter.Type, _cancellationToken).Type; return explicitLambdaParameterType != null; } } } // Non-parenthesized lambdas cannot explicitly specify the type of the single parameter explicitLambdaParameterType = null; return false; } private ImmutableArray<ISymbol> GetSymbolsForCurrentContext() { if (_context.IsGlobalStatementContext) { // Script, interactive, or top-level statement return GetSymbolsForGlobalStatementContext(); } else if (_context.IsAnyExpressionContext || _context.IsStatementContext || _context.SyntaxTree.IsDefiniteCastTypeContext(_context.Position, _context.LeftToken)) { // GitHub #717: With automatic brace completion active, typing '(i' produces "(i)", which gets parsed as // as cast. The user might be trying to type a parenthesized expression, so even though a cast // is a type-only context, we'll show all symbols anyway. return GetSymbolsForExpressionOrStatementContext(); } else if (_context.IsTypeContext || _context.IsNamespaceContext) { return GetSymbolsForTypeOrNamespaceContext(); } else if (_context.IsLabelContext) { return GetSymbolsForLabelContext(); } else if (_context.IsTypeArgumentOfConstraintContext) { return GetSymbolsForTypeArgumentOfConstraintClause(); } else if (_context.IsDestructorTypeContext) { var symbol = _context.SemanticModel.GetDeclaredSymbol(_context.ContainingTypeOrEnumDeclaration!, _cancellationToken); return symbol == null ? ImmutableArray<ISymbol>.Empty : ImmutableArray.Create<ISymbol>(symbol); } else if (_context.IsNamespaceDeclarationNameContext) { return GetSymbolsForNamespaceDeclarationNameContext<BaseNamespaceDeclarationSyntax>(); } return ImmutableArray<ISymbol>.Empty; } private RecommendedSymbols GetSymbolsOffOfContainer() { // Ensure that we have the correct token in A.B| case var node = _context.TargetToken.GetRequiredParent(); return node switch { MemberAccessExpressionSyntax(SyntaxKind.SimpleMemberAccessExpression) memberAccess => GetSymbolsOffOfExpression(memberAccess.Expression), MemberAccessExpressionSyntax(SyntaxKind.PointerMemberAccessExpression) memberAccess => GetSymbolsOffOfDereferencedExpression(memberAccess.Expression), // This code should be executing only if the cursor is between two dots in a dotdot token. RangeExpressionSyntax rangeExpression => GetSymbolsOffOfExpression(rangeExpression.LeftOperand), QualifiedNameSyntax qualifiedName => GetSymbolsOffOfName(qualifiedName.Left), AliasQualifiedNameSyntax aliasName => GetSymbolsOffOffAlias(aliasName.Alias), MemberBindingExpressionSyntax _ => GetSymbolsOffOfConditionalReceiver(node.GetParentConditionalAccessExpression()!.Expression), _ => default, }; } private ImmutableArray<ISymbol> GetSymbolsForGlobalStatementContext() { var syntaxTree = _context.SyntaxTree; var position = _context.Position; var token = _context.LeftToken; // The following code is a hack to get around a binding problem when asking binding // questions immediately after a using directive. This is special-cased in the binder // factory to ensure that using directives are not within scope inside other using // directives. That generally works fine for .cs, but it's a problem for interactive // code in this case: // // using System; // | if (token.Kind() == SyntaxKind.SemicolonToken && token.Parent.IsKind(SyntaxKind.UsingDirective) && position >= token.Span.End) { var compUnit = (CompilationUnitSyntax)syntaxTree.GetRoot(_cancellationToken); if (compUnit.Usings.Count > 0 && compUnit.Usings.Last().SemicolonToken == token) { token = token.GetNextToken(includeZeroWidth: true); } } var symbols = _context.SemanticModel.LookupSymbols(token.SpanStart); return symbols; } private ImmutableArray<ISymbol> GetSymbolsForTypeArgumentOfConstraintClause() { var enclosingSymbol = _context.LeftToken.GetRequiredParent() .AncestorsAndSelf() .Select(n => _context.SemanticModel.GetDeclaredSymbol(n, _cancellationToken)) .WhereNotNull() .FirstOrDefault(); var symbols = enclosingSymbol != null ? enclosingSymbol.GetTypeArguments() : ImmutableArray<ITypeSymbol>.Empty; return ImmutableArray<ISymbol>.CastUp(symbols); } private RecommendedSymbols GetSymbolsOffOffAlias(IdentifierNameSyntax alias) { var aliasSymbol = _context.SemanticModel.GetAliasInfo(alias, _cancellationToken); if (aliasSymbol == null) return default; return new RecommendedSymbols(_context.SemanticModel.LookupNamespacesAndTypes( alias.SpanStart, aliasSymbol.Target)); } private ImmutableArray<ISymbol> GetSymbolsForLabelContext() { var allLabels = _context.SemanticModel.LookupLabels(_context.LeftToken.SpanStart); // Exclude labels (other than 'default') that come from case switch statements return allLabels .WhereAsArray(label => label.DeclaringSyntaxReferences.First().GetSyntax(_cancellationToken) .IsKind(SyntaxKind.LabeledStatement, SyntaxKind.DefaultSwitchLabel)); } private ImmutableArray<ISymbol> GetSymbolsForTypeOrNamespaceContext() { var symbols = _context.SemanticModel.LookupNamespacesAndTypes(_context.LeftToken.SpanStart); if (_context.TargetToken.IsUsingKeywordInUsingDirective()) { return symbols.WhereAsArray(s => s.IsNamespace()); } if (_context.TargetToken.IsStaticKeywordInUsingDirective()) { return symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType()); } return symbols; } private ImmutableArray<ISymbol> GetSymbolsForExpressionOrStatementContext() { // Check if we're in an interesting situation like this: // // i // <-- here // I = 0; // The problem is that "i I = 0" causes a local to be in scope called "I". So, later when // we look up symbols, it masks any other 'I's in scope (i.e. if there's a field with that // name). If this is the case, we do not want to filter out inaccessible locals. var filterOutOfScopeLocals = _filterOutOfScopeLocals; if (filterOutOfScopeLocals) filterOutOfScopeLocals = !_context.LeftToken.GetRequiredParent().IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type); var symbols = !_context.IsNameOfContext && _context.LeftToken.GetRequiredParent().IsInStaticContext() ? _context.SemanticModel.LookupStaticMembers(_context.LeftToken.SpanStart) : _context.SemanticModel.LookupSymbols(_context.LeftToken.SpanStart); // Filter out any extension methods that might be imported by a using static directive. // But include extension methods declared in the context's type or it's parents var contextOuterTypes = _context.GetOuterTypes(_cancellationToken); var contextEnclosingNamedType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken); symbols = symbols.WhereAsArray(symbol => !symbol.IsExtensionMethod() || Equals(contextEnclosingNamedType, symbol.ContainingType) || contextOuterTypes.Any(outerType => outerType.Equals(symbol.ContainingType))); // The symbols may include local variables that are declared later in the method and // should not be included in the completion list, so remove those. Filter them away, // unless we're in the debugger, where we show all locals in scope. if (filterOutOfScopeLocals) { symbols = symbols.WhereAsArray(symbol => !symbol.IsInaccessibleLocal(_context.Position)); } return symbols; } private RecommendedSymbols GetSymbolsOffOfName(NameSyntax name) { // Using an is pattern on an enum is a qualified name, but normal symbol processing works fine if (_context.IsEnumTypeMemberAccessContext) return GetSymbolsOffOfExpression(name); if (ShouldBeTreatedAsTypeInsteadOfExpression(name, out var nameBinding, out var container)) return GetSymbolsOffOfBoundExpression(name, name, nameBinding, container, unwrapNullable: false); // We're in a name-only context, since if we were an expression we'd be a // MemberAccessExpressionSyntax. Thus, let's do other namespaces and types. nameBinding = _context.SemanticModel.GetSymbolInfo(name, _cancellationToken); if (nameBinding.Symbol is not INamespaceOrTypeSymbol symbol) return default; if (_context.IsNameOfContext) return new RecommendedSymbols(_context.SemanticModel.LookupSymbols(position: name.SpanStart, container: symbol)); var symbols = _context.SemanticModel.LookupNamespacesAndTypes( position: name.SpanStart, container: symbol); if (_context.IsNamespaceDeclarationNameContext) { var declarationSyntax = name.GetAncestorOrThis<BaseNamespaceDeclarationSyntax>(); return new RecommendedSymbols(symbols.WhereAsArray(s => IsNonIntersectingNamespace(s, declarationSyntax))); } // Filter the types when in a using directive, but not an alias. // // Cases: // using | -- Show namespaces // using A.| -- Show namespaces // using static | -- Show namespace and types // using A = B.| -- Show namespace and types var usingDirective = name.GetAncestorOrThis<UsingDirectiveSyntax>(); if (usingDirective != null && usingDirective.Alias == null) { return new RecommendedSymbols(usingDirective.StaticKeyword.IsKind(SyntaxKind.StaticKeyword) ? symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType()) : symbols.WhereAsArray(s => s.IsNamespace())); } return new RecommendedSymbols(symbols); } /// <summary> /// DeterminesCheck if we're in an interesting situation like this: /// <code> /// int i = 5; /// i. // -- here /// List ml = new List(); /// </code> /// The problem is that "i.List" gets parsed as a type. In this case we need to try binding again as if "i" is /// an expression and not a type. In order to do that, we need to speculate as to what 'i' meant if it wasn't /// part of a local declaration's type. /// <para/> /// Another interesting case is something like: /// <code> /// stringList. /// await Test2(); /// </code> /// Here "stringList.await" is thought of as the return type of a local function. /// </summary> private bool ShouldBeTreatedAsTypeInsteadOfExpression( ExpressionSyntax name, out SymbolInfo leftHandBinding, out ITypeSymbol? container) { if (name.IsFoundUnder<LocalFunctionStatementSyntax>(d => d.ReturnType) || name.IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type) || name.IsFoundUnder<FieldDeclarationSyntax>(d => d.Declaration.Type)) { leftHandBinding = _context.SemanticModel.GetSpeculativeSymbolInfo( name.SpanStart, name, SpeculativeBindingOption.BindAsExpression); container = _context.SemanticModel.GetSpeculativeTypeInfo( name.SpanStart, name, SpeculativeBindingOption.BindAsExpression).Type; return true; } leftHandBinding = default; container = null; return false; } private RecommendedSymbols GetSymbolsOffOfExpression(ExpressionSyntax? originalExpression) { if (originalExpression == null) return default; // In case of 'await x$$', we want to move to 'x' to get it's members. // To run GetSymbolInfo, we also need to get rid of parenthesis. var expression = originalExpression is AwaitExpressionSyntax awaitExpression ? awaitExpression.Expression.WalkDownParentheses() : originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; var result = GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false); // Check for the Color Color case. if (originalExpression.CanAccessInstanceAndStaticMembersOffOf(_context.SemanticModel, _cancellationToken)) { var speculativeSymbolInfo = _context.SemanticModel.GetSpeculativeSymbolInfo(expression.SpanStart, expression, SpeculativeBindingOption.BindAsTypeOrNamespace); var typeMembers = GetSymbolsOffOfBoundExpression(originalExpression, expression, speculativeSymbolInfo, container, unwrapNullable: false); result = new RecommendedSymbols( result.NamedSymbols.Concat(typeMembers.NamedSymbols), result.UnnamedSymbols); } return result; } private RecommendedSymbols GetSymbolsOffOfDereferencedExpression(ExpressionSyntax originalExpression) { var expression = originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; if (container is IPointerTypeSymbol pointerType) { container = pointerType.PointedAtType; } return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false); } private RecommendedSymbols GetSymbolsOffOfConditionalReceiver(ExpressionSyntax originalExpression) { // Given ((T?)t)?.|, the '.' will behave as if the expression was actually ((T)t).|. More plainly, // a member access off of a conditional receiver of nullable type binds to the unwrapped nullable // type. This is not exposed via the binding information for the LHS, so repeat this work here. var expression = originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; // If the thing on the left is a type, namespace, or alias, we shouldn't show anything in // IntelliSense. if (leftHandBinding.GetBestOrAllSymbols().FirstOrDefault().MatchesKind(SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Alias)) return default; return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: true); } private RecommendedSymbols GetSymbolsOffOfBoundExpression( ExpressionSyntax originalExpression, ExpressionSyntax expression, SymbolInfo leftHandBinding, ITypeSymbol? containerType, bool unwrapNullable) { var abstractsOnly = false; var excludeInstance = false; var excludeStatic = true; ISymbol? containerSymbol = containerType; var symbol = leftHandBinding.GetAnySymbol(); if (symbol != null) { // If the thing on the left is a lambda expression, we shouldn't show anything. if (symbol is IMethodSymbol { MethodKind: MethodKind.AnonymousFunction }) return default; var originalExpressionKind = originalExpression.Kind(); // If the thing on the left is a type, namespace or alias and the original // expression was parenthesized, we shouldn't show anything in IntelliSense. if (originalExpressionKind is SyntaxKind.ParenthesizedExpression && symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.Alias) { return default; } // If the thing on the left is a method name identifier, we shouldn't show anything. if (symbol.Kind is SymbolKind.Method && originalExpressionKind is SyntaxKind.IdentifierName or SyntaxKind.GenericName) { return default; } // If the thing on the left is an event that can't be used as a field, we shouldn't show anything if (symbol is IEventSymbol ev && !_context.SemanticModel.IsEventUsableAsField(originalExpression.SpanStart, ev)) { return default; } if (symbol is IAliasSymbol alias) symbol = alias.Target; if (symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.TypeParameter) { // For named typed, namespaces, and type parameters (potentially constrainted to interface with statics), we flip things around. // We only want statics and not instance members. excludeInstance = true; excludeStatic = false; abstractsOnly = symbol.Kind == SymbolKind.TypeParameter; containerSymbol = symbol; } // Special case parameters. If we have a normal (non this/base) parameter, then that's what we want to // lookup symbols off of as we have a lot of special logic for determining member symbols of lambda // parameters. // // If it is a this/base parameter and we're in a static context, we shouldn't show anything if (symbol is IParameterSymbol parameter) { if (parameter.IsThis && expression.IsInStaticContext()) return default; containerSymbol = symbol; } } else if (containerType != null) { // Otherwise, if it wasn't a symbol on the left, but it was something that had a type, // then include instance members for it. excludeStatic = true; } if (containerSymbol == null) return default; Debug.Assert(!excludeInstance || !excludeStatic); Debug.Assert(!abstractsOnly || (abstractsOnly && !excludeStatic && excludeInstance)); // nameof(X.| // Show static and instance members. if (_context.IsNameOfContext) { excludeInstance = false; excludeStatic = false; } var useBaseReferenceAccessibility = symbol is IParameterSymbol { IsThis: true } p && !p.Type.Equals(containerType); var symbols = GetMemberSymbols(containerSymbol, position: originalExpression.SpanStart, excludeInstance, useBaseReferenceAccessibility, unwrapNullable); // If we're showing instance members, don't include nested types var namedSymbols = excludeStatic ? symbols.WhereAsArray(s => !(s.IsStatic || s is ITypeSymbol)) : (abstractsOnly ? symbols.WhereAsArray(s => s.IsAbstract) : symbols); // if we're dotting off an instance, then add potential operators/indexers/conversions that may be // applicable to it as well. var unnamedSymbols = _context.IsNameOfContext || excludeInstance ? default : GetUnnamedSymbols(originalExpression); return new RecommendedSymbols(namedSymbols, unnamedSymbols); } private ImmutableArray<ISymbol> GetUnnamedSymbols(ExpressionSyntax originalExpression) { var semanticModel = _context.SemanticModel; var container = GetContainerForUnnamedSymbols(semanticModel, originalExpression); if (container == null) return ImmutableArray<ISymbol>.Empty; // In a case like `x?.Y` if we bind the type of `.Y` we will get a value type back (like `int`), and not // `int?`. However, we want to think of the constructed type as that's the type of the overall expression // that will be casted. if (originalExpression.GetRootConditionalAccessExpression() != null) container = TryMakeNullable(semanticModel.Compilation, container); using var _ = ArrayBuilder<ISymbol>.GetInstance(out var symbols); AddIndexers(container, symbols); AddOperators(container, symbols); AddConversions(container, symbols); return symbols.ToImmutable(); } private ITypeSymbol? GetContainerForUnnamedSymbols(SemanticModel semanticModel, ExpressionSyntax originalExpression) { return ShouldBeTreatedAsTypeInsteadOfExpression(originalExpression, out _, out var container) ? container : semanticModel.GetTypeInfo(originalExpression, _cancellationToken).Type; } private void AddIndexers(ITypeSymbol container, ArrayBuilder<ISymbol> symbols) { var containingType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken); if (containingType == null) return; foreach (var member in container.RemoveNullableIfPresent().GetAccessibleMembersInThisAndBaseTypes<IPropertySymbol>(containingType)) { if (member.IsIndexer) symbols.Add(member); } } } }
1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/EditorFeatures/Core.Wpf/Preview/AbstractPreviewTaggerProvider.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 Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview { internal class AbstractPreviewTaggerProvider<TTag> : ITaggerProvider where TTag : ITag { private readonly object _key; private readonly TTag _tagInstance; protected AbstractPreviewTaggerProvider(object key, TTag tagInstance) { _key = key; _tagInstance = tagInstance; } public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag => new Tagger(buffer, _key, _tagInstance) as ITagger<T>; private class Tagger : ITagger<TTag> { private readonly ITextBuffer _buffer; private readonly object _key; private readonly TTag _tagInstance; public Tagger(ITextBuffer buffer, object key, TTag tagInstance) { _buffer = buffer; _key = key; _tagInstance = tagInstance; } public IEnumerable<ITagSpan<TTag>> GetTags(NormalizedSnapshotSpanCollection spans) { if (_buffer.Properties.TryGetProperty(_key, out NormalizedSnapshotSpanCollection matchingSpans)) { var intersection = NormalizedSnapshotSpanCollection.Intersection(matchingSpans, spans); return intersection.Select(s => new TagSpan<TTag>(s, _tagInstance)); } return SpecializedCollections.EmptyEnumerable<ITagSpan<TTag>>(); } public event EventHandler<SnapshotSpanEventArgs> TagsChanged = (s, e) => { }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview { internal class AbstractPreviewTaggerProvider<TTag> : ITaggerProvider where TTag : ITag { private readonly object _key; private readonly TTag _tagInstance; protected AbstractPreviewTaggerProvider(object key, TTag tagInstance) { _key = key; _tagInstance = tagInstance; } public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag => new Tagger(buffer, _key, _tagInstance) as ITagger<T>; private class Tagger : ITagger<TTag> { private readonly ITextBuffer _buffer; private readonly object _key; private readonly TTag _tagInstance; public Tagger(ITextBuffer buffer, object key, TTag tagInstance) { _buffer = buffer; _key = key; _tagInstance = tagInstance; } public IEnumerable<ITagSpan<TTag>> GetTags(NormalizedSnapshotSpanCollection spans) { if (_buffer.Properties.TryGetProperty(_key, out NormalizedSnapshotSpanCollection matchingSpans)) { var intersection = NormalizedSnapshotSpanCollection.Intersection(matchingSpans, spans); return intersection.Select(s => new TagSpan<TTag>(s, _tagInstance)); } return SpecializedCollections.EmptyEnumerable<ITagSpan<TTag>>(); } public event EventHandler<SnapshotSpanEventArgs> TagsChanged = (s, e) => { }; } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptLanguageDebugInfoService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript { [Shared] [ExportLanguageService(typeof(ILanguageDebugInfoService), InternalLanguageNames.TypeScript)] internal sealed class VSTypeScriptLanguageDebugInfoService : ILanguageDebugInfoService { private readonly IVSTypeScriptLanguageDebugInfoServiceImplementation _implementation; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VSTypeScriptLanguageDebugInfoService(IVSTypeScriptLanguageDebugInfoServiceImplementation implementation) => _implementation = implementation; public async Task<DebugDataTipInfo> GetDataTipInfoAsync(Document document, int position, CancellationToken cancellationToken) => (await _implementation.GetDataTipInfoAsync(document, position, cancellationToken).ConfigureAwait(false)).UnderlyingObject; public async Task<DebugLocationInfo> GetLocationInfoAsync(Document document, int position, CancellationToken cancellationToken) => (await _implementation.GetLocationInfoAsync(document, position, cancellationToken).ConfigureAwait(false)).UnderlyingObject; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript { [Shared] [ExportLanguageService(typeof(ILanguageDebugInfoService), InternalLanguageNames.TypeScript)] internal sealed class VSTypeScriptLanguageDebugInfoService : ILanguageDebugInfoService { private readonly IVSTypeScriptLanguageDebugInfoServiceImplementation _implementation; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VSTypeScriptLanguageDebugInfoService(IVSTypeScriptLanguageDebugInfoServiceImplementation implementation) => _implementation = implementation; public async Task<DebugDataTipInfo> GetDataTipInfoAsync(Document document, int position, CancellationToken cancellationToken) => (await _implementation.GetDataTipInfoAsync(document, position, cancellationToken).ConfigureAwait(false)).UnderlyingObject; public async Task<DebugLocationInfo> GetLocationInfoAsync(Document document, int position, CancellationToken cancellationToken) => (await _implementation.GetLocationInfoAsync(document, position, cancellationToken).ConfigureAwait(false)).UnderlyingObject; } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Workspaces/Core/Portable/Workspace/Workspace_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; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public abstract partial class Workspace { private readonly EventMap _eventMap = new(); private const string WorkspaceChangeEventName = "WorkspaceChanged"; private const string WorkspaceFailedEventName = "WorkspaceFailed"; private const string DocumentOpenedEventName = "DocumentOpened"; private const string DocumentClosedEventName = "DocumentClosed"; private const string DocumentActiveContextChangedName = "DocumentActiveContextChanged"; /// <summary> /// An event raised whenever the current solution is changed. /// </summary> public event EventHandler<WorkspaceChangeEventArgs> WorkspaceChanged { add { _eventMap.AddEventHandler(WorkspaceChangeEventName, value); } remove { _eventMap.RemoveEventHandler(WorkspaceChangeEventName, value); } } protected Task RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind kind, Solution oldSolution, Solution newSolution, ProjectId projectId = null, DocumentId documentId = null) { if (newSolution == null) { throw new ArgumentNullException(nameof(newSolution)); } if (oldSolution == newSolution) { return Task.CompletedTask; } if (projectId == null && documentId != null) { projectId = documentId.ProjectId; } var ev = GetEventHandlers<WorkspaceChangeEventArgs>(WorkspaceChangeEventName); if (ev.HasHandlers) { return this.ScheduleTask(() => { using (Logger.LogBlock(FunctionId.Workspace_Events, (s, p, d, k) => $"{s.Id} - {p} - {d} {kind.ToString()}", newSolution, projectId, documentId, kind, CancellationToken.None)) { var args = new WorkspaceChangeEventArgs(kind, oldSolution, newSolution, projectId, documentId); ev.RaiseEvent(handler => handler(this, args)); } }, WorkspaceChangeEventName); } else { return Task.CompletedTask; } } /// <summary> /// An event raised whenever the workspace or part of its solution model /// fails to access a file or other external resource. /// </summary> public event EventHandler<WorkspaceDiagnosticEventArgs> WorkspaceFailed { add { _eventMap.AddEventHandler(WorkspaceFailedEventName, value); } remove { _eventMap.RemoveEventHandler(WorkspaceFailedEventName, value); } } protected internal virtual void OnWorkspaceFailed(WorkspaceDiagnostic diagnostic) { var ev = GetEventHandlers<WorkspaceDiagnosticEventArgs>(WorkspaceFailedEventName); if (ev.HasHandlers) { var args = new WorkspaceDiagnosticEventArgs(diagnostic); ev.RaiseEvent(handler => handler(this, args)); } } /// <summary> /// An event that is fired when a documents is opened in the editor. /// </summary> public event EventHandler<DocumentEventArgs> DocumentOpened { add { _eventMap.AddEventHandler(DocumentOpenedEventName, value); } remove { _eventMap.RemoveEventHandler(DocumentOpenedEventName, value); } } protected Task RaiseDocumentOpenedEventAsync(Document document) { var ev = GetEventHandlers<DocumentEventArgs>(DocumentOpenedEventName); if (ev.HasHandlers && document != null) { return this.ScheduleTask(() => { var args = new DocumentEventArgs(document); ev.RaiseEvent(handler => handler(this, args)); }, DocumentOpenedEventName); } else { return Task.CompletedTask; } } /// <summary> /// An event that is fired when a document is closed in the editor. /// </summary> public event EventHandler<DocumentEventArgs> DocumentClosed { add { _eventMap.AddEventHandler(DocumentClosedEventName, value); } remove { _eventMap.RemoveEventHandler(DocumentClosedEventName, value); } } protected Task RaiseDocumentClosedEventAsync(Document document) { var ev = GetEventHandlers<DocumentEventArgs>(DocumentClosedEventName); if (ev.HasHandlers && document != null) { return this.ScheduleTask(() => { var args = new DocumentEventArgs(document); ev.RaiseEvent(handler => handler(this, args)); }, DocumentClosedEventName); } else { return Task.CompletedTask; } } /// <summary> /// An event that is fired when the active context document associated with a buffer /// changes. /// </summary> public event EventHandler<DocumentActiveContextChangedEventArgs> DocumentActiveContextChanged { add { _eventMap.AddEventHandler(DocumentActiveContextChangedName, value); } remove { _eventMap.RemoveEventHandler(DocumentActiveContextChangedName, value); } } [Obsolete("This member is obsolete. Use the RaiseDocumentActiveContextChangedEventAsync(SourceTextContainer, DocumentId, DocumentId) overload instead.", error: true)] protected Task RaiseDocumentActiveContextChangedEventAsync(Document document) => throw new NotImplementedException(); protected Task RaiseDocumentActiveContextChangedEventAsync(SourceTextContainer sourceTextContainer, DocumentId oldActiveContextDocumentId, DocumentId newActiveContextDocumentId) { var ev = GetEventHandlers<DocumentActiveContextChangedEventArgs>(DocumentActiveContextChangedName); if (ev.HasHandlers && sourceTextContainer != null && oldActiveContextDocumentId != null && newActiveContextDocumentId != null) { // Capture the current solution snapshot (inside the _serializationLock of OnDocumentContextUpdated) var currentSolution = this.CurrentSolution; return this.ScheduleTask(() => { var args = new DocumentActiveContextChangedEventArgs(currentSolution, sourceTextContainer, oldActiveContextDocumentId, newActiveContextDocumentId); ev.RaiseEvent(handler => handler(this, args)); }, "Workspace.WorkspaceChanged"); } else { return Task.CompletedTask; } } private EventMap.EventHandlerSet<EventHandler<T>> GetEventHandlers<T>(string eventName) where T : EventArgs { // this will register features that want to listen to workspace events // lazily first time workspace event is actually fired this.Services.GetService<IWorkspaceEventListenerService>()?.EnsureListeners(); return _eventMap.GetEventHandlers<EventHandler<T>>(eventName); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public abstract partial class Workspace { private readonly EventMap _eventMap = new(); private const string WorkspaceChangeEventName = "WorkspaceChanged"; private const string WorkspaceFailedEventName = "WorkspaceFailed"; private const string DocumentOpenedEventName = "DocumentOpened"; private const string DocumentClosedEventName = "DocumentClosed"; private const string DocumentActiveContextChangedName = "DocumentActiveContextChanged"; /// <summary> /// An event raised whenever the current solution is changed. /// </summary> public event EventHandler<WorkspaceChangeEventArgs> WorkspaceChanged { add { _eventMap.AddEventHandler(WorkspaceChangeEventName, value); } remove { _eventMap.RemoveEventHandler(WorkspaceChangeEventName, value); } } protected Task RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind kind, Solution oldSolution, Solution newSolution, ProjectId projectId = null, DocumentId documentId = null) { if (newSolution == null) { throw new ArgumentNullException(nameof(newSolution)); } if (oldSolution == newSolution) { return Task.CompletedTask; } if (projectId == null && documentId != null) { projectId = documentId.ProjectId; } var ev = GetEventHandlers<WorkspaceChangeEventArgs>(WorkspaceChangeEventName); if (ev.HasHandlers) { return this.ScheduleTask(() => { using (Logger.LogBlock(FunctionId.Workspace_Events, (s, p, d, k) => $"{s.Id} - {p} - {d} {kind.ToString()}", newSolution, projectId, documentId, kind, CancellationToken.None)) { var args = new WorkspaceChangeEventArgs(kind, oldSolution, newSolution, projectId, documentId); ev.RaiseEvent(handler => handler(this, args)); } }, WorkspaceChangeEventName); } else { return Task.CompletedTask; } } /// <summary> /// An event raised whenever the workspace or part of its solution model /// fails to access a file or other external resource. /// </summary> public event EventHandler<WorkspaceDiagnosticEventArgs> WorkspaceFailed { add { _eventMap.AddEventHandler(WorkspaceFailedEventName, value); } remove { _eventMap.RemoveEventHandler(WorkspaceFailedEventName, value); } } protected internal virtual void OnWorkspaceFailed(WorkspaceDiagnostic diagnostic) { var ev = GetEventHandlers<WorkspaceDiagnosticEventArgs>(WorkspaceFailedEventName); if (ev.HasHandlers) { var args = new WorkspaceDiagnosticEventArgs(diagnostic); ev.RaiseEvent(handler => handler(this, args)); } } /// <summary> /// An event that is fired when a documents is opened in the editor. /// </summary> public event EventHandler<DocumentEventArgs> DocumentOpened { add { _eventMap.AddEventHandler(DocumentOpenedEventName, value); } remove { _eventMap.RemoveEventHandler(DocumentOpenedEventName, value); } } protected Task RaiseDocumentOpenedEventAsync(Document document) { var ev = GetEventHandlers<DocumentEventArgs>(DocumentOpenedEventName); if (ev.HasHandlers && document != null) { return this.ScheduleTask(() => { var args = new DocumentEventArgs(document); ev.RaiseEvent(handler => handler(this, args)); }, DocumentOpenedEventName); } else { return Task.CompletedTask; } } /// <summary> /// An event that is fired when a document is closed in the editor. /// </summary> public event EventHandler<DocumentEventArgs> DocumentClosed { add { _eventMap.AddEventHandler(DocumentClosedEventName, value); } remove { _eventMap.RemoveEventHandler(DocumentClosedEventName, value); } } protected Task RaiseDocumentClosedEventAsync(Document document) { var ev = GetEventHandlers<DocumentEventArgs>(DocumentClosedEventName); if (ev.HasHandlers && document != null) { return this.ScheduleTask(() => { var args = new DocumentEventArgs(document); ev.RaiseEvent(handler => handler(this, args)); }, DocumentClosedEventName); } else { return Task.CompletedTask; } } /// <summary> /// An event that is fired when the active context document associated with a buffer /// changes. /// </summary> public event EventHandler<DocumentActiveContextChangedEventArgs> DocumentActiveContextChanged { add { _eventMap.AddEventHandler(DocumentActiveContextChangedName, value); } remove { _eventMap.RemoveEventHandler(DocumentActiveContextChangedName, value); } } [Obsolete("This member is obsolete. Use the RaiseDocumentActiveContextChangedEventAsync(SourceTextContainer, DocumentId, DocumentId) overload instead.", error: true)] protected Task RaiseDocumentActiveContextChangedEventAsync(Document document) => throw new NotImplementedException(); protected Task RaiseDocumentActiveContextChangedEventAsync(SourceTextContainer sourceTextContainer, DocumentId oldActiveContextDocumentId, DocumentId newActiveContextDocumentId) { var ev = GetEventHandlers<DocumentActiveContextChangedEventArgs>(DocumentActiveContextChangedName); if (ev.HasHandlers && sourceTextContainer != null && oldActiveContextDocumentId != null && newActiveContextDocumentId != null) { // Capture the current solution snapshot (inside the _serializationLock of OnDocumentContextUpdated) var currentSolution = this.CurrentSolution; return this.ScheduleTask(() => { var args = new DocumentActiveContextChangedEventArgs(currentSolution, sourceTextContainer, oldActiveContextDocumentId, newActiveContextDocumentId); ev.RaiseEvent(handler => handler(this, args)); }, "Workspace.WorkspaceChanged"); } else { return Task.CompletedTask; } } private EventMap.EventHandlerSet<EventHandler<T>> GetEventHandlers<T>(string eventName) where T : EventArgs { // this will register features that want to listen to workspace events // lazily first time workspace event is actually fired this.Services.GetService<IWorkspaceEventListenerService>()?.EnsureListeners(); return _eventMap.GetEventHandlers<EventHandler<T>>(eventName); } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Compilers/CSharp/Test/Syntax/Syntax/SyntaxTreeTests.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.Text; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using static Roslyn.Test.Utilities.TestHelpers; using KeyValuePair = Roslyn.Utilities.KeyValuePairUtil; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SyntaxTreeTests : ParsingTests { public SyntaxTreeTests(ITestOutputHelper output) : base(output) { } protected SyntaxTree UsingTree(string text, CSharpParseOptions options, params DiagnosticDescription[] expectedErrors) { var tree = base.UsingTree(text, options); var actualErrors = tree.GetDiagnostics(); actualErrors.Verify(expectedErrors); return tree; } // Diagnostic options on syntax trees are now obsolete #pragma warning disable CS0618 [Fact] public void CreateTreeWithDiagnostics() { var options = CreateImmutableDictionary(("CS0078", ReportDiagnostic.Suppress)); var tree = CSharpSyntaxTree.Create(SyntaxFactory.ParseCompilationUnit(""), options: null, path: "", encoding: null, diagnosticOptions: options); Assert.Same(options, tree.DiagnosticOptions); } [Fact] public void ParseTreeWithChangesPreservesDiagnosticOptions() { var options = CreateImmutableDictionary(("CS0078", ReportDiagnostic.Suppress)); var tree = CSharpSyntaxTree.ParseText( SourceText.From(""), options: null, path: "", diagnosticOptions: options, isGeneratedCode: null, cancellationToken: default); Assert.Same(options, tree.DiagnosticOptions); var newTree = tree.WithChangedText(SourceText.From("class C { }")); Assert.Same(options, newTree.DiagnosticOptions); } [Fact] public void ParseTreeNullDiagnosticOptions() { var tree = CSharpSyntaxTree.ParseText( SourceText.From(""), options: null, path: "", diagnosticOptions: null, isGeneratedCode: null, cancellationToken: default); Assert.NotNull(tree.DiagnosticOptions); Assert.True(tree.DiagnosticOptions.IsEmpty); // The default options are case insensitive but the default empty ImmutableDictionary is not Assert.NotSame(ImmutableDictionary<string, ReportDiagnostic>.Empty, tree.DiagnosticOptions); } [Fact] public void ParseTreeEmptyDiagnosticOptions() { var tree = CSharpSyntaxTree.ParseText( SourceText.From(""), options: null, path: "", diagnosticOptions: ImmutableDictionary<string, ReportDiagnostic>.Empty, isGeneratedCode: null, cancellationToken: default); Assert.NotNull(tree.DiagnosticOptions); Assert.True(tree.DiagnosticOptions.IsEmpty); Assert.Same(ImmutableDictionary<string, ReportDiagnostic>.Empty, tree.DiagnosticOptions); } [Fact] public void ParseTreeCustomDiagnosticOptions() { var options = CreateImmutableDictionary(("CS0078", ReportDiagnostic.Suppress)); var tree = CSharpSyntaxTree.ParseText( SourceText.From(""), options: null, path: "", diagnosticOptions: options, isGeneratedCode: null, cancellationToken: default); Assert.Same(options, tree.DiagnosticOptions); } [Fact] public void DefaultTreeDiagnosticOptions() { var tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()); Assert.NotNull(tree.DiagnosticOptions); Assert.True(tree.DiagnosticOptions.IsEmpty); } [Fact] public void WithDiagnosticOptionsNull() { var tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()); var newTree = tree.WithDiagnosticOptions(null); Assert.NotNull(newTree.DiagnosticOptions); Assert.True(newTree.DiagnosticOptions.IsEmpty); Assert.Same(tree, newTree); } [Fact] public void WithDiagnosticOptionsEmpty() { var tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()); var newTree = tree.WithDiagnosticOptions(ImmutableDictionary<string, ReportDiagnostic>.Empty); Assert.NotNull(tree.DiagnosticOptions); Assert.True(newTree.DiagnosticOptions.IsEmpty); // Default empty immutable dictionary is case sensitive Assert.NotSame(tree.DiagnosticOptions, newTree.DiagnosticOptions); } [Fact] public void PerTreeDiagnosticOptionsNewDict() { var tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()); var map = ImmutableDictionary.CreateRange( new[] { KeyValuePair.Create("CS00778", ReportDiagnostic.Suppress) }); var newTree = tree.WithDiagnosticOptions(map); Assert.NotNull(newTree.DiagnosticOptions); Assert.Same(map, newTree.DiagnosticOptions); Assert.NotEqual(tree, newTree); } #pragma warning restore CS0618 [Fact] public void WithRootAndOptions_ParsedTree() { var oldTree = SyntaxFactory.ParseSyntaxTree("class B {}"); var newRoot = SyntaxFactory.ParseCompilationUnit("class C {}"); var newOptions = new CSharpParseOptions(); var newTree = oldTree.WithRootAndOptions(newRoot, newOptions); var newText = newTree.GetText(); Assert.Equal(newRoot.ToString(), newTree.GetRoot().ToString()); Assert.Same(newOptions, newTree.Options); Assert.Null(newText.Encoding); Assert.Equal(SourceHashAlgorithm.Sha1, newText.ChecksumAlgorithm); } [Fact] public void WithRootAndOptions_ParsedTreeWithText() { var oldText = SourceText.From("class B {}", Encoding.Unicode, SourceHashAlgorithm.Sha256); var oldTree = SyntaxFactory.ParseSyntaxTree(oldText); var newRoot = SyntaxFactory.ParseCompilationUnit("class C {}"); var newOptions = new CSharpParseOptions(); var newTree = oldTree.WithRootAndOptions(newRoot, newOptions); var newText = newTree.GetText(); Assert.Equal(newRoot.ToString(), newTree.GetRoot().ToString()); Assert.Same(newOptions, newTree.Options); Assert.Same(Encoding.Unicode, newText.Encoding); Assert.Equal(SourceHashAlgorithm.Sha256, newText.ChecksumAlgorithm); } [Fact] public void WithRootAndOptions_DummyTree() { var dummy = new CSharpSyntaxTree.DummySyntaxTree(); var newRoot = SyntaxFactory.ParseCompilationUnit("class C {}"); var newOptions = new CSharpParseOptions(); var newTree = dummy.WithRootAndOptions(newRoot, newOptions); Assert.Equal(newRoot.ToString(), newTree.GetRoot().ToString()); Assert.Same(newOptions, newTree.Options); } [Fact] public void WithFilePath_ParsedTree() { var oldTree = SyntaxFactory.ParseSyntaxTree("class B {}", path: "old.cs"); var newTree = oldTree.WithFilePath("new.cs"); var newText = newTree.GetText(); Assert.Equal("new.cs", newTree.FilePath); Assert.Equal(oldTree.ToString(), newTree.ToString()); Assert.Null(newText.Encoding); Assert.Equal(SourceHashAlgorithm.Sha1, newText.ChecksumAlgorithm); } [Fact] public void WithFilePath_ParsedTreeWithText() { var oldText = SourceText.From("class B {}", Encoding.Unicode, SourceHashAlgorithm.Sha256); var oldTree = SyntaxFactory.ParseSyntaxTree(oldText, path: "old.cs"); var newTree = oldTree.WithFilePath("new.cs"); var newText = newTree.GetText(); Assert.Equal("new.cs", newTree.FilePath); Assert.Equal(oldTree.ToString(), newTree.ToString()); Assert.Same(Encoding.Unicode, newText.Encoding); Assert.Equal(SourceHashAlgorithm.Sha256, newText.ChecksumAlgorithm); } [Fact] public void WithFilePath_DummyTree() { var oldTree = new CSharpSyntaxTree.DummySyntaxTree(); var newTree = oldTree.WithFilePath("new.cs"); Assert.Equal("new.cs", newTree.FilePath); Assert.Equal(oldTree.ToString(), newTree.ToString()); } [Fact, WorkItem(12638, "https://github.com/dotnet/roslyn/issues/12638")] public void WithFilePath_Null() { SyntaxTree oldTree = new CSharpSyntaxTree.DummySyntaxTree(); Assert.Equal(string.Empty, oldTree.WithFilePath(null).FilePath); oldTree = SyntaxFactory.ParseSyntaxTree("", path: "old.cs"); Assert.Equal(string.Empty, oldTree.WithFilePath(null).FilePath); Assert.Equal(string.Empty, SyntaxFactory.ParseSyntaxTree("", path: null).FilePath); Assert.Equal(string.Empty, CSharpSyntaxTree.Create((CSharpSyntaxNode)oldTree.GetRoot(), path: null).FilePath); } [Fact] public void GlobalUsingDirective_01() { var test = "global using ns1;"; UsingTree(test, TestOptions.Regular10); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_02() { var test = "global using ns1;"; UsingTree(test, TestOptions.Regular9, // (1,1): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // global using ns1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_03() { var test = "namespace ns { global using ns1; }"; UsingTree(test, TestOptions.Regular10); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_04() { var test = "namespace ns { global using ns1; }"; UsingTree(test, TestOptions.Regular9, // (1,16): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // namespace ns { global using ns1; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 16) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_05() { var test = "global using static ns1;"; UsingTree(test, TestOptions.Regular10); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_06() { var test = "global using static ns1;"; UsingTree(test, TestOptions.Regular9, // (1,1): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // global using static ns1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using static ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_07() { var test = "namespace ns { global using static ns1; }"; UsingTree(test, TestOptions.Regular10); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_08() { var test = "namespace ns { global using static ns1; }"; UsingTree(test, TestOptions.Regular9, // (1,16): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // namespace ns { global using static ns1; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using static ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 16) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_09() { var test = "global using alias = ns1;"; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_10() { var test = "global using alias = ns1;"; UsingTree(test, TestOptions.Regular9, // (1,1): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // global using alias = ns1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using alias = ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_11() { var test = "namespace ns { global using alias = ns1; }"; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_12() { var test = "namespace ns { global using alias = ns1; }"; UsingTree(test, TestOptions.Regular9, // (1,16): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // namespace ns { global using alias = ns1; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using alias = ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 16) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_13() { var test = @" namespace ns {} global using ns1; "; UsingTree(test, TestOptions.RegularPreview, // (3,1): error CS1529: A using clause must precede all other elements defined in the namespace except extern alias declarations // global using ns1; Diagnostic(ErrorCode.ERR_UsingAfterElements, "global using ns1;").WithLocation(3, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_14() { var test = @" global using ns1; extern alias a; "; UsingTree(test, TestOptions.RegularPreview, // (3,1): error CS0439: An extern alias declaration must precede all other elements defined in the namespace // extern alias a; Diagnostic(ErrorCode.ERR_ExternAfterElements, "extern").WithLocation(3, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_15() { var test = @" namespace ns2 { namespace ns {} global using ns1; } "; UsingTree(test, TestOptions.RegularPreview, // (5,5): error CS1529: A using clause must precede all other elements defined in the namespace except extern alias declarations // global using ns1; Diagnostic(ErrorCode.ERR_UsingAfterElements, "global using ns1;").WithLocation(5, 5) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_16() { var test = @" global using ns1; namespace ns {} "; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void UsingDirective_01() { var test = "d using ns1;"; UsingTree(test, TestOptions.Regular, // (1,1): error CS0116: A namespace cannot directly contain members such as fields or methods // d using ns1; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(1, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_17() { var test = "d global using ns1;"; UsingTree(test, TestOptions.RegularPreview, // (1,1): error CS0116: A namespace cannot directly contain members such as fields or methods // d global using ns1; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(1, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void UsingDirective_02() { var test = "using ns1; p using ns2;"; UsingTree(test, TestOptions.Regular, // (1,12): error CS0116: A namespace cannot directly contain members such as fields or methods // using ns1; p using ns2; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "p").WithLocation(1, 12) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_18() { var test = "global using ns1; p global using ns2;"; UsingTree(test, TestOptions.RegularPreview, // (1,19): error CS0116: A namespace cannot directly contain members such as fields or methods // global using ns1; p global using ns2; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "p").WithLocation(1, 19) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_19() { var test = @" M(); global using ns1; "; UsingTree(test, TestOptions.RegularPreview, // (3,1): error CS1529: A using clause must precede all other elements defined in the namespace except extern alias declarations // global using ns1; Diagnostic(ErrorCode.ERR_UsingAfterElements, "global using ns1;").WithLocation(3, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_20() { var test = @" global using ns1; using ns2; M(); "; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_21() { var test = @" global using alias1 = ns1; using alias2 = ns2; M(); "; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias1"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias2"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_22() { var test = @" global using static ns1; using static ns2; M(); "; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Text; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using static Roslyn.Test.Utilities.TestHelpers; using KeyValuePair = Roslyn.Utilities.KeyValuePairUtil; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SyntaxTreeTests : ParsingTests { public SyntaxTreeTests(ITestOutputHelper output) : base(output) { } protected SyntaxTree UsingTree(string text, CSharpParseOptions options, params DiagnosticDescription[] expectedErrors) { var tree = base.UsingTree(text, options); var actualErrors = tree.GetDiagnostics(); actualErrors.Verify(expectedErrors); return tree; } // Diagnostic options on syntax trees are now obsolete #pragma warning disable CS0618 [Fact] public void CreateTreeWithDiagnostics() { var options = CreateImmutableDictionary(("CS0078", ReportDiagnostic.Suppress)); var tree = CSharpSyntaxTree.Create(SyntaxFactory.ParseCompilationUnit(""), options: null, path: "", encoding: null, diagnosticOptions: options); Assert.Same(options, tree.DiagnosticOptions); } [Fact] public void ParseTreeWithChangesPreservesDiagnosticOptions() { var options = CreateImmutableDictionary(("CS0078", ReportDiagnostic.Suppress)); var tree = CSharpSyntaxTree.ParseText( SourceText.From(""), options: null, path: "", diagnosticOptions: options, isGeneratedCode: null, cancellationToken: default); Assert.Same(options, tree.DiagnosticOptions); var newTree = tree.WithChangedText(SourceText.From("class C { }")); Assert.Same(options, newTree.DiagnosticOptions); } [Fact] public void ParseTreeNullDiagnosticOptions() { var tree = CSharpSyntaxTree.ParseText( SourceText.From(""), options: null, path: "", diagnosticOptions: null, isGeneratedCode: null, cancellationToken: default); Assert.NotNull(tree.DiagnosticOptions); Assert.True(tree.DiagnosticOptions.IsEmpty); // The default options are case insensitive but the default empty ImmutableDictionary is not Assert.NotSame(ImmutableDictionary<string, ReportDiagnostic>.Empty, tree.DiagnosticOptions); } [Fact] public void ParseTreeEmptyDiagnosticOptions() { var tree = CSharpSyntaxTree.ParseText( SourceText.From(""), options: null, path: "", diagnosticOptions: ImmutableDictionary<string, ReportDiagnostic>.Empty, isGeneratedCode: null, cancellationToken: default); Assert.NotNull(tree.DiagnosticOptions); Assert.True(tree.DiagnosticOptions.IsEmpty); Assert.Same(ImmutableDictionary<string, ReportDiagnostic>.Empty, tree.DiagnosticOptions); } [Fact] public void ParseTreeCustomDiagnosticOptions() { var options = CreateImmutableDictionary(("CS0078", ReportDiagnostic.Suppress)); var tree = CSharpSyntaxTree.ParseText( SourceText.From(""), options: null, path: "", diagnosticOptions: options, isGeneratedCode: null, cancellationToken: default); Assert.Same(options, tree.DiagnosticOptions); } [Fact] public void DefaultTreeDiagnosticOptions() { var tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()); Assert.NotNull(tree.DiagnosticOptions); Assert.True(tree.DiagnosticOptions.IsEmpty); } [Fact] public void WithDiagnosticOptionsNull() { var tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()); var newTree = tree.WithDiagnosticOptions(null); Assert.NotNull(newTree.DiagnosticOptions); Assert.True(newTree.DiagnosticOptions.IsEmpty); Assert.Same(tree, newTree); } [Fact] public void WithDiagnosticOptionsEmpty() { var tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()); var newTree = tree.WithDiagnosticOptions(ImmutableDictionary<string, ReportDiagnostic>.Empty); Assert.NotNull(tree.DiagnosticOptions); Assert.True(newTree.DiagnosticOptions.IsEmpty); // Default empty immutable dictionary is case sensitive Assert.NotSame(tree.DiagnosticOptions, newTree.DiagnosticOptions); } [Fact] public void PerTreeDiagnosticOptionsNewDict() { var tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()); var map = ImmutableDictionary.CreateRange( new[] { KeyValuePair.Create("CS00778", ReportDiagnostic.Suppress) }); var newTree = tree.WithDiagnosticOptions(map); Assert.NotNull(newTree.DiagnosticOptions); Assert.Same(map, newTree.DiagnosticOptions); Assert.NotEqual(tree, newTree); } #pragma warning restore CS0618 [Fact] public void WithRootAndOptions_ParsedTree() { var oldTree = SyntaxFactory.ParseSyntaxTree("class B {}"); var newRoot = SyntaxFactory.ParseCompilationUnit("class C {}"); var newOptions = new CSharpParseOptions(); var newTree = oldTree.WithRootAndOptions(newRoot, newOptions); var newText = newTree.GetText(); Assert.Equal(newRoot.ToString(), newTree.GetRoot().ToString()); Assert.Same(newOptions, newTree.Options); Assert.Null(newText.Encoding); Assert.Equal(SourceHashAlgorithm.Sha1, newText.ChecksumAlgorithm); } [Fact] public void WithRootAndOptions_ParsedTreeWithText() { var oldText = SourceText.From("class B {}", Encoding.Unicode, SourceHashAlgorithm.Sha256); var oldTree = SyntaxFactory.ParseSyntaxTree(oldText); var newRoot = SyntaxFactory.ParseCompilationUnit("class C {}"); var newOptions = new CSharpParseOptions(); var newTree = oldTree.WithRootAndOptions(newRoot, newOptions); var newText = newTree.GetText(); Assert.Equal(newRoot.ToString(), newTree.GetRoot().ToString()); Assert.Same(newOptions, newTree.Options); Assert.Same(Encoding.Unicode, newText.Encoding); Assert.Equal(SourceHashAlgorithm.Sha256, newText.ChecksumAlgorithm); } [Fact] public void WithRootAndOptions_DummyTree() { var dummy = new CSharpSyntaxTree.DummySyntaxTree(); var newRoot = SyntaxFactory.ParseCompilationUnit("class C {}"); var newOptions = new CSharpParseOptions(); var newTree = dummy.WithRootAndOptions(newRoot, newOptions); Assert.Equal(newRoot.ToString(), newTree.GetRoot().ToString()); Assert.Same(newOptions, newTree.Options); } [Fact] public void WithFilePath_ParsedTree() { var oldTree = SyntaxFactory.ParseSyntaxTree("class B {}", path: "old.cs"); var newTree = oldTree.WithFilePath("new.cs"); var newText = newTree.GetText(); Assert.Equal("new.cs", newTree.FilePath); Assert.Equal(oldTree.ToString(), newTree.ToString()); Assert.Null(newText.Encoding); Assert.Equal(SourceHashAlgorithm.Sha1, newText.ChecksumAlgorithm); } [Fact] public void WithFilePath_ParsedTreeWithText() { var oldText = SourceText.From("class B {}", Encoding.Unicode, SourceHashAlgorithm.Sha256); var oldTree = SyntaxFactory.ParseSyntaxTree(oldText, path: "old.cs"); var newTree = oldTree.WithFilePath("new.cs"); var newText = newTree.GetText(); Assert.Equal("new.cs", newTree.FilePath); Assert.Equal(oldTree.ToString(), newTree.ToString()); Assert.Same(Encoding.Unicode, newText.Encoding); Assert.Equal(SourceHashAlgorithm.Sha256, newText.ChecksumAlgorithm); } [Fact] public void WithFilePath_DummyTree() { var oldTree = new CSharpSyntaxTree.DummySyntaxTree(); var newTree = oldTree.WithFilePath("new.cs"); Assert.Equal("new.cs", newTree.FilePath); Assert.Equal(oldTree.ToString(), newTree.ToString()); } [Fact, WorkItem(12638, "https://github.com/dotnet/roslyn/issues/12638")] public void WithFilePath_Null() { SyntaxTree oldTree = new CSharpSyntaxTree.DummySyntaxTree(); Assert.Equal(string.Empty, oldTree.WithFilePath(null).FilePath); oldTree = SyntaxFactory.ParseSyntaxTree("", path: "old.cs"); Assert.Equal(string.Empty, oldTree.WithFilePath(null).FilePath); Assert.Equal(string.Empty, SyntaxFactory.ParseSyntaxTree("", path: null).FilePath); Assert.Equal(string.Empty, CSharpSyntaxTree.Create((CSharpSyntaxNode)oldTree.GetRoot(), path: null).FilePath); } [Fact] public void GlobalUsingDirective_01() { var test = "global using ns1;"; UsingTree(test, TestOptions.Regular10); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_02() { var test = "global using ns1;"; UsingTree(test, TestOptions.Regular9, // (1,1): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // global using ns1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_03() { var test = "namespace ns { global using ns1; }"; UsingTree(test, TestOptions.Regular10); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_04() { var test = "namespace ns { global using ns1; }"; UsingTree(test, TestOptions.Regular9, // (1,16): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // namespace ns { global using ns1; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 16) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_05() { var test = "global using static ns1;"; UsingTree(test, TestOptions.Regular10); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_06() { var test = "global using static ns1;"; UsingTree(test, TestOptions.Regular9, // (1,1): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // global using static ns1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using static ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_07() { var test = "namespace ns { global using static ns1; }"; UsingTree(test, TestOptions.Regular10); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_08() { var test = "namespace ns { global using static ns1; }"; UsingTree(test, TestOptions.Regular9, // (1,16): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // namespace ns { global using static ns1; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using static ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 16) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_09() { var test = "global using alias = ns1;"; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_10() { var test = "global using alias = ns1;"; UsingTree(test, TestOptions.Regular9, // (1,1): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // global using alias = ns1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using alias = ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_11() { var test = "namespace ns { global using alias = ns1; }"; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_12() { var test = "namespace ns { global using alias = ns1; }"; UsingTree(test, TestOptions.Regular9, // (1,16): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // namespace ns { global using alias = ns1; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using alias = ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 16) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_13() { var test = @" namespace ns {} global using ns1; "; UsingTree(test, TestOptions.RegularPreview, // (3,1): error CS1529: A using clause must precede all other elements defined in the namespace except extern alias declarations // global using ns1; Diagnostic(ErrorCode.ERR_UsingAfterElements, "global using ns1;").WithLocation(3, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_14() { var test = @" global using ns1; extern alias a; "; UsingTree(test, TestOptions.RegularPreview, // (3,1): error CS0439: An extern alias declaration must precede all other elements defined in the namespace // extern alias a; Diagnostic(ErrorCode.ERR_ExternAfterElements, "extern").WithLocation(3, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_15() { var test = @" namespace ns2 { namespace ns {} global using ns1; } "; UsingTree(test, TestOptions.RegularPreview, // (5,5): error CS1529: A using clause must precede all other elements defined in the namespace except extern alias declarations // global using ns1; Diagnostic(ErrorCode.ERR_UsingAfterElements, "global using ns1;").WithLocation(5, 5) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_16() { var test = @" global using ns1; namespace ns {} "; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void UsingDirective_01() { var test = "d using ns1;"; UsingTree(test, TestOptions.Regular, // (1,1): error CS0116: A namespace cannot directly contain members such as fields or methods // d using ns1; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(1, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_17() { var test = "d global using ns1;"; UsingTree(test, TestOptions.RegularPreview, // (1,1): error CS0116: A namespace cannot directly contain members such as fields or methods // d global using ns1; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(1, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void UsingDirective_02() { var test = "using ns1; p using ns2;"; UsingTree(test, TestOptions.Regular, // (1,12): error CS0116: A namespace cannot directly contain members such as fields or methods // using ns1; p using ns2; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "p").WithLocation(1, 12) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_18() { var test = "global using ns1; p global using ns2;"; UsingTree(test, TestOptions.RegularPreview, // (1,19): error CS0116: A namespace cannot directly contain members such as fields or methods // global using ns1; p global using ns2; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "p").WithLocation(1, 19) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_19() { var test = @" M(); global using ns1; "; UsingTree(test, TestOptions.RegularPreview, // (3,1): error CS1529: A using clause must precede all other elements defined in the namespace except extern alias declarations // global using ns1; Diagnostic(ErrorCode.ERR_UsingAfterElements, "global using ns1;").WithLocation(3, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_20() { var test = @" global using ns1; using ns2; M(); "; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_21() { var test = @" global using alias1 = ns1; using alias2 = ns2; M(); "; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias1"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias2"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_22() { var test = @" global using static ns1; using static ns2; M(); "; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/EditorFeatures/Core/EditorConfigSettings/DataProvider/CombinedProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider { internal class CombinedProvider<T> : ISettingsProvider<T> { private readonly ImmutableArray<ISettingsProvider<T>> _providers; public CombinedProvider(ImmutableArray<ISettingsProvider<T>> providers) { _providers = providers; } public async Task<SourceText> GetChangedEditorConfigAsync(SourceText sourceText) { foreach (var provider in _providers) { sourceText = await provider.GetChangedEditorConfigAsync(sourceText).ConfigureAwait(false); } return sourceText; } public ImmutableArray<T> GetCurrentDataSnapshot() { var snapShot = ImmutableArray<T>.Empty; foreach (var provider in _providers) { snapShot = snapShot.Concat(provider.GetCurrentDataSnapshot()); } return snapShot; } public void RegisterViewModel(ISettingsEditorViewModel model) { foreach (var provider in _providers) { provider.RegisterViewModel(model); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider { internal class CombinedProvider<T> : ISettingsProvider<T> { private readonly ImmutableArray<ISettingsProvider<T>> _providers; public CombinedProvider(ImmutableArray<ISettingsProvider<T>> providers) { _providers = providers; } public async Task<SourceText> GetChangedEditorConfigAsync(SourceText sourceText) { foreach (var provider in _providers) { sourceText = await provider.GetChangedEditorConfigAsync(sourceText).ConfigureAwait(false); } return sourceText; } public ImmutableArray<T> GetCurrentDataSnapshot() { var snapShot = ImmutableArray<T>.Empty; foreach (var provider in _providers) { snapShot = snapShot.Concat(provider.GetCurrentDataSnapshot()); } return snapShot; } public void RegisterViewModel(ISettingsEditorViewModel model) { foreach (var provider in _providers) { provider.RegisterViewModel(model); } } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Compilers/CSharp/Portable/Symbols/FunctionTypeSymbol.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 Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A <see cref="TypeSymbol"/> implementation that represents the inferred signature of a /// lambda expression or method group. This is implemented as a <see cref="TypeSymbol"/> /// to allow types and function signatures to be treated similarly in <see cref="ConversionsBase"/>, /// <see cref="BestTypeInferrer"/>, and <see cref="MethodTypeInferrer"/>. Instances of this type /// should only be used in those code paths and should not be exposed from the symbol model. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] internal sealed partial class FunctionTypeSymbol : TypeSymbol { internal static readonly FunctionTypeSymbol Uninitialized = new FunctionTypeSymbol(ErrorTypeSymbol.UnknownResultType); private readonly NamedTypeSymbol _delegateType; internal FunctionTypeSymbol(NamedTypeSymbol delegateType) { _delegateType = delegateType; } internal NamedTypeSymbol GetInternalDelegateType() => _delegateType; public override bool IsReferenceType => true; public override bool IsValueType => false; public override TypeKind TypeKind => TypeKindInternal.FunctionType; public override bool IsRefLikeType => false; public override bool IsReadOnly => true; public override SymbolKind Kind => SymbolKindInternal.FunctionType; public override Symbol? ContainingSymbol => null; public override ImmutableArray<Location> Locations => throw ExceptionUtilities.Unreachable; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => throw ExceptionUtilities.Unreachable; public override Accessibility DeclaredAccessibility => throw ExceptionUtilities.Unreachable; public override bool IsStatic => false; public override bool IsAbstract => throw ExceptionUtilities.Unreachable; public override bool IsSealed => throw ExceptionUtilities.Unreachable; internal override NamedTypeSymbol? BaseTypeNoUseSiteDiagnostics => null; internal override bool IsRecord => throw ExceptionUtilities.Unreachable; internal override bool IsRecordStruct => throw ExceptionUtilities.Unreachable; internal override ObsoleteAttributeData ObsoleteAttributeData => throw ExceptionUtilities.Unreachable; public override void Accept(CSharpSymbolVisitor visitor) => throw ExceptionUtilities.Unreachable; public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) => throw ExceptionUtilities.Unreachable; public override ImmutableArray<Symbol> GetMembers() => throw ExceptionUtilities.Unreachable; public override ImmutableArray<Symbol> GetMembers(string name) => throw ExceptionUtilities.Unreachable; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() => throw ExceptionUtilities.Unreachable; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) => throw ExceptionUtilities.Unreachable; protected override ISymbol CreateISymbol() => throw ExceptionUtilities.Unreachable; protected override ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation) => throw ExceptionUtilities.Unreachable; internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument a) => throw ExceptionUtilities.Unreachable; internal override void AddNullableTransforms(ArrayBuilder<byte> transforms) => throw ExceptionUtilities.Unreachable; internal override bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result) => throw ExceptionUtilities.Unreachable; internal override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => throw ExceptionUtilities.Unreachable; internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) => throw ExceptionUtilities.Unreachable; internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol>? basesBeingResolved = null) => ImmutableArray<NamedTypeSymbol>.Empty; internal override TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance) { Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); var otherType = (FunctionTypeSymbol)other; var delegateType = (NamedTypeSymbol)_delegateType.MergeEquivalentTypes(otherType._delegateType, variance); return (object)_delegateType == delegateType ? this : otherType.WithDelegateType(delegateType); } internal override TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform) { return WithDelegateType((NamedTypeSymbol)_delegateType.SetNullabilityForReferenceTypes(transform)); } private FunctionTypeSymbol WithDelegateType(NamedTypeSymbol delegateType) { return (object)_delegateType == delegateType ? this : new FunctionTypeSymbol(delegateType); } internal override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() => throw ExceptionUtilities.Unreachable; internal override bool Equals(TypeSymbol t2, TypeCompareKind compareKind) { if (ReferenceEquals(this, t2)) { return true; } var otherType = (t2 as FunctionTypeSymbol)?._delegateType; return _delegateType.Equals(otherType, compareKind); } public override int GetHashCode() { return _delegateType.GetHashCode(); } internal override string GetDebuggerDisplay() { return $"FunctionTypeSymbol: {_delegateType.GetDebuggerDisplay()}"; } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A <see cref="TypeSymbol"/> implementation that represents the inferred signature of a /// lambda expression or method group. This is implemented as a <see cref="TypeSymbol"/> /// to allow types and function signatures to be treated similarly in <see cref="ConversionsBase"/>, /// <see cref="BestTypeInferrer"/>, and <see cref="MethodTypeInferrer"/>. Instances of this type /// should only be used in those code paths and should not be exposed from the symbol model. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] internal sealed partial class FunctionTypeSymbol : TypeSymbol { internal static readonly FunctionTypeSymbol Uninitialized = new FunctionTypeSymbol(ErrorTypeSymbol.UnknownResultType); private readonly NamedTypeSymbol _delegateType; internal FunctionTypeSymbol(NamedTypeSymbol delegateType) { _delegateType = delegateType; } internal NamedTypeSymbol GetInternalDelegateType() => _delegateType; public override bool IsReferenceType => true; public override bool IsValueType => false; public override TypeKind TypeKind => TypeKindInternal.FunctionType; public override bool IsRefLikeType => false; public override bool IsReadOnly => true; public override SymbolKind Kind => SymbolKindInternal.FunctionType; public override Symbol? ContainingSymbol => null; public override ImmutableArray<Location> Locations => throw ExceptionUtilities.Unreachable; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => throw ExceptionUtilities.Unreachable; public override Accessibility DeclaredAccessibility => throw ExceptionUtilities.Unreachable; public override bool IsStatic => false; public override bool IsAbstract => throw ExceptionUtilities.Unreachable; public override bool IsSealed => throw ExceptionUtilities.Unreachable; internal override NamedTypeSymbol? BaseTypeNoUseSiteDiagnostics => null; internal override bool IsRecord => throw ExceptionUtilities.Unreachable; internal override bool IsRecordStruct => throw ExceptionUtilities.Unreachable; internal override ObsoleteAttributeData ObsoleteAttributeData => throw ExceptionUtilities.Unreachable; public override void Accept(CSharpSymbolVisitor visitor) => throw ExceptionUtilities.Unreachable; public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) => throw ExceptionUtilities.Unreachable; public override ImmutableArray<Symbol> GetMembers() => throw ExceptionUtilities.Unreachable; public override ImmutableArray<Symbol> GetMembers(string name) => throw ExceptionUtilities.Unreachable; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() => throw ExceptionUtilities.Unreachable; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) => throw ExceptionUtilities.Unreachable; protected override ISymbol CreateISymbol() => throw ExceptionUtilities.Unreachable; protected override ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation) => throw ExceptionUtilities.Unreachable; internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument a) => throw ExceptionUtilities.Unreachable; internal override void AddNullableTransforms(ArrayBuilder<byte> transforms) => throw ExceptionUtilities.Unreachable; internal override bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result) => throw ExceptionUtilities.Unreachable; internal override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => throw ExceptionUtilities.Unreachable; internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) => throw ExceptionUtilities.Unreachable; internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol>? basesBeingResolved = null) => ImmutableArray<NamedTypeSymbol>.Empty; internal override TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance) { Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); var otherType = (FunctionTypeSymbol)other; var delegateType = (NamedTypeSymbol)_delegateType.MergeEquivalentTypes(otherType._delegateType, variance); return (object)_delegateType == delegateType ? this : otherType.WithDelegateType(delegateType); } internal override TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform) { return WithDelegateType((NamedTypeSymbol)_delegateType.SetNullabilityForReferenceTypes(transform)); } private FunctionTypeSymbol WithDelegateType(NamedTypeSymbol delegateType) { return (object)_delegateType == delegateType ? this : new FunctionTypeSymbol(delegateType); } internal override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() => throw ExceptionUtilities.Unreachable; internal override bool Equals(TypeSymbol t2, TypeCompareKind compareKind) { if (ReferenceEquals(this, t2)) { return true; } var otherType = (t2 as FunctionTypeSymbol)?._delegateType; return _delegateType.Equals(otherType, compareKind); } public override int GetHashCode() { return _delegateType.GetHashCode(); } internal override string GetDebuggerDisplay() { return $"FunctionTypeSymbol: {_delegateType.GetDebuggerDisplay()}"; } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Workspaces/CSharp/Portable/FindSymbols/CSharpDeclaredSymbolInfoFactoryService.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.Composition; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.FindSymbols { [ExportLanguageService(typeof(IDeclaredSymbolInfoFactoryService), LanguageNames.CSharp), Shared] internal class CSharpDeclaredSymbolInfoFactoryService : AbstractDeclaredSymbolInfoFactoryService< CompilationUnitSyntax, UsingDirectiveSyntax, BaseNamespaceDeclarationSyntax, TypeDeclarationSyntax, EnumDeclarationSyntax, MemberDeclarationSyntax, NameSyntax, QualifiedNameSyntax, IdentifierNameSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpDeclaredSymbolInfoFactoryService() { } private static ImmutableArray<string> GetInheritanceNames(StringTable stringTable, BaseListSyntax baseList) { if (baseList == null) { return ImmutableArray<string>.Empty; } var builder = ArrayBuilder<string>.GetInstance(baseList.Types.Count); // It's not sufficient to just store the textual names we see in the inheritance list // of a type. For example if we have: // // using Y = X; // ... // using Z = Y; // ... // class C : Z // // It's insufficient to just state that 'C' derives from 'Z'. If we search for derived // types from 'B' we won't examine 'C'. To solve this, we keep track of the aliasing // that occurs in containing scopes. Then, when we're adding an inheritance name we // walk the alias maps and we also add any names that these names alias to. In the // above example we'd put Z, Y, and X in the inheritance names list for 'C'. // Each dictionary in this list is a mapping from alias name to the name of the thing // it aliases. Then, each scope with alias mapping gets its own entry in this list. // For the above example, we would produce: [{Z => Y}, {Y => X}] var aliasMaps = AllocateAliasMapList(); try { AddAliasMaps(baseList, aliasMaps); foreach (var baseType in baseList.Types) { AddInheritanceName(builder, baseType.Type, aliasMaps); } Intern(stringTable, builder); return builder.ToImmutableAndFree(); } finally { FreeAliasMapList(aliasMaps); } } private static void AddAliasMaps(SyntaxNode node, List<Dictionary<string, string>> aliasMaps) { for (var current = node; current != null; current = current.Parent) { if (current is BaseNamespaceDeclarationSyntax nsDecl) { ProcessUsings(aliasMaps, nsDecl.Usings); } else if (current.IsKind(SyntaxKind.CompilationUnit, out CompilationUnitSyntax compilationUnit)) { ProcessUsings(aliasMaps, compilationUnit.Usings); } } } private static void ProcessUsings(List<Dictionary<string, string>> aliasMaps, SyntaxList<UsingDirectiveSyntax> usings) { Dictionary<string, string> aliasMap = null; foreach (var usingDecl in usings) { if (usingDecl.Alias != null) { var mappedName = GetTypeName(usingDecl.Name); if (mappedName != null) { aliasMap ??= AllocateAliasMap(); // If we have: using X = Goo, then we store a mapping from X -> Goo // here. That way if we see a class that inherits from X we also state // that it inherits from Goo as well. aliasMap[usingDecl.Alias.Name.Identifier.ValueText] = mappedName; } } } if (aliasMap != null) { aliasMaps.Add(aliasMap); } } private static void AddInheritanceName( ArrayBuilder<string> builder, TypeSyntax type, List<Dictionary<string, string>> aliasMaps) { var name = GetTypeName(type); if (name != null) { // First, add the name that the typename that the type directly says it inherits from. builder.Add(name); // Now, walk the alias chain and add any names this alias may eventually map to. var currentName = name; foreach (var aliasMap in aliasMaps) { if (aliasMap.TryGetValue(currentName, out var mappedName)) { // Looks like this could be an alias. Also include the name the alias points to builder.Add(mappedName); // Keep on searching. An alias in an inner namespcae can refer to an // alias in an outer namespace. currentName = mappedName; } } } } protected override void AddDeclaredSymbolInfosWorker( SyntaxNode container, MemberDeclarationSyntax node, StringTable stringTable, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, string> aliases, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, string containerDisplayName, string fullyQualifiedContainerName, CancellationToken cancellationToken) { // If this is a part of partial type that only contains nested types, then we don't make an info type for // it. That's because we effectively think of this as just being a virtual container just to hold the nested // types, and not something someone would want to explicitly navigate to itself. Similar to how we think of // namespaces. if (node is TypeDeclarationSyntax typeDeclaration && typeDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword) && typeDeclaration.Members.Any() && typeDeclaration.Members.All(m => m is BaseTypeDeclarationSyntax)) { return; } switch (node.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: var typeDecl = (TypeDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, typeDecl.Identifier.ValueText, GetTypeParameterSuffix(typeDecl.TypeParameterList), containerDisplayName, fullyQualifiedContainerName, typeDecl.Modifiers.Any(SyntaxKind.PartialKeyword), node.Kind() switch { SyntaxKind.ClassDeclaration => DeclaredSymbolInfoKind.Class, SyntaxKind.RecordDeclaration => DeclaredSymbolInfoKind.Record, SyntaxKind.InterfaceDeclaration => DeclaredSymbolInfoKind.Interface, SyntaxKind.StructDeclaration => DeclaredSymbolInfoKind.Struct, SyntaxKind.RecordStructDeclaration => DeclaredSymbolInfoKind.RecordStruct, _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()), }, GetAccessibility(container, typeDecl.Modifiers), typeDecl.Identifier.Span, GetInheritanceNames(stringTable, typeDecl.BaseList), IsNestedType(typeDecl))); return; case SyntaxKind.EnumDeclaration: var enumDecl = (EnumDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, enumDecl.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, enumDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Enum, GetAccessibility(container, enumDecl.Modifiers), enumDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, isNestedType: IsNestedType(enumDecl))); return; case SyntaxKind.ConstructorDeclaration: var ctorDecl = (ConstructorDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, ctorDecl.Identifier.ValueText, GetConstructorSuffix(ctorDecl), containerDisplayName, fullyQualifiedContainerName, ctorDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Constructor, GetAccessibility(container, ctorDecl.Modifiers), ctorDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, parameterCount: ctorDecl.ParameterList?.Parameters.Count ?? 0)); return; case SyntaxKind.DelegateDeclaration: var delegateDecl = (DelegateDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, delegateDecl.Identifier.ValueText, GetTypeParameterSuffix(delegateDecl.TypeParameterList), containerDisplayName, fullyQualifiedContainerName, delegateDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Delegate, GetAccessibility(container, delegateDecl.Modifiers), delegateDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.EnumMemberDeclaration: var enumMember = (EnumMemberDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, enumMember.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, enumMember.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.EnumMember, Accessibility.Public, enumMember.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.EventDeclaration: var eventDecl = (EventDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, eventDecl.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, eventDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Event, GetAccessibility(container, eventDecl.Modifiers), eventDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.IndexerDeclaration: var indexerDecl = (IndexerDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, "this", GetIndexerSuffix(indexerDecl), containerDisplayName, fullyQualifiedContainerName, indexerDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Indexer, GetAccessibility(container, indexerDecl.Modifiers), indexerDecl.ThisKeyword.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)node; var isExtensionMethod = IsExtensionMethod(method); declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, method.Identifier.ValueText, GetMethodSuffix(method), containerDisplayName, fullyQualifiedContainerName, method.Modifiers.Any(SyntaxKind.PartialKeyword), isExtensionMethod ? DeclaredSymbolInfoKind.ExtensionMethod : DeclaredSymbolInfoKind.Method, GetAccessibility(container, method.Modifiers), method.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, parameterCount: method.ParameterList?.Parameters.Count ?? 0, typeParameterCount: method.TypeParameterList?.Parameters.Count ?? 0)); if (isExtensionMethod) AddExtensionMethodInfo(method, aliases, declaredSymbolInfos.Count - 1, extensionMethodInfo); return; case SyntaxKind.PropertyDeclaration: var property = (PropertyDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, property.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, property.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Property, GetAccessibility(container, property.Modifiers), property.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: var fieldDeclaration = (BaseFieldDeclarationSyntax)node; foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables) { var kind = fieldDeclaration is EventFieldDeclarationSyntax ? DeclaredSymbolInfoKind.Event : fieldDeclaration.Modifiers.Any(m => m.Kind() == SyntaxKind.ConstKeyword) ? DeclaredSymbolInfoKind.Constant : DeclaredSymbolInfoKind.Field; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, variableDeclarator.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, fieldDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword), kind, GetAccessibility(container, fieldDeclaration.Modifiers), variableDeclarator.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); } return; } } protected override SyntaxList<MemberDeclarationSyntax> GetChildren(CompilationUnitSyntax node) => node.Members; protected override SyntaxList<MemberDeclarationSyntax> GetChildren(BaseNamespaceDeclarationSyntax node) => node.Members; protected override SyntaxList<MemberDeclarationSyntax> GetChildren(TypeDeclarationSyntax node) => node.Members; protected override IEnumerable<MemberDeclarationSyntax> GetChildren(EnumDeclarationSyntax node) => node.Members; protected override SyntaxList<UsingDirectiveSyntax> GetUsingAliases(CompilationUnitSyntax node) => node.Usings; protected override SyntaxList<UsingDirectiveSyntax> GetUsingAliases(BaseNamespaceDeclarationSyntax node) => node.Usings; protected override NameSyntax GetName(BaseNamespaceDeclarationSyntax node) => node.Name; protected override NameSyntax GetLeft(QualifiedNameSyntax node) => node.Left; protected override NameSyntax GetRight(QualifiedNameSyntax node) => node.Right; protected override SyntaxToken GetIdentifier(IdentifierNameSyntax node) => node.Identifier; private static bool IsNestedType(BaseTypeDeclarationSyntax typeDecl) => typeDecl.Parent is BaseTypeDeclarationSyntax; private static string GetConstructorSuffix(ConstructorDeclarationSyntax constructor) => constructor.Modifiers.Any(SyntaxKind.StaticKeyword) ? ".static " + constructor.Identifier + "()" : GetSuffix('(', ')', constructor.ParameterList.Parameters); private static string GetMethodSuffix(MethodDeclarationSyntax method) => GetTypeParameterSuffix(method.TypeParameterList) + GetSuffix('(', ')', method.ParameterList.Parameters); private static string GetIndexerSuffix(IndexerDeclarationSyntax indexer) => GetSuffix('[', ']', indexer.ParameterList.Parameters); private static string GetTypeParameterSuffix(TypeParameterListSyntax typeParameterList) { if (typeParameterList == null) { return null; } var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append('<'); var first = true; foreach (var parameter in typeParameterList.Parameters) { if (!first) { builder.Append(", "); } builder.Append(parameter.Identifier.Text); first = false; } builder.Append('>'); return pooledBuilder.ToStringAndFree(); } /// <summary> /// Builds up the suffix to show for something with parameters in navigate-to. /// While it would be nice to just use the compiler SymbolDisplay API for this, /// it would be too expensive as it requires going back to Symbols (which requires /// creating compilations, etc.) in a perf sensitive area. /// /// So, instead, we just build a reasonable suffix using the pure syntax that a /// user provided. That means that if they wrote "Method(System.Int32 i)" we'll /// show that as "Method(System.Int32)" not "Method(int)". Given that this is /// actually what the user wrote, and it saves us from ever having to go back to /// symbols/compilations, this is well worth it, even if it does mean we have to /// create our own 'symbol display' logic here. /// </summary> private static string GetSuffix( char openBrace, char closeBrace, SeparatedSyntaxList<ParameterSyntax> parameters) { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append(openBrace); AppendParameters(parameters, builder); builder.Append(closeBrace); return pooledBuilder.ToStringAndFree(); } private static void AppendParameters(SeparatedSyntaxList<ParameterSyntax> parameters, StringBuilder builder) { var first = true; foreach (var parameter in parameters) { if (!first) { builder.Append(", "); } foreach (var modifier in parameter.Modifiers) { builder.Append(modifier.Text); builder.Append(' '); } if (parameter.Type != null) { AppendTokens(parameter.Type, builder); } else { builder.Append(parameter.Identifier.Text); } first = false; } } protected override string GetContainerDisplayName(MemberDeclarationSyntax node) => CSharpSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeTypeParameters); protected override string GetFullyQualifiedContainerName(MemberDeclarationSyntax node, string rootNamespace) => CSharpSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeNamespaces); private static Accessibility GetAccessibility(SyntaxNode container, SyntaxTokenList modifiers) { var sawInternal = false; foreach (var modifier in modifiers) { switch (modifier.Kind()) { case SyntaxKind.PublicKeyword: return Accessibility.Public; case SyntaxKind.PrivateKeyword: return Accessibility.Private; case SyntaxKind.ProtectedKeyword: return Accessibility.Protected; case SyntaxKind.InternalKeyword: sawInternal = true; continue; } } if (sawInternal) return Accessibility.Internal; // No accessibility modifiers: switch (container.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: // Anything without modifiers is private if it's in a class/struct declaration. return Accessibility.Private; case SyntaxKind.InterfaceDeclaration: // Anything without modifiers is public if it's in an interface declaration. return Accessibility.Public; case SyntaxKind.CompilationUnit: // Things are private by default in script if (((CSharpParseOptions)container.SyntaxTree.Options).Kind == SourceCodeKind.Script) return Accessibility.Private; return Accessibility.Internal; default: // Otherwise it's internal return Accessibility.Internal; } } private static string GetTypeName(TypeSyntax type) { if (type is SimpleNameSyntax simpleName) { return GetSimpleTypeName(simpleName); } else if (type is QualifiedNameSyntax qualifiedName) { return GetSimpleTypeName(qualifiedName.Right); } else if (type is AliasQualifiedNameSyntax aliasName) { return GetSimpleTypeName(aliasName.Name); } return null; } private static string GetSimpleTypeName(SimpleNameSyntax name) => name.Identifier.ValueText; private static bool IsExtensionMethod(MethodDeclarationSyntax method) => method.ParameterList.Parameters.Count > 0 && method.ParameterList.Parameters[0].Modifiers.Any(SyntaxKind.ThisKeyword); // Root namespace is a VB only concept, which basically means root namespace is always global in C#. protected override string GetRootNamespace(CompilationOptions compilationOptions) => string.Empty; protected override bool TryGetAliasesFromUsingDirective( UsingDirectiveSyntax usingDirectiveNode, out ImmutableArray<(string aliasName, string name)> aliases) { if (usingDirectiveNode.Alias != null) { if (TryGetSimpleTypeName(usingDirectiveNode.Alias.Name, typeParameterNames: null, out var aliasName, out _) && TryGetSimpleTypeName(usingDirectiveNode.Name, typeParameterNames: null, out var name, out _)) { aliases = ImmutableArray.Create<(string, string)>((aliasName, name)); return true; } } aliases = default; return false; } protected override string GetReceiverTypeName(MemberDeclarationSyntax node) { var methodDeclaration = (MethodDeclarationSyntax)node; Debug.Assert(IsExtensionMethod(methodDeclaration)); var typeParameterNames = methodDeclaration.TypeParameterList?.Parameters.SelectAsArray(p => p.Identifier.Text); TryGetSimpleTypeName(methodDeclaration.ParameterList.Parameters[0].Type, typeParameterNames, out var targetTypeName, out var isArray); return CreateReceiverTypeString(targetTypeName, isArray); } private static bool TryGetSimpleTypeName(SyntaxNode node, ImmutableArray<string>? typeParameterNames, out string simpleTypeName, out bool isArray) { isArray = false; if (node is TypeSyntax typeNode) { switch (typeNode) { case IdentifierNameSyntax identifierNameNode: // We consider it a complex method if the receiver type is a type parameter. var text = identifierNameNode.Identifier.Text; simpleTypeName = typeParameterNames?.Contains(text) == true ? null : text; return simpleTypeName != null; case ArrayTypeSyntax arrayTypeNode: isArray = true; return TryGetSimpleTypeName(arrayTypeNode.ElementType, typeParameterNames, out simpleTypeName, out _); case GenericNameSyntax genericNameNode: var name = genericNameNode.Identifier.Text; var arity = genericNameNode.Arity; simpleTypeName = arity == 0 ? name : name + ArityUtilities.GetMetadataAritySuffix(arity); return true; case PredefinedTypeSyntax predefinedTypeNode: simpleTypeName = GetSpecialTypeName(predefinedTypeNode); return simpleTypeName != null; case AliasQualifiedNameSyntax aliasQualifiedNameNode: return TryGetSimpleTypeName(aliasQualifiedNameNode.Name, typeParameterNames, out simpleTypeName, out _); case QualifiedNameSyntax qualifiedNameNode: // For an identifier to the right of a '.', it can't be a type parameter, // so we don't need to check for it further. return TryGetSimpleTypeName(qualifiedNameNode.Right, typeParameterNames: null, out simpleTypeName, out _); case NullableTypeSyntax nullableNode: // Ignore nullability, becase nullable reference type might not be enabled universally. // In the worst case we just include more methods to check in out filter. return TryGetSimpleTypeName(nullableNode.ElementType, typeParameterNames, out simpleTypeName, out isArray); case TupleTypeSyntax tupleType: simpleTypeName = CreateValueTupleTypeString(tupleType.Elements.Count); return true; } } simpleTypeName = null; return false; } private static string GetSpecialTypeName(PredefinedTypeSyntax predefinedTypeNode) { var kind = predefinedTypeNode.Keyword.Kind(); return kind switch { SyntaxKind.BoolKeyword => "Boolean", SyntaxKind.ByteKeyword => "Byte", SyntaxKind.SByteKeyword => "SByte", SyntaxKind.ShortKeyword => "Int16", SyntaxKind.UShortKeyword => "UInt16", SyntaxKind.IntKeyword => "Int32", SyntaxKind.UIntKeyword => "UInt32", SyntaxKind.LongKeyword => "Int64", SyntaxKind.ULongKeyword => "UInt64", SyntaxKind.DoubleKeyword => "Double", SyntaxKind.FloatKeyword => "Single", SyntaxKind.DecimalKeyword => "Decimal", SyntaxKind.StringKeyword => "String", SyntaxKind.CharKeyword => "Char", SyntaxKind.ObjectKeyword => "Object", _ => 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.FindSymbols { [ExportLanguageService(typeof(IDeclaredSymbolInfoFactoryService), LanguageNames.CSharp), Shared] internal class CSharpDeclaredSymbolInfoFactoryService : AbstractDeclaredSymbolInfoFactoryService< CompilationUnitSyntax, UsingDirectiveSyntax, BaseNamespaceDeclarationSyntax, TypeDeclarationSyntax, EnumDeclarationSyntax, MemberDeclarationSyntax, NameSyntax, QualifiedNameSyntax, IdentifierNameSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpDeclaredSymbolInfoFactoryService() { } private static ImmutableArray<string> GetInheritanceNames(StringTable stringTable, BaseListSyntax baseList) { if (baseList == null) { return ImmutableArray<string>.Empty; } var builder = ArrayBuilder<string>.GetInstance(baseList.Types.Count); // It's not sufficient to just store the textual names we see in the inheritance list // of a type. For example if we have: // // using Y = X; // ... // using Z = Y; // ... // class C : Z // // It's insufficient to just state that 'C' derives from 'Z'. If we search for derived // types from 'B' we won't examine 'C'. To solve this, we keep track of the aliasing // that occurs in containing scopes. Then, when we're adding an inheritance name we // walk the alias maps and we also add any names that these names alias to. In the // above example we'd put Z, Y, and X in the inheritance names list for 'C'. // Each dictionary in this list is a mapping from alias name to the name of the thing // it aliases. Then, each scope with alias mapping gets its own entry in this list. // For the above example, we would produce: [{Z => Y}, {Y => X}] var aliasMaps = AllocateAliasMapList(); try { AddAliasMaps(baseList, aliasMaps); foreach (var baseType in baseList.Types) { AddInheritanceName(builder, baseType.Type, aliasMaps); } Intern(stringTable, builder); return builder.ToImmutableAndFree(); } finally { FreeAliasMapList(aliasMaps); } } private static void AddAliasMaps(SyntaxNode node, List<Dictionary<string, string>> aliasMaps) { for (var current = node; current != null; current = current.Parent) { if (current is BaseNamespaceDeclarationSyntax nsDecl) { ProcessUsings(aliasMaps, nsDecl.Usings); } else if (current.IsKind(SyntaxKind.CompilationUnit, out CompilationUnitSyntax compilationUnit)) { ProcessUsings(aliasMaps, compilationUnit.Usings); } } } private static void ProcessUsings(List<Dictionary<string, string>> aliasMaps, SyntaxList<UsingDirectiveSyntax> usings) { Dictionary<string, string> aliasMap = null; foreach (var usingDecl in usings) { if (usingDecl.Alias != null) { var mappedName = GetTypeName(usingDecl.Name); if (mappedName != null) { aliasMap ??= AllocateAliasMap(); // If we have: using X = Goo, then we store a mapping from X -> Goo // here. That way if we see a class that inherits from X we also state // that it inherits from Goo as well. aliasMap[usingDecl.Alias.Name.Identifier.ValueText] = mappedName; } } } if (aliasMap != null) { aliasMaps.Add(aliasMap); } } private static void AddInheritanceName( ArrayBuilder<string> builder, TypeSyntax type, List<Dictionary<string, string>> aliasMaps) { var name = GetTypeName(type); if (name != null) { // First, add the name that the typename that the type directly says it inherits from. builder.Add(name); // Now, walk the alias chain and add any names this alias may eventually map to. var currentName = name; foreach (var aliasMap in aliasMaps) { if (aliasMap.TryGetValue(currentName, out var mappedName)) { // Looks like this could be an alias. Also include the name the alias points to builder.Add(mappedName); // Keep on searching. An alias in an inner namespcae can refer to an // alias in an outer namespace. currentName = mappedName; } } } } protected override void AddDeclaredSymbolInfosWorker( SyntaxNode container, MemberDeclarationSyntax node, StringTable stringTable, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, string> aliases, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, string containerDisplayName, string fullyQualifiedContainerName, CancellationToken cancellationToken) { // If this is a part of partial type that only contains nested types, then we don't make an info type for // it. That's because we effectively think of this as just being a virtual container just to hold the nested // types, and not something someone would want to explicitly navigate to itself. Similar to how we think of // namespaces. if (node is TypeDeclarationSyntax typeDeclaration && typeDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword) && typeDeclaration.Members.Any() && typeDeclaration.Members.All(m => m is BaseTypeDeclarationSyntax)) { return; } switch (node.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: var typeDecl = (TypeDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, typeDecl.Identifier.ValueText, GetTypeParameterSuffix(typeDecl.TypeParameterList), containerDisplayName, fullyQualifiedContainerName, typeDecl.Modifiers.Any(SyntaxKind.PartialKeyword), node.Kind() switch { SyntaxKind.ClassDeclaration => DeclaredSymbolInfoKind.Class, SyntaxKind.RecordDeclaration => DeclaredSymbolInfoKind.Record, SyntaxKind.InterfaceDeclaration => DeclaredSymbolInfoKind.Interface, SyntaxKind.StructDeclaration => DeclaredSymbolInfoKind.Struct, SyntaxKind.RecordStructDeclaration => DeclaredSymbolInfoKind.RecordStruct, _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()), }, GetAccessibility(container, typeDecl.Modifiers), typeDecl.Identifier.Span, GetInheritanceNames(stringTable, typeDecl.BaseList), IsNestedType(typeDecl))); return; case SyntaxKind.EnumDeclaration: var enumDecl = (EnumDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, enumDecl.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, enumDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Enum, GetAccessibility(container, enumDecl.Modifiers), enumDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, isNestedType: IsNestedType(enumDecl))); return; case SyntaxKind.ConstructorDeclaration: var ctorDecl = (ConstructorDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, ctorDecl.Identifier.ValueText, GetConstructorSuffix(ctorDecl), containerDisplayName, fullyQualifiedContainerName, ctorDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Constructor, GetAccessibility(container, ctorDecl.Modifiers), ctorDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, parameterCount: ctorDecl.ParameterList?.Parameters.Count ?? 0)); return; case SyntaxKind.DelegateDeclaration: var delegateDecl = (DelegateDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, delegateDecl.Identifier.ValueText, GetTypeParameterSuffix(delegateDecl.TypeParameterList), containerDisplayName, fullyQualifiedContainerName, delegateDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Delegate, GetAccessibility(container, delegateDecl.Modifiers), delegateDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.EnumMemberDeclaration: var enumMember = (EnumMemberDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, enumMember.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, enumMember.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.EnumMember, Accessibility.Public, enumMember.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.EventDeclaration: var eventDecl = (EventDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, eventDecl.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, eventDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Event, GetAccessibility(container, eventDecl.Modifiers), eventDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.IndexerDeclaration: var indexerDecl = (IndexerDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, "this", GetIndexerSuffix(indexerDecl), containerDisplayName, fullyQualifiedContainerName, indexerDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Indexer, GetAccessibility(container, indexerDecl.Modifiers), indexerDecl.ThisKeyword.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)node; var isExtensionMethod = IsExtensionMethod(method); declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, method.Identifier.ValueText, GetMethodSuffix(method), containerDisplayName, fullyQualifiedContainerName, method.Modifiers.Any(SyntaxKind.PartialKeyword), isExtensionMethod ? DeclaredSymbolInfoKind.ExtensionMethod : DeclaredSymbolInfoKind.Method, GetAccessibility(container, method.Modifiers), method.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, parameterCount: method.ParameterList?.Parameters.Count ?? 0, typeParameterCount: method.TypeParameterList?.Parameters.Count ?? 0)); if (isExtensionMethod) AddExtensionMethodInfo(method, aliases, declaredSymbolInfos.Count - 1, extensionMethodInfo); return; case SyntaxKind.PropertyDeclaration: var property = (PropertyDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, property.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, property.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Property, GetAccessibility(container, property.Modifiers), property.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: var fieldDeclaration = (BaseFieldDeclarationSyntax)node; foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables) { var kind = fieldDeclaration is EventFieldDeclarationSyntax ? DeclaredSymbolInfoKind.Event : fieldDeclaration.Modifiers.Any(m => m.Kind() == SyntaxKind.ConstKeyword) ? DeclaredSymbolInfoKind.Constant : DeclaredSymbolInfoKind.Field; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, variableDeclarator.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, fieldDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword), kind, GetAccessibility(container, fieldDeclaration.Modifiers), variableDeclarator.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); } return; } } protected override SyntaxList<MemberDeclarationSyntax> GetChildren(CompilationUnitSyntax node) => node.Members; protected override SyntaxList<MemberDeclarationSyntax> GetChildren(BaseNamespaceDeclarationSyntax node) => node.Members; protected override SyntaxList<MemberDeclarationSyntax> GetChildren(TypeDeclarationSyntax node) => node.Members; protected override IEnumerable<MemberDeclarationSyntax> GetChildren(EnumDeclarationSyntax node) => node.Members; protected override SyntaxList<UsingDirectiveSyntax> GetUsingAliases(CompilationUnitSyntax node) => node.Usings; protected override SyntaxList<UsingDirectiveSyntax> GetUsingAliases(BaseNamespaceDeclarationSyntax node) => node.Usings; protected override NameSyntax GetName(BaseNamespaceDeclarationSyntax node) => node.Name; protected override NameSyntax GetLeft(QualifiedNameSyntax node) => node.Left; protected override NameSyntax GetRight(QualifiedNameSyntax node) => node.Right; protected override SyntaxToken GetIdentifier(IdentifierNameSyntax node) => node.Identifier; private static bool IsNestedType(BaseTypeDeclarationSyntax typeDecl) => typeDecl.Parent is BaseTypeDeclarationSyntax; private static string GetConstructorSuffix(ConstructorDeclarationSyntax constructor) => constructor.Modifiers.Any(SyntaxKind.StaticKeyword) ? ".static " + constructor.Identifier + "()" : GetSuffix('(', ')', constructor.ParameterList.Parameters); private static string GetMethodSuffix(MethodDeclarationSyntax method) => GetTypeParameterSuffix(method.TypeParameterList) + GetSuffix('(', ')', method.ParameterList.Parameters); private static string GetIndexerSuffix(IndexerDeclarationSyntax indexer) => GetSuffix('[', ']', indexer.ParameterList.Parameters); private static string GetTypeParameterSuffix(TypeParameterListSyntax typeParameterList) { if (typeParameterList == null) { return null; } var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append('<'); var first = true; foreach (var parameter in typeParameterList.Parameters) { if (!first) { builder.Append(", "); } builder.Append(parameter.Identifier.Text); first = false; } builder.Append('>'); return pooledBuilder.ToStringAndFree(); } /// <summary> /// Builds up the suffix to show for something with parameters in navigate-to. /// While it would be nice to just use the compiler SymbolDisplay API for this, /// it would be too expensive as it requires going back to Symbols (which requires /// creating compilations, etc.) in a perf sensitive area. /// /// So, instead, we just build a reasonable suffix using the pure syntax that a /// user provided. That means that if they wrote "Method(System.Int32 i)" we'll /// show that as "Method(System.Int32)" not "Method(int)". Given that this is /// actually what the user wrote, and it saves us from ever having to go back to /// symbols/compilations, this is well worth it, even if it does mean we have to /// create our own 'symbol display' logic here. /// </summary> private static string GetSuffix( char openBrace, char closeBrace, SeparatedSyntaxList<ParameterSyntax> parameters) { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append(openBrace); AppendParameters(parameters, builder); builder.Append(closeBrace); return pooledBuilder.ToStringAndFree(); } private static void AppendParameters(SeparatedSyntaxList<ParameterSyntax> parameters, StringBuilder builder) { var first = true; foreach (var parameter in parameters) { if (!first) { builder.Append(", "); } foreach (var modifier in parameter.Modifiers) { builder.Append(modifier.Text); builder.Append(' '); } if (parameter.Type != null) { AppendTokens(parameter.Type, builder); } else { builder.Append(parameter.Identifier.Text); } first = false; } } protected override string GetContainerDisplayName(MemberDeclarationSyntax node) => CSharpSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeTypeParameters); protected override string GetFullyQualifiedContainerName(MemberDeclarationSyntax node, string rootNamespace) => CSharpSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeNamespaces); private static Accessibility GetAccessibility(SyntaxNode container, SyntaxTokenList modifiers) { var sawInternal = false; foreach (var modifier in modifiers) { switch (modifier.Kind()) { case SyntaxKind.PublicKeyword: return Accessibility.Public; case SyntaxKind.PrivateKeyword: return Accessibility.Private; case SyntaxKind.ProtectedKeyword: return Accessibility.Protected; case SyntaxKind.InternalKeyword: sawInternal = true; continue; } } if (sawInternal) return Accessibility.Internal; // No accessibility modifiers: switch (container.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: // Anything without modifiers is private if it's in a class/struct declaration. return Accessibility.Private; case SyntaxKind.InterfaceDeclaration: // Anything without modifiers is public if it's in an interface declaration. return Accessibility.Public; case SyntaxKind.CompilationUnit: // Things are private by default in script if (((CSharpParseOptions)container.SyntaxTree.Options).Kind == SourceCodeKind.Script) return Accessibility.Private; return Accessibility.Internal; default: // Otherwise it's internal return Accessibility.Internal; } } private static string GetTypeName(TypeSyntax type) { if (type is SimpleNameSyntax simpleName) { return GetSimpleTypeName(simpleName); } else if (type is QualifiedNameSyntax qualifiedName) { return GetSimpleTypeName(qualifiedName.Right); } else if (type is AliasQualifiedNameSyntax aliasName) { return GetSimpleTypeName(aliasName.Name); } return null; } private static string GetSimpleTypeName(SimpleNameSyntax name) => name.Identifier.ValueText; private static bool IsExtensionMethod(MethodDeclarationSyntax method) => method.ParameterList.Parameters.Count > 0 && method.ParameterList.Parameters[0].Modifiers.Any(SyntaxKind.ThisKeyword); // Root namespace is a VB only concept, which basically means root namespace is always global in C#. protected override string GetRootNamespace(CompilationOptions compilationOptions) => string.Empty; protected override bool TryGetAliasesFromUsingDirective( UsingDirectiveSyntax usingDirectiveNode, out ImmutableArray<(string aliasName, string name)> aliases) { if (usingDirectiveNode.Alias != null) { if (TryGetSimpleTypeName(usingDirectiveNode.Alias.Name, typeParameterNames: null, out var aliasName, out _) && TryGetSimpleTypeName(usingDirectiveNode.Name, typeParameterNames: null, out var name, out _)) { aliases = ImmutableArray.Create<(string, string)>((aliasName, name)); return true; } } aliases = default; return false; } protected override string GetReceiverTypeName(MemberDeclarationSyntax node) { var methodDeclaration = (MethodDeclarationSyntax)node; Debug.Assert(IsExtensionMethod(methodDeclaration)); var typeParameterNames = methodDeclaration.TypeParameterList?.Parameters.SelectAsArray(p => p.Identifier.Text); TryGetSimpleTypeName(methodDeclaration.ParameterList.Parameters[0].Type, typeParameterNames, out var targetTypeName, out var isArray); return CreateReceiverTypeString(targetTypeName, isArray); } private static bool TryGetSimpleTypeName(SyntaxNode node, ImmutableArray<string>? typeParameterNames, out string simpleTypeName, out bool isArray) { isArray = false; if (node is TypeSyntax typeNode) { switch (typeNode) { case IdentifierNameSyntax identifierNameNode: // We consider it a complex method if the receiver type is a type parameter. var text = identifierNameNode.Identifier.Text; simpleTypeName = typeParameterNames?.Contains(text) == true ? null : text; return simpleTypeName != null; case ArrayTypeSyntax arrayTypeNode: isArray = true; return TryGetSimpleTypeName(arrayTypeNode.ElementType, typeParameterNames, out simpleTypeName, out _); case GenericNameSyntax genericNameNode: var name = genericNameNode.Identifier.Text; var arity = genericNameNode.Arity; simpleTypeName = arity == 0 ? name : name + ArityUtilities.GetMetadataAritySuffix(arity); return true; case PredefinedTypeSyntax predefinedTypeNode: simpleTypeName = GetSpecialTypeName(predefinedTypeNode); return simpleTypeName != null; case AliasQualifiedNameSyntax aliasQualifiedNameNode: return TryGetSimpleTypeName(aliasQualifiedNameNode.Name, typeParameterNames, out simpleTypeName, out _); case QualifiedNameSyntax qualifiedNameNode: // For an identifier to the right of a '.', it can't be a type parameter, // so we don't need to check for it further. return TryGetSimpleTypeName(qualifiedNameNode.Right, typeParameterNames: null, out simpleTypeName, out _); case NullableTypeSyntax nullableNode: // Ignore nullability, becase nullable reference type might not be enabled universally. // In the worst case we just include more methods to check in out filter. return TryGetSimpleTypeName(nullableNode.ElementType, typeParameterNames, out simpleTypeName, out isArray); case TupleTypeSyntax tupleType: simpleTypeName = CreateValueTupleTypeString(tupleType.Elements.Count); return true; } } simpleTypeName = null; return false; } private static string GetSpecialTypeName(PredefinedTypeSyntax predefinedTypeNode) { var kind = predefinedTypeNode.Keyword.Kind(); return kind switch { SyntaxKind.BoolKeyword => "Boolean", SyntaxKind.ByteKeyword => "Byte", SyntaxKind.SByteKeyword => "SByte", SyntaxKind.ShortKeyword => "Int16", SyntaxKind.UShortKeyword => "UInt16", SyntaxKind.IntKeyword => "Int32", SyntaxKind.UIntKeyword => "UInt32", SyntaxKind.LongKeyword => "Int64", SyntaxKind.ULongKeyword => "UInt64", SyntaxKind.DoubleKeyword => "Double", SyntaxKind.FloatKeyword => "Single", SyntaxKind.DecimalKeyword => "Decimal", SyntaxKind.StringKeyword => "String", SyntaxKind.CharKeyword => "Char", SyntaxKind.ObjectKeyword => "Object", _ => null, }; } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Workspaces/Core/MSBuild/MSBuild/MSBuildProjectLoader.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.Build.Framework; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.MSBuild.Build; using Roslyn.Utilities; using MSB = Microsoft.Build; namespace Microsoft.CodeAnalysis.MSBuild { /// <summary> /// An API for loading msbuild project files. /// </summary> public partial class MSBuildProjectLoader { // the workspace that the projects and solutions are intended to be loaded into. private readonly HostWorkspaceServices _workspaceServices; private readonly DiagnosticReporter _diagnosticReporter; private readonly PathResolver _pathResolver; private readonly ProjectFileLoaderRegistry _projectFileLoaderRegistry; // used to protect access to the following mutable state private readonly NonReentrantLock _dataGuard = new(); internal MSBuildProjectLoader( HostWorkspaceServices workspaceServices, DiagnosticReporter diagnosticReporter, ProjectFileLoaderRegistry? projectFileLoaderRegistry, ImmutableDictionary<string, string>? properties) { _workspaceServices = workspaceServices; _diagnosticReporter = diagnosticReporter; _pathResolver = new PathResolver(_diagnosticReporter); _projectFileLoaderRegistry = projectFileLoaderRegistry ?? new ProjectFileLoaderRegistry(workspaceServices, _diagnosticReporter); Properties = ImmutableDictionary.Create<string, string>(StringComparer.OrdinalIgnoreCase); if (properties != null) { Properties = Properties.AddRange(properties); } } /// <summary> /// Create a new instance of an <see cref="MSBuildProjectLoader"/>. /// </summary> /// <param name="workspace">The workspace whose services this <see cref="MSBuildProjectLoader"/> should use.</param> /// <param name="properties">An optional dictionary of additional MSBuild properties and values to use when loading projects. /// These are the same properties that are passed to msbuild via the /property:&lt;n&gt;=&lt;v&gt; command line argument.</param> public MSBuildProjectLoader(Workspace workspace, ImmutableDictionary<string, string>? properties = null) : this(workspace.Services, new DiagnosticReporter(workspace), projectFileLoaderRegistry: null, properties) { } /// <summary> /// The MSBuild properties used when interpreting project files. /// These are the same properties that are passed to msbuild via the /property:&lt;n&gt;=&lt;v&gt; command line argument. /// </summary> public ImmutableDictionary<string, string> Properties { get; private set; } /// <summary> /// Determines if metadata from existing output assemblies is loaded instead of opening referenced projects. /// If the referenced project is already opened, the metadata will not be loaded. /// If the metadata assembly cannot be found the referenced project will be opened instead. /// </summary> public bool LoadMetadataForReferencedProjects { get; set; } = false; /// <summary> /// Determines if unrecognized projects are skipped when solutions or projects are opened. /// /// A project is unrecognized if it either has /// a) an invalid file path, /// b) a non-existent project file, /// c) has an unrecognized file extension or /// d) a file extension associated with an unsupported language. /// /// If unrecognized projects cannot be skipped a corresponding exception is thrown. /// </summary> public bool SkipUnrecognizedProjects { get; set; } = true; /// <summary> /// Associates a project file extension with a language name. /// </summary> /// <param name="projectFileExtension">The project file extension to associate with <paramref name="language"/>.</param> /// <param name="language">The language to associate with <paramref name="projectFileExtension"/>. This value /// should typically be taken from <see cref="LanguageNames"/>.</param> public void AssociateFileExtensionWithLanguage(string projectFileExtension, string language) { if (projectFileExtension == null) { throw new ArgumentNullException(nameof(projectFileExtension)); } if (language == null) { throw new ArgumentNullException(nameof(language)); } _projectFileLoaderRegistry.AssociateFileExtensionWithLanguage(projectFileExtension, language); } private void SetSolutionProperties(string? solutionFilePath) { const string SolutionDirProperty = "SolutionDir"; // When MSBuild is building an individual project, it doesn't define $(SolutionDir). // However when building an .sln file, or when working inside Visual Studio, // $(SolutionDir) is defined to be the directory where the .sln file is located. // Some projects out there rely on $(SolutionDir) being set (although the best practice is to // use MSBuildProjectDirectory which is always defined). if (!RoslynString.IsNullOrEmpty(solutionFilePath)) { var solutionDirectory = PathUtilities.GetDirectoryName(solutionFilePath) + PathUtilities.DirectorySeparatorChar; if (Directory.Exists(solutionDirectory)) { Properties = Properties.SetItem(SolutionDirProperty, solutionDirectory); } } } private DiagnosticReportingMode GetReportingModeForUnrecognizedProjects() => this.SkipUnrecognizedProjects ? DiagnosticReportingMode.Log : DiagnosticReportingMode.Throw; /// <summary> /// Loads the <see cref="SolutionInfo"/> for the specified solution file, including all projects referenced by the solution file and /// all the projects referenced by the project files. /// </summary> /// <param name="solutionFilePath">The path to the solution file to be loaded. This may be an absolute path or a path relative to the /// current working directory.</param> /// <param name="progress">An optional <see cref="IProgress{T}"/> that will receive updates as the solution is loaded.</param> /// <param name="msbuildLogger">An optional <see cref="ILogger"/> that will log msbuild results.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> to allow cancellation of this operation.</param> public async Task<SolutionInfo> LoadSolutionInfoAsync( string solutionFilePath, IProgress<ProjectLoadProgress>? progress = null, ILogger? msbuildLogger = null, CancellationToken cancellationToken = default) { if (solutionFilePath == null) { throw new ArgumentNullException(nameof(solutionFilePath)); } if (!_pathResolver.TryGetAbsoluteSolutionPath(solutionFilePath, baseDirectory: Directory.GetCurrentDirectory(), DiagnosticReportingMode.Throw, out var absoluteSolutionPath)) { // TryGetAbsoluteSolutionPath should throw before we get here. return null!; } var projectfilter = ImmutableHashSet<string>.Empty; if (SolutionFilterReader.IsSolutionFilterFilename(absoluteSolutionPath) && !SolutionFilterReader.TryRead(absoluteSolutionPath, _pathResolver, out absoluteSolutionPath, out projectfilter)) { throw new Exception(string.Format(WorkspaceMSBuildResources.Failed_to_load_solution_filter_0, solutionFilePath)); } using (_dataGuard.DisposableWait(cancellationToken)) { this.SetSolutionProperties(absoluteSolutionPath); } var solutionFile = MSB.Construction.SolutionFile.Parse(absoluteSolutionPath); var reportingMode = GetReportingModeForUnrecognizedProjects(); var reportingOptions = new DiagnosticReportingOptions( onPathFailure: reportingMode, onLoaderFailure: reportingMode); var projectPaths = ImmutableArray.CreateBuilder<string>(); // load all the projects foreach (var project in solutionFile.ProjectsInOrder) { cancellationToken.ThrowIfCancellationRequested(); if (project.ProjectType == MSB.Construction.SolutionProjectType.SolutionFolder) { continue; } // Load project if we have an empty project filter and the project path is present. if (projectfilter.IsEmpty || projectfilter.Contains(project.AbsolutePath)) { projectPaths.Add(project.RelativePath); } } var buildManager = new ProjectBuildManager(Properties, msbuildLogger); var worker = new Worker( _workspaceServices, _diagnosticReporter, _pathResolver, _projectFileLoaderRegistry, buildManager, projectPaths.ToImmutable(), // TryGetAbsoluteSolutionPath should not return an invalid path baseDirectory: Path.GetDirectoryName(absoluteSolutionPath)!, Properties, projectMap: null, progress, requestedProjectOptions: reportingOptions, discoveredProjectOptions: reportingOptions, preferMetadataForReferencesOfDiscoveredProjects: false); var projects = await worker.LoadAsync(cancellationToken).ConfigureAwait(false); // construct workspace from loaded project infos return SolutionInfo.Create( SolutionId.CreateNewId(debugName: absoluteSolutionPath), version: default, absoluteSolutionPath, projects); } /// <summary> /// Loads the <see cref="ProjectInfo"/> from the specified project file and all referenced projects. /// The first <see cref="ProjectInfo"/> in the result corresponds to the specified project file. /// </summary> /// <param name="projectFilePath">The path to the project file to be loaded. This may be an absolute path or a path relative to the /// current working directory.</param> /// <param name="projectMap">An optional <see cref="ProjectMap"/> that will be used to resolve project references to existing projects. /// This is useful when populating a custom <see cref="Workspace"/>.</param> /// <param name="progress">An optional <see cref="IProgress{T}"/> that will receive updates as the project is loaded.</param> /// <param name="msbuildLogger">An optional <see cref="ILogger"/> that will log msbuild results.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> to allow cancellation of this operation.</param> public async Task<ImmutableArray<ProjectInfo>> LoadProjectInfoAsync( string projectFilePath, ProjectMap? projectMap = null, IProgress<ProjectLoadProgress>? progress = null, ILogger? msbuildLogger = null, CancellationToken cancellationToken = default) { if (projectFilePath == null) { throw new ArgumentNullException(nameof(projectFilePath)); } var requestedProjectOptions = DiagnosticReportingOptions.ThrowForAll; var reportingMode = GetReportingModeForUnrecognizedProjects(); var discoveredProjectOptions = new DiagnosticReportingOptions( onPathFailure: reportingMode, onLoaderFailure: reportingMode); var buildManager = new ProjectBuildManager(Properties, msbuildLogger); var worker = new Worker( _workspaceServices, _diagnosticReporter, _pathResolver, _projectFileLoaderRegistry, buildManager, requestedProjectPaths: ImmutableArray.Create(projectFilePath), baseDirectory: Directory.GetCurrentDirectory(), globalProperties: Properties, projectMap, progress, requestedProjectOptions, discoveredProjectOptions, this.LoadMetadataForReferencedProjects); return await worker.LoadAsync(cancellationToken).ConfigureAwait(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.Build.Framework; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.MSBuild.Build; using Roslyn.Utilities; using MSB = Microsoft.Build; namespace Microsoft.CodeAnalysis.MSBuild { /// <summary> /// An API for loading msbuild project files. /// </summary> public partial class MSBuildProjectLoader { // the workspace that the projects and solutions are intended to be loaded into. private readonly HostWorkspaceServices _workspaceServices; private readonly DiagnosticReporter _diagnosticReporter; private readonly PathResolver _pathResolver; private readonly ProjectFileLoaderRegistry _projectFileLoaderRegistry; // used to protect access to the following mutable state private readonly NonReentrantLock _dataGuard = new(); internal MSBuildProjectLoader( HostWorkspaceServices workspaceServices, DiagnosticReporter diagnosticReporter, ProjectFileLoaderRegistry? projectFileLoaderRegistry, ImmutableDictionary<string, string>? properties) { _workspaceServices = workspaceServices; _diagnosticReporter = diagnosticReporter; _pathResolver = new PathResolver(_diagnosticReporter); _projectFileLoaderRegistry = projectFileLoaderRegistry ?? new ProjectFileLoaderRegistry(workspaceServices, _diagnosticReporter); Properties = ImmutableDictionary.Create<string, string>(StringComparer.OrdinalIgnoreCase); if (properties != null) { Properties = Properties.AddRange(properties); } } /// <summary> /// Create a new instance of an <see cref="MSBuildProjectLoader"/>. /// </summary> /// <param name="workspace">The workspace whose services this <see cref="MSBuildProjectLoader"/> should use.</param> /// <param name="properties">An optional dictionary of additional MSBuild properties and values to use when loading projects. /// These are the same properties that are passed to msbuild via the /property:&lt;n&gt;=&lt;v&gt; command line argument.</param> public MSBuildProjectLoader(Workspace workspace, ImmutableDictionary<string, string>? properties = null) : this(workspace.Services, new DiagnosticReporter(workspace), projectFileLoaderRegistry: null, properties) { } /// <summary> /// The MSBuild properties used when interpreting project files. /// These are the same properties that are passed to msbuild via the /property:&lt;n&gt;=&lt;v&gt; command line argument. /// </summary> public ImmutableDictionary<string, string> Properties { get; private set; } /// <summary> /// Determines if metadata from existing output assemblies is loaded instead of opening referenced projects. /// If the referenced project is already opened, the metadata will not be loaded. /// If the metadata assembly cannot be found the referenced project will be opened instead. /// </summary> public bool LoadMetadataForReferencedProjects { get; set; } = false; /// <summary> /// Determines if unrecognized projects are skipped when solutions or projects are opened. /// /// A project is unrecognized if it either has /// a) an invalid file path, /// b) a non-existent project file, /// c) has an unrecognized file extension or /// d) a file extension associated with an unsupported language. /// /// If unrecognized projects cannot be skipped a corresponding exception is thrown. /// </summary> public bool SkipUnrecognizedProjects { get; set; } = true; /// <summary> /// Associates a project file extension with a language name. /// </summary> /// <param name="projectFileExtension">The project file extension to associate with <paramref name="language"/>.</param> /// <param name="language">The language to associate with <paramref name="projectFileExtension"/>. This value /// should typically be taken from <see cref="LanguageNames"/>.</param> public void AssociateFileExtensionWithLanguage(string projectFileExtension, string language) { if (projectFileExtension == null) { throw new ArgumentNullException(nameof(projectFileExtension)); } if (language == null) { throw new ArgumentNullException(nameof(language)); } _projectFileLoaderRegistry.AssociateFileExtensionWithLanguage(projectFileExtension, language); } private void SetSolutionProperties(string? solutionFilePath) { const string SolutionDirProperty = "SolutionDir"; // When MSBuild is building an individual project, it doesn't define $(SolutionDir). // However when building an .sln file, or when working inside Visual Studio, // $(SolutionDir) is defined to be the directory where the .sln file is located. // Some projects out there rely on $(SolutionDir) being set (although the best practice is to // use MSBuildProjectDirectory which is always defined). if (!RoslynString.IsNullOrEmpty(solutionFilePath)) { var solutionDirectory = PathUtilities.GetDirectoryName(solutionFilePath) + PathUtilities.DirectorySeparatorChar; if (Directory.Exists(solutionDirectory)) { Properties = Properties.SetItem(SolutionDirProperty, solutionDirectory); } } } private DiagnosticReportingMode GetReportingModeForUnrecognizedProjects() => this.SkipUnrecognizedProjects ? DiagnosticReportingMode.Log : DiagnosticReportingMode.Throw; /// <summary> /// Loads the <see cref="SolutionInfo"/> for the specified solution file, including all projects referenced by the solution file and /// all the projects referenced by the project files. /// </summary> /// <param name="solutionFilePath">The path to the solution file to be loaded. This may be an absolute path or a path relative to the /// current working directory.</param> /// <param name="progress">An optional <see cref="IProgress{T}"/> that will receive updates as the solution is loaded.</param> /// <param name="msbuildLogger">An optional <see cref="ILogger"/> that will log msbuild results.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> to allow cancellation of this operation.</param> public async Task<SolutionInfo> LoadSolutionInfoAsync( string solutionFilePath, IProgress<ProjectLoadProgress>? progress = null, ILogger? msbuildLogger = null, CancellationToken cancellationToken = default) { if (solutionFilePath == null) { throw new ArgumentNullException(nameof(solutionFilePath)); } if (!_pathResolver.TryGetAbsoluteSolutionPath(solutionFilePath, baseDirectory: Directory.GetCurrentDirectory(), DiagnosticReportingMode.Throw, out var absoluteSolutionPath)) { // TryGetAbsoluteSolutionPath should throw before we get here. return null!; } var projectfilter = ImmutableHashSet<string>.Empty; if (SolutionFilterReader.IsSolutionFilterFilename(absoluteSolutionPath) && !SolutionFilterReader.TryRead(absoluteSolutionPath, _pathResolver, out absoluteSolutionPath, out projectfilter)) { throw new Exception(string.Format(WorkspaceMSBuildResources.Failed_to_load_solution_filter_0, solutionFilePath)); } using (_dataGuard.DisposableWait(cancellationToken)) { this.SetSolutionProperties(absoluteSolutionPath); } var solutionFile = MSB.Construction.SolutionFile.Parse(absoluteSolutionPath); var reportingMode = GetReportingModeForUnrecognizedProjects(); var reportingOptions = new DiagnosticReportingOptions( onPathFailure: reportingMode, onLoaderFailure: reportingMode); var projectPaths = ImmutableArray.CreateBuilder<string>(); // load all the projects foreach (var project in solutionFile.ProjectsInOrder) { cancellationToken.ThrowIfCancellationRequested(); if (project.ProjectType == MSB.Construction.SolutionProjectType.SolutionFolder) { continue; } // Load project if we have an empty project filter and the project path is present. if (projectfilter.IsEmpty || projectfilter.Contains(project.AbsolutePath)) { projectPaths.Add(project.RelativePath); } } var buildManager = new ProjectBuildManager(Properties, msbuildLogger); var worker = new Worker( _workspaceServices, _diagnosticReporter, _pathResolver, _projectFileLoaderRegistry, buildManager, projectPaths.ToImmutable(), // TryGetAbsoluteSolutionPath should not return an invalid path baseDirectory: Path.GetDirectoryName(absoluteSolutionPath)!, Properties, projectMap: null, progress, requestedProjectOptions: reportingOptions, discoveredProjectOptions: reportingOptions, preferMetadataForReferencesOfDiscoveredProjects: false); var projects = await worker.LoadAsync(cancellationToken).ConfigureAwait(false); // construct workspace from loaded project infos return SolutionInfo.Create( SolutionId.CreateNewId(debugName: absoluteSolutionPath), version: default, absoluteSolutionPath, projects); } /// <summary> /// Loads the <see cref="ProjectInfo"/> from the specified project file and all referenced projects. /// The first <see cref="ProjectInfo"/> in the result corresponds to the specified project file. /// </summary> /// <param name="projectFilePath">The path to the project file to be loaded. This may be an absolute path or a path relative to the /// current working directory.</param> /// <param name="projectMap">An optional <see cref="ProjectMap"/> that will be used to resolve project references to existing projects. /// This is useful when populating a custom <see cref="Workspace"/>.</param> /// <param name="progress">An optional <see cref="IProgress{T}"/> that will receive updates as the project is loaded.</param> /// <param name="msbuildLogger">An optional <see cref="ILogger"/> that will log msbuild results.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> to allow cancellation of this operation.</param> public async Task<ImmutableArray<ProjectInfo>> LoadProjectInfoAsync( string projectFilePath, ProjectMap? projectMap = null, IProgress<ProjectLoadProgress>? progress = null, ILogger? msbuildLogger = null, CancellationToken cancellationToken = default) { if (projectFilePath == null) { throw new ArgumentNullException(nameof(projectFilePath)); } var requestedProjectOptions = DiagnosticReportingOptions.ThrowForAll; var reportingMode = GetReportingModeForUnrecognizedProjects(); var discoveredProjectOptions = new DiagnosticReportingOptions( onPathFailure: reportingMode, onLoaderFailure: reportingMode); var buildManager = new ProjectBuildManager(Properties, msbuildLogger); var worker = new Worker( _workspaceServices, _diagnosticReporter, _pathResolver, _projectFileLoaderRegistry, buildManager, requestedProjectPaths: ImmutableArray.Create(projectFilePath), baseDirectory: Directory.GetCurrentDirectory(), globalProperties: Properties, projectMap, progress, requestedProjectOptions, discoveredProjectOptions, this.LoadMetadataForReferencedProjects); return await worker.LoadAsync(cancellationToken).ConfigureAwait(false); } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Analyzers/CSharp/Tests/UseCollectionInitializer/UseCollectionInitializerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.UseCollectionInitializer; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseCollectionInitializer { public partial class UseCollectionInitializerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseCollectionInitializerTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseCollectionInitializerDiagnosticAnalyzer(), new CSharpUseCollectionInitializerCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestOnVariableDeclarator() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(1); } }", @"using System.Collections.Generic; class C { void M() { var c = new List<int> { 1 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestIndexAccess1() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c[1] = 2; } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { [1] = 2 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestIndexAccess1_NotInCSharp5() { await TestMissingAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c[1] = 2; } }", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestComplexIndexAccess1() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { a.b.c = [||]new List<int>(); a.b.c[1] = 2; } }", @" using System.Collections.Generic; class C { void M() { a.b.c = new List<int> { [1] = 2 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestIndexAccess2() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c[1] = 2; c[2] = """"; } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { [1] = 2, [2] = """" }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestIndexAccess3() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c[1] = 2; c[2] = """"; c[3, 4] = 5; } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { [1] = 2, [2] = """", [3, 4] = 5 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestIndexFollowedByInvocation() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c[1] = 2; c.Add(0); } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { [1] = 2 }; c.Add(0); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestInvocationFollowedByIndex() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(0); c[1] = 2; } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { 0 }; c[1] = 2; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestWithInterimStatement() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(1); c.Add(2); throw new Exception(); c.Add(3); c.Add(4); } }", @"using System.Collections.Generic; class C { void M() { var c = new List<int> { 1, 2 }; throw new Exception(); c.Add(3); c.Add(4); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingBeforeCSharp3() { await TestMissingAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(1); } }", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp2))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingOnNonIEnumerable() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new C(); c.Add(1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingOnNonIEnumerableEvenWithAdd() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new C(); c.Add(1); } public void Add(int i) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestWithCreationArguments() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(1); c.Add(1); } }", @"using System.Collections.Generic; class C { void M() { var c = new List<int>(1) { 1 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestOnAssignmentExpression() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { List<int> c = null; c = [||]new List<int>(); c.Add(1); } }", @"using System.Collections.Generic; class C { void M() { List<int> c = null; c = new List<int> { 1 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingOnRefAdd() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(ref i); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestComplexInitializer() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { List<int>[] array; array[0] = [||]new List<int>(); array[0].Add(1); array[0].Add(2); } }", @"using System.Collections.Generic; class C { void M() { List<int>[] array; array[0] = new List<int> { 1, 2 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestNotOnNamedArg() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(arg: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingWithExistingInitializer() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>() { 1 }; c.Add(1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestFixAllInDocument1() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { List<int>[] array; array[0] = {|FixAllInDocument:new|} List<int>(); array[0].Add(1); array[0].Add(2); array[1] = new List<int>(); array[1].Add(3); array[1].Add(4); } }", @"using System.Collections.Generic; class C { void M() { List<int>[] array; array[0] = new List<int> { 1, 2 }; array[1] = new List<int> { 3, 4 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestFixAllInDocument2() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var list1 = {|FixAllInDocument:new|} List<int>(() => { var list2 = new List<int>(); list2.Add(2); }); list1.Add(1); } }", @"using System.Collections.Generic; class C { void M() { var list1 = new List<int>(() => { var list2 = new List<int> { 2 }; }) { 1 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestFixAllInDocument3() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var list1 = {|FixAllInDocument:new|} List<int>(); list1.Add(() => { var list2 = new List<int>(); list2.Add(2); }); } }", @"using System.Collections.Generic; class C { void M() { var list1 = new List<int> { () => { var list2 = new List<int> { 2 }; } }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestTrivia1() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(1); // Goo c.Add(2); // Bar } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { 1, // Goo 2 // Bar }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestComplexInitializer2() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = new [||]Dictionary<int, string>(); c.Add(1, ""x""); c.Add(2, ""y""); } }", @"using System.Collections.Generic; class C { void M() { var c = new Dictionary<int, string> { { 1, ""x"" }, { 2, ""y"" } }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(16158, "https://github.com/dotnet/roslyn/issues/16158")] public async Task TestIncorrectAddName() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; public class Goo { public static void Bar() { string item = null; var items = new List<string>(); var values = new [||]List<string>(); // Collection initialization can be simplified values.Add(item); values.AddRange(items); } }", @"using System.Collections.Generic; public class Goo { public static void Bar() { string item = null; var items = new List<string>(); var values = new List<string> { item }; // Collection initialization can be simplified values.AddRange(items); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(16241, "https://github.com/dotnet/roslyn/issues/16241")] public async Task TestNestedCollectionInitializer() { await TestMissingInRegularAndScriptAsync( @" using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var myStringArray = new string[] { ""Test"", ""123"", ""ABC"" }; var myStringList = myStringArray?.ToList() ?? new [||]List<string>(); myStringList.Add(""Done""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(17823, "https://github.com/dotnet/roslyn/issues/17823")] public async Task TestMissingWhenReferencedInInitializer() { await TestMissingInRegularAndScriptAsync( @" using System.Collections.Generic; class C { static void M() { var items = new [||]List<object>(); items[0] = items[0]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(17823, "https://github.com/dotnet/roslyn/issues/17823")] public async Task TestWhenReferencedInInitializer_LocalVar() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; class C { static void M() { var items = new [||]List<object>(); items[0] = 1; items[1] = items[0]; } }", @" using System.Collections.Generic; class C { static void M() { var items = new [||]List<object> { [0] = 1 }; items[1] = items[0]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(17823, "https://github.com/dotnet/roslyn/issues/17823")] public async Task TestWhenReferencedInInitializer_LocalVar2() { await TestMissingInRegularAndScriptAsync( @" using System.Collections.Generic; using System.Linq; class C { void M() { var t = [||]new List<int>(new int[] { 1, 2, 3 }); t.Add(t.Min() - 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(18260, "https://github.com/dotnet/roslyn/issues/18260")] public async Task TestWhenReferencedInInitializer_Assignment() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; class C { static void M() { List<object> items = null; items = new [||]List<object>(); items[0] = 1; items[1] = items[0]; } }", @" using System.Collections.Generic; class C { static void M() { List<object> items = null; items = new [||]List<object> { [0] = 1 }; items[1] = items[0]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(18260, "https://github.com/dotnet/roslyn/issues/18260")] public async Task TestWhenReferencedInInitializer_Assignment2() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { List<int> t = null; t = [||]new List<int>(new int[] { 1, 2, 3 }); t.Add(t.Min() - 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(18260, "https://github.com/dotnet/roslyn/issues/18260")] public async Task TestFieldReference() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { private List<int> myField; void M() { myField = [||]new List<int>(); myField.Add(this.myField.Count); } }"); } [WorkItem(17853, "https://github.com/dotnet/roslyn/issues/17853")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingForDynamic() { await TestMissingInRegularAndScriptAsync( @"using System.Dynamic; class C { void Goo() { dynamic body = [||]new ExpandoObject(); body[0] = new ExpandoObject(); } }"); } [WorkItem(17953, "https://github.com/dotnet/roslyn/issues/17953")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingAcrossPreprocessorDirective() { await TestMissingInRegularAndScriptAsync( @" using System.Collections.Generic; public class Goo { public void M() { var items = new [||]List<object>(); #if true items.Add(1); #endif } }"); } [WorkItem(17953, "https://github.com/dotnet/roslyn/issues/17953")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestAvailableInsidePreprocessorDirective() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; public class Goo { public void M() { #if true var items = new [||]List<object>(); items.Add(1); #endif } }", @" using System.Collections.Generic; public class Goo { public void M() { #if true var items = new List<object> { 1 }; #endif } }"); } [WorkItem(18242, "https://github.com/dotnet/roslyn/issues/18242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestObjectInitializerAssignmentAmbiguity() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; public class Goo { public void M() { int lastItem; var list = [||]new List<int>(); list.Add(lastItem = 5); } }", @" using System.Collections.Generic; public class Goo { public void M() { int lastItem; var list = new List<int> { (lastItem = 5) }; } }"); } [WorkItem(18242, "https://github.com/dotnet/roslyn/issues/18242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestObjectInitializerCompoundAssignment() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; public class Goo { public void M() { int lastItem = 0; var list = [||]new List<int>(); list.Add(lastItem += 5); } }", @" using System.Collections.Generic; public class Goo { public void M() { int lastItem = 0; var list = new List<int> { (lastItem += 5) }; } }"); } [WorkItem(19253, "https://github.com/dotnet/roslyn/issues/19253")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestKeepBlankLinesAfter() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; class MyClass { public void Main() { var list = [||]new List<int>(); list.Add(1); int horse = 1; } }", @" using System.Collections.Generic; class MyClass { public void Main() { var list = new List<int> { 1 }; int horse = 1; } }"); } [WorkItem(23672, "https://github.com/dotnet/roslyn/issues/23672")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingWithExplicitImplementedAddMethod() { await TestMissingInRegularAndScriptAsync( @" using System.Collections.Generic; using System.Dynamic; public class Goo { public void M() { IDictionary<string, object> obj = [||]new ExpandoObject(); obj.Add(""string"", ""v""); obj.Add(""int"", 1); obj.Add("" object"", new { X = 1, Y = 2 }); } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.UseCollectionInitializer; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseCollectionInitializer { public partial class UseCollectionInitializerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseCollectionInitializerTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseCollectionInitializerDiagnosticAnalyzer(), new CSharpUseCollectionInitializerCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestOnVariableDeclarator() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(1); } }", @"using System.Collections.Generic; class C { void M() { var c = new List<int> { 1 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestIndexAccess1() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c[1] = 2; } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { [1] = 2 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestIndexAccess1_NotInCSharp5() { await TestMissingAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c[1] = 2; } }", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestComplexIndexAccess1() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { a.b.c = [||]new List<int>(); a.b.c[1] = 2; } }", @" using System.Collections.Generic; class C { void M() { a.b.c = new List<int> { [1] = 2 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestIndexAccess2() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c[1] = 2; c[2] = """"; } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { [1] = 2, [2] = """" }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestIndexAccess3() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c[1] = 2; c[2] = """"; c[3, 4] = 5; } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { [1] = 2, [2] = """", [3, 4] = 5 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestIndexFollowedByInvocation() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c[1] = 2; c.Add(0); } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { [1] = 2 }; c.Add(0); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestInvocationFollowedByIndex() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(0); c[1] = 2; } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { 0 }; c[1] = 2; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestWithInterimStatement() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(1); c.Add(2); throw new Exception(); c.Add(3); c.Add(4); } }", @"using System.Collections.Generic; class C { void M() { var c = new List<int> { 1, 2 }; throw new Exception(); c.Add(3); c.Add(4); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingBeforeCSharp3() { await TestMissingAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(1); } }", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp2))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingOnNonIEnumerable() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new C(); c.Add(1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingOnNonIEnumerableEvenWithAdd() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new C(); c.Add(1); } public void Add(int i) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestWithCreationArguments() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(1); c.Add(1); } }", @"using System.Collections.Generic; class C { void M() { var c = new List<int>(1) { 1 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestOnAssignmentExpression() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { List<int> c = null; c = [||]new List<int>(); c.Add(1); } }", @"using System.Collections.Generic; class C { void M() { List<int> c = null; c = new List<int> { 1 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingOnRefAdd() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(ref i); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestComplexInitializer() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { List<int>[] array; array[0] = [||]new List<int>(); array[0].Add(1); array[0].Add(2); } }", @"using System.Collections.Generic; class C { void M() { List<int>[] array; array[0] = new List<int> { 1, 2 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestNotOnNamedArg() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(arg: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingWithExistingInitializer() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = [||]new List<int>() { 1 }; c.Add(1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestFixAllInDocument1() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { List<int>[] array; array[0] = {|FixAllInDocument:new|} List<int>(); array[0].Add(1); array[0].Add(2); array[1] = new List<int>(); array[1].Add(3); array[1].Add(4); } }", @"using System.Collections.Generic; class C { void M() { List<int>[] array; array[0] = new List<int> { 1, 2 }; array[1] = new List<int> { 3, 4 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestFixAllInDocument2() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var list1 = {|FixAllInDocument:new|} List<int>(() => { var list2 = new List<int>(); list2.Add(2); }); list1.Add(1); } }", @"using System.Collections.Generic; class C { void M() { var list1 = new List<int>(() => { var list2 = new List<int> { 2 }; }) { 1 }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestFixAllInDocument3() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var list1 = {|FixAllInDocument:new|} List<int>(); list1.Add(() => { var list2 = new List<int>(); list2.Add(2); }); } }", @"using System.Collections.Generic; class C { void M() { var list1 = new List<int> { () => { var list2 = new List<int> { 2 }; } }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestTrivia1() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class C { void M() { var c = [||]new List<int>(); c.Add(1); // Goo c.Add(2); // Bar } }", @" using System.Collections.Generic; class C { void M() { var c = new List<int> { 1, // Goo 2 // Bar }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestComplexInitializer2() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { void M() { var c = new [||]Dictionary<int, string>(); c.Add(1, ""x""); c.Add(2, ""y""); } }", @"using System.Collections.Generic; class C { void M() { var c = new Dictionary<int, string> { { 1, ""x"" }, { 2, ""y"" } }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(16158, "https://github.com/dotnet/roslyn/issues/16158")] public async Task TestIncorrectAddName() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; public class Goo { public static void Bar() { string item = null; var items = new List<string>(); var values = new [||]List<string>(); // Collection initialization can be simplified values.Add(item); values.AddRange(items); } }", @"using System.Collections.Generic; public class Goo { public static void Bar() { string item = null; var items = new List<string>(); var values = new List<string> { item }; // Collection initialization can be simplified values.AddRange(items); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(16241, "https://github.com/dotnet/roslyn/issues/16241")] public async Task TestNestedCollectionInitializer() { await TestMissingInRegularAndScriptAsync( @" using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var myStringArray = new string[] { ""Test"", ""123"", ""ABC"" }; var myStringList = myStringArray?.ToList() ?? new [||]List<string>(); myStringList.Add(""Done""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(17823, "https://github.com/dotnet/roslyn/issues/17823")] public async Task TestMissingWhenReferencedInInitializer() { await TestMissingInRegularAndScriptAsync( @" using System.Collections.Generic; class C { static void M() { var items = new [||]List<object>(); items[0] = items[0]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(17823, "https://github.com/dotnet/roslyn/issues/17823")] public async Task TestWhenReferencedInInitializer_LocalVar() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; class C { static void M() { var items = new [||]List<object>(); items[0] = 1; items[1] = items[0]; } }", @" using System.Collections.Generic; class C { static void M() { var items = new [||]List<object> { [0] = 1 }; items[1] = items[0]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(17823, "https://github.com/dotnet/roslyn/issues/17823")] public async Task TestWhenReferencedInInitializer_LocalVar2() { await TestMissingInRegularAndScriptAsync( @" using System.Collections.Generic; using System.Linq; class C { void M() { var t = [||]new List<int>(new int[] { 1, 2, 3 }); t.Add(t.Min() - 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(18260, "https://github.com/dotnet/roslyn/issues/18260")] public async Task TestWhenReferencedInInitializer_Assignment() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; class C { static void M() { List<object> items = null; items = new [||]List<object>(); items[0] = 1; items[1] = items[0]; } }", @" using System.Collections.Generic; class C { static void M() { List<object> items = null; items = new [||]List<object> { [0] = 1 }; items[1] = items[0]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(18260, "https://github.com/dotnet/roslyn/issues/18260")] public async Task TestWhenReferencedInInitializer_Assignment2() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; using System.Linq; class C { void M() { List<int> t = null; t = [||]new List<int>(new int[] { 1, 2, 3 }); t.Add(t.Min() - 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] [WorkItem(18260, "https://github.com/dotnet/roslyn/issues/18260")] public async Task TestFieldReference() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class C { private List<int> myField; void M() { myField = [||]new List<int>(); myField.Add(this.myField.Count); } }"); } [WorkItem(17853, "https://github.com/dotnet/roslyn/issues/17853")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingForDynamic() { await TestMissingInRegularAndScriptAsync( @"using System.Dynamic; class C { void Goo() { dynamic body = [||]new ExpandoObject(); body[0] = new ExpandoObject(); } }"); } [WorkItem(17953, "https://github.com/dotnet/roslyn/issues/17953")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingAcrossPreprocessorDirective() { await TestMissingInRegularAndScriptAsync( @" using System.Collections.Generic; public class Goo { public void M() { var items = new [||]List<object>(); #if true items.Add(1); #endif } }"); } [WorkItem(17953, "https://github.com/dotnet/roslyn/issues/17953")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestAvailableInsidePreprocessorDirective() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; public class Goo { public void M() { #if true var items = new [||]List<object>(); items.Add(1); #endif } }", @" using System.Collections.Generic; public class Goo { public void M() { #if true var items = new List<object> { 1 }; #endif } }"); } [WorkItem(18242, "https://github.com/dotnet/roslyn/issues/18242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestObjectInitializerAssignmentAmbiguity() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; public class Goo { public void M() { int lastItem; var list = [||]new List<int>(); list.Add(lastItem = 5); } }", @" using System.Collections.Generic; public class Goo { public void M() { int lastItem; var list = new List<int> { (lastItem = 5) }; } }"); } [WorkItem(18242, "https://github.com/dotnet/roslyn/issues/18242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestObjectInitializerCompoundAssignment() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; public class Goo { public void M() { int lastItem = 0; var list = [||]new List<int>(); list.Add(lastItem += 5); } }", @" using System.Collections.Generic; public class Goo { public void M() { int lastItem = 0; var list = new List<int> { (lastItem += 5) }; } }"); } [WorkItem(19253, "https://github.com/dotnet/roslyn/issues/19253")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestKeepBlankLinesAfter() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; class MyClass { public void Main() { var list = [||]new List<int>(); list.Add(1); int horse = 1; } }", @" using System.Collections.Generic; class MyClass { public void Main() { var list = new List<int> { 1 }; int horse = 1; } }"); } [WorkItem(23672, "https://github.com/dotnet/roslyn/issues/23672")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)] public async Task TestMissingWithExplicitImplementedAddMethod() { await TestMissingInRegularAndScriptAsync( @" using System.Collections.Generic; using System.Dynamic; public class Goo { public void M() { IDictionary<string, object> obj = [||]new ExpandoObject(); obj.Add(""string"", ""v""); obj.Add(""int"", 1); obj.Add("" object"", new { X = 1, Y = 2 }); } }"); } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_NullablePublicOnly.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_NullablePublicOnly : CSharpTestBase { [Fact] public void ExplicitAttribute_FromSource() { var source = @"public class A<T> { } public class B : A<object?> { }"; var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; CSharpTestSource sources = new[] { NullablePublicOnlyAttributeDefinition, source }; var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true)); comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: true, publicDefinition: true)); } [Fact] public void ExplicitAttribute_FromMetadata() { var source = @"public class A<T> { } public class B : A<object?> { }"; var comp = CreateCompilation(NullablePublicOnlyAttributeDefinition, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); var ref1 = comp.EmitToImageReference(); var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; comp = CreateCompilation(source, references: new[] { ref1 }, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: false, includesAttributeUse: false, publicDefinition: true)); comp = CreateCompilation(source, references: new[] { ref1 }, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: false, includesAttributeUse: true, publicDefinition: true)); } [Fact] public void ExplicitAttribute_MissingSingleValueConstructor() { var source1 = @"namespace System.Runtime.CompilerServices { public sealed class NullablePublicOnlyAttribute : Attribute { } }"; var source2 = @"public class A<T> { } public class B : A<object?> { }"; var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; var comp = CreateCompilation(new[] { source1, source2 }, options: options, parseOptions: parseOptions); comp.VerifyEmitDiagnostics(); comp = CreateCompilation(new[] { source1, source2 }, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); comp.VerifyEmitDiagnostics( // error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullablePublicOnlyAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Runtime.CompilerServices.NullablePublicOnlyAttribute", ".ctor").WithLocation(1, 1)); } [Fact] public void EmptyProject() { var source = @""; var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; var comp = CreateCompilation(source, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); } [Fact] public void CSharp7_NoAttribute() { var source = @"public class A<T> { } public class B : A<object> { }"; var options = TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular7; var comp = CreateCompilation(source, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); } [Fact] public void NullableEnabled() { var source = @"public class A<T> { } public class B : A<object?> { }"; var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; var comp = CreateCompilation(source, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: AssertNullablePublicOnlyAttribute); } [Fact] public void NullableEnabled_NoPublicMembers() { var source = @"class A<T> { } class B : A<object?> { }"; var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; var comp = CreateCompilation(source, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); } [Fact] public void NullableDisabled() { var source = @"public class A<T> { } public class B : A<object> { }"; var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; var comp = CreateCompilation(source, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); } [Fact] public void NullableDisabled_Annotation() { var source = @"public class A<T> { } public class B : A<object?> { }"; var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; var comp = CreateCompilation(source, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: AssertNullablePublicOnlyAttribute); } [Fact] public void NullableDisabled_OtherNullableAttributeDefinitions() { var source = @"public class Program { }"; var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, source }; var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); } [Fact] public void NullableEnabled_MethodBodyOnly() { var source0 = @"#nullable enable public class A { public static object? F; public static void M(object o) { } }"; var comp = CreateCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @"public class B { static void Main() { #nullable enable A.M(A.F); } }"; comp = CreateCompilation( source1, references: new[] { ref0 }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular8.WithNullablePublicOnly()); comp.VerifyDiagnostics( // (6,13): warning CS8604: Possible null reference argument for parameter 'o' in 'void A.M(object o)'. // A.M(A.F); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "A.F").WithArguments("o", "void A.M(object o)").WithLocation(6, 13)); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); } [Fact] public void NullableEnabled_AllNullableAttributeDefinitions_01() { var source = @"#nullable enable public class Program { }"; var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, NullablePublicOnlyAttributeDefinition, source }; var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true)); comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true)); } [Fact] public void NullableEnabled_AllNullableAttributeDefinitions_02() { var source = @"#nullable enable public class Program { public object F() => null!; }"; var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, NullablePublicOnlyAttributeDefinition, source }; var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true)); comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: true, publicDefinition: true)); } [Fact] public void NullableEnabled_OtherNullableAttributeDefinitions_01() { var source = @"#nullable enable public class Program { }"; var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, source }; var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); } [Fact] public void NullableEnabled_OtherNullableAttributeDefinitions_02() { var source = @"#nullable enable public class Program { public object F() => null!; }"; var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, source }; var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: AssertNullablePublicOnlyAttribute); } [Fact] public void LocalFunctionReturnType_SynthesizedAttributeDefinitions() { var source = @"public class Program { static void Main() { #nullable enable object? L() => null; L(); } }"; var options = TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; var comp = CreateCompilation(source, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); } [Fact] public void LocalFunctionReturnType_ExplicitAttributeDefinitions() { var source = @"public class Program { static void Main() { #nullable enable object? L() => null; L(); } }"; var options = TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, NullablePublicOnlyAttributeDefinition, source }; var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true)); comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true)); } [Fact] [WorkItem(36457, "https://github.com/dotnet/roslyn/issues/36457")] public void ExplicitAttribute_ReferencedInSource_Assembly() { var sourceAttribute = @"namespace System.Runtime.CompilerServices { internal class NullablePublicOnlyAttribute : System.Attribute { internal NullablePublicOnlyAttribute(bool b) { } } }"; var source = @"using System.Runtime.CompilerServices; [assembly: NullablePublicOnly(false)] [module: NullablePublicOnly(false)] "; // C#7 var comp = CreateCompilation(new[] { sourceAttribute, source }, parseOptions: TestOptions.Regular7); verifyDiagnostics(comp); // C#8 comp = CreateCompilation(new[] { sourceAttribute, source }); verifyDiagnostics(comp); static void verifyDiagnostics(CSharpCompilation comp) { comp.VerifyDiagnostics( // (3,10): error CS8335: Do not use 'System.Runtime.CompilerServices.NullablePublicOnlyAttribute'. This is reserved for compiler usage. // [module: NullablePublicOnly(false)] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NullablePublicOnly(false)").WithArguments("System.Runtime.CompilerServices.NullablePublicOnlyAttribute").WithLocation(3, 10)); } } [Fact] [WorkItem(36457, "https://github.com/dotnet/roslyn/issues/36457")] public void ExplicitAttribute_ReferencedInSource_Other() { var sourceAttribute = @"namespace System.Runtime.CompilerServices { internal class NullablePublicOnlyAttribute : System.Attribute { internal NullablePublicOnlyAttribute(bool b) { } } }"; var source = @"using System.Runtime.CompilerServices; [NullablePublicOnly(false)] class Program { }"; var comp = CreateCompilation(new[] { sourceAttribute, source }); comp.VerifyDiagnostics(); } [Fact] public void ExplicitAttribute_WithNullableAttribute() { var sourceAttribute = @"#nullable enable namespace System.Runtime.CompilerServices { public class NullablePublicOnlyAttribute : System.Attribute { public NullablePublicOnlyAttribute(bool b) { } public NullablePublicOnlyAttribute( object x, object? y, #nullable disable object z) { } } }"; var comp = CreateCompilation(sourceAttribute); var ref0 = comp.EmitToImageReference(); var expected = @"System.Runtime.CompilerServices.NullablePublicOnlyAttribute NullablePublicOnlyAttribute(System.Object! x, System.Object? y, System.Object z) [Nullable(1)] System.Object! x [Nullable(2)] System.Object? y "; AssertNullableAttributes(comp, expected); var source = @"#nullable enable public class Program { public object _f1; public object? _f2; #nullable disable public object _f3; }"; comp = CreateCompilation(source, references: new[] { ref0 }); expected = @"Program [Nullable(1)] System.Object! _f1 [Nullable(2)] System.Object? _f2 "; AssertNullableAttributes(comp, expected); } [Fact] [WorkItem(36934, "https://github.com/dotnet/roslyn/issues/36934")] public void AttributeUsage() { var source = @"#nullable enable public class Program { public object? F; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithNullablePublicOnly(), options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)); CompileAndVerify(comp, symbolValidator: module => { var attributeType = module.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Runtime.CompilerServices.NullablePublicOnlyAttribute"); AttributeUsageInfo attributeUsage = attributeType.GetAttributeUsageInfo(); Assert.False(attributeUsage.Inherited); Assert.False(attributeUsage.AllowMultiple); Assert.True(attributeUsage.HasValidAttributeTargets); Assert.Equal(AttributeTargets.Module, attributeUsage.ValidTargets); }); } [Fact] public void MissingAttributeUsageAttribute() { var source = @"#nullable enable public class Program { public object? F; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithNullablePublicOnly()); comp.MakeTypeMissing(WellKnownType.System_AttributeUsageAttribute); comp.VerifyEmitDiagnostics( // 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), // 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)); } [Fact] public void AttributeField() { var source = @"#nullable enable using System; using System.Linq; using System.Reflection; public class Program { public static void Main(string[] args) { var value = GetAttributeValue(typeof(Program).Assembly.Modules.First()); Console.WriteLine(value == null ? ""<null>"" : value.ToString()); } static bool? GetAttributeValue(Module module) { var attribute = module.GetCustomAttributes(false).SingleOrDefault(a => a.GetType().Name == ""NullablePublicOnlyAttribute""); if (attribute == null) return null; var field = attribute.GetType().GetField(""IncludesInternals""); return (bool)field.GetValue(attribute); } }"; var sourceIVTs = @"using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""Other"")]"; var parseOptions = TestOptions.Regular8; CompileAndVerify(source, parseOptions: parseOptions, expectedOutput: "<null>"); CompileAndVerify(source, parseOptions: parseOptions.WithNullablePublicOnly(), expectedOutput: "False"); CompileAndVerify(new[] { source, sourceIVTs }, parseOptions: parseOptions, expectedOutput: "<null>"); CompileAndVerify(new[] { source, sourceIVTs }, parseOptions: parseOptions.WithNullablePublicOnly(), expectedOutput: "True"); } private static void AssertNoNullablePublicOnlyAttribute(ModuleSymbol module) { AssertNullablePublicOnlyAttribute(module, includesAttributeDefinition: false, includesAttributeUse: false, publicDefinition: false); } private static void AssertNullablePublicOnlyAttribute(ModuleSymbol module) { AssertNullablePublicOnlyAttribute(module, includesAttributeDefinition: true, includesAttributeUse: true, publicDefinition: false); } private static void AssertNullablePublicOnlyAttribute(ModuleSymbol module, bool includesAttributeDefinition, bool includesAttributeUse, bool publicDefinition) { const string attributeName = "System.Runtime.CompilerServices.NullablePublicOnlyAttribute"; var type = (NamedTypeSymbol)module.GlobalNamespace.GetMember(attributeName); var attribute = module.GetAttributes().SingleOrDefault(); if (includesAttributeDefinition) { Assert.NotNull(type); } else { Assert.Null(type); if (includesAttributeUse) { type = attribute.AttributeClass; } } if (type is object) { Assert.Equal(publicDefinition ? Accessibility.Public : Accessibility.Internal, type.DeclaredAccessibility); } if (includesAttributeUse) { Assert.Equal(type, attribute.AttributeClass); } else { Assert.Null(attribute); } } private void AssertNullableAttributes(CSharpCompilation comp, string expected) { CompileAndVerify(comp, symbolValidator: module => AssertNullableAttributes(module, expected)); } private static void AssertNullableAttributes(ModuleSymbol module, string expected) { var actual = NullableAttributesVisitor.GetString((PEModuleSymbol)module); AssertEx.AssertEqualToleratingWhitespaceDifferences(expected, actual); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_NullablePublicOnly : CSharpTestBase { [Fact] public void ExplicitAttribute_FromSource() { var source = @"public class A<T> { } public class B : A<object?> { }"; var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; CSharpTestSource sources = new[] { NullablePublicOnlyAttributeDefinition, source }; var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true)); comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: true, publicDefinition: true)); } [Fact] public void ExplicitAttribute_FromMetadata() { var source = @"public class A<T> { } public class B : A<object?> { }"; var comp = CreateCompilation(NullablePublicOnlyAttributeDefinition, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); var ref1 = comp.EmitToImageReference(); var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; comp = CreateCompilation(source, references: new[] { ref1 }, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: false, includesAttributeUse: false, publicDefinition: true)); comp = CreateCompilation(source, references: new[] { ref1 }, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: false, includesAttributeUse: true, publicDefinition: true)); } [Fact] public void ExplicitAttribute_MissingSingleValueConstructor() { var source1 = @"namespace System.Runtime.CompilerServices { public sealed class NullablePublicOnlyAttribute : Attribute { } }"; var source2 = @"public class A<T> { } public class B : A<object?> { }"; var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; var comp = CreateCompilation(new[] { source1, source2 }, options: options, parseOptions: parseOptions); comp.VerifyEmitDiagnostics(); comp = CreateCompilation(new[] { source1, source2 }, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); comp.VerifyEmitDiagnostics( // error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullablePublicOnlyAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.Runtime.CompilerServices.NullablePublicOnlyAttribute", ".ctor").WithLocation(1, 1)); } [Fact] public void EmptyProject() { var source = @""; var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; var comp = CreateCompilation(source, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); } [Fact] public void CSharp7_NoAttribute() { var source = @"public class A<T> { } public class B : A<object> { }"; var options = TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular7; var comp = CreateCompilation(source, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); } [Fact] public void NullableEnabled() { var source = @"public class A<T> { } public class B : A<object?> { }"; var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; var comp = CreateCompilation(source, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: AssertNullablePublicOnlyAttribute); } [Fact] public void NullableEnabled_NoPublicMembers() { var source = @"class A<T> { } class B : A<object?> { }"; var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; var comp = CreateCompilation(source, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); } [Fact] public void NullableDisabled() { var source = @"public class A<T> { } public class B : A<object> { }"; var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; var comp = CreateCompilation(source, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); } [Fact] public void NullableDisabled_Annotation() { var source = @"public class A<T> { } public class B : A<object?> { }"; var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; var comp = CreateCompilation(source, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: AssertNullablePublicOnlyAttribute); } [Fact] public void NullableDisabled_OtherNullableAttributeDefinitions() { var source = @"public class Program { }"; var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, source }; var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); } [Fact] public void NullableEnabled_MethodBodyOnly() { var source0 = @"#nullable enable public class A { public static object? F; public static void M(object o) { } }"; var comp = CreateCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @"public class B { static void Main() { #nullable enable A.M(A.F); } }"; comp = CreateCompilation( source1, references: new[] { ref0 }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular8.WithNullablePublicOnly()); comp.VerifyDiagnostics( // (6,13): warning CS8604: Possible null reference argument for parameter 'o' in 'void A.M(object o)'. // A.M(A.F); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "A.F").WithArguments("o", "void A.M(object o)").WithLocation(6, 13)); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); } [Fact] public void NullableEnabled_AllNullableAttributeDefinitions_01() { var source = @"#nullable enable public class Program { }"; var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, NullablePublicOnlyAttributeDefinition, source }; var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true)); comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true)); } [Fact] public void NullableEnabled_AllNullableAttributeDefinitions_02() { var source = @"#nullable enable public class Program { public object F() => null!; }"; var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, NullablePublicOnlyAttributeDefinition, source }; var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true)); comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: true, publicDefinition: true)); } [Fact] public void NullableEnabled_OtherNullableAttributeDefinitions_01() { var source = @"#nullable enable public class Program { }"; var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, source }; var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); } [Fact] public void NullableEnabled_OtherNullableAttributeDefinitions_02() { var source = @"#nullable enable public class Program { public object F() => null!; }"; var options = WithNullableDisable().WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, source }; var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: AssertNullablePublicOnlyAttribute); } [Fact] public void LocalFunctionReturnType_SynthesizedAttributeDefinitions() { var source = @"public class Program { static void Main() { #nullable enable object? L() => null; L(); } }"; var options = TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; var comp = CreateCompilation(source, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); comp = CreateCompilation(source, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: AssertNoNullablePublicOnlyAttribute); } [Fact] public void LocalFunctionReturnType_ExplicitAttributeDefinitions() { var source = @"public class Program { static void Main() { #nullable enable object? L() => null; L(); } }"; var options = TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All); var parseOptions = TestOptions.Regular8; CSharpTestSource sources = new[] { NullableAttributeDefinition, NullableContextAttributeDefinition, NullablePublicOnlyAttributeDefinition, source }; var comp = CreateCompilation(sources, options: options, parseOptions: parseOptions); CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true)); comp = CreateCompilation(sources, options: options, parseOptions: parseOptions.WithNullablePublicOnly()); CompileAndVerify(comp, symbolValidator: m => AssertNullablePublicOnlyAttribute(m, includesAttributeDefinition: true, includesAttributeUse: false, publicDefinition: true)); } [Fact] [WorkItem(36457, "https://github.com/dotnet/roslyn/issues/36457")] public void ExplicitAttribute_ReferencedInSource_Assembly() { var sourceAttribute = @"namespace System.Runtime.CompilerServices { internal class NullablePublicOnlyAttribute : System.Attribute { internal NullablePublicOnlyAttribute(bool b) { } } }"; var source = @"using System.Runtime.CompilerServices; [assembly: NullablePublicOnly(false)] [module: NullablePublicOnly(false)] "; // C#7 var comp = CreateCompilation(new[] { sourceAttribute, source }, parseOptions: TestOptions.Regular7); verifyDiagnostics(comp); // C#8 comp = CreateCompilation(new[] { sourceAttribute, source }); verifyDiagnostics(comp); static void verifyDiagnostics(CSharpCompilation comp) { comp.VerifyDiagnostics( // (3,10): error CS8335: Do not use 'System.Runtime.CompilerServices.NullablePublicOnlyAttribute'. This is reserved for compiler usage. // [module: NullablePublicOnly(false)] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NullablePublicOnly(false)").WithArguments("System.Runtime.CompilerServices.NullablePublicOnlyAttribute").WithLocation(3, 10)); } } [Fact] [WorkItem(36457, "https://github.com/dotnet/roslyn/issues/36457")] public void ExplicitAttribute_ReferencedInSource_Other() { var sourceAttribute = @"namespace System.Runtime.CompilerServices { internal class NullablePublicOnlyAttribute : System.Attribute { internal NullablePublicOnlyAttribute(bool b) { } } }"; var source = @"using System.Runtime.CompilerServices; [NullablePublicOnly(false)] class Program { }"; var comp = CreateCompilation(new[] { sourceAttribute, source }); comp.VerifyDiagnostics(); } [Fact] public void ExplicitAttribute_WithNullableAttribute() { var sourceAttribute = @"#nullable enable namespace System.Runtime.CompilerServices { public class NullablePublicOnlyAttribute : System.Attribute { public NullablePublicOnlyAttribute(bool b) { } public NullablePublicOnlyAttribute( object x, object? y, #nullable disable object z) { } } }"; var comp = CreateCompilation(sourceAttribute); var ref0 = comp.EmitToImageReference(); var expected = @"System.Runtime.CompilerServices.NullablePublicOnlyAttribute NullablePublicOnlyAttribute(System.Object! x, System.Object? y, System.Object z) [Nullable(1)] System.Object! x [Nullable(2)] System.Object? y "; AssertNullableAttributes(comp, expected); var source = @"#nullable enable public class Program { public object _f1; public object? _f2; #nullable disable public object _f3; }"; comp = CreateCompilation(source, references: new[] { ref0 }); expected = @"Program [Nullable(1)] System.Object! _f1 [Nullable(2)] System.Object? _f2 "; AssertNullableAttributes(comp, expected); } [Fact] [WorkItem(36934, "https://github.com/dotnet/roslyn/issues/36934")] public void AttributeUsage() { var source = @"#nullable enable public class Program { public object? F; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithNullablePublicOnly(), options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)); CompileAndVerify(comp, symbolValidator: module => { var attributeType = module.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Runtime.CompilerServices.NullablePublicOnlyAttribute"); AttributeUsageInfo attributeUsage = attributeType.GetAttributeUsageInfo(); Assert.False(attributeUsage.Inherited); Assert.False(attributeUsage.AllowMultiple); Assert.True(attributeUsage.HasValidAttributeTargets); Assert.Equal(AttributeTargets.Module, attributeUsage.ValidTargets); }); } [Fact] public void MissingAttributeUsageAttribute() { var source = @"#nullable enable public class Program { public object? F; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithNullablePublicOnly()); comp.MakeTypeMissing(WellKnownType.System_AttributeUsageAttribute); comp.VerifyEmitDiagnostics( // 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), // 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)); } [Fact] public void AttributeField() { var source = @"#nullable enable using System; using System.Linq; using System.Reflection; public class Program { public static void Main(string[] args) { var value = GetAttributeValue(typeof(Program).Assembly.Modules.First()); Console.WriteLine(value == null ? ""<null>"" : value.ToString()); } static bool? GetAttributeValue(Module module) { var attribute = module.GetCustomAttributes(false).SingleOrDefault(a => a.GetType().Name == ""NullablePublicOnlyAttribute""); if (attribute == null) return null; var field = attribute.GetType().GetField(""IncludesInternals""); return (bool)field.GetValue(attribute); } }"; var sourceIVTs = @"using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""Other"")]"; var parseOptions = TestOptions.Regular8; CompileAndVerify(source, parseOptions: parseOptions, expectedOutput: "<null>"); CompileAndVerify(source, parseOptions: parseOptions.WithNullablePublicOnly(), expectedOutput: "False"); CompileAndVerify(new[] { source, sourceIVTs }, parseOptions: parseOptions, expectedOutput: "<null>"); CompileAndVerify(new[] { source, sourceIVTs }, parseOptions: parseOptions.WithNullablePublicOnly(), expectedOutput: "True"); } private static void AssertNoNullablePublicOnlyAttribute(ModuleSymbol module) { AssertNullablePublicOnlyAttribute(module, includesAttributeDefinition: false, includesAttributeUse: false, publicDefinition: false); } private static void AssertNullablePublicOnlyAttribute(ModuleSymbol module) { AssertNullablePublicOnlyAttribute(module, includesAttributeDefinition: true, includesAttributeUse: true, publicDefinition: false); } private static void AssertNullablePublicOnlyAttribute(ModuleSymbol module, bool includesAttributeDefinition, bool includesAttributeUse, bool publicDefinition) { const string attributeName = "System.Runtime.CompilerServices.NullablePublicOnlyAttribute"; var type = (NamedTypeSymbol)module.GlobalNamespace.GetMember(attributeName); var attribute = module.GetAttributes().SingleOrDefault(); if (includesAttributeDefinition) { Assert.NotNull(type); } else { Assert.Null(type); if (includesAttributeUse) { type = attribute.AttributeClass; } } if (type is object) { Assert.Equal(publicDefinition ? Accessibility.Public : Accessibility.Internal, type.DeclaredAccessibility); } if (includesAttributeUse) { Assert.Equal(type, attribute.AttributeClass); } else { Assert.Null(attribute); } } private void AssertNullableAttributes(CSharpCompilation comp, string expected) { CompileAndVerify(comp, symbolValidator: module => AssertNullableAttributes(module, expected)); } private static void AssertNullableAttributes(ModuleSymbol module, string expected) { var actual = NullableAttributesVisitor.GetString((PEModuleSymbol)module); AssertEx.AssertEqualToleratingWhitespaceDifferences(expected, actual); } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationOperatorSymbol.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.Editing; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationOperatorSymbol : CodeGenerationMethodSymbol { public CodeGenerationOperatorSymbol( INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol returnType, CodeGenerationOperatorKind operatorKind, ImmutableArray<IParameterSymbol> parameters, ImmutableArray<AttributeData> returnTypeAttributes, string documentationCommentXml) : base(containingType, attributes, accessibility, modifiers, returnType, refKind: RefKind.None, explicitInterfaceImplementations: default, GetMetadataName(operatorKind), typeParameters: ImmutableArray<ITypeParameterSymbol>.Empty, parameters, returnTypeAttributes, documentationCommentXml) { } public override MethodKind MethodKind => MethodKind.UserDefinedOperator; public static int GetParameterCount(CodeGenerationOperatorKind operatorKind) { switch (operatorKind) { case CodeGenerationOperatorKind.Addition: case CodeGenerationOperatorKind.BitwiseAnd: case CodeGenerationOperatorKind.BitwiseOr: case CodeGenerationOperatorKind.Concatenate: case CodeGenerationOperatorKind.Division: case CodeGenerationOperatorKind.Equality: case CodeGenerationOperatorKind.ExclusiveOr: case CodeGenerationOperatorKind.Exponent: case CodeGenerationOperatorKind.GreaterThan: case CodeGenerationOperatorKind.GreaterThanOrEqual: case CodeGenerationOperatorKind.Inequality: case CodeGenerationOperatorKind.IntegerDivision: case CodeGenerationOperatorKind.LeftShift: case CodeGenerationOperatorKind.LessThan: case CodeGenerationOperatorKind.LessThanOrEqual: case CodeGenerationOperatorKind.Like: case CodeGenerationOperatorKind.Modulus: case CodeGenerationOperatorKind.Multiplication: case CodeGenerationOperatorKind.RightShift: case CodeGenerationOperatorKind.Subtraction: return 2; case CodeGenerationOperatorKind.Increment: case CodeGenerationOperatorKind.Decrement: case CodeGenerationOperatorKind.False: case CodeGenerationOperatorKind.LogicalNot: case CodeGenerationOperatorKind.OnesComplement: case CodeGenerationOperatorKind.True: case CodeGenerationOperatorKind.UnaryPlus: case CodeGenerationOperatorKind.UnaryNegation: return 1; default: throw ExceptionUtilities.UnexpectedValue(operatorKind); } } private static string GetMetadataName(CodeGenerationOperatorKind operatorKind) => operatorKind switch { CodeGenerationOperatorKind.Addition => WellKnownMemberNames.AdditionOperatorName, CodeGenerationOperatorKind.BitwiseAnd => WellKnownMemberNames.BitwiseAndOperatorName, CodeGenerationOperatorKind.BitwiseOr => WellKnownMemberNames.BitwiseOrOperatorName, CodeGenerationOperatorKind.Concatenate => WellKnownMemberNames.ConcatenateOperatorName, CodeGenerationOperatorKind.Decrement => WellKnownMemberNames.DecrementOperatorName, CodeGenerationOperatorKind.Division => WellKnownMemberNames.DivisionOperatorName, CodeGenerationOperatorKind.Equality => WellKnownMemberNames.EqualityOperatorName, CodeGenerationOperatorKind.ExclusiveOr => WellKnownMemberNames.ExclusiveOrOperatorName, CodeGenerationOperatorKind.Exponent => WellKnownMemberNames.ExponentOperatorName, CodeGenerationOperatorKind.False => WellKnownMemberNames.FalseOperatorName, CodeGenerationOperatorKind.GreaterThan => WellKnownMemberNames.GreaterThanOperatorName, CodeGenerationOperatorKind.GreaterThanOrEqual => WellKnownMemberNames.GreaterThanOrEqualOperatorName, CodeGenerationOperatorKind.Increment => WellKnownMemberNames.IncrementOperatorName, CodeGenerationOperatorKind.Inequality => WellKnownMemberNames.InequalityOperatorName, CodeGenerationOperatorKind.IntegerDivision => WellKnownMemberNames.IntegerDivisionOperatorName, CodeGenerationOperatorKind.LeftShift => WellKnownMemberNames.LeftShiftOperatorName, CodeGenerationOperatorKind.LessThan => WellKnownMemberNames.LessThanOperatorName, CodeGenerationOperatorKind.LessThanOrEqual => WellKnownMemberNames.LessThanOrEqualOperatorName, CodeGenerationOperatorKind.Like => WellKnownMemberNames.LikeOperatorName, CodeGenerationOperatorKind.LogicalNot => WellKnownMemberNames.LogicalNotOperatorName, CodeGenerationOperatorKind.Modulus => WellKnownMemberNames.ModulusOperatorName, CodeGenerationOperatorKind.Multiplication => WellKnownMemberNames.MultiplyOperatorName, CodeGenerationOperatorKind.OnesComplement => WellKnownMemberNames.OnesComplementOperatorName, CodeGenerationOperatorKind.RightShift => WellKnownMemberNames.RightShiftOperatorName, CodeGenerationOperatorKind.Subtraction => WellKnownMemberNames.SubtractionOperatorName, CodeGenerationOperatorKind.True => WellKnownMemberNames.TrueOperatorName, CodeGenerationOperatorKind.UnaryPlus => WellKnownMemberNames.UnaryPlusOperatorName, CodeGenerationOperatorKind.UnaryNegation => WellKnownMemberNames.UnaryNegationOperatorName, _ => throw ExceptionUtilities.UnexpectedValue(operatorKind), }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Editing; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationOperatorSymbol : CodeGenerationMethodSymbol { public CodeGenerationOperatorSymbol( INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol returnType, CodeGenerationOperatorKind operatorKind, ImmutableArray<IParameterSymbol> parameters, ImmutableArray<AttributeData> returnTypeAttributes, string documentationCommentXml) : base(containingType, attributes, accessibility, modifiers, returnType, refKind: RefKind.None, explicitInterfaceImplementations: default, GetMetadataName(operatorKind), typeParameters: ImmutableArray<ITypeParameterSymbol>.Empty, parameters, returnTypeAttributes, documentationCommentXml) { } public override MethodKind MethodKind => MethodKind.UserDefinedOperator; public static int GetParameterCount(CodeGenerationOperatorKind operatorKind) { switch (operatorKind) { case CodeGenerationOperatorKind.Addition: case CodeGenerationOperatorKind.BitwiseAnd: case CodeGenerationOperatorKind.BitwiseOr: case CodeGenerationOperatorKind.Concatenate: case CodeGenerationOperatorKind.Division: case CodeGenerationOperatorKind.Equality: case CodeGenerationOperatorKind.ExclusiveOr: case CodeGenerationOperatorKind.Exponent: case CodeGenerationOperatorKind.GreaterThan: case CodeGenerationOperatorKind.GreaterThanOrEqual: case CodeGenerationOperatorKind.Inequality: case CodeGenerationOperatorKind.IntegerDivision: case CodeGenerationOperatorKind.LeftShift: case CodeGenerationOperatorKind.LessThan: case CodeGenerationOperatorKind.LessThanOrEqual: case CodeGenerationOperatorKind.Like: case CodeGenerationOperatorKind.Modulus: case CodeGenerationOperatorKind.Multiplication: case CodeGenerationOperatorKind.RightShift: case CodeGenerationOperatorKind.Subtraction: return 2; case CodeGenerationOperatorKind.Increment: case CodeGenerationOperatorKind.Decrement: case CodeGenerationOperatorKind.False: case CodeGenerationOperatorKind.LogicalNot: case CodeGenerationOperatorKind.OnesComplement: case CodeGenerationOperatorKind.True: case CodeGenerationOperatorKind.UnaryPlus: case CodeGenerationOperatorKind.UnaryNegation: return 1; default: throw ExceptionUtilities.UnexpectedValue(operatorKind); } } private static string GetMetadataName(CodeGenerationOperatorKind operatorKind) => operatorKind switch { CodeGenerationOperatorKind.Addition => WellKnownMemberNames.AdditionOperatorName, CodeGenerationOperatorKind.BitwiseAnd => WellKnownMemberNames.BitwiseAndOperatorName, CodeGenerationOperatorKind.BitwiseOr => WellKnownMemberNames.BitwiseOrOperatorName, CodeGenerationOperatorKind.Concatenate => WellKnownMemberNames.ConcatenateOperatorName, CodeGenerationOperatorKind.Decrement => WellKnownMemberNames.DecrementOperatorName, CodeGenerationOperatorKind.Division => WellKnownMemberNames.DivisionOperatorName, CodeGenerationOperatorKind.Equality => WellKnownMemberNames.EqualityOperatorName, CodeGenerationOperatorKind.ExclusiveOr => WellKnownMemberNames.ExclusiveOrOperatorName, CodeGenerationOperatorKind.Exponent => WellKnownMemberNames.ExponentOperatorName, CodeGenerationOperatorKind.False => WellKnownMemberNames.FalseOperatorName, CodeGenerationOperatorKind.GreaterThan => WellKnownMemberNames.GreaterThanOperatorName, CodeGenerationOperatorKind.GreaterThanOrEqual => WellKnownMemberNames.GreaterThanOrEqualOperatorName, CodeGenerationOperatorKind.Increment => WellKnownMemberNames.IncrementOperatorName, CodeGenerationOperatorKind.Inequality => WellKnownMemberNames.InequalityOperatorName, CodeGenerationOperatorKind.IntegerDivision => WellKnownMemberNames.IntegerDivisionOperatorName, CodeGenerationOperatorKind.LeftShift => WellKnownMemberNames.LeftShiftOperatorName, CodeGenerationOperatorKind.LessThan => WellKnownMemberNames.LessThanOperatorName, CodeGenerationOperatorKind.LessThanOrEqual => WellKnownMemberNames.LessThanOrEqualOperatorName, CodeGenerationOperatorKind.Like => WellKnownMemberNames.LikeOperatorName, CodeGenerationOperatorKind.LogicalNot => WellKnownMemberNames.LogicalNotOperatorName, CodeGenerationOperatorKind.Modulus => WellKnownMemberNames.ModulusOperatorName, CodeGenerationOperatorKind.Multiplication => WellKnownMemberNames.MultiplyOperatorName, CodeGenerationOperatorKind.OnesComplement => WellKnownMemberNames.OnesComplementOperatorName, CodeGenerationOperatorKind.RightShift => WellKnownMemberNames.RightShiftOperatorName, CodeGenerationOperatorKind.Subtraction => WellKnownMemberNames.SubtractionOperatorName, CodeGenerationOperatorKind.True => WellKnownMemberNames.TrueOperatorName, CodeGenerationOperatorKind.UnaryPlus => WellKnownMemberNames.UnaryPlusOperatorName, CodeGenerationOperatorKind.UnaryNegation => WellKnownMemberNames.UnaryNegationOperatorName, _ => throw ExceptionUtilities.UnexpectedValue(operatorKind), }; } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Compilers/CSharp/Portable/Syntax/CrefParameterSyntax.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.CodeAnalysis.CSharp.Syntax { public sealed partial class CrefParameterSyntax { /// <summary> /// Pre C# 7.2 back-compat overload, which simply calls the replacement property <see cref="RefKindKeyword"/>. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public SyntaxToken RefOrOutKeyword => this.RefKindKeyword; /// <summary> /// Pre C# 7.2 back-compat overload, which simply calls the replacement method <see cref="Update"/>. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public CrefParameterSyntax WithRefOrOutKeyword(SyntaxToken refOrOutKeyword) { return this.Update(refOrOutKeyword, this.Type); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public sealed partial class CrefParameterSyntax { /// <summary> /// Pre C# 7.2 back-compat overload, which simply calls the replacement property <see cref="RefKindKeyword"/>. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public SyntaxToken RefOrOutKeyword => this.RefKindKeyword; /// <summary> /// Pre C# 7.2 back-compat overload, which simply calls the replacement method <see cref="Update"/>. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public CrefParameterSyntax WithRefOrOutKeyword(SyntaxToken refOrOutKeyword) { return this.Update(refOrOutKeyword, this.Type); } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Features/CSharp/Portable/SignatureHelp/InvocationExpressionSignatureHelpProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { [ExportSignatureHelpProvider("InvocationExpressionSignatureHelpProvider", LanguageNames.CSharp), Shared] internal sealed class InvocationExpressionSignatureHelpProvider : InvocationExpressionSignatureHelpProviderBase { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InvocationExpressionSignatureHelpProvider() { } } internal partial class InvocationExpressionSignatureHelpProviderBase : AbstractOrdinaryMethodSignatureHelpProvider { public override bool IsTriggerCharacter(char ch) => ch is '(' or ','; public override bool IsRetriggerCharacter(char ch) => ch == ')'; private bool TryGetInvocationExpression(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out InvocationExpressionSyntax expression) { if (!CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out expression)) { return false; } return expression.ArgumentList != null; } private bool IsTriggerToken(SyntaxToken token) => SignatureHelpUtilities.IsTriggerParenOrComma<InvocationExpressionSyntax>(token, IsTriggerCharacter); private static bool IsArgumentListToken(InvocationExpressionSyntax expression, SyntaxToken token) { return expression.ArgumentList.Span.Contains(token.SpanStart) && token != expression.ArgumentList.CloseParenToken; } protected override async Task<SignatureHelpItems?> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (!TryGetInvocationExpression(root, position, document.GetRequiredLanguageService<ISyntaxFactsService>(), triggerInfo.TriggerReason, cancellationToken, out var invocationExpression)) { return null; } var semanticModel = await document.ReuseExistingSpeculativeModelAsync(invocationExpression, cancellationToken).ConfigureAwait(false); var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); if (within == null) { return null; } // get the regular signature help items var methodGroup = semanticModel.GetMemberGroup(invocationExpression.Expression, cancellationToken) .OfType<IMethodSymbol>() .ToImmutableArray() .FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation); // try to bind to the actual method var symbolInfo = semanticModel.GetSymbolInfo(invocationExpression, cancellationToken); // if the symbol could be bound, replace that item in the symbol list if (symbolInfo.Symbol is IMethodSymbol matchedMethodSymbol && matchedMethodSymbol.IsGenericMethod) { methodGroup = methodGroup.SelectAsArray(m => Equals(matchedMethodSymbol.OriginalDefinition, m) ? matchedMethodSymbol : m); } methodGroup = methodGroup.Sort( semanticModel, invocationExpression.SpanStart); var structuralTypeDisplayService = document.Project.LanguageServices.GetRequiredService<IStructuralTypeDisplayService>(); var documentationCommentFormattingService = document.Project.LanguageServices.GetRequiredService<IDocumentationCommentFormattingService>(); var textSpan = SignatureHelpUtilities.GetSignatureHelpSpan(invocationExpression.ArgumentList); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); if (methodGroup.Any()) { var accessibleMethods = GetAccessibleMethods(invocationExpression, semanticModel, within, methodGroup, cancellationToken); var (items, selectedItem) = await GetMethodGroupItemsAndSelectionAsync(accessibleMethods, document, invocationExpression, semanticModel, symbolInfo, cancellationToken).ConfigureAwait(false); return CreateSignatureHelpItems( items, textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), selectedItem); } var invokedType = semanticModel.GetTypeInfo(invocationExpression.Expression, cancellationToken).Type; if (invokedType is INamedTypeSymbol expressionType && expressionType.TypeKind == TypeKind.Delegate) { var items = GetDelegateInvokeItems(invocationExpression, semanticModel, structuralTypeDisplayService, documentationCommentFormattingService, within, expressionType, out var selectedItem, cancellationToken); return CreateSignatureHelpItems(items, textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), selectedItem); } else if (invokedType is IFunctionPointerTypeSymbol functionPointerType) { var items = GetFunctionPointerInvokeItems(invocationExpression, semanticModel, structuralTypeDisplayService, documentationCommentFormattingService, functionPointerType, out var selectedItem, cancellationToken); return CreateSignatureHelpItems(items, textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), selectedItem); } return null; } public override SignatureHelpState? GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken) { if (TryGetInvocationExpression( root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, out var expression) && currentSpan.Start == SignatureHelpUtilities.GetSignatureHelpSpan(expression.ArgumentList).Start) { return SignatureHelpUtilities.GetSignatureHelpState(expression.ArgumentList, position); } 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. using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { [ExportSignatureHelpProvider("InvocationExpressionSignatureHelpProvider", LanguageNames.CSharp), Shared] internal sealed class InvocationExpressionSignatureHelpProvider : InvocationExpressionSignatureHelpProviderBase { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InvocationExpressionSignatureHelpProvider() { } } internal partial class InvocationExpressionSignatureHelpProviderBase : AbstractOrdinaryMethodSignatureHelpProvider { public override bool IsTriggerCharacter(char ch) => ch is '(' or ','; public override bool IsRetriggerCharacter(char ch) => ch == ')'; private bool TryGetInvocationExpression(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out InvocationExpressionSyntax expression) { if (!CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out expression)) { return false; } return expression.ArgumentList != null; } private bool IsTriggerToken(SyntaxToken token) => SignatureHelpUtilities.IsTriggerParenOrComma<InvocationExpressionSyntax>(token, IsTriggerCharacter); private static bool IsArgumentListToken(InvocationExpressionSyntax expression, SyntaxToken token) { return expression.ArgumentList.Span.Contains(token.SpanStart) && token != expression.ArgumentList.CloseParenToken; } protected override async Task<SignatureHelpItems?> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (!TryGetInvocationExpression(root, position, document.GetRequiredLanguageService<ISyntaxFactsService>(), triggerInfo.TriggerReason, cancellationToken, out var invocationExpression)) { return null; } var semanticModel = await document.ReuseExistingSpeculativeModelAsync(invocationExpression, cancellationToken).ConfigureAwait(false); var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); if (within == null) { return null; } // get the regular signature help items var methodGroup = semanticModel.GetMemberGroup(invocationExpression.Expression, cancellationToken) .OfType<IMethodSymbol>() .ToImmutableArray() .FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation); // try to bind to the actual method var symbolInfo = semanticModel.GetSymbolInfo(invocationExpression, cancellationToken); // if the symbol could be bound, replace that item in the symbol list if (symbolInfo.Symbol is IMethodSymbol matchedMethodSymbol && matchedMethodSymbol.IsGenericMethod) { methodGroup = methodGroup.SelectAsArray(m => Equals(matchedMethodSymbol.OriginalDefinition, m) ? matchedMethodSymbol : m); } methodGroup = methodGroup.Sort( semanticModel, invocationExpression.SpanStart); var structuralTypeDisplayService = document.Project.LanguageServices.GetRequiredService<IStructuralTypeDisplayService>(); var documentationCommentFormattingService = document.Project.LanguageServices.GetRequiredService<IDocumentationCommentFormattingService>(); var textSpan = SignatureHelpUtilities.GetSignatureHelpSpan(invocationExpression.ArgumentList); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); if (methodGroup.Any()) { var accessibleMethods = GetAccessibleMethods(invocationExpression, semanticModel, within, methodGroup, cancellationToken); var (items, selectedItem) = await GetMethodGroupItemsAndSelectionAsync(accessibleMethods, document, invocationExpression, semanticModel, symbolInfo, cancellationToken).ConfigureAwait(false); return CreateSignatureHelpItems( items, textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), selectedItem); } var invokedType = semanticModel.GetTypeInfo(invocationExpression.Expression, cancellationToken).Type; if (invokedType is INamedTypeSymbol expressionType && expressionType.TypeKind == TypeKind.Delegate) { var items = GetDelegateInvokeItems(invocationExpression, semanticModel, structuralTypeDisplayService, documentationCommentFormattingService, within, expressionType, out var selectedItem, cancellationToken); return CreateSignatureHelpItems(items, textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), selectedItem); } else if (invokedType is IFunctionPointerTypeSymbol functionPointerType) { var items = GetFunctionPointerInvokeItems(invocationExpression, semanticModel, structuralTypeDisplayService, documentationCommentFormattingService, functionPointerType, out var selectedItem, cancellationToken); return CreateSignatureHelpItems(items, textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), selectedItem); } return null; } public override SignatureHelpState? GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken) { if (TryGetInvocationExpression( root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, out var expression) && currentSpan.Start == SignatureHelpUtilities.GetSignatureHelpSpan(expression.ArgumentList).Start) { return SignatureHelpUtilities.GetSignatureHelpState(expression.ArgumentList, position); } return null; } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/EditorFeatures/CSharpTest2/Recommendations/WithKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class WithKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterWith() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = goo with $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExpr() { await VerifyKeywordAsync(AddInsideMethod( @"var q = goo $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDottedName() { await VerifyKeywordAsync(AddInsideMethod( @"var q = goo.Current $$")); } [WorkItem(543041, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543041")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterVarInForLoop() { await VerifyAbsenceAsync(AddInsideMethod( @"for (var $$")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeFirstStringHole() { await VerifyAbsenceAsync(AddInsideMethod( @"var x = ""\{0}$$\{1}\{2}""")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBetweenStringHoles() { await VerifyAbsenceAsync(AddInsideMethod( @"var x = ""\{0}\{1}$$\{2}""")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStringHoles() { await VerifyAbsenceAsync(AddInsideMethod( @"var x = ""\{0}\{1}\{2}$$""")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLastStringHole() { await VerifyKeywordAsync(AddInsideMethod( @"var x = ""\{0}\{1}\{2}"" $$")); } [WorkItem(1736, "https://github.com/dotnet/roslyn/issues/1736")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotWithinNumericLiteral() { await VerifyAbsenceAsync(AddInsideMethod( @"var x = .$$0;")); } [WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAsync() { await VerifyAbsenceAsync( @" using System; class C { void Goo() { Bar(async $$ } void Bar(Func<int, string> f) { } }"); } [WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterMethodReference() { await VerifyAbsenceAsync( @" using System; class C { void M() { var v = Console.WriteLine $$"); } [WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAnonymousMethod() { await VerifyAbsenceAsync( @" using System; class C { void M() { Action a = delegate { } $$"); } [WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterLambda1() { await VerifyAbsenceAsync( @" using System; class C { void M() { Action b = (() => 0) $$"); } [WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterLambda2() { await VerifyAbsenceAsync( @" using System; class C { void M() { Action b = () => {} $$"); } [WorkItem(48573, "https://github.com/dotnet/roslyn/issues/48573")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMissingAfterNumericLiteral() { await VerifyAbsenceAsync( @" class C { void M() { var x = 1$$ } }"); } [WorkItem(48573, "https://github.com/dotnet/roslyn/issues/48573")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMissingAfterNumericLiteralAndDot() { await VerifyAbsenceAsync( @" class C { void M() { var x = 1.$$ } }"); } [WorkItem(48573, "https://github.com/dotnet/roslyn/issues/48573")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMissingAfterNumericLiteralDotAndSpace() { await VerifyAbsenceAsync( @" class C { void M() { var x = 1. $$ } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class WithKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterWith() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = goo with $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExpr() { await VerifyKeywordAsync(AddInsideMethod( @"var q = goo $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDottedName() { await VerifyKeywordAsync(AddInsideMethod( @"var q = goo.Current $$")); } [WorkItem(543041, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543041")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterVarInForLoop() { await VerifyAbsenceAsync(AddInsideMethod( @"for (var $$")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeFirstStringHole() { await VerifyAbsenceAsync(AddInsideMethod( @"var x = ""\{0}$$\{1}\{2}""")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBetweenStringHoles() { await VerifyAbsenceAsync(AddInsideMethod( @"var x = ""\{0}\{1}$$\{2}""")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStringHoles() { await VerifyAbsenceAsync(AddInsideMethod( @"var x = ""\{0}\{1}\{2}$$""")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLastStringHole() { await VerifyKeywordAsync(AddInsideMethod( @"var x = ""\{0}\{1}\{2}"" $$")); } [WorkItem(1736, "https://github.com/dotnet/roslyn/issues/1736")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotWithinNumericLiteral() { await VerifyAbsenceAsync(AddInsideMethod( @"var x = .$$0;")); } [WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAsync() { await VerifyAbsenceAsync( @" using System; class C { void Goo() { Bar(async $$ } void Bar(Func<int, string> f) { } }"); } [WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterMethodReference() { await VerifyAbsenceAsync( @" using System; class C { void M() { var v = Console.WriteLine $$"); } [WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAnonymousMethod() { await VerifyAbsenceAsync( @" using System; class C { void M() { Action a = delegate { } $$"); } [WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterLambda1() { await VerifyAbsenceAsync( @" using System; class C { void M() { Action b = (() => 0) $$"); } [WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterLambda2() { await VerifyAbsenceAsync( @" using System; class C { void M() { Action b = () => {} $$"); } [WorkItem(48573, "https://github.com/dotnet/roslyn/issues/48573")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMissingAfterNumericLiteral() { await VerifyAbsenceAsync( @" class C { void M() { var x = 1$$ } }"); } [WorkItem(48573, "https://github.com/dotnet/roslyn/issues/48573")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMissingAfterNumericLiteralAndDot() { await VerifyAbsenceAsync( @" class C { void M() { var x = 1.$$ } }"); } [WorkItem(48573, "https://github.com/dotnet/roslyn/issues/48573")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMissingAfterNumericLiteralDotAndSpace() { await VerifyAbsenceAsync( @" class C { void M() { var x = 1. $$ } }"); } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/Operations/AdjustNewLinesOperation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting.Rules { /// <summary> /// indicate how many lines are needed between two tokens /// </summary> internal sealed class AdjustNewLinesOperation { internal AdjustNewLinesOperation(int line, AdjustNewLinesOption option) { Contract.ThrowIfFalse(option != AdjustNewLinesOption.ForceLines || line > 0); Contract.ThrowIfFalse(option != AdjustNewLinesOption.PreserveLines || line >= 0); Contract.ThrowIfFalse(option != AdjustNewLinesOption.ForceLinesIfOnSingleLine || line > 0); this.Line = line; this.Option = option; } public int Line { get; } public AdjustNewLinesOption Option { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting.Rules { /// <summary> /// indicate how many lines are needed between two tokens /// </summary> internal sealed class AdjustNewLinesOperation { internal AdjustNewLinesOperation(int line, AdjustNewLinesOption option) { Contract.ThrowIfFalse(option != AdjustNewLinesOption.ForceLines || line > 0); Contract.ThrowIfFalse(option != AdjustNewLinesOption.PreserveLines || line >= 0); Contract.ThrowIfFalse(option != AdjustNewLinesOption.ForceLinesIfOnSingleLine || line > 0); this.Line = line; this.Option = option; } public int Line { get; } public AdjustNewLinesOption Option { get; } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Workspaces/Core/Portable/CodeStyle/CodeStyleOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.CodeStyle { /// <inheritdoc cref="CodeStyleOptions2"/> public class CodeStyleOptions { /// <inheritdoc cref="CodeStyleOptions2.QualifyFieldAccess"/> public static readonly PerLanguageOption<CodeStyleOption<bool>> QualifyFieldAccess = CodeStyleOptions2.QualifyFieldAccess.ToPublicOption(); /// <inheritdoc cref="CodeStyleOptions2.QualifyPropertyAccess"/> public static readonly PerLanguageOption<CodeStyleOption<bool>> QualifyPropertyAccess = CodeStyleOptions2.QualifyPropertyAccess.ToPublicOption(); /// <inheritdoc cref="CodeStyleOptions2.QualifyMethodAccess"/> public static readonly PerLanguageOption<CodeStyleOption<bool>> QualifyMethodAccess = CodeStyleOptions2.QualifyMethodAccess.ToPublicOption(); /// <inheritdoc cref="CodeStyleOptions2.QualifyEventAccess"/> public static readonly PerLanguageOption<CodeStyleOption<bool>> QualifyEventAccess = CodeStyleOptions2.QualifyEventAccess.ToPublicOption(); /// <inheritdoc cref="CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration"/> public static readonly PerLanguageOption<CodeStyleOption<bool>> PreferIntrinsicPredefinedTypeKeywordInDeclaration = CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration.ToPublicOption(); /// <inheritdoc cref="CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess"/> public static readonly PerLanguageOption<CodeStyleOption<bool>> PreferIntrinsicPredefinedTypeKeywordInMemberAccess = CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess.ToPublicOption(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.CodeStyle { /// <inheritdoc cref="CodeStyleOptions2"/> public class CodeStyleOptions { /// <inheritdoc cref="CodeStyleOptions2.QualifyFieldAccess"/> public static readonly PerLanguageOption<CodeStyleOption<bool>> QualifyFieldAccess = CodeStyleOptions2.QualifyFieldAccess.ToPublicOption(); /// <inheritdoc cref="CodeStyleOptions2.QualifyPropertyAccess"/> public static readonly PerLanguageOption<CodeStyleOption<bool>> QualifyPropertyAccess = CodeStyleOptions2.QualifyPropertyAccess.ToPublicOption(); /// <inheritdoc cref="CodeStyleOptions2.QualifyMethodAccess"/> public static readonly PerLanguageOption<CodeStyleOption<bool>> QualifyMethodAccess = CodeStyleOptions2.QualifyMethodAccess.ToPublicOption(); /// <inheritdoc cref="CodeStyleOptions2.QualifyEventAccess"/> public static readonly PerLanguageOption<CodeStyleOption<bool>> QualifyEventAccess = CodeStyleOptions2.QualifyEventAccess.ToPublicOption(); /// <inheritdoc cref="CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration"/> public static readonly PerLanguageOption<CodeStyleOption<bool>> PreferIntrinsicPredefinedTypeKeywordInDeclaration = CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration.ToPublicOption(); /// <inheritdoc cref="CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess"/> public static readonly PerLanguageOption<CodeStyleOption<bool>> PreferIntrinsicPredefinedTypeKeywordInMemberAccess = CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess.ToPublicOption(); } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Features/Core/Portable/Wrapping/WrapItemsAction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using static Microsoft.CodeAnalysis.CodeActions.CodeAction; namespace Microsoft.CodeAnalysis.Wrapping { /// <summary> /// Code action for actually wrapping items. Provided as a special subclass because it will /// also update the wrapping most-recently-used list when the code action is actually /// invoked. /// </summary> internal class WrapItemsAction : DocumentChangeAction { // Keeps track of the invoked code actions. That way we can prioritize those code actions // in the future since they're more likely the ones the user wants. This is important as // we have 9 different code actions offered (3 major groups, with 3 actions per group). // It's likely the user will just pick from a few of these. So we'd like the ones they // choose to be prioritized accordingly. private static ImmutableArray<string> s_mruTitles = ImmutableArray<string>.Empty; public string ParentTitle { get; } public string SortTitle { get; } // Make our code action low priority. This option will be offered *a lot*, and // much of the time will not be something the user particularly wants to do. // It should be offered after all other normal refactorings. // // This value is only relevant if this code action is the only one in its group, // and it ends up getting inlined as a top-level-action that is offered. internal override CodeActionPriority Priority => CodeActionPriority.Low; public WrapItemsAction(string title, string parentTitle, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { ParentTitle = parentTitle; SortTitle = parentTitle + "_" + title; } protected override Task<IEnumerable<CodeActionOperation>> ComputePreviewOperationsAsync(CancellationToken cancellationToken) { // For preview, we don't want to compute the normal operations. Specifically, we don't // want to compute the stateful operation that tracks which code action was triggered. return base.ComputeOperationsAsync(cancellationToken); } protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken) { var operations = await base.ComputeOperationsAsync(cancellationToken).ConfigureAwait(false); var operationsList = operations.ToList(); operationsList.Add(new RecordCodeActionOperation(SortTitle, ParentTitle)); return operationsList; } public static ImmutableArray<CodeAction> SortActionsByMostRecentlyUsed(ImmutableArray<CodeAction> codeActions) => SortByMostRecentlyUsed(codeActions, s_mruTitles, a => GetSortTitle(a)); public static ImmutableArray<T> SortByMostRecentlyUsed<T>( ImmutableArray<T> items, ImmutableArray<string> mostRecentlyUsedKeys, Func<T, string> getKey) { return items.Sort((d1, d2) => { var mruIndex1 = mostRecentlyUsedKeys.IndexOf(getKey(d1)); var mruIndex2 = mostRecentlyUsedKeys.IndexOf(getKey(d2)); // If both are in the mru, prefer the one earlier on. if (mruIndex1 >= 0 && mruIndex2 >= 0) return mruIndex1 - mruIndex2; // if either is in the mru, and the other is not, then the mru item is preferred. if (mruIndex1 >= 0) return -1; if (mruIndex2 >= 0) return 1; // Neither are in the mru. Sort them based on their original locations. var index1 = items.IndexOf(d1); var index2 = items.IndexOf(d2); // Note: we don't return 0 here as ImmutableArray.Sort is not stable. return index1 - index2; }); } private static string GetSortTitle(CodeAction codeAction) => (codeAction as WrapItemsAction)?.SortTitle ?? codeAction.Title; private class RecordCodeActionOperation : CodeActionOperation { private readonly string _sortTitle; private readonly string _parentTitle; public RecordCodeActionOperation(string sortTitle, string parentTitle) { _sortTitle = sortTitle; _parentTitle = parentTitle; } internal override bool ApplyDuringTests => false; public override void Apply(Workspace workspace, CancellationToken cancellationToken) { // Record both the sortTitle of the nested action and the tile of the parent // action. This way we any invocation of a code action helps prioritize both // the parent lists and the nested lists. s_mruTitles = s_mruTitles.Remove(_sortTitle).Remove(_parentTitle) .Insert(0, _sortTitle).Insert(0, _parentTitle); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using static Microsoft.CodeAnalysis.CodeActions.CodeAction; namespace Microsoft.CodeAnalysis.Wrapping { /// <summary> /// Code action for actually wrapping items. Provided as a special subclass because it will /// also update the wrapping most-recently-used list when the code action is actually /// invoked. /// </summary> internal class WrapItemsAction : DocumentChangeAction { // Keeps track of the invoked code actions. That way we can prioritize those code actions // in the future since they're more likely the ones the user wants. This is important as // we have 9 different code actions offered (3 major groups, with 3 actions per group). // It's likely the user will just pick from a few of these. So we'd like the ones they // choose to be prioritized accordingly. private static ImmutableArray<string> s_mruTitles = ImmutableArray<string>.Empty; public string ParentTitle { get; } public string SortTitle { get; } // Make our code action low priority. This option will be offered *a lot*, and // much of the time will not be something the user particularly wants to do. // It should be offered after all other normal refactorings. // // This value is only relevant if this code action is the only one in its group, // and it ends up getting inlined as a top-level-action that is offered. internal override CodeActionPriority Priority => CodeActionPriority.Low; public WrapItemsAction(string title, string parentTitle, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { ParentTitle = parentTitle; SortTitle = parentTitle + "_" + title; } protected override Task<IEnumerable<CodeActionOperation>> ComputePreviewOperationsAsync(CancellationToken cancellationToken) { // For preview, we don't want to compute the normal operations. Specifically, we don't // want to compute the stateful operation that tracks which code action was triggered. return base.ComputeOperationsAsync(cancellationToken); } protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken) { var operations = await base.ComputeOperationsAsync(cancellationToken).ConfigureAwait(false); var operationsList = operations.ToList(); operationsList.Add(new RecordCodeActionOperation(SortTitle, ParentTitle)); return operationsList; } public static ImmutableArray<CodeAction> SortActionsByMostRecentlyUsed(ImmutableArray<CodeAction> codeActions) => SortByMostRecentlyUsed(codeActions, s_mruTitles, a => GetSortTitle(a)); public static ImmutableArray<T> SortByMostRecentlyUsed<T>( ImmutableArray<T> items, ImmutableArray<string> mostRecentlyUsedKeys, Func<T, string> getKey) { return items.Sort((d1, d2) => { var mruIndex1 = mostRecentlyUsedKeys.IndexOf(getKey(d1)); var mruIndex2 = mostRecentlyUsedKeys.IndexOf(getKey(d2)); // If both are in the mru, prefer the one earlier on. if (mruIndex1 >= 0 && mruIndex2 >= 0) return mruIndex1 - mruIndex2; // if either is in the mru, and the other is not, then the mru item is preferred. if (mruIndex1 >= 0) return -1; if (mruIndex2 >= 0) return 1; // Neither are in the mru. Sort them based on their original locations. var index1 = items.IndexOf(d1); var index2 = items.IndexOf(d2); // Note: we don't return 0 here as ImmutableArray.Sort is not stable. return index1 - index2; }); } private static string GetSortTitle(CodeAction codeAction) => (codeAction as WrapItemsAction)?.SortTitle ?? codeAction.Title; private class RecordCodeActionOperation : CodeActionOperation { private readonly string _sortTitle; private readonly string _parentTitle; public RecordCodeActionOperation(string sortTitle, string parentTitle) { _sortTitle = sortTitle; _parentTitle = parentTitle; } internal override bool ApplyDuringTests => false; public override void Apply(Workspace workspace, CancellationToken cancellationToken) { // Record both the sortTitle of the nested action and the tile of the parent // action. This way we any invocation of a code action helps prioritize both // the parent lists and the nested lists. s_mruTitles = s_mruTitles.Remove(_sortTitle).Remove(_parentTitle) .Insert(0, _sortTitle).Insert(0, _parentTitle); } } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Workspaces/Core/Portable/Shared/Utilities/EditorBrowsableHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal static class EditorBrowsableHelpers { public struct EditorBrowsableInfo { public Compilation Compilation { get; } public INamedTypeSymbol? HideModuleNameAttribute { get; } public IMethodSymbol? EditorBrowsableAttributeConstructor { get; } public ImmutableArray<IMethodSymbol> TypeLibTypeAttributeConstructors { get; } public ImmutableArray<IMethodSymbol> TypeLibFuncAttributeConstructors { get; } public ImmutableArray<IMethodSymbol> TypeLibVarAttributeConstructors { get; } public bool IsDefault => Compilation == null; public EditorBrowsableInfo(Compilation compilation) { Compilation = compilation; HideModuleNameAttribute = compilation.HideModuleNameAttribute(); EditorBrowsableAttributeConstructor = GetSpecialEditorBrowsableAttributeConstructor(compilation); TypeLibTypeAttributeConstructors = GetSpecialTypeLibTypeAttributeConstructors(compilation); TypeLibFuncAttributeConstructors = GetSpecialTypeLibFuncAttributeConstructors(compilation); TypeLibVarAttributeConstructors = GetSpecialTypeLibVarAttributeConstructors(compilation); } } /// <summary> /// Finds the constructor which takes exactly one argument, which must be of type EditorBrowsableState. /// It does not require that the EditorBrowsableAttribute and EditorBrowsableState types be those /// shipped by Microsoft, but it does demand the types found follow the expected pattern. If at any /// point that pattern appears to be violated, return null to indicate that an appropriate constructor /// could not be found. /// </summary> public static IMethodSymbol? GetSpecialEditorBrowsableAttributeConstructor(Compilation compilation) { var editorBrowsableAttributeType = compilation.EditorBrowsableAttributeType(); var editorBrowsableStateType = compilation.EditorBrowsableStateType(); if (editorBrowsableAttributeType == null || editorBrowsableStateType == null) { return null; } var candidateConstructors = editorBrowsableAttributeType.Constructors .Where(c => c.Parameters.Length == 1 && Equals(c.Parameters[0].Type, editorBrowsableStateType)); // Ensure the constructor adheres to the expected EditorBrowsable pattern candidateConstructors = candidateConstructors.Where(c => (!c.IsVararg && !c.Parameters[0].IsRefOrOut() && !c.Parameters[0].CustomModifiers.Any())); // If there are multiple constructors that look correct then the discovered types do not match the // expected pattern, so return null. if (candidateConstructors.Count() <= 1) { return candidateConstructors.FirstOrDefault(); } else { return null; } } public static ImmutableArray<IMethodSymbol> GetSpecialTypeLibTypeAttributeConstructors(Compilation compilation) { return GetSpecialTypeLibAttributeConstructorsWorker( compilation, "System.Runtime.InteropServices.TypeLibTypeAttribute", "System.Runtime.InteropServices.TypeLibTypeFlags"); } public static ImmutableArray<IMethodSymbol> GetSpecialTypeLibFuncAttributeConstructors(Compilation compilation) { return GetSpecialTypeLibAttributeConstructorsWorker( compilation, "System.Runtime.InteropServices.TypeLibFuncAttribute", "System.Runtime.InteropServices.TypeLibFuncFlags"); } public static ImmutableArray<IMethodSymbol> GetSpecialTypeLibVarAttributeConstructors(Compilation compilation) { return GetSpecialTypeLibAttributeConstructorsWorker( compilation, "System.Runtime.InteropServices.TypeLibVarAttribute", "System.Runtime.InteropServices.TypeLibVarFlags"); } /// <summary> /// The TypeLib*Attribute classes that accept TypeLib*Flags with FHidden as an option all have two constructors, /// one accepting a TypeLib*Flags and the other a short. This methods gets those two constructor symbols for any /// of these attribute classes. It does not require that the either of these types be those shipped by Microsoft, /// but it does demand the types found follow the expected pattern. If at any point that pattern appears to be /// violated, return an empty enumerable to indicate that no appropriate constructors were found. /// </summary> private static ImmutableArray<IMethodSymbol> GetSpecialTypeLibAttributeConstructorsWorker( Compilation compilation, string attributeMetadataName, string flagsMetadataName) { var typeLibAttributeType = compilation.GetTypeByMetadataName(attributeMetadataName); var typeLibFlagsType = compilation.GetTypeByMetadataName(flagsMetadataName); var shortType = compilation.GetSpecialType(SpecialType.System_Int16); if (typeLibAttributeType == null || typeLibFlagsType == null || shortType == null) { return ImmutableArray<IMethodSymbol>.Empty; } var candidateConstructors = typeLibAttributeType.Constructors .Where(c => c.Parameters.Length == 1 && (Equals(c.Parameters[0].Type, typeLibFlagsType) || Equals(c.Parameters[0].Type, shortType))); candidateConstructors = candidateConstructors.Where(c => (!c.IsVararg && !c.Parameters[0].IsRefOrOut() && !c.Parameters[0].CustomModifiers.Any())); return candidateConstructors.ToImmutableArrayOrEmpty(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal static class EditorBrowsableHelpers { public struct EditorBrowsableInfo { public Compilation Compilation { get; } public INamedTypeSymbol? HideModuleNameAttribute { get; } public IMethodSymbol? EditorBrowsableAttributeConstructor { get; } public ImmutableArray<IMethodSymbol> TypeLibTypeAttributeConstructors { get; } public ImmutableArray<IMethodSymbol> TypeLibFuncAttributeConstructors { get; } public ImmutableArray<IMethodSymbol> TypeLibVarAttributeConstructors { get; } public bool IsDefault => Compilation == null; public EditorBrowsableInfo(Compilation compilation) { Compilation = compilation; HideModuleNameAttribute = compilation.HideModuleNameAttribute(); EditorBrowsableAttributeConstructor = GetSpecialEditorBrowsableAttributeConstructor(compilation); TypeLibTypeAttributeConstructors = GetSpecialTypeLibTypeAttributeConstructors(compilation); TypeLibFuncAttributeConstructors = GetSpecialTypeLibFuncAttributeConstructors(compilation); TypeLibVarAttributeConstructors = GetSpecialTypeLibVarAttributeConstructors(compilation); } } /// <summary> /// Finds the constructor which takes exactly one argument, which must be of type EditorBrowsableState. /// It does not require that the EditorBrowsableAttribute and EditorBrowsableState types be those /// shipped by Microsoft, but it does demand the types found follow the expected pattern. If at any /// point that pattern appears to be violated, return null to indicate that an appropriate constructor /// could not be found. /// </summary> public static IMethodSymbol? GetSpecialEditorBrowsableAttributeConstructor(Compilation compilation) { var editorBrowsableAttributeType = compilation.EditorBrowsableAttributeType(); var editorBrowsableStateType = compilation.EditorBrowsableStateType(); if (editorBrowsableAttributeType == null || editorBrowsableStateType == null) { return null; } var candidateConstructors = editorBrowsableAttributeType.Constructors .Where(c => c.Parameters.Length == 1 && Equals(c.Parameters[0].Type, editorBrowsableStateType)); // Ensure the constructor adheres to the expected EditorBrowsable pattern candidateConstructors = candidateConstructors.Where(c => (!c.IsVararg && !c.Parameters[0].IsRefOrOut() && !c.Parameters[0].CustomModifiers.Any())); // If there are multiple constructors that look correct then the discovered types do not match the // expected pattern, so return null. if (candidateConstructors.Count() <= 1) { return candidateConstructors.FirstOrDefault(); } else { return null; } } public static ImmutableArray<IMethodSymbol> GetSpecialTypeLibTypeAttributeConstructors(Compilation compilation) { return GetSpecialTypeLibAttributeConstructorsWorker( compilation, "System.Runtime.InteropServices.TypeLibTypeAttribute", "System.Runtime.InteropServices.TypeLibTypeFlags"); } public static ImmutableArray<IMethodSymbol> GetSpecialTypeLibFuncAttributeConstructors(Compilation compilation) { return GetSpecialTypeLibAttributeConstructorsWorker( compilation, "System.Runtime.InteropServices.TypeLibFuncAttribute", "System.Runtime.InteropServices.TypeLibFuncFlags"); } public static ImmutableArray<IMethodSymbol> GetSpecialTypeLibVarAttributeConstructors(Compilation compilation) { return GetSpecialTypeLibAttributeConstructorsWorker( compilation, "System.Runtime.InteropServices.TypeLibVarAttribute", "System.Runtime.InteropServices.TypeLibVarFlags"); } /// <summary> /// The TypeLib*Attribute classes that accept TypeLib*Flags with FHidden as an option all have two constructors, /// one accepting a TypeLib*Flags and the other a short. This methods gets those two constructor symbols for any /// of these attribute classes. It does not require that the either of these types be those shipped by Microsoft, /// but it does demand the types found follow the expected pattern. If at any point that pattern appears to be /// violated, return an empty enumerable to indicate that no appropriate constructors were found. /// </summary> private static ImmutableArray<IMethodSymbol> GetSpecialTypeLibAttributeConstructorsWorker( Compilation compilation, string attributeMetadataName, string flagsMetadataName) { var typeLibAttributeType = compilation.GetTypeByMetadataName(attributeMetadataName); var typeLibFlagsType = compilation.GetTypeByMetadataName(flagsMetadataName); var shortType = compilation.GetSpecialType(SpecialType.System_Int16); if (typeLibAttributeType == null || typeLibFlagsType == null || shortType == null) { return ImmutableArray<IMethodSymbol>.Empty; } var candidateConstructors = typeLibAttributeType.Constructors .Where(c => c.Parameters.Length == 1 && (Equals(c.Parameters[0].Type, typeLibFlagsType) || Equals(c.Parameters[0].Type, shortType))); candidateConstructors = candidateConstructors.Where(c => (!c.IsVararg && !c.Parameters[0].IsRefOrOut() && !c.Parameters[0].CustomModifiers.Any())); return candidateConstructors.ToImmutableArrayOrEmpty(); } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Compilers/CSharp/Portable/Binder/BinderFactory.NodeUsage.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.CSharp { internal partial class BinderFactory { internal enum NodeUsage : byte { Normal = 0, MethodTypeParameters = 1 << 0, MethodBody = 1 << 1, ConstructorBodyOrInitializer = 1 << 0, AccessorBody = 1 << 0, OperatorBody = 1 << 0, NamedTypeBodyOrTypeParameters = 1 << 1, // Cannot share the value with ConstructorBodyOrInitializer NamedTypeBaseListOrParameterList = 1 << 2, // Cannot share the value with ConstructorBodyOrInitializer NamespaceBody = 1 << 0, NamespaceUsings = 1 << 1, CompilationUnitUsings = 1 << 0, CompilationUnitScript = 1 << 1, CompilationUnitScriptUsings = 1 << 2, DocumentationCommentParameter = 1 << 0, DocumentationCommentTypeParameter = 1 << 1, DocumentationCommentTypeParameterReference = 1 << 2, CrefParameterOrReturnType = 1 << 0, } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.CSharp { internal partial class BinderFactory { internal enum NodeUsage : byte { Normal = 0, MethodTypeParameters = 1 << 0, MethodBody = 1 << 1, ConstructorBodyOrInitializer = 1 << 0, AccessorBody = 1 << 0, OperatorBody = 1 << 0, NamedTypeBodyOrTypeParameters = 1 << 1, // Cannot share the value with ConstructorBodyOrInitializer NamedTypeBaseListOrParameterList = 1 << 2, // Cannot share the value with ConstructorBodyOrInitializer NamespaceBody = 1 << 0, NamespaceUsings = 1 << 1, CompilationUnitUsings = 1 << 0, CompilationUnitScript = 1 << 1, CompilationUnitScriptUsings = 1 << 2, DocumentationCommentParameter = 1 << 0, DocumentationCommentTypeParameter = 1 << 1, DocumentationCommentTypeParameterReference = 1 << 2, CrefParameterOrReturnType = 1 << 0, } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Features/Core/Portable/DocumentationComments/AbstractDocumentationCommentSnippetService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.DocumentationComments { internal abstract class AbstractDocumentationCommentSnippetService<TDocumentationComment, TMemberNode> : IDocumentationCommentSnippetService where TDocumentationComment : SyntaxNode, IStructuredTriviaSyntax where TMemberNode : SyntaxNode { protected abstract TMemberNode? GetContainingMember(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken); protected abstract bool SupportsDocumentationComments(TMemberNode member); protected abstract bool HasDocumentationComment(TMemberNode member); protected abstract int GetPrecedingDocumentationCommentCount(TMemberNode member); protected abstract bool IsMemberDeclaration(TMemberNode member); protected abstract List<string> GetDocumentationCommentStubLines(TMemberNode member); protected abstract SyntaxToken GetTokenToRight(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken); protected abstract SyntaxToken GetTokenToLeft(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken); protected abstract bool IsDocCommentNewLine(SyntaxToken token); protected abstract bool IsEndOfLineTrivia(SyntaxTrivia trivia); protected abstract bool IsSingleExteriorTrivia(TDocumentationComment documentationComment, bool allowWhitespace = false); protected abstract bool EndsWithSingleExteriorTrivia(TDocumentationComment? documentationComment); protected abstract bool IsMultilineDocComment(TDocumentationComment? documentationComment); protected abstract bool HasSkippedTrailingTrivia(SyntaxToken token); public abstract string DocumentationCommentCharacter { get; } protected abstract string ExteriorTriviaText { get; } protected abstract bool AddIndent { get; } public DocumentationCommentSnippet? GetDocumentationCommentSnippetOnCharacterTyped( SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken) { if (!options.GetOption(DocumentationCommentOptions.AutoXmlDocCommentGeneration)) { return null; } // Only generate if the position is immediately after '///', // and that is the only documentation comment on the target member. var token = syntaxTree.GetRoot(cancellationToken).FindToken(position, findInsideTrivia: true); if (position != token.SpanStart) { return null; } var lines = GetDocumentationCommentLines(token, text, options, out var indentText); if (lines == null) { return null; } var newLine = options.GetOption(FormattingOptions.NewLine); var lastLine = lines[^1]; lines[^1] = lastLine.Substring(0, lastLine.Length - newLine.Length); var comments = string.Join(string.Empty, lines); var offset = lines[0].Length + lines[1].Length - newLine.Length; // When typing we don't replace a token, but insert before it var replaceSpan = new TextSpan(token.Span.Start, 0); return new DocumentationCommentSnippet(replaceSpan, comments, offset); } private List<string>? GetDocumentationCommentLines(SyntaxToken token, SourceText text, DocumentOptionSet options, out string? indentText) { indentText = null; var documentationComment = token.GetAncestor<TDocumentationComment>(); if (documentationComment == null || !IsSingleExteriorTrivia(documentationComment)) { return null; } var targetMember = GetTargetMember(documentationComment); // Ensure that the target member is only preceded by a single documentation comment (i.e. our ///). if (targetMember == null || GetPrecedingDocumentationCommentCount(targetMember) != 1) { return null; } var line = text.Lines.GetLineFromPosition(documentationComment.FullSpan.Start); if (line.IsEmptyOrWhitespace()) { return null; } var lines = GetDocumentationCommentStubLines(targetMember); Debug.Assert(lines.Count > 2); var newLine = options.GetOption(FormattingOptions.NewLine); AddLineBreaks(lines, newLine); // Shave off initial three slashes lines[0] = lines[0][3..]; // Add indents var lineOffset = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(options.GetOption(FormattingOptions.TabSize)); indentText = lineOffset.CreateIndentationString(options.GetOption(FormattingOptions.UseTabs), options.GetOption(FormattingOptions.TabSize)); IndentLines(lines, indentText); return lines; } public bool IsValidTargetMember(SyntaxTree syntaxTree, SourceText text, int position, CancellationToken cancellationToken) => GetTargetMember(syntaxTree, text, position, cancellationToken) != null; private TMemberNode? GetTargetMember(SyntaxTree syntaxTree, SourceText text, int position, CancellationToken cancellationToken) { var member = GetContainingMember(syntaxTree, position, cancellationToken); if (member == null) { return null; } if (!SupportsDocumentationComments(member) || HasDocumentationComment(member)) { return null; } var startPosition = member.GetFirstToken().SpanStart; var line = text.Lines.GetLineFromPosition(startPosition); var lineOffset = line.GetFirstNonWhitespaceOffset(); if (!lineOffset.HasValue || line.Start + lineOffset.Value < startPosition) { return null; } return member; } private TMemberNode? GetTargetMember(TDocumentationComment documentationComment) { var targetMember = documentationComment.ParentTrivia.Token.GetAncestor<TMemberNode>(); if (targetMember == null || !IsMemberDeclaration(targetMember)) { return null; } if (targetMember.SpanStart < documentationComment.SpanStart) { return null; } return targetMember; } private static void AddLineBreaks(IList<string> lines, string newLine) { for (var i = 0; i < lines.Count; i++) { lines[i] = lines[i] + newLine; } } private static void IndentLines(List<string> lines, string? indentText) { for (var i = 1; i < lines.Count; i++) { lines[i] = indentText + lines[i]; } } public DocumentationCommentSnippet? GetDocumentationCommentSnippetOnEnterTyped(SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken) { // Don't attempt to generate a new XML doc comment on ENTER if the option to auto-generate // them isn't set. Regardless of the option, we should generate exterior trivia (i.e. /// or ''') // on ENTER inside an existing XML doc comment. if (options.GetOption(DocumentationCommentOptions.AutoXmlDocCommentGeneration)) { var result = GenerateDocumentationCommentAfterEnter(syntaxTree, text, position, options, cancellationToken); if (result != null) { return result; } } return GenerateExteriorTriviaAfterEnter(syntaxTree, text, position, options, cancellationToken); } private DocumentationCommentSnippet? GenerateDocumentationCommentAfterEnter(SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken) { // Find the documentation comment before the new line that was just pressed var token = GetTokenToLeft(syntaxTree, position, cancellationToken); if (!IsDocCommentNewLine(token)) { return null; } var newLine = options.GetOption(FormattingOptions.NewLine); var lines = GetDocumentationCommentLines(token, text, options, out var indentText); if (lines == null) { return null; } var newText = string.Join(string.Empty, lines); var offset = lines[0].Length + lines[1].Length - newLine.Length; // Shave off final line break or add trailing indent if necessary var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false); if (IsEndOfLineTrivia(trivia)) { newText = newText.Substring(0, newText.Length - newLine.Length); } else { newText += indentText; } var replaceSpan = token.Span; var currentLine = text.Lines.GetLineFromPosition(position); var currentLinePosition = currentLine.GetFirstNonWhitespacePosition(); if (currentLinePosition.HasValue) { var start = token.Span.Start; replaceSpan = new TextSpan(start, currentLinePosition.Value - start); } return new DocumentationCommentSnippet(replaceSpan, newText, offset); } public DocumentationCommentSnippet? GetDocumentationCommentSnippetOnCommandInvoke(SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken) { var targetMember = GetTargetMember(syntaxTree, text, position, cancellationToken); if (targetMember == null) { return null; } var token = targetMember.GetFirstToken(); var startPosition = token.SpanStart; var line = text.Lines.GetLineFromPosition(startPosition); Debug.Assert(!line.IsEmptyOrWhitespace()); var lines = GetDocumentationCommentStubLines(targetMember); Debug.Assert(lines.Count > 2); var newLine = options.GetOption(FormattingOptions.NewLine); AddLineBreaks(lines, newLine); // Add indents var lineOffset = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(options.GetOption(FormattingOptions.TabSize)); Debug.Assert(line.Start + lineOffset == startPosition); var indentText = lineOffset.CreateIndentationString(options.GetOption(FormattingOptions.UseTabs), options.GetOption(FormattingOptions.TabSize)); IndentLines(lines, indentText); lines[^1] = lines[^1] + indentText; var comments = string.Join(string.Empty, lines); var offset = lines[0].Length + lines[1].Length - newLine.Length; // For a command we don't replace a token, but insert before it var replaceSpan = new TextSpan(token.Span.Start, 0); return new DocumentationCommentSnippet(replaceSpan, comments, offset); } private DocumentationCommentSnippet? GenerateExteriorTriviaAfterEnter(SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken) { // Find the documentation comment before the new line that was just pressed var token = GetTokenToLeft(syntaxTree, position, cancellationToken); if (!IsDocCommentNewLine(token) && HasSkippedTrailingTrivia(token)) { // See PressingEnter_InsertSlashes11 for an example of // a case where multiple skipped tokens trivia appear at the same position. // In that case, we need to ask for the token from the next position over. token = GetTokenToLeft(syntaxTree, position + 1, cancellationToken); if (!IsDocCommentNewLine(token)) { return null; } } var currentLine = text.Lines.GetLineFromPosition(position); if (currentLine.LineNumber == 0) { return null; } // Previous line must begin with a doc comment var previousLine = text.Lines[currentLine.LineNumber - 1]; var previousLineText = previousLine.ToString().Trim(); if (!previousLineText.StartsWith(ExteriorTriviaText, StringComparison.Ordinal)) { return null; } var nextLineStartsWithDocComment = text.Lines.Count > currentLine.LineNumber + 1 && text.Lines[currentLine.LineNumber + 1].ToString().Trim().StartsWith(ExteriorTriviaText, StringComparison.Ordinal); // if previous line has only exterior trivia, current line is empty and next line doesn't begin // with exterior trivia then stop inserting auto generated xml doc string if (previousLineText.Equals(ExteriorTriviaText) && string.IsNullOrWhiteSpace(currentLine.ToString()) && !nextLineStartsWithDocComment) { return null; } var documentationComment = token.GetAncestor<TDocumentationComment>(); if (IsMultilineDocComment(documentationComment)) { return null; } if (EndsWithSingleExteriorTrivia(documentationComment) && currentLine.IsEmptyOrWhitespace() && !nextLineStartsWithDocComment) { return null; } return GetDocumentationCommentSnippetFromPreviousLine(options, currentLine, previousLine); } public DocumentationCommentSnippet GetDocumentationCommentSnippetFromPreviousLine(DocumentOptionSet options, TextLine currentLine, TextLine previousLine) { var insertionText = CreateInsertionTextFromPreviousLine(previousLine, options); var firstNonWhitespaceOffset = currentLine.GetFirstNonWhitespaceOffset(); var replaceSpan = firstNonWhitespaceOffset != null ? TextSpan.FromBounds(currentLine.Start, currentLine.Start + firstNonWhitespaceOffset.Value) : currentLine.Span; return new DocumentationCommentSnippet(replaceSpan, insertionText, insertionText.Length); } private string CreateInsertionTextFromPreviousLine(TextLine previousLine, DocumentOptionSet options) { var useTabs = options.GetOption(FormattingOptions.UseTabs); var tabSize = options.GetOption(FormattingOptions.TabSize); var previousLineText = previousLine.ToString(); var firstNonWhitespaceColumn = previousLineText.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(tabSize); var trimmedPreviousLine = previousLineText.Trim(); Debug.Assert(trimmedPreviousLine.StartsWith(ExteriorTriviaText), "Unexpected: previous line does not begin with doc comment exterior trivia."); // skip exterior trivia. trimmedPreviousLine = trimmedPreviousLine[3..]; var firstNonWhitespaceOffsetInPreviousXmlText = trimmedPreviousLine.GetFirstNonWhitespaceOffset(); var extraIndent = firstNonWhitespaceOffsetInPreviousXmlText != null ? trimmedPreviousLine.Substring(0, firstNonWhitespaceOffsetInPreviousXmlText.Value) : " "; return firstNonWhitespaceColumn.CreateIndentationString(useTabs, tabSize) + ExteriorTriviaText + extraIndent; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.DocumentationComments { internal abstract class AbstractDocumentationCommentSnippetService<TDocumentationComment, TMemberNode> : IDocumentationCommentSnippetService where TDocumentationComment : SyntaxNode, IStructuredTriviaSyntax where TMemberNode : SyntaxNode { protected abstract TMemberNode? GetContainingMember(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken); protected abstract bool SupportsDocumentationComments(TMemberNode member); protected abstract bool HasDocumentationComment(TMemberNode member); protected abstract int GetPrecedingDocumentationCommentCount(TMemberNode member); protected abstract bool IsMemberDeclaration(TMemberNode member); protected abstract List<string> GetDocumentationCommentStubLines(TMemberNode member); protected abstract SyntaxToken GetTokenToRight(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken); protected abstract SyntaxToken GetTokenToLeft(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken); protected abstract bool IsDocCommentNewLine(SyntaxToken token); protected abstract bool IsEndOfLineTrivia(SyntaxTrivia trivia); protected abstract bool IsSingleExteriorTrivia(TDocumentationComment documentationComment, bool allowWhitespace = false); protected abstract bool EndsWithSingleExteriorTrivia(TDocumentationComment? documentationComment); protected abstract bool IsMultilineDocComment(TDocumentationComment? documentationComment); protected abstract bool HasSkippedTrailingTrivia(SyntaxToken token); public abstract string DocumentationCommentCharacter { get; } protected abstract string ExteriorTriviaText { get; } protected abstract bool AddIndent { get; } public DocumentationCommentSnippet? GetDocumentationCommentSnippetOnCharacterTyped( SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken) { if (!options.GetOption(DocumentationCommentOptions.AutoXmlDocCommentGeneration)) { return null; } // Only generate if the position is immediately after '///', // and that is the only documentation comment on the target member. var token = syntaxTree.GetRoot(cancellationToken).FindToken(position, findInsideTrivia: true); if (position != token.SpanStart) { return null; } var lines = GetDocumentationCommentLines(token, text, options, out var indentText); if (lines == null) { return null; } var newLine = options.GetOption(FormattingOptions.NewLine); var lastLine = lines[^1]; lines[^1] = lastLine.Substring(0, lastLine.Length - newLine.Length); var comments = string.Join(string.Empty, lines); var offset = lines[0].Length + lines[1].Length - newLine.Length; // When typing we don't replace a token, but insert before it var replaceSpan = new TextSpan(token.Span.Start, 0); return new DocumentationCommentSnippet(replaceSpan, comments, offset); } private List<string>? GetDocumentationCommentLines(SyntaxToken token, SourceText text, DocumentOptionSet options, out string? indentText) { indentText = null; var documentationComment = token.GetAncestor<TDocumentationComment>(); if (documentationComment == null || !IsSingleExteriorTrivia(documentationComment)) { return null; } var targetMember = GetTargetMember(documentationComment); // Ensure that the target member is only preceded by a single documentation comment (i.e. our ///). if (targetMember == null || GetPrecedingDocumentationCommentCount(targetMember) != 1) { return null; } var line = text.Lines.GetLineFromPosition(documentationComment.FullSpan.Start); if (line.IsEmptyOrWhitespace()) { return null; } var lines = GetDocumentationCommentStubLines(targetMember); Debug.Assert(lines.Count > 2); var newLine = options.GetOption(FormattingOptions.NewLine); AddLineBreaks(lines, newLine); // Shave off initial three slashes lines[0] = lines[0][3..]; // Add indents var lineOffset = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(options.GetOption(FormattingOptions.TabSize)); indentText = lineOffset.CreateIndentationString(options.GetOption(FormattingOptions.UseTabs), options.GetOption(FormattingOptions.TabSize)); IndentLines(lines, indentText); return lines; } public bool IsValidTargetMember(SyntaxTree syntaxTree, SourceText text, int position, CancellationToken cancellationToken) => GetTargetMember(syntaxTree, text, position, cancellationToken) != null; private TMemberNode? GetTargetMember(SyntaxTree syntaxTree, SourceText text, int position, CancellationToken cancellationToken) { var member = GetContainingMember(syntaxTree, position, cancellationToken); if (member == null) { return null; } if (!SupportsDocumentationComments(member) || HasDocumentationComment(member)) { return null; } var startPosition = member.GetFirstToken().SpanStart; var line = text.Lines.GetLineFromPosition(startPosition); var lineOffset = line.GetFirstNonWhitespaceOffset(); if (!lineOffset.HasValue || line.Start + lineOffset.Value < startPosition) { return null; } return member; } private TMemberNode? GetTargetMember(TDocumentationComment documentationComment) { var targetMember = documentationComment.ParentTrivia.Token.GetAncestor<TMemberNode>(); if (targetMember == null || !IsMemberDeclaration(targetMember)) { return null; } if (targetMember.SpanStart < documentationComment.SpanStart) { return null; } return targetMember; } private static void AddLineBreaks(IList<string> lines, string newLine) { for (var i = 0; i < lines.Count; i++) { lines[i] = lines[i] + newLine; } } private static void IndentLines(List<string> lines, string? indentText) { for (var i = 1; i < lines.Count; i++) { lines[i] = indentText + lines[i]; } } public DocumentationCommentSnippet? GetDocumentationCommentSnippetOnEnterTyped(SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken) { // Don't attempt to generate a new XML doc comment on ENTER if the option to auto-generate // them isn't set. Regardless of the option, we should generate exterior trivia (i.e. /// or ''') // on ENTER inside an existing XML doc comment. if (options.GetOption(DocumentationCommentOptions.AutoXmlDocCommentGeneration)) { var result = GenerateDocumentationCommentAfterEnter(syntaxTree, text, position, options, cancellationToken); if (result != null) { return result; } } return GenerateExteriorTriviaAfterEnter(syntaxTree, text, position, options, cancellationToken); } private DocumentationCommentSnippet? GenerateDocumentationCommentAfterEnter(SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken) { // Find the documentation comment before the new line that was just pressed var token = GetTokenToLeft(syntaxTree, position, cancellationToken); if (!IsDocCommentNewLine(token)) { return null; } var newLine = options.GetOption(FormattingOptions.NewLine); var lines = GetDocumentationCommentLines(token, text, options, out var indentText); if (lines == null) { return null; } var newText = string.Join(string.Empty, lines); var offset = lines[0].Length + lines[1].Length - newLine.Length; // Shave off final line break or add trailing indent if necessary var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false); if (IsEndOfLineTrivia(trivia)) { newText = newText.Substring(0, newText.Length - newLine.Length); } else { newText += indentText; } var replaceSpan = token.Span; var currentLine = text.Lines.GetLineFromPosition(position); var currentLinePosition = currentLine.GetFirstNonWhitespacePosition(); if (currentLinePosition.HasValue) { var start = token.Span.Start; replaceSpan = new TextSpan(start, currentLinePosition.Value - start); } return new DocumentationCommentSnippet(replaceSpan, newText, offset); } public DocumentationCommentSnippet? GetDocumentationCommentSnippetOnCommandInvoke(SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken) { var targetMember = GetTargetMember(syntaxTree, text, position, cancellationToken); if (targetMember == null) { return null; } var token = targetMember.GetFirstToken(); var startPosition = token.SpanStart; var line = text.Lines.GetLineFromPosition(startPosition); Debug.Assert(!line.IsEmptyOrWhitespace()); var lines = GetDocumentationCommentStubLines(targetMember); Debug.Assert(lines.Count > 2); var newLine = options.GetOption(FormattingOptions.NewLine); AddLineBreaks(lines, newLine); // Add indents var lineOffset = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(options.GetOption(FormattingOptions.TabSize)); Debug.Assert(line.Start + lineOffset == startPosition); var indentText = lineOffset.CreateIndentationString(options.GetOption(FormattingOptions.UseTabs), options.GetOption(FormattingOptions.TabSize)); IndentLines(lines, indentText); lines[^1] = lines[^1] + indentText; var comments = string.Join(string.Empty, lines); var offset = lines[0].Length + lines[1].Length - newLine.Length; // For a command we don't replace a token, but insert before it var replaceSpan = new TextSpan(token.Span.Start, 0); return new DocumentationCommentSnippet(replaceSpan, comments, offset); } private DocumentationCommentSnippet? GenerateExteriorTriviaAfterEnter(SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken) { // Find the documentation comment before the new line that was just pressed var token = GetTokenToLeft(syntaxTree, position, cancellationToken); if (!IsDocCommentNewLine(token) && HasSkippedTrailingTrivia(token)) { // See PressingEnter_InsertSlashes11 for an example of // a case where multiple skipped tokens trivia appear at the same position. // In that case, we need to ask for the token from the next position over. token = GetTokenToLeft(syntaxTree, position + 1, cancellationToken); if (!IsDocCommentNewLine(token)) { return null; } } var currentLine = text.Lines.GetLineFromPosition(position); if (currentLine.LineNumber == 0) { return null; } // Previous line must begin with a doc comment var previousLine = text.Lines[currentLine.LineNumber - 1]; var previousLineText = previousLine.ToString().Trim(); if (!previousLineText.StartsWith(ExteriorTriviaText, StringComparison.Ordinal)) { return null; } var nextLineStartsWithDocComment = text.Lines.Count > currentLine.LineNumber + 1 && text.Lines[currentLine.LineNumber + 1].ToString().Trim().StartsWith(ExteriorTriviaText, StringComparison.Ordinal); // if previous line has only exterior trivia, current line is empty and next line doesn't begin // with exterior trivia then stop inserting auto generated xml doc string if (previousLineText.Equals(ExteriorTriviaText) && string.IsNullOrWhiteSpace(currentLine.ToString()) && !nextLineStartsWithDocComment) { return null; } var documentationComment = token.GetAncestor<TDocumentationComment>(); if (IsMultilineDocComment(documentationComment)) { return null; } if (EndsWithSingleExteriorTrivia(documentationComment) && currentLine.IsEmptyOrWhitespace() && !nextLineStartsWithDocComment) { return null; } return GetDocumentationCommentSnippetFromPreviousLine(options, currentLine, previousLine); } public DocumentationCommentSnippet GetDocumentationCommentSnippetFromPreviousLine(DocumentOptionSet options, TextLine currentLine, TextLine previousLine) { var insertionText = CreateInsertionTextFromPreviousLine(previousLine, options); var firstNonWhitespaceOffset = currentLine.GetFirstNonWhitespaceOffset(); var replaceSpan = firstNonWhitespaceOffset != null ? TextSpan.FromBounds(currentLine.Start, currentLine.Start + firstNonWhitespaceOffset.Value) : currentLine.Span; return new DocumentationCommentSnippet(replaceSpan, insertionText, insertionText.Length); } private string CreateInsertionTextFromPreviousLine(TextLine previousLine, DocumentOptionSet options) { var useTabs = options.GetOption(FormattingOptions.UseTabs); var tabSize = options.GetOption(FormattingOptions.TabSize); var previousLineText = previousLine.ToString(); var firstNonWhitespaceColumn = previousLineText.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(tabSize); var trimmedPreviousLine = previousLineText.Trim(); Debug.Assert(trimmedPreviousLine.StartsWith(ExteriorTriviaText), "Unexpected: previous line does not begin with doc comment exterior trivia."); // skip exterior trivia. trimmedPreviousLine = trimmedPreviousLine[3..]; var firstNonWhitespaceOffsetInPreviousXmlText = trimmedPreviousLine.GetFirstNonWhitespaceOffset(); var extraIndent = firstNonWhitespaceOffsetInPreviousXmlText != null ? trimmedPreviousLine.Substring(0, firstNonWhitespaceOffsetInPreviousXmlText.Value) : " "; return firstNonWhitespaceColumn.CreateIndentationString(useTabs, tabSize) + ExteriorTriviaText + extraIndent; } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Compilers/CSharp/Portable/Parser/SyntaxParser.ResetPoint.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { internal partial class SyntaxParser { protected struct ResetPoint { internal readonly int ResetCount; internal readonly LexerMode Mode; internal readonly int Position; internal readonly GreenNode PrevTokenTrailingTrivia; internal ResetPoint(int resetCount, LexerMode mode, int position, GreenNode prevTokenTrailingTrivia) { this.ResetCount = resetCount; this.Mode = mode; this.Position = position; this.PrevTokenTrailingTrivia = prevTokenTrailingTrivia; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { internal partial class SyntaxParser { protected struct ResetPoint { internal readonly int ResetCount; internal readonly LexerMode Mode; internal readonly int Position; internal readonly GreenNode PrevTokenTrailingTrivia; internal ResetPoint(int resetCount, LexerMode mode, int position, GreenNode prevTokenTrailingTrivia) { this.ResetCount = resetCount; this.Mode = mode; this.Position = position; this.PrevTokenTrailingTrivia = prevTokenTrailingTrivia; } } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Tools/ExternalAccess/FSharp/Internal/Editor/FSharpEditorInlineRenameService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Collections.Generic; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Editor { internal static class FSharpInlineRenameReplacementKindHelpers { public static InlineRenameReplacementKind ConvertTo(FSharpInlineRenameReplacementKind kind) { switch (kind) { case FSharpInlineRenameReplacementKind.NoConflict: { return InlineRenameReplacementKind.NoConflict; } case FSharpInlineRenameReplacementKind.ResolvedReferenceConflict: { return InlineRenameReplacementKind.ResolvedReferenceConflict; } case FSharpInlineRenameReplacementKind.ResolvedNonReferenceConflict: { return InlineRenameReplacementKind.ResolvedNonReferenceConflict; } case FSharpInlineRenameReplacementKind.UnresolvedConflict: { return InlineRenameReplacementKind.UnresolvedConflict; } case FSharpInlineRenameReplacementKind.Complexified: { return InlineRenameReplacementKind.Complexified; } default: { throw ExceptionUtilities.UnexpectedValue(kind); } } } } internal class FSharpInlineRenameReplacementInfo : IInlineRenameReplacementInfo { private readonly IFSharpInlineRenameReplacementInfo _info; public FSharpInlineRenameReplacementInfo(IFSharpInlineRenameReplacementInfo info) { _info = info; } public Solution NewSolution => _info.NewSolution; public bool ReplacementTextValid => _info.ReplacementTextValid; public IEnumerable<DocumentId> DocumentIds => _info.DocumentIds; public IEnumerable<InlineRenameReplacement> GetReplacements(DocumentId documentId) { return _info.GetReplacements(documentId)?.Select(x => new InlineRenameReplacement(FSharpInlineRenameReplacementKindHelpers.ConvertTo(x.Kind), x.OriginalSpan, x.NewSpan)); } } internal class FSharpInlineRenameLocationSet : IInlineRenameLocationSet { private readonly IFSharpInlineRenameLocationSet _set; private readonly IList<InlineRenameLocation> _locations; public FSharpInlineRenameLocationSet(IFSharpInlineRenameLocationSet set) { _set = set; _locations = set.Locations?.Select(x => new InlineRenameLocation(x.Document, x.TextSpan)).ToList(); } public IList<InlineRenameLocation> Locations => _locations; public async Task<IInlineRenameReplacementInfo> GetReplacementsAsync(string replacementText, OptionSet optionSet, CancellationToken cancellationToken) { var info = await _set.GetReplacementsAsync(replacementText, optionSet, cancellationToken).ConfigureAwait(false); if (info != null) { return new FSharpInlineRenameReplacementInfo(info); } else { return null; } } } internal class FSharpInlineRenameInfo : IInlineRenameInfo { private readonly IFSharpInlineRenameInfo _info; public FSharpInlineRenameInfo(IFSharpInlineRenameInfo info) { _info = info; } public bool CanRename => _info.CanRename; public string LocalizedErrorMessage => _info.LocalizedErrorMessage; public TextSpan TriggerSpan => _info.TriggerSpan; public bool HasOverloads => _info.HasOverloads; public bool ForceRenameOverloads => _info.ForceRenameOverloads; public string DisplayName => _info.DisplayName; public string FullDisplayName => _info.FullDisplayName; public Glyph Glyph => FSharpGlyphHelpers.ConvertTo(_info.Glyph); // This property isn't currently supported in F# since it would involve modifying the IFSharpInlineRenameInfo interface. public ImmutableArray<DocumentSpan> DefinitionLocations => default; public async Task<IInlineRenameLocationSet> FindRenameLocationsAsync(OptionSet optionSet, CancellationToken cancellationToken) { var set = await _info.FindRenameLocationsAsync(optionSet, cancellationToken).ConfigureAwait(false); if (set != null) { return new FSharpInlineRenameLocationSet(set); } else { return null; } } public TextSpan? GetConflictEditSpan(InlineRenameLocation location, string triggerText, string replacementText, CancellationToken cancellationToken) { return _info.GetConflictEditSpan(new FSharpInlineRenameLocation(location.Document, location.TextSpan), replacementText, cancellationToken); } public string GetFinalSymbolName(string replacementText) { return _info.GetFinalSymbolName(replacementText); } public TextSpan GetReferenceEditSpan(InlineRenameLocation location, string triggerText, CancellationToken cancellationToken) { return _info.GetReferenceEditSpan(new FSharpInlineRenameLocation(location.Document, location.TextSpan), cancellationToken); } public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) { return _info.TryOnAfterGlobalSymbolRenamed(workspace, changedDocumentIDs, replacementText); } public bool TryOnBeforeGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) { return _info.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocumentIDs, replacementText); } } [Shared] [ExportLanguageService(typeof(IEditorInlineRenameService), LanguageNames.FSharp)] internal class FSharpEditorInlineRenameService : IEditorInlineRenameService { private readonly IFSharpEditorInlineRenameService _service; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpEditorInlineRenameService(IFSharpEditorInlineRenameService service) { _service = service; } public async Task<IInlineRenameInfo> GetRenameInfoAsync(Document document, int position, CancellationToken cancellationToken) { var info = await _service.GetRenameInfoAsync(document, position, cancellationToken).ConfigureAwait(false); if (info != null) { return new FSharpInlineRenameInfo(info); } else { 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; using System.Linq; using System.Collections.Generic; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Editor { internal static class FSharpInlineRenameReplacementKindHelpers { public static InlineRenameReplacementKind ConvertTo(FSharpInlineRenameReplacementKind kind) { switch (kind) { case FSharpInlineRenameReplacementKind.NoConflict: { return InlineRenameReplacementKind.NoConflict; } case FSharpInlineRenameReplacementKind.ResolvedReferenceConflict: { return InlineRenameReplacementKind.ResolvedReferenceConflict; } case FSharpInlineRenameReplacementKind.ResolvedNonReferenceConflict: { return InlineRenameReplacementKind.ResolvedNonReferenceConflict; } case FSharpInlineRenameReplacementKind.UnresolvedConflict: { return InlineRenameReplacementKind.UnresolvedConflict; } case FSharpInlineRenameReplacementKind.Complexified: { return InlineRenameReplacementKind.Complexified; } default: { throw ExceptionUtilities.UnexpectedValue(kind); } } } } internal class FSharpInlineRenameReplacementInfo : IInlineRenameReplacementInfo { private readonly IFSharpInlineRenameReplacementInfo _info; public FSharpInlineRenameReplacementInfo(IFSharpInlineRenameReplacementInfo info) { _info = info; } public Solution NewSolution => _info.NewSolution; public bool ReplacementTextValid => _info.ReplacementTextValid; public IEnumerable<DocumentId> DocumentIds => _info.DocumentIds; public IEnumerable<InlineRenameReplacement> GetReplacements(DocumentId documentId) { return _info.GetReplacements(documentId)?.Select(x => new InlineRenameReplacement(FSharpInlineRenameReplacementKindHelpers.ConvertTo(x.Kind), x.OriginalSpan, x.NewSpan)); } } internal class FSharpInlineRenameLocationSet : IInlineRenameLocationSet { private readonly IFSharpInlineRenameLocationSet _set; private readonly IList<InlineRenameLocation> _locations; public FSharpInlineRenameLocationSet(IFSharpInlineRenameLocationSet set) { _set = set; _locations = set.Locations?.Select(x => new InlineRenameLocation(x.Document, x.TextSpan)).ToList(); } public IList<InlineRenameLocation> Locations => _locations; public async Task<IInlineRenameReplacementInfo> GetReplacementsAsync(string replacementText, OptionSet optionSet, CancellationToken cancellationToken) { var info = await _set.GetReplacementsAsync(replacementText, optionSet, cancellationToken).ConfigureAwait(false); if (info != null) { return new FSharpInlineRenameReplacementInfo(info); } else { return null; } } } internal class FSharpInlineRenameInfo : IInlineRenameInfo { private readonly IFSharpInlineRenameInfo _info; public FSharpInlineRenameInfo(IFSharpInlineRenameInfo info) { _info = info; } public bool CanRename => _info.CanRename; public string LocalizedErrorMessage => _info.LocalizedErrorMessage; public TextSpan TriggerSpan => _info.TriggerSpan; public bool HasOverloads => _info.HasOverloads; public bool ForceRenameOverloads => _info.ForceRenameOverloads; public string DisplayName => _info.DisplayName; public string FullDisplayName => _info.FullDisplayName; public Glyph Glyph => FSharpGlyphHelpers.ConvertTo(_info.Glyph); // This property isn't currently supported in F# since it would involve modifying the IFSharpInlineRenameInfo interface. public ImmutableArray<DocumentSpan> DefinitionLocations => default; public async Task<IInlineRenameLocationSet> FindRenameLocationsAsync(OptionSet optionSet, CancellationToken cancellationToken) { var set = await _info.FindRenameLocationsAsync(optionSet, cancellationToken).ConfigureAwait(false); if (set != null) { return new FSharpInlineRenameLocationSet(set); } else { return null; } } public TextSpan? GetConflictEditSpan(InlineRenameLocation location, string triggerText, string replacementText, CancellationToken cancellationToken) { return _info.GetConflictEditSpan(new FSharpInlineRenameLocation(location.Document, location.TextSpan), replacementText, cancellationToken); } public string GetFinalSymbolName(string replacementText) { return _info.GetFinalSymbolName(replacementText); } public TextSpan GetReferenceEditSpan(InlineRenameLocation location, string triggerText, CancellationToken cancellationToken) { return _info.GetReferenceEditSpan(new FSharpInlineRenameLocation(location.Document, location.TextSpan), cancellationToken); } public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) { return _info.TryOnAfterGlobalSymbolRenamed(workspace, changedDocumentIDs, replacementText); } public bool TryOnBeforeGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) { return _info.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocumentIDs, replacementText); } } [Shared] [ExportLanguageService(typeof(IEditorInlineRenameService), LanguageNames.FSharp)] internal class FSharpEditorInlineRenameService : IEditorInlineRenameService { private readonly IFSharpEditorInlineRenameService _service; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpEditorInlineRenameService(IFSharpEditorInlineRenameService service) { _service = service; } public async Task<IInlineRenameInfo> GetRenameInfoAsync(Document document, int position, CancellationToken cancellationToken) { var info = await _service.GetRenameInfoAsync(document, position, cancellationToken).ConfigureAwait(false); if (info != null) { return new FSharpInlineRenameInfo(info); } else { return null; } } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Features/Core/Portable/CodeRefactorings/AddAwait/AbstractAddAwaitCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CodeRefactorings.AddAwait { /// <summary> /// Refactor: /// var x = GetAsync(); /// /// Into: /// var x = await GetAsync(); /// /// Or: /// var x = await GetAsync().ConfigureAwait(false); /// </summary> internal abstract class AbstractAddAwaitCodeRefactoringProvider<TExpressionSyntax> : CodeRefactoringProvider where TExpressionSyntax : SyntaxNode { protected abstract string GetTitle(); protected abstract string GetTitleWithConfigureAwait(); protected abstract bool IsInAsyncContext(SyntaxNode node); public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, span, cancellationToken) = context; var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var node = root.FindNode(span); if (!IsInAsyncContext(node)) return; var model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var expressions = await context.GetRelevantNodesAsync<TExpressionSyntax>().ConfigureAwait(false); for (var i = expressions.Length - 1; i >= 0; i--) { var expression = expressions[i]; if (IsValidAwaitableExpression(model, syntaxFacts, expression, cancellationToken)) { context.RegisterRefactoring( new MyCodeAction( GetTitle(), c => AddAwaitAsync(document, expression, withConfigureAwait: false, c)), expression.Span); context.RegisterRefactoring( new MyCodeAction( GetTitleWithConfigureAwait(), c => AddAwaitAsync(document, expression, withConfigureAwait: true, c)), expression.Span); } } } private static bool IsValidAwaitableExpression( SemanticModel model, ISyntaxFactsService syntaxFacts, SyntaxNode node, CancellationToken cancellationToken) { if (syntaxFacts.IsExpressionOfInvocationExpression(node.Parent)) { // Do not offer fix on `MethodAsync()$$.ConfigureAwait()` // Do offer fix on `MethodAsync()$$.Invalid()` if (!model.GetTypeInfo(node.GetRequiredParent().GetRequiredParent(), cancellationToken).Type.IsErrorType()) return false; } if (syntaxFacts.IsExpressionOfAwaitExpression(node)) return false; // if we're on an actual type symbol itself (like literally `Task`) we don't want to offer to add await. // we only want to add for actual expressions whose type is awaitable, not on the awaitable type itself. var symbol = model.GetSymbolInfo(node, cancellationToken).GetAnySymbol(); if (symbol is ITypeSymbol) return false; var type = model.GetTypeInfo(node, cancellationToken).Type; return type?.IsAwaitableNonDynamic(model, node.SpanStart) == true; } private static Task<Document> AddAwaitAsync( Document document, TExpressionSyntax expression, bool withConfigureAwait, CancellationToken cancellationToken) { var generator = SyntaxGenerator.GetGenerator(document); var withoutTrivia = expression.WithoutTrivia(); withoutTrivia = (TExpressionSyntax)generator.AddParentheses(withoutTrivia); if (withConfigureAwait) { withoutTrivia = (TExpressionSyntax)generator.InvocationExpression( generator.MemberAccessExpression(withoutTrivia, nameof(Task.ConfigureAwait)), generator.FalseLiteralExpression()); } var awaitExpression = generator .AddParentheses(generator.AwaitExpression(withoutTrivia)) .WithTriviaFrom(expression); return document.ReplaceNodeAsync(expression, awaitExpression, cancellationToken); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CodeRefactorings.AddAwait { /// <summary> /// Refactor: /// var x = GetAsync(); /// /// Into: /// var x = await GetAsync(); /// /// Or: /// var x = await GetAsync().ConfigureAwait(false); /// </summary> internal abstract class AbstractAddAwaitCodeRefactoringProvider<TExpressionSyntax> : CodeRefactoringProvider where TExpressionSyntax : SyntaxNode { protected abstract string GetTitle(); protected abstract string GetTitleWithConfigureAwait(); protected abstract bool IsInAsyncContext(SyntaxNode node); public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, span, cancellationToken) = context; var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var node = root.FindNode(span); if (!IsInAsyncContext(node)) return; var model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var expressions = await context.GetRelevantNodesAsync<TExpressionSyntax>().ConfigureAwait(false); for (var i = expressions.Length - 1; i >= 0; i--) { var expression = expressions[i]; if (IsValidAwaitableExpression(model, syntaxFacts, expression, cancellationToken)) { context.RegisterRefactoring( new MyCodeAction( GetTitle(), c => AddAwaitAsync(document, expression, withConfigureAwait: false, c)), expression.Span); context.RegisterRefactoring( new MyCodeAction( GetTitleWithConfigureAwait(), c => AddAwaitAsync(document, expression, withConfigureAwait: true, c)), expression.Span); } } } private static bool IsValidAwaitableExpression( SemanticModel model, ISyntaxFactsService syntaxFacts, SyntaxNode node, CancellationToken cancellationToken) { if (syntaxFacts.IsExpressionOfInvocationExpression(node.Parent)) { // Do not offer fix on `MethodAsync()$$.ConfigureAwait()` // Do offer fix on `MethodAsync()$$.Invalid()` if (!model.GetTypeInfo(node.GetRequiredParent().GetRequiredParent(), cancellationToken).Type.IsErrorType()) return false; } if (syntaxFacts.IsExpressionOfAwaitExpression(node)) return false; // if we're on an actual type symbol itself (like literally `Task`) we don't want to offer to add await. // we only want to add for actual expressions whose type is awaitable, not on the awaitable type itself. var symbol = model.GetSymbolInfo(node, cancellationToken).GetAnySymbol(); if (symbol is ITypeSymbol) return false; var type = model.GetTypeInfo(node, cancellationToken).Type; return type?.IsAwaitableNonDynamic(model, node.SpanStart) == true; } private static Task<Document> AddAwaitAsync( Document document, TExpressionSyntax expression, bool withConfigureAwait, CancellationToken cancellationToken) { var generator = SyntaxGenerator.GetGenerator(document); var withoutTrivia = expression.WithoutTrivia(); withoutTrivia = (TExpressionSyntax)generator.AddParentheses(withoutTrivia); if (withConfigureAwait) { withoutTrivia = (TExpressionSyntax)generator.InvocationExpression( generator.MemberAccessExpression(withoutTrivia, nameof(Task.ConfigureAwait)), generator.FalseLiteralExpression()); } var awaitExpression = generator .AddParentheses(generator.AwaitExpression(withoutTrivia)) .WithTriviaFrom(expression); return document.ReplaceNodeAsync(expression, awaitExpression, cancellationToken); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Features/CSharp/Portable/Structure/Providers/TypeDeclarationStructureProvider.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.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class TypeDeclarationStructureProvider : AbstractSyntaxNodeStructureProvider<TypeDeclarationSyntax> { protected override void CollectBlockSpans( SyntaxToken previousToken, TypeDeclarationSyntax typeDeclaration, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { CSharpStructureHelpers.CollectCommentBlockSpans(typeDeclaration, ref spans, optionProvider); if (!typeDeclaration.OpenBraceToken.IsMissing && !typeDeclaration.CloseBraceToken.IsMissing) { var lastToken = typeDeclaration.TypeParameterList == null ? typeDeclaration.Identifier : typeDeclaration.TypeParameterList.GetLastToken(includeZeroWidth: true); SyntaxNodeOrToken current = typeDeclaration; var nextSibling = current.GetNextSibling(); // Check IsNode to compress blank lines after this node if it is the last child of the parent. // // Collapse to Definitions doesn't collapse type nodes, but a Toggle All Outlining would collapse groups // of types to the compressed form of not showing blank lines. All kinds of types are grouped together // in Metadata as Source. var compressEmptyLines = optionProvider.IsMetadataAsSource && (!nextSibling.IsNode || nextSibling.AsNode() is BaseTypeDeclarationSyntax); spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( typeDeclaration, lastToken, compressEmptyLines: compressEmptyLines, autoCollapse: false, type: BlockTypes.Type, isCollapsible: true)); } // add any leading comments before the end of the type block if (!typeDeclaration.CloseBraceToken.IsMissing) { var leadingTrivia = typeDeclaration.CloseBraceToken.LeadingTrivia; CSharpStructureHelpers.CollectCommentBlockSpans(leadingTrivia, ref spans); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class TypeDeclarationStructureProvider : AbstractSyntaxNodeStructureProvider<TypeDeclarationSyntax> { protected override void CollectBlockSpans( SyntaxToken previousToken, TypeDeclarationSyntax typeDeclaration, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { CSharpStructureHelpers.CollectCommentBlockSpans(typeDeclaration, ref spans, optionProvider); if (!typeDeclaration.OpenBraceToken.IsMissing && !typeDeclaration.CloseBraceToken.IsMissing) { var lastToken = typeDeclaration.TypeParameterList == null ? typeDeclaration.Identifier : typeDeclaration.TypeParameterList.GetLastToken(includeZeroWidth: true); SyntaxNodeOrToken current = typeDeclaration; var nextSibling = current.GetNextSibling(); // Check IsNode to compress blank lines after this node if it is the last child of the parent. // // Collapse to Definitions doesn't collapse type nodes, but a Toggle All Outlining would collapse groups // of types to the compressed form of not showing blank lines. All kinds of types are grouped together // in Metadata as Source. var compressEmptyLines = optionProvider.IsMetadataAsSource && (!nextSibling.IsNode || nextSibling.AsNode() is BaseTypeDeclarationSyntax); spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( typeDeclaration, lastToken, compressEmptyLines: compressEmptyLines, autoCollapse: false, type: BlockTypes.Type, isCollapsible: true)); } // add any leading comments before the end of the type block if (!typeDeclaration.CloseBraceToken.IsMissing) { var leadingTrivia = typeDeclaration.CloseBraceToken.LeadingTrivia; CSharpStructureHelpers.CollectCommentBlockSpans(leadingTrivia, ref spans); } } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Compilers/Test/Core/Platform/Desktop/AppDomainAssemblyCache.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #if NET472 using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Roslyn.Test.Utilities; namespace Roslyn.Test.Utilities.Desktop { /// <summary> /// This is a singleton per AppDomain which manages all of the assemblies which were ever loaded into it. /// </summary> internal sealed class AppDomainAssemblyCache { private static AppDomainAssemblyCache s_singleton; private static readonly object s_guard = new object(); // The key is the manifest module MVID, which is unique for each distinct assembly. private readonly Dictionary<Guid, Assembly> _assemblyCache = new Dictionary<Guid, Assembly>(); private readonly Dictionary<Guid, Assembly> _reflectionOnlyAssemblyCache = new Dictionary<Guid, Assembly>(); internal static AppDomainAssemblyCache GetOrCreate() { lock (s_guard) { if (s_singleton == null) { s_singleton = new AppDomainAssemblyCache(); var currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyLoad += OnAssemblyLoad; } return s_singleton; } } private AppDomainAssemblyCache() { foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { var cache = assembly.ReflectionOnly ? _assemblyCache : _reflectionOnlyAssemblyCache; cache.Add(assembly.ManifestModule.ModuleVersionId, assembly); } } internal Assembly GetOrDefault(ModuleDataId id, bool reflectionOnly) { var cache = reflectionOnly ? _reflectionOnlyAssemblyCache : _assemblyCache; lock (s_guard) { if (cache.TryGetValue(id.Mvid, out var assembly)) { return assembly; } return null; } } internal Assembly GetOrLoad(ModuleData moduleData, bool reflectionOnly) { var cache = reflectionOnly ? _reflectionOnlyAssemblyCache : _assemblyCache; lock (s_guard) { if (cache.TryGetValue(moduleData.Mvid, out var assembly)) { return assembly; } var loadedAssembly = DesktopRuntimeUtil.LoadAsAssembly(moduleData.SimpleName, moduleData.Image, reflectionOnly); // Validate the loaded assembly matches the value that we now have in the cache. if (!cache.TryGetValue(moduleData.Mvid, out assembly)) { throw new Exception($"Explicit assembly load didn't update the proper cache: '{moduleData.SimpleName}' ({moduleData.Mvid})"); } if (loadedAssembly != assembly) { throw new Exception("Cache entry doesn't match result of load"); } return assembly; } } private void OnAssemblyLoad(Assembly assembly) { // We need to add loaded assemblies to the cache in order to avoid loading them twice. // This is not just optimization. CLR isn't able to load the same assembly from multiple "locations". // Location for byte[] assemblies is the location of the assembly that invokes Assembly.Load. // PE verifier invokes load directly for the assembly being verified. If this assembly is also a dependency // of another assembly we verify our AssemblyResolve is invoked. If we didn't reuse the assembly already loaded // by PE verifier we would get an error from Assembly.Load. var cache = assembly.ReflectionOnly ? _reflectionOnlyAssemblyCache : _assemblyCache; lock (s_guard) { var mvid = assembly.ManifestModule.ModuleVersionId; if (!cache.ContainsKey(mvid)) { cache.Add(mvid, assembly); } } } private static void OnAssemblyLoad(object sender, AssemblyLoadEventArgs args) { GetOrCreate().OnAssemblyLoad(args.LoadedAssembly); } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #if NET472 using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Roslyn.Test.Utilities; namespace Roslyn.Test.Utilities.Desktop { /// <summary> /// This is a singleton per AppDomain which manages all of the assemblies which were ever loaded into it. /// </summary> internal sealed class AppDomainAssemblyCache { private static AppDomainAssemblyCache s_singleton; private static readonly object s_guard = new object(); // The key is the manifest module MVID, which is unique for each distinct assembly. private readonly Dictionary<Guid, Assembly> _assemblyCache = new Dictionary<Guid, Assembly>(); private readonly Dictionary<Guid, Assembly> _reflectionOnlyAssemblyCache = new Dictionary<Guid, Assembly>(); internal static AppDomainAssemblyCache GetOrCreate() { lock (s_guard) { if (s_singleton == null) { s_singleton = new AppDomainAssemblyCache(); var currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyLoad += OnAssemblyLoad; } return s_singleton; } } private AppDomainAssemblyCache() { foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { var cache = assembly.ReflectionOnly ? _assemblyCache : _reflectionOnlyAssemblyCache; cache.Add(assembly.ManifestModule.ModuleVersionId, assembly); } } internal Assembly GetOrDefault(ModuleDataId id, bool reflectionOnly) { var cache = reflectionOnly ? _reflectionOnlyAssemblyCache : _assemblyCache; lock (s_guard) { if (cache.TryGetValue(id.Mvid, out var assembly)) { return assembly; } return null; } } internal Assembly GetOrLoad(ModuleData moduleData, bool reflectionOnly) { var cache = reflectionOnly ? _reflectionOnlyAssemblyCache : _assemblyCache; lock (s_guard) { if (cache.TryGetValue(moduleData.Mvid, out var assembly)) { return assembly; } var loadedAssembly = DesktopRuntimeUtil.LoadAsAssembly(moduleData.SimpleName, moduleData.Image, reflectionOnly); // Validate the loaded assembly matches the value that we now have in the cache. if (!cache.TryGetValue(moduleData.Mvid, out assembly)) { throw new Exception($"Explicit assembly load didn't update the proper cache: '{moduleData.SimpleName}' ({moduleData.Mvid})"); } if (loadedAssembly != assembly) { throw new Exception("Cache entry doesn't match result of load"); } return assembly; } } private void OnAssemblyLoad(Assembly assembly) { // We need to add loaded assemblies to the cache in order to avoid loading them twice. // This is not just optimization. CLR isn't able to load the same assembly from multiple "locations". // Location for byte[] assemblies is the location of the assembly that invokes Assembly.Load. // PE verifier invokes load directly for the assembly being verified. If this assembly is also a dependency // of another assembly we verify our AssemblyResolve is invoked. If we didn't reuse the assembly already loaded // by PE verifier we would get an error from Assembly.Load. var cache = assembly.ReflectionOnly ? _reflectionOnlyAssemblyCache : _assemblyCache; lock (s_guard) { var mvid = assembly.ManifestModule.ModuleVersionId; if (!cache.ContainsKey(mvid)) { cache.Add(mvid, assembly); } } } private static void OnAssemblyLoad(object sender, AssemblyLoadEventArgs args) { GetOrCreate().OnAssemblyLoad(args.LoadedAssembly); } } } #endif
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/VisualStudio/Core/Def/xlf/Commands.vsct.pl.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="pl" original="../Commands.vsct"> <body> <trans-unit id="ECMD_RUNFXCOPSEL|ButtonText"> <source>Run Code &amp;Analysis on Selection</source> <target state="translated">&amp;Uruchom analizę kodu dla zaznaczenia</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeCurrentFile|ButtonText"> <source>&amp;Current Document</source> <target state="translated">&amp;Bieżący dokument</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeCurrentFile|CommandName"> <source>AnalysisScopeCurrentDocument</source> <target state="translated">AnalysisScopeCurrentDocument</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeCurrentFile|LocCanonicalName"> <source>Current Document</source> <target state="translated">Bieżący dokument</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeDefault|ButtonText"> <source>&amp;Default</source> <target state="translated">&amp;Domyślny</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeDefault|CommandName"> <source>AnalysisScopeDefault</source> <target state="translated">AnalysisScopeDefault</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeDefault|LocCanonicalName"> <source>Default</source> <target state="translated">Domyślny</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeEntireSolution|ButtonText"> <source>&amp;Entire Solution</source> <target state="translated">&amp;Całe rozwiązanie</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeEntireSolution|CommandName"> <source>AnalysisScopeEntireSolution</source> <target state="translated">AnalysisScopeEntireSolution</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeEntireSolution|LocCanonicalName"> <source>Entire Solution</source> <target state="translated">Całe rozwiązanie</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeOpenFiles|ButtonText"> <source>&amp;Open Documents</source> <target state="translated">&amp;Otwórz dokumenty</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeOpenFiles|CommandName"> <source>AnalysisScopeOpenDocuments</source> <target state="translated">AnalysisScopeOpenDocuments</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeOpenFiles|LocCanonicalName"> <source>Open Documents</source> <target state="translated">Otwórz dokumenty</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeSubMenu|ButtonText"> <source>Set Analysis Scope</source> <target state="translated">Ustaw zakres analizy</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeSubMenu|CommandName"> <source>Set Analysis Scope</source> <target state="translated">Ustaw zakres analizy</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeSubMenu|LocCanonicalName"> <source>SetAnalysisScope</source> <target state="translated">SetAnalysisScope</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeSortUsings|ButtonText"> <source>Sort &amp;Usings</source> <target state="translated">Sortuj &amp;użycia</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeSortUsings|LocCanonicalName"> <source>SortUsings</source> <target state="translated">SortUsings</target> <note /> </trans-unit> <trans-unit id="cmdidContextOrganizeRemoveAndSort|ButtonText"> <source>Remove &amp;and Sort</source> <target state="translated">Usuń &amp;i sortuj</target> <note /> </trans-unit> <trans-unit id="cmdidContextOrganizeRemoveAndSort|LocCanonicalName"> <source>RemoveAndSort</source> <target state="translated">RemoveAndSort</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeRemoveAndSort|ButtonText"> <source>Remove &amp;and Sort</source> <target state="translated">Usuń &amp;i sortuj</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeRemoveAndSort|LocCanonicalName"> <source>RemoveAndSort</source> <target state="translated">RemoveAndSort</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityDefault|ButtonText"> <source>&amp;Default</source> <target state="new">&amp;Default</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityDefault|CommandName"> <source>ErrorListSetSeverityDefault</source> <target state="new">ErrorListSetSeverityDefault</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityDefault|LocCanonicalName"> <source>Default</source> <target state="new">Default</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityError|ButtonText"> <source>&amp;Error</source> <target state="new">&amp;Error</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityError|CommandName"> <source>ErrorListSetSeverityError</source> <target state="new">ErrorListSetSeverityError</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityError|LocCanonicalName"> <source>Error</source> <target state="new">Error</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityHidden|ButtonText"> <source>&amp;Silent</source> <target state="new">&amp;Silent</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityHidden|CommandName"> <source>ErrorListSetSeverityHidden</source> <target state="new">ErrorListSetSeverityHidden</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityHidden|LocCanonicalName"> <source>Silent</source> <target state="new">Silent</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityInfo|ButtonText"> <source>&amp;Suggestion</source> <target state="new">&amp;Suggestion</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityInfo|CommandName"> <source>ErrorListSetSeverityInfo</source> <target state="new">ErrorListSetSeverityInfo</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityInfo|LocCanonicalName"> <source>Suggestion</source> <target state="new">Suggestion</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityNone|ButtonText"> <source>&amp;None</source> <target state="new">&amp;None</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityNone|CommandName"> <source>ErrorListSetSeverityNone</source> <target state="new">ErrorListSetSeverityNone</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityNone|LocCanonicalName"> <source>None</source> <target state="new">None</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeveritySubMenu|ButtonText"> <source>Set severity</source> <target state="new">Set severity</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeveritySubMenu|CommandName"> <source>Set severity</source> <target state="new">Set severity</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeveritySubMenu|LocCanonicalName"> <source>Set severity</source> <target state="new">Set severity</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityWarning|ButtonText"> <source>&amp;Warning</source> <target state="new">&amp;Warning</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityWarning|CommandName"> <source>ErrorListSetSeverityWarning</source> <target state="new">ErrorListSetSeverityWarning</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityWarning|LocCanonicalName"> <source>Warning</source> <target state="new">Warning</target> <note /> </trans-unit> <trans-unit id="cmdidProjectContextAddAnalyzer|ButtonText"> <source>&amp;Analyzer...</source> <target state="translated">&amp;Analizator...</target> <note /> </trans-unit> <trans-unit id="cmdidProjectContextAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidProjectAddAnalyzer|ButtonText"> <source>Add &amp;Analyzer...</source> <target state="translated">Dodaj &amp;analizator...</target> <note /> </trans-unit> <trans-unit id="cmdidProjectAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidReferencesContextAddAnalyzer|ButtonText"> <source>Add &amp;Analyzer...</source> <target state="translated">Dodaj &amp;analizator...</target> <note /> </trans-unit> <trans-unit id="cmdidReferencesContextAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidAddAnalyzer|ButtonText"> <source>Add &amp;Analyzer...</source> <target state="translated">Dodaj &amp;analizator...</target> <note /> </trans-unit> <trans-unit id="cmdidAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveAnalyzer|ButtonText"> <source>&amp;Remove</source> <target state="translated">&amp;Usuń</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveAnalyzer|LocCanonicalName"> <source>RemoveAnalyzer</source> <target state="translated">RemoveAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveAnalyzer|CommandName"> <source>RemoveAnalyzer</source> <target state="translated">RemoveAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidOpenRuleSet|ButtonText"> <source>&amp;Open Active Rule Set</source> <target state="translated">&amp;Otwórz aktywny zestaw reguł</target> <note /> </trans-unit> <trans-unit id="cmdidOpenRuleSet|LocCanonicalName"> <source>OpenActiveRuleSet</source> <target state="translated">OpenActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidOpenRuleSet|CommandName"> <source>OpenActiveRuleSet</source> <target state="translated">OpenActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveUnusedReferences|ButtonText"> <source>Remove Unused References...</source> <target state="translated">Usuń nieużywane odwołania...</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveUnusedReferences|CommandName"> <source>RemoveUnusedReferences</source> <target state="translated">RemoveUnusedReferences</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveUnusedReferences|LocCanonicalName"> <source>RemoveUnusedReferences</source> <target state="translated">RemoveUnusedReferences</target> <note /> </trans-unit> <trans-unit id="cmdidRunCodeAnalysisForProject|ButtonText"> <source>Run C&amp;ode Analysis</source> <target state="translated">Uru&amp;chom analizę kodu</target> <note /> </trans-unit> <trans-unit id="cmdidRunCodeAnalysisForProject|CommandName"> <source>RunCodeAnalysisForProject</source> <target state="translated">RunCodeAnalysisForProject</target> <note /> </trans-unit> <trans-unit id="cmdidRunCodeAnalysisForProject|LocCanonicalName"> <source>RunCodeAnalysisForProject</source> <target state="translated">RunCodeAnalysisForProject</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityDefault|ButtonText"> <source>&amp;Default</source> <target state="translated">&amp;Domyślny</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityDefault|LocCanonicalName"> <source>Default</source> <target state="translated">Domyślny</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityDefault|CommandName"> <source>SetSeverityDefault</source> <target state="translated">SetSeverityDefault</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityError|ButtonText"> <source>&amp;Error</source> <target state="translated">&amp;Błąd</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityError|LocCanonicalName"> <source>Error</source> <target state="translated">Błąd</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityError|CommandName"> <source>SetSeverityError</source> <target state="translated">SetSeverityError</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityWarning|ButtonText"> <source>&amp;Warning</source> <target state="translated">&amp;Ostrzeżenie</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityWarning|LocCanonicalName"> <source>Warning</source> <target state="translated">Ostrzeżenie</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityWarning|CommandName"> <source>SetSeverityWarning</source> <target state="translated">SetSeverityWarning</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityInfo|ButtonText"> <source>&amp;Suggestion</source> <target state="translated">&amp;Sugestia</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityInfo|LocCanonicalName"> <source>Suggestion</source> <target state="translated">Sugestia</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityInfo|CommandName"> <source>SetSeverityInfo</source> <target state="translated">SetSeverityInfo</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityHidden|ButtonText"> <source>&amp;Silent</source> <target state="translated">&amp;Dyskretne</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityHidden|LocCanonicalName"> <source>Silent</source> <target state="translated">Dyskretne</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityHidden|CommandName"> <source>SetSeverityHidden</source> <target state="translated">SetSeverityHidden</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityNone|ButtonText"> <source>&amp;None</source> <target state="translated">&amp;Brak</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityNone|LocCanonicalName"> <source>None</source> <target state="translated">brak</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityNone|CommandName"> <source>SetSeverityNone</source> <target state="translated">SetSeverityNone</target> <note /> </trans-unit> <trans-unit id="cmdidOpenDiagnosticHelpLink|ButtonText"> <source>&amp;View Help...</source> <target state="translated">&amp;Pokaż pomoc...</target> <note /> </trans-unit> <trans-unit id="cmdidOpenDiagnosticHelpLink|LocCanonicalName"> <source>ViewHelp</source> <target state="translated">ViewHelp</target> <note /> </trans-unit> <trans-unit id="cmdidOpenDiagnosticHelpLink|CommandName"> <source>ViewHelp</source> <target state="translated">ViewHelp</target> <note /> </trans-unit> <trans-unit id="cmdidSetActiveRuleSet|ButtonText"> <source>&amp;Set as Active Rule Set</source> <target state="translated">&amp;Ustaw jako aktywny zestaw reguł</target> <note /> </trans-unit> <trans-unit id="cmdidSetActiveRuleSet|LocCanonicalName"> <source>SetAsActiveRuleSet</source> <target state="translated">SetAsActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidSetActiveRuleSet|CommandName"> <source>SetAsActiveRuleSet</source> <target state="translated">SetAsActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveSuppressions|ButtonText"> <source>Remove&amp; Suppression(s)</source> <target state="translated">Usuń &amp;pominięcia</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveSuppressions|LocCanonicalName"> <source>RemoveSuppressions</source> <target state="translated">RemoveSuppressions</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveSuppressions|CommandName"> <source>RemoveSuppressions</source> <target state="translated">RemoveSuppressions</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSource|ButtonText"> <source>In &amp;Source</source> <target state="translated">W źró&amp;dle</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSource|LocCanonicalName"> <source>AddSuppressionsInSource</source> <target state="translated">AddSuppressionsInSource</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSource|CommandName"> <source>AddSuppressionsInSource</source> <target state="translated">AddSuppressionsInSource</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSuppressionFile|ButtonText"> <source>In&amp; Suppression File</source> <target state="translated">W pli&amp;ku pominięć</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSuppressionFile|LocCanonicalName"> <source>AddSuppressionsInSuppressionFile</source> <target state="translated">AddSuppressionsInSuppressionFile</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSuppressionFile|CommandName"> <source>AddSuppressionsInSuppressionFile</source> <target state="translated">AddSuppressionsInSuppressionFile</target> <note /> </trans-unit> <trans-unit id="cmdidGoToImplementation|ButtonText"> <source>Go To Implementation</source> <target state="translated">Przejdź do implementacji</target> <note /> </trans-unit> <trans-unit id="cmdidGoToImplementation|LocCanonicalName"> <source>GoToImplementation</source> <target state="translated">GoToImplementation</target> <note /> </trans-unit> <trans-unit id="cmdidGoToImplementation|CommandName"> <source>Go To Implementation</source> <target state="translated">Przejdź do implementacji</target> <note /> </trans-unit> <trans-unit id="cmdidSyncNamespaces|ButtonText"> <source>Sync &amp;Namespaces</source> <target state="translated">Synchronizuj &amp;przestrzenie nazw</target> <note /> </trans-unit> <trans-unit id="cmdidSyncNamespaces|CommandName"> <source>SyncNamespaces</source> <target state="translated">SyncNamespaces</target> <note /> </trans-unit> <trans-unit id="cmdidSyncNamespaces|LocCanonicalName"> <source>SyncNamespaces</source> <target state="translated">SyncNamespaces</target> <note /> </trans-unit> <trans-unit id="cmdidshowValueTracking|ButtonText"> <source>Track Value Source</source> <target state="translated">Śledź źródło wartości</target> <note /> </trans-unit> <trans-unit id="cmdidshowValueTracking|CommandName"> <source>ShowValueTrackingCommandName</source> <target state="translated">ShowValueTrackingCommandName</target> <note /> </trans-unit> <trans-unit id="cmdidshowValueTracking|LocCanonicalName"> <source>ViewEditorConfigSettings</source> <target state="translated">ViewEditorConfigSettings</target> <note /> </trans-unit> <trans-unit id="guidCSharpInteractiveCommandSet|cmdidResetInteractiveFromProject|ButtonText"> <source>Initialize Interactive with Project</source> <target state="translated">Inicjuj środowisko interaktywne z projektem</target> <note /> </trans-unit> <trans-unit id="guidCSharpInteractiveCommandSet|cmdidResetInteractiveFromProject|LocCanonicalName"> <source>ResetC#InteractiveFromProject</source> <target state="translated">ResetC#InteractiveFromProject</target> <note /> </trans-unit> <trans-unit id="guidVisualBasicInteractiveCommandSet|cmdidResetInteractiveFromProject|ButtonText"> <source>Reset Visual Basic Interactive from Project</source> <target state="translated">Resetuj środowisko interaktywne z projektu programu Visual Basic</target> <note /> </trans-unit> <trans-unit id="guidVisualBasicInteractiveCommandSet|cmdidResetInteractiveFromProject|LocCanonicalName"> <source>ResetVisualBasicInteractiveFromProject</source> <target state="translated">ResetVisualBasicInteractiveFromProject</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerContextMenu|ButtonText"> <source>Analyzer</source> <target state="translated">Analizator</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerContextMenu|LocCanonicalName"> <source>Analyzer</source> <target state="translated">Analizator</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerFolderContextMenu|ButtonText"> <source>Analyzers</source> <target state="translated">Analizatory</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerFolderContextMenu|LocCanonicalName"> <source>Analyzers</source> <target state="translated">Analizatory</target> <note /> </trans-unit> <trans-unit id="cmdidDiagnosticContextMenu|ButtonText"> <source>Diagnostic</source> <target state="translated">Diagnostyka</target> <note /> </trans-unit> <trans-unit id="cmdidDiagnosticContextMenu|LocCanonicalName"> <source>Diagnostic</source> <target state="translated">Diagnostyka</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeveritySubMenu|ButtonText"> <source>Set severity</source> <target state="translated">Ustaw ważność</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeveritySubMenu|CommandName"> <source>Set severity</source> <target state="translated">Ustaw ważność</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeveritySubMenu|LocCanonicalName"> <source>Set severity</source> <target state="translated">Ustaw ważność</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsContextMenu|ButtonText"> <source>S&amp;uppress</source> <target state="translated">P&amp;omiń</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsContextMenu|LocCanonicalName"> <source>S&amp;uppress</source> <target state="translated">P&amp;omiń</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsContextMenu|CommandName"> <source>S&amp;uppress</source> <target state="translated">P&amp;omiń</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="pl" original="../Commands.vsct"> <body> <trans-unit id="ECMD_RUNFXCOPSEL|ButtonText"> <source>Run Code &amp;Analysis on Selection</source> <target state="translated">&amp;Uruchom analizę kodu dla zaznaczenia</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeCurrentFile|ButtonText"> <source>&amp;Current Document</source> <target state="translated">&amp;Bieżący dokument</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeCurrentFile|CommandName"> <source>AnalysisScopeCurrentDocument</source> <target state="translated">AnalysisScopeCurrentDocument</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeCurrentFile|LocCanonicalName"> <source>Current Document</source> <target state="translated">Bieżący dokument</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeDefault|ButtonText"> <source>&amp;Default</source> <target state="translated">&amp;Domyślny</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeDefault|CommandName"> <source>AnalysisScopeDefault</source> <target state="translated">AnalysisScopeDefault</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeDefault|LocCanonicalName"> <source>Default</source> <target state="translated">Domyślny</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeEntireSolution|ButtonText"> <source>&amp;Entire Solution</source> <target state="translated">&amp;Całe rozwiązanie</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeEntireSolution|CommandName"> <source>AnalysisScopeEntireSolution</source> <target state="translated">AnalysisScopeEntireSolution</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeEntireSolution|LocCanonicalName"> <source>Entire Solution</source> <target state="translated">Całe rozwiązanie</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeOpenFiles|ButtonText"> <source>&amp;Open Documents</source> <target state="translated">&amp;Otwórz dokumenty</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeOpenFiles|CommandName"> <source>AnalysisScopeOpenDocuments</source> <target state="translated">AnalysisScopeOpenDocuments</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeOpenFiles|LocCanonicalName"> <source>Open Documents</source> <target state="translated">Otwórz dokumenty</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeSubMenu|ButtonText"> <source>Set Analysis Scope</source> <target state="translated">Ustaw zakres analizy</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeSubMenu|CommandName"> <source>Set Analysis Scope</source> <target state="translated">Ustaw zakres analizy</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeSubMenu|LocCanonicalName"> <source>SetAnalysisScope</source> <target state="translated">SetAnalysisScope</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeSortUsings|ButtonText"> <source>Sort &amp;Usings</source> <target state="translated">Sortuj &amp;użycia</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeSortUsings|LocCanonicalName"> <source>SortUsings</source> <target state="translated">SortUsings</target> <note /> </trans-unit> <trans-unit id="cmdidContextOrganizeRemoveAndSort|ButtonText"> <source>Remove &amp;and Sort</source> <target state="translated">Usuń &amp;i sortuj</target> <note /> </trans-unit> <trans-unit id="cmdidContextOrganizeRemoveAndSort|LocCanonicalName"> <source>RemoveAndSort</source> <target state="translated">RemoveAndSort</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeRemoveAndSort|ButtonText"> <source>Remove &amp;and Sort</source> <target state="translated">Usuń &amp;i sortuj</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeRemoveAndSort|LocCanonicalName"> <source>RemoveAndSort</source> <target state="translated">RemoveAndSort</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityDefault|ButtonText"> <source>&amp;Default</source> <target state="new">&amp;Default</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityDefault|CommandName"> <source>ErrorListSetSeverityDefault</source> <target state="new">ErrorListSetSeverityDefault</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityDefault|LocCanonicalName"> <source>Default</source> <target state="new">Default</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityError|ButtonText"> <source>&amp;Error</source> <target state="new">&amp;Error</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityError|CommandName"> <source>ErrorListSetSeverityError</source> <target state="new">ErrorListSetSeverityError</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityError|LocCanonicalName"> <source>Error</source> <target state="new">Error</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityHidden|ButtonText"> <source>&amp;Silent</source> <target state="new">&amp;Silent</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityHidden|CommandName"> <source>ErrorListSetSeverityHidden</source> <target state="new">ErrorListSetSeverityHidden</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityHidden|LocCanonicalName"> <source>Silent</source> <target state="new">Silent</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityInfo|ButtonText"> <source>&amp;Suggestion</source> <target state="new">&amp;Suggestion</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityInfo|CommandName"> <source>ErrorListSetSeverityInfo</source> <target state="new">ErrorListSetSeverityInfo</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityInfo|LocCanonicalName"> <source>Suggestion</source> <target state="new">Suggestion</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityNone|ButtonText"> <source>&amp;None</source> <target state="new">&amp;None</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityNone|CommandName"> <source>ErrorListSetSeverityNone</source> <target state="new">ErrorListSetSeverityNone</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityNone|LocCanonicalName"> <source>None</source> <target state="new">None</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeveritySubMenu|ButtonText"> <source>Set severity</source> <target state="new">Set severity</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeveritySubMenu|CommandName"> <source>Set severity</source> <target state="new">Set severity</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeveritySubMenu|LocCanonicalName"> <source>Set severity</source> <target state="new">Set severity</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityWarning|ButtonText"> <source>&amp;Warning</source> <target state="new">&amp;Warning</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityWarning|CommandName"> <source>ErrorListSetSeverityWarning</source> <target state="new">ErrorListSetSeverityWarning</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityWarning|LocCanonicalName"> <source>Warning</source> <target state="new">Warning</target> <note /> </trans-unit> <trans-unit id="cmdidProjectContextAddAnalyzer|ButtonText"> <source>&amp;Analyzer...</source> <target state="translated">&amp;Analizator...</target> <note /> </trans-unit> <trans-unit id="cmdidProjectContextAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidProjectAddAnalyzer|ButtonText"> <source>Add &amp;Analyzer...</source> <target state="translated">Dodaj &amp;analizator...</target> <note /> </trans-unit> <trans-unit id="cmdidProjectAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidReferencesContextAddAnalyzer|ButtonText"> <source>Add &amp;Analyzer...</source> <target state="translated">Dodaj &amp;analizator...</target> <note /> </trans-unit> <trans-unit id="cmdidReferencesContextAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidAddAnalyzer|ButtonText"> <source>Add &amp;Analyzer...</source> <target state="translated">Dodaj &amp;analizator...</target> <note /> </trans-unit> <trans-unit id="cmdidAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveAnalyzer|ButtonText"> <source>&amp;Remove</source> <target state="translated">&amp;Usuń</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveAnalyzer|LocCanonicalName"> <source>RemoveAnalyzer</source> <target state="translated">RemoveAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveAnalyzer|CommandName"> <source>RemoveAnalyzer</source> <target state="translated">RemoveAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidOpenRuleSet|ButtonText"> <source>&amp;Open Active Rule Set</source> <target state="translated">&amp;Otwórz aktywny zestaw reguł</target> <note /> </trans-unit> <trans-unit id="cmdidOpenRuleSet|LocCanonicalName"> <source>OpenActiveRuleSet</source> <target state="translated">OpenActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidOpenRuleSet|CommandName"> <source>OpenActiveRuleSet</source> <target state="translated">OpenActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveUnusedReferences|ButtonText"> <source>Remove Unused References...</source> <target state="translated">Usuń nieużywane odwołania...</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveUnusedReferences|CommandName"> <source>RemoveUnusedReferences</source> <target state="translated">RemoveUnusedReferences</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveUnusedReferences|LocCanonicalName"> <source>RemoveUnusedReferences</source> <target state="translated">RemoveUnusedReferences</target> <note /> </trans-unit> <trans-unit id="cmdidRunCodeAnalysisForProject|ButtonText"> <source>Run C&amp;ode Analysis</source> <target state="translated">Uru&amp;chom analizę kodu</target> <note /> </trans-unit> <trans-unit id="cmdidRunCodeAnalysisForProject|CommandName"> <source>RunCodeAnalysisForProject</source> <target state="translated">RunCodeAnalysisForProject</target> <note /> </trans-unit> <trans-unit id="cmdidRunCodeAnalysisForProject|LocCanonicalName"> <source>RunCodeAnalysisForProject</source> <target state="translated">RunCodeAnalysisForProject</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityDefault|ButtonText"> <source>&amp;Default</source> <target state="translated">&amp;Domyślny</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityDefault|LocCanonicalName"> <source>Default</source> <target state="translated">Domyślny</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityDefault|CommandName"> <source>SetSeverityDefault</source> <target state="translated">SetSeverityDefault</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityError|ButtonText"> <source>&amp;Error</source> <target state="translated">&amp;Błąd</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityError|LocCanonicalName"> <source>Error</source> <target state="translated">Błąd</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityError|CommandName"> <source>SetSeverityError</source> <target state="translated">SetSeverityError</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityWarning|ButtonText"> <source>&amp;Warning</source> <target state="translated">&amp;Ostrzeżenie</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityWarning|LocCanonicalName"> <source>Warning</source> <target state="translated">Ostrzeżenie</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityWarning|CommandName"> <source>SetSeverityWarning</source> <target state="translated">SetSeverityWarning</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityInfo|ButtonText"> <source>&amp;Suggestion</source> <target state="translated">&amp;Sugestia</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityInfo|LocCanonicalName"> <source>Suggestion</source> <target state="translated">Sugestia</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityInfo|CommandName"> <source>SetSeverityInfo</source> <target state="translated">SetSeverityInfo</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityHidden|ButtonText"> <source>&amp;Silent</source> <target state="translated">&amp;Dyskretne</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityHidden|LocCanonicalName"> <source>Silent</source> <target state="translated">Dyskretne</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityHidden|CommandName"> <source>SetSeverityHidden</source> <target state="translated">SetSeverityHidden</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityNone|ButtonText"> <source>&amp;None</source> <target state="translated">&amp;Brak</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityNone|LocCanonicalName"> <source>None</source> <target state="translated">brak</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityNone|CommandName"> <source>SetSeverityNone</source> <target state="translated">SetSeverityNone</target> <note /> </trans-unit> <trans-unit id="cmdidOpenDiagnosticHelpLink|ButtonText"> <source>&amp;View Help...</source> <target state="translated">&amp;Pokaż pomoc...</target> <note /> </trans-unit> <trans-unit id="cmdidOpenDiagnosticHelpLink|LocCanonicalName"> <source>ViewHelp</source> <target state="translated">ViewHelp</target> <note /> </trans-unit> <trans-unit id="cmdidOpenDiagnosticHelpLink|CommandName"> <source>ViewHelp</source> <target state="translated">ViewHelp</target> <note /> </trans-unit> <trans-unit id="cmdidSetActiveRuleSet|ButtonText"> <source>&amp;Set as Active Rule Set</source> <target state="translated">&amp;Ustaw jako aktywny zestaw reguł</target> <note /> </trans-unit> <trans-unit id="cmdidSetActiveRuleSet|LocCanonicalName"> <source>SetAsActiveRuleSet</source> <target state="translated">SetAsActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidSetActiveRuleSet|CommandName"> <source>SetAsActiveRuleSet</source> <target state="translated">SetAsActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveSuppressions|ButtonText"> <source>Remove&amp; Suppression(s)</source> <target state="translated">Usuń &amp;pominięcia</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveSuppressions|LocCanonicalName"> <source>RemoveSuppressions</source> <target state="translated">RemoveSuppressions</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveSuppressions|CommandName"> <source>RemoveSuppressions</source> <target state="translated">RemoveSuppressions</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSource|ButtonText"> <source>In &amp;Source</source> <target state="translated">W źró&amp;dle</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSource|LocCanonicalName"> <source>AddSuppressionsInSource</source> <target state="translated">AddSuppressionsInSource</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSource|CommandName"> <source>AddSuppressionsInSource</source> <target state="translated">AddSuppressionsInSource</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSuppressionFile|ButtonText"> <source>In&amp; Suppression File</source> <target state="translated">W pli&amp;ku pominięć</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSuppressionFile|LocCanonicalName"> <source>AddSuppressionsInSuppressionFile</source> <target state="translated">AddSuppressionsInSuppressionFile</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSuppressionFile|CommandName"> <source>AddSuppressionsInSuppressionFile</source> <target state="translated">AddSuppressionsInSuppressionFile</target> <note /> </trans-unit> <trans-unit id="cmdidGoToImplementation|ButtonText"> <source>Go To Implementation</source> <target state="translated">Przejdź do implementacji</target> <note /> </trans-unit> <trans-unit id="cmdidGoToImplementation|LocCanonicalName"> <source>GoToImplementation</source> <target state="translated">GoToImplementation</target> <note /> </trans-unit> <trans-unit id="cmdidGoToImplementation|CommandName"> <source>Go To Implementation</source> <target state="translated">Przejdź do implementacji</target> <note /> </trans-unit> <trans-unit id="cmdidSyncNamespaces|ButtonText"> <source>Sync &amp;Namespaces</source> <target state="translated">Synchronizuj &amp;przestrzenie nazw</target> <note /> </trans-unit> <trans-unit id="cmdidSyncNamespaces|CommandName"> <source>SyncNamespaces</source> <target state="translated">SyncNamespaces</target> <note /> </trans-unit> <trans-unit id="cmdidSyncNamespaces|LocCanonicalName"> <source>SyncNamespaces</source> <target state="translated">SyncNamespaces</target> <note /> </trans-unit> <trans-unit id="cmdidshowValueTracking|ButtonText"> <source>Track Value Source</source> <target state="translated">Śledź źródło wartości</target> <note /> </trans-unit> <trans-unit id="cmdidshowValueTracking|CommandName"> <source>ShowValueTrackingCommandName</source> <target state="translated">ShowValueTrackingCommandName</target> <note /> </trans-unit> <trans-unit id="cmdidshowValueTracking|LocCanonicalName"> <source>ViewEditorConfigSettings</source> <target state="translated">ViewEditorConfigSettings</target> <note /> </trans-unit> <trans-unit id="guidCSharpInteractiveCommandSet|cmdidResetInteractiveFromProject|ButtonText"> <source>Initialize Interactive with Project</source> <target state="translated">Inicjuj środowisko interaktywne z projektem</target> <note /> </trans-unit> <trans-unit id="guidCSharpInteractiveCommandSet|cmdidResetInteractiveFromProject|LocCanonicalName"> <source>ResetC#InteractiveFromProject</source> <target state="translated">ResetC#InteractiveFromProject</target> <note /> </trans-unit> <trans-unit id="guidVisualBasicInteractiveCommandSet|cmdidResetInteractiveFromProject|ButtonText"> <source>Reset Visual Basic Interactive from Project</source> <target state="translated">Resetuj środowisko interaktywne z projektu programu Visual Basic</target> <note /> </trans-unit> <trans-unit id="guidVisualBasicInteractiveCommandSet|cmdidResetInteractiveFromProject|LocCanonicalName"> <source>ResetVisualBasicInteractiveFromProject</source> <target state="translated">ResetVisualBasicInteractiveFromProject</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerContextMenu|ButtonText"> <source>Analyzer</source> <target state="translated">Analizator</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerContextMenu|LocCanonicalName"> <source>Analyzer</source> <target state="translated">Analizator</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerFolderContextMenu|ButtonText"> <source>Analyzers</source> <target state="translated">Analizatory</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerFolderContextMenu|LocCanonicalName"> <source>Analyzers</source> <target state="translated">Analizatory</target> <note /> </trans-unit> <trans-unit id="cmdidDiagnosticContextMenu|ButtonText"> <source>Diagnostic</source> <target state="translated">Diagnostyka</target> <note /> </trans-unit> <trans-unit id="cmdidDiagnosticContextMenu|LocCanonicalName"> <source>Diagnostic</source> <target state="translated">Diagnostyka</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeveritySubMenu|ButtonText"> <source>Set severity</source> <target state="translated">Ustaw ważność</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeveritySubMenu|CommandName"> <source>Set severity</source> <target state="translated">Ustaw ważność</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeveritySubMenu|LocCanonicalName"> <source>Set severity</source> <target state="translated">Ustaw ważność</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsContextMenu|ButtonText"> <source>S&amp;uppress</source> <target state="translated">P&amp;omiń</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsContextMenu|LocCanonicalName"> <source>S&amp;uppress</source> <target state="translated">P&amp;omiń</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsContextMenu|CommandName"> <source>S&amp;uppress</source> <target state="translated">P&amp;omiń</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Compilers/VisualBasic/Portable/Binding/DocumentationCommentCrefBinder_TypeParameters.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 Imports System.Runtime.InteropServices Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class DocumentationCommentCrefBinder Inherits DocumentationCommentBinder Private NotInheritable Class TypeParametersBinder Inherits Binder Friend ReadOnly _typeParameters As Dictionary(Of String, CrefTypeParameterSymbol) Public Sub New(containingBinder As Binder, typeParameters As Dictionary(Of String, CrefTypeParameterSymbol)) MyBase.New(containingBinder) Me._typeParameters = typeParameters End Sub Friend Overrides Sub LookupInSingleBinder(lookupResult As LookupResult, name As String, arity As Integer, options As LookupOptions, originalBinder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(lookupResult.IsClear) Dim typeParameter As CrefTypeParameterSymbol = Nothing If Me._typeParameters.TryGetValue(name, typeParameter) Then lookupResult.SetFrom(CheckViability(typeParameter, arity, options Or LookupOptions.IgnoreAccessibility, Nothing, useSiteInfo)) End If End Sub Friend Overrides Sub AddLookupSymbolsInfoInSingleBinder(nameSet As LookupSymbolsInfo, options As LookupOptions, originalBinder As Binder) For Each typeParameter In _typeParameters.Values If originalBinder.CanAddLookupSymbolInfo(typeParameter, options, nameSet, Nothing) Then nameSet.AddSymbol(typeParameter, typeParameter.Name, 0) End If Next End Sub End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports System.Runtime.InteropServices Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class DocumentationCommentCrefBinder Inherits DocumentationCommentBinder Private NotInheritable Class TypeParametersBinder Inherits Binder Friend ReadOnly _typeParameters As Dictionary(Of String, CrefTypeParameterSymbol) Public Sub New(containingBinder As Binder, typeParameters As Dictionary(Of String, CrefTypeParameterSymbol)) MyBase.New(containingBinder) Me._typeParameters = typeParameters End Sub Friend Overrides Sub LookupInSingleBinder(lookupResult As LookupResult, name As String, arity As Integer, options As LookupOptions, originalBinder As Binder, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) Debug.Assert(lookupResult.IsClear) Dim typeParameter As CrefTypeParameterSymbol = Nothing If Me._typeParameters.TryGetValue(name, typeParameter) Then lookupResult.SetFrom(CheckViability(typeParameter, arity, options Or LookupOptions.IgnoreAccessibility, Nothing, useSiteInfo)) End If End Sub Friend Overrides Sub AddLookupSymbolsInfoInSingleBinder(nameSet As LookupSymbolsInfo, options As LookupOptions, originalBinder As Binder) For Each typeParameter In _typeParameters.Values If originalBinder.CanAddLookupSymbolInfo(typeParameter, options, nameSet, Nothing) Then nameSet.AddSymbol(typeParameter, typeParameter.Name, 0) End If Next End Sub End Class End Class End Namespace
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/AndKeywordRecommender.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 AndKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public AndKeywordRecommender() : base(SyntaxKind.AndKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsAtEndOfPattern; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 AndKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public AndKeywordRecommender() : base(SyntaxKind.AndKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsAtEndOfPattern; } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/TempPECompiler.TempPEProject.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.IO Imports System.Runtime.InteropServices.ComTypes Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop Imports Microsoft.VisualStudio.Shell.Interop Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim Partial Friend Class TempPECompiler Private Class TempPEProject Implements IVbCompilerProject Private ReadOnly _compilerHost As IVbCompilerHost Private ReadOnly _references As New HashSet(Of String)(StringComparer.OrdinalIgnoreCase) Private ReadOnly _files As New HashSet(Of String)(StringComparer.OrdinalIgnoreCase) Private _parseOptions As VisualBasicParseOptions Private _compilationOptions As VisualBasicCompilationOptions Private _outputPath As String Private _runtimeLibraries As ImmutableArray(Of String) Public Sub New(compilerHost As IVbCompilerHost) _compilerHost = compilerHost End Sub Public Function CompileAndGetErrorCount(metadataService As IMetadataService) As Integer Dim trees = _files.Select(Function(path) Using stream = FileUtilities.OpenRead(path) Return SyntaxFactory.ParseSyntaxTree(SourceText.From(stream), options:=_parseOptions, path:=path) End Using End Function) Dim metadataReferences = _references.Concat(_runtimeLibraries) _ .Distinct(StringComparer.InvariantCultureIgnoreCase) _ .Select(Function(path) metadataService.GetReference(path, MetadataReferenceProperties.Assembly)) Dim c = VisualBasicCompilation.Create( Path.GetFileName(_outputPath), trees, metadataReferences, _compilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)) Dim emitResult = c.Emit(_outputPath) Return emitResult.Diagnostics.Where(Function(d) d.Severity = DiagnosticSeverity.Error).Count() End Function Public Sub AddApplicationObjectVariable(wszClassName As String, wszMemberName As String) Implements IVbCompilerProject.AddApplicationObjectVariable Throw New NotImplementedException() End Sub Public Sub AddBuffer(wszBuffer As String, dwLen As Integer, wszMkr As String, itemid As UInteger, fAdvise As Boolean, fShowErrorsInTaskList As Boolean) Implements IVbCompilerProject.AddBuffer Throw New NotImplementedException() End Sub Public Function AddEmbeddedMetaDataReference(wszFileName As String) As Integer Implements IVbCompilerProject.AddEmbeddedMetaDataReference Return VSConstants.E_NOTIMPL End Function Public Sub AddEmbeddedProjectReference(pReferencedCompilerProject As IVbCompilerProject) Implements IVbCompilerProject.AddEmbeddedProjectReference Throw New NotImplementedException() End Sub Public Sub AddFile(wszFileName As String, itemid As UInteger, fAddDuringOpen As Boolean) Implements IVbCompilerProject.AddFile ' We are only ever given VSITEMIDs that are Nil because a TempPE project isn't ' associated with a IVsHierarchy. Contract.ThrowIfFalse(itemid = VSConstants.VSITEMID.Nil) _files.Add(wszFileName) End Sub Public Sub AddImport(wszImport As String) Implements IVbCompilerProject.AddImport Throw New NotImplementedException() End Sub Public Function AddMetaDataReference(wszFileName As String, bAssembly As Boolean) As Integer Implements IVbCompilerProject.AddMetaDataReference _references.Add(wszFileName) Return VSConstants.S_OK End Function Public Sub AddProjectReference(pReferencedCompilerProject As IVbCompilerProject) Implements IVbCompilerProject.AddProjectReference Throw New NotImplementedException() End Sub Public Sub AddResourceReference(wszFileName As String, wszName As String, fPublic As Boolean, fEmbed As Boolean) Implements IVbCompilerProject.AddResourceReference Throw New NotImplementedException() End Sub Public Function AdviseBuildStatusCallback(pIVbBuildStatusCallback As IVbBuildStatusCallback) As UInteger Implements IVbCompilerProject.AdviseBuildStatusCallback Throw New NotImplementedException() End Function Public Function CreateCodeModel(pProject As EnvDTE.Project, pProjectItem As EnvDTE.ProjectItem, ByRef pCodeModel As EnvDTE.CodeModel) As Integer Implements IVbCompilerProject.CreateCodeModel Throw New NotImplementedException() End Function Public Function CreateFileCodeModel(pProject As EnvDTE.Project, pProjectItem As EnvDTE.ProjectItem, ByRef pFileCodeModel As EnvDTE.FileCodeModel) As Integer Implements IVbCompilerProject.CreateFileCodeModel Throw New NotImplementedException() End Function Public Sub DeleteAllImports() Implements IVbCompilerProject.DeleteAllImports Throw New NotImplementedException() End Sub Public Sub DeleteAllResourceReferences() Implements IVbCompilerProject.DeleteAllResourceReferences Throw New NotImplementedException() End Sub Public Sub DeleteImport(wszImport As String) Implements IVbCompilerProject.DeleteImport Throw New NotImplementedException() End Sub Public Sub Disconnect() Implements IVbCompilerProject.Disconnect End Sub Public Function ENCRebuild(in_pProgram As Object, ByRef out_ppUpdate As Object) As Integer Implements IVbCompilerProject.ENCRebuild Throw New NotImplementedException() End Function Public Sub FinishEdit() Implements IVbCompilerProject.FinishEdit ' The project system calls BeginEdit/FinishEdit so we can batch and avoid doing ' expensive things between each call to one of the Add* methods. But since we're not ' doing anything expensive, this can be a no-op. End Sub Public Function GetDefaultReferences(cElements As Integer, ByRef rgbstrReferences() As String, ByVal cActualReferences As IntPtr) As Integer Implements IVbCompilerProject.GetDefaultReferences Throw New NotImplementedException() End Function Public Sub GetEntryPointsList(cItems As Integer, strList() As String, ByVal pcActualItems As IntPtr) Implements IVbCompilerProject.GetEntryPointsList Throw New NotImplementedException() End Sub Public Sub GetMethodFromLine(itemid As UInteger, iLine As Integer, ByRef pBstrProcName As String, ByRef pBstrClassName As String) Implements IVbCompilerProject.GetMethodFromLine Throw New NotImplementedException() End Sub Public Sub GetPEImage(ByRef ppImage As IntPtr) Implements IVbCompilerProject.GetPEImage Throw New NotImplementedException() End Sub Public Sub RemoveAllApplicationObjectVariables() Implements IVbCompilerProject.RemoveAllApplicationObjectVariables Throw New NotImplementedException() End Sub Public Sub RemoveAllReferences() Implements IVbCompilerProject.RemoveAllReferences Throw New NotImplementedException() End Sub Public Sub RemoveFile(wszFileName As String, itemid As UInteger) Implements IVbCompilerProject.RemoveFile Throw New NotImplementedException() End Sub Public Sub RemoveFileByName(wszPath As String) Implements IVbCompilerProject.RemoveFileByName Throw New NotImplementedException() End Sub Public Sub RemoveMetaDataReference(wszFileName As String) Implements IVbCompilerProject.RemoveMetaDataReference Throw New NotImplementedException() End Sub Public Sub RemoveProjectReference(pReferencedCompilerProject As IVbCompilerProject) Implements IVbCompilerProject.RemoveProjectReference Throw New NotImplementedException() End Sub Public Sub RenameDefaultNamespace(bstrDefaultNamespace As String) Implements IVbCompilerProject.RenameDefaultNamespace Throw New NotImplementedException() End Sub Public Sub RenameFile(wszOldFileName As String, wszNewFileName As String, itemid As UInteger) Implements IVbCompilerProject.RenameFile Throw New NotImplementedException() End Sub Public Sub RenameProject(wszNewProjectName As String) Implements IVbCompilerProject.RenameProject Throw New NotImplementedException() End Sub Public Sub ResumePostedNotifications() Implements IVbCompilerProject.ResumePostedNotifications Throw New NotImplementedException() End Sub Public Sub SetBackgroundCompilerPriorityLow() Implements IVbCompilerProject.SetBackgroundCompilerPriorityLow Throw New NotImplementedException() End Sub Public Sub SetBackgroundCompilerPriorityNormal() Implements IVbCompilerProject.SetBackgroundCompilerPriorityNormal Throw New NotImplementedException() End Sub Public Sub SetCompilerOptions(ByRef pCompilerOptions As VBCompilerOptions) Implements IVbCompilerProject.SetCompilerOptions _runtimeLibraries = VisualBasicProject.OptionsProcessor.GetRuntimeLibraries(_compilerHost, pCompilerOptions) _outputPath = PathUtilities.CombinePathsUnchecked(pCompilerOptions.wszOutputPath, pCompilerOptions.wszExeName) _parseOptions = VisualBasicProject.OptionsProcessor.ApplyVisualBasicParseOptionsFromCompilerOptions(VisualBasicParseOptions.Default, pCompilerOptions) ' Note that we pass a "default" compilation options with DLL set as output kind; the Apply method will figure out what the right one is and fix it up _compilationOptions = VisualBasicProject.OptionsProcessor.ApplyCompilationOptionsFromVBCompilerOptions( New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, parseOptions:=_parseOptions), pCompilerOptions) End Sub Public Sub SetModuleAssemblyName(wszName As String) Implements IVbCompilerProject.SetModuleAssemblyName Throw New NotImplementedException() End Sub Public Sub SetStreamForPDB(pStreamPDB As IStream) Implements IVbCompilerProject.SetStreamForPDB Throw New NotImplementedException() End Sub Public Sub StartBuild(pVsOutputWindowPane As IVsOutputWindowPane, fRebuildAll As Boolean) Implements IVbCompilerProject.StartBuild Throw New NotImplementedException() End Sub Public Sub StartDebugging() Implements IVbCompilerProject.StartDebugging Throw New NotImplementedException() End Sub Public Sub StartEdit() Implements IVbCompilerProject.StartEdit ' The project system calls BeginEdit/FinishEdit so we can batch and avoid doing ' expensive things between each call to one of the Add* methods. But since we're not ' doing anything expensive, this can be a no-op. End Sub Public Sub StopBuild() Implements IVbCompilerProject.StopBuild Throw New NotImplementedException() End Sub Public Sub StopDebugging() Implements IVbCompilerProject.StopDebugging Throw New NotImplementedException() End Sub Public Sub SuspendPostedNotifications() Implements IVbCompilerProject.SuspendPostedNotifications Throw New NotImplementedException() End Sub Public Sub UnadviseBuildStatusCallback(dwCookie As UInteger) Implements IVbCompilerProject.UnadviseBuildStatusCallback Throw New NotImplementedException() End Sub Public Sub WaitUntilBound() Implements IVbCompilerProject.WaitUntilBound Throw New NotImplementedException() End Sub End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.IO Imports System.Runtime.InteropServices.ComTypes Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop Imports Microsoft.VisualStudio.Shell.Interop Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim Partial Friend Class TempPECompiler Private Class TempPEProject Implements IVbCompilerProject Private ReadOnly _compilerHost As IVbCompilerHost Private ReadOnly _references As New HashSet(Of String)(StringComparer.OrdinalIgnoreCase) Private ReadOnly _files As New HashSet(Of String)(StringComparer.OrdinalIgnoreCase) Private _parseOptions As VisualBasicParseOptions Private _compilationOptions As VisualBasicCompilationOptions Private _outputPath As String Private _runtimeLibraries As ImmutableArray(Of String) Public Sub New(compilerHost As IVbCompilerHost) _compilerHost = compilerHost End Sub Public Function CompileAndGetErrorCount(metadataService As IMetadataService) As Integer Dim trees = _files.Select(Function(path) Using stream = FileUtilities.OpenRead(path) Return SyntaxFactory.ParseSyntaxTree(SourceText.From(stream), options:=_parseOptions, path:=path) End Using End Function) Dim metadataReferences = _references.Concat(_runtimeLibraries) _ .Distinct(StringComparer.InvariantCultureIgnoreCase) _ .Select(Function(path) metadataService.GetReference(path, MetadataReferenceProperties.Assembly)) Dim c = VisualBasicCompilation.Create( Path.GetFileName(_outputPath), trees, metadataReferences, _compilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)) Dim emitResult = c.Emit(_outputPath) Return emitResult.Diagnostics.Where(Function(d) d.Severity = DiagnosticSeverity.Error).Count() End Function Public Sub AddApplicationObjectVariable(wszClassName As String, wszMemberName As String) Implements IVbCompilerProject.AddApplicationObjectVariable Throw New NotImplementedException() End Sub Public Sub AddBuffer(wszBuffer As String, dwLen As Integer, wszMkr As String, itemid As UInteger, fAdvise As Boolean, fShowErrorsInTaskList As Boolean) Implements IVbCompilerProject.AddBuffer Throw New NotImplementedException() End Sub Public Function AddEmbeddedMetaDataReference(wszFileName As String) As Integer Implements IVbCompilerProject.AddEmbeddedMetaDataReference Return VSConstants.E_NOTIMPL End Function Public Sub AddEmbeddedProjectReference(pReferencedCompilerProject As IVbCompilerProject) Implements IVbCompilerProject.AddEmbeddedProjectReference Throw New NotImplementedException() End Sub Public Sub AddFile(wszFileName As String, itemid As UInteger, fAddDuringOpen As Boolean) Implements IVbCompilerProject.AddFile ' We are only ever given VSITEMIDs that are Nil because a TempPE project isn't ' associated with a IVsHierarchy. Contract.ThrowIfFalse(itemid = VSConstants.VSITEMID.Nil) _files.Add(wszFileName) End Sub Public Sub AddImport(wszImport As String) Implements IVbCompilerProject.AddImport Throw New NotImplementedException() End Sub Public Function AddMetaDataReference(wszFileName As String, bAssembly As Boolean) As Integer Implements IVbCompilerProject.AddMetaDataReference _references.Add(wszFileName) Return VSConstants.S_OK End Function Public Sub AddProjectReference(pReferencedCompilerProject As IVbCompilerProject) Implements IVbCompilerProject.AddProjectReference Throw New NotImplementedException() End Sub Public Sub AddResourceReference(wszFileName As String, wszName As String, fPublic As Boolean, fEmbed As Boolean) Implements IVbCompilerProject.AddResourceReference Throw New NotImplementedException() End Sub Public Function AdviseBuildStatusCallback(pIVbBuildStatusCallback As IVbBuildStatusCallback) As UInteger Implements IVbCompilerProject.AdviseBuildStatusCallback Throw New NotImplementedException() End Function Public Function CreateCodeModel(pProject As EnvDTE.Project, pProjectItem As EnvDTE.ProjectItem, ByRef pCodeModel As EnvDTE.CodeModel) As Integer Implements IVbCompilerProject.CreateCodeModel Throw New NotImplementedException() End Function Public Function CreateFileCodeModel(pProject As EnvDTE.Project, pProjectItem As EnvDTE.ProjectItem, ByRef pFileCodeModel As EnvDTE.FileCodeModel) As Integer Implements IVbCompilerProject.CreateFileCodeModel Throw New NotImplementedException() End Function Public Sub DeleteAllImports() Implements IVbCompilerProject.DeleteAllImports Throw New NotImplementedException() End Sub Public Sub DeleteAllResourceReferences() Implements IVbCompilerProject.DeleteAllResourceReferences Throw New NotImplementedException() End Sub Public Sub DeleteImport(wszImport As String) Implements IVbCompilerProject.DeleteImport Throw New NotImplementedException() End Sub Public Sub Disconnect() Implements IVbCompilerProject.Disconnect End Sub Public Function ENCRebuild(in_pProgram As Object, ByRef out_ppUpdate As Object) As Integer Implements IVbCompilerProject.ENCRebuild Throw New NotImplementedException() End Function Public Sub FinishEdit() Implements IVbCompilerProject.FinishEdit ' The project system calls BeginEdit/FinishEdit so we can batch and avoid doing ' expensive things between each call to one of the Add* methods. But since we're not ' doing anything expensive, this can be a no-op. End Sub Public Function GetDefaultReferences(cElements As Integer, ByRef rgbstrReferences() As String, ByVal cActualReferences As IntPtr) As Integer Implements IVbCompilerProject.GetDefaultReferences Throw New NotImplementedException() End Function Public Sub GetEntryPointsList(cItems As Integer, strList() As String, ByVal pcActualItems As IntPtr) Implements IVbCompilerProject.GetEntryPointsList Throw New NotImplementedException() End Sub Public Sub GetMethodFromLine(itemid As UInteger, iLine As Integer, ByRef pBstrProcName As String, ByRef pBstrClassName As String) Implements IVbCompilerProject.GetMethodFromLine Throw New NotImplementedException() End Sub Public Sub GetPEImage(ByRef ppImage As IntPtr) Implements IVbCompilerProject.GetPEImage Throw New NotImplementedException() End Sub Public Sub RemoveAllApplicationObjectVariables() Implements IVbCompilerProject.RemoveAllApplicationObjectVariables Throw New NotImplementedException() End Sub Public Sub RemoveAllReferences() Implements IVbCompilerProject.RemoveAllReferences Throw New NotImplementedException() End Sub Public Sub RemoveFile(wszFileName As String, itemid As UInteger) Implements IVbCompilerProject.RemoveFile Throw New NotImplementedException() End Sub Public Sub RemoveFileByName(wszPath As String) Implements IVbCompilerProject.RemoveFileByName Throw New NotImplementedException() End Sub Public Sub RemoveMetaDataReference(wszFileName As String) Implements IVbCompilerProject.RemoveMetaDataReference Throw New NotImplementedException() End Sub Public Sub RemoveProjectReference(pReferencedCompilerProject As IVbCompilerProject) Implements IVbCompilerProject.RemoveProjectReference Throw New NotImplementedException() End Sub Public Sub RenameDefaultNamespace(bstrDefaultNamespace As String) Implements IVbCompilerProject.RenameDefaultNamespace Throw New NotImplementedException() End Sub Public Sub RenameFile(wszOldFileName As String, wszNewFileName As String, itemid As UInteger) Implements IVbCompilerProject.RenameFile Throw New NotImplementedException() End Sub Public Sub RenameProject(wszNewProjectName As String) Implements IVbCompilerProject.RenameProject Throw New NotImplementedException() End Sub Public Sub ResumePostedNotifications() Implements IVbCompilerProject.ResumePostedNotifications Throw New NotImplementedException() End Sub Public Sub SetBackgroundCompilerPriorityLow() Implements IVbCompilerProject.SetBackgroundCompilerPriorityLow Throw New NotImplementedException() End Sub Public Sub SetBackgroundCompilerPriorityNormal() Implements IVbCompilerProject.SetBackgroundCompilerPriorityNormal Throw New NotImplementedException() End Sub Public Sub SetCompilerOptions(ByRef pCompilerOptions As VBCompilerOptions) Implements IVbCompilerProject.SetCompilerOptions _runtimeLibraries = VisualBasicProject.OptionsProcessor.GetRuntimeLibraries(_compilerHost, pCompilerOptions) _outputPath = PathUtilities.CombinePathsUnchecked(pCompilerOptions.wszOutputPath, pCompilerOptions.wszExeName) _parseOptions = VisualBasicProject.OptionsProcessor.ApplyVisualBasicParseOptionsFromCompilerOptions(VisualBasicParseOptions.Default, pCompilerOptions) ' Note that we pass a "default" compilation options with DLL set as output kind; the Apply method will figure out what the right one is and fix it up _compilationOptions = VisualBasicProject.OptionsProcessor.ApplyCompilationOptionsFromVBCompilerOptions( New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, parseOptions:=_parseOptions), pCompilerOptions) End Sub Public Sub SetModuleAssemblyName(wszName As String) Implements IVbCompilerProject.SetModuleAssemblyName Throw New NotImplementedException() End Sub Public Sub SetStreamForPDB(pStreamPDB As IStream) Implements IVbCompilerProject.SetStreamForPDB Throw New NotImplementedException() End Sub Public Sub StartBuild(pVsOutputWindowPane As IVsOutputWindowPane, fRebuildAll As Boolean) Implements IVbCompilerProject.StartBuild Throw New NotImplementedException() End Sub Public Sub StartDebugging() Implements IVbCompilerProject.StartDebugging Throw New NotImplementedException() End Sub Public Sub StartEdit() Implements IVbCompilerProject.StartEdit ' The project system calls BeginEdit/FinishEdit so we can batch and avoid doing ' expensive things between each call to one of the Add* methods. But since we're not ' doing anything expensive, this can be a no-op. End Sub Public Sub StopBuild() Implements IVbCompilerProject.StopBuild Throw New NotImplementedException() End Sub Public Sub StopDebugging() Implements IVbCompilerProject.StopDebugging Throw New NotImplementedException() End Sub Public Sub SuspendPostedNotifications() Implements IVbCompilerProject.SuspendPostedNotifications Throw New NotImplementedException() End Sub Public Sub UnadviseBuildStatusCallback(dwCookie As UInteger) Implements IVbCompilerProject.UnadviseBuildStatusCallback Throw New NotImplementedException() End Sub Public Sub WaitUntilBound() Implements IVbCompilerProject.WaitUntilBound Throw New NotImplementedException() End Sub End Class End Class End Namespace
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Compilers/Core/Portable/InternalUtilities/ReferenceEqualityComparer.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.Runtime.CompilerServices; namespace Roslyn.Utilities { /// <summary> /// Compares objects based upon their reference identity. /// </summary> internal class ReferenceEqualityComparer : IEqualityComparer<object?> { public static readonly ReferenceEqualityComparer Instance = new(); private ReferenceEqualityComparer() { } bool IEqualityComparer<object?>.Equals(object? a, object? b) { return a == b; } int IEqualityComparer<object?>.GetHashCode(object? a) { return ReferenceEqualityComparer.GetHashCode(a); } public static int GetHashCode(object? a) { // https://github.com/dotnet/roslyn/issues/41539 return RuntimeHelpers.GetHashCode(a!); } } }
// Licensed to the .NET Foundation under one or more 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.Runtime.CompilerServices; namespace Roslyn.Utilities { /// <summary> /// Compares objects based upon their reference identity. /// </summary> internal class ReferenceEqualityComparer : IEqualityComparer<object?> { public static readonly ReferenceEqualityComparer Instance = new(); private ReferenceEqualityComparer() { } bool IEqualityComparer<object?>.Equals(object? a, object? b) { return a == b; } int IEqualityComparer<object?>.GetHashCode(object? a) { return ReferenceEqualityComparer.GetHashCode(a); } public static int GetHashCode(object? a) { // https://github.com/dotnet/roslyn/issues/41539 return RuntimeHelpers.GetHashCode(a!); } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedProperty.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 Microsoft.CodeAnalysis.CodeGen; using Cci = Microsoft.Cci; namespace Microsoft.CodeAnalysis.Emit.NoPia { internal abstract partial class EmbeddedTypesManager< TPEModuleBuilder, TModuleCompilationState, TEmbeddedTypesManager, TSyntaxNode, TAttributeData, TSymbol, TAssemblySymbol, TNamedTypeSymbol, TFieldSymbol, TMethodSymbol, TEventSymbol, TPropertySymbol, TParameterSymbol, TTypeParameterSymbol, TEmbeddedType, TEmbeddedField, TEmbeddedMethod, TEmbeddedEvent, TEmbeddedProperty, TEmbeddedParameter, TEmbeddedTypeParameter> { internal abstract class CommonEmbeddedProperty : CommonEmbeddedMember<TPropertySymbol>, Cci.IPropertyDefinition { private readonly ImmutableArray<TEmbeddedParameter> _parameters; private readonly TEmbeddedMethod _getter; private readonly TEmbeddedMethod _setter; protected CommonEmbeddedProperty(TPropertySymbol underlyingProperty, TEmbeddedMethod getter, TEmbeddedMethod setter) : base(underlyingProperty) { Debug.Assert(getter != null || setter != null); _getter = getter; _setter = setter; _parameters = GetParameters(); } internal override TEmbeddedTypesManager TypeManager { get { return AnAccessor.TypeManager; } } protected abstract ImmutableArray<TEmbeddedParameter> GetParameters(); protected abstract bool IsRuntimeSpecial { get; } protected abstract bool IsSpecialName { get; } protected abstract Cci.ISignature UnderlyingPropertySignature { get; } protected abstract TEmbeddedType ContainingType { get; } protected abstract Cci.TypeMemberVisibility Visibility { get; } protected abstract string Name { get; } public TPropertySymbol UnderlyingProperty { get { return this.UnderlyingSymbol; } } Cci.IMethodReference Cci.IPropertyDefinition.Getter { get { return _getter; } } Cci.IMethodReference Cci.IPropertyDefinition.Setter { get { return _setter; } } IEnumerable<Cci.IMethodReference> Cci.IPropertyDefinition.GetAccessors(EmitContext context) { if (_getter != null) { yield return _getter; } if (_setter != null) { yield return _setter; } } bool Cci.IPropertyDefinition.HasDefaultValue { get { return false; } } MetadataConstant Cci.IPropertyDefinition.DefaultValue { get { return null; } } bool Cci.IPropertyDefinition.IsRuntimeSpecial { get { return IsRuntimeSpecial; } } bool Cci.IPropertyDefinition.IsSpecialName { get { return IsSpecialName; } } ImmutableArray<Cci.IParameterDefinition> Cci.IPropertyDefinition.Parameters { get { return StaticCast<Cci.IParameterDefinition>.From(_parameters); } } Cci.CallingConvention Cci.ISignature.CallingConvention { get { return UnderlyingPropertySignature.CallingConvention; } } ushort Cci.ISignature.ParameterCount { get { return (ushort)_parameters.Length; } } ImmutableArray<Cci.IParameterTypeInformation> Cci.ISignature.GetParameters(EmitContext context) { return StaticCast<Cci.IParameterTypeInformation>.From(_parameters); } ImmutableArray<Cci.ICustomModifier> Cci.ISignature.ReturnValueCustomModifiers { get { return UnderlyingPropertySignature.ReturnValueCustomModifiers; } } ImmutableArray<Cci.ICustomModifier> Cci.ISignature.RefCustomModifiers { get { return UnderlyingPropertySignature.RefCustomModifiers; } } bool Cci.ISignature.ReturnValueIsByRef { get { return UnderlyingPropertySignature.ReturnValueIsByRef; } } Cci.ITypeReference Cci.ISignature.GetType(EmitContext context) { return UnderlyingPropertySignature.GetType(context); } protected TEmbeddedMethod AnAccessor { get { return _getter ?? _setter; } } Cci.ITypeDefinition Cci.ITypeDefinitionMember.ContainingTypeDefinition { get { return ContainingType; } } Cci.TypeMemberVisibility Cci.ITypeDefinitionMember.Visibility { get { return Visibility; } } Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context) { return ContainingType; } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit((Cci.IPropertyDefinition)this); } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return this; } string Cci.INamedEntity.Name { get { return Name; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.CodeGen; using Cci = Microsoft.Cci; namespace Microsoft.CodeAnalysis.Emit.NoPia { internal abstract partial class EmbeddedTypesManager< TPEModuleBuilder, TModuleCompilationState, TEmbeddedTypesManager, TSyntaxNode, TAttributeData, TSymbol, TAssemblySymbol, TNamedTypeSymbol, TFieldSymbol, TMethodSymbol, TEventSymbol, TPropertySymbol, TParameterSymbol, TTypeParameterSymbol, TEmbeddedType, TEmbeddedField, TEmbeddedMethod, TEmbeddedEvent, TEmbeddedProperty, TEmbeddedParameter, TEmbeddedTypeParameter> { internal abstract class CommonEmbeddedProperty : CommonEmbeddedMember<TPropertySymbol>, Cci.IPropertyDefinition { private readonly ImmutableArray<TEmbeddedParameter> _parameters; private readonly TEmbeddedMethod _getter; private readonly TEmbeddedMethod _setter; protected CommonEmbeddedProperty(TPropertySymbol underlyingProperty, TEmbeddedMethod getter, TEmbeddedMethod setter) : base(underlyingProperty) { Debug.Assert(getter != null || setter != null); _getter = getter; _setter = setter; _parameters = GetParameters(); } internal override TEmbeddedTypesManager TypeManager { get { return AnAccessor.TypeManager; } } protected abstract ImmutableArray<TEmbeddedParameter> GetParameters(); protected abstract bool IsRuntimeSpecial { get; } protected abstract bool IsSpecialName { get; } protected abstract Cci.ISignature UnderlyingPropertySignature { get; } protected abstract TEmbeddedType ContainingType { get; } protected abstract Cci.TypeMemberVisibility Visibility { get; } protected abstract string Name { get; } public TPropertySymbol UnderlyingProperty { get { return this.UnderlyingSymbol; } } Cci.IMethodReference Cci.IPropertyDefinition.Getter { get { return _getter; } } Cci.IMethodReference Cci.IPropertyDefinition.Setter { get { return _setter; } } IEnumerable<Cci.IMethodReference> Cci.IPropertyDefinition.GetAccessors(EmitContext context) { if (_getter != null) { yield return _getter; } if (_setter != null) { yield return _setter; } } bool Cci.IPropertyDefinition.HasDefaultValue { get { return false; } } MetadataConstant Cci.IPropertyDefinition.DefaultValue { get { return null; } } bool Cci.IPropertyDefinition.IsRuntimeSpecial { get { return IsRuntimeSpecial; } } bool Cci.IPropertyDefinition.IsSpecialName { get { return IsSpecialName; } } ImmutableArray<Cci.IParameterDefinition> Cci.IPropertyDefinition.Parameters { get { return StaticCast<Cci.IParameterDefinition>.From(_parameters); } } Cci.CallingConvention Cci.ISignature.CallingConvention { get { return UnderlyingPropertySignature.CallingConvention; } } ushort Cci.ISignature.ParameterCount { get { return (ushort)_parameters.Length; } } ImmutableArray<Cci.IParameterTypeInformation> Cci.ISignature.GetParameters(EmitContext context) { return StaticCast<Cci.IParameterTypeInformation>.From(_parameters); } ImmutableArray<Cci.ICustomModifier> Cci.ISignature.ReturnValueCustomModifiers { get { return UnderlyingPropertySignature.ReturnValueCustomModifiers; } } ImmutableArray<Cci.ICustomModifier> Cci.ISignature.RefCustomModifiers { get { return UnderlyingPropertySignature.RefCustomModifiers; } } bool Cci.ISignature.ReturnValueIsByRef { get { return UnderlyingPropertySignature.ReturnValueIsByRef; } } Cci.ITypeReference Cci.ISignature.GetType(EmitContext context) { return UnderlyingPropertySignature.GetType(context); } protected TEmbeddedMethod AnAccessor { get { return _getter ?? _setter; } } Cci.ITypeDefinition Cci.ITypeDefinitionMember.ContainingTypeDefinition { get { return ContainingType; } } Cci.TypeMemberVisibility Cci.ITypeDefinitionMember.Visibility { get { return Visibility; } } Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context) { return ContainingType; } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit((Cci.IPropertyDefinition)this); } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return this; } string Cci.INamedEntity.Name { get { return Name; } } } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Compilers/Core/Portable/RuleSet/RuleSetInclude.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.IO; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a Include tag in a RuleSet file. /// </summary> public class RuleSetInclude { private readonly string _includePath; /// <summary> /// The path of the included file. /// </summary> public string IncludePath { get { return _includePath; } } private readonly ReportDiagnostic _action; /// <summary> /// The effective action to apply on this included ruleset. /// </summary> public ReportDiagnostic Action { get { return _action; } } /// <summary> /// Create a RuleSetInclude given the include path and the effective action. /// </summary> public RuleSetInclude(string includePath, ReportDiagnostic action) { _includePath = includePath; _action = action; } /// <summary> /// Gets the RuleSet associated with this ruleset include /// </summary> /// <param name="parent">The parent of this ruleset include</param> public RuleSet? LoadRuleSet(RuleSet parent) { // Try to load the rule set RuleSet? ruleSet = null; string? path = _includePath; try { path = GetIncludePath(parent); if (path == null) { return null; } ruleSet = RuleSetProcessor.LoadFromFile(path); } catch (FileNotFoundException) { // The compiler uses the same rule set files as FxCop, but doesn't have all of // the same logic for resolving included files. For the moment, just ignore any // includes we can't resolve. } catch (Exception e) { throw new InvalidRuleSetException(string.Format(CodeAnalysisResources.InvalidRuleSetInclude, path, e.Message)); } return ruleSet; } /// <summary> /// Returns a full path to the include file. Relative paths are expanded relative to the current rule set file. /// </summary> /// <param name="parent">The parent of this rule set include</param> private string? GetIncludePath(RuleSet parent) { var resolvedIncludePath = resolveIncludePath(_includePath, parent?.FilePath); if (resolvedIncludePath == null) { return null; } // Return the canonical full path return Path.GetFullPath(resolvedIncludePath); static string? resolveIncludePath(string includePath, string? parentRulesetPath) { var resolvedIncludePath = resolveIncludePathCore(includePath, parentRulesetPath); if (resolvedIncludePath == null && PathUtilities.IsUnixLikePlatform) { // Attempt to resolve legacy ruleset includes after replacing Windows style directory separator char with current plaform's directory separator char. includePath = includePath.Replace('\\', Path.DirectorySeparatorChar); resolvedIncludePath = resolveIncludePathCore(includePath, parentRulesetPath); } return resolvedIncludePath; } static string? resolveIncludePathCore(string includePath, string? parentRulesetPath) { includePath = Environment.ExpandEnvironmentVariables(includePath); // If a full path is specified then use it if (Path.IsPathRooted(includePath)) { if (File.Exists(includePath)) { return includePath; } } else if (!string.IsNullOrEmpty(parentRulesetPath)) { // Otherwise, try to find the include file relative to the parent ruleset. includePath = PathUtilities.CombinePathsUnchecked(Path.GetDirectoryName(parentRulesetPath) ?? "", includePath); if (File.Exists(includePath)) { return includePath; } } 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. using System; using System.IO; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a Include tag in a RuleSet file. /// </summary> public class RuleSetInclude { private readonly string _includePath; /// <summary> /// The path of the included file. /// </summary> public string IncludePath { get { return _includePath; } } private readonly ReportDiagnostic _action; /// <summary> /// The effective action to apply on this included ruleset. /// </summary> public ReportDiagnostic Action { get { return _action; } } /// <summary> /// Create a RuleSetInclude given the include path and the effective action. /// </summary> public RuleSetInclude(string includePath, ReportDiagnostic action) { _includePath = includePath; _action = action; } /// <summary> /// Gets the RuleSet associated with this ruleset include /// </summary> /// <param name="parent">The parent of this ruleset include</param> public RuleSet? LoadRuleSet(RuleSet parent) { // Try to load the rule set RuleSet? ruleSet = null; string? path = _includePath; try { path = GetIncludePath(parent); if (path == null) { return null; } ruleSet = RuleSetProcessor.LoadFromFile(path); } catch (FileNotFoundException) { // The compiler uses the same rule set files as FxCop, but doesn't have all of // the same logic for resolving included files. For the moment, just ignore any // includes we can't resolve. } catch (Exception e) { throw new InvalidRuleSetException(string.Format(CodeAnalysisResources.InvalidRuleSetInclude, path, e.Message)); } return ruleSet; } /// <summary> /// Returns a full path to the include file. Relative paths are expanded relative to the current rule set file. /// </summary> /// <param name="parent">The parent of this rule set include</param> private string? GetIncludePath(RuleSet parent) { var resolvedIncludePath = resolveIncludePath(_includePath, parent?.FilePath); if (resolvedIncludePath == null) { return null; } // Return the canonical full path return Path.GetFullPath(resolvedIncludePath); static string? resolveIncludePath(string includePath, string? parentRulesetPath) { var resolvedIncludePath = resolveIncludePathCore(includePath, parentRulesetPath); if (resolvedIncludePath == null && PathUtilities.IsUnixLikePlatform) { // Attempt to resolve legacy ruleset includes after replacing Windows style directory separator char with current plaform's directory separator char. includePath = includePath.Replace('\\', Path.DirectorySeparatorChar); resolvedIncludePath = resolveIncludePathCore(includePath, parentRulesetPath); } return resolvedIncludePath; } static string? resolveIncludePathCore(string includePath, string? parentRulesetPath) { includePath = Environment.ExpandEnvironmentVariables(includePath); // If a full path is specified then use it if (Path.IsPathRooted(includePath)) { if (File.Exists(includePath)) { return includePath; } } else if (!string.IsNullOrEmpty(parentRulesetPath)) { // Otherwise, try to find the include file relative to the parent ruleset. includePath = PathUtilities.CombinePathsUnchecked(Path.GetDirectoryName(parentRulesetPath) ?? "", includePath); if (File.Exists(includePath)) { return includePath; } } return null; } } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Workspaces/Core/Portable/Workspace/WorkspaceDiagnostic.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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public class WorkspaceDiagnostic { public WorkspaceDiagnosticKind Kind { get; } public string Message { get; } public WorkspaceDiagnostic(WorkspaceDiagnosticKind kind, string message) { this.Kind = kind; this.Message = message; } public override string ToString() { string kindText; switch (Kind) { case WorkspaceDiagnosticKind.Failure: kindText = WorkspacesResources.Failure; break; case WorkspaceDiagnosticKind.Warning: kindText = WorkspacesResources.Warning; break; default: throw ExceptionUtilities.UnexpectedValue(Kind); } return $"[{kindText}] {Message}"; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public class WorkspaceDiagnostic { public WorkspaceDiagnosticKind Kind { get; } public string Message { get; } public WorkspaceDiagnostic(WorkspaceDiagnosticKind kind, string message) { this.Kind = kind; this.Message = message; } public override string ToString() { string kindText; switch (Kind) { case WorkspaceDiagnosticKind.Failure: kindText = WorkspacesResources.Failure; break; case WorkspaceDiagnosticKind.Warning: kindText = WorkspacesResources.Warning; break; default: throw ExceptionUtilities.UnexpectedValue(Kind); } return $"[{kindText}] {Message}"; } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/EditorFeatures/VisualBasicTest/BasicServicesTest.Debug.xunit
<xunit> <assemblies> <assembly filename="..\..\..\..\Binaries\Debug\Roslyn.Services.VisualBasic.Implementation.UnitTests.dll" shadow-copy="true"/> </assemblies> </xunit>
<xunit> <assemblies> <assembly filename="..\..\..\..\Binaries\Debug\Roslyn.Services.VisualBasic.Implementation.UnitTests.dll" shadow-copy="true"/> </assemblies> </xunit>
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Features/Core/Portable/ExternalAccess/VSTypeScript/Api/VSTypeScriptDocumentNavigationServiceWrapper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal readonly struct VSTypeScriptDocumentNavigationServiceWrapper { private readonly IDocumentNavigationService _underlyingObject; public VSTypeScriptDocumentNavigationServiceWrapper(IDocumentNavigationService underlyingObject) => _underlyingObject = underlyingObject; public static VSTypeScriptDocumentNavigationServiceWrapper Create(Workspace workspace) => new(workspace.Services.GetRequiredService<IDocumentNavigationService>()); [Obsolete("Call overload that takes a CancellationToken", error: false)] public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace = 0, OptionSet? options = null) => this.TryNavigateToPosition(workspace, documentId, position, virtualSpace, options, CancellationToken.None); /// <inheritdoc cref="IDocumentNavigationService.TryNavigateToPosition"/> public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet? options, CancellationToken cancellationToken) => _underlyingObject.TryNavigateToPosition(workspace, documentId, position, virtualSpace, options, cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal readonly struct VSTypeScriptDocumentNavigationServiceWrapper { private readonly IDocumentNavigationService _underlyingObject; public VSTypeScriptDocumentNavigationServiceWrapper(IDocumentNavigationService underlyingObject) => _underlyingObject = underlyingObject; public static VSTypeScriptDocumentNavigationServiceWrapper Create(Workspace workspace) => new(workspace.Services.GetRequiredService<IDocumentNavigationService>()); [Obsolete("Call overload that takes a CancellationToken", error: false)] public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace = 0, OptionSet? options = null) => this.TryNavigateToPosition(workspace, documentId, position, virtualSpace, options, CancellationToken.None); /// <inheritdoc cref="IDocumentNavigationService.TryNavigateToPosition"/> public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet? options, CancellationToken cancellationToken) => _underlyingObject.TryNavigateToPosition(workspace, documentId, position, virtualSpace, options, cancellationToken); } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Test/Perf/tests/csharp/csharp_compiler.csx
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #r "../../Perf.Utilities/Roslyn.Test.Performance.Utilities.dll" using System.IO; using System.Collections.Generic; using Roslyn.Test.Performance.Utilities; using static Roslyn.Test.Performance.Utilities.TestUtilities; class CSharpCompilerTest: PerfTest { private string _rspFile; private ILogger _logger; public CSharpCompilerTest(string rspFile): base() { _rspFile = rspFile; _logger = new ConsoleAndFileLogger(); } public override void Setup() { DownloadProject("csharp", version: 1, logger: _logger); } public override void Test() { string responseFile = "@" + Path.Combine(TempDirectory, "csharp", _rspFile); string keyfileLocation = Path.Combine(TempDirectory, "csharp", "keyfile", "35MSSharedLib1024.snk"); string args = $"{responseFile} /keyfile:{keyfileLocation}"; string workingDirectory = Path.Combine(TempDirectory, "csharp"); ShellOutVital(Path.Combine(MyBinaries(), "Exes", "csc", "net46", "csc.exe"), args, workingDirectory); _logger.Flush(); } public override int Iterations => 3; public override string Name => "csharp " + _rspFile; public override string MeasuredProc => "csc"; public override bool ProvidesScenarios => false; public override string[] GetScenarios() { throw new System.NotImplementedException(); } } TestThisPlease( new CSharpCompilerTest("CSharpCompiler.rsp"), new CSharpCompilerTest("CSharpCompilerNoAnalyzer.rsp"), new CSharpCompilerTest("CSharpCompilerNoAnalyzerNoDeterminism.rsp") );
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #r "../../Perf.Utilities/Roslyn.Test.Performance.Utilities.dll" using System.IO; using System.Collections.Generic; using Roslyn.Test.Performance.Utilities; using static Roslyn.Test.Performance.Utilities.TestUtilities; class CSharpCompilerTest: PerfTest { private string _rspFile; private ILogger _logger; public CSharpCompilerTest(string rspFile): base() { _rspFile = rspFile; _logger = new ConsoleAndFileLogger(); } public override void Setup() { DownloadProject("csharp", version: 1, logger: _logger); } public override void Test() { string responseFile = "@" + Path.Combine(TempDirectory, "csharp", _rspFile); string keyfileLocation = Path.Combine(TempDirectory, "csharp", "keyfile", "35MSSharedLib1024.snk"); string args = $"{responseFile} /keyfile:{keyfileLocation}"; string workingDirectory = Path.Combine(TempDirectory, "csharp"); ShellOutVital(Path.Combine(MyBinaries(), "Exes", "csc", "net46", "csc.exe"), args, workingDirectory); _logger.Flush(); } public override int Iterations => 3; public override string Name => "csharp " + _rspFile; public override string MeasuredProc => "csc"; public override bool ProvidesScenarios => false; public override string[] GetScenarios() { throw new System.NotImplementedException(); } } TestThisPlease( new CSharpCompilerTest("CSharpCompiler.rsp"), new CSharpCompilerTest("CSharpCompilerNoAnalyzer.rsp"), new CSharpCompilerTest("CSharpCompilerNoAnalyzerNoDeterminism.rsp") );
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/EditorFeatures/Core/Extensibility/Composition/IContentTypeMetadata.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; namespace Microsoft.CodeAnalysis.Editor { internal interface IContentTypeMetadata { IEnumerable<string> ContentTypes { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Editor { internal interface IContentTypeMetadata { IEnumerable<string> ContentTypes { get; } } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/EditorFeatures/VisualBasicTest/KeywordHighlighting/WithBlockHighlighterTests.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.VisualBasic.KeywordHighlighting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting Public Class WithBlockHighlighterTests Inherits AbstractVisualBasicKeywordHighlighterTests Friend Overrides Function GetHighlighterType() As Type Return GetType(WithBlockHighlighter) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestWithBlock1() As Task Await TestAsync(<Text> Class C Sub M() {|Cursor:[|With|]|} y .x = 10 Console.WriteLine(.x) [|End With|] End Sub End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestWithBlock2() As Task Await TestAsync(<Text> Class C Sub M() [|With|] y .x = 10 Console.WriteLine(.x) {|Cursor:[|End With|]|} End Sub End Class</Text>) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting Public Class WithBlockHighlighterTests Inherits AbstractVisualBasicKeywordHighlighterTests Friend Overrides Function GetHighlighterType() As Type Return GetType(WithBlockHighlighter) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestWithBlock1() As Task Await TestAsync(<Text> Class C Sub M() {|Cursor:[|With|]|} y .x = 10 Console.WriteLine(.x) [|End With|] End Sub End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestWithBlock2() As Task Await TestAsync(<Text> Class C Sub M() [|With|] y .x = 10 Console.WriteLine(.x) {|Cursor:[|End With|]|} End Sub End Class</Text>) End Function End Class End Namespace
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Compilers/VisualBasic/Portable/BoundTree/BoundParameter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundParameter Public Sub New(syntax As SyntaxNode, parameterSymbol As ParameterSymbol, isLValue As Boolean, type As TypeSymbol, hasErrors As Boolean) Me.New(syntax, parameterSymbol, isLValue, suppressVirtualCalls:=False, type:=type, hasErrors:=hasErrors) End Sub Public Sub New(syntax As SyntaxNode, parameterSymbol As ParameterSymbol, isLValue As Boolean, type As TypeSymbol) Me.New(syntax, parameterSymbol, isLValue, suppressVirtualCalls:=False, type:=type) End Sub Public Sub New(syntax As SyntaxNode, parameterSymbol As ParameterSymbol, type As TypeSymbol, hasErrors As Boolean) Me.New(syntax, parameterSymbol, isLValue:=True, suppressVirtualCalls:=False, type:=type, hasErrors:=hasErrors) End Sub Public Sub New(syntax As SyntaxNode, parameterSymbol As ParameterSymbol, type As TypeSymbol) Me.New(syntax, parameterSymbol, isLValue:=True, suppressVirtualCalls:=False, type:=type) End Sub Public Overrides ReadOnly Property ExpressionSymbol As Symbol Get Return Me.ParameterSymbol End Get End Property Protected Overrides Function MakeRValueImpl() As BoundExpression Return MakeRValue() End Function Public Shadows Function MakeRValue() As BoundParameter If _IsLValue Then Return Me.Update(_ParameterSymbol, False, SuppressVirtualCalls, Type) End If Return Me End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundParameter Public Sub New(syntax As SyntaxNode, parameterSymbol As ParameterSymbol, isLValue As Boolean, type As TypeSymbol, hasErrors As Boolean) Me.New(syntax, parameterSymbol, isLValue, suppressVirtualCalls:=False, type:=type, hasErrors:=hasErrors) End Sub Public Sub New(syntax As SyntaxNode, parameterSymbol As ParameterSymbol, isLValue As Boolean, type As TypeSymbol) Me.New(syntax, parameterSymbol, isLValue, suppressVirtualCalls:=False, type:=type) End Sub Public Sub New(syntax As SyntaxNode, parameterSymbol As ParameterSymbol, type As TypeSymbol, hasErrors As Boolean) Me.New(syntax, parameterSymbol, isLValue:=True, suppressVirtualCalls:=False, type:=type, hasErrors:=hasErrors) End Sub Public Sub New(syntax As SyntaxNode, parameterSymbol As ParameterSymbol, type As TypeSymbol) Me.New(syntax, parameterSymbol, isLValue:=True, suppressVirtualCalls:=False, type:=type) End Sub Public Overrides ReadOnly Property ExpressionSymbol As Symbol Get Return Me.ParameterSymbol End Get End Property Protected Overrides Function MakeRValueImpl() As BoundExpression Return MakeRValue() End Function Public Shadows Function MakeRValue() As BoundParameter If _IsLValue Then Return Me.Update(_ParameterSymbol, False, SuppressVirtualCalls, Type) End If Return Me End Function End Class End Namespace
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/Dependencies/Collections/ImmutableSegmentedDictionary`2+KeyCollection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Collections { internal readonly partial struct ImmutableSegmentedDictionary<TKey, TValue> { public readonly partial struct KeyCollection : IReadOnlyCollection<TKey>, ICollection<TKey>, ICollection { private readonly ImmutableSegmentedDictionary<TKey, TValue> _dictionary; internal KeyCollection(ImmutableSegmentedDictionary<TKey, TValue> dictionary) { _dictionary = dictionary; } public int Count => _dictionary.Count; bool ICollection<TKey>.IsReadOnly => true; bool ICollection.IsSynchronized => true; object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot; public Enumerator GetEnumerator() => new(_dictionary.GetEnumerator()); public bool Contains(TKey item) => _dictionary.ContainsKey(item); IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); void ICollection<TKey>.CopyTo(TKey[] array, int arrayIndex) => ((ICollection<TKey>)_dictionary._dictionary.Keys).CopyTo(array, arrayIndex); void ICollection.CopyTo(Array array, int index) => ((ICollection)_dictionary._dictionary.Keys).CopyTo(array, index); void ICollection<TKey>.Add(TKey item) => throw new NotSupportedException(); void ICollection<TKey>.Clear() => throw new NotSupportedException(); bool ICollection<TKey>.Remove(TKey item) => throw new NotSupportedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Collections { internal readonly partial struct ImmutableSegmentedDictionary<TKey, TValue> { public readonly partial struct KeyCollection : IReadOnlyCollection<TKey>, ICollection<TKey>, ICollection { private readonly ImmutableSegmentedDictionary<TKey, TValue> _dictionary; internal KeyCollection(ImmutableSegmentedDictionary<TKey, TValue> dictionary) { _dictionary = dictionary; } public int Count => _dictionary.Count; bool ICollection<TKey>.IsReadOnly => true; bool ICollection.IsSynchronized => true; object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot; public Enumerator GetEnumerator() => new(_dictionary.GetEnumerator()); public bool Contains(TKey item) => _dictionary.ContainsKey(item); IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); void ICollection<TKey>.CopyTo(TKey[] array, int arrayIndex) => ((ICollection<TKey>)_dictionary._dictionary.Keys).CopyTo(array, arrayIndex); void ICollection.CopyTo(Array array, int index) => ((ICollection)_dictionary._dictionary.Keys).CopyTo(array, index); void ICollection<TKey>.Add(TKey item) => throw new NotSupportedException(); void ICollection<TKey>.Clear() => throw new NotSupportedException(); bool ICollection<TKey>.Remove(TKey item) => throw new NotSupportedException(); } } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Compilers/Core/CodeAnalysisTest/DefaultAnalyzerAssemblyLoaderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.UnitTests { [CollectionDefinition(Name)] public class AssemblyLoadTestFixtureCollection : ICollectionFixture<AssemblyLoadTestFixture> { public const string Name = nameof(AssemblyLoadTestFixtureCollection); private AssemblyLoadTestFixtureCollection() { } } [Collection(AssemblyLoadTestFixtureCollection.Name)] public sealed class DefaultAnalyzerAssemblyLoaderTests : TestBase { private static readonly CSharpCompilationOptions s_dllWithMaxWarningLevel = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: CodeAnalysis.Diagnostic.MaxWarningLevel); private readonly ITestOutputHelper _output; private readonly AssemblyLoadTestFixture _testFixture; public DefaultAnalyzerAssemblyLoaderTests(ITestOutputHelper output, AssemblyLoadTestFixture testFixture) { _output = output; _testFixture = testFixture; } [Fact, WorkItem(32226, "https://github.com/dotnet/roslyn/issues/32226")] public void LoadWithDependency() { var analyzerDependencyFile = _testFixture.AnalyzerDependency; var analyzerMainFile = _testFixture.AnalyzerWithDependency; var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(analyzerDependencyFile.Path); var analyzerMainReference = new AnalyzerFileReference(analyzerMainFile.Path, loader); analyzerMainReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message); var analyzerDependencyReference = new AnalyzerFileReference(analyzerDependencyFile.Path, loader); analyzerDependencyReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message); var analyzers = analyzerMainReference.GetAnalyzersForAllLanguages(); Assert.Equal(1, analyzers.Length); Assert.Equal("TestAnalyzer", analyzers[0].ToString()); Assert.Equal(0, analyzerDependencyReference.GetAnalyzersForAllLanguages().Length); Assert.NotNull(analyzerDependencyReference.GetAssembly()); } [Fact] public void AddDependencyLocationThrowsOnNull() { var loader = new DefaultAnalyzerAssemblyLoader(); Assert.Throws<ArgumentNullException>("fullPath", () => loader.AddDependencyLocation(null)); Assert.Throws<ArgumentException>("fullPath", () => loader.AddDependencyLocation("a")); } [Fact] public void ThrowsForMissingFile() { var path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".dll"); var loader = new DefaultAnalyzerAssemblyLoader(); Assert.ThrowsAny<Exception>(() => loader.LoadFromPath(path)); } [Fact] public void BasicLoad() { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Alpha.Path); Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path); Assert.NotNull(alpha); } [Fact] public void AssemblyLoading() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Alpha.Path); loader.AddDependencyLocation(_testFixture.Beta.Path); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path); var a = alpha.CreateInstance("Alpha.A")!; a.GetType().GetMethod("Write")!.Invoke(a, new object[] { sb, "Test A" }); Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path); var b = beta.CreateInstance("Beta.B")!; b.GetType().GetMethod("Write")!.Invoke(b, new object[] { sb, "Test B" }); var expected = @"Delta: Gamma: Alpha: Test A Delta: Gamma: Beta: Test B "; var actual = sb.ToString(); Assert.Equal(expected, actual); } [ConditionalFact(typeof(CoreClrOnly))] public void AssemblyLoading_AssemblyLocationNotAdded() { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); Assert.Throws<FileNotFoundException>(() => loader.LoadFromPath(_testFixture.Beta.Path)); } [ConditionalFact(typeof(CoreClrOnly))] public void AssemblyLoading_DependencyLocationNotAdded() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); // We don't pass Alpha's path to AddDependencyLocation here, and therefore expect // calling Beta.B.Write to fail. loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Beta.Path); Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path); var b = beta.CreateInstance("Beta.B")!; var writeMethod = b.GetType().GetMethod("Write")!; var exception = Assert.Throws<TargetInvocationException>( () => writeMethod.Invoke(b, new object[] { sb, "Test B" })); Assert.IsAssignableFrom<FileNotFoundException>(exception.InnerException); var actual = sb.ToString(); Assert.Equal(@"", actual); } [Fact] public void AssemblyLoading_MultipleVersions() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); loader.AddDependencyLocation(_testFixture.Epsilon.Path); loader.AddDependencyLocation(_testFixture.Delta2.Path); Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G")!; g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); #if NETCOREAPP var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader); Assert.Equal(2, alcs.Length); Assert.Equal(new[] { ("Delta", "1.0.0.0", _testFixture.Delta1.Path), ("Gamma", "0.0.0.0", _testFixture.Gamma.Path) }, alcs[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order()); Assert.Equal(new[] { ("Delta", "2.0.0.0", _testFixture.Delta2.Path), ("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path) }, alcs[1].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order()); #endif var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { Assert.Equal( @"Delta: Gamma: Test G Delta.2: Epsilon: Test E ", actual); } else { Assert.Equal( @"Delta: Gamma: Test G Delta: Epsilon: Test E ", actual); } } [Fact] public void AssemblyLoading_MultipleVersions_MultipleLoaders() { StringBuilder sb = new StringBuilder(); var loader1 = new DefaultAnalyzerAssemblyLoader(); loader1.AddDependencyLocation(_testFixture.Gamma.Path); loader1.AddDependencyLocation(_testFixture.Delta1.Path); var loader2 = new DefaultAnalyzerAssemblyLoader(); loader2.AddDependencyLocation(_testFixture.Epsilon.Path); loader2.AddDependencyLocation(_testFixture.Delta2.Path); Assembly gamma = loader1.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G")!; g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader2.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); #if NETCOREAPP var alcs1 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader1); Assert.Equal(1, alcs1.Length); Assert.Equal(new[] { ("Delta", "1.0.0.0", _testFixture.Delta1.Path), ("Gamma", "0.0.0.0", _testFixture.Gamma.Path) }, alcs1[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order()); var alcs2 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader2); Assert.Equal(1, alcs2.Length); Assert.Equal(new[] { ("Delta", "2.0.0.0", _testFixture.Delta2.Path), ("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path) }, alcs2[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order()); #endif var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { Assert.Equal( @"Delta: Gamma: Test G Delta.2: Epsilon: Test E ", actual); } else { Assert.Equal( @"Delta: Gamma: Test G Delta: Epsilon: Test E ", actual); } } [Fact] public void AssemblyLoading_MultipleVersions_MissingVersion() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); loader.AddDependencyLocation(_testFixture.Epsilon.Path); Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G")!; g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; var eWrite = e.GetType().GetMethod("Write")!; var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { var exception = Assert.Throws<TargetInvocationException>(() => eWrite.Invoke(e, new object[] { sb, "Test E" })); Assert.IsAssignableFrom<FileNotFoundException>(exception.InnerException); } else { eWrite.Invoke(e, new object[] { sb, "Test E" }); Assert.Equal( @"Delta: Gamma: Test G ", actual); } } [Fact] public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_01() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path); loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path); var analyzer = analyzerAssembly.CreateInstance("Analyzer")!; if (ExecutionConditionUtil.IsCoreClr) { var ex = Assert.ThrowsAny<Exception>(() => analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb })); Assert.True(ex is MissingMethodException or TargetInvocationException, $@"Unexpected exception type: ""{ex.GetType()}"""); } else { analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb }); Assert.Equal("42", sb.ToString()); } } [Fact] public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_02() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path); loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path); var analyzer = analyzerAssembly.CreateInstance("Analyzer")!; analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb }); Assert.Equal(ExecutionConditionUtil.IsCoreClr ? "1" : "42", sb.ToString()); } [ConditionalFact(typeof(WindowsOnly), typeof(CoreClrOnly))] public void AssemblyLoading_NativeDependency() { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.AnalyzerWithNativeDependency.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerWithNativeDependency.Path); var analyzer = analyzerAssembly.CreateInstance("Class1")!; var result = analyzer.GetType().GetMethod("GetFileAttributes")!.Invoke(analyzer, new[] { _testFixture.AnalyzerWithNativeDependency.Path }); Assert.Equal(0, Marshal.GetLastWin32Error()); Assert.Equal(FileAttributes.Archive, (FileAttributes)result!); } [Fact] public void AssemblyLoading_Delete() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); var tempDir = Temp.CreateDirectory(); var deltaCopy = tempDir.CreateFile("Delta.dll").CopyContentFrom(_testFixture.Delta1.Path); loader.AddDependencyLocation(deltaCopy.Path); Assembly delta = loader.LoadFromPath(deltaCopy.Path); try { File.Delete(deltaCopy.Path); } catch (UnauthorizedAccessException) { return; } // The above call may or may not throw depending on the platform configuration. // If it doesn't throw, we might as well check that things are still functioning reasonably. var d = delta.CreateInstance("Delta.D"); d!.GetType().GetMethod("Write")!.Invoke(d, new object[] { sb, "Test D" }); var actual = sb.ToString(); Assert.Equal( @"Delta: Test D ", actual); } #if NETCOREAPP [Fact] public void VerifyCompilerAssemblySimpleNames() { var caAssembly = typeof(Microsoft.CodeAnalysis.SyntaxNode).Assembly; var caReferences = caAssembly.GetReferencedAssemblies(); var allReferenceSimpleNames = ArrayBuilder<string>.GetInstance(); allReferenceSimpleNames.Add(caAssembly.GetName().Name ?? throw new InvalidOperationException()); foreach (var reference in caReferences) { allReferenceSimpleNames.Add(reference.Name ?? throw new InvalidOperationException()); } var csAssembly = typeof(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode).Assembly; allReferenceSimpleNames.Add(csAssembly.GetName().Name ?? throw new InvalidOperationException()); var csReferences = csAssembly.GetReferencedAssemblies(); foreach (var reference in csReferences) { var name = reference.Name ?? throw new InvalidOperationException(); if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase)) { allReferenceSimpleNames.Add(name); } } var vbAssembly = typeof(Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxNode).Assembly; var vbReferences = vbAssembly.GetReferencedAssemblies(); allReferenceSimpleNames.Add(vbAssembly.GetName().Name ?? throw new InvalidOperationException()); foreach (var reference in vbReferences) { var name = reference.Name ?? throw new InvalidOperationException(); if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase)) { allReferenceSimpleNames.Add(name); } } if (!DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames.SetEquals(allReferenceSimpleNames)) { allReferenceSimpleNames.Sort(); var allNames = string.Join(",\r\n ", allReferenceSimpleNames.Select(name => $@"""{name}""")); _output.WriteLine(" internal static readonly ImmutableHashSet<string> CompilerAssemblySimpleNames ="); _output.WriteLine(" ImmutableHashSet.Create("); _output.WriteLine(" StringComparer.OrdinalIgnoreCase,"); _output.WriteLine($" {allNames});"); allReferenceSimpleNames.Free(); Assert.True(false, $"{nameof(DefaultAnalyzerAssemblyLoader)}.{nameof(DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames)} is not up to date. Paste in the standard output of this test to update it."); } else { allReferenceSimpleNames.Free(); } } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.UnitTests { [CollectionDefinition(Name)] public class AssemblyLoadTestFixtureCollection : ICollectionFixture<AssemblyLoadTestFixture> { public const string Name = nameof(AssemblyLoadTestFixtureCollection); private AssemblyLoadTestFixtureCollection() { } } [Collection(AssemblyLoadTestFixtureCollection.Name)] public sealed class DefaultAnalyzerAssemblyLoaderTests : TestBase { private static readonly CSharpCompilationOptions s_dllWithMaxWarningLevel = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: CodeAnalysis.Diagnostic.MaxWarningLevel); private readonly ITestOutputHelper _output; private readonly AssemblyLoadTestFixture _testFixture; public DefaultAnalyzerAssemblyLoaderTests(ITestOutputHelper output, AssemblyLoadTestFixture testFixture) { _output = output; _testFixture = testFixture; } [Fact, WorkItem(32226, "https://github.com/dotnet/roslyn/issues/32226")] public void LoadWithDependency() { var analyzerDependencyFile = _testFixture.AnalyzerDependency; var analyzerMainFile = _testFixture.AnalyzerWithDependency; var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(analyzerDependencyFile.Path); var analyzerMainReference = new AnalyzerFileReference(analyzerMainFile.Path, loader); analyzerMainReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message); var analyzerDependencyReference = new AnalyzerFileReference(analyzerDependencyFile.Path, loader); analyzerDependencyReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message); var analyzers = analyzerMainReference.GetAnalyzersForAllLanguages(); Assert.Equal(1, analyzers.Length); Assert.Equal("TestAnalyzer", analyzers[0].ToString()); Assert.Equal(0, analyzerDependencyReference.GetAnalyzersForAllLanguages().Length); Assert.NotNull(analyzerDependencyReference.GetAssembly()); } [Fact] public void AddDependencyLocationThrowsOnNull() { var loader = new DefaultAnalyzerAssemblyLoader(); Assert.Throws<ArgumentNullException>("fullPath", () => loader.AddDependencyLocation(null)); Assert.Throws<ArgumentException>("fullPath", () => loader.AddDependencyLocation("a")); } [Fact] public void ThrowsForMissingFile() { var path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".dll"); var loader = new DefaultAnalyzerAssemblyLoader(); Assert.ThrowsAny<Exception>(() => loader.LoadFromPath(path)); } [Fact] public void BasicLoad() { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Alpha.Path); Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path); Assert.NotNull(alpha); } [Fact] public void AssemblyLoading() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Alpha.Path); loader.AddDependencyLocation(_testFixture.Beta.Path); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path); var a = alpha.CreateInstance("Alpha.A")!; a.GetType().GetMethod("Write")!.Invoke(a, new object[] { sb, "Test A" }); Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path); var b = beta.CreateInstance("Beta.B")!; b.GetType().GetMethod("Write")!.Invoke(b, new object[] { sb, "Test B" }); var expected = @"Delta: Gamma: Alpha: Test A Delta: Gamma: Beta: Test B "; var actual = sb.ToString(); Assert.Equal(expected, actual); } [ConditionalFact(typeof(CoreClrOnly))] public void AssemblyLoading_AssemblyLocationNotAdded() { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); Assert.Throws<FileNotFoundException>(() => loader.LoadFromPath(_testFixture.Beta.Path)); } [ConditionalFact(typeof(CoreClrOnly))] public void AssemblyLoading_DependencyLocationNotAdded() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); // We don't pass Alpha's path to AddDependencyLocation here, and therefore expect // calling Beta.B.Write to fail. loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Beta.Path); Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path); var b = beta.CreateInstance("Beta.B")!; var writeMethod = b.GetType().GetMethod("Write")!; var exception = Assert.Throws<TargetInvocationException>( () => writeMethod.Invoke(b, new object[] { sb, "Test B" })); Assert.IsAssignableFrom<FileNotFoundException>(exception.InnerException); var actual = sb.ToString(); Assert.Equal(@"", actual); } [Fact] public void AssemblyLoading_MultipleVersions() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); loader.AddDependencyLocation(_testFixture.Epsilon.Path); loader.AddDependencyLocation(_testFixture.Delta2.Path); Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G")!; g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); #if NETCOREAPP var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader); Assert.Equal(2, alcs.Length); Assert.Equal(new[] { ("Delta", "1.0.0.0", _testFixture.Delta1.Path), ("Gamma", "0.0.0.0", _testFixture.Gamma.Path) }, alcs[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order()); Assert.Equal(new[] { ("Delta", "2.0.0.0", _testFixture.Delta2.Path), ("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path) }, alcs[1].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order()); #endif var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { Assert.Equal( @"Delta: Gamma: Test G Delta.2: Epsilon: Test E ", actual); } else { Assert.Equal( @"Delta: Gamma: Test G Delta: Epsilon: Test E ", actual); } } [Fact] public void AssemblyLoading_MultipleVersions_MultipleLoaders() { StringBuilder sb = new StringBuilder(); var loader1 = new DefaultAnalyzerAssemblyLoader(); loader1.AddDependencyLocation(_testFixture.Gamma.Path); loader1.AddDependencyLocation(_testFixture.Delta1.Path); var loader2 = new DefaultAnalyzerAssemblyLoader(); loader2.AddDependencyLocation(_testFixture.Epsilon.Path); loader2.AddDependencyLocation(_testFixture.Delta2.Path); Assembly gamma = loader1.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G")!; g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader2.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); #if NETCOREAPP var alcs1 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader1); Assert.Equal(1, alcs1.Length); Assert.Equal(new[] { ("Delta", "1.0.0.0", _testFixture.Delta1.Path), ("Gamma", "0.0.0.0", _testFixture.Gamma.Path) }, alcs1[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order()); var alcs2 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader2); Assert.Equal(1, alcs2.Length); Assert.Equal(new[] { ("Delta", "2.0.0.0", _testFixture.Delta2.Path), ("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path) }, alcs2[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order()); #endif var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { Assert.Equal( @"Delta: Gamma: Test G Delta.2: Epsilon: Test E ", actual); } else { Assert.Equal( @"Delta: Gamma: Test G Delta: Epsilon: Test E ", actual); } } [Fact] public void AssemblyLoading_MultipleVersions_MissingVersion() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); loader.AddDependencyLocation(_testFixture.Epsilon.Path); Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G")!; g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; var eWrite = e.GetType().GetMethod("Write")!; var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { var exception = Assert.Throws<TargetInvocationException>(() => eWrite.Invoke(e, new object[] { sb, "Test E" })); Assert.IsAssignableFrom<FileNotFoundException>(exception.InnerException); } else { eWrite.Invoke(e, new object[] { sb, "Test E" }); Assert.Equal( @"Delta: Gamma: Test G ", actual); } } [Fact] public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_01() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path); loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path); var analyzer = analyzerAssembly.CreateInstance("Analyzer")!; if (ExecutionConditionUtil.IsCoreClr) { var ex = Assert.ThrowsAny<Exception>(() => analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb })); Assert.True(ex is MissingMethodException or TargetInvocationException, $@"Unexpected exception type: ""{ex.GetType()}"""); } else { analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb }); Assert.Equal("42", sb.ToString()); } } [Fact] public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_02() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path); loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path); var analyzer = analyzerAssembly.CreateInstance("Analyzer")!; analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb }); Assert.Equal(ExecutionConditionUtil.IsCoreClr ? "1" : "42", sb.ToString()); } [ConditionalFact(typeof(WindowsOnly), typeof(CoreClrOnly))] public void AssemblyLoading_NativeDependency() { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.AnalyzerWithNativeDependency.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerWithNativeDependency.Path); var analyzer = analyzerAssembly.CreateInstance("Class1")!; var result = analyzer.GetType().GetMethod("GetFileAttributes")!.Invoke(analyzer, new[] { _testFixture.AnalyzerWithNativeDependency.Path }); Assert.Equal(0, Marshal.GetLastWin32Error()); Assert.Equal(FileAttributes.Archive, (FileAttributes)result!); } [Fact] public void AssemblyLoading_Delete() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); var tempDir = Temp.CreateDirectory(); var deltaCopy = tempDir.CreateFile("Delta.dll").CopyContentFrom(_testFixture.Delta1.Path); loader.AddDependencyLocation(deltaCopy.Path); Assembly delta = loader.LoadFromPath(deltaCopy.Path); try { File.Delete(deltaCopy.Path); } catch (UnauthorizedAccessException) { return; } // The above call may or may not throw depending on the platform configuration. // If it doesn't throw, we might as well check that things are still functioning reasonably. var d = delta.CreateInstance("Delta.D"); d!.GetType().GetMethod("Write")!.Invoke(d, new object[] { sb, "Test D" }); var actual = sb.ToString(); Assert.Equal( @"Delta: Test D ", actual); } #if NETCOREAPP [Fact] public void VerifyCompilerAssemblySimpleNames() { var caAssembly = typeof(Microsoft.CodeAnalysis.SyntaxNode).Assembly; var caReferences = caAssembly.GetReferencedAssemblies(); var allReferenceSimpleNames = ArrayBuilder<string>.GetInstance(); allReferenceSimpleNames.Add(caAssembly.GetName().Name ?? throw new InvalidOperationException()); foreach (var reference in caReferences) { allReferenceSimpleNames.Add(reference.Name ?? throw new InvalidOperationException()); } var csAssembly = typeof(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode).Assembly; allReferenceSimpleNames.Add(csAssembly.GetName().Name ?? throw new InvalidOperationException()); var csReferences = csAssembly.GetReferencedAssemblies(); foreach (var reference in csReferences) { var name = reference.Name ?? throw new InvalidOperationException(); if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase)) { allReferenceSimpleNames.Add(name); } } var vbAssembly = typeof(Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxNode).Assembly; var vbReferences = vbAssembly.GetReferencedAssemblies(); allReferenceSimpleNames.Add(vbAssembly.GetName().Name ?? throw new InvalidOperationException()); foreach (var reference in vbReferences) { var name = reference.Name ?? throw new InvalidOperationException(); if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase)) { allReferenceSimpleNames.Add(name); } } if (!DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames.SetEquals(allReferenceSimpleNames)) { allReferenceSimpleNames.Sort(); var allNames = string.Join(",\r\n ", allReferenceSimpleNames.Select(name => $@"""{name}""")); _output.WriteLine(" internal static readonly ImmutableHashSet<string> CompilerAssemblySimpleNames ="); _output.WriteLine(" ImmutableHashSet.Create("); _output.WriteLine(" StringComparer.OrdinalIgnoreCase,"); _output.WriteLine($" {allNames});"); allReferenceSimpleNames.Free(); Assert.True(false, $"{nameof(DefaultAnalyzerAssemblyLoader)}.{nameof(DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames)} is not up to date. Paste in the standard output of this test to update it."); } else { allReferenceSimpleNames.Free(); } } [Fact] public void AssemblyLoadingInNonDefaultContext_AnalyzerReferencesSystemCollectionsImmutable() { // Create a separate ALC as the compiler context, load the compiler assembly and a modified version of S.C.I into it, // then use that to load and run `AssemblyLoadingInNonDefaultContextHelper1` below. We expect the analyzer running in // its own `DirectoryLoadContext` would use the bogus S.C.I loaded in the compiler load context instead of the real one // in the default context. var compilerContext = new System.Runtime.Loader.AssemblyLoadContext("compilerContext"); _ = compilerContext.LoadFromAssemblyPath(_testFixture.UserSystemCollectionsImmutable.Path); _ = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoader).GetTypeInfo().Assembly.Location); var testAssembly = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoaderTests).GetTypeInfo().Assembly.Location); var testObject = testAssembly.CreateInstance(typeof(DefaultAnalyzerAssemblyLoaderTests).FullName!, ignoreCase: false, BindingFlags.Default, binder: null, args: new object[] { _output, _testFixture }, null, null)!; StringBuilder sb = new StringBuilder(); testObject.GetType().GetMethod(nameof(AssemblyLoadingInNonDefaultContextHelper1), BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(testObject, new object[] { sb }); Assert.Equal("42", sb.ToString()); } // This helper does the same thing as in `AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_01` test above except the assertions. private void AssemblyLoadingInNonDefaultContextHelper1(StringBuilder sb) { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path); loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path); var analyzer = analyzerAssembly.CreateInstance("Analyzer")!; analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb }); } [Fact] public void AssemblyLoadingInNonDefaultContext_AnalyzerReferencesNonCompilerAssemblyUsedByDefaultContext() { // Load the V2 of Delta to default ALC, then create a separate ALC for compiler and load compiler assembly. // Next use compiler context to load and run `AssemblyLoadingInNonDefaultContextHelper2` below. We expect the analyzer running in // its own `DirectoryLoadContext` would load and use Delta V1 located in its directory instead of V2 already loaded in the default context. _ = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(_testFixture.Delta2.Path); var compilerContext = new System.Runtime.Loader.AssemblyLoadContext("compilerContext"); _ = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoader).GetTypeInfo().Assembly.Location); var testAssembly = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoaderTests).GetTypeInfo().Assembly.Location); var testObject = testAssembly.CreateInstance(typeof(DefaultAnalyzerAssemblyLoaderTests).FullName!, ignoreCase: false, BindingFlags.Default, binder: null, args: new object[] { _output, _testFixture }, null, null)!; StringBuilder sb = new StringBuilder(); testObject.GetType().GetMethod(nameof(AssemblyLoadingInNonDefaultContextHelper2), BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(testObject, new object[] { sb }); Assert.Equal( @"Delta: Hello ", sb.ToString()); } private void AssemblyLoadingInNonDefaultContextHelper2(StringBuilder sb) { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.AnalyzerReferencesDelta1.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesDelta1.Path); var analyzer = analyzerAssembly.CreateInstance("Analyzer")!; analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb }); } #endif } }
1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Compilers/Core/Portable/DiagnosticAnalyzer/DefaultAnalyzerAssemblyLoader.Core.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. #if NETCOREAPP using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Loader; namespace Microsoft.CodeAnalysis { internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader { /// <summary> /// <p>Typically a user analyzer has a reference to the compiler and some of the compiler's /// dependencies such as System.Collections.Immutable. For the analyzer to correctly /// interoperate with the compiler that created it, we need to ensure that we always use the /// compiler's version of a given assembly over the analyzer's version.</p> /// /// <p>If we neglect to do this, then in the case where the user ships the compiler or its /// dependencies in the analyzer's bin directory, we could end up loading a separate /// instance of those assemblies in the process of loading the analyzer, which will surface /// as a failure to load the analyzer.</p> /// </summary> internal static readonly ImmutableHashSet<string> CompilerAssemblySimpleNames = ImmutableHashSet.Create( StringComparer.OrdinalIgnoreCase, "Microsoft.CodeAnalysis", "Microsoft.CodeAnalysis.CSharp", "Microsoft.CodeAnalysis.VisualBasic", "System.Collections", "System.Collections.Concurrent", "System.Collections.Immutable", "System.Console", "System.Diagnostics.Debug", "System.Diagnostics.StackTrace", "System.Diagnostics.Tracing", "System.IO.Compression", "System.IO.FileSystem", "System.Linq", "System.Linq.Expressions", "System.Memory", "System.Reflection.Metadata", "System.Reflection.Primitives", "System.Resources.ResourceManager", "System.Runtime", "System.Runtime.CompilerServices.Unsafe", "System.Runtime.Extensions", "System.Runtime.InteropServices", "System.Runtime.Loader", "System.Runtime.Numerics", "System.Runtime.Serialization.Primitives", "System.Security.Cryptography.Algorithms", "System.Security.Cryptography.Primitives", "System.Text.Encoding.CodePages", "System.Text.Encoding.Extensions", "System.Text.RegularExpressions", "System.Threading", "System.Threading.Tasks", "System.Threading.Tasks.Parallel", "System.Threading.Thread", "System.Threading.ThreadPool", "System.Xml.ReaderWriter", "System.Xml.XDocument", "System.Xml.XPath.XDocument"); private readonly object _guard = new object(); private readonly Dictionary<string, DirectoryLoadContext> _loadContextByDirectory = new Dictionary<string, DirectoryLoadContext>(StringComparer.Ordinal); protected override Assembly LoadFromPathImpl(string fullPath) { DirectoryLoadContext? loadContext; var fullDirectoryPath = Path.GetDirectoryName(fullPath) ?? throw new ArgumentException(message: null, paramName: nameof(fullPath)); lock (_guard) { if (!_loadContextByDirectory.TryGetValue(fullDirectoryPath, out loadContext)) { loadContext = new DirectoryLoadContext(fullDirectoryPath, this); _loadContextByDirectory[fullDirectoryPath] = loadContext; } } var name = AssemblyName.GetAssemblyName(fullPath); return loadContext.LoadFromAssemblyName(name); } internal static class TestAccessor { public static AssemblyLoadContext[] GetOrderedLoadContexts(DefaultAnalyzerAssemblyLoader loader) { return loader._loadContextByDirectory.Values.OrderBy(v => v.Directory).ToArray(); } } private sealed class DirectoryLoadContext : AssemblyLoadContext { internal string Directory { get; } private readonly DefaultAnalyzerAssemblyLoader _loader; public DirectoryLoadContext(string directory, DefaultAnalyzerAssemblyLoader loader) { Directory = directory; _loader = loader; } protected override Assembly? Load(AssemblyName assemblyName) { var simpleName = assemblyName.Name!; if (CompilerAssemblySimpleNames.Contains(simpleName)) { // Delegate to the compiler's load context to load the compiler or anything // referenced by the compiler return null; } var assemblyPath = Path.Combine(Directory, simpleName + ".dll"); if (!_loader.IsKnownDependencyLocation(assemblyPath)) { // The analyzer didn't explicitly register this dependency. Most likely the // assembly we're trying to load here is netstandard or a similar framework // assembly. We assume that if that is not the case, then the parent ALC will // fail to load this. return null; } var pathToLoad = _loader.GetPathToLoad(assemblyPath); return LoadFromAssemblyPath(pathToLoad); } protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) { var assemblyPath = Path.Combine(Directory, unmanagedDllName + ".dll"); if (!_loader.IsKnownDependencyLocation(assemblyPath)) { return IntPtr.Zero; } var pathToLoad = _loader.GetPathToLoad(assemblyPath); return LoadUnmanagedDllFromPath(pathToLoad); } } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #if NETCOREAPP using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Loader; namespace Microsoft.CodeAnalysis { internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader { /// <summary> /// <p>Typically a user analyzer has a reference to the compiler and some of the compiler's /// dependencies such as System.Collections.Immutable. For the analyzer to correctly /// interoperate with the compiler that created it, we need to ensure that we always use the /// compiler's version of a given assembly over the analyzer's version.</p> /// /// <p>If we neglect to do this, then in the case where the user ships the compiler or its /// dependencies in the analyzer's bin directory, we could end up loading a separate /// instance of those assemblies in the process of loading the analyzer, which will surface /// as a failure to load the analyzer.</p> /// </summary> internal static readonly ImmutableHashSet<string> CompilerAssemblySimpleNames = ImmutableHashSet.Create( StringComparer.OrdinalIgnoreCase, "Microsoft.CodeAnalysis", "Microsoft.CodeAnalysis.CSharp", "Microsoft.CodeAnalysis.VisualBasic", "System.Collections", "System.Collections.Concurrent", "System.Collections.Immutable", "System.Console", "System.Diagnostics.Debug", "System.Diagnostics.StackTrace", "System.Diagnostics.Tracing", "System.IO.Compression", "System.IO.FileSystem", "System.Linq", "System.Linq.Expressions", "System.Memory", "System.Reflection.Metadata", "System.Reflection.Primitives", "System.Resources.ResourceManager", "System.Runtime", "System.Runtime.CompilerServices.Unsafe", "System.Runtime.Extensions", "System.Runtime.InteropServices", "System.Runtime.Loader", "System.Runtime.Numerics", "System.Runtime.Serialization.Primitives", "System.Security.Cryptography.Algorithms", "System.Security.Cryptography.Primitives", "System.Text.Encoding.CodePages", "System.Text.Encoding.Extensions", "System.Text.RegularExpressions", "System.Threading", "System.Threading.Tasks", "System.Threading.Tasks.Parallel", "System.Threading.Thread", "System.Threading.ThreadPool", "System.Xml.ReaderWriter", "System.Xml.XDocument", "System.Xml.XPath.XDocument"); // This is the context where compiler (and some of its dependencies) are being loaded into, which might be different from AssemblyLoadContext.Default. private static readonly AssemblyLoadContext s_compilerLoadContext = AssemblyLoadContext.GetLoadContext(typeof(DefaultAnalyzerAssemblyLoader).GetTypeInfo().Assembly)!; private readonly object _guard = new object(); private readonly Dictionary<string, DirectoryLoadContext> _loadContextByDirectory = new Dictionary<string, DirectoryLoadContext>(StringComparer.Ordinal); protected override Assembly LoadFromPathImpl(string fullPath) { DirectoryLoadContext? loadContext; var fullDirectoryPath = Path.GetDirectoryName(fullPath) ?? throw new ArgumentException(message: null, paramName: nameof(fullPath)); lock (_guard) { if (!_loadContextByDirectory.TryGetValue(fullDirectoryPath, out loadContext)) { loadContext = new DirectoryLoadContext(fullDirectoryPath, this, s_compilerLoadContext); _loadContextByDirectory[fullDirectoryPath] = loadContext; } } var name = AssemblyName.GetAssemblyName(fullPath); return loadContext.LoadFromAssemblyName(name); } internal static class TestAccessor { public static AssemblyLoadContext[] GetOrderedLoadContexts(DefaultAnalyzerAssemblyLoader loader) { return loader._loadContextByDirectory.Values.OrderBy(v => v.Directory).ToArray(); } } private sealed class DirectoryLoadContext : AssemblyLoadContext { internal string Directory { get; } private readonly DefaultAnalyzerAssemblyLoader _loader; private readonly AssemblyLoadContext _compilerLoadContext; public DirectoryLoadContext(string directory, DefaultAnalyzerAssemblyLoader loader, AssemblyLoadContext compilerLoadContext) { Directory = directory; _loader = loader; _compilerLoadContext = compilerLoadContext; } protected override Assembly? Load(AssemblyName assemblyName) { var simpleName = assemblyName.Name!; if (CompilerAssemblySimpleNames.Contains(simpleName)) { // Delegate to the compiler's load context to load the compiler or anything // referenced by the compiler return _compilerLoadContext.LoadFromAssemblyName(assemblyName); } var assemblyPath = Path.Combine(Directory, simpleName + ".dll"); if (!_loader.IsKnownDependencyLocation(assemblyPath)) { // The analyzer didn't explicitly register this dependency. Most likely the // assembly we're trying to load here is netstandard or a similar framework // assembly. In this case, we want to load it in compiler's ALC to avoid any // potential type mismatch issue. Otherwise, if this is truly an unknown assembly, // we assume both compiler and default ALC will fail to load it. return _compilerLoadContext.LoadFromAssemblyName(assemblyName); } var pathToLoad = _loader.GetPathToLoad(assemblyPath); return LoadFromAssemblyPath(pathToLoad); } protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) { var assemblyPath = Path.Combine(Directory, unmanagedDllName + ".dll"); if (!_loader.IsKnownDependencyLocation(assemblyPath)) { return IntPtr.Zero; } var pathToLoad = _loader.GetPathToLoad(assemblyPath); return LoadUnmanagedDllFromPath(pathToLoad); } } } } #endif
1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Compilers/Test/Core/AssemblyLoadTestFixture.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using Basic.Reference.Assemblies; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.Test.Utilities { public sealed class AssemblyLoadTestFixture : IDisposable { private static readonly CSharpCompilationOptions s_dllWithMaxWarningLevel = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: Diagnostic.MaxWarningLevel); private readonly TempRoot _temp; private readonly TempDirectory _directory; public TempFile Delta1 { get; } public TempFile Gamma { get; } public TempFile Beta { get; } public TempFile Alpha { get; } public TempFile Delta2 { get; } public TempFile Epsilon { get; } public TempFile UserSystemCollectionsImmutable { get; } /// <summary> /// An analyzer which uses members in its referenced version of System.Collections.Immutable /// that are not present in the compiler's version of System.Collections.Immutable. /// </summary> public TempFile AnalyzerReferencesSystemCollectionsImmutable1 { get; } /// <summary> /// An analyzer which uses members in its referenced version of System.Collections.Immutable /// which have different behavior than the same members in compiler's version of System.Collections.Immutable. /// </summary> public TempFile AnalyzerReferencesSystemCollectionsImmutable2 { get; } public TempFile FaultyAnalyzer { get; } public TempFile AnalyzerWithDependency { get; } public TempFile AnalyzerDependency { get; } public TempFile AnalyzerWithNativeDependency { get; } public AssemblyLoadTestFixture() { _temp = new TempRoot(); _directory = _temp.CreateDirectory(); Delta1 = GenerateDll("Delta", _directory, @" using System.Text; [assembly: System.Reflection.AssemblyTitle(""Delta"")] [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] namespace Delta { public class D { public void Write(StringBuilder sb, string s) { sb.AppendLine(""Delta: "" + s); } } } "); var delta1Reference = MetadataReference.CreateFromFile(Delta1.Path); Gamma = GenerateDll("Gamma", _directory, @" using System.Text; using Delta; namespace Gamma { public class G { public void Write(StringBuilder sb, string s) { D d = new D(); d.Write(sb, ""Gamma: "" + s); } } } ", delta1Reference); var gammaReference = MetadataReference.CreateFromFile(Gamma.Path); Beta = GenerateDll("Beta", _directory, @" using System.Text; using Gamma; namespace Beta { public class B { public void Write(StringBuilder sb, string s) { G g = new G(); g.Write(sb, ""Beta: "" + s); } } } ", gammaReference); Alpha = GenerateDll("Alpha", _directory, @" using System.Text; using Gamma; namespace Alpha { public class A { public void Write(StringBuilder sb, string s) { G g = new G(); g.Write(sb, ""Alpha: "" + s); } } } ", gammaReference); var v2Directory = _directory.CreateDirectory("Version2"); Delta2 = GenerateDll("Delta", v2Directory, @" using System.Text; [assembly: System.Reflection.AssemblyTitle(""Delta"")] [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] namespace Delta { public class D { public void Write(StringBuilder sb, string s) { sb.AppendLine(""Delta.2: "" + s); } } } "); var delta2Reference = MetadataReference.CreateFromFile(Delta2.Path); Epsilon = GenerateDll("Epsilon", v2Directory, @" using System.Text; using Delta; namespace Epsilon { public class E { public void Write(StringBuilder sb, string s) { D d = new D(); d.Write(sb, ""Epsilon: "" + s); } } } ", delta2Reference); var sciUserDirectory = _directory.CreateDirectory("SCIUser"); var compilerReference = MetadataReference.CreateFromFile(typeof(Microsoft.CodeAnalysis.SyntaxNode).Assembly.Location); UserSystemCollectionsImmutable = GenerateDll("System.Collections.Immutable", sciUserDirectory, @" namespace System.Collections.Immutable { public static class ImmutableArray { public static ImmutableArray<T> Create<T>(T t) => new(); } public struct ImmutableArray<T> { public int Length => 42; public static int MyMethod() => 42; } } ", compilerReference); var userSystemCollectionsImmutableReference = MetadataReference.CreateFromFile(UserSystemCollectionsImmutable.Path); AnalyzerReferencesSystemCollectionsImmutable1 = GenerateDll("AnalyzerUsesSystemCollectionsImmutable1", sciUserDirectory, @" using System.Text; using System.Collections.Immutable; public class Analyzer { public void Method(StringBuilder sb) { sb.Append(ImmutableArray<object>.MyMethod()); } } ", userSystemCollectionsImmutableReference, compilerReference); AnalyzerReferencesSystemCollectionsImmutable2 = GenerateDll("AnalyzerUsesSystemCollectionsImmutable2", sciUserDirectory, @" using System.Text; using System.Collections.Immutable; public class Analyzer { public void Method(StringBuilder sb) { sb.Append(ImmutableArray.Create(""a"").Length); } } ", userSystemCollectionsImmutableReference, compilerReference); var faultyAnalyzerDirectory = _directory.CreateDirectory("FaultyAnalyzer"); FaultyAnalyzer = GenerateDll("FaultyAnalyzer", faultyAnalyzerDirectory, @" using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public abstract class TestAnalyzer : DiagnosticAnalyzer { } ", compilerReference); var realSciReference = MetadataReference.CreateFromFile(typeof(ImmutableArray).Assembly.Location); var analyzerWithDependencyDirectory = _directory.CreateDirectory("AnalyzerWithDependency"); AnalyzerDependency = GenerateDll("AnalyzerDependency", analyzerWithDependencyDirectory, @" using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; public abstract class AbstractTestAnalyzer : DiagnosticAnalyzer { protected static string SomeString = nameof(SomeString); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } } ", realSciReference, compilerReference); AnalyzerWithDependency = GenerateDll("Analyzer", analyzerWithDependencyDirectory, @" using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp)] public sealed class TestAnalyzer : AbstractTestAnalyzer { private static string SomeString2 = AbstractTestAnalyzer.SomeString; }", realSciReference, compilerReference, MetadataReference.CreateFromFile(AnalyzerDependency.Path)); AnalyzerWithNativeDependency = GenerateDll("AnalyzerWithNativeDependency", _directory, @" using System; using System.Runtime.InteropServices; public class Class1 { [DllImport(""kernel32.dll"", CharSet = CharSet.Unicode, SetLastError = true)] private static extern int GetFileAttributesW(string lpFileName); public int GetFileAttributes(string path) { return GetFileAttributesW(path); } } "); } private static TempFile GenerateDll(string assemblyName, TempDirectory directory, string csSource, params MetadataReference[] additionalReferences) { var analyzerDependencyCompilation = CSharpCompilation.Create( assemblyName: assemblyName, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(csSource) }, references: new MetadataReference[] { NetStandard20.mscorlib, NetStandard20.netstandard, NetStandard20.SystemRuntime }.Concat(additionalReferences), options: s_dllWithMaxWarningLevel); var tempFile = directory.CreateFile($"{assemblyName}.dll"); tempFile.WriteAllBytes(analyzerDependencyCompilation.EmitToArray()); return tempFile; } public void Dispose() { _temp.Dispose(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using Basic.Reference.Assemblies; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Roslyn.Test.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Test.Utilities { public sealed class AssemblyLoadTestFixture : IDisposable { private static readonly CSharpCompilationOptions s_dllWithMaxWarningLevel = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: Diagnostic.MaxWarningLevel); private readonly TempRoot _temp; private readonly TempDirectory _directory; public TempFile Delta1 { get; } public TempFile Gamma { get; } public TempFile Beta { get; } public TempFile Alpha { get; } public TempFile Delta2 { get; } public TempFile Epsilon { get; } public TempFile UserSystemCollectionsImmutable { get; } /// <summary> /// An analyzer which uses members in its referenced version of System.Collections.Immutable /// that are not present in the compiler's version of System.Collections.Immutable. /// </summary> public TempFile AnalyzerReferencesSystemCollectionsImmutable1 { get; } /// <summary> /// An analyzer which uses members in its referenced version of System.Collections.Immutable /// which have different behavior than the same members in compiler's version of System.Collections.Immutable. /// </summary> public TempFile AnalyzerReferencesSystemCollectionsImmutable2 { get; } public TempFile AnalyzerReferencesDelta1 { get; } public TempFile FaultyAnalyzer { get; } public TempFile AnalyzerWithDependency { get; } public TempFile AnalyzerDependency { get; } public TempFile AnalyzerWithNativeDependency { get; } public AssemblyLoadTestFixture() { _temp = new TempRoot(); _directory = _temp.CreateDirectory(); Delta1 = GenerateDll("Delta", _directory, @" using System.Text; [assembly: System.Reflection.AssemblyTitle(""Delta"")] [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] namespace Delta { public class D { public void Write(StringBuilder sb, string s) { sb.AppendLine(""Delta: "" + s); } } } "); var delta1Reference = MetadataReference.CreateFromFile(Delta1.Path); Gamma = GenerateDll("Gamma", _directory, @" using System.Text; using Delta; namespace Gamma { public class G { public void Write(StringBuilder sb, string s) { D d = new D(); d.Write(sb, ""Gamma: "" + s); } } } ", delta1Reference); var gammaReference = MetadataReference.CreateFromFile(Gamma.Path); Beta = GenerateDll("Beta", _directory, @" using System.Text; using Gamma; namespace Beta { public class B { public void Write(StringBuilder sb, string s) { G g = new G(); g.Write(sb, ""Beta: "" + s); } } } ", gammaReference); Alpha = GenerateDll("Alpha", _directory, @" using System.Text; using Gamma; namespace Alpha { public class A { public void Write(StringBuilder sb, string s) { G g = new G(); g.Write(sb, ""Alpha: "" + s); } } } ", gammaReference); var v2Directory = _directory.CreateDirectory("Version2"); Delta2 = GenerateDll("Delta", v2Directory, @" using System.Text; [assembly: System.Reflection.AssemblyTitle(""Delta"")] [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] namespace Delta { public class D { public void Write(StringBuilder sb, string s) { sb.AppendLine(""Delta.2: "" + s); } } } "); var delta2Reference = MetadataReference.CreateFromFile(Delta2.Path); Epsilon = GenerateDll("Epsilon", v2Directory, @" using System.Text; using Delta; namespace Epsilon { public class E { public void Write(StringBuilder sb, string s) { D d = new D(); d.Write(sb, ""Epsilon: "" + s); } } } ", delta2Reference); var sciUserDirectory = _directory.CreateDirectory("SCIUser"); var compilerReference = MetadataReference.CreateFromFile(typeof(Microsoft.CodeAnalysis.SyntaxNode).Assembly.Location); UserSystemCollectionsImmutable = GenerateDll("System.Collections.Immutable", sciUserDirectory, @" namespace System.Collections.Immutable { public static class ImmutableArray { public static ImmutableArray<T> Create<T>(T t) => new(); } public struct ImmutableArray<T> { public int Length => 42; public static int MyMethod() => 42; } } ", compilerReference); var userSystemCollectionsImmutableReference = MetadataReference.CreateFromFile(UserSystemCollectionsImmutable.Path); AnalyzerReferencesSystemCollectionsImmutable1 = GenerateDll("AnalyzerUsesSystemCollectionsImmutable1", sciUserDirectory, @" using System.Text; using System.Collections.Immutable; public class Analyzer { public void Method(StringBuilder sb) { sb.Append(ImmutableArray<object>.MyMethod()); } } ", userSystemCollectionsImmutableReference, compilerReference); AnalyzerReferencesSystemCollectionsImmutable2 = GenerateDll("AnalyzerUsesSystemCollectionsImmutable2", sciUserDirectory, @" using System.Text; using System.Collections.Immutable; public class Analyzer { public void Method(StringBuilder sb) { sb.Append(ImmutableArray.Create(""a"").Length); } } ", userSystemCollectionsImmutableReference, compilerReference); var analyzerReferencesDelta1Directory = _directory.CreateDirectory("AnalyzerReferencesDelta1"); var delta1InAnalyzerReferencesDelta1 = analyzerReferencesDelta1Directory.CopyFile(Delta1.Path); AnalyzerReferencesDelta1 = GenerateDll("AnalyzerReferencesDelta1", _directory, @" using System.Text; using Delta; public class Analyzer { public void Method(StringBuilder sb) { var d = new D(); d.Write(sb, ""Hello""); } } ", MetadataReference.CreateFromFile(delta1InAnalyzerReferencesDelta1.Path), compilerReference); var faultyAnalyzerDirectory = _directory.CreateDirectory("FaultyAnalyzer"); FaultyAnalyzer = GenerateDll("FaultyAnalyzer", faultyAnalyzerDirectory, @" using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public abstract class TestAnalyzer : DiagnosticAnalyzer { } ", compilerReference); var realSciReference = MetadataReference.CreateFromFile(typeof(ImmutableArray).Assembly.Location); var analyzerWithDependencyDirectory = _directory.CreateDirectory("AnalyzerWithDependency"); AnalyzerDependency = GenerateDll("AnalyzerDependency", analyzerWithDependencyDirectory, @" using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; public abstract class AbstractTestAnalyzer : DiagnosticAnalyzer { protected static string SomeString = nameof(SomeString); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } } ", realSciReference, compilerReference); AnalyzerWithDependency = GenerateDll("Analyzer", analyzerWithDependencyDirectory, @" using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp)] public sealed class TestAnalyzer : AbstractTestAnalyzer { private static string SomeString2 = AbstractTestAnalyzer.SomeString; }", realSciReference, compilerReference, MetadataReference.CreateFromFile(AnalyzerDependency.Path)); AnalyzerWithNativeDependency = GenerateDll("AnalyzerWithNativeDependency", _directory, @" using System; using System.Runtime.InteropServices; public class Class1 { [DllImport(""kernel32.dll"", CharSet = CharSet.Unicode, SetLastError = true)] private static extern int GetFileAttributesW(string lpFileName); public int GetFileAttributes(string path) { return GetFileAttributesW(path); } } "); } private static TempFile GenerateDll(string assemblyName, TempDirectory directory, string csSource, params MetadataReference[] additionalReferences) { var analyzerDependencyCompilation = CSharpCompilation.Create( assemblyName: assemblyName, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(csSource) }, references: new MetadataReference[] { NetStandard20.mscorlib, NetStandard20.netstandard, NetStandard20.SystemRuntime }.Concat(additionalReferences), options: s_dllWithMaxWarningLevel); var tempFile = directory.CreateFile($"{assemblyName}.dll"); tempFile.WriteAllBytes(analyzerDependencyCompilation.EmitToArray()); return tempFile; } public void Dispose() { _temp.Dispose(); } } }
1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./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 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.VisualBasic.Features.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>
<?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.Workspaces.dll" /> <Asset Type="Microsoft.VisualStudio.Analyzer" Path="Microsoft.CodeAnalysis.CSharp.Features.dll" /> <Asset Type="Microsoft.VisualStudio.Analyzer" Path="Microsoft.CodeAnalysis.VisualBasic.Features.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
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Workspaces/Core/Portable/Shared/Utilities/ExtensionOrderer.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; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal static partial class ExtensionOrderer { internal static IList<Lazy<TExtension, TMetadata>> Order<TExtension, TMetadata>( IEnumerable<Lazy<TExtension, TMetadata>> extensions) where TMetadata : OrderableMetadata { var graph = GetGraph(extensions); return graph.TopologicalSort(); } private static Graph<TExtension, TMetadata> GetGraph<TExtension, TMetadata>( IEnumerable<Lazy<TExtension, TMetadata>> extensions) where TMetadata : OrderableMetadata { var list = extensions.ToList(); var graph = new Graph<TExtension, TMetadata>(); foreach (var extension in list) { graph.Nodes.Add(extension, new Node<TExtension, TMetadata>(extension)); } foreach (var extension in list) { var extensionNode = graph.Nodes[extension]; foreach (var before in extension.Metadata.BeforeTyped) { foreach (var beforeExtension in graph.FindExtensions(before)) { var otherExtensionNode = graph.Nodes[beforeExtension]; otherExtensionNode.ExtensionsBeforeMeSet.Add(extensionNode); } } foreach (var after in extension.Metadata.AfterTyped) { foreach (var afterExtension in graph.FindExtensions(after)) { var otherExtensionNode = graph.Nodes[afterExtension]; extensionNode.ExtensionsBeforeMeSet.Add(otherExtensionNode); } } } return graph; } internal static class TestAccessor { /// <summary> /// Helper for checking whether cycles exist in the extension ordering. /// Throws <see cref="ArgumentException"/> if a cycle is detected. /// </summary> /// <exception cref="ArgumentException">A cycle was detected in the extension ordering.</exception> internal static void CheckForCycles<TExtension, TMetadata>( IEnumerable<Lazy<TExtension, TMetadata>> extensions) where TMetadata : OrderableMetadata { var graph = GetGraph(extensions); graph.CheckForCycles(); } } } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal static partial class ExtensionOrderer { internal static IList<Lazy<TExtension, TMetadata>> Order<TExtension, TMetadata>( IEnumerable<Lazy<TExtension, TMetadata>> extensions) where TMetadata : OrderableMetadata { var graph = GetGraph(extensions); return graph.TopologicalSort(); } private static Graph<TExtension, TMetadata> GetGraph<TExtension, TMetadata>( IEnumerable<Lazy<TExtension, TMetadata>> extensions) where TMetadata : OrderableMetadata { var list = extensions.ToList(); var graph = new Graph<TExtension, TMetadata>(); foreach (var extension in list) { graph.Nodes.Add(extension, new Node<TExtension, TMetadata>(extension)); } foreach (var extension in list) { var extensionNode = graph.Nodes[extension]; foreach (var before in extension.Metadata.BeforeTyped) { foreach (var beforeExtension in graph.FindExtensions(before)) { var otherExtensionNode = graph.Nodes[beforeExtension]; otherExtensionNode.ExtensionsBeforeMeSet.Add(extensionNode); } } foreach (var after in extension.Metadata.AfterTyped) { foreach (var afterExtension in graph.FindExtensions(after)) { var otherExtensionNode = graph.Nodes[afterExtension]; extensionNode.ExtensionsBeforeMeSet.Add(otherExtensionNode); } } } return graph; } internal static class TestAccessor { /// <summary> /// Helper for checking whether cycles exist in the extension ordering. /// Throws <see cref="ArgumentException"/> if a cycle is detected. /// </summary> /// <exception cref="ArgumentException">A cycle was detected in the extension ordering.</exception> internal static void CheckForCycles<TExtension, TMetadata>( IEnumerable<Lazy<TExtension, TMetadata>> extensions) where TMetadata : OrderableMetadata { var graph = GetGraph(extensions); graph.CheckForCycles(); } } } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Features/Core/Portable/ValidateFormatString/ValidateFormatStringOptionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.ValidateFormatString { [ExportOptionProvider, Shared] internal class ValidateFormatStringOptionProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ValidateFormatStringOptionProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.ValidateFormatString { [ExportOptionProvider, Shared] internal class ValidateFormatStringOptionProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ValidateFormatStringOptionProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls); } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/Legacy/AbstractLegacyProject_IVsHierarchyEvents.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.IO; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy { internal partial class AbstractLegacyProject : IVsHierarchyEvents { private uint _hierarchyEventsCookie; private void ConnectHierarchyEvents() { Debug.Assert(!this.AreHierarchyEventsConnected, "IVsHierarchyEvents are already connected!"); if (ErrorHandler.Failed(Hierarchy.AdviseHierarchyEvents(this, out _hierarchyEventsCookie))) { Debug.Fail("Failed to connect IVsHierarchyEvents"); _hierarchyEventsCookie = 0; } } private void DisconnectHierarchyEvents() { if (this.AreHierarchyEventsConnected) { Hierarchy.UnadviseHierarchyEvents(_hierarchyEventsCookie); _hierarchyEventsCookie = 0; } } private bool AreHierarchyEventsConnected { get { return _hierarchyEventsCookie != 0; } } int IVsHierarchyEvents.OnInvalidateIcon(IntPtr hicon) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnInvalidateItems(uint itemidParent) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnItemAdded(uint itemidParent, uint itemidSiblingPrev, uint itemidAdded) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnItemDeleted(uint itemid) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnItemsAppended(uint itemidParent) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnPropertyChanged(uint itemid, int propid, uint flags) { if ((propid == (int)__VSHPROPID.VSHPROPID_Caption || propid == (int)__VSHPROPID.VSHPROPID_Name) && itemid == (uint)VSConstants.VSITEMID.Root) { var filePath = Hierarchy.TryGetProjectFilePath(); if (filePath != null && File.Exists(filePath)) { VisualStudioProject.FilePath = filePath; } if (Hierarchy.TryGetName(out var name)) { VisualStudioProject.DisplayName = name; } } return VSConstants.S_OK; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.IO; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy { internal partial class AbstractLegacyProject : IVsHierarchyEvents { private uint _hierarchyEventsCookie; private void ConnectHierarchyEvents() { Debug.Assert(!this.AreHierarchyEventsConnected, "IVsHierarchyEvents are already connected!"); if (ErrorHandler.Failed(Hierarchy.AdviseHierarchyEvents(this, out _hierarchyEventsCookie))) { Debug.Fail("Failed to connect IVsHierarchyEvents"); _hierarchyEventsCookie = 0; } } private void DisconnectHierarchyEvents() { if (this.AreHierarchyEventsConnected) { Hierarchy.UnadviseHierarchyEvents(_hierarchyEventsCookie); _hierarchyEventsCookie = 0; } } private bool AreHierarchyEventsConnected { get { return _hierarchyEventsCookie != 0; } } int IVsHierarchyEvents.OnInvalidateIcon(IntPtr hicon) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnInvalidateItems(uint itemidParent) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnItemAdded(uint itemidParent, uint itemidSiblingPrev, uint itemidAdded) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnItemDeleted(uint itemid) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnItemsAppended(uint itemidParent) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnPropertyChanged(uint itemid, int propid, uint flags) { if ((propid == (int)__VSHPROPID.VSHPROPID_Caption || propid == (int)__VSHPROPID.VSHPROPID_Name) && itemid == (uint)VSConstants.VSITEMID.Root) { var filePath = Hierarchy.TryGetProjectFilePath(); if (filePath != null && File.Exists(filePath)) { VisualStudioProject.FilePath = filePath; } if (Hierarchy.TryGetName(out var name)) { VisualStudioProject.DisplayName = name; } } return VSConstants.S_OK; } } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Compilers/Test/Resources/Core/SymbolsTests/Methods/CSMethods.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. // csc /t:library CSMethods.cs public class C1 { public class SameName { } public void sameName() { } public void SameName2() { } public void SameName2(int x) { } public void sameName2(double x) { } } public abstract class Modifiers1 { public abstract void M1(); public virtual void M2() {} public void M3() {} public virtual void M4() {} } public abstract class Modifiers2 : Modifiers1 { public sealed override void M1() {} public abstract override void M2(); public virtual new void M3() { } } public abstract class Modifiers3 : Modifiers1 { public override void M1() {} public new void M3() { } public abstract new void M4(); } public class DefaultParameterValues { public static void M( string text, string path = "", DefaultParameterValues d = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } } public class MultiDimArrays { public static void Goo(int[,] x) { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // csc /t:library CSMethods.cs public class C1 { public class SameName { } public void sameName() { } public void SameName2() { } public void SameName2(int x) { } public void sameName2(double x) { } } public abstract class Modifiers1 { public abstract void M1(); public virtual void M2() {} public void M3() {} public virtual void M4() {} } public abstract class Modifiers2 : Modifiers1 { public sealed override void M1() {} public abstract override void M2(); public virtual new void M3() { } } public abstract class Modifiers3 : Modifiers1 { public override void M1() {} public new void M3() { } public abstract new void M4(); } public class DefaultParameterValues { public static void M( string text, string path = "", DefaultParameterValues d = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } } public class MultiDimArrays { public static void Goo(int[,] x) { } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/ChangeSignatureDialog_OutOfProc.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class ChangeSignatureDialog_OutOfProc : OutOfProcComponent { private readonly ChangeSignatureDialog_InProc _inProc; public ChangeSignatureDialog_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { _inProc = CreateInProcComponent<ChangeSignatureDialog_InProc>(visualStudioInstance); } public void VerifyOpen() => _inProc.VerifyOpen(); public void VerifyClosed() => _inProc.VerifyClosed(); public bool CloseWindow() => _inProc.CloseWindow(); public void Invoke() => VisualStudioInstance.Editor.SendKeys(new KeyPress(VirtualKey.R, ShiftState.Ctrl), new KeyPress(VirtualKey.V, ShiftState.Ctrl)); public void ClickOK() => _inProc.ClickOK(); public void ClickCancel() => _inProc.ClickCancel(); public void ClickDownButton() => _inProc.ClickDownButton(); public void ClickUpButton() => _inProc.ClickUpButton(); public void ClickAddButton() => _inProc.ClickAddButton(); public void ClickRemoveButton() => _inProc.ClickRemoveButton(); public void ClickRestoreButton() => _inProc.ClickRestoreButton(); public void SelectParameter(string parameterName) => _inProc.SelectParameter(parameterName); } }
// Licensed to the .NET Foundation under one or more 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.VisualStudio.IntegrationTest.Utilities.InProcess; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class ChangeSignatureDialog_OutOfProc : OutOfProcComponent { private readonly ChangeSignatureDialog_InProc _inProc; public ChangeSignatureDialog_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { _inProc = CreateInProcComponent<ChangeSignatureDialog_InProc>(visualStudioInstance); } public void VerifyOpen() => _inProc.VerifyOpen(); public void VerifyClosed() => _inProc.VerifyClosed(); public bool CloseWindow() => _inProc.CloseWindow(); public void Invoke() => VisualStudioInstance.Editor.SendKeys(new KeyPress(VirtualKey.R, ShiftState.Ctrl), new KeyPress(VirtualKey.V, ShiftState.Ctrl)); public void ClickOK() => _inProc.ClickOK(); public void ClickCancel() => _inProc.ClickCancel(); public void ClickDownButton() => _inProc.ClickDownButton(); public void ClickUpButton() => _inProc.ClickUpButton(); public void ClickAddButton() => _inProc.ClickAddButton(); public void ClickRemoveButton() => _inProc.ClickRemoveButton(); public void ClickRestoreButton() => _inProc.ClickRestoreButton(); public void SelectParameter(string parameterName) => _inProc.SelectParameter(parameterName); } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Analyzers/Core/CodeFixes/UseThrowExpression/UseThrowExpressionCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseThrowExpression { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseThrowExpression), Shared] internal partial class UseThrowExpressionCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseThrowExpressionCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseThrowExpressionDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary); public override Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, diagnostic, c)), diagnostic); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var generator = editor.Generator; var root = editor.OriginalRoot; foreach (var diagnostic in diagnostics) { var ifStatement = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan); var throwStatementExpression = root.FindNode(diagnostic.AdditionalLocations[1].SourceSpan); var assignmentValue = root.FindNode(diagnostic.AdditionalLocations[2].SourceSpan); // First, remote the if-statement entirely. editor.RemoveNode(ifStatement); // Now, update the assignment value to go from 'a' to 'a ?? throw ...'. editor.ReplaceNode(assignmentValue, generator.CoalesceExpression(assignmentValue, generator.ThrowExpression(throwStatementExpression))); } return Task.CompletedTask; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction( Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Use_throw_expression, createChangedDocument, nameof(AnalyzersResources.Use_throw_expression)) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseThrowExpression { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseThrowExpression), Shared] internal partial class UseThrowExpressionCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseThrowExpressionCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseThrowExpressionDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.Descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary); public override Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, diagnostic, c)), diagnostic); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var generator = editor.Generator; var root = editor.OriginalRoot; foreach (var diagnostic in diagnostics) { var ifStatement = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan); var throwStatementExpression = root.FindNode(diagnostic.AdditionalLocations[1].SourceSpan); var assignmentValue = root.FindNode(diagnostic.AdditionalLocations[2].SourceSpan); // First, remote the if-statement entirely. editor.RemoveNode(ifStatement); // Now, update the assignment value to go from 'a' to 'a ?? throw ...'. editor.ReplaceNode(assignmentValue, generator.CoalesceExpression(assignmentValue, generator.ThrowExpression(throwStatementExpression))); } return Task.CompletedTask; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction( Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Use_throw_expression, createChangedDocument, nameof(AnalyzersResources.Use_throw_expression)) { } } } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioAddMetadataReferenceCodeActionOperationFactoryWorkspaceService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeActions.WorkspaceServices; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [ExportWorkspaceService(typeof(IAddMetadataReferenceCodeActionOperationFactoryWorkspaceService), ServiceLayer.Host), Shared] internal sealed class VisualStudioAddMetadataReferenceCodeActionOperationFactoryWorkspaceService : IAddMetadataReferenceCodeActionOperationFactoryWorkspaceService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioAddMetadataReferenceCodeActionOperationFactoryWorkspaceService() { } public CodeActionOperation CreateAddMetadataReferenceOperation(ProjectId projectId, AssemblyIdentity assemblyIdentity) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (assemblyIdentity == null) { throw new ArgumentNullException(nameof(assemblyIdentity)); } return new AddMetadataReferenceOperation(projectId, assemblyIdentity); } private class AddMetadataReferenceOperation : Microsoft.CodeAnalysis.CodeActions.CodeActionOperation { private readonly AssemblyIdentity _assemblyIdentity; private readonly ProjectId _projectId; public AddMetadataReferenceOperation(ProjectId projectId, AssemblyIdentity assemblyIdentity) { _projectId = projectId; _assemblyIdentity = assemblyIdentity; } public override void Apply(Microsoft.CodeAnalysis.Workspace workspace, CancellationToken cancellationToken = default) { var visualStudioWorkspace = (VisualStudioWorkspaceImpl)workspace; if (!visualStudioWorkspace.TryAddReferenceToProject(_projectId, "*" + _assemblyIdentity.GetDisplayName())) { // We failed to add the reference, which means the project system wasn't able to bind. // We'll pop up the Add Reference dialog to let the user figure this out themselves. // This is the same approach done in CVBErrorFixApply::ApplyAddMetaReferenceFix if (visualStudioWorkspace.GetHierarchy(_projectId) is IVsUIHierarchy uiHierarchy) { var command = new OLECMD[1]; command[0].cmdID = (uint)VSConstants.VSStd2KCmdID.ADDREFERENCE; if (ErrorHandler.Succeeded(uiHierarchy.QueryStatusCommand((uint)VSConstants.VSITEMID.Root, VSConstants.VSStd2K, 1, command, IntPtr.Zero))) { if ((((OLECMDF)command[0].cmdf) & OLECMDF.OLECMDF_ENABLED) != 0) { uiHierarchy.ExecCommand((uint)VSConstants.VSITEMID.Root, VSConstants.VSStd2K, (uint)VSConstants.VSStd2KCmdID.ADDREFERENCE, 0, IntPtr.Zero, IntPtr.Zero); } } } } } public override string Title => string.Format(ServicesVSResources.Add_a_reference_to_0, _assemblyIdentity.GetDisplayName()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeActions.WorkspaceServices; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [ExportWorkspaceService(typeof(IAddMetadataReferenceCodeActionOperationFactoryWorkspaceService), ServiceLayer.Host), Shared] internal sealed class VisualStudioAddMetadataReferenceCodeActionOperationFactoryWorkspaceService : IAddMetadataReferenceCodeActionOperationFactoryWorkspaceService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioAddMetadataReferenceCodeActionOperationFactoryWorkspaceService() { } public CodeActionOperation CreateAddMetadataReferenceOperation(ProjectId projectId, AssemblyIdentity assemblyIdentity) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (assemblyIdentity == null) { throw new ArgumentNullException(nameof(assemblyIdentity)); } return new AddMetadataReferenceOperation(projectId, assemblyIdentity); } private class AddMetadataReferenceOperation : Microsoft.CodeAnalysis.CodeActions.CodeActionOperation { private readonly AssemblyIdentity _assemblyIdentity; private readonly ProjectId _projectId; public AddMetadataReferenceOperation(ProjectId projectId, AssemblyIdentity assemblyIdentity) { _projectId = projectId; _assemblyIdentity = assemblyIdentity; } public override void Apply(Microsoft.CodeAnalysis.Workspace workspace, CancellationToken cancellationToken = default) { var visualStudioWorkspace = (VisualStudioWorkspaceImpl)workspace; if (!visualStudioWorkspace.TryAddReferenceToProject(_projectId, "*" + _assemblyIdentity.GetDisplayName())) { // We failed to add the reference, which means the project system wasn't able to bind. // We'll pop up the Add Reference dialog to let the user figure this out themselves. // This is the same approach done in CVBErrorFixApply::ApplyAddMetaReferenceFix if (visualStudioWorkspace.GetHierarchy(_projectId) is IVsUIHierarchy uiHierarchy) { var command = new OLECMD[1]; command[0].cmdID = (uint)VSConstants.VSStd2KCmdID.ADDREFERENCE; if (ErrorHandler.Succeeded(uiHierarchy.QueryStatusCommand((uint)VSConstants.VSITEMID.Root, VSConstants.VSStd2K, 1, command, IntPtr.Zero))) { if ((((OLECMDF)command[0].cmdf) & OLECMDF.OLECMDF_ENABLED) != 0) { uiHierarchy.ExecCommand((uint)VSConstants.VSITEMID.Root, VSConstants.VSStd2K, (uint)VSConstants.VSStd2KCmdID.ADDREFERENCE, 0, IntPtr.Zero, IntPtr.Zero); } } } } } public override string Title => string.Format(ServicesVSResources.Add_a_reference_to_0, _assemblyIdentity.GetDisplayName()); } } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/VisualStudio/Core/Impl/CodeModel/ExternalElements/ExternalCodeEvent.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeEvent))] public sealed class ExternalCodeEvent : AbstractExternalCodeMember, EnvDTE80.CodeEvent { internal static EnvDTE80.CodeEvent Create(CodeModelState state, ProjectId projectId, IEventSymbol symbol) { var element = new ExternalCodeEvent(state, projectId, symbol); return (EnvDTE80.CodeEvent)ComAggregate.CreateAggregatedObject(element); } private ExternalCodeEvent(CodeModelState state, ProjectId projectId, IEventSymbol symbol) : base(state, projectId, symbol) { } private IEventSymbol EventSymbol { get { return (IEventSymbol)LookupSymbol(); } } protected override EnvDTE.CodeElements GetParameters() => throw new NotImplementedException(); public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementEvent; } } public EnvDTE.CodeFunction Adder { get { var symbol = EventSymbol; if (symbol.AddMethod == null) { throw Exceptions.ThrowEFail(); } return ExternalCodeAccessorFunction.Create(this.State, this.ProjectId, symbol.AddMethod, this); } set { throw Exceptions.ThrowEFail(); } } // TODO: Verify VB implementation public bool IsPropertyStyleEvent { get { return true; } } // TODO: Verify VB implementation public EnvDTE80.vsCMOverrideKind OverrideKind { get { throw Exceptions.ThrowENotImpl(); } set { throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeFunction Remover { get { var symbol = EventSymbol; if (symbol.RemoveMethod == null) { throw Exceptions.ThrowEFail(); } return ExternalCodeAccessorFunction.Create(this.State, this.ProjectId, symbol.RemoveMethod, this); } set { throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeFunction Thrower { get { // TODO: Verify this with VB implementation var symbol = EventSymbol; if (symbol.RaiseMethod == null) { throw Exceptions.ThrowEFail(); } return ExternalCodeAccessorFunction.Create(this.State, this.ProjectId, symbol.RaiseMethod, this); } set { throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeTypeRef Type { get { return CodeTypeRef.Create(this.State, this, this.ProjectId, EventSymbol.Type); } set { throw Exceptions.ThrowEFail(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeEvent))] public sealed class ExternalCodeEvent : AbstractExternalCodeMember, EnvDTE80.CodeEvent { internal static EnvDTE80.CodeEvent Create(CodeModelState state, ProjectId projectId, IEventSymbol symbol) { var element = new ExternalCodeEvent(state, projectId, symbol); return (EnvDTE80.CodeEvent)ComAggregate.CreateAggregatedObject(element); } private ExternalCodeEvent(CodeModelState state, ProjectId projectId, IEventSymbol symbol) : base(state, projectId, symbol) { } private IEventSymbol EventSymbol { get { return (IEventSymbol)LookupSymbol(); } } protected override EnvDTE.CodeElements GetParameters() => throw new NotImplementedException(); public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementEvent; } } public EnvDTE.CodeFunction Adder { get { var symbol = EventSymbol; if (symbol.AddMethod == null) { throw Exceptions.ThrowEFail(); } return ExternalCodeAccessorFunction.Create(this.State, this.ProjectId, symbol.AddMethod, this); } set { throw Exceptions.ThrowEFail(); } } // TODO: Verify VB implementation public bool IsPropertyStyleEvent { get { return true; } } // TODO: Verify VB implementation public EnvDTE80.vsCMOverrideKind OverrideKind { get { throw Exceptions.ThrowENotImpl(); } set { throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeFunction Remover { get { var symbol = EventSymbol; if (symbol.RemoveMethod == null) { throw Exceptions.ThrowEFail(); } return ExternalCodeAccessorFunction.Create(this.State, this.ProjectId, symbol.RemoveMethod, this); } set { throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeFunction Thrower { get { // TODO: Verify this with VB implementation var symbol = EventSymbol; if (symbol.RaiseMethod == null) { throw Exceptions.ThrowEFail(); } return ExternalCodeAccessorFunction.Create(this.State, this.ProjectId, symbol.RaiseMethod, this); } set { throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeTypeRef Type { get { return CodeTypeRef.Create(this.State, this, this.ProjectId, EventSymbol.Type); } set { throw Exceptions.ThrowEFail(); } } } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/ParenthesesPreference.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.CodeStyle { internal enum ParenthesesPreference { AlwaysForClarity, NeverIfUnnecessary, } }
// Licensed to the .NET Foundation under one or more 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.CodeStyle { internal enum ParenthesesPreference { AlwaysForClarity, NeverIfUnnecessary, } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Compilers/Core/Portable/EncodedStringText.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.IO; using System.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text { internal static class EncodedStringText { private const int LargeObjectHeapLimitInChars = 40 * 1024; // 40KB /// <summary> /// Encoding to use when there is no byte order mark (BOM) on the stream. This encoder may throw a <see cref="DecoderFallbackException"/> /// if the stream contains invalid UTF-8 bytes. /// </summary> private static readonly Encoding s_utf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); private static readonly Lazy<Encoding> s_fallbackEncoding = new(CreateFallbackEncoding); /// <summary> /// Encoding to use when UTF-8 fails. We try to find the following, in order, if available: /// 1. The default ANSI codepage /// 2. CodePage 1252. /// 3. Latin1. /// </summary> internal static Encoding CreateFallbackEncoding() { try { if (CodePagesEncodingProvider.Instance != null) { // If we're running on CoreCLR we have to register the CodePagesEncodingProvider // first Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); } // Try to get the default ANSI code page in the operating system's // regional and language settings, and fall back to 1252 otherwise return Encoding.GetEncoding(0) ?? Encoding.GetEncoding(1252); } catch (NotSupportedException) { return Encoding.GetEncoding(name: "Latin1"); } } /// <summary> /// Initializes an instance of <see cref="SourceText"/> from the provided stream. This version differs /// from <see cref="SourceText.From(Stream, Encoding, SourceHashAlgorithm, bool)"/> in two ways: /// 1. It attempts to minimize allocations by trying to read the stream into a byte array. /// 2. If <paramref name="defaultEncoding"/> is null, it will first try UTF8 and, if that fails, it will /// try CodePage 1252. If CodePage 1252 is not available on the system, then it will try Latin1. /// </summary> /// <param name="stream">The stream containing encoded text.</param> /// <param name="defaultEncoding"> /// Specifies an encoding to be used if the actual encoding can't be determined from the stream content (the stream doesn't start with Byte Order Mark). /// If not specified auto-detect heuristics are used to determine the encoding. If these heuristics fail the decoding is assumed to be Encoding.Default. /// Note that if the stream starts with Byte Order Mark the value of <paramref name="defaultEncoding"/> is ignored. /// </param> /// <param name="canBeEmbedded">Indicates if the file can be embedded in the PDB.</param> /// <param name="checksumAlgorithm">Hash algorithm used to calculate document checksum.</param> /// <exception cref="InvalidDataException"> /// The stream content can't be decoded using the specified <paramref name="defaultEncoding"/>, or /// <paramref name="defaultEncoding"/> is null and the stream appears to be a binary file. /// </exception> /// <exception cref="IOException">An IO error occurred while reading from the stream.</exception> internal static SourceText Create(Stream stream, Encoding? defaultEncoding = null, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1, bool canBeEmbedded = false) { return Create(stream, s_fallbackEncoding, defaultEncoding: defaultEncoding, checksumAlgorithm: checksumAlgorithm, canBeEmbedded: canBeEmbedded); } internal static SourceText Create(Stream stream, Lazy<Encoding> getEncoding, Encoding? defaultEncoding = null, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1, bool canBeEmbedded = false) { RoslynDebug.Assert(stream != null); RoslynDebug.Assert(stream.CanRead); bool detectEncoding = defaultEncoding == null; if (detectEncoding) { try { return Decode(stream, s_utf8Encoding, checksumAlgorithm, throwIfBinaryDetected: false, canBeEmbedded: canBeEmbedded); } catch (DecoderFallbackException) { // Fall back to Encoding.ASCII } } try { return Decode(stream, defaultEncoding ?? getEncoding.Value, checksumAlgorithm, throwIfBinaryDetected: detectEncoding, canBeEmbedded: canBeEmbedded); } catch (DecoderFallbackException e) { throw new InvalidDataException(e.Message); } } /// <summary> /// Try to create a <see cref="SourceText"/> from the given stream using the given encoding. /// </summary> /// <param name="data">The input stream containing the encoded text. The stream will not be closed.</param> /// <param name="encoding">The expected encoding of the stream. The actual encoding used may be different if byte order marks are detected.</param> /// <param name="checksumAlgorithm">The checksum algorithm to use.</param> /// <param name="throwIfBinaryDetected">Throw <see cref="InvalidDataException"/> if binary (non-text) data is detected.</param> /// <param name="canBeEmbedded">Indicates if the text can be embedded in the PDB.</param> /// <returns>The <see cref="SourceText"/> decoded from the stream.</returns> /// <exception cref="DecoderFallbackException">The decoder was unable to decode the stream with the given encoding.</exception> /// <exception cref="IOException">Error reading from stream.</exception> private static SourceText Decode( Stream data, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected = false, bool canBeEmbedded = false) { RoslynDebug.Assert(data != null); RoslynDebug.Assert(encoding != null); if (data.CanSeek) { data.Seek(0, SeekOrigin.Begin); // For small streams, see if we can read the byte buffer directly. if (encoding.GetMaxCharCountOrThrowIfHuge(data) < LargeObjectHeapLimitInChars) { if (TryGetBytesFromStream(data, out ArraySegment<byte> bytes) && bytes.Offset == 0 && bytes.Array is object) { return SourceText.From(bytes.Array, (int)data.Length, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded); } } } return SourceText.From(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded); } /// <summary> /// Some streams are easily represented as bytes. /// </summary> /// <param name="data">The stream</param> /// <param name="bytes">The bytes, if available.</param> /// <returns> /// True if the stream's bytes could easily be read, false otherwise. /// </returns> internal static bool TryGetBytesFromStream(Stream data, out ArraySegment<byte> bytes) { // PERF: If the input is a MemoryStream, we may be able to get at the buffer directly var memoryStream = data as MemoryStream; if (memoryStream != null) { return memoryStream.TryGetBuffer(out bytes); } // PERF: If the input is a FileStream, we may be able to minimize allocations var fileStream = data as FileStream; if (fileStream != null) { return TryGetBytesFromFileStream(fileStream, out bytes); } bytes = new ArraySegment<byte>(Array.Empty<byte>()); return false; } /// <summary> /// Read the contents of a FileStream into a byte array. /// </summary> /// <param name="stream">The FileStream with encoded text.</param> /// <param name="bytes">A byte array filled with the contents of the file.</param> /// <returns>True if a byte array could be created.</returns> private static bool TryGetBytesFromFileStream(FileStream stream, out ArraySegment<byte> bytes) { RoslynDebug.Assert(stream != null); RoslynDebug.Assert(stream.Position == 0); int length = (int)stream.Length; if (length == 0) { bytes = new ArraySegment<byte>(Array.Empty<byte>()); return true; } // PERF: While this is an obvious byte array allocation, it is still cheaper than // using StreamReader.ReadToEnd. The alternative allocates: // 1. A 1KB byte array in the StreamReader for buffered reads // 2. A 4KB byte array in the FileStream for buffered reads // 3. A StringBuilder and its associated char arrays (enough to represent the final decoded string) // TODO: Can this allocation be pooled? var buffer = new byte[length]; // Note: FileStream.Read may still allocate its internal buffer if length is less // than the buffer size. The default buffer size is 4KB, so this will incur a 4KB // allocation for any files less than 4KB. That's why, for example, the command // line compiler actually specifies a very small buffer size. var success = stream.TryReadAll(buffer, 0, length) == length; bytes = success ? new ArraySegment<byte>(buffer) : new ArraySegment<byte>(Array.Empty<byte>()); return success; } internal static class TestAccessor { internal static SourceText Create(Stream stream, Lazy<Encoding> getEncoding, Encoding defaultEncoding, SourceHashAlgorithm checksumAlgorithm, bool canBeEmbedded) => EncodedStringText.Create(stream, getEncoding, defaultEncoding, checksumAlgorithm, canBeEmbedded); internal static SourceText Decode(Stream data, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected, bool canBeEmbedded) => EncodedStringText.Decode(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded); } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text { internal static class EncodedStringText { private const int LargeObjectHeapLimitInChars = 40 * 1024; // 40KB /// <summary> /// Encoding to use when there is no byte order mark (BOM) on the stream. This encoder may throw a <see cref="DecoderFallbackException"/> /// if the stream contains invalid UTF-8 bytes. /// </summary> private static readonly Encoding s_utf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); private static readonly Lazy<Encoding> s_fallbackEncoding = new(CreateFallbackEncoding); /// <summary> /// Encoding to use when UTF-8 fails. We try to find the following, in order, if available: /// 1. The default ANSI codepage /// 2. CodePage 1252. /// 3. Latin1. /// </summary> internal static Encoding CreateFallbackEncoding() { try { if (CodePagesEncodingProvider.Instance != null) { // If we're running on CoreCLR we have to register the CodePagesEncodingProvider // first Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); } // Try to get the default ANSI code page in the operating system's // regional and language settings, and fall back to 1252 otherwise return Encoding.GetEncoding(0) ?? Encoding.GetEncoding(1252); } catch (NotSupportedException) { return Encoding.GetEncoding(name: "Latin1"); } } /// <summary> /// Initializes an instance of <see cref="SourceText"/> from the provided stream. This version differs /// from <see cref="SourceText.From(Stream, Encoding, SourceHashAlgorithm, bool)"/> in two ways: /// 1. It attempts to minimize allocations by trying to read the stream into a byte array. /// 2. If <paramref name="defaultEncoding"/> is null, it will first try UTF8 and, if that fails, it will /// try CodePage 1252. If CodePage 1252 is not available on the system, then it will try Latin1. /// </summary> /// <param name="stream">The stream containing encoded text.</param> /// <param name="defaultEncoding"> /// Specifies an encoding to be used if the actual encoding can't be determined from the stream content (the stream doesn't start with Byte Order Mark). /// If not specified auto-detect heuristics are used to determine the encoding. If these heuristics fail the decoding is assumed to be Encoding.Default. /// Note that if the stream starts with Byte Order Mark the value of <paramref name="defaultEncoding"/> is ignored. /// </param> /// <param name="canBeEmbedded">Indicates if the file can be embedded in the PDB.</param> /// <param name="checksumAlgorithm">Hash algorithm used to calculate document checksum.</param> /// <exception cref="InvalidDataException"> /// The stream content can't be decoded using the specified <paramref name="defaultEncoding"/>, or /// <paramref name="defaultEncoding"/> is null and the stream appears to be a binary file. /// </exception> /// <exception cref="IOException">An IO error occurred while reading from the stream.</exception> internal static SourceText Create(Stream stream, Encoding? defaultEncoding = null, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1, bool canBeEmbedded = false) { return Create(stream, s_fallbackEncoding, defaultEncoding: defaultEncoding, checksumAlgorithm: checksumAlgorithm, canBeEmbedded: canBeEmbedded); } internal static SourceText Create(Stream stream, Lazy<Encoding> getEncoding, Encoding? defaultEncoding = null, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1, bool canBeEmbedded = false) { RoslynDebug.Assert(stream != null); RoslynDebug.Assert(stream.CanRead); bool detectEncoding = defaultEncoding == null; if (detectEncoding) { try { return Decode(stream, s_utf8Encoding, checksumAlgorithm, throwIfBinaryDetected: false, canBeEmbedded: canBeEmbedded); } catch (DecoderFallbackException) { // Fall back to Encoding.ASCII } } try { return Decode(stream, defaultEncoding ?? getEncoding.Value, checksumAlgorithm, throwIfBinaryDetected: detectEncoding, canBeEmbedded: canBeEmbedded); } catch (DecoderFallbackException e) { throw new InvalidDataException(e.Message); } } /// <summary> /// Try to create a <see cref="SourceText"/> from the given stream using the given encoding. /// </summary> /// <param name="data">The input stream containing the encoded text. The stream will not be closed.</param> /// <param name="encoding">The expected encoding of the stream. The actual encoding used may be different if byte order marks are detected.</param> /// <param name="checksumAlgorithm">The checksum algorithm to use.</param> /// <param name="throwIfBinaryDetected">Throw <see cref="InvalidDataException"/> if binary (non-text) data is detected.</param> /// <param name="canBeEmbedded">Indicates if the text can be embedded in the PDB.</param> /// <returns>The <see cref="SourceText"/> decoded from the stream.</returns> /// <exception cref="DecoderFallbackException">The decoder was unable to decode the stream with the given encoding.</exception> /// <exception cref="IOException">Error reading from stream.</exception> private static SourceText Decode( Stream data, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected = false, bool canBeEmbedded = false) { RoslynDebug.Assert(data != null); RoslynDebug.Assert(encoding != null); if (data.CanSeek) { data.Seek(0, SeekOrigin.Begin); // For small streams, see if we can read the byte buffer directly. if (encoding.GetMaxCharCountOrThrowIfHuge(data) < LargeObjectHeapLimitInChars) { if (TryGetBytesFromStream(data, out ArraySegment<byte> bytes) && bytes.Offset == 0 && bytes.Array is object) { return SourceText.From(bytes.Array, (int)data.Length, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded); } } } return SourceText.From(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded); } /// <summary> /// Some streams are easily represented as bytes. /// </summary> /// <param name="data">The stream</param> /// <param name="bytes">The bytes, if available.</param> /// <returns> /// True if the stream's bytes could easily be read, false otherwise. /// </returns> internal static bool TryGetBytesFromStream(Stream data, out ArraySegment<byte> bytes) { // PERF: If the input is a MemoryStream, we may be able to get at the buffer directly var memoryStream = data as MemoryStream; if (memoryStream != null) { return memoryStream.TryGetBuffer(out bytes); } // PERF: If the input is a FileStream, we may be able to minimize allocations var fileStream = data as FileStream; if (fileStream != null) { return TryGetBytesFromFileStream(fileStream, out bytes); } bytes = new ArraySegment<byte>(Array.Empty<byte>()); return false; } /// <summary> /// Read the contents of a FileStream into a byte array. /// </summary> /// <param name="stream">The FileStream with encoded text.</param> /// <param name="bytes">A byte array filled with the contents of the file.</param> /// <returns>True if a byte array could be created.</returns> private static bool TryGetBytesFromFileStream(FileStream stream, out ArraySegment<byte> bytes) { RoslynDebug.Assert(stream != null); RoslynDebug.Assert(stream.Position == 0); int length = (int)stream.Length; if (length == 0) { bytes = new ArraySegment<byte>(Array.Empty<byte>()); return true; } // PERF: While this is an obvious byte array allocation, it is still cheaper than // using StreamReader.ReadToEnd. The alternative allocates: // 1. A 1KB byte array in the StreamReader for buffered reads // 2. A 4KB byte array in the FileStream for buffered reads // 3. A StringBuilder and its associated char arrays (enough to represent the final decoded string) // TODO: Can this allocation be pooled? var buffer = new byte[length]; // Note: FileStream.Read may still allocate its internal buffer if length is less // than the buffer size. The default buffer size is 4KB, so this will incur a 4KB // allocation for any files less than 4KB. That's why, for example, the command // line compiler actually specifies a very small buffer size. var success = stream.TryReadAll(buffer, 0, length) == length; bytes = success ? new ArraySegment<byte>(buffer) : new ArraySegment<byte>(Array.Empty<byte>()); return success; } internal static class TestAccessor { internal static SourceText Create(Stream stream, Lazy<Encoding> getEncoding, Encoding defaultEncoding, SourceHashAlgorithm checksumAlgorithm, bool canBeEmbedded) => EncodedStringText.Create(stream, getEncoding, defaultEncoding, checksumAlgorithm, canBeEmbedded); internal static SourceText Decode(Stream data, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected, bool canBeEmbedded) => EncodedStringText.Decode(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded); } } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Compilers/Test/Resources/Core/Encoding/sjis.cs
using System.IO; using System.Text; class vleX { public static void Main() { File.WriteAllText("output.txt", " Y", Encoding.GetEncoding(932)); } }
using System.IO; using System.Text; class vleX { public static void Main() { File.WriteAllText("output.txt", " Y", Encoding.GetEncoding(932)); } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/VisualStudio/Core/Impl/ProjectSystem/CPS/CPSProject_IProjectCodeModelProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.CPS { internal sealed partial class CPSProject { public EnvDTE.CodeModel GetCodeModel(EnvDTE.Project parent) => _projectCodeModel.GetOrCreateRootCodeModel(parent); public EnvDTE.FileCodeModel GetFileCodeModel(EnvDTE.ProjectItem item) { if (!item.TryGetFullPath(out var filePath)) { return null; } return _projectCodeModel.GetOrCreateFileCodeModel(filePath, item); } private class CPSCodeModelInstanceFactory : ICodeModelInstanceFactory { private readonly CPSProject _project; public CPSCodeModelInstanceFactory(CPSProject project) => _project = project; EnvDTE.FileCodeModel ICodeModelInstanceFactory.TryCreateFileCodeModelThroughProjectSystem(string filePath) { var projectItem = GetProjectItem(filePath); if (projectItem == null) { return null; } return _project._projectCodeModel.GetOrCreateFileCodeModel(filePath, projectItem); } private EnvDTE.ProjectItem GetProjectItem(string filePath) { var dteProject = _project._visualStudioWorkspace.TryGetDTEProject(_project._visualStudioProject.Id); if (dteProject == null) { return null; } return dteProject.FindItemByPath(filePath, StringComparer.OrdinalIgnoreCase); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.CPS { internal sealed partial class CPSProject { public EnvDTE.CodeModel GetCodeModel(EnvDTE.Project parent) => _projectCodeModel.GetOrCreateRootCodeModel(parent); public EnvDTE.FileCodeModel GetFileCodeModel(EnvDTE.ProjectItem item) { if (!item.TryGetFullPath(out var filePath)) { return null; } return _projectCodeModel.GetOrCreateFileCodeModel(filePath, item); } private class CPSCodeModelInstanceFactory : ICodeModelInstanceFactory { private readonly CPSProject _project; public CPSCodeModelInstanceFactory(CPSProject project) => _project = project; EnvDTE.FileCodeModel ICodeModelInstanceFactory.TryCreateFileCodeModelThroughProjectSystem(string filePath) { var projectItem = GetProjectItem(filePath); if (projectItem == null) { return null; } return _project._projectCodeModel.GetOrCreateFileCodeModel(filePath, projectItem); } private EnvDTE.ProjectItem GetProjectItem(string filePath) { var dteProject = _project._visualStudioWorkspace.TryGetDTEProject(_project._visualStudioProject.Id); if (dteProject == null) { return null; } return dteProject.FindItemByPath(filePath, StringComparer.OrdinalIgnoreCase); } } } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/VisualStudio/Core/Def/Implementation/Snippets/AbstractSnippetExpansionClient.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.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.TextManager.Interop; using MSXML; using Roslyn.Utilities; using CommonFormattingHelpers = Microsoft.CodeAnalysis.Editor.Shared.Utilities.CommonFormattingHelpers; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets { internal abstract class AbstractSnippetExpansionClient : ForegroundThreadAffinitizedObject, IVsExpansionClient { /// <summary> /// The name of a snippet field created for caret placement in Full Method Call snippet sessions when the /// invocation has no parameters. /// </summary> private const string PlaceholderSnippetField = "placeholder"; /// <summary> /// A generated random string which is used to identify argument completion snippets from other snippets. /// </summary> private static readonly string s_fullMethodCallDescriptionSentinel = Guid.NewGuid().ToString("N"); private readonly SignatureHelpControllerProvider _signatureHelpControllerProvider; private readonly IEditorCommandHandlerServiceFactory _editorCommandHandlerServiceFactory; protected readonly IVsEditorAdaptersFactoryService EditorAdaptersFactoryService; protected readonly Guid LanguageServiceGuid; protected readonly ITextView TextView; protected readonly ITextBuffer SubjectBuffer; private readonly ImmutableArray<Lazy<ArgumentProvider, OrderableLanguageMetadata>> _allArgumentProviders; private ImmutableArray<ArgumentProvider> _argumentProviders; private bool _indentCaretOnCommit; private int _indentDepth; private bool _earlyEndExpansionHappened; /// <summary> /// Set to <see langword="true"/> when the snippet client registers an event listener for /// <see cref="Controller.ModelUpdated"/>. /// </summary> /// <remarks> /// This field should only be used from the main thread. /// </remarks> private bool _registeredForSignatureHelpEvents; // Writes to this state only occur on the main thread. private readonly State _state = new(); public AbstractSnippetExpansionClient( IThreadingContext threadingContext, Guid languageServiceGuid, ITextView textView, ITextBuffer subjectBuffer, SignatureHelpControllerProvider signatureHelpControllerProvider, IEditorCommandHandlerServiceFactory editorCommandHandlerServiceFactory, IVsEditorAdaptersFactoryService editorAdaptersFactoryService, ImmutableArray<Lazy<ArgumentProvider, OrderableLanguageMetadata>> argumentProviders) : base(threadingContext) { this.LanguageServiceGuid = languageServiceGuid; this.TextView = textView; this.SubjectBuffer = subjectBuffer; _signatureHelpControllerProvider = signatureHelpControllerProvider; _editorCommandHandlerServiceFactory = editorCommandHandlerServiceFactory; this.EditorAdaptersFactoryService = editorAdaptersFactoryService; _allArgumentProviders = argumentProviders; } /// <inheritdoc cref="State._expansionSession"/> public IVsExpansionSession? ExpansionSession => _state._expansionSession; /// <inheritdoc cref="State.IsFullMethodCallSnippet"/> public bool IsFullMethodCallSnippet => _state.IsFullMethodCallSnippet; public ImmutableArray<ArgumentProvider> GetArgumentProviders(Workspace workspace) { AssertIsForeground(); // TODO: Move this to ArgumentProviderService: https://github.com/dotnet/roslyn/issues/50897 if (_argumentProviders.IsDefault) { _argumentProviders = workspace.Services .SelectMatchingExtensionValues(ExtensionOrderer.Order(_allArgumentProviders), SubjectBuffer.ContentType) .ToImmutableArray(); } return _argumentProviders; } public abstract int GetExpansionFunction(IXMLDOMNode xmlFunctionNode, string bstrFieldName, out IVsExpansionFunction? pFunc); protected abstract ITrackingSpan? InsertEmptyCommentAndGetEndPositionTrackingSpan(); internal abstract Document AddImports(Document document, OptionSet options, int position, XElement snippetNode, bool allowInHiddenRegions, CancellationToken cancellationToken); protected abstract string FallbackDefaultLiteral { get; } public int FormatSpan(IVsTextLines pBuffer, VsTextSpan[] tsInSurfaceBuffer) { AssertIsForeground(); if (ExpansionSession == null) { return VSConstants.E_FAIL; } // If this is a manually-constructed snippet for a full method call, avoid formatting the snippet since // doing so will disrupt signature help. Check ExpansionSession instead of '_state.IsFullMethodCallSnippet' // because '_state._methodNameForInsertFullMethodCall' is not initialized at this point. if (ExpansionSession.TryGetHeaderNode("Description", out var descriptionNode) && descriptionNode?.text == s_fullMethodCallDescriptionSentinel) { return VSConstants.S_OK; } // Formatting a snippet isn't cancellable. var cancellationToken = CancellationToken.None; // At this point, the $selection$ token has been replaced with the selected text and // declarations have been replaced with their default text. We need to format the // inserted snippet text while carefully handling $end$ position (where the caret goes // after Return is pressed). The IVsExpansionSession keeps a tracking point for this // position but we do the tracking ourselves to properly deal with virtual space. To // ensure the end location is correct, we take three extra steps: // 1. Insert an empty comment ("/**/" or "'") at the current $end$ position (prior // to formatting), and keep a tracking span for the comment. // 2. After formatting the new snippet text, find and delete the empty multiline // comment (via the tracking span) and notify the IVsExpansionSession of the new // $end$ location. If the line then contains only whitespace (due to the formatter // putting the empty comment on its own line), then delete the white space and // remember the indentation depth for that line. // 3. When the snippet is finally completed (via Return), and PositionCaretForEditing() // is called, check to see if the end location was on a line containing only white // space in the previous step. If so, and if that line is still empty, then position // the caret in virtual space. // This technique ensures that a snippet like "if($condition$) { $end$ }" will end up // as: // if ($condition$) // { // $end$ // } if (!TryGetSubjectBufferSpan(tsInSurfaceBuffer[0], out var snippetSpan)) { return VSConstants.S_OK; } // Insert empty comment and track end position var snippetTrackingSpan = snippetSpan.CreateTrackingSpan(SpanTrackingMode.EdgeInclusive); var fullSnippetSpan = new VsTextSpan[1]; ExpansionSession.GetSnippetSpan(fullSnippetSpan); var isFullSnippetFormat = fullSnippetSpan[0].iStartLine == tsInSurfaceBuffer[0].iStartLine && fullSnippetSpan[0].iStartIndex == tsInSurfaceBuffer[0].iStartIndex && fullSnippetSpan[0].iEndLine == tsInSurfaceBuffer[0].iEndLine && fullSnippetSpan[0].iEndIndex == tsInSurfaceBuffer[0].iEndIndex; var endPositionTrackingSpan = isFullSnippetFormat ? InsertEmptyCommentAndGetEndPositionTrackingSpan() : null; var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(SubjectBuffer.CurrentSnapshot, snippetTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot)); SubjectBuffer.CurrentSnapshot.FormatAndApplyToBuffer(formattingSpan, CancellationToken.None); if (isFullSnippetFormat) { CleanUpEndLocation(endPositionTrackingSpan); // Unfortunately, this is the only place we can safely add references and imports // specified in the snippet xml. In OnBeforeInsertion we have no guarantee that the // snippet xml will be available, and changing the buffer during OnAfterInsertion can // cause the underlying tracking spans to get out of sync. var currentStartPosition = snippetTrackingSpan.GetStartPoint(SubjectBuffer.CurrentSnapshot).Position; AddReferencesAndImports( ExpansionSession, currentStartPosition, cancellationToken); SetNewEndPosition(endPositionTrackingSpan); } return VSConstants.S_OK; } private void SetNewEndPosition(ITrackingSpan? endTrackingSpan) { RoslynDebug.AssertNotNull(ExpansionSession); if (SetEndPositionIfNoneSpecified(ExpansionSession)) { return; } if (endTrackingSpan != null) { if (!TryGetSpanOnHigherBuffer( endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot), TextView.TextBuffer, out var endSpanInSurfaceBuffer)) { return; } TextView.TextSnapshot.GetLineAndCharacter(endSpanInSurfaceBuffer.Start.Position, out var endLine, out var endChar); ExpansionSession.SetEndSpan(new VsTextSpan { iStartLine = endLine, iStartIndex = endChar, iEndLine = endLine, iEndIndex = endChar }); } } private void CleanUpEndLocation(ITrackingSpan? endTrackingSpan) { if (endTrackingSpan != null) { // Find the empty comment and remove it... var endSnapshotSpan = endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot); SubjectBuffer.Delete(endSnapshotSpan.Span); // Remove the whitespace before the comment if necessary. If whitespace is removed, // then remember the indentation depth so we can appropriately position the caret // in virtual space when the session is ended. var line = SubjectBuffer.CurrentSnapshot.GetLineFromPosition(endSnapshotSpan.Start.Position); var lineText = line.GetText(); if (lineText.Trim() == string.Empty) { _indentCaretOnCommit = true; var document = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { var documentOptions = document.GetOptionsAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); _indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, documentOptions.GetOption(FormattingOptions.TabSize)); } else { // If we don't have a document, then just guess the typical default TabSize value. _indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, tabSize: 4); } SubjectBuffer.Delete(new Span(line.Start.Position, line.Length)); _ = SubjectBuffer.CurrentSnapshot.GetSpan(new Span(line.Start.Position, 0)); } } } /// <summary> /// If there was no $end$ token, place it at the end of the snippet code. Otherwise, it /// defaults to the beginning of the snippet code. /// </summary> private static bool SetEndPositionIfNoneSpecified(IVsExpansionSession pSession) { if (!TryGetSnippetNode(pSession, out var snippetNode)) { return false; } var ns = snippetNode.Name.NamespaceName; var codeNode = snippetNode.Element(XName.Get("Code", ns)); if (codeNode == null) { return false; } var delimiterAttribute = codeNode.Attribute("Delimiter"); var delimiter = delimiterAttribute != null ? delimiterAttribute.Value : "$"; if (codeNode.Value.IndexOf(string.Format("{0}end{0}", delimiter), StringComparison.OrdinalIgnoreCase) != -1) { return false; } var snippetSpan = new VsTextSpan[1]; if (pSession.GetSnippetSpan(snippetSpan) != VSConstants.S_OK) { return false; } var newEndSpan = new VsTextSpan { iStartLine = snippetSpan[0].iEndLine, iStartIndex = snippetSpan[0].iEndIndex, iEndLine = snippetSpan[0].iEndLine, iEndIndex = snippetSpan[0].iEndIndex }; pSession.SetEndSpan(newEndSpan); return true; } protected static bool TryGetSnippetNode(IVsExpansionSession pSession, [NotNullWhen(true)] out XElement? snippetNode) { IXMLDOMNode? xmlNode = null; snippetNode = null; try { // Cast to our own version of IVsExpansionSession so that we can get pNode as an // IntPtr instead of a via a RCW. This allows us to guarantee that it pNode is // released before leaving this method. Otherwise, a second invocation of the same // snippet may cause an AccessViolationException. var session = (IVsExpansionSessionInternal)pSession; if (session.GetSnippetNode(null, out var pNode) != VSConstants.S_OK) { return false; } xmlNode = (IXMLDOMNode)Marshal.GetUniqueObjectForIUnknown(pNode); snippetNode = XElement.Parse(xmlNode.xml); return true; } finally { if (xmlNode != null && Marshal.IsComObject(xmlNode)) { Marshal.ReleaseComObject(xmlNode); } } } public int PositionCaretForEditing(IVsTextLines pBuffer, [ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")] VsTextSpan[] ts) { // If the formatted location of the $end$ position (the inserted comment) was on an // empty line and indented, then we have already removed the white space on that line // and the navigation location will be at column 0 on a blank line. We must now // position the caret in virtual space. pBuffer.GetLengthOfLine(ts[0].iStartLine, out var lineLength); pBuffer.GetLineText(ts[0].iStartLine, 0, ts[0].iStartLine, lineLength, out var endLineText); pBuffer.GetPositionOfLine(ts[0].iStartLine, out var endLinePosition); PositionCaretForEditingInternal(endLineText, endLinePosition); return VSConstants.S_OK; } /// <summary> /// Internal for testing purposes. All real caret positioning logic takes place here. <see cref="PositionCaretForEditing"/> /// only extracts the <paramref name="endLineText"/> and <paramref name="endLinePosition"/> from the provided <see cref="IVsTextLines"/>. /// Tests can call this method directly to avoid producing an IVsTextLines. /// </summary> /// <param name="endLineText"></param> /// <param name="endLinePosition"></param> internal void PositionCaretForEditingInternal(string endLineText, int endLinePosition) { if (_indentCaretOnCommit && endLineText == string.Empty) { TextView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(TextView.TextSnapshot.GetPoint(endLinePosition), _indentDepth)); } } public virtual bool TryHandleTab() { if (ExpansionSession != null) { // When 'Tab' is pressed in the last field of a normal snippet, the session wraps back around to the // first field (this is preservation of historical behavior). When 'Tab' is pressed at the end of an // argument provider snippet, the snippet session is automatically committed (this behavior matches the // design for Insert Full Method Call intended for multiple IDEs). var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(fCommitIfLast: _state.IsFullMethodCallSnippet ? 1 : 0); if (!tabbedInsideSnippetField) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); } return tabbedInsideSnippetField; } return false; } public virtual bool TryHandleBackTab() { if (ExpansionSession != null) { var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToPreviousExpansionField(); if (!tabbedInsideSnippetField) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); } return tabbedInsideSnippetField; } return false; } public virtual bool TryHandleEscape() { if (ExpansionSession != null) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); return true; } return false; } public virtual bool TryHandleReturn() { return CommitSnippet(leaveCaret: false); } /// <summary> /// Commit the active snippet, if any. /// </summary> /// <param name="leaveCaret"><see langword="true"/> to leave the caret position unchanged by the call; /// otherwise, <see langword="false"/> to move the caret to the <c>$end$</c> position of the snippet when the /// snippet is committed.</param> /// <returns><see langword="true"/> if the caret may have moved from the call; otherwise, /// <see langword="false"/> if the caret did not move, or if there was no active snippet session to /// commit.</returns> public bool CommitSnippet(bool leaveCaret) { if (ExpansionSession != null) { if (!leaveCaret) { // Only move the caret if the enter was hit within the snippet fields. var hitWithinField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(fCommitIfLast: 0); leaveCaret = !hitWithinField; } ExpansionSession.EndCurrentExpansion(fLeaveCaret: leaveCaret ? 1 : 0); return !leaveCaret; } return false; } public virtual bool TryInsertExpansion(int startPositionInSubjectBuffer, int endPositionInSubjectBuffer, CancellationToken cancellationToken) { var textViewModel = TextView.TextViewModel; if (textViewModel == null) { Debug.Assert(TextView.IsClosed); return false; } // The expansion itself needs to be created in the data buffer, so map everything up var triggerSpan = SubjectBuffer.CurrentSnapshot.GetSpan(startPositionInSubjectBuffer, endPositionInSubjectBuffer - startPositionInSubjectBuffer); if (!TryGetSpanOnHigherBuffer(triggerSpan, textViewModel.DataBuffer, out var dataBufferSpan)) { return false; } var buffer = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer); if (buffer is not IVsExpansion expansion) { return false; } buffer.GetLineIndexOfPosition(dataBufferSpan.Start.Position, out var startLine, out var startIndex); buffer.GetLineIndexOfPosition(dataBufferSpan.End.Position, out var endLine, out var endIndex); var textSpan = new VsTextSpan { iStartLine = startLine, iStartIndex = startIndex, iEndLine = endLine, iEndIndex = endIndex }; if (TryInsertArgumentCompletionSnippet(triggerSpan, dataBufferSpan, expansion, textSpan, cancellationToken)) { Debug.Assert(_state.IsFullMethodCallSnippet); return true; } if (expansion.InsertExpansion(textSpan, textSpan, this, LanguageServiceGuid, out _state._expansionSession) == VSConstants.S_OK) { // This expansion is not derived from a symbol, so make sure the state isn't tracking any symbol // information Debug.Assert(!_state.IsFullMethodCallSnippet); return true; } return false; } private bool TryInsertArgumentCompletionSnippet(SnapshotSpan triggerSpan, SnapshotSpan dataBufferSpan, IVsExpansion expansion, VsTextSpan textSpan, CancellationToken cancellationToken) { if (!(SubjectBuffer.GetFeatureOnOffOption(CompletionOptions.EnableArgumentCompletionSnippets) ?? false)) { // Argument completion snippets are not enabled return false; } var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document is null) { // Couldn't identify the current document return false; } var symbols = ThreadingContext.JoinableTaskFactory.Run(() => GetReferencedSymbolsToLeftOfCaretAsync(document, caretPosition: triggerSpan.End, cancellationToken)); var methodSymbols = symbols.OfType<IMethodSymbol>().ToImmutableArray(); if (methodSymbols.Any()) { // This is the method name as it appears in source text var methodName = dataBufferSpan.GetText(); var snippet = CreateMethodCallSnippet(methodName, includeMethod: true, ImmutableArray<IParameterSymbol>.Empty, ImmutableDictionary<string, string>.Empty); var doc = (DOMDocument)new DOMDocumentClass(); if (doc.loadXML(snippet.ToString(SaveOptions.OmitDuplicateNamespaces))) { if (expansion.InsertSpecificExpansion(doc, textSpan, this, LanguageServiceGuid, pszRelativePath: null, out _state._expansionSession) == VSConstants.S_OK) { Debug.Assert(_state._expansionSession != null); _state._methodNameForInsertFullMethodCall = methodSymbols.First().Name; Debug.Assert(_state._method == null); if (_signatureHelpControllerProvider.GetController(TextView, SubjectBuffer) is { } controller) { EnsureRegisteredForModelUpdatedEvents(this, controller); } // Trigger signature help after starting the snippet session // // TODO: Figure out why ISignatureHelpBroker.TriggerSignatureHelp doesn't work but this does. // https://github.com/dotnet/roslyn/issues/50036 var editorCommandHandlerService = _editorCommandHandlerServiceFactory.GetService(TextView, SubjectBuffer); editorCommandHandlerService.Execute((view, buffer) => new InvokeSignatureHelpCommandArgs(view, buffer), nextCommandHandler: null); return true; } } } return false; // Local function static void EnsureRegisteredForModelUpdatedEvents(AbstractSnippetExpansionClient client, Controller controller) { // Access to _registeredForSignatureHelpEvents is synchronized on the main thread client.ThreadingContext.ThrowIfNotOnUIThread(); if (!client._registeredForSignatureHelpEvents) { client._registeredForSignatureHelpEvents = true; controller.ModelUpdated += client.OnModelUpdated; client.TextView.Closed += delegate { controller.ModelUpdated -= client.OnModelUpdated; }; } } } /// <summary> /// Creates a snippet for providing arguments to a call. /// </summary> /// <param name="methodName">The name of the method as it should appear in code.</param> /// <param name="includeMethod"> /// <para><see langword="true"/> to include the method name and invocation parentheses in the resulting snippet; /// otherwise, <see langword="false"/> if the method name and parentheses are assumed to already exist and the /// template will only specify the argument placeholders. Since the <c>$end$</c> marker is always considered to /// lie after the closing <c>)</c> of the invocation, it is only included when this parameter is /// <see langword="true"/>.</para> /// /// <para>For example, consider a call to <see cref="int.ToString(IFormatProvider)"/>. If /// <paramref name="includeMethod"/> is <see langword="true"/>, the resulting snippet text might look like /// this:</para> /// /// <code> /// ToString($provider$)$end$ /// </code> /// /// <para>If <paramref name="includeMethod"/> is <see langword="false"/>, the resulting snippet text might look /// like this:</para> /// /// <code> /// $provider$ /// </code> /// /// <para>This parameter supports cycling between overloads of a method for argument completion. Since any text /// edit that alters the <c>(</c> or <c>)</c> characters will force the Signature Help session to close, we are /// careful to only update text that lies between these characters.</para> /// </param> /// <param name="parameters">The parameters to the method. If the specific target of the invocation is not /// known, an empty array may be passed to create a template with a placeholder where arguments will eventually /// go.</param> private static XDocument CreateMethodCallSnippet(string methodName, bool includeMethod, ImmutableArray<IParameterSymbol> parameters, ImmutableDictionary<string, string> parameterValues) { XNamespace snippetNamespace = "http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"; var template = new StringBuilder(); if (includeMethod) { template.Append(methodName).Append('('); } var declarations = new List<XElement>(); foreach (var parameter in parameters) { if (declarations.Any()) { template.Append(", "); } // Create a snippet field for the argument. The name of the field matches the parameter name, and the // default value for the field is provided by a call to the internal ArgumentValue snippet function. The // parameter to the snippet function is a serialized SymbolKey which can be mapped back to the // IParameterSymbol. template.Append('$').Append(parameter.Name).Append('$'); declarations.Add(new XElement( snippetNamespace + "Literal", new XElement(snippetNamespace + "ID", new XText(parameter.Name)), new XElement(snippetNamespace + "Default", new XText(parameterValues.GetValueOrDefault(parameter.Name, ""))))); } if (!declarations.Any()) { // If the invocation does not have any parameters, include an empty placeholder in the snippet template // to ensure the caret starts inside the parentheses and can track changes to other overloads (which may // have parameters). template.Append($"${PlaceholderSnippetField}$"); declarations.Add(new XElement( snippetNamespace + "Literal", new XElement(snippetNamespace + "ID", new XText(PlaceholderSnippetField)), new XElement(snippetNamespace + "Default", new XText("")))); } if (includeMethod) { template.Append(')'); } template.Append("$end$"); // A snippet is manually constructed. Replacement fields are added for each argument, and the field name // matches the parameter name. // https://docs.microsoft.com/en-us/visualstudio/ide/code-snippets-schema-reference?view=vs-2019 return new XDocument( new XDeclaration("1.0", "utf-8", null), new XElement( snippetNamespace + "CodeSnippets", new XElement( snippetNamespace + "CodeSnippet", new XAttribute(snippetNamespace + "Format", "1.0.0"), new XElement( snippetNamespace + "Header", new XElement(snippetNamespace + "Title", new XText(methodName)), new XElement(snippetNamespace + "Description", new XText(s_fullMethodCallDescriptionSentinel))), new XElement( snippetNamespace + "Snippet", new XElement(snippetNamespace + "Declarations", declarations.ToArray()), new XElement( snippetNamespace + "Code", new XAttribute(snippetNamespace + "Language", "csharp"), new XCData(template.ToString())))))); } private void OnModelUpdated(object sender, ModelUpdatedEventsArgs e) { AssertIsForeground(); if (e.NewModel is null) { // Signature Help was dismissed, but it's possible for a user to bring it back with Ctrl+Shift+Space. // Leave the snippet session (if any) in its current state to allow it to process either a subsequent // Signature Help update or the Escape/Enter keys that close the snippet session. return; } if (!_state.IsFullMethodCallSnippet) { // Signature Help is showing an updated signature, but either there is no active snippet, or the active // snippet is not performing argument value completion, so we just ignore it. return; } if (!e.NewModel.UserSelected && _state._method is not null) { // This was an implicit signature change which was not triggered by user pressing up/down, and we are // already showing an initialized argument completion snippet session, so avoid switching sessions. return; } var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document is null) { // It's unclear if/how this state would occur, but if it does we would throw an exception trying to // use it. Just return immediately. return; } // TODO: The following blocks the UI thread without cancellation, but it only occurs when an argument value // completion session is active, which is behind an experimental feature flag. // https://github.com/dotnet/roslyn/issues/50634 var compilation = ThreadingContext.JoinableTaskFactory.Run(() => document.Project.GetRequiredCompilationAsync(CancellationToken.None)); var newSymbolKey = (e.NewModel.SelectedItem as AbstractSignatureHelpProvider.SymbolKeySignatureHelpItem)?.SymbolKey ?? default; var newSymbol = newSymbolKey.Resolve(compilation, cancellationToken: CancellationToken.None).GetAnySymbol(); if (newSymbol is not IMethodSymbol method) return; MoveToSpecificMethod(method, CancellationToken.None); } private static async Task<ImmutableArray<ISymbol>> GetReferencedSymbolsToLeftOfCaretAsync( Document document, SnapshotPoint caretPosition, CancellationToken cancellationToken) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var token = await semanticModel.SyntaxTree.GetTouchingWordAsync(caretPosition.Position, document.GetRequiredLanguageService<ISyntaxFactsService>(), cancellationToken).ConfigureAwait(false); if (token.RawKind == 0) { // There is no touching word, so return empty immediately return ImmutableArray<ISymbol>.Empty; } var semanticInfo = semanticModel.GetSemanticInfo(token, document.Project.Solution.Workspace, cancellationToken); return semanticInfo.ReferencedSymbols; } /// <summary> /// Update the current argument value completion session to use a specific method. /// </summary> /// <param name="method">The currently-selected method in Signature Help.</param> /// <param name="cancellationToken">A cancellation token the operation may observe.</param> public void MoveToSpecificMethod(IMethodSymbol method, CancellationToken cancellationToken) { AssertIsForeground(); if (ExpansionSession is null) { return; } if (SymbolEquivalenceComparer.Instance.Equals(_state._method, method)) { return; } if (_state._methodNameForInsertFullMethodCall != method.Name) { // Signature Help is showing a signature that wasn't part of the set this argument value completion // session was created from. It's unclear how this state should be handled, so we stop processing // Signature Help updates for the current session. // TODO: https://github.com/dotnet/roslyn/issues/50636 ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); return; } // If the first method overload chosen is a zero-parameter method, the snippet we'll create is the same snippet // as the one did initially. The editor appears to have a bug where inserting a zero-width snippet (when we update the parameters) // causes the inserted session to immediately dismiss; this works around that issue. if (_state._method is null && method.Parameters.Length == 0) { _state._method = method; return; } var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document is null) { // Couldn't identify the current document ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); return; } var textViewModel = TextView.TextViewModel; if (textViewModel == null) { Debug.Assert(TextView.IsClosed); return; } var buffer = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer); if (buffer is not IVsExpansion expansion) { return; } // We need to replace the portion of the existing Full Method Call snippet which appears inside parentheses. // This span starts at the beginning of the first snippet field, and ends at the end of the last snippet // field. Methods with no arguments still have an empty "placeholder" snippet field representing the initial // caret position when the snippet is created. var textSpan = new VsTextSpan[1]; if (ExpansionSession.GetSnippetSpan(textSpan) != VSConstants.S_OK) { return; } var firstField = _state._method?.Parameters.FirstOrDefault()?.Name ?? PlaceholderSnippetField; if (ExpansionSession.GetFieldSpan(firstField, textSpan) != VSConstants.S_OK) { return; } VsTextSpan adjustedTextSpan; adjustedTextSpan.iStartLine = textSpan[0].iStartLine; adjustedTextSpan.iStartIndex = textSpan[0].iStartIndex; var lastField = _state._method?.Parameters.LastOrDefault()?.Name ?? PlaceholderSnippetField; if (ExpansionSession.GetFieldSpan(lastField, textSpan) != VSConstants.S_OK) { return; } adjustedTextSpan.iEndLine = textSpan[0].iEndLine; adjustedTextSpan.iEndIndex = textSpan[0].iEndIndex; // Track current argument values so input created/updated by a user is not lost when cycling through // Signature Help overloads: // // 1. For each parameter of the method currently presented as a snippet, the value of the argument as // it appears in code. // 2. Place the argument values in a map from parameter name to current value. // 3. (Later) the values in the map can be read to avoid providing new values for equivalent parameters. var newArguments = _state._arguments; if (_state._method is null || !_state._method.Parameters.Any()) { // If we didn't have any previous parameters, then there is only the placeholder in the snippet. // We don't want to lose what the user has typed there, if they typed something if (ExpansionSession.GetFieldValue(PlaceholderSnippetField, out var placeholderValue) == VSConstants.S_OK && placeholderValue.Length > 0) { if (method.Parameters.Any()) { newArguments = newArguments.SetItem(method.Parameters[0].Name, placeholderValue); } else { // TODO: if the user is typing before signature help updated the model, and we have no parameters here, // should we still create a new snippet that has the existing placeholder text? } } } else if (_state._method is not null) { foreach (var previousParameter in _state._method.Parameters) { if (ExpansionSession.GetFieldValue(previousParameter.Name, out var previousValue) == VSConstants.S_OK) { newArguments = newArguments.SetItem(previousParameter.Name, previousValue); } } } // Now compute the new arguments for the new call var semanticModel = document.GetRequiredSemanticModelAsync(cancellationToken).AsTask().WaitAndGetResult(cancellationToken); var position = SubjectBuffer.CurrentSnapshot.GetPosition(adjustedTextSpan.iStartLine, adjustedTextSpan.iStartIndex); foreach (var parameter in method.Parameters) { newArguments.TryGetValue(parameter.Name, out var value); foreach (var provider in GetArgumentProviders(document.Project.Solution.Workspace)) { var context = new ArgumentContext(provider, semanticModel, position, parameter, value, cancellationToken); ThreadingContext.JoinableTaskFactory.Run(() => provider.ProvideArgumentAsync(context)); if (context.DefaultValue is not null) { value = context.DefaultValue; break; } } // If we still have no value, fill in the default if (value is null) { value = FallbackDefaultLiteral; } newArguments = newArguments.SetItem(parameter.Name, value); } var snippet = CreateMethodCallSnippet(method.Name, includeMethod: false, method.Parameters, newArguments); var doc = (DOMDocument)new DOMDocumentClass(); if (doc.loadXML(snippet.ToString(SaveOptions.OmitDuplicateNamespaces))) { if (expansion.InsertSpecificExpansion(doc, adjustedTextSpan, this, LanguageServiceGuid, pszRelativePath: null, out _state._expansionSession) == VSConstants.S_OK) { Debug.Assert(_state._expansionSession != null); _state._methodNameForInsertFullMethodCall = method.Name; _state._method = method; _state._arguments = newArguments; // On this path, the closing parenthesis is not part of the updated snippet, so there is no way for // the snippet itself to represent the $end$ marker (which falls after the ')' character). Instead, // we use the internal APIs to manually specify the effective position of the $end$ marker as the // location in code immediately following the ')'. To do this, we use the knowledge that the snippet // includes all text up to (but not including) the ')', and move that span one position to the // right. if (ExpansionSession.GetEndSpan(textSpan) == VSConstants.S_OK) { textSpan[0].iStartIndex++; textSpan[0].iEndIndex++; ExpansionSession.SetEndSpan(textSpan[0]); } } } } public int EndExpansion() { if (ExpansionSession == null) { _earlyEndExpansionHappened = true; } _state.Clear(); _indentCaretOnCommit = false; return VSConstants.S_OK; } public int IsValidKind(IVsTextLines pBuffer, VsTextSpan[] ts, string bstrKind, out int pfIsValidKind) { pfIsValidKind = 1; return VSConstants.S_OK; } public int IsValidType(IVsTextLines pBuffer, VsTextSpan[] ts, string[] rgTypes, int iCountTypes, out int pfIsValidType) { pfIsValidType = 1; return VSConstants.S_OK; } public int OnAfterInsertion(IVsExpansionSession pSession) { Logger.Log(FunctionId.Snippet_OnAfterInsertion); return VSConstants.S_OK; } public int OnBeforeInsertion(IVsExpansionSession pSession) { Logger.Log(FunctionId.Snippet_OnBeforeInsertion); _state._expansionSession = pSession; // Symbol information (when necessary) is set by the caller return VSConstants.S_OK; } public int OnItemChosen(string pszTitle, string pszPath) { var textViewModel = TextView.TextViewModel; if (textViewModel == null) { Debug.Assert(TextView.IsClosed); return VSConstants.E_FAIL; } int hr; try { VsTextSpan textSpan; GetCaretPositionInSurfaceBuffer(out textSpan.iStartLine, out textSpan.iStartIndex); textSpan.iEndLine = textSpan.iStartLine; textSpan.iEndIndex = textSpan.iStartIndex; var expansion = (IVsExpansion?)EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer); Contract.ThrowIfNull(expansion); _earlyEndExpansionHappened = false; hr = expansion.InsertNamedExpansion(pszTitle, pszPath, textSpan, this, LanguageServiceGuid, fShowDisambiguationUI: 0, pSession: out _state._expansionSession); if (_earlyEndExpansionHappened) { // EndExpansion was called before InsertNamedExpansion returned, so set // expansionSession to null to indicate that there is no active expansion // session. This can occur when the snippet inserted doesn't have any expansion // fields. _state._expansionSession = null; _earlyEndExpansionHappened = false; } } catch (COMException ex) { hr = ex.ErrorCode; } return hr; } private void GetCaretPositionInSurfaceBuffer(out int caretLine, out int caretColumn) { var vsTextView = EditorAdaptersFactoryService.GetViewAdapter(TextView); Contract.ThrowIfNull(vsTextView); vsTextView.GetCaretPos(out caretLine, out caretColumn); vsTextView.GetBuffer(out var textLines); // Handle virtual space (e.g, see Dev10 778675) textLines.GetLengthOfLine(caretLine, out var lineLength); if (caretColumn > lineLength) { caretColumn = lineLength; } } private void AddReferencesAndImports( IVsExpansionSession pSession, int position, CancellationToken cancellationToken) { if (!TryGetSnippetNode(pSession, out var snippetNode)) { return; } var documentWithImports = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (documentWithImports == null) { return; } var documentOptions = documentWithImports.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken); var allowInHiddenRegions = documentWithImports.CanAddImportsInHiddenRegions(); documentWithImports = AddImports(documentWithImports, documentOptions, position, snippetNode, allowInHiddenRegions, cancellationToken); AddReferences(documentWithImports.Project, snippetNode); } private void AddReferences(Project originalProject, XElement snippetNode) { var referencesNode = snippetNode.Element(XName.Get("References", snippetNode.Name.NamespaceName)); if (referencesNode == null) { return; } var existingReferenceNames = originalProject.MetadataReferences.Select(r => Path.GetFileNameWithoutExtension(r.Display)); var workspace = originalProject.Solution.Workspace; var projectId = originalProject.Id; var assemblyXmlName = XName.Get("Assembly", snippetNode.Name.NamespaceName); var failedReferenceAdditions = new List<string>(); foreach (var reference in referencesNode.Elements(XName.Get("Reference", snippetNode.Name.NamespaceName))) { // Note: URL references are not supported var assemblyElement = reference.Element(assemblyXmlName); var assemblyName = assemblyElement != null ? assemblyElement.Value.Trim() : null; if (RoslynString.IsNullOrEmpty(assemblyName)) { continue; } if (workspace is not VisualStudioWorkspaceImpl visualStudioWorkspace || !visualStudioWorkspace.TryAddReferenceToProject(projectId, assemblyName)) { failedReferenceAdditions.Add(assemblyName); } } if (failedReferenceAdditions.Any()) { var notificationService = workspace.Services.GetRequiredService<INotificationService>(); notificationService.SendNotification( string.Format(ServicesVSResources.The_following_references_were_not_found_0_Please_locate_and_add_them_manually, Environment.NewLine) + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, failedReferenceAdditions), severity: NotificationSeverity.Warning); } } protected static bool TryAddImportsToContainedDocument(Document document, IEnumerable<string> memberImportsNamespaces) { if (document.Project.Solution.Workspace is not VisualStudioWorkspaceImpl vsWorkspace) { return false; } var containedDocument = vsWorkspace.TryGetContainedDocument(document.Id); if (containedDocument == null) { return false; } if (containedDocument.ContainedLanguageHost is IVsContainedLanguageHostInternal containedLanguageHost) { foreach (var importClause in memberImportsNamespaces) { if (containedLanguageHost.InsertImportsDirective(importClause) != VSConstants.S_OK) { return false; } } } return true; } protected static bool TryGetSnippetFunctionInfo( IXMLDOMNode xmlFunctionNode, [NotNullWhen(true)] out string? snippetFunctionName, [NotNullWhen(true)] out string? param) { if (xmlFunctionNode.text.IndexOf('(') == -1 || xmlFunctionNode.text.IndexOf(')') == -1 || xmlFunctionNode.text.IndexOf(')') < xmlFunctionNode.text.IndexOf('(')) { snippetFunctionName = null; param = null; return false; } snippetFunctionName = xmlFunctionNode.text.Substring(0, xmlFunctionNode.text.IndexOf('(')); var paramStart = xmlFunctionNode.text.IndexOf('(') + 1; var paramLength = xmlFunctionNode.text.LastIndexOf(')') - xmlFunctionNode.text.IndexOf('(') - 1; param = xmlFunctionNode.text.Substring(paramStart, paramLength); return true; } internal bool TryGetSubjectBufferSpan(VsTextSpan surfaceBufferTextSpan, out SnapshotSpan subjectBufferSpan) { var snapshotSpan = TextView.TextSnapshot.GetSpan(surfaceBufferTextSpan); var subjectBufferSpanCollection = TextView.BufferGraph.MapDownToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, SubjectBuffer); // Bail if a snippet span does not map down to exactly one subject buffer span. if (subjectBufferSpanCollection.Count == 1) { subjectBufferSpan = subjectBufferSpanCollection.Single(); return true; } subjectBufferSpan = default; return false; } internal bool TryGetSpanOnHigherBuffer(SnapshotSpan snapshotSpan, ITextBuffer targetBuffer, out SnapshotSpan span) { var spanCollection = TextView.BufferGraph.MapUpToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, targetBuffer); // Bail if a snippet span does not map up to exactly one span. if (spanCollection.Count == 1) { span = spanCollection.Single(); return true; } span = default; return false; } private sealed class State { /// <summary> /// The current expansion session. /// </summary> public IVsExpansionSession? _expansionSession; /// <summary> /// The symbol name of the method that we have invoked insert full method call on; or <see langword="null"/> /// if there is no active snippet session or the active session is a regular snippets session. /// </summary> public string? _methodNameForInsertFullMethodCall; /// <summary> /// The current symbol presented in an Argument Provider snippet session. This may be null if Signature Help /// has not yet provided a symbol to show. /// </summary> public IMethodSymbol? _method; /// <summary> /// Maps from parameter name to current argument value. When this dictionary does not contain a mapping for /// a parameter, it means no argument has been provided yet by an ArgumentProvider or the user for a /// parameter with this name. This map is cleared at the final end of an argument provider snippet session. /// </summary> public ImmutableDictionary<string, string> _arguments = ImmutableDictionary.Create<string, string>(); /// <summary> /// <see langword="true"/> if the current snippet session is a Full Method Call snippet session; otherwise, /// <see langword="false"/> if there is no current snippet session or if the current snippet session is a normal snippet. /// </summary> public bool IsFullMethodCallSnippet => _expansionSession is not null && _methodNameForInsertFullMethodCall is not null; public void Clear() { _expansionSession = null; _methodNameForInsertFullMethodCall = null; _method = null; _arguments = _arguments.Clear(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.TextManager.Interop; using MSXML; using Roslyn.Utilities; using CommonFormattingHelpers = Microsoft.CodeAnalysis.Editor.Shared.Utilities.CommonFormattingHelpers; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets { internal abstract class AbstractSnippetExpansionClient : ForegroundThreadAffinitizedObject, IVsExpansionClient { /// <summary> /// The name of a snippet field created for caret placement in Full Method Call snippet sessions when the /// invocation has no parameters. /// </summary> private const string PlaceholderSnippetField = "placeholder"; /// <summary> /// A generated random string which is used to identify argument completion snippets from other snippets. /// </summary> private static readonly string s_fullMethodCallDescriptionSentinel = Guid.NewGuid().ToString("N"); private readonly SignatureHelpControllerProvider _signatureHelpControllerProvider; private readonly IEditorCommandHandlerServiceFactory _editorCommandHandlerServiceFactory; protected readonly IVsEditorAdaptersFactoryService EditorAdaptersFactoryService; protected readonly Guid LanguageServiceGuid; protected readonly ITextView TextView; protected readonly ITextBuffer SubjectBuffer; private readonly ImmutableArray<Lazy<ArgumentProvider, OrderableLanguageMetadata>> _allArgumentProviders; private ImmutableArray<ArgumentProvider> _argumentProviders; private bool _indentCaretOnCommit; private int _indentDepth; private bool _earlyEndExpansionHappened; /// <summary> /// Set to <see langword="true"/> when the snippet client registers an event listener for /// <see cref="Controller.ModelUpdated"/>. /// </summary> /// <remarks> /// This field should only be used from the main thread. /// </remarks> private bool _registeredForSignatureHelpEvents; // Writes to this state only occur on the main thread. private readonly State _state = new(); public AbstractSnippetExpansionClient( IThreadingContext threadingContext, Guid languageServiceGuid, ITextView textView, ITextBuffer subjectBuffer, SignatureHelpControllerProvider signatureHelpControllerProvider, IEditorCommandHandlerServiceFactory editorCommandHandlerServiceFactory, IVsEditorAdaptersFactoryService editorAdaptersFactoryService, ImmutableArray<Lazy<ArgumentProvider, OrderableLanguageMetadata>> argumentProviders) : base(threadingContext) { this.LanguageServiceGuid = languageServiceGuid; this.TextView = textView; this.SubjectBuffer = subjectBuffer; _signatureHelpControllerProvider = signatureHelpControllerProvider; _editorCommandHandlerServiceFactory = editorCommandHandlerServiceFactory; this.EditorAdaptersFactoryService = editorAdaptersFactoryService; _allArgumentProviders = argumentProviders; } /// <inheritdoc cref="State._expansionSession"/> public IVsExpansionSession? ExpansionSession => _state._expansionSession; /// <inheritdoc cref="State.IsFullMethodCallSnippet"/> public bool IsFullMethodCallSnippet => _state.IsFullMethodCallSnippet; public ImmutableArray<ArgumentProvider> GetArgumentProviders(Workspace workspace) { AssertIsForeground(); // TODO: Move this to ArgumentProviderService: https://github.com/dotnet/roslyn/issues/50897 if (_argumentProviders.IsDefault) { _argumentProviders = workspace.Services .SelectMatchingExtensionValues(ExtensionOrderer.Order(_allArgumentProviders), SubjectBuffer.ContentType) .ToImmutableArray(); } return _argumentProviders; } public abstract int GetExpansionFunction(IXMLDOMNode xmlFunctionNode, string bstrFieldName, out IVsExpansionFunction? pFunc); protected abstract ITrackingSpan? InsertEmptyCommentAndGetEndPositionTrackingSpan(); internal abstract Document AddImports(Document document, OptionSet options, int position, XElement snippetNode, bool allowInHiddenRegions, CancellationToken cancellationToken); protected abstract string FallbackDefaultLiteral { get; } public int FormatSpan(IVsTextLines pBuffer, VsTextSpan[] tsInSurfaceBuffer) { AssertIsForeground(); if (ExpansionSession == null) { return VSConstants.E_FAIL; } // If this is a manually-constructed snippet for a full method call, avoid formatting the snippet since // doing so will disrupt signature help. Check ExpansionSession instead of '_state.IsFullMethodCallSnippet' // because '_state._methodNameForInsertFullMethodCall' is not initialized at this point. if (ExpansionSession.TryGetHeaderNode("Description", out var descriptionNode) && descriptionNode?.text == s_fullMethodCallDescriptionSentinel) { return VSConstants.S_OK; } // Formatting a snippet isn't cancellable. var cancellationToken = CancellationToken.None; // At this point, the $selection$ token has been replaced with the selected text and // declarations have been replaced with their default text. We need to format the // inserted snippet text while carefully handling $end$ position (where the caret goes // after Return is pressed). The IVsExpansionSession keeps a tracking point for this // position but we do the tracking ourselves to properly deal with virtual space. To // ensure the end location is correct, we take three extra steps: // 1. Insert an empty comment ("/**/" or "'") at the current $end$ position (prior // to formatting), and keep a tracking span for the comment. // 2. After formatting the new snippet text, find and delete the empty multiline // comment (via the tracking span) and notify the IVsExpansionSession of the new // $end$ location. If the line then contains only whitespace (due to the formatter // putting the empty comment on its own line), then delete the white space and // remember the indentation depth for that line. // 3. When the snippet is finally completed (via Return), and PositionCaretForEditing() // is called, check to see if the end location was on a line containing only white // space in the previous step. If so, and if that line is still empty, then position // the caret in virtual space. // This technique ensures that a snippet like "if($condition$) { $end$ }" will end up // as: // if ($condition$) // { // $end$ // } if (!TryGetSubjectBufferSpan(tsInSurfaceBuffer[0], out var snippetSpan)) { return VSConstants.S_OK; } // Insert empty comment and track end position var snippetTrackingSpan = snippetSpan.CreateTrackingSpan(SpanTrackingMode.EdgeInclusive); var fullSnippetSpan = new VsTextSpan[1]; ExpansionSession.GetSnippetSpan(fullSnippetSpan); var isFullSnippetFormat = fullSnippetSpan[0].iStartLine == tsInSurfaceBuffer[0].iStartLine && fullSnippetSpan[0].iStartIndex == tsInSurfaceBuffer[0].iStartIndex && fullSnippetSpan[0].iEndLine == tsInSurfaceBuffer[0].iEndLine && fullSnippetSpan[0].iEndIndex == tsInSurfaceBuffer[0].iEndIndex; var endPositionTrackingSpan = isFullSnippetFormat ? InsertEmptyCommentAndGetEndPositionTrackingSpan() : null; var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(SubjectBuffer.CurrentSnapshot, snippetTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot)); SubjectBuffer.CurrentSnapshot.FormatAndApplyToBuffer(formattingSpan, CancellationToken.None); if (isFullSnippetFormat) { CleanUpEndLocation(endPositionTrackingSpan); // Unfortunately, this is the only place we can safely add references and imports // specified in the snippet xml. In OnBeforeInsertion we have no guarantee that the // snippet xml will be available, and changing the buffer during OnAfterInsertion can // cause the underlying tracking spans to get out of sync. var currentStartPosition = snippetTrackingSpan.GetStartPoint(SubjectBuffer.CurrentSnapshot).Position; AddReferencesAndImports( ExpansionSession, currentStartPosition, cancellationToken); SetNewEndPosition(endPositionTrackingSpan); } return VSConstants.S_OK; } private void SetNewEndPosition(ITrackingSpan? endTrackingSpan) { RoslynDebug.AssertNotNull(ExpansionSession); if (SetEndPositionIfNoneSpecified(ExpansionSession)) { return; } if (endTrackingSpan != null) { if (!TryGetSpanOnHigherBuffer( endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot), TextView.TextBuffer, out var endSpanInSurfaceBuffer)) { return; } TextView.TextSnapshot.GetLineAndCharacter(endSpanInSurfaceBuffer.Start.Position, out var endLine, out var endChar); ExpansionSession.SetEndSpan(new VsTextSpan { iStartLine = endLine, iStartIndex = endChar, iEndLine = endLine, iEndIndex = endChar }); } } private void CleanUpEndLocation(ITrackingSpan? endTrackingSpan) { if (endTrackingSpan != null) { // Find the empty comment and remove it... var endSnapshotSpan = endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot); SubjectBuffer.Delete(endSnapshotSpan.Span); // Remove the whitespace before the comment if necessary. If whitespace is removed, // then remember the indentation depth so we can appropriately position the caret // in virtual space when the session is ended. var line = SubjectBuffer.CurrentSnapshot.GetLineFromPosition(endSnapshotSpan.Start.Position); var lineText = line.GetText(); if (lineText.Trim() == string.Empty) { _indentCaretOnCommit = true; var document = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { var documentOptions = document.GetOptionsAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); _indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, documentOptions.GetOption(FormattingOptions.TabSize)); } else { // If we don't have a document, then just guess the typical default TabSize value. _indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, tabSize: 4); } SubjectBuffer.Delete(new Span(line.Start.Position, line.Length)); _ = SubjectBuffer.CurrentSnapshot.GetSpan(new Span(line.Start.Position, 0)); } } } /// <summary> /// If there was no $end$ token, place it at the end of the snippet code. Otherwise, it /// defaults to the beginning of the snippet code. /// </summary> private static bool SetEndPositionIfNoneSpecified(IVsExpansionSession pSession) { if (!TryGetSnippetNode(pSession, out var snippetNode)) { return false; } var ns = snippetNode.Name.NamespaceName; var codeNode = snippetNode.Element(XName.Get("Code", ns)); if (codeNode == null) { return false; } var delimiterAttribute = codeNode.Attribute("Delimiter"); var delimiter = delimiterAttribute != null ? delimiterAttribute.Value : "$"; if (codeNode.Value.IndexOf(string.Format("{0}end{0}", delimiter), StringComparison.OrdinalIgnoreCase) != -1) { return false; } var snippetSpan = new VsTextSpan[1]; if (pSession.GetSnippetSpan(snippetSpan) != VSConstants.S_OK) { return false; } var newEndSpan = new VsTextSpan { iStartLine = snippetSpan[0].iEndLine, iStartIndex = snippetSpan[0].iEndIndex, iEndLine = snippetSpan[0].iEndLine, iEndIndex = snippetSpan[0].iEndIndex }; pSession.SetEndSpan(newEndSpan); return true; } protected static bool TryGetSnippetNode(IVsExpansionSession pSession, [NotNullWhen(true)] out XElement? snippetNode) { IXMLDOMNode? xmlNode = null; snippetNode = null; try { // Cast to our own version of IVsExpansionSession so that we can get pNode as an // IntPtr instead of a via a RCW. This allows us to guarantee that it pNode is // released before leaving this method. Otherwise, a second invocation of the same // snippet may cause an AccessViolationException. var session = (IVsExpansionSessionInternal)pSession; if (session.GetSnippetNode(null, out var pNode) != VSConstants.S_OK) { return false; } xmlNode = (IXMLDOMNode)Marshal.GetUniqueObjectForIUnknown(pNode); snippetNode = XElement.Parse(xmlNode.xml); return true; } finally { if (xmlNode != null && Marshal.IsComObject(xmlNode)) { Marshal.ReleaseComObject(xmlNode); } } } public int PositionCaretForEditing(IVsTextLines pBuffer, [ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")] VsTextSpan[] ts) { // If the formatted location of the $end$ position (the inserted comment) was on an // empty line and indented, then we have already removed the white space on that line // and the navigation location will be at column 0 on a blank line. We must now // position the caret in virtual space. pBuffer.GetLengthOfLine(ts[0].iStartLine, out var lineLength); pBuffer.GetLineText(ts[0].iStartLine, 0, ts[0].iStartLine, lineLength, out var endLineText); pBuffer.GetPositionOfLine(ts[0].iStartLine, out var endLinePosition); PositionCaretForEditingInternal(endLineText, endLinePosition); return VSConstants.S_OK; } /// <summary> /// Internal for testing purposes. All real caret positioning logic takes place here. <see cref="PositionCaretForEditing"/> /// only extracts the <paramref name="endLineText"/> and <paramref name="endLinePosition"/> from the provided <see cref="IVsTextLines"/>. /// Tests can call this method directly to avoid producing an IVsTextLines. /// </summary> /// <param name="endLineText"></param> /// <param name="endLinePosition"></param> internal void PositionCaretForEditingInternal(string endLineText, int endLinePosition) { if (_indentCaretOnCommit && endLineText == string.Empty) { TextView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(TextView.TextSnapshot.GetPoint(endLinePosition), _indentDepth)); } } public virtual bool TryHandleTab() { if (ExpansionSession != null) { // When 'Tab' is pressed in the last field of a normal snippet, the session wraps back around to the // first field (this is preservation of historical behavior). When 'Tab' is pressed at the end of an // argument provider snippet, the snippet session is automatically committed (this behavior matches the // design for Insert Full Method Call intended for multiple IDEs). var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(fCommitIfLast: _state.IsFullMethodCallSnippet ? 1 : 0); if (!tabbedInsideSnippetField) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); } return tabbedInsideSnippetField; } return false; } public virtual bool TryHandleBackTab() { if (ExpansionSession != null) { var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToPreviousExpansionField(); if (!tabbedInsideSnippetField) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); } return tabbedInsideSnippetField; } return false; } public virtual bool TryHandleEscape() { if (ExpansionSession != null) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); return true; } return false; } public virtual bool TryHandleReturn() { return CommitSnippet(leaveCaret: false); } /// <summary> /// Commit the active snippet, if any. /// </summary> /// <param name="leaveCaret"><see langword="true"/> to leave the caret position unchanged by the call; /// otherwise, <see langword="false"/> to move the caret to the <c>$end$</c> position of the snippet when the /// snippet is committed.</param> /// <returns><see langword="true"/> if the caret may have moved from the call; otherwise, /// <see langword="false"/> if the caret did not move, or if there was no active snippet session to /// commit.</returns> public bool CommitSnippet(bool leaveCaret) { if (ExpansionSession != null) { if (!leaveCaret) { // Only move the caret if the enter was hit within the snippet fields. var hitWithinField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(fCommitIfLast: 0); leaveCaret = !hitWithinField; } ExpansionSession.EndCurrentExpansion(fLeaveCaret: leaveCaret ? 1 : 0); return !leaveCaret; } return false; } public virtual bool TryInsertExpansion(int startPositionInSubjectBuffer, int endPositionInSubjectBuffer, CancellationToken cancellationToken) { var textViewModel = TextView.TextViewModel; if (textViewModel == null) { Debug.Assert(TextView.IsClosed); return false; } // The expansion itself needs to be created in the data buffer, so map everything up var triggerSpan = SubjectBuffer.CurrentSnapshot.GetSpan(startPositionInSubjectBuffer, endPositionInSubjectBuffer - startPositionInSubjectBuffer); if (!TryGetSpanOnHigherBuffer(triggerSpan, textViewModel.DataBuffer, out var dataBufferSpan)) { return false; } var buffer = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer); if (buffer is not IVsExpansion expansion) { return false; } buffer.GetLineIndexOfPosition(dataBufferSpan.Start.Position, out var startLine, out var startIndex); buffer.GetLineIndexOfPosition(dataBufferSpan.End.Position, out var endLine, out var endIndex); var textSpan = new VsTextSpan { iStartLine = startLine, iStartIndex = startIndex, iEndLine = endLine, iEndIndex = endIndex }; if (TryInsertArgumentCompletionSnippet(triggerSpan, dataBufferSpan, expansion, textSpan, cancellationToken)) { Debug.Assert(_state.IsFullMethodCallSnippet); return true; } if (expansion.InsertExpansion(textSpan, textSpan, this, LanguageServiceGuid, out _state._expansionSession) == VSConstants.S_OK) { // This expansion is not derived from a symbol, so make sure the state isn't tracking any symbol // information Debug.Assert(!_state.IsFullMethodCallSnippet); return true; } return false; } private bool TryInsertArgumentCompletionSnippet(SnapshotSpan triggerSpan, SnapshotSpan dataBufferSpan, IVsExpansion expansion, VsTextSpan textSpan, CancellationToken cancellationToken) { if (!(SubjectBuffer.GetFeatureOnOffOption(CompletionOptions.EnableArgumentCompletionSnippets) ?? false)) { // Argument completion snippets are not enabled return false; } var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document is null) { // Couldn't identify the current document return false; } var symbols = ThreadingContext.JoinableTaskFactory.Run(() => GetReferencedSymbolsToLeftOfCaretAsync(document, caretPosition: triggerSpan.End, cancellationToken)); var methodSymbols = symbols.OfType<IMethodSymbol>().ToImmutableArray(); if (methodSymbols.Any()) { // This is the method name as it appears in source text var methodName = dataBufferSpan.GetText(); var snippet = CreateMethodCallSnippet(methodName, includeMethod: true, ImmutableArray<IParameterSymbol>.Empty, ImmutableDictionary<string, string>.Empty); var doc = (DOMDocument)new DOMDocumentClass(); if (doc.loadXML(snippet.ToString(SaveOptions.OmitDuplicateNamespaces))) { if (expansion.InsertSpecificExpansion(doc, textSpan, this, LanguageServiceGuid, pszRelativePath: null, out _state._expansionSession) == VSConstants.S_OK) { Debug.Assert(_state._expansionSession != null); _state._methodNameForInsertFullMethodCall = methodSymbols.First().Name; Debug.Assert(_state._method == null); if (_signatureHelpControllerProvider.GetController(TextView, SubjectBuffer) is { } controller) { EnsureRegisteredForModelUpdatedEvents(this, controller); } // Trigger signature help after starting the snippet session // // TODO: Figure out why ISignatureHelpBroker.TriggerSignatureHelp doesn't work but this does. // https://github.com/dotnet/roslyn/issues/50036 var editorCommandHandlerService = _editorCommandHandlerServiceFactory.GetService(TextView, SubjectBuffer); editorCommandHandlerService.Execute((view, buffer) => new InvokeSignatureHelpCommandArgs(view, buffer), nextCommandHandler: null); return true; } } } return false; // Local function static void EnsureRegisteredForModelUpdatedEvents(AbstractSnippetExpansionClient client, Controller controller) { // Access to _registeredForSignatureHelpEvents is synchronized on the main thread client.ThreadingContext.ThrowIfNotOnUIThread(); if (!client._registeredForSignatureHelpEvents) { client._registeredForSignatureHelpEvents = true; controller.ModelUpdated += client.OnModelUpdated; client.TextView.Closed += delegate { controller.ModelUpdated -= client.OnModelUpdated; }; } } } /// <summary> /// Creates a snippet for providing arguments to a call. /// </summary> /// <param name="methodName">The name of the method as it should appear in code.</param> /// <param name="includeMethod"> /// <para><see langword="true"/> to include the method name and invocation parentheses in the resulting snippet; /// otherwise, <see langword="false"/> if the method name and parentheses are assumed to already exist and the /// template will only specify the argument placeholders. Since the <c>$end$</c> marker is always considered to /// lie after the closing <c>)</c> of the invocation, it is only included when this parameter is /// <see langword="true"/>.</para> /// /// <para>For example, consider a call to <see cref="int.ToString(IFormatProvider)"/>. If /// <paramref name="includeMethod"/> is <see langword="true"/>, the resulting snippet text might look like /// this:</para> /// /// <code> /// ToString($provider$)$end$ /// </code> /// /// <para>If <paramref name="includeMethod"/> is <see langword="false"/>, the resulting snippet text might look /// like this:</para> /// /// <code> /// $provider$ /// </code> /// /// <para>This parameter supports cycling between overloads of a method for argument completion. Since any text /// edit that alters the <c>(</c> or <c>)</c> characters will force the Signature Help session to close, we are /// careful to only update text that lies between these characters.</para> /// </param> /// <param name="parameters">The parameters to the method. If the specific target of the invocation is not /// known, an empty array may be passed to create a template with a placeholder where arguments will eventually /// go.</param> private static XDocument CreateMethodCallSnippet(string methodName, bool includeMethod, ImmutableArray<IParameterSymbol> parameters, ImmutableDictionary<string, string> parameterValues) { XNamespace snippetNamespace = "http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"; var template = new StringBuilder(); if (includeMethod) { template.Append(methodName).Append('('); } var declarations = new List<XElement>(); foreach (var parameter in parameters) { if (declarations.Any()) { template.Append(", "); } // Create a snippet field for the argument. The name of the field matches the parameter name, and the // default value for the field is provided by a call to the internal ArgumentValue snippet function. The // parameter to the snippet function is a serialized SymbolKey which can be mapped back to the // IParameterSymbol. template.Append('$').Append(parameter.Name).Append('$'); declarations.Add(new XElement( snippetNamespace + "Literal", new XElement(snippetNamespace + "ID", new XText(parameter.Name)), new XElement(snippetNamespace + "Default", new XText(parameterValues.GetValueOrDefault(parameter.Name, ""))))); } if (!declarations.Any()) { // If the invocation does not have any parameters, include an empty placeholder in the snippet template // to ensure the caret starts inside the parentheses and can track changes to other overloads (which may // have parameters). template.Append($"${PlaceholderSnippetField}$"); declarations.Add(new XElement( snippetNamespace + "Literal", new XElement(snippetNamespace + "ID", new XText(PlaceholderSnippetField)), new XElement(snippetNamespace + "Default", new XText("")))); } if (includeMethod) { template.Append(')'); } template.Append("$end$"); // A snippet is manually constructed. Replacement fields are added for each argument, and the field name // matches the parameter name. // https://docs.microsoft.com/en-us/visualstudio/ide/code-snippets-schema-reference?view=vs-2019 return new XDocument( new XDeclaration("1.0", "utf-8", null), new XElement( snippetNamespace + "CodeSnippets", new XElement( snippetNamespace + "CodeSnippet", new XAttribute(snippetNamespace + "Format", "1.0.0"), new XElement( snippetNamespace + "Header", new XElement(snippetNamespace + "Title", new XText(methodName)), new XElement(snippetNamespace + "Description", new XText(s_fullMethodCallDescriptionSentinel))), new XElement( snippetNamespace + "Snippet", new XElement(snippetNamespace + "Declarations", declarations.ToArray()), new XElement( snippetNamespace + "Code", new XAttribute(snippetNamespace + "Language", "csharp"), new XCData(template.ToString())))))); } private void OnModelUpdated(object sender, ModelUpdatedEventsArgs e) { AssertIsForeground(); if (e.NewModel is null) { // Signature Help was dismissed, but it's possible for a user to bring it back with Ctrl+Shift+Space. // Leave the snippet session (if any) in its current state to allow it to process either a subsequent // Signature Help update or the Escape/Enter keys that close the snippet session. return; } if (!_state.IsFullMethodCallSnippet) { // Signature Help is showing an updated signature, but either there is no active snippet, or the active // snippet is not performing argument value completion, so we just ignore it. return; } if (!e.NewModel.UserSelected && _state._method is not null) { // This was an implicit signature change which was not triggered by user pressing up/down, and we are // already showing an initialized argument completion snippet session, so avoid switching sessions. return; } var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document is null) { // It's unclear if/how this state would occur, but if it does we would throw an exception trying to // use it. Just return immediately. return; } // TODO: The following blocks the UI thread without cancellation, but it only occurs when an argument value // completion session is active, which is behind an experimental feature flag. // https://github.com/dotnet/roslyn/issues/50634 var compilation = ThreadingContext.JoinableTaskFactory.Run(() => document.Project.GetRequiredCompilationAsync(CancellationToken.None)); var newSymbolKey = (e.NewModel.SelectedItem as AbstractSignatureHelpProvider.SymbolKeySignatureHelpItem)?.SymbolKey ?? default; var newSymbol = newSymbolKey.Resolve(compilation, cancellationToken: CancellationToken.None).GetAnySymbol(); if (newSymbol is not IMethodSymbol method) return; MoveToSpecificMethod(method, CancellationToken.None); } private static async Task<ImmutableArray<ISymbol>> GetReferencedSymbolsToLeftOfCaretAsync( Document document, SnapshotPoint caretPosition, CancellationToken cancellationToken) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var token = await semanticModel.SyntaxTree.GetTouchingWordAsync(caretPosition.Position, document.GetRequiredLanguageService<ISyntaxFactsService>(), cancellationToken).ConfigureAwait(false); if (token.RawKind == 0) { // There is no touching word, so return empty immediately return ImmutableArray<ISymbol>.Empty; } var semanticInfo = semanticModel.GetSemanticInfo(token, document.Project.Solution.Workspace, cancellationToken); return semanticInfo.ReferencedSymbols; } /// <summary> /// Update the current argument value completion session to use a specific method. /// </summary> /// <param name="method">The currently-selected method in Signature Help.</param> /// <param name="cancellationToken">A cancellation token the operation may observe.</param> public void MoveToSpecificMethod(IMethodSymbol method, CancellationToken cancellationToken) { AssertIsForeground(); if (ExpansionSession is null) { return; } if (SymbolEquivalenceComparer.Instance.Equals(_state._method, method)) { return; } if (_state._methodNameForInsertFullMethodCall != method.Name) { // Signature Help is showing a signature that wasn't part of the set this argument value completion // session was created from. It's unclear how this state should be handled, so we stop processing // Signature Help updates for the current session. // TODO: https://github.com/dotnet/roslyn/issues/50636 ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); return; } // If the first method overload chosen is a zero-parameter method, the snippet we'll create is the same snippet // as the one did initially. The editor appears to have a bug where inserting a zero-width snippet (when we update the parameters) // causes the inserted session to immediately dismiss; this works around that issue. if (_state._method is null && method.Parameters.Length == 0) { _state._method = method; return; } var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document is null) { // Couldn't identify the current document ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); return; } var textViewModel = TextView.TextViewModel; if (textViewModel == null) { Debug.Assert(TextView.IsClosed); return; } var buffer = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer); if (buffer is not IVsExpansion expansion) { return; } // We need to replace the portion of the existing Full Method Call snippet which appears inside parentheses. // This span starts at the beginning of the first snippet field, and ends at the end of the last snippet // field. Methods with no arguments still have an empty "placeholder" snippet field representing the initial // caret position when the snippet is created. var textSpan = new VsTextSpan[1]; if (ExpansionSession.GetSnippetSpan(textSpan) != VSConstants.S_OK) { return; } var firstField = _state._method?.Parameters.FirstOrDefault()?.Name ?? PlaceholderSnippetField; if (ExpansionSession.GetFieldSpan(firstField, textSpan) != VSConstants.S_OK) { return; } VsTextSpan adjustedTextSpan; adjustedTextSpan.iStartLine = textSpan[0].iStartLine; adjustedTextSpan.iStartIndex = textSpan[0].iStartIndex; var lastField = _state._method?.Parameters.LastOrDefault()?.Name ?? PlaceholderSnippetField; if (ExpansionSession.GetFieldSpan(lastField, textSpan) != VSConstants.S_OK) { return; } adjustedTextSpan.iEndLine = textSpan[0].iEndLine; adjustedTextSpan.iEndIndex = textSpan[0].iEndIndex; // Track current argument values so input created/updated by a user is not lost when cycling through // Signature Help overloads: // // 1. For each parameter of the method currently presented as a snippet, the value of the argument as // it appears in code. // 2. Place the argument values in a map from parameter name to current value. // 3. (Later) the values in the map can be read to avoid providing new values for equivalent parameters. var newArguments = _state._arguments; if (_state._method is null || !_state._method.Parameters.Any()) { // If we didn't have any previous parameters, then there is only the placeholder in the snippet. // We don't want to lose what the user has typed there, if they typed something if (ExpansionSession.GetFieldValue(PlaceholderSnippetField, out var placeholderValue) == VSConstants.S_OK && placeholderValue.Length > 0) { if (method.Parameters.Any()) { newArguments = newArguments.SetItem(method.Parameters[0].Name, placeholderValue); } else { // TODO: if the user is typing before signature help updated the model, and we have no parameters here, // should we still create a new snippet that has the existing placeholder text? } } } else if (_state._method is not null) { foreach (var previousParameter in _state._method.Parameters) { if (ExpansionSession.GetFieldValue(previousParameter.Name, out var previousValue) == VSConstants.S_OK) { newArguments = newArguments.SetItem(previousParameter.Name, previousValue); } } } // Now compute the new arguments for the new call var semanticModel = document.GetRequiredSemanticModelAsync(cancellationToken).AsTask().WaitAndGetResult(cancellationToken); var position = SubjectBuffer.CurrentSnapshot.GetPosition(adjustedTextSpan.iStartLine, adjustedTextSpan.iStartIndex); foreach (var parameter in method.Parameters) { newArguments.TryGetValue(parameter.Name, out var value); foreach (var provider in GetArgumentProviders(document.Project.Solution.Workspace)) { var context = new ArgumentContext(provider, semanticModel, position, parameter, value, cancellationToken); ThreadingContext.JoinableTaskFactory.Run(() => provider.ProvideArgumentAsync(context)); if (context.DefaultValue is not null) { value = context.DefaultValue; break; } } // If we still have no value, fill in the default if (value is null) { value = FallbackDefaultLiteral; } newArguments = newArguments.SetItem(parameter.Name, value); } var snippet = CreateMethodCallSnippet(method.Name, includeMethod: false, method.Parameters, newArguments); var doc = (DOMDocument)new DOMDocumentClass(); if (doc.loadXML(snippet.ToString(SaveOptions.OmitDuplicateNamespaces))) { if (expansion.InsertSpecificExpansion(doc, adjustedTextSpan, this, LanguageServiceGuid, pszRelativePath: null, out _state._expansionSession) == VSConstants.S_OK) { Debug.Assert(_state._expansionSession != null); _state._methodNameForInsertFullMethodCall = method.Name; _state._method = method; _state._arguments = newArguments; // On this path, the closing parenthesis is not part of the updated snippet, so there is no way for // the snippet itself to represent the $end$ marker (which falls after the ')' character). Instead, // we use the internal APIs to manually specify the effective position of the $end$ marker as the // location in code immediately following the ')'. To do this, we use the knowledge that the snippet // includes all text up to (but not including) the ')', and move that span one position to the // right. if (ExpansionSession.GetEndSpan(textSpan) == VSConstants.S_OK) { textSpan[0].iStartIndex++; textSpan[0].iEndIndex++; ExpansionSession.SetEndSpan(textSpan[0]); } } } } public int EndExpansion() { if (ExpansionSession == null) { _earlyEndExpansionHappened = true; } _state.Clear(); _indentCaretOnCommit = false; return VSConstants.S_OK; } public int IsValidKind(IVsTextLines pBuffer, VsTextSpan[] ts, string bstrKind, out int pfIsValidKind) { pfIsValidKind = 1; return VSConstants.S_OK; } public int IsValidType(IVsTextLines pBuffer, VsTextSpan[] ts, string[] rgTypes, int iCountTypes, out int pfIsValidType) { pfIsValidType = 1; return VSConstants.S_OK; } public int OnAfterInsertion(IVsExpansionSession pSession) { Logger.Log(FunctionId.Snippet_OnAfterInsertion); return VSConstants.S_OK; } public int OnBeforeInsertion(IVsExpansionSession pSession) { Logger.Log(FunctionId.Snippet_OnBeforeInsertion); _state._expansionSession = pSession; // Symbol information (when necessary) is set by the caller return VSConstants.S_OK; } public int OnItemChosen(string pszTitle, string pszPath) { var textViewModel = TextView.TextViewModel; if (textViewModel == null) { Debug.Assert(TextView.IsClosed); return VSConstants.E_FAIL; } int hr; try { VsTextSpan textSpan; GetCaretPositionInSurfaceBuffer(out textSpan.iStartLine, out textSpan.iStartIndex); textSpan.iEndLine = textSpan.iStartLine; textSpan.iEndIndex = textSpan.iStartIndex; var expansion = (IVsExpansion?)EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer); Contract.ThrowIfNull(expansion); _earlyEndExpansionHappened = false; hr = expansion.InsertNamedExpansion(pszTitle, pszPath, textSpan, this, LanguageServiceGuid, fShowDisambiguationUI: 0, pSession: out _state._expansionSession); if (_earlyEndExpansionHappened) { // EndExpansion was called before InsertNamedExpansion returned, so set // expansionSession to null to indicate that there is no active expansion // session. This can occur when the snippet inserted doesn't have any expansion // fields. _state._expansionSession = null; _earlyEndExpansionHappened = false; } } catch (COMException ex) { hr = ex.ErrorCode; } return hr; } private void GetCaretPositionInSurfaceBuffer(out int caretLine, out int caretColumn) { var vsTextView = EditorAdaptersFactoryService.GetViewAdapter(TextView); Contract.ThrowIfNull(vsTextView); vsTextView.GetCaretPos(out caretLine, out caretColumn); vsTextView.GetBuffer(out var textLines); // Handle virtual space (e.g, see Dev10 778675) textLines.GetLengthOfLine(caretLine, out var lineLength); if (caretColumn > lineLength) { caretColumn = lineLength; } } private void AddReferencesAndImports( IVsExpansionSession pSession, int position, CancellationToken cancellationToken) { if (!TryGetSnippetNode(pSession, out var snippetNode)) { return; } var documentWithImports = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (documentWithImports == null) { return; } var documentOptions = documentWithImports.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken); var allowInHiddenRegions = documentWithImports.CanAddImportsInHiddenRegions(); documentWithImports = AddImports(documentWithImports, documentOptions, position, snippetNode, allowInHiddenRegions, cancellationToken); AddReferences(documentWithImports.Project, snippetNode); } private void AddReferences(Project originalProject, XElement snippetNode) { var referencesNode = snippetNode.Element(XName.Get("References", snippetNode.Name.NamespaceName)); if (referencesNode == null) { return; } var existingReferenceNames = originalProject.MetadataReferences.Select(r => Path.GetFileNameWithoutExtension(r.Display)); var workspace = originalProject.Solution.Workspace; var projectId = originalProject.Id; var assemblyXmlName = XName.Get("Assembly", snippetNode.Name.NamespaceName); var failedReferenceAdditions = new List<string>(); foreach (var reference in referencesNode.Elements(XName.Get("Reference", snippetNode.Name.NamespaceName))) { // Note: URL references are not supported var assemblyElement = reference.Element(assemblyXmlName); var assemblyName = assemblyElement != null ? assemblyElement.Value.Trim() : null; if (RoslynString.IsNullOrEmpty(assemblyName)) { continue; } if (workspace is not VisualStudioWorkspaceImpl visualStudioWorkspace || !visualStudioWorkspace.TryAddReferenceToProject(projectId, assemblyName)) { failedReferenceAdditions.Add(assemblyName); } } if (failedReferenceAdditions.Any()) { var notificationService = workspace.Services.GetRequiredService<INotificationService>(); notificationService.SendNotification( string.Format(ServicesVSResources.The_following_references_were_not_found_0_Please_locate_and_add_them_manually, Environment.NewLine) + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, failedReferenceAdditions), severity: NotificationSeverity.Warning); } } protected static bool TryAddImportsToContainedDocument(Document document, IEnumerable<string> memberImportsNamespaces) { if (document.Project.Solution.Workspace is not VisualStudioWorkspaceImpl vsWorkspace) { return false; } var containedDocument = vsWorkspace.TryGetContainedDocument(document.Id); if (containedDocument == null) { return false; } if (containedDocument.ContainedLanguageHost is IVsContainedLanguageHostInternal containedLanguageHost) { foreach (var importClause in memberImportsNamespaces) { if (containedLanguageHost.InsertImportsDirective(importClause) != VSConstants.S_OK) { return false; } } } return true; } protected static bool TryGetSnippetFunctionInfo( IXMLDOMNode xmlFunctionNode, [NotNullWhen(true)] out string? snippetFunctionName, [NotNullWhen(true)] out string? param) { if (xmlFunctionNode.text.IndexOf('(') == -1 || xmlFunctionNode.text.IndexOf(')') == -1 || xmlFunctionNode.text.IndexOf(')') < xmlFunctionNode.text.IndexOf('(')) { snippetFunctionName = null; param = null; return false; } snippetFunctionName = xmlFunctionNode.text.Substring(0, xmlFunctionNode.text.IndexOf('(')); var paramStart = xmlFunctionNode.text.IndexOf('(') + 1; var paramLength = xmlFunctionNode.text.LastIndexOf(')') - xmlFunctionNode.text.IndexOf('(') - 1; param = xmlFunctionNode.text.Substring(paramStart, paramLength); return true; } internal bool TryGetSubjectBufferSpan(VsTextSpan surfaceBufferTextSpan, out SnapshotSpan subjectBufferSpan) { var snapshotSpan = TextView.TextSnapshot.GetSpan(surfaceBufferTextSpan); var subjectBufferSpanCollection = TextView.BufferGraph.MapDownToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, SubjectBuffer); // Bail if a snippet span does not map down to exactly one subject buffer span. if (subjectBufferSpanCollection.Count == 1) { subjectBufferSpan = subjectBufferSpanCollection.Single(); return true; } subjectBufferSpan = default; return false; } internal bool TryGetSpanOnHigherBuffer(SnapshotSpan snapshotSpan, ITextBuffer targetBuffer, out SnapshotSpan span) { var spanCollection = TextView.BufferGraph.MapUpToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, targetBuffer); // Bail if a snippet span does not map up to exactly one span. if (spanCollection.Count == 1) { span = spanCollection.Single(); return true; } span = default; return false; } private sealed class State { /// <summary> /// The current expansion session. /// </summary> public IVsExpansionSession? _expansionSession; /// <summary> /// The symbol name of the method that we have invoked insert full method call on; or <see langword="null"/> /// if there is no active snippet session or the active session is a regular snippets session. /// </summary> public string? _methodNameForInsertFullMethodCall; /// <summary> /// The current symbol presented in an Argument Provider snippet session. This may be null if Signature Help /// has not yet provided a symbol to show. /// </summary> public IMethodSymbol? _method; /// <summary> /// Maps from parameter name to current argument value. When this dictionary does not contain a mapping for /// a parameter, it means no argument has been provided yet by an ArgumentProvider or the user for a /// parameter with this name. This map is cleared at the final end of an argument provider snippet session. /// </summary> public ImmutableDictionary<string, string> _arguments = ImmutableDictionary.Create<string, string>(); /// <summary> /// <see langword="true"/> if the current snippet session is a Full Method Call snippet session; otherwise, /// <see langword="false"/> if there is no current snippet session or if the current snippet session is a normal snippet. /// </summary> public bool IsFullMethodCallSnippet => _expansionSession is not null && _methodNameForInsertFullMethodCall is not null; public void Clear() { _expansionSession = null; _methodNameForInsertFullMethodCall = null; _method = null; _arguments = _arguments.Clear(); } } } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForLocalFunctionsRefactoringTests.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 UseExpressionBodyForLocalFunctionsRefactoringTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseExpressionBodyCodeRefactoringProvider(); private OptionsCollection UseExpressionBody => Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement); private OptionsCollection UseExpressionBodyDisabledDiagnostic => Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenPossible, NotificationOption2.None)); private OptionsCollection UseBlockBody => Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.NeverWithSilentEnforcement); private OptionsCollection UseBlockBodyDisabledDiagnostic => Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.Never, NotificationOption2.None)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() { await TestMissingAsync( @"class C { void Goo() { void Bar() { [||]Test(); } } }", parameters: new TestParameters(options: UseExpressionBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() { await TestInRegularAndScript1Async( @"class C { void Goo() { void Bar() { [||]Test(); } } }", @"class C { void Goo() { void Bar() => Test(); } }", parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() { await TestInRegularAndScript1Async( @"class C { void Goo() { void Bar() { [||]Test(); } } }", @"class C { void Goo() { void Bar() => Test(); } }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() { await TestMissingAsync( @"class C { void Goo() { void Bar() => [||]Test(); } }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() { await TestInRegularAndScript1Async( @"class C { void Goo() { void Bar() => [||]Test(); } }", @"class C { void Goo() { void Bar() { Test(); } } }", parameters: new TestParameters(options: UseBlockBodyDisabledDiagnostic)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() { await TestInRegularAndScript1Async( @"class C { void Goo() { void Bar() => [||]Test(); } }", @"class C { void Goo() { void Bar() { Test(); } } }", 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 UseExpressionBodyForLocalFunctionsRefactoringTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseExpressionBodyCodeRefactoringProvider(); private OptionsCollection UseExpressionBody => Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement); private OptionsCollection UseExpressionBodyDisabledDiagnostic => Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenPossible, NotificationOption2.None)); private OptionsCollection UseBlockBody => Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.NeverWithSilentEnforcement); private OptionsCollection UseBlockBodyDisabledDiagnostic => Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.Never, NotificationOption2.None)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() { await TestMissingAsync( @"class C { void Goo() { void Bar() { [||]Test(); } } }", parameters: new TestParameters(options: UseExpressionBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() { await TestInRegularAndScript1Async( @"class C { void Goo() { void Bar() { [||]Test(); } } }", @"class C { void Goo() { void Bar() => Test(); } }", parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() { await TestInRegularAndScript1Async( @"class C { void Goo() { void Bar() { [||]Test(); } } }", @"class C { void Goo() { void Bar() => Test(); } }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() { await TestMissingAsync( @"class C { void Goo() { void Bar() => [||]Test(); } }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() { await TestInRegularAndScript1Async( @"class C { void Goo() { void Bar() => [||]Test(); } }", @"class C { void Goo() { void Bar() { Test(); } } }", parameters: new TestParameters(options: UseBlockBodyDisabledDiagnostic)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() { await TestInRegularAndScript1Async( @"class C { void Goo() { void Bar() => [||]Test(); } }", @"class C { void Goo() { void Bar() { Test(); } } }", parameters: new TestParameters(options: UseExpressionBody)); } } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Workspaces/Core/Portable/Workspace/Solution/ProjectState.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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Serialization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class ProjectState { private readonly ProjectInfo _projectInfo; private readonly HostLanguageServices _languageServices; private readonly SolutionServices _solutionServices; /// <summary> /// The documents in this project. They are sorted by <see cref="DocumentId.Id"/> to provide a stable sort for /// <see cref="GetChecksumAsync(CancellationToken)"/>. /// </summary> public readonly TextDocumentStates<DocumentState> DocumentStates; /// <summary> /// The additional documents in this project. They are sorted by <see cref="DocumentId.Id"/> to provide a stable sort for /// <see cref="GetChecksumAsync(CancellationToken)"/>. /// </summary> public readonly TextDocumentStates<AdditionalDocumentState> AdditionalDocumentStates; /// <summary> /// The analyzer config documents in this project. They are sorted by <see cref="DocumentId.Id"/> to provide a stable sort for /// <see cref="GetChecksumAsync(CancellationToken)"/>. /// </summary> public readonly TextDocumentStates<AnalyzerConfigDocumentState> AnalyzerConfigDocumentStates; private readonly AsyncLazy<VersionStamp> _lazyLatestDocumentVersion; private readonly AsyncLazy<VersionStamp> _lazyLatestDocumentTopLevelChangeVersion; // Checksums for this solution state private readonly ValueSource<ProjectStateChecksums> _lazyChecksums; /// <summary> /// The <see cref="AnalyzerConfigSet"/> to be used for analyzer options for specific trees. /// </summary> private readonly ValueSource<CachingAnalyzerConfigSet> _lazyAnalyzerConfigSet; private AnalyzerOptions? _lazyAnalyzerOptions; /// <summary> /// Backing field for <see cref="SourceGenerators"/>; this is a default ImmutableArray if it hasn't been computed yet. /// </summary> private ImmutableArray<ISourceGenerator> _lazySourceGenerators; private ProjectState( ProjectInfo projectInfo, HostLanguageServices languageServices, SolutionServices solutionServices, TextDocumentStates<DocumentState> documentStates, TextDocumentStates<AdditionalDocumentState> additionalDocumentStates, TextDocumentStates<AnalyzerConfigDocumentState> analyzerConfigDocumentStates, AsyncLazy<VersionStamp> lazyLatestDocumentVersion, AsyncLazy<VersionStamp> lazyLatestDocumentTopLevelChangeVersion, ValueSource<CachingAnalyzerConfigSet> lazyAnalyzerConfigSet) { _solutionServices = solutionServices; _languageServices = languageServices; DocumentStates = documentStates; AdditionalDocumentStates = additionalDocumentStates; AnalyzerConfigDocumentStates = analyzerConfigDocumentStates; _lazyLatestDocumentVersion = lazyLatestDocumentVersion; _lazyLatestDocumentTopLevelChangeVersion = lazyLatestDocumentTopLevelChangeVersion; _lazyAnalyzerConfigSet = lazyAnalyzerConfigSet; // ownership of information on document has moved to project state. clear out documentInfo the state is // holding on. otherwise, these information will be held onto unnecessarily by projectInfo even after // the info has changed by DocumentState. _projectInfo = ClearAllDocumentsFromProjectInfo(projectInfo); _lazyChecksums = new AsyncLazy<ProjectStateChecksums>(ComputeChecksumsAsync, cacheResult: true); } public ProjectState(ProjectInfo projectInfo, HostLanguageServices languageServices, SolutionServices solutionServices) { Contract.ThrowIfNull(projectInfo); Contract.ThrowIfNull(languageServices); Contract.ThrowIfNull(solutionServices); _languageServices = languageServices; _solutionServices = solutionServices; var projectInfoFixed = FixProjectInfo(projectInfo); // We need to compute our AnalyerConfigDocumentStates first, since we use those to produce our DocumentStates AnalyzerConfigDocumentStates = new TextDocumentStates<AnalyzerConfigDocumentState>(projectInfoFixed.AnalyzerConfigDocuments, info => new AnalyzerConfigDocumentState(info, solutionServices)); _lazyAnalyzerConfigSet = ComputeAnalyzerConfigSetValueSource(AnalyzerConfigDocumentStates); // Add analyzer config information to the compilation options if (projectInfoFixed.CompilationOptions != null) { projectInfoFixed = projectInfoFixed.WithCompilationOptions( projectInfoFixed.CompilationOptions.WithSyntaxTreeOptionsProvider( new WorkspaceSyntaxTreeOptionsProvider(_lazyAnalyzerConfigSet))); } var parseOptions = projectInfoFixed.ParseOptions; DocumentStates = new TextDocumentStates<DocumentState>(projectInfoFixed.Documents, info => CreateDocument(info, parseOptions)); AdditionalDocumentStates = new TextDocumentStates<AdditionalDocumentState>(projectInfoFixed.AdditionalDocuments, info => new AdditionalDocumentState(info, solutionServices)); _lazyLatestDocumentVersion = new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentVersionAsync(DocumentStates, AdditionalDocumentStates, c), cacheResult: true); _lazyLatestDocumentTopLevelChangeVersion = new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentTopLevelChangeVersionAsync(DocumentStates, AdditionalDocumentStates, c), cacheResult: true); // ownership of information on document has moved to project state. clear out documentInfo the state is // holding on. otherwise, these information will be held onto unnecessarily by projectInfo even after // the info has changed by DocumentState. // we hold onto the info so that we don't need to duplicate all information info already has in the state _projectInfo = ClearAllDocumentsFromProjectInfo(projectInfoFixed); _lazyChecksums = new AsyncLazy<ProjectStateChecksums>(ComputeChecksumsAsync, cacheResult: true); } private static ProjectInfo ClearAllDocumentsFromProjectInfo(ProjectInfo projectInfo) { return projectInfo .WithDocuments(ImmutableArray<DocumentInfo>.Empty) .WithAdditionalDocuments(ImmutableArray<DocumentInfo>.Empty) .WithAnalyzerConfigDocuments(ImmutableArray<DocumentInfo>.Empty); } private ProjectInfo FixProjectInfo(ProjectInfo projectInfo) { if (projectInfo.CompilationOptions == null) { var compilationFactory = _languageServices.GetService<ICompilationFactoryService>(); if (compilationFactory != null) { projectInfo = projectInfo.WithCompilationOptions(compilationFactory.GetDefaultCompilationOptions()); } } if (projectInfo.ParseOptions == null) { var syntaxTreeFactory = _languageServices.GetService<ISyntaxTreeFactoryService>(); if (syntaxTreeFactory != null) { projectInfo = projectInfo.WithParseOptions(syntaxTreeFactory.GetDefaultParseOptions()); } } return projectInfo; } private static async Task<VersionStamp> ComputeLatestDocumentVersionAsync(TextDocumentStates<DocumentState> documentStates, TextDocumentStates<AdditionalDocumentState> additionalDocumentStates, CancellationToken cancellationToken) { // this may produce a version that is out of sync with the actual Document versions. var latestVersion = VersionStamp.Default; foreach (var (_, state) in documentStates.States) { cancellationToken.ThrowIfCancellationRequested(); if (!state.IsGenerated) { var version = await state.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); latestVersion = version.GetNewerVersion(latestVersion); } } foreach (var (_, state) in additionalDocumentStates.States) { cancellationToken.ThrowIfCancellationRequested(); var version = await state.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); latestVersion = version.GetNewerVersion(latestVersion); } return latestVersion; } private AsyncLazy<VersionStamp> CreateLazyLatestDocumentTopLevelChangeVersion( TextDocumentState newDocument, TextDocumentStates<DocumentState> newDocumentStates, TextDocumentStates<AdditionalDocumentState> newAdditionalDocumentStates) { if (_lazyLatestDocumentTopLevelChangeVersion.TryGetValue(out var oldVersion)) { return new AsyncLazy<VersionStamp>(c => ComputeTopLevelChangeTextVersionAsync(oldVersion, newDocument, c), cacheResult: true); } else { return new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentTopLevelChangeVersionAsync(newDocumentStates, newAdditionalDocumentStates, c), cacheResult: true); } } private static async Task<VersionStamp> ComputeTopLevelChangeTextVersionAsync(VersionStamp oldVersion, TextDocumentState newDocument, CancellationToken cancellationToken) { var newVersion = await newDocument.GetTopLevelChangeTextVersionAsync(cancellationToken).ConfigureAwait(false); return newVersion.GetNewerVersion(oldVersion); } private static async Task<VersionStamp> ComputeLatestDocumentTopLevelChangeVersionAsync(TextDocumentStates<DocumentState> documentStates, TextDocumentStates<AdditionalDocumentState> additionalDocumentStates, CancellationToken cancellationToken) { // this may produce a version that is out of sync with the actual Document versions. var latestVersion = VersionStamp.Default; foreach (var (_, state) in documentStates.States) { cancellationToken.ThrowIfCancellationRequested(); var version = await state.GetTopLevelChangeTextVersionAsync(cancellationToken).ConfigureAwait(false); latestVersion = version.GetNewerVersion(latestVersion); } foreach (var (_, state) in additionalDocumentStates.States) { cancellationToken.ThrowIfCancellationRequested(); var version = await state.GetTopLevelChangeTextVersionAsync(cancellationToken).ConfigureAwait(false); latestVersion = version.GetNewerVersion(latestVersion); } return latestVersion; } internal DocumentState CreateDocument(DocumentInfo documentInfo, ParseOptions? parseOptions) { var doc = new DocumentState(documentInfo, parseOptions, _languageServices, _solutionServices); if (doc.SourceCodeKind != documentInfo.SourceCodeKind) { doc = doc.UpdateSourceCodeKind(documentInfo.SourceCodeKind); } return doc; } public AnalyzerOptions AnalyzerOptions => _lazyAnalyzerOptions ??= new AnalyzerOptions( additionalFiles: AdditionalDocumentStates.SelectAsArray(static documentState => documentState.AdditionalText), optionsProvider: new WorkspaceAnalyzerConfigOptionsProvider(this)); public async Task<ImmutableDictionary<string, string>> GetAnalyzerOptionsForPathAsync( string path, CancellationToken cancellationToken) { var configSet = await _lazyAnalyzerConfigSet.GetValueAsync(cancellationToken).ConfigureAwait(false); return configSet.GetOptionsForSourcePath(path).AnalyzerOptions; } public AnalyzerConfigOptionsResult? GetAnalyzerConfigOptions() { // We need to find the analyzer config options at the root of the project. // Currently, there is no compiler API to query analyzer config options for a directory in a language agnostic fashion. // So, we use a dummy language-specific file name appended to the project directory to query analyzer config options. var projectDirectory = PathUtilities.GetDirectoryName(_projectInfo.FilePath); if (!PathUtilities.IsAbsolute(projectDirectory)) { return null; } var fileName = Guid.NewGuid().ToString(); string sourceFilePath; switch (_projectInfo.Language) { case LanguageNames.CSharp: // Suppression should be removed or addressed https://github.com/dotnet/roslyn/issues/41636 sourceFilePath = PathUtilities.CombineAbsoluteAndRelativePaths(projectDirectory, $"{fileName}.cs")!; break; case LanguageNames.VisualBasic: // Suppression should be removed or addressed https://github.com/dotnet/roslyn/issues/41636 sourceFilePath = PathUtilities.CombineAbsoluteAndRelativePaths(projectDirectory, $"{fileName}.vb")!; break; default: return null; } return _lazyAnalyzerConfigSet.GetValue(CancellationToken.None).GetOptionsForSourcePath(sourceFilePath); } internal sealed class WorkspaceAnalyzerConfigOptionsProvider : AnalyzerConfigOptionsProvider { private readonly ProjectState _projectState; public WorkspaceAnalyzerConfigOptionsProvider(ProjectState projectState) => _projectState = projectState; public override AnalyzerConfigOptions GlobalOptions => new WorkspaceAnalyzerConfigOptions(_projectState._lazyAnalyzerConfigSet.GetValue(CancellationToken.None).GetOptionsForSourcePath(string.Empty)); public override AnalyzerConfigOptions GetOptions(SyntaxTree tree) => new WorkspaceAnalyzerConfigOptions(_projectState._lazyAnalyzerConfigSet.GetValue(CancellationToken.None).GetOptionsForSourcePath(tree.FilePath)); public override AnalyzerConfigOptions GetOptions(AdditionalText textFile) { // TODO: correctly find the file path, since it looks like we give this the document's .Name under the covers if we don't have one return new WorkspaceAnalyzerConfigOptions(_projectState._lazyAnalyzerConfigSet.GetValue(CancellationToken.None).GetOptionsForSourcePath(textFile.Path)); } public AnalyzerConfigOptions GetOptionsForSourcePath(string path) => new WorkspaceAnalyzerConfigOptions(_projectState._lazyAnalyzerConfigSet.GetValue(CancellationToken.None).GetOptionsForSourcePath(path)); private sealed class WorkspaceAnalyzerConfigOptions : AnalyzerConfigOptions { private readonly ImmutableDictionary<string, string> _backing; public WorkspaceAnalyzerConfigOptions(AnalyzerConfigOptionsResult analyzerConfigOptions) => _backing = analyzerConfigOptions.AnalyzerOptions; public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value) => _backing.TryGetValue(key, out value); } } private sealed class WorkspaceSyntaxTreeOptionsProvider : SyntaxTreeOptionsProvider { private readonly ValueSource<CachingAnalyzerConfigSet> _lazyAnalyzerConfigSet; public WorkspaceSyntaxTreeOptionsProvider(ValueSource<CachingAnalyzerConfigSet> lazyAnalyzerConfigSet) => _lazyAnalyzerConfigSet = lazyAnalyzerConfigSet; public override GeneratedKind IsGenerated(SyntaxTree tree, CancellationToken cancellationToken) { var options = _lazyAnalyzerConfigSet .GetValue(cancellationToken).GetOptionsForSourcePath(tree.FilePath); return GeneratedCodeUtilities.GetIsGeneratedCodeFromOptions(options.AnalyzerOptions); } public override bool TryGetDiagnosticValue(SyntaxTree tree, string diagnosticId, CancellationToken cancellationToken, out ReportDiagnostic severity) { var options = _lazyAnalyzerConfigSet .GetValue(cancellationToken).GetOptionsForSourcePath(tree.FilePath); return options.TreeOptions.TryGetValue(diagnosticId, out severity); } public override bool TryGetGlobalDiagnosticValue(string diagnosticId, CancellationToken cancellationToken, out ReportDiagnostic severity) { var options = _lazyAnalyzerConfigSet .GetValue(cancellationToken).GlobalConfigOptions; return options.TreeOptions.TryGetValue(diagnosticId, out severity); } public override bool Equals(object? obj) { return obj is WorkspaceSyntaxTreeOptionsProvider other && _lazyAnalyzerConfigSet == other._lazyAnalyzerConfigSet; } public override int GetHashCode() => _lazyAnalyzerConfigSet.GetHashCode(); } private static ValueSource<CachingAnalyzerConfigSet> ComputeAnalyzerConfigSetValueSource(TextDocumentStates<AnalyzerConfigDocumentState> analyzerConfigDocumentStates) { return new AsyncLazy<CachingAnalyzerConfigSet>( asynchronousComputeFunction: async cancellationToken => { var tasks = analyzerConfigDocumentStates.States.Values.Select(a => a.GetAnalyzerConfigAsync(cancellationToken)); var analyzerConfigs = await Task.WhenAll(tasks).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); return new CachingAnalyzerConfigSet(AnalyzerConfigSet.Create(analyzerConfigs)); }, synchronousComputeFunction: cancellationToken => { var analyzerConfigs = analyzerConfigDocumentStates.SelectAsArray(a => a.GetAnalyzerConfig(cancellationToken)); return new CachingAnalyzerConfigSet(AnalyzerConfigSet.Create(analyzerConfigs)); }, cacheResult: true); } public Task<VersionStamp> GetLatestDocumentVersionAsync(CancellationToken cancellationToken) => _lazyLatestDocumentVersion.GetValueAsync(cancellationToken); public async Task<VersionStamp> GetSemanticVersionAsync(CancellationToken cancellationToken = default) { var docVersion = await _lazyLatestDocumentTopLevelChangeVersion.GetValueAsync(cancellationToken).ConfigureAwait(false); return docVersion.GetNewerVersion(this.Version); } [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public ProjectId Id => this.ProjectInfo.Id; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public string? FilePath => this.ProjectInfo.FilePath; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public string? OutputFilePath => this.ProjectInfo.OutputFilePath; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public string? OutputRefFilePath => this.ProjectInfo.OutputRefFilePath; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public CompilationOutputInfo CompilationOutputInfo => this.ProjectInfo.CompilationOutputInfo; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public string? DefaultNamespace => this.ProjectInfo.DefaultNamespace; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public HostLanguageServices LanguageServices => _languageServices; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public string Language => LanguageServices.Language; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public string Name => this.ProjectInfo.Name; /// <inheritdoc cref="ProjectInfo.NameAndFlavor"/> [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public (string? name, string? flavor) NameAndFlavor => this.ProjectInfo.NameAndFlavor; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public bool IsSubmission => this.ProjectInfo.IsSubmission; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public Type? HostObjectType => this.ProjectInfo.HostObjectType; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public bool SupportsCompilation => this.LanguageServices.GetService<ICompilationFactoryService>() != null; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public VersionStamp Version => this.ProjectInfo.Version; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public ProjectInfo ProjectInfo => _projectInfo; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public string AssemblyName => this.ProjectInfo.AssemblyName; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public CompilationOptions? CompilationOptions => this.ProjectInfo.CompilationOptions; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public ParseOptions? ParseOptions => this.ProjectInfo.ParseOptions; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public IReadOnlyList<MetadataReference> MetadataReferences => this.ProjectInfo.MetadataReferences; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public IReadOnlyList<AnalyzerReference> AnalyzerReferences => this.ProjectInfo.AnalyzerReferences; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public IReadOnlyList<ProjectReference> ProjectReferences => this.ProjectInfo.ProjectReferences; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public bool HasAllInformation => this.ProjectInfo.HasAllInformation; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public bool RunAnalyzers => this.ProjectInfo.RunAnalyzers; private ProjectState With( ProjectInfo? projectInfo = null, TextDocumentStates<DocumentState>? documentStates = null, TextDocumentStates<AdditionalDocumentState>? additionalDocumentStates = null, TextDocumentStates<AnalyzerConfigDocumentState>? analyzerConfigDocumentStates = null, AsyncLazy<VersionStamp>? latestDocumentVersion = null, AsyncLazy<VersionStamp>? latestDocumentTopLevelChangeVersion = null, ValueSource<CachingAnalyzerConfigSet>? analyzerConfigSet = null) { return new ProjectState( projectInfo ?? _projectInfo, _languageServices, _solutionServices, documentStates ?? DocumentStates, additionalDocumentStates ?? AdditionalDocumentStates, analyzerConfigDocumentStates ?? AnalyzerConfigDocumentStates, latestDocumentVersion ?? _lazyLatestDocumentVersion, latestDocumentTopLevelChangeVersion ?? _lazyLatestDocumentTopLevelChangeVersion, analyzerConfigSet ?? _lazyAnalyzerConfigSet); } private ProjectInfo.ProjectAttributes Attributes => ProjectInfo.Attributes; private ProjectState WithAttributes(ProjectInfo.ProjectAttributes attributes) => With(projectInfo: ProjectInfo.With(attributes: attributes)); public ProjectState WithName(string name) => (name == Name) ? this : WithAttributes(Attributes.With(name: name, version: Version.GetNewerVersion())); public ProjectState WithFilePath(string? filePath) => (filePath == FilePath) ? this : WithAttributes(Attributes.With(filePath: filePath, version: Version.GetNewerVersion())); public ProjectState WithAssemblyName(string assemblyName) => (assemblyName == AssemblyName) ? this : WithAttributes(Attributes.With(assemblyName: assemblyName, version: Version.GetNewerVersion())); public ProjectState WithOutputFilePath(string? outputFilePath) => (outputFilePath == OutputFilePath) ? this : WithAttributes(Attributes.With(outputPath: outputFilePath, version: Version.GetNewerVersion())); public ProjectState WithOutputRefFilePath(string? outputRefFilePath) => (outputRefFilePath == OutputRefFilePath) ? this : WithAttributes(Attributes.With(outputRefPath: outputRefFilePath, version: Version.GetNewerVersion())); public ProjectState WithCompilationOutputInfo(in CompilationOutputInfo info) => (info == CompilationOutputInfo) ? this : WithAttributes(Attributes.With(compilationOutputInfo: info, version: Version.GetNewerVersion())); public ProjectState WithDefaultNamespace(string? defaultNamespace) => (defaultNamespace == DefaultNamespace) ? this : WithAttributes(Attributes.With(defaultNamespace: defaultNamespace, version: Version.GetNewerVersion())); public ProjectState WithHasAllInformation(bool hasAllInformation) => (hasAllInformation == HasAllInformation) ? this : WithAttributes(Attributes.With(hasAllInformation: hasAllInformation, version: Version.GetNewerVersion())); public ProjectState WithRunAnalyzers(bool runAnalyzers) => (runAnalyzers == RunAnalyzers) ? this : WithAttributes(Attributes.With(runAnalyzers: runAnalyzers, version: Version.GetNewerVersion())); public ProjectState WithCompilationOptions(CompilationOptions options) { if (options == CompilationOptions) { return this; } var newProvider = new WorkspaceSyntaxTreeOptionsProvider(_lazyAnalyzerConfigSet); return With(projectInfo: ProjectInfo.WithCompilationOptions(options.WithSyntaxTreeOptionsProvider(newProvider)) .WithVersion(Version.GetNewerVersion())); } public ProjectState WithParseOptions(ParseOptions options) { if (options == ParseOptions) { return this; } return With( projectInfo: ProjectInfo.WithParseOptions(options).WithVersion(Version.GetNewerVersion()), documentStates: DocumentStates.UpdateStates(static (state, options) => state.UpdateParseOptions(options), options)); } public static bool IsSameLanguage(ProjectState project1, ProjectState project2) => project1.LanguageServices == project2.LanguageServices; /// <summary> /// Determines whether <see cref="ProjectReferences"/> contains a reference to a specified project. /// </summary> /// <param name="projectId">The target project of the reference.</param> /// <returns><see langword="true"/> if this project references <paramref name="projectId"/>; otherwise, <see langword="false"/>.</returns> public bool ContainsReferenceToProject(ProjectId projectId) { foreach (var projectReference in ProjectReferences) { if (projectReference.ProjectId == projectId) return true; } return false; } public ProjectState WithProjectReferences(IReadOnlyList<ProjectReference> projectReferences) { if (projectReferences == ProjectReferences) { return this; } return With(projectInfo: ProjectInfo.With(projectReferences: projectReferences).WithVersion(Version.GetNewerVersion())); } public ProjectState WithMetadataReferences(IReadOnlyList<MetadataReference> metadataReferences) { if (metadataReferences == MetadataReferences) { return this; } return With(projectInfo: ProjectInfo.With(metadataReferences: metadataReferences).WithVersion(Version.GetNewerVersion())); } public ProjectState WithAnalyzerReferences(IEnumerable<AnalyzerReference> analyzerReferences) { if (analyzerReferences == AnalyzerReferences) { return this; } return With(projectInfo: ProjectInfo.WithAnalyzerReferences(analyzerReferences).WithVersion(Version.GetNewerVersion())); } public ImmutableArray<ISourceGenerator> SourceGenerators { get { if (_lazySourceGenerators.IsDefault) { var generators = AnalyzerReferences.SelectMany(a => a.GetGenerators(this.Language)).ToImmutableArray(); ImmutableInterlocked.InterlockedInitialize(ref _lazySourceGenerators, generators); } return _lazySourceGenerators; } } public ProjectState AddDocuments(ImmutableArray<DocumentState> documents) { Debug.Assert(!documents.Any(d => DocumentStates.Contains(d.Id))); return With( projectInfo: ProjectInfo.WithVersion(Version.GetNewerVersion()), documentStates: DocumentStates.AddRange(documents)); } public ProjectState AddAdditionalDocuments(ImmutableArray<AdditionalDocumentState> documents) { Debug.Assert(!documents.Any(d => AdditionalDocumentStates.Contains(d.Id))); return With( projectInfo: ProjectInfo.WithVersion(Version.GetNewerVersion()), additionalDocumentStates: AdditionalDocumentStates.AddRange(documents)); } public ProjectState AddAnalyzerConfigDocuments(ImmutableArray<AnalyzerConfigDocumentState> documents) { Debug.Assert(!documents.Any(d => AnalyzerConfigDocumentStates.Contains(d.Id))); var newAnalyzerConfigDocumentStates = AnalyzerConfigDocumentStates.AddRange(documents); return CreateNewStateForChangedAnalyzerConfigDocuments(newAnalyzerConfigDocumentStates); } private ProjectState CreateNewStateForChangedAnalyzerConfigDocuments(TextDocumentStates<AnalyzerConfigDocumentState> newAnalyzerConfigDocumentStates) { var newAnalyzerConfigSet = ComputeAnalyzerConfigSetValueSource(newAnalyzerConfigDocumentStates); var projectInfo = ProjectInfo.WithVersion(Version.GetNewerVersion()); // Changing analyzer configs changes compilation options if (CompilationOptions != null) { var newProvider = new WorkspaceSyntaxTreeOptionsProvider(newAnalyzerConfigSet); projectInfo = projectInfo .WithCompilationOptions(CompilationOptions.WithSyntaxTreeOptionsProvider(newProvider)); } return With( projectInfo: projectInfo, analyzerConfigDocumentStates: newAnalyzerConfigDocumentStates, analyzerConfigSet: newAnalyzerConfigSet); } public ProjectState RemoveDocuments(ImmutableArray<DocumentId> documentIds) { // We create a new CachingAnalyzerConfigSet for the new snapshot to avoid holding onto cached information // for removed documents. return With( projectInfo: ProjectInfo.WithVersion(Version.GetNewerVersion()), documentStates: DocumentStates.RemoveRange(documentIds), analyzerConfigSet: ComputeAnalyzerConfigSetValueSource(AnalyzerConfigDocumentStates)); } public ProjectState RemoveAdditionalDocuments(ImmutableArray<DocumentId> documentIds) { return With( projectInfo: ProjectInfo.WithVersion(Version.GetNewerVersion()), additionalDocumentStates: AdditionalDocumentStates.RemoveRange(documentIds)); } public ProjectState RemoveAnalyzerConfigDocuments(ImmutableArray<DocumentId> documentIds) { var newAnalyzerConfigDocumentStates = AnalyzerConfigDocumentStates.RemoveRange(documentIds); return CreateNewStateForChangedAnalyzerConfigDocuments(newAnalyzerConfigDocumentStates); } public ProjectState RemoveAllDocuments() { // We create a new CachingAnalyzerConfigSet for the new snapshot to avoid holding onto cached information // for removed documents. return With( projectInfo: ProjectInfo.WithVersion(Version.GetNewerVersion()), documentStates: TextDocumentStates<DocumentState>.Empty, analyzerConfigSet: ComputeAnalyzerConfigSetValueSource(AnalyzerConfigDocumentStates)); } public ProjectState UpdateDocument(DocumentState newDocument, bool textChanged, bool recalculateDependentVersions) { var oldDocument = DocumentStates.GetRequiredState(newDocument.Id); if (oldDocument == newDocument) { return this; } var newDocumentStates = DocumentStates.SetState(newDocument.Id, newDocument); GetLatestDependentVersions( newDocumentStates, AdditionalDocumentStates, oldDocument, newDocument, recalculateDependentVersions, textChanged, out var dependentDocumentVersion, out var dependentSemanticVersion); return With( documentStates: newDocumentStates, latestDocumentVersion: dependentDocumentVersion, latestDocumentTopLevelChangeVersion: dependentSemanticVersion); } public ProjectState UpdateAdditionalDocument(AdditionalDocumentState newDocument, bool textChanged, bool recalculateDependentVersions) { var oldDocument = AdditionalDocumentStates.GetRequiredState(newDocument.Id); if (oldDocument == newDocument) { return this; } var newDocumentStates = AdditionalDocumentStates.SetState(newDocument.Id, newDocument); GetLatestDependentVersions( DocumentStates, newDocumentStates, oldDocument, newDocument, recalculateDependentVersions, textChanged, out var dependentDocumentVersion, out var dependentSemanticVersion); return this.With( additionalDocumentStates: newDocumentStates, latestDocumentVersion: dependentDocumentVersion, latestDocumentTopLevelChangeVersion: dependentSemanticVersion); } public ProjectState UpdateAnalyzerConfigDocument(AnalyzerConfigDocumentState newDocument) { var oldDocument = AnalyzerConfigDocumentStates.GetRequiredState(newDocument.Id); if (oldDocument == newDocument) { return this; } var newDocumentStates = AnalyzerConfigDocumentStates.SetState(newDocument.Id, newDocument); return CreateNewStateForChangedAnalyzerConfigDocuments(newDocumentStates); } public ProjectState UpdateDocumentsOrder(ImmutableList<DocumentId> documentIds) { if (documentIds.SequenceEqual(DocumentStates.Ids)) { return this; } return With( projectInfo: ProjectInfo.WithVersion(Version.GetNewerVersion()), documentStates: DocumentStates.WithCompilationOrder(documentIds)); } private void GetLatestDependentVersions( TextDocumentStates<DocumentState> newDocumentStates, TextDocumentStates<AdditionalDocumentState> newAdditionalDocumentStates, TextDocumentState oldDocument, TextDocumentState newDocument, bool recalculateDependentVersions, bool textChanged, out AsyncLazy<VersionStamp> dependentDocumentVersion, out AsyncLazy<VersionStamp> dependentSemanticVersion) { var recalculateDocumentVersion = false; var recalculateSemanticVersion = false; if (recalculateDependentVersions) { if (oldDocument.TryGetTextVersion(out var oldVersion)) { if (!_lazyLatestDocumentVersion.TryGetValue(out var documentVersion) || documentVersion == oldVersion) { recalculateDocumentVersion = true; } if (!_lazyLatestDocumentTopLevelChangeVersion.TryGetValue(out var semanticVersion) || semanticVersion == oldVersion) { recalculateSemanticVersion = true; } } } dependentDocumentVersion = recalculateDocumentVersion ? new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentVersionAsync(newDocumentStates, newAdditionalDocumentStates, c), cacheResult: true) : textChanged ? new AsyncLazy<VersionStamp>(newDocument.GetTextVersionAsync, cacheResult: true) : _lazyLatestDocumentVersion; dependentSemanticVersion = recalculateSemanticVersion ? new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentTopLevelChangeVersionAsync(newDocumentStates, newAdditionalDocumentStates, c), cacheResult: true) : textChanged ? CreateLazyLatestDocumentTopLevelChangeVersion(newDocument, newDocumentStates, newAdditionalDocumentStates) : _lazyLatestDocumentTopLevelChangeVersion; } } }
// Licensed to the .NET Foundation under one or more 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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Serialization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class ProjectState { private readonly ProjectInfo _projectInfo; private readonly HostLanguageServices _languageServices; private readonly SolutionServices _solutionServices; /// <summary> /// The documents in this project. They are sorted by <see cref="DocumentId.Id"/> to provide a stable sort for /// <see cref="GetChecksumAsync(CancellationToken)"/>. /// </summary> public readonly TextDocumentStates<DocumentState> DocumentStates; /// <summary> /// The additional documents in this project. They are sorted by <see cref="DocumentId.Id"/> to provide a stable sort for /// <see cref="GetChecksumAsync(CancellationToken)"/>. /// </summary> public readonly TextDocumentStates<AdditionalDocumentState> AdditionalDocumentStates; /// <summary> /// The analyzer config documents in this project. They are sorted by <see cref="DocumentId.Id"/> to provide a stable sort for /// <see cref="GetChecksumAsync(CancellationToken)"/>. /// </summary> public readonly TextDocumentStates<AnalyzerConfigDocumentState> AnalyzerConfigDocumentStates; private readonly AsyncLazy<VersionStamp> _lazyLatestDocumentVersion; private readonly AsyncLazy<VersionStamp> _lazyLatestDocumentTopLevelChangeVersion; // Checksums for this solution state private readonly ValueSource<ProjectStateChecksums> _lazyChecksums; /// <summary> /// The <see cref="AnalyzerConfigSet"/> to be used for analyzer options for specific trees. /// </summary> private readonly ValueSource<CachingAnalyzerConfigSet> _lazyAnalyzerConfigSet; private AnalyzerOptions? _lazyAnalyzerOptions; /// <summary> /// Backing field for <see cref="SourceGenerators"/>; this is a default ImmutableArray if it hasn't been computed yet. /// </summary> private ImmutableArray<ISourceGenerator> _lazySourceGenerators; private ProjectState( ProjectInfo projectInfo, HostLanguageServices languageServices, SolutionServices solutionServices, TextDocumentStates<DocumentState> documentStates, TextDocumentStates<AdditionalDocumentState> additionalDocumentStates, TextDocumentStates<AnalyzerConfigDocumentState> analyzerConfigDocumentStates, AsyncLazy<VersionStamp> lazyLatestDocumentVersion, AsyncLazy<VersionStamp> lazyLatestDocumentTopLevelChangeVersion, ValueSource<CachingAnalyzerConfigSet> lazyAnalyzerConfigSet) { _solutionServices = solutionServices; _languageServices = languageServices; DocumentStates = documentStates; AdditionalDocumentStates = additionalDocumentStates; AnalyzerConfigDocumentStates = analyzerConfigDocumentStates; _lazyLatestDocumentVersion = lazyLatestDocumentVersion; _lazyLatestDocumentTopLevelChangeVersion = lazyLatestDocumentTopLevelChangeVersion; _lazyAnalyzerConfigSet = lazyAnalyzerConfigSet; // ownership of information on document has moved to project state. clear out documentInfo the state is // holding on. otherwise, these information will be held onto unnecessarily by projectInfo even after // the info has changed by DocumentState. _projectInfo = ClearAllDocumentsFromProjectInfo(projectInfo); _lazyChecksums = new AsyncLazy<ProjectStateChecksums>(ComputeChecksumsAsync, cacheResult: true); } public ProjectState(ProjectInfo projectInfo, HostLanguageServices languageServices, SolutionServices solutionServices) { Contract.ThrowIfNull(projectInfo); Contract.ThrowIfNull(languageServices); Contract.ThrowIfNull(solutionServices); _languageServices = languageServices; _solutionServices = solutionServices; var projectInfoFixed = FixProjectInfo(projectInfo); // We need to compute our AnalyerConfigDocumentStates first, since we use those to produce our DocumentStates AnalyzerConfigDocumentStates = new TextDocumentStates<AnalyzerConfigDocumentState>(projectInfoFixed.AnalyzerConfigDocuments, info => new AnalyzerConfigDocumentState(info, solutionServices)); _lazyAnalyzerConfigSet = ComputeAnalyzerConfigSetValueSource(AnalyzerConfigDocumentStates); // Add analyzer config information to the compilation options if (projectInfoFixed.CompilationOptions != null) { projectInfoFixed = projectInfoFixed.WithCompilationOptions( projectInfoFixed.CompilationOptions.WithSyntaxTreeOptionsProvider( new WorkspaceSyntaxTreeOptionsProvider(_lazyAnalyzerConfigSet))); } var parseOptions = projectInfoFixed.ParseOptions; DocumentStates = new TextDocumentStates<DocumentState>(projectInfoFixed.Documents, info => CreateDocument(info, parseOptions)); AdditionalDocumentStates = new TextDocumentStates<AdditionalDocumentState>(projectInfoFixed.AdditionalDocuments, info => new AdditionalDocumentState(info, solutionServices)); _lazyLatestDocumentVersion = new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentVersionAsync(DocumentStates, AdditionalDocumentStates, c), cacheResult: true); _lazyLatestDocumentTopLevelChangeVersion = new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentTopLevelChangeVersionAsync(DocumentStates, AdditionalDocumentStates, c), cacheResult: true); // ownership of information on document has moved to project state. clear out documentInfo the state is // holding on. otherwise, these information will be held onto unnecessarily by projectInfo even after // the info has changed by DocumentState. // we hold onto the info so that we don't need to duplicate all information info already has in the state _projectInfo = ClearAllDocumentsFromProjectInfo(projectInfoFixed); _lazyChecksums = new AsyncLazy<ProjectStateChecksums>(ComputeChecksumsAsync, cacheResult: true); } private static ProjectInfo ClearAllDocumentsFromProjectInfo(ProjectInfo projectInfo) { return projectInfo .WithDocuments(ImmutableArray<DocumentInfo>.Empty) .WithAdditionalDocuments(ImmutableArray<DocumentInfo>.Empty) .WithAnalyzerConfigDocuments(ImmutableArray<DocumentInfo>.Empty); } private ProjectInfo FixProjectInfo(ProjectInfo projectInfo) { if (projectInfo.CompilationOptions == null) { var compilationFactory = _languageServices.GetService<ICompilationFactoryService>(); if (compilationFactory != null) { projectInfo = projectInfo.WithCompilationOptions(compilationFactory.GetDefaultCompilationOptions()); } } if (projectInfo.ParseOptions == null) { var syntaxTreeFactory = _languageServices.GetService<ISyntaxTreeFactoryService>(); if (syntaxTreeFactory != null) { projectInfo = projectInfo.WithParseOptions(syntaxTreeFactory.GetDefaultParseOptions()); } } return projectInfo; } private static async Task<VersionStamp> ComputeLatestDocumentVersionAsync(TextDocumentStates<DocumentState> documentStates, TextDocumentStates<AdditionalDocumentState> additionalDocumentStates, CancellationToken cancellationToken) { // this may produce a version that is out of sync with the actual Document versions. var latestVersion = VersionStamp.Default; foreach (var (_, state) in documentStates.States) { cancellationToken.ThrowIfCancellationRequested(); if (!state.IsGenerated) { var version = await state.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); latestVersion = version.GetNewerVersion(latestVersion); } } foreach (var (_, state) in additionalDocumentStates.States) { cancellationToken.ThrowIfCancellationRequested(); var version = await state.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); latestVersion = version.GetNewerVersion(latestVersion); } return latestVersion; } private AsyncLazy<VersionStamp> CreateLazyLatestDocumentTopLevelChangeVersion( TextDocumentState newDocument, TextDocumentStates<DocumentState> newDocumentStates, TextDocumentStates<AdditionalDocumentState> newAdditionalDocumentStates) { if (_lazyLatestDocumentTopLevelChangeVersion.TryGetValue(out var oldVersion)) { return new AsyncLazy<VersionStamp>(c => ComputeTopLevelChangeTextVersionAsync(oldVersion, newDocument, c), cacheResult: true); } else { return new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentTopLevelChangeVersionAsync(newDocumentStates, newAdditionalDocumentStates, c), cacheResult: true); } } private static async Task<VersionStamp> ComputeTopLevelChangeTextVersionAsync(VersionStamp oldVersion, TextDocumentState newDocument, CancellationToken cancellationToken) { var newVersion = await newDocument.GetTopLevelChangeTextVersionAsync(cancellationToken).ConfigureAwait(false); return newVersion.GetNewerVersion(oldVersion); } private static async Task<VersionStamp> ComputeLatestDocumentTopLevelChangeVersionAsync(TextDocumentStates<DocumentState> documentStates, TextDocumentStates<AdditionalDocumentState> additionalDocumentStates, CancellationToken cancellationToken) { // this may produce a version that is out of sync with the actual Document versions. var latestVersion = VersionStamp.Default; foreach (var (_, state) in documentStates.States) { cancellationToken.ThrowIfCancellationRequested(); var version = await state.GetTopLevelChangeTextVersionAsync(cancellationToken).ConfigureAwait(false); latestVersion = version.GetNewerVersion(latestVersion); } foreach (var (_, state) in additionalDocumentStates.States) { cancellationToken.ThrowIfCancellationRequested(); var version = await state.GetTopLevelChangeTextVersionAsync(cancellationToken).ConfigureAwait(false); latestVersion = version.GetNewerVersion(latestVersion); } return latestVersion; } internal DocumentState CreateDocument(DocumentInfo documentInfo, ParseOptions? parseOptions) { var doc = new DocumentState(documentInfo, parseOptions, _languageServices, _solutionServices); if (doc.SourceCodeKind != documentInfo.SourceCodeKind) { doc = doc.UpdateSourceCodeKind(documentInfo.SourceCodeKind); } return doc; } public AnalyzerOptions AnalyzerOptions => _lazyAnalyzerOptions ??= new AnalyzerOptions( additionalFiles: AdditionalDocumentStates.SelectAsArray(static documentState => documentState.AdditionalText), optionsProvider: new WorkspaceAnalyzerConfigOptionsProvider(this)); public async Task<ImmutableDictionary<string, string>> GetAnalyzerOptionsForPathAsync( string path, CancellationToken cancellationToken) { var configSet = await _lazyAnalyzerConfigSet.GetValueAsync(cancellationToken).ConfigureAwait(false); return configSet.GetOptionsForSourcePath(path).AnalyzerOptions; } public AnalyzerConfigOptionsResult? GetAnalyzerConfigOptions() { // We need to find the analyzer config options at the root of the project. // Currently, there is no compiler API to query analyzer config options for a directory in a language agnostic fashion. // So, we use a dummy language-specific file name appended to the project directory to query analyzer config options. var projectDirectory = PathUtilities.GetDirectoryName(_projectInfo.FilePath); if (!PathUtilities.IsAbsolute(projectDirectory)) { return null; } var fileName = Guid.NewGuid().ToString(); string sourceFilePath; switch (_projectInfo.Language) { case LanguageNames.CSharp: // Suppression should be removed or addressed https://github.com/dotnet/roslyn/issues/41636 sourceFilePath = PathUtilities.CombineAbsoluteAndRelativePaths(projectDirectory, $"{fileName}.cs")!; break; case LanguageNames.VisualBasic: // Suppression should be removed or addressed https://github.com/dotnet/roslyn/issues/41636 sourceFilePath = PathUtilities.CombineAbsoluteAndRelativePaths(projectDirectory, $"{fileName}.vb")!; break; default: return null; } return _lazyAnalyzerConfigSet.GetValue(CancellationToken.None).GetOptionsForSourcePath(sourceFilePath); } internal sealed class WorkspaceAnalyzerConfigOptionsProvider : AnalyzerConfigOptionsProvider { private readonly ProjectState _projectState; public WorkspaceAnalyzerConfigOptionsProvider(ProjectState projectState) => _projectState = projectState; public override AnalyzerConfigOptions GlobalOptions => new WorkspaceAnalyzerConfigOptions(_projectState._lazyAnalyzerConfigSet.GetValue(CancellationToken.None).GetOptionsForSourcePath(string.Empty)); public override AnalyzerConfigOptions GetOptions(SyntaxTree tree) => new WorkspaceAnalyzerConfigOptions(_projectState._lazyAnalyzerConfigSet.GetValue(CancellationToken.None).GetOptionsForSourcePath(tree.FilePath)); public override AnalyzerConfigOptions GetOptions(AdditionalText textFile) { // TODO: correctly find the file path, since it looks like we give this the document's .Name under the covers if we don't have one return new WorkspaceAnalyzerConfigOptions(_projectState._lazyAnalyzerConfigSet.GetValue(CancellationToken.None).GetOptionsForSourcePath(textFile.Path)); } public AnalyzerConfigOptions GetOptionsForSourcePath(string path) => new WorkspaceAnalyzerConfigOptions(_projectState._lazyAnalyzerConfigSet.GetValue(CancellationToken.None).GetOptionsForSourcePath(path)); private sealed class WorkspaceAnalyzerConfigOptions : AnalyzerConfigOptions { private readonly ImmutableDictionary<string, string> _backing; public WorkspaceAnalyzerConfigOptions(AnalyzerConfigOptionsResult analyzerConfigOptions) => _backing = analyzerConfigOptions.AnalyzerOptions; public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value) => _backing.TryGetValue(key, out value); } } private sealed class WorkspaceSyntaxTreeOptionsProvider : SyntaxTreeOptionsProvider { private readonly ValueSource<CachingAnalyzerConfigSet> _lazyAnalyzerConfigSet; public WorkspaceSyntaxTreeOptionsProvider(ValueSource<CachingAnalyzerConfigSet> lazyAnalyzerConfigSet) => _lazyAnalyzerConfigSet = lazyAnalyzerConfigSet; public override GeneratedKind IsGenerated(SyntaxTree tree, CancellationToken cancellationToken) { var options = _lazyAnalyzerConfigSet .GetValue(cancellationToken).GetOptionsForSourcePath(tree.FilePath); return GeneratedCodeUtilities.GetIsGeneratedCodeFromOptions(options.AnalyzerOptions); } public override bool TryGetDiagnosticValue(SyntaxTree tree, string diagnosticId, CancellationToken cancellationToken, out ReportDiagnostic severity) { var options = _lazyAnalyzerConfigSet .GetValue(cancellationToken).GetOptionsForSourcePath(tree.FilePath); return options.TreeOptions.TryGetValue(diagnosticId, out severity); } public override bool TryGetGlobalDiagnosticValue(string diagnosticId, CancellationToken cancellationToken, out ReportDiagnostic severity) { var options = _lazyAnalyzerConfigSet .GetValue(cancellationToken).GlobalConfigOptions; return options.TreeOptions.TryGetValue(diagnosticId, out severity); } public override bool Equals(object? obj) { return obj is WorkspaceSyntaxTreeOptionsProvider other && _lazyAnalyzerConfigSet == other._lazyAnalyzerConfigSet; } public override int GetHashCode() => _lazyAnalyzerConfigSet.GetHashCode(); } private static ValueSource<CachingAnalyzerConfigSet> ComputeAnalyzerConfigSetValueSource(TextDocumentStates<AnalyzerConfigDocumentState> analyzerConfigDocumentStates) { return new AsyncLazy<CachingAnalyzerConfigSet>( asynchronousComputeFunction: async cancellationToken => { var tasks = analyzerConfigDocumentStates.States.Values.Select(a => a.GetAnalyzerConfigAsync(cancellationToken)); var analyzerConfigs = await Task.WhenAll(tasks).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); return new CachingAnalyzerConfigSet(AnalyzerConfigSet.Create(analyzerConfigs)); }, synchronousComputeFunction: cancellationToken => { var analyzerConfigs = analyzerConfigDocumentStates.SelectAsArray(a => a.GetAnalyzerConfig(cancellationToken)); return new CachingAnalyzerConfigSet(AnalyzerConfigSet.Create(analyzerConfigs)); }, cacheResult: true); } public Task<VersionStamp> GetLatestDocumentVersionAsync(CancellationToken cancellationToken) => _lazyLatestDocumentVersion.GetValueAsync(cancellationToken); public async Task<VersionStamp> GetSemanticVersionAsync(CancellationToken cancellationToken = default) { var docVersion = await _lazyLatestDocumentTopLevelChangeVersion.GetValueAsync(cancellationToken).ConfigureAwait(false); return docVersion.GetNewerVersion(this.Version); } [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public ProjectId Id => this.ProjectInfo.Id; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public string? FilePath => this.ProjectInfo.FilePath; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public string? OutputFilePath => this.ProjectInfo.OutputFilePath; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public string? OutputRefFilePath => this.ProjectInfo.OutputRefFilePath; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public CompilationOutputInfo CompilationOutputInfo => this.ProjectInfo.CompilationOutputInfo; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public string? DefaultNamespace => this.ProjectInfo.DefaultNamespace; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public HostLanguageServices LanguageServices => _languageServices; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public string Language => LanguageServices.Language; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public string Name => this.ProjectInfo.Name; /// <inheritdoc cref="ProjectInfo.NameAndFlavor"/> [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public (string? name, string? flavor) NameAndFlavor => this.ProjectInfo.NameAndFlavor; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public bool IsSubmission => this.ProjectInfo.IsSubmission; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public Type? HostObjectType => this.ProjectInfo.HostObjectType; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public bool SupportsCompilation => this.LanguageServices.GetService<ICompilationFactoryService>() != null; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public VersionStamp Version => this.ProjectInfo.Version; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public ProjectInfo ProjectInfo => _projectInfo; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public string AssemblyName => this.ProjectInfo.AssemblyName; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public CompilationOptions? CompilationOptions => this.ProjectInfo.CompilationOptions; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public ParseOptions? ParseOptions => this.ProjectInfo.ParseOptions; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public IReadOnlyList<MetadataReference> MetadataReferences => this.ProjectInfo.MetadataReferences; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public IReadOnlyList<AnalyzerReference> AnalyzerReferences => this.ProjectInfo.AnalyzerReferences; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public IReadOnlyList<ProjectReference> ProjectReferences => this.ProjectInfo.ProjectReferences; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public bool HasAllInformation => this.ProjectInfo.HasAllInformation; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public bool RunAnalyzers => this.ProjectInfo.RunAnalyzers; private ProjectState With( ProjectInfo? projectInfo = null, TextDocumentStates<DocumentState>? documentStates = null, TextDocumentStates<AdditionalDocumentState>? additionalDocumentStates = null, TextDocumentStates<AnalyzerConfigDocumentState>? analyzerConfigDocumentStates = null, AsyncLazy<VersionStamp>? latestDocumentVersion = null, AsyncLazy<VersionStamp>? latestDocumentTopLevelChangeVersion = null, ValueSource<CachingAnalyzerConfigSet>? analyzerConfigSet = null) { return new ProjectState( projectInfo ?? _projectInfo, _languageServices, _solutionServices, documentStates ?? DocumentStates, additionalDocumentStates ?? AdditionalDocumentStates, analyzerConfigDocumentStates ?? AnalyzerConfigDocumentStates, latestDocumentVersion ?? _lazyLatestDocumentVersion, latestDocumentTopLevelChangeVersion ?? _lazyLatestDocumentTopLevelChangeVersion, analyzerConfigSet ?? _lazyAnalyzerConfigSet); } private ProjectInfo.ProjectAttributes Attributes => ProjectInfo.Attributes; private ProjectState WithAttributes(ProjectInfo.ProjectAttributes attributes) => With(projectInfo: ProjectInfo.With(attributes: attributes)); public ProjectState WithName(string name) => (name == Name) ? this : WithAttributes(Attributes.With(name: name, version: Version.GetNewerVersion())); public ProjectState WithFilePath(string? filePath) => (filePath == FilePath) ? this : WithAttributes(Attributes.With(filePath: filePath, version: Version.GetNewerVersion())); public ProjectState WithAssemblyName(string assemblyName) => (assemblyName == AssemblyName) ? this : WithAttributes(Attributes.With(assemblyName: assemblyName, version: Version.GetNewerVersion())); public ProjectState WithOutputFilePath(string? outputFilePath) => (outputFilePath == OutputFilePath) ? this : WithAttributes(Attributes.With(outputPath: outputFilePath, version: Version.GetNewerVersion())); public ProjectState WithOutputRefFilePath(string? outputRefFilePath) => (outputRefFilePath == OutputRefFilePath) ? this : WithAttributes(Attributes.With(outputRefPath: outputRefFilePath, version: Version.GetNewerVersion())); public ProjectState WithCompilationOutputInfo(in CompilationOutputInfo info) => (info == CompilationOutputInfo) ? this : WithAttributes(Attributes.With(compilationOutputInfo: info, version: Version.GetNewerVersion())); public ProjectState WithDefaultNamespace(string? defaultNamespace) => (defaultNamespace == DefaultNamespace) ? this : WithAttributes(Attributes.With(defaultNamespace: defaultNamespace, version: Version.GetNewerVersion())); public ProjectState WithHasAllInformation(bool hasAllInformation) => (hasAllInformation == HasAllInformation) ? this : WithAttributes(Attributes.With(hasAllInformation: hasAllInformation, version: Version.GetNewerVersion())); public ProjectState WithRunAnalyzers(bool runAnalyzers) => (runAnalyzers == RunAnalyzers) ? this : WithAttributes(Attributes.With(runAnalyzers: runAnalyzers, version: Version.GetNewerVersion())); public ProjectState WithCompilationOptions(CompilationOptions options) { if (options == CompilationOptions) { return this; } var newProvider = new WorkspaceSyntaxTreeOptionsProvider(_lazyAnalyzerConfigSet); return With(projectInfo: ProjectInfo.WithCompilationOptions(options.WithSyntaxTreeOptionsProvider(newProvider)) .WithVersion(Version.GetNewerVersion())); } public ProjectState WithParseOptions(ParseOptions options) { if (options == ParseOptions) { return this; } return With( projectInfo: ProjectInfo.WithParseOptions(options).WithVersion(Version.GetNewerVersion()), documentStates: DocumentStates.UpdateStates(static (state, options) => state.UpdateParseOptions(options), options)); } public static bool IsSameLanguage(ProjectState project1, ProjectState project2) => project1.LanguageServices == project2.LanguageServices; /// <summary> /// Determines whether <see cref="ProjectReferences"/> contains a reference to a specified project. /// </summary> /// <param name="projectId">The target project of the reference.</param> /// <returns><see langword="true"/> if this project references <paramref name="projectId"/>; otherwise, <see langword="false"/>.</returns> public bool ContainsReferenceToProject(ProjectId projectId) { foreach (var projectReference in ProjectReferences) { if (projectReference.ProjectId == projectId) return true; } return false; } public ProjectState WithProjectReferences(IReadOnlyList<ProjectReference> projectReferences) { if (projectReferences == ProjectReferences) { return this; } return With(projectInfo: ProjectInfo.With(projectReferences: projectReferences).WithVersion(Version.GetNewerVersion())); } public ProjectState WithMetadataReferences(IReadOnlyList<MetadataReference> metadataReferences) { if (metadataReferences == MetadataReferences) { return this; } return With(projectInfo: ProjectInfo.With(metadataReferences: metadataReferences).WithVersion(Version.GetNewerVersion())); } public ProjectState WithAnalyzerReferences(IEnumerable<AnalyzerReference> analyzerReferences) { if (analyzerReferences == AnalyzerReferences) { return this; } return With(projectInfo: ProjectInfo.WithAnalyzerReferences(analyzerReferences).WithVersion(Version.GetNewerVersion())); } public ImmutableArray<ISourceGenerator> SourceGenerators { get { if (_lazySourceGenerators.IsDefault) { var generators = AnalyzerReferences.SelectMany(a => a.GetGenerators(this.Language)).ToImmutableArray(); ImmutableInterlocked.InterlockedInitialize(ref _lazySourceGenerators, generators); } return _lazySourceGenerators; } } public ProjectState AddDocuments(ImmutableArray<DocumentState> documents) { Debug.Assert(!documents.Any(d => DocumentStates.Contains(d.Id))); return With( projectInfo: ProjectInfo.WithVersion(Version.GetNewerVersion()), documentStates: DocumentStates.AddRange(documents)); } public ProjectState AddAdditionalDocuments(ImmutableArray<AdditionalDocumentState> documents) { Debug.Assert(!documents.Any(d => AdditionalDocumentStates.Contains(d.Id))); return With( projectInfo: ProjectInfo.WithVersion(Version.GetNewerVersion()), additionalDocumentStates: AdditionalDocumentStates.AddRange(documents)); } public ProjectState AddAnalyzerConfigDocuments(ImmutableArray<AnalyzerConfigDocumentState> documents) { Debug.Assert(!documents.Any(d => AnalyzerConfigDocumentStates.Contains(d.Id))); var newAnalyzerConfigDocumentStates = AnalyzerConfigDocumentStates.AddRange(documents); return CreateNewStateForChangedAnalyzerConfigDocuments(newAnalyzerConfigDocumentStates); } private ProjectState CreateNewStateForChangedAnalyzerConfigDocuments(TextDocumentStates<AnalyzerConfigDocumentState> newAnalyzerConfigDocumentStates) { var newAnalyzerConfigSet = ComputeAnalyzerConfigSetValueSource(newAnalyzerConfigDocumentStates); var projectInfo = ProjectInfo.WithVersion(Version.GetNewerVersion()); // Changing analyzer configs changes compilation options if (CompilationOptions != null) { var newProvider = new WorkspaceSyntaxTreeOptionsProvider(newAnalyzerConfigSet); projectInfo = projectInfo .WithCompilationOptions(CompilationOptions.WithSyntaxTreeOptionsProvider(newProvider)); } return With( projectInfo: projectInfo, analyzerConfigDocumentStates: newAnalyzerConfigDocumentStates, analyzerConfigSet: newAnalyzerConfigSet); } public ProjectState RemoveDocuments(ImmutableArray<DocumentId> documentIds) { // We create a new CachingAnalyzerConfigSet for the new snapshot to avoid holding onto cached information // for removed documents. return With( projectInfo: ProjectInfo.WithVersion(Version.GetNewerVersion()), documentStates: DocumentStates.RemoveRange(documentIds), analyzerConfigSet: ComputeAnalyzerConfigSetValueSource(AnalyzerConfigDocumentStates)); } public ProjectState RemoveAdditionalDocuments(ImmutableArray<DocumentId> documentIds) { return With( projectInfo: ProjectInfo.WithVersion(Version.GetNewerVersion()), additionalDocumentStates: AdditionalDocumentStates.RemoveRange(documentIds)); } public ProjectState RemoveAnalyzerConfigDocuments(ImmutableArray<DocumentId> documentIds) { var newAnalyzerConfigDocumentStates = AnalyzerConfigDocumentStates.RemoveRange(documentIds); return CreateNewStateForChangedAnalyzerConfigDocuments(newAnalyzerConfigDocumentStates); } public ProjectState RemoveAllDocuments() { // We create a new CachingAnalyzerConfigSet for the new snapshot to avoid holding onto cached information // for removed documents. return With( projectInfo: ProjectInfo.WithVersion(Version.GetNewerVersion()), documentStates: TextDocumentStates<DocumentState>.Empty, analyzerConfigSet: ComputeAnalyzerConfigSetValueSource(AnalyzerConfigDocumentStates)); } public ProjectState UpdateDocument(DocumentState newDocument, bool textChanged, bool recalculateDependentVersions) { var oldDocument = DocumentStates.GetRequiredState(newDocument.Id); if (oldDocument == newDocument) { return this; } var newDocumentStates = DocumentStates.SetState(newDocument.Id, newDocument); GetLatestDependentVersions( newDocumentStates, AdditionalDocumentStates, oldDocument, newDocument, recalculateDependentVersions, textChanged, out var dependentDocumentVersion, out var dependentSemanticVersion); return With( documentStates: newDocumentStates, latestDocumentVersion: dependentDocumentVersion, latestDocumentTopLevelChangeVersion: dependentSemanticVersion); } public ProjectState UpdateAdditionalDocument(AdditionalDocumentState newDocument, bool textChanged, bool recalculateDependentVersions) { var oldDocument = AdditionalDocumentStates.GetRequiredState(newDocument.Id); if (oldDocument == newDocument) { return this; } var newDocumentStates = AdditionalDocumentStates.SetState(newDocument.Id, newDocument); GetLatestDependentVersions( DocumentStates, newDocumentStates, oldDocument, newDocument, recalculateDependentVersions, textChanged, out var dependentDocumentVersion, out var dependentSemanticVersion); return this.With( additionalDocumentStates: newDocumentStates, latestDocumentVersion: dependentDocumentVersion, latestDocumentTopLevelChangeVersion: dependentSemanticVersion); } public ProjectState UpdateAnalyzerConfigDocument(AnalyzerConfigDocumentState newDocument) { var oldDocument = AnalyzerConfigDocumentStates.GetRequiredState(newDocument.Id); if (oldDocument == newDocument) { return this; } var newDocumentStates = AnalyzerConfigDocumentStates.SetState(newDocument.Id, newDocument); return CreateNewStateForChangedAnalyzerConfigDocuments(newDocumentStates); } public ProjectState UpdateDocumentsOrder(ImmutableList<DocumentId> documentIds) { if (documentIds.SequenceEqual(DocumentStates.Ids)) { return this; } return With( projectInfo: ProjectInfo.WithVersion(Version.GetNewerVersion()), documentStates: DocumentStates.WithCompilationOrder(documentIds)); } private void GetLatestDependentVersions( TextDocumentStates<DocumentState> newDocumentStates, TextDocumentStates<AdditionalDocumentState> newAdditionalDocumentStates, TextDocumentState oldDocument, TextDocumentState newDocument, bool recalculateDependentVersions, bool textChanged, out AsyncLazy<VersionStamp> dependentDocumentVersion, out AsyncLazy<VersionStamp> dependentSemanticVersion) { var recalculateDocumentVersion = false; var recalculateSemanticVersion = false; if (recalculateDependentVersions) { if (oldDocument.TryGetTextVersion(out var oldVersion)) { if (!_lazyLatestDocumentVersion.TryGetValue(out var documentVersion) || documentVersion == oldVersion) { recalculateDocumentVersion = true; } if (!_lazyLatestDocumentTopLevelChangeVersion.TryGetValue(out var semanticVersion) || semanticVersion == oldVersion) { recalculateSemanticVersion = true; } } } dependentDocumentVersion = recalculateDocumentVersion ? new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentVersionAsync(newDocumentStates, newAdditionalDocumentStates, c), cacheResult: true) : textChanged ? new AsyncLazy<VersionStamp>(newDocument.GetTextVersionAsync, cacheResult: true) : _lazyLatestDocumentVersion; dependentSemanticVersion = recalculateSemanticVersion ? new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentTopLevelChangeVersionAsync(newDocumentStates, newAdditionalDocumentStates, c), cacheResult: true) : textChanged ? CreateLazyLatestDocumentTopLevelChangeVersion(newDocument, newDocumentStates, newAdditionalDocumentStates) : _lazyLatestDocumentTopLevelChangeVersion; } } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/VisualStudio/Core/Def/Implementation/ColorSchemes/ColorSchemeApplier.ClassificationVerifier.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.Security.Permissions; using System.Windows; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.ColorSchemes; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.ColorSchemes { internal partial class ColorSchemeApplier { private sealed class ClassificationVerifier : ForegroundThreadAffinitizedObject { private readonly IServiceProvider _serviceProvider; private readonly ImmutableDictionary<SchemeName, ImmutableDictionary<Guid, ImmutableDictionary<string, uint>>> _colorSchemes; private static readonly Guid TextEditorMEFItemsColorCategory = new("75a05685-00a8-4ded-bae5-e7a50bfa929a"); // These classification colors (0x00BBGGRR) should match the VS\EditorColors.xml file. // They are not in the scheme files because they are core classifications. private const uint DarkThemePlainText = 0x00DCDCDCu; private const uint DarkThemeIdentifier = DarkThemePlainText; private const uint DarkThemeOperator = 0x00B4B4B4u; private const uint DarkThemeKeyword = 0x00D69C56u; private const uint LightThemePlainText = 0x00000000u; private const uint LightThemeIdentifier = LightThemePlainText; private const uint LightThemeOperator = LightThemePlainText; private const uint LightThemeKeyword = 0x00FF0000u; private const string PlainTextClassificationTypeName = "plain text"; // Dark Theme Core Classifications private static ImmutableDictionary<string, uint> DarkThemeForeground => new Dictionary<string, uint>() { [PlainTextClassificationTypeName] = DarkThemePlainText, [ClassificationTypeNames.Identifier] = DarkThemeIdentifier, [ClassificationTypeNames.Keyword] = DarkThemeKeyword, [ClassificationTypeNames.Operator] = DarkThemeOperator, }.ToImmutableDictionary(); // Light, Blue, or AdditionalContrast Theme Core Classifications private static ImmutableDictionary<string, uint> BlueLightThemeForeground => new Dictionary<string, uint>() { [PlainTextClassificationTypeName] = LightThemePlainText, [ClassificationTypeNames.Identifier] = LightThemeIdentifier, [ClassificationTypeNames.Keyword] = LightThemeKeyword, [ClassificationTypeNames.Operator] = LightThemeOperator, }.ToImmutableDictionary(); // The High Contrast theme is not included because we do not want to make changes when the user is in High Contrast mode. private IVsFontAndColorStorage? _fontAndColorStorage; private IVsFontAndColorUtilities? _fontAndColorUtilities; private ImmutableArray<string> Classifications { get; } public ClassificationVerifier(IThreadingContext threadingContext, IServiceProvider serviceProvider, ImmutableDictionary<SchemeName, ColorScheme> colorSchemes) : base(threadingContext) { _serviceProvider = serviceProvider; _colorSchemes = colorSchemes.ToImmutableDictionary( nameAndScheme => nameAndScheme.Key, nameAndScheme => nameAndScheme.Value.Themes.ToImmutableDictionary( theme => theme.Guid, theme => theme.Category.Colors .Where(color => color.Foreground.HasValue) .ToImmutableDictionary(color => color.Name, color => color.Foreground!.Value))); // Gather all the classifications from the core and scheme dictionaries. var coreClassifications = DarkThemeForeground.Keys.Concat(BlueLightThemeForeground.Keys).Distinct(); var colorSchemeClassifications = _colorSchemes.Values.SelectMany(scheme => scheme.Values.SelectMany(theme => theme.Keys)).Distinct(); Classifications = coreClassifications.Concat(colorSchemeClassifications).ToImmutableArray(); } /// <summary> /// Determines if any Classification foreground colors have been customized in Fonts and Colors. /// </summary> public bool AreForegroundColorsCustomized(SchemeName schemeName, Guid themeId) { AssertIsForeground(); // Ensure we are initialized if (_fontAndColorStorage is null) { _fontAndColorStorage = _serviceProvider.GetService<SVsFontAndColorStorage, IVsFontAndColorStorage>(); _fontAndColorUtilities = (IVsFontAndColorUtilities)_fontAndColorStorage!; } // Make no changes when in high contast mode or in unknown theme. if (SystemParameters.HighContrast || !_colorSchemes.TryGetValue(schemeName, out var colorScheme) || !colorScheme.TryGetValue(themeId, out var colorSchemeTheme)) { return false; } var coreThemeColors = (themeId == KnownColorThemes.Dark) ? DarkThemeForeground : BlueLightThemeForeground; // Open Text Editor category for readonly access and do not load items if they are defaulted. if (_fontAndColorStorage.OpenCategory(TextEditorMEFItemsColorCategory, (uint)__FCSTORAGEFLAGS.FCSF_READONLY) != VSConstants.S_OK) { // We were unable to access color information. return false; } try { foreach (var classification in Classifications) { var colorItems = new ColorableItemInfo[1]; if (_fontAndColorStorage.GetItem(classification, colorItems) != VSConstants.S_OK) { // Classifications that are still defaulted will not have entries. continue; } var colorItem = colorItems[0]; if (IsClassificationCustomized(coreThemeColors, colorSchemeTheme, colorItem, classification)) { return true; } } } finally { _fontAndColorStorage.CloseCategory(); } return false; } /// <summary> /// Determines if the ColorableItemInfo's Foreground has been customized to a color that doesn't match the /// selected scheme. /// </summary> private bool IsClassificationCustomized( ImmutableDictionary<string, uint> coreThemeColors, ImmutableDictionary<string, uint> schemeThemeColors, ColorableItemInfo colorItem, string classification) { AssertIsForeground(); Contract.ThrowIfNull(_fontAndColorUtilities); var foregroundColorRef = colorItem.crForeground; if (_fontAndColorUtilities.GetColorType(foregroundColorRef, out var foregroundColorType) != VSConstants.S_OK) { // Without being able to check color type, we cannot make a determination. return false; } // If the color is defaulted then it isn't customized. if (foregroundColorType == (int)__VSCOLORTYPE.CT_AUTOMATIC) { return false; } // Since the color type isn't default then it has been customized, we will // perform an additional check for RGB colors to see if the customized color // matches the color scheme color. if (foregroundColorType != (int)__VSCOLORTYPE.CT_RAW) { return true; } if (coreThemeColors.TryGetValue(classification, out var coreColor)) { return foregroundColorRef != coreColor; } if (schemeThemeColors.TryGetValue(classification, out var schemeColor)) { return foregroundColorRef != schemeColor; } // Since Classification inheritance isn't represented in the scheme files, // this switch case will handle the 3 cases we expect. var fallbackColor = classification switch { ClassificationTypeNames.OperatorOverloaded => coreThemeColors[ClassificationTypeNames.Operator], ClassificationTypeNames.ControlKeyword => coreThemeColors[ClassificationTypeNames.Keyword], _ => coreThemeColors[ClassificationTypeNames.Identifier] }; return foregroundColorRef != fallbackColor; } } } }
// Licensed to the .NET Foundation under one or more 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.Security.Permissions; using System.Windows; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.ColorSchemes; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.ColorSchemes { internal partial class ColorSchemeApplier { private sealed class ClassificationVerifier : ForegroundThreadAffinitizedObject { private readonly IServiceProvider _serviceProvider; private readonly ImmutableDictionary<SchemeName, ImmutableDictionary<Guid, ImmutableDictionary<string, uint>>> _colorSchemes; private static readonly Guid TextEditorMEFItemsColorCategory = new("75a05685-00a8-4ded-bae5-e7a50bfa929a"); // These classification colors (0x00BBGGRR) should match the VS\EditorColors.xml file. // They are not in the scheme files because they are core classifications. private const uint DarkThemePlainText = 0x00DCDCDCu; private const uint DarkThemeIdentifier = DarkThemePlainText; private const uint DarkThemeOperator = 0x00B4B4B4u; private const uint DarkThemeKeyword = 0x00D69C56u; private const uint LightThemePlainText = 0x00000000u; private const uint LightThemeIdentifier = LightThemePlainText; private const uint LightThemeOperator = LightThemePlainText; private const uint LightThemeKeyword = 0x00FF0000u; private const string PlainTextClassificationTypeName = "plain text"; // Dark Theme Core Classifications private static ImmutableDictionary<string, uint> DarkThemeForeground => new Dictionary<string, uint>() { [PlainTextClassificationTypeName] = DarkThemePlainText, [ClassificationTypeNames.Identifier] = DarkThemeIdentifier, [ClassificationTypeNames.Keyword] = DarkThemeKeyword, [ClassificationTypeNames.Operator] = DarkThemeOperator, }.ToImmutableDictionary(); // Light, Blue, or AdditionalContrast Theme Core Classifications private static ImmutableDictionary<string, uint> BlueLightThemeForeground => new Dictionary<string, uint>() { [PlainTextClassificationTypeName] = LightThemePlainText, [ClassificationTypeNames.Identifier] = LightThemeIdentifier, [ClassificationTypeNames.Keyword] = LightThemeKeyword, [ClassificationTypeNames.Operator] = LightThemeOperator, }.ToImmutableDictionary(); // The High Contrast theme is not included because we do not want to make changes when the user is in High Contrast mode. private IVsFontAndColorStorage? _fontAndColorStorage; private IVsFontAndColorUtilities? _fontAndColorUtilities; private ImmutableArray<string> Classifications { get; } public ClassificationVerifier(IThreadingContext threadingContext, IServiceProvider serviceProvider, ImmutableDictionary<SchemeName, ColorScheme> colorSchemes) : base(threadingContext) { _serviceProvider = serviceProvider; _colorSchemes = colorSchemes.ToImmutableDictionary( nameAndScheme => nameAndScheme.Key, nameAndScheme => nameAndScheme.Value.Themes.ToImmutableDictionary( theme => theme.Guid, theme => theme.Category.Colors .Where(color => color.Foreground.HasValue) .ToImmutableDictionary(color => color.Name, color => color.Foreground!.Value))); // Gather all the classifications from the core and scheme dictionaries. var coreClassifications = DarkThemeForeground.Keys.Concat(BlueLightThemeForeground.Keys).Distinct(); var colorSchemeClassifications = _colorSchemes.Values.SelectMany(scheme => scheme.Values.SelectMany(theme => theme.Keys)).Distinct(); Classifications = coreClassifications.Concat(colorSchemeClassifications).ToImmutableArray(); } /// <summary> /// Determines if any Classification foreground colors have been customized in Fonts and Colors. /// </summary> public bool AreForegroundColorsCustomized(SchemeName schemeName, Guid themeId) { AssertIsForeground(); // Ensure we are initialized if (_fontAndColorStorage is null) { _fontAndColorStorage = _serviceProvider.GetService<SVsFontAndColorStorage, IVsFontAndColorStorage>(); _fontAndColorUtilities = (IVsFontAndColorUtilities)_fontAndColorStorage!; } // Make no changes when in high contast mode or in unknown theme. if (SystemParameters.HighContrast || !_colorSchemes.TryGetValue(schemeName, out var colorScheme) || !colorScheme.TryGetValue(themeId, out var colorSchemeTheme)) { return false; } var coreThemeColors = (themeId == KnownColorThemes.Dark) ? DarkThemeForeground : BlueLightThemeForeground; // Open Text Editor category for readonly access and do not load items if they are defaulted. if (_fontAndColorStorage.OpenCategory(TextEditorMEFItemsColorCategory, (uint)__FCSTORAGEFLAGS.FCSF_READONLY) != VSConstants.S_OK) { // We were unable to access color information. return false; } try { foreach (var classification in Classifications) { var colorItems = new ColorableItemInfo[1]; if (_fontAndColorStorage.GetItem(classification, colorItems) != VSConstants.S_OK) { // Classifications that are still defaulted will not have entries. continue; } var colorItem = colorItems[0]; if (IsClassificationCustomized(coreThemeColors, colorSchemeTheme, colorItem, classification)) { return true; } } } finally { _fontAndColorStorage.CloseCategory(); } return false; } /// <summary> /// Determines if the ColorableItemInfo's Foreground has been customized to a color that doesn't match the /// selected scheme. /// </summary> private bool IsClassificationCustomized( ImmutableDictionary<string, uint> coreThemeColors, ImmutableDictionary<string, uint> schemeThemeColors, ColorableItemInfo colorItem, string classification) { AssertIsForeground(); Contract.ThrowIfNull(_fontAndColorUtilities); var foregroundColorRef = colorItem.crForeground; if (_fontAndColorUtilities.GetColorType(foregroundColorRef, out var foregroundColorType) != VSConstants.S_OK) { // Without being able to check color type, we cannot make a determination. return false; } // If the color is defaulted then it isn't customized. if (foregroundColorType == (int)__VSCOLORTYPE.CT_AUTOMATIC) { return false; } // Since the color type isn't default then it has been customized, we will // perform an additional check for RGB colors to see if the customized color // matches the color scheme color. if (foregroundColorType != (int)__VSCOLORTYPE.CT_RAW) { return true; } if (coreThemeColors.TryGetValue(classification, out var coreColor)) { return foregroundColorRef != coreColor; } if (schemeThemeColors.TryGetValue(classification, out var schemeColor)) { return foregroundColorRef != schemeColor; } // Since Classification inheritance isn't represented in the scheme files, // this switch case will handle the 3 cases we expect. var fallbackColor = classification switch { ClassificationTypeNames.OperatorOverloaded => coreThemeColors[ClassificationTypeNames.Operator], ClassificationTypeNames.ControlKeyword => coreThemeColors[ClassificationTypeNames.Keyword], _ => coreThemeColors[ClassificationTypeNames.Identifier] }; return foregroundColorRef != fallbackColor; } } } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Compilers/Core/Portable/InternalUtilities/SpecializedCollections.Singleton.Enumerator`1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; namespace Roslyn.Utilities { internal static partial class SpecializedCollections { private static partial class Singleton { internal class Enumerator<T> : IEnumerator<T> { private readonly T _loneValue; private bool _moveNextCalled; public Enumerator(T value) { _loneValue = value; _moveNextCalled = false; } public T Current => _loneValue; object? IEnumerator.Current => _loneValue; public void Dispose() { } public bool MoveNext() { if (!_moveNextCalled) { _moveNextCalled = true; return true; } return false; } public void Reset() { _moveNextCalled = false; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; namespace Roslyn.Utilities { internal static partial class SpecializedCollections { private static partial class Singleton { internal class Enumerator<T> : IEnumerator<T> { private readonly T _loneValue; private bool _moveNextCalled; public Enumerator(T value) { _loneValue = value; _moveNextCalled = false; } public T Current => _loneValue; object? IEnumerator.Current => _loneValue; public void Dispose() { } public bool MoveNext() { if (!_moveNextCalled) { _moveNextCalled = true; return true; } return false; } public void Reset() { _moveNextCalled = false; } } } } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/VisualStudio/IntegrationTest/TestUtilities/InProcess/VisualStudio_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.Diagnostics; using EnvDTE; using EnvDTE80; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { internal partial class VisualStudio_InProc : InProcComponent { private VisualStudio_InProc() { } public static VisualStudio_InProc Create() => new VisualStudio_InProc(); public new void WaitForApplicationIdle(TimeSpan timeout) => InProcComponent.WaitForApplicationIdle(timeout); public new void WaitForSystemIdle() => InProcComponent.WaitForSystemIdle(); public new bool IsCommandAvailable(string commandName) => InProcComponent.IsCommandAvailable(commandName); public new void ExecuteCommand(string commandName, string args = "") => InProcComponent.ExecuteCommand(commandName, args); public string[] GetAvailableCommands() { var result = new List<string>(); var commands = GetDTE().Commands; foreach (Command command in commands) { try { var commandName = command.Name; if (command.IsAvailable) { result.Add(commandName); } } finally { } } return result.ToArray(); } public void ActivateMainWindow() => InvokeOnUIThread(cancellationToken => { var dte = GetDTE(); var activeVisualStudioWindow = (IntPtr)dte.ActiveWindow.HWnd; Debug.WriteLine($"DTE.ActiveWindow.HWnd = {activeVisualStudioWindow}"); if (activeVisualStudioWindow == IntPtr.Zero) { activeVisualStudioWindow = (IntPtr)dte.MainWindow.HWnd; Debug.WriteLine($"DTE.MainWindow.HWnd = {activeVisualStudioWindow}"); } IntegrationHelper.SetForegroundWindow(activeVisualStudioWindow); }); public int GetErrorListErrorCount() { var dte = (DTE2)GetDTE(); var errorList = dte.ToolWindows.ErrorList; var errorItems = errorList.ErrorItems; var errorItemsCount = errorItems.Count; var errorCount = 0; try { for (var index = 1; index <= errorItemsCount; index++) { var errorItem = errorItems.Item(index); if (errorItem.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelHigh) { errorCount += 1; } } } catch (IndexOutOfRangeException) { // It is entirely possible that the items in the error list are modified // after we start iterating, in which case we want to try again. return GetErrorListErrorCount(); } return errorCount; } public void WaitForNoErrorsInErrorList() { while (GetErrorListErrorCount() != 0) { System.Threading.Thread.Yield(); } } public void Quit() => GetDTE().Quit(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using EnvDTE; using EnvDTE80; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { internal partial class VisualStudio_InProc : InProcComponent { private VisualStudio_InProc() { } public static VisualStudio_InProc Create() => new VisualStudio_InProc(); public new void WaitForApplicationIdle(TimeSpan timeout) => InProcComponent.WaitForApplicationIdle(timeout); public new void WaitForSystemIdle() => InProcComponent.WaitForSystemIdle(); public new bool IsCommandAvailable(string commandName) => InProcComponent.IsCommandAvailable(commandName); public new void ExecuteCommand(string commandName, string args = "") => InProcComponent.ExecuteCommand(commandName, args); public string[] GetAvailableCommands() { var result = new List<string>(); var commands = GetDTE().Commands; foreach (Command command in commands) { try { var commandName = command.Name; if (command.IsAvailable) { result.Add(commandName); } } finally { } } return result.ToArray(); } public void ActivateMainWindow() => InvokeOnUIThread(cancellationToken => { var dte = GetDTE(); var activeVisualStudioWindow = (IntPtr)dte.ActiveWindow.HWnd; Debug.WriteLine($"DTE.ActiveWindow.HWnd = {activeVisualStudioWindow}"); if (activeVisualStudioWindow == IntPtr.Zero) { activeVisualStudioWindow = (IntPtr)dte.MainWindow.HWnd; Debug.WriteLine($"DTE.MainWindow.HWnd = {activeVisualStudioWindow}"); } IntegrationHelper.SetForegroundWindow(activeVisualStudioWindow); }); public int GetErrorListErrorCount() { var dte = (DTE2)GetDTE(); var errorList = dte.ToolWindows.ErrorList; var errorItems = errorList.ErrorItems; var errorItemsCount = errorItems.Count; var errorCount = 0; try { for (var index = 1; index <= errorItemsCount; index++) { var errorItem = errorItems.Item(index); if (errorItem.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelHigh) { errorCount += 1; } } } catch (IndexOutOfRangeException) { // It is entirely possible that the items in the error list are modified // after we start iterating, in which case we want to try again. return GetErrorListErrorCount(); } return errorCount; } public void WaitForNoErrorsInErrorList() { while (GetErrorListErrorCount() != 0) { System.Threading.Thread.Yield(); } } public void Quit() => GetDTE().Quit(); } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/EditorFeatures/Core/Implementation/NavigationBar/NavigationBarControllerFactoryService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationBar { [Export(typeof(INavigationBarControllerFactoryService))] internal class NavigationBarControllerFactoryService : INavigationBarControllerFactoryService { private readonly IThreadingContext _threadingContext; private readonly IUIThreadOperationExecutor _uIThreadOperationExecutor; private readonly IAsynchronousOperationListener _asyncListener; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public NavigationBarControllerFactoryService( IThreadingContext threadingContext, IUIThreadOperationExecutor uIThreadOperationExecutor, IAsynchronousOperationListenerProvider listenerProvider) { _threadingContext = threadingContext; _uIThreadOperationExecutor = uIThreadOperationExecutor; _asyncListener = listenerProvider.GetListener(FeatureAttribute.NavigationBar); } public IDisposable CreateController(INavigationBarPresenter presenter, ITextBuffer textBuffer) { return new NavigationBarController( _threadingContext, presenter, textBuffer, _uIThreadOperationExecutor, _asyncListener); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationBar { [Export(typeof(INavigationBarControllerFactoryService))] internal class NavigationBarControllerFactoryService : INavigationBarControllerFactoryService { private readonly IThreadingContext _threadingContext; private readonly IUIThreadOperationExecutor _uIThreadOperationExecutor; private readonly IAsynchronousOperationListener _asyncListener; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public NavigationBarControllerFactoryService( IThreadingContext threadingContext, IUIThreadOperationExecutor uIThreadOperationExecutor, IAsynchronousOperationListenerProvider listenerProvider) { _threadingContext = threadingContext; _uIThreadOperationExecutor = uIThreadOperationExecutor; _asyncListener = listenerProvider.GetListener(FeatureAttribute.NavigationBar); } public IDisposable CreateController(INavigationBarPresenter presenter, ITextBuffer textBuffer) { return new NavigationBarController( _threadingContext, presenter, textBuffer, _uIThreadOperationExecutor, _asyncListener); } } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo_Metadata.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal partial class SymbolTreeInfo { private static string GetMetadataNameWithoutBackticks(MetadataReader reader, StringHandle name) { var blobReader = reader.GetBlobReader(name); var backtickIndex = blobReader.IndexOf((byte)'`'); if (backtickIndex == -1) { return reader.GetString(name); } unsafe { return MetadataStringDecoder.DefaultUTF8.GetString( blobReader.CurrentPointer, backtickIndex); } } public static MetadataId GetMetadataIdNoThrow(PortableExecutableReference reference) { try { return reference.GetMetadataId(); } catch (Exception e) when (e is BadImageFormatException or IOException) { return null; } } private static Metadata GetMetadataNoThrow(PortableExecutableReference reference) { try { return reference.GetMetadata(); } catch (Exception e) when (e is BadImageFormatException or IOException) { return null; } } public static ValueTask<SymbolTreeInfo> GetInfoForMetadataReferenceAsync( Solution solution, PortableExecutableReference reference, bool loadOnly, CancellationToken cancellationToken) { var checksum = GetMetadataChecksum(solution, reference, cancellationToken); return GetInfoForMetadataReferenceAsync( solution, reference, checksum, loadOnly, cancellationToken); } /// <summary> /// Produces a <see cref="SymbolTreeInfo"/> for a given <see cref="PortableExecutableReference"/>. /// Note: will never return null; /// </summary> [PerformanceSensitive("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1224834", OftenCompletesSynchronously = true)] public static async ValueTask<SymbolTreeInfo> GetInfoForMetadataReferenceAsync( Solution solution, PortableExecutableReference reference, Checksum checksum, bool loadOnly, CancellationToken cancellationToken) { var metadataId = GetMetadataIdNoThrow(reference); if (metadataId == null) return CreateEmpty(checksum); if (s_metadataIdToInfo.TryGetValue(metadataId, out var infoTask)) { var info = await infoTask.GetValueAsync(cancellationToken).ConfigureAwait(false); if (info.Checksum == checksum) return info; } var metadata = GetMetadataNoThrow(reference); if (metadata == null) return CreateEmpty(checksum); // If the data isn't in the table, and the client only wants the data if already loaded, then bail out as we // have no results to give. The data will eventually populate in memory due to // SymbolTreeInfoIncrementalAnalyzer eventually getting around to loading it. if (loadOnly) return null; var database = solution.Options.GetPersistentStorageDatabase(); return await GetInfoForMetadataReferenceSlowAsync( solution.Workspace.Services, SolutionKey.ToSolutionKey(solution), reference, checksum, database, metadata, cancellationToken).ConfigureAwait(false); } private static async Task<SymbolTreeInfo> GetInfoForMetadataReferenceSlowAsync( HostWorkspaceServices services, SolutionKey solutionKey, PortableExecutableReference reference, Checksum checksum, StorageDatabase database, Metadata metadata, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Important: this captured async lazy may live a long time *without* computing the final results. As such, // it is important that it note capture any large state. For example, it should not hold onto a Solution // instance. var asyncLazy = s_metadataIdToInfo.GetValue( metadata.Id, id => new AsyncLazy<SymbolTreeInfo>( c => TryCreateMetadataSymbolTreeInfoAsync(services, solutionKey, reference, checksum, database, c), cacheResult: true)); return await asyncLazy.GetValueAsync(cancellationToken).ConfigureAwait(false); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/33131", AllowCaptures = false)] public static Checksum GetMetadataChecksum( Solution solution, PortableExecutableReference reference, CancellationToken cancellationToken) { // We can reuse the index for any given reference as long as it hasn't changed. // So our checksum is just the checksum for the PEReference itself. // First see if the value is already in the cache, to avoid an allocation if possible. if (ChecksumCache.TryGetValue(reference, out var cached)) { return cached; } // Break things up to the fast path above and this slow path where we allocate a closure. return GetMetadataChecksumSlow(solution, reference, cancellationToken); } private static Checksum GetMetadataChecksumSlow(Solution solution, PortableExecutableReference reference, CancellationToken cancellationToken) { return ChecksumCache.GetOrCreate(reference, _ => { var serializer = solution.Workspace.Services.GetService<ISerializerService>(); var checksum = serializer.CreateChecksum(reference, cancellationToken); // Include serialization format version in our checksum. That way if the // version ever changes, all persisted data won't match the current checksum // we expect, and we'll recompute things. return Checksum.Create(checksum, SerializationFormatChecksum); }); } private static Task<SymbolTreeInfo> TryCreateMetadataSymbolTreeInfoAsync( HostWorkspaceServices services, SolutionKey solutionKey, PortableExecutableReference reference, Checksum checksum, StorageDatabase database, CancellationToken cancellationToken) { var filePath = reference.FilePath; var result = TryLoadOrCreateAsync( services, solutionKey, checksum, database, loadOnly: false, createAsync: () => CreateMetadataSymbolTreeInfoAsync(services, solutionKey, checksum, database, reference), keySuffix: "_Metadata_" + filePath, tryReadObject: reader => TryReadSymbolTreeInfo(reader, checksum, nodes => GetSpellCheckerAsync(services, solutionKey, checksum, database, filePath, nodes)), cancellationToken: cancellationToken); Contract.ThrowIfNull(result); return result; } private static Task<SymbolTreeInfo> CreateMetadataSymbolTreeInfoAsync( HostWorkspaceServices services, SolutionKey solutionKey, Checksum checksum, StorageDatabase database, PortableExecutableReference reference) { var creator = new MetadataInfoCreator(services, solutionKey, checksum, database, reference); return Task.FromResult(creator.Create()); } private struct MetadataInfoCreator : IDisposable { private static readonly Predicate<string> s_isNotNullOrEmpty = s => !string.IsNullOrEmpty(s); private static readonly ObjectPool<List<string>> s_stringListPool = SharedPools.Default<List<string>>(); private readonly HostWorkspaceServices _services; private readonly SolutionKey _solutionKey; private readonly Checksum _checksum; private readonly StorageDatabase _database; private readonly PortableExecutableReference _reference; private readonly OrderPreservingMultiDictionary<string, string> _inheritanceMap; private readonly OrderPreservingMultiDictionary<MetadataNode, MetadataNode> _parentToChildren; private readonly MetadataNode _rootNode; // The metadata reader for the current metadata in the PEReference. private MetadataReader _metadataReader; // The set of type definitions we've read out of the current metadata reader. private readonly List<MetadataDefinition> _allTypeDefinitions; // Map from node represents extension method to list of possible parameter type info. // We can have more than one if there's multiple methods with same name but different receiver type. // e.g. // // public static bool AnotherExtensionMethod1(this int x); // public static bool AnotherExtensionMethod1(this bool x); // private readonly MultiDictionary<MetadataNode, ParameterTypeInfo> _extensionMethodToParameterTypeInfo; private bool _containsExtensionsMethod; public MetadataInfoCreator( HostWorkspaceServices services, SolutionKey solutionKey, Checksum checksum, StorageDatabase database, PortableExecutableReference reference) { _services = services; _solutionKey = solutionKey; _checksum = checksum; _database = database; _reference = reference; _metadataReader = null; _allTypeDefinitions = new List<MetadataDefinition>(); _containsExtensionsMethod = false; _inheritanceMap = OrderPreservingMultiDictionary<string, string>.GetInstance(); _parentToChildren = OrderPreservingMultiDictionary<MetadataNode, MetadataNode>.GetInstance(); _extensionMethodToParameterTypeInfo = new MultiDictionary<MetadataNode, ParameterTypeInfo>(); _rootNode = MetadataNode.Allocate(name: ""); } private static ImmutableArray<ModuleMetadata> GetModuleMetadata(Metadata metadata) { try { if (metadata is AssemblyMetadata assembly) { return assembly.GetModules(); } else if (metadata is ModuleMetadata module) { return ImmutableArray.Create(module); } } catch (BadImageFormatException) { // Trying to get the modules of an assembly can throw. For example, if // there is an invalid public-key defined for the assembly. See: // https://devdiv.visualstudio.com/DevDiv/_workitems?id=234447 } return ImmutableArray<ModuleMetadata>.Empty; } internal SymbolTreeInfo Create() { foreach (var moduleMetadata in GetModuleMetadata(GetMetadataNoThrow(_reference))) { try { _metadataReader = moduleMetadata.GetMetadataReader(); // First, walk all the symbols from metadata, populating the parentToChilren // map accordingly. GenerateMetadataNodes(); // Now, once we populated the initial map, go and get all the inheritance // information for all the types in the metadata. This may refer to // types that we haven't seen yet. We'll add those types to the parentToChildren // map accordingly. PopulateInheritanceMap(); // Clear the set of type definitions we read out of this piece of metadata. _allTypeDefinitions.Clear(); } catch (BadImageFormatException) { // any operation off metadata can throw BadImageFormatException continue; } } var extensionMethodsMap = new MultiDictionary<string, ExtensionMethodInfo>(); var unsortedNodes = GenerateUnsortedNodes(extensionMethodsMap); return CreateSymbolTreeInfo( _services, _solutionKey, _checksum, _database, _reference.FilePath, unsortedNodes, _inheritanceMap, extensionMethodsMap); } public void Dispose() { // Return all the metadata nodes back to the pool so that they can be // used for the next PEReference we read. foreach (var (_, children) in _parentToChildren) { foreach (var child in children) MetadataNode.Free(child); } MetadataNode.Free(_rootNode); _parentToChildren.Free(); _inheritanceMap.Free(); } private void GenerateMetadataNodes() { var globalNamespace = _metadataReader.GetNamespaceDefinitionRoot(); var definitionMap = OrderPreservingMultiDictionary<string, MetadataDefinition>.GetInstance(); try { LookupMetadataDefinitions(globalNamespace, definitionMap); foreach (var (name, definitions) in definitionMap) GenerateMetadataNodes(_rootNode, name, definitions); } finally { definitionMap.Free(); } } private void GenerateMetadataNodes( MetadataNode parentNode, string nodeName, OrderPreservingMultiDictionary<string, MetadataDefinition>.ValueSet definitionsWithSameName) { if (!UnicodeCharacterUtilities.IsValidIdentifier(nodeName)) { return; } var childNode = MetadataNode.Allocate(nodeName); _parentToChildren.Add(parentNode, childNode); // Add all child members var definitionMap = OrderPreservingMultiDictionary<string, MetadataDefinition>.GetInstance(); try { foreach (var definition in definitionsWithSameName) { if (definition.Kind == MetadataDefinitionKind.Member) { // We need to support having multiple methods with same name but different receiver type. _extensionMethodToParameterTypeInfo.Add(childNode, definition.ReceiverTypeInfo); } LookupMetadataDefinitions(definition, definitionMap); } foreach (var (name, definitions) in definitionMap) GenerateMetadataNodes(childNode, name, definitions); } finally { definitionMap.Free(); } } private void LookupMetadataDefinitions( MetadataDefinition definition, OrderPreservingMultiDictionary<string, MetadataDefinition> definitionMap) { switch (definition.Kind) { case MetadataDefinitionKind.Namespace: LookupMetadataDefinitions(definition.Namespace, definitionMap); break; case MetadataDefinitionKind.Type: LookupMetadataDefinitions(definition.Type, definitionMap); break; } } private void LookupMetadataDefinitions( TypeDefinition typeDefinition, OrderPreservingMultiDictionary<string, MetadataDefinition> definitionMap) { // Only bother looking for extension methods in static types. // Note this check means we would ignore extension methods declared in assemblies // compiled from VB code, since a module in VB is compiled into class with // "sealed" attribute but not "abstract". // Although this can be addressed by checking custom attributes, // we believe this is not a common scenario to warrant potential perf impact. if ((typeDefinition.Attributes & TypeAttributes.Abstract) != 0 && (typeDefinition.Attributes & TypeAttributes.Sealed) != 0) { foreach (var child in typeDefinition.GetMethods()) { var method = _metadataReader.GetMethodDefinition(child); if ((method.Attributes & MethodAttributes.SpecialName) != 0 || (method.Attributes & MethodAttributes.RTSpecialName) != 0) { continue; } // SymbolTreeInfo is only searched for types and extension methods. // So we don't want to pull in all methods here. As a simple approximation // we just pull in methods that have attributes on them. if ((method.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public && (method.Attributes & MethodAttributes.Static) != 0 && method.GetParameters().Count > 0 && method.GetCustomAttributes().Count > 0) { // Decode method signature to get the receiver type name (i.e. type name for the first parameter) var blob = _metadataReader.GetBlobReader(method.Signature); var decoder = new SignatureDecoder<ParameterTypeInfo, object>(ParameterTypeInfoProvider.Instance, _metadataReader, genericContext: null); var signature = decoder.DecodeMethodSignature(ref blob); // It'd be good if we don't need to go through all parameters and make unnecessary allocations. // However, this is not possible with meatadata reader API right now (although it's possible by copying code from meatadata reader implementaion) if (signature.ParameterTypes.Length > 0) { _containsExtensionsMethod = true; var firstParameterTypeInfo = signature.ParameterTypes[0]; var definition = new MetadataDefinition(MetadataDefinitionKind.Member, _metadataReader.GetString(method.Name), firstParameterTypeInfo); definitionMap.Add(definition.Name, definition); } } } } foreach (var child in typeDefinition.GetNestedTypes()) { var type = _metadataReader.GetTypeDefinition(child); // We don't include internals from metadata assemblies. It's less likely that // a project would have IVT to it and so it helps us save on memory. It also // means we can avoid loading lots and lots of obfuscated code in the case the // dll was obfuscated. if (IsPublic(type.Attributes)) { var definition = MetadataDefinition.Create(_metadataReader, type); definitionMap.Add(definition.Name, definition); _allTypeDefinitions.Add(definition); } } } private void LookupMetadataDefinitions( NamespaceDefinition namespaceDefinition, OrderPreservingMultiDictionary<string, MetadataDefinition> definitionMap) { foreach (var child in namespaceDefinition.NamespaceDefinitions) { var definition = MetadataDefinition.Create(_metadataReader, child); definitionMap.Add(definition.Name, definition); } foreach (var child in namespaceDefinition.TypeDefinitions) { var typeDefinition = _metadataReader.GetTypeDefinition(child); if (IsPublic(typeDefinition.Attributes)) { var definition = MetadataDefinition.Create(_metadataReader, typeDefinition); definitionMap.Add(definition.Name, definition); _allTypeDefinitions.Add(definition); } } } private static bool IsPublic(TypeAttributes attributes) { var masked = attributes & TypeAttributes.VisibilityMask; return masked is TypeAttributes.Public or TypeAttributes.NestedPublic; } private void PopulateInheritanceMap() { foreach (var typeDefinition in _allTypeDefinitions) { Debug.Assert(typeDefinition.Kind == MetadataDefinitionKind.Type); PopulateInheritance(typeDefinition); } } private void PopulateInheritance(MetadataDefinition metadataTypeDefinition) { var derivedTypeDefinition = metadataTypeDefinition.Type; var interfaceImplHandles = derivedTypeDefinition.GetInterfaceImplementations(); if (derivedTypeDefinition.BaseType.IsNil && interfaceImplHandles.Count == 0) { return; } var derivedTypeSimpleName = metadataTypeDefinition.Name; PopulateInheritance(derivedTypeSimpleName, derivedTypeDefinition.BaseType); foreach (var interfaceImplHandle in interfaceImplHandles) { if (!interfaceImplHandle.IsNil) { var interfaceImpl = _metadataReader.GetInterfaceImplementation(interfaceImplHandle); PopulateInheritance(derivedTypeSimpleName, interfaceImpl.Interface); } } } private void PopulateInheritance( string derivedTypeSimpleName, EntityHandle baseTypeOrInterfaceHandle) { if (baseTypeOrInterfaceHandle.IsNil) { return; } var baseTypeNameParts = s_stringListPool.Allocate(); try { AddBaseTypeNameParts(baseTypeOrInterfaceHandle, baseTypeNameParts); if (baseTypeNameParts.Count > 0 && baseTypeNameParts.TrueForAll(s_isNotNullOrEmpty)) { var lastPart = baseTypeNameParts.Last(); if (!_inheritanceMap.Contains(lastPart, derivedTypeSimpleName)) { _inheritanceMap.Add(baseTypeNameParts.Last(), derivedTypeSimpleName); } // The parent/child map may not know about this base-type yet (for example, // if the base type is a reference to a type outside of this assembly). // Add the base type to our map so we'll be able to resolve it later if // requested. EnsureParentsAndChildren(baseTypeNameParts); } } finally { s_stringListPool.ClearAndFree(baseTypeNameParts); } } private void AddBaseTypeNameParts( EntityHandle baseTypeOrInterfaceHandle, List<string> simpleNames) { var typeDefOrRefHandle = GetTypeDefOrRefHandle(baseTypeOrInterfaceHandle); if (typeDefOrRefHandle.Kind == HandleKind.TypeDefinition) { AddTypeDefinitionNameParts((TypeDefinitionHandle)typeDefOrRefHandle, simpleNames); } else if (typeDefOrRefHandle.Kind == HandleKind.TypeReference) { AddTypeReferenceNameParts((TypeReferenceHandle)typeDefOrRefHandle, simpleNames); } } private void AddTypeDefinitionNameParts( TypeDefinitionHandle handle, List<string> simpleNames) { var typeDefinition = _metadataReader.GetTypeDefinition(handle); var declaringType = typeDefinition.GetDeclaringType(); if (declaringType.IsNil) { // Not a nested type, just add the containing namespace. AddNamespaceParts(typeDefinition.NamespaceDefinition, simpleNames); } else { // We're a nested type, recurse and add the type we're declared in. // It will handle adding the namespace properly. AddTypeDefinitionNameParts(declaringType, simpleNames); } // Now add the simple name of the type itself. simpleNames.Add(GetMetadataNameWithoutBackticks(_metadataReader, typeDefinition.Name)); } private void AddNamespaceParts( StringHandle namespaceHandle, List<string> simpleNames) { var blobReader = _metadataReader.GetBlobReader(namespaceHandle); while (true) { var dotIndex = blobReader.IndexOf((byte)'.'); unsafe { // Note: we won't get any string sharing as we're just using the // default string decoded. However, that's ok. We only produce // these strings when we first read metadata. Then we create and // persist our own index. In the future when we read in that index // there's no way for us to share strings between us and the // compiler at that point. if (dotIndex == -1) { simpleNames.Add(MetadataStringDecoder.DefaultUTF8.GetString( blobReader.CurrentPointer, blobReader.RemainingBytes)); return; } else { simpleNames.Add(MetadataStringDecoder.DefaultUTF8.GetString( blobReader.CurrentPointer, dotIndex)); blobReader.Offset += dotIndex + 1; } } } } private void AddNamespaceParts( NamespaceDefinitionHandle namespaceHandle, List<string> simpleNames) { if (namespaceHandle.IsNil) { return; } var namespaceDefinition = _metadataReader.GetNamespaceDefinition(namespaceHandle); AddNamespaceParts(namespaceDefinition.Parent, simpleNames); simpleNames.Add(_metadataReader.GetString(namespaceDefinition.Name)); } private void AddTypeReferenceNameParts(TypeReferenceHandle handle, List<string> simpleNames) { var typeReference = _metadataReader.GetTypeReference(handle); AddNamespaceParts(typeReference.Namespace, simpleNames); simpleNames.Add(GetMetadataNameWithoutBackticks(_metadataReader, typeReference.Name)); } private EntityHandle GetTypeDefOrRefHandle(EntityHandle baseTypeOrInterfaceHandle) { switch (baseTypeOrInterfaceHandle.Kind) { case HandleKind.TypeDefinition: case HandleKind.TypeReference: return baseTypeOrInterfaceHandle; case HandleKind.TypeSpecification: return FirstEntityHandleProvider.Instance.GetTypeFromSpecification( _metadataReader, (TypeSpecificationHandle)baseTypeOrInterfaceHandle); default: return default; } } private void EnsureParentsAndChildren(List<string> simpleNames) { var currentNode = _rootNode; foreach (var simpleName in simpleNames) { var childNode = GetOrCreateChildNode(currentNode, simpleName); currentNode = childNode; } } private MetadataNode GetOrCreateChildNode( MetadataNode currentNode, string simpleName) { if (_parentToChildren.TryGetValue(currentNode, static (childNode, simpleName) => childNode.Name == simpleName, simpleName, out var childNode)) { // Found an existing child node. Just return that and all // future parts off of it. return childNode; } // Couldn't find a child node with this name. Make a new node for // it and return that for all future parts to be added to. var newChildNode = MetadataNode.Allocate(simpleName); _parentToChildren.Add(currentNode, newChildNode); return newChildNode; } private ImmutableArray<BuilderNode> GenerateUnsortedNodes(MultiDictionary<string, ExtensionMethodInfo> receiverTypeNameToMethodMap) { var unsortedNodes = ArrayBuilder<BuilderNode>.GetInstance(); unsortedNodes.Add(BuilderNode.RootNode); AddUnsortedNodes(unsortedNodes, receiverTypeNameToMethodMap, parentNode: _rootNode, parentIndex: 0, fullyQualifiedContainerName: _containsExtensionsMethod ? "" : null); return unsortedNodes.ToImmutableAndFree(); } private void AddUnsortedNodes(ArrayBuilder<BuilderNode> unsortedNodes, MultiDictionary<string, ExtensionMethodInfo> receiverTypeNameToMethodMap, MetadataNode parentNode, int parentIndex, string fullyQualifiedContainerName) { foreach (var child in _parentToChildren[parentNode]) { var childNode = new BuilderNode(child.Name, parentIndex, _extensionMethodToParameterTypeInfo[child]); var childIndex = unsortedNodes.Count; unsortedNodes.Add(childNode); if (fullyQualifiedContainerName != null) { foreach (var parameterTypeInfo in _extensionMethodToParameterTypeInfo[child]) { // We do not differentiate array of different kinds for simplicity. // e.g. int[], int[][], int[,], etc. are all represented as int[] in the index. // similar for complex receiver types, "[]" means it's an array type, "" otherwise. var parameterTypeName = (parameterTypeInfo.IsComplexType, parameterTypeInfo.IsArray) switch { (true, true) => Extensions.ComplexArrayReceiverTypeName, // complex array type, e.g. "T[,]" (true, false) => Extensions.ComplexReceiverTypeName, // complex non-array type, e.g. "T" (false, true) => parameterTypeInfo.Name + Extensions.ArrayReceiverTypeNameSuffix, // simple array type, e.g. "int[][,]" (false, false) => parameterTypeInfo.Name // simple non-array type, e.g. "int" }; receiverTypeNameToMethodMap.Add(parameterTypeName, new ExtensionMethodInfo(fullyQualifiedContainerName, child.Name)); } } AddUnsortedNodes(unsortedNodes, receiverTypeNameToMethodMap, child, childIndex, Concat(fullyQualifiedContainerName, child.Name)); } static string Concat(string containerName, string name) { if (containerName == null) { return null; } if (containerName.Length == 0) { return name; } return containerName + "." + name; } } } private class MetadataNode { public string Name { get; private set; } private static readonly ObjectPool<MetadataNode> s_pool = SharedPools.Default<MetadataNode>(); public static MetadataNode Allocate(string name) { var node = s_pool.Allocate(); Debug.Assert(node.Name == null); node.Name = name; return node; } public static void Free(MetadataNode node) { Debug.Assert(node.Name != null); node.Name = null; s_pool.Free(node); } } private enum MetadataDefinitionKind { Namespace, Type, Member, } private struct MetadataDefinition { public string Name { get; } public MetadataDefinitionKind Kind { get; } /// <summary> /// Only applies to member kind. Represents the type info of the first parameter. /// </summary> public ParameterTypeInfo ReceiverTypeInfo { get; } public NamespaceDefinition Namespace { get; private set; } public TypeDefinition Type { get; private set; } public MetadataDefinition(MetadataDefinitionKind kind, string name, ParameterTypeInfo receiverTypeInfo = default) : this() { Kind = kind; Name = name; ReceiverTypeInfo = receiverTypeInfo; } public static MetadataDefinition Create( MetadataReader reader, NamespaceDefinitionHandle namespaceHandle) { var definition = reader.GetNamespaceDefinition(namespaceHandle); return new MetadataDefinition( MetadataDefinitionKind.Namespace, reader.GetString(definition.Name)) { Namespace = definition }; } public static MetadataDefinition Create( MetadataReader reader, TypeDefinition definition) { var typeName = GetMetadataNameWithoutBackticks(reader, definition.Name); return new MetadataDefinition(MetadataDefinitionKind.Type, typeName) { Type = definition }; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal partial class SymbolTreeInfo { private static string GetMetadataNameWithoutBackticks(MetadataReader reader, StringHandle name) { var blobReader = reader.GetBlobReader(name); var backtickIndex = blobReader.IndexOf((byte)'`'); if (backtickIndex == -1) { return reader.GetString(name); } unsafe { return MetadataStringDecoder.DefaultUTF8.GetString( blobReader.CurrentPointer, backtickIndex); } } public static MetadataId GetMetadataIdNoThrow(PortableExecutableReference reference) { try { return reference.GetMetadataId(); } catch (Exception e) when (e is BadImageFormatException or IOException) { return null; } } private static Metadata GetMetadataNoThrow(PortableExecutableReference reference) { try { return reference.GetMetadata(); } catch (Exception e) when (e is BadImageFormatException or IOException) { return null; } } public static ValueTask<SymbolTreeInfo> GetInfoForMetadataReferenceAsync( Solution solution, PortableExecutableReference reference, bool loadOnly, CancellationToken cancellationToken) { var checksum = GetMetadataChecksum(solution, reference, cancellationToken); return GetInfoForMetadataReferenceAsync( solution, reference, checksum, loadOnly, cancellationToken); } /// <summary> /// Produces a <see cref="SymbolTreeInfo"/> for a given <see cref="PortableExecutableReference"/>. /// Note: will never return null; /// </summary> [PerformanceSensitive("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1224834", OftenCompletesSynchronously = true)] public static async ValueTask<SymbolTreeInfo> GetInfoForMetadataReferenceAsync( Solution solution, PortableExecutableReference reference, Checksum checksum, bool loadOnly, CancellationToken cancellationToken) { var metadataId = GetMetadataIdNoThrow(reference); if (metadataId == null) return CreateEmpty(checksum); if (s_metadataIdToInfo.TryGetValue(metadataId, out var infoTask)) { var info = await infoTask.GetValueAsync(cancellationToken).ConfigureAwait(false); if (info.Checksum == checksum) return info; } var metadata = GetMetadataNoThrow(reference); if (metadata == null) return CreateEmpty(checksum); // If the data isn't in the table, and the client only wants the data if already loaded, then bail out as we // have no results to give. The data will eventually populate in memory due to // SymbolTreeInfoIncrementalAnalyzer eventually getting around to loading it. if (loadOnly) return null; var database = solution.Options.GetPersistentStorageDatabase(); return await GetInfoForMetadataReferenceSlowAsync( solution.Workspace.Services, SolutionKey.ToSolutionKey(solution), reference, checksum, database, metadata, cancellationToken).ConfigureAwait(false); } private static async Task<SymbolTreeInfo> GetInfoForMetadataReferenceSlowAsync( HostWorkspaceServices services, SolutionKey solutionKey, PortableExecutableReference reference, Checksum checksum, StorageDatabase database, Metadata metadata, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Important: this captured async lazy may live a long time *without* computing the final results. As such, // it is important that it note capture any large state. For example, it should not hold onto a Solution // instance. var asyncLazy = s_metadataIdToInfo.GetValue( metadata.Id, id => new AsyncLazy<SymbolTreeInfo>( c => TryCreateMetadataSymbolTreeInfoAsync(services, solutionKey, reference, checksum, database, c), cacheResult: true)); return await asyncLazy.GetValueAsync(cancellationToken).ConfigureAwait(false); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/33131", AllowCaptures = false)] public static Checksum GetMetadataChecksum( Solution solution, PortableExecutableReference reference, CancellationToken cancellationToken) { // We can reuse the index for any given reference as long as it hasn't changed. // So our checksum is just the checksum for the PEReference itself. // First see if the value is already in the cache, to avoid an allocation if possible. if (ChecksumCache.TryGetValue(reference, out var cached)) { return cached; } // Break things up to the fast path above and this slow path where we allocate a closure. return GetMetadataChecksumSlow(solution, reference, cancellationToken); } private static Checksum GetMetadataChecksumSlow(Solution solution, PortableExecutableReference reference, CancellationToken cancellationToken) { return ChecksumCache.GetOrCreate(reference, _ => { var serializer = solution.Workspace.Services.GetService<ISerializerService>(); var checksum = serializer.CreateChecksum(reference, cancellationToken); // Include serialization format version in our checksum. That way if the // version ever changes, all persisted data won't match the current checksum // we expect, and we'll recompute things. return Checksum.Create(checksum, SerializationFormatChecksum); }); } private static Task<SymbolTreeInfo> TryCreateMetadataSymbolTreeInfoAsync( HostWorkspaceServices services, SolutionKey solutionKey, PortableExecutableReference reference, Checksum checksum, StorageDatabase database, CancellationToken cancellationToken) { var filePath = reference.FilePath; var result = TryLoadOrCreateAsync( services, solutionKey, checksum, database, loadOnly: false, createAsync: () => CreateMetadataSymbolTreeInfoAsync(services, solutionKey, checksum, database, reference), keySuffix: "_Metadata_" + filePath, tryReadObject: reader => TryReadSymbolTreeInfo(reader, checksum, nodes => GetSpellCheckerAsync(services, solutionKey, checksum, database, filePath, nodes)), cancellationToken: cancellationToken); Contract.ThrowIfNull(result); return result; } private static Task<SymbolTreeInfo> CreateMetadataSymbolTreeInfoAsync( HostWorkspaceServices services, SolutionKey solutionKey, Checksum checksum, StorageDatabase database, PortableExecutableReference reference) { var creator = new MetadataInfoCreator(services, solutionKey, checksum, database, reference); return Task.FromResult(creator.Create()); } private struct MetadataInfoCreator : IDisposable { private static readonly Predicate<string> s_isNotNullOrEmpty = s => !string.IsNullOrEmpty(s); private static readonly ObjectPool<List<string>> s_stringListPool = SharedPools.Default<List<string>>(); private readonly HostWorkspaceServices _services; private readonly SolutionKey _solutionKey; private readonly Checksum _checksum; private readonly StorageDatabase _database; private readonly PortableExecutableReference _reference; private readonly OrderPreservingMultiDictionary<string, string> _inheritanceMap; private readonly OrderPreservingMultiDictionary<MetadataNode, MetadataNode> _parentToChildren; private readonly MetadataNode _rootNode; // The metadata reader for the current metadata in the PEReference. private MetadataReader _metadataReader; // The set of type definitions we've read out of the current metadata reader. private readonly List<MetadataDefinition> _allTypeDefinitions; // Map from node represents extension method to list of possible parameter type info. // We can have more than one if there's multiple methods with same name but different receiver type. // e.g. // // public static bool AnotherExtensionMethod1(this int x); // public static bool AnotherExtensionMethod1(this bool x); // private readonly MultiDictionary<MetadataNode, ParameterTypeInfo> _extensionMethodToParameterTypeInfo; private bool _containsExtensionsMethod; public MetadataInfoCreator( HostWorkspaceServices services, SolutionKey solutionKey, Checksum checksum, StorageDatabase database, PortableExecutableReference reference) { _services = services; _solutionKey = solutionKey; _checksum = checksum; _database = database; _reference = reference; _metadataReader = null; _allTypeDefinitions = new List<MetadataDefinition>(); _containsExtensionsMethod = false; _inheritanceMap = OrderPreservingMultiDictionary<string, string>.GetInstance(); _parentToChildren = OrderPreservingMultiDictionary<MetadataNode, MetadataNode>.GetInstance(); _extensionMethodToParameterTypeInfo = new MultiDictionary<MetadataNode, ParameterTypeInfo>(); _rootNode = MetadataNode.Allocate(name: ""); } private static ImmutableArray<ModuleMetadata> GetModuleMetadata(Metadata metadata) { try { if (metadata is AssemblyMetadata assembly) { return assembly.GetModules(); } else if (metadata is ModuleMetadata module) { return ImmutableArray.Create(module); } } catch (BadImageFormatException) { // Trying to get the modules of an assembly can throw. For example, if // there is an invalid public-key defined for the assembly. See: // https://devdiv.visualstudio.com/DevDiv/_workitems?id=234447 } return ImmutableArray<ModuleMetadata>.Empty; } internal SymbolTreeInfo Create() { foreach (var moduleMetadata in GetModuleMetadata(GetMetadataNoThrow(_reference))) { try { _metadataReader = moduleMetadata.GetMetadataReader(); // First, walk all the symbols from metadata, populating the parentToChilren // map accordingly. GenerateMetadataNodes(); // Now, once we populated the initial map, go and get all the inheritance // information for all the types in the metadata. This may refer to // types that we haven't seen yet. We'll add those types to the parentToChildren // map accordingly. PopulateInheritanceMap(); // Clear the set of type definitions we read out of this piece of metadata. _allTypeDefinitions.Clear(); } catch (BadImageFormatException) { // any operation off metadata can throw BadImageFormatException continue; } } var extensionMethodsMap = new MultiDictionary<string, ExtensionMethodInfo>(); var unsortedNodes = GenerateUnsortedNodes(extensionMethodsMap); return CreateSymbolTreeInfo( _services, _solutionKey, _checksum, _database, _reference.FilePath, unsortedNodes, _inheritanceMap, extensionMethodsMap); } public void Dispose() { // Return all the metadata nodes back to the pool so that they can be // used for the next PEReference we read. foreach (var (_, children) in _parentToChildren) { foreach (var child in children) MetadataNode.Free(child); } MetadataNode.Free(_rootNode); _parentToChildren.Free(); _inheritanceMap.Free(); } private void GenerateMetadataNodes() { var globalNamespace = _metadataReader.GetNamespaceDefinitionRoot(); var definitionMap = OrderPreservingMultiDictionary<string, MetadataDefinition>.GetInstance(); try { LookupMetadataDefinitions(globalNamespace, definitionMap); foreach (var (name, definitions) in definitionMap) GenerateMetadataNodes(_rootNode, name, definitions); } finally { definitionMap.Free(); } } private void GenerateMetadataNodes( MetadataNode parentNode, string nodeName, OrderPreservingMultiDictionary<string, MetadataDefinition>.ValueSet definitionsWithSameName) { if (!UnicodeCharacterUtilities.IsValidIdentifier(nodeName)) { return; } var childNode = MetadataNode.Allocate(nodeName); _parentToChildren.Add(parentNode, childNode); // Add all child members var definitionMap = OrderPreservingMultiDictionary<string, MetadataDefinition>.GetInstance(); try { foreach (var definition in definitionsWithSameName) { if (definition.Kind == MetadataDefinitionKind.Member) { // We need to support having multiple methods with same name but different receiver type. _extensionMethodToParameterTypeInfo.Add(childNode, definition.ReceiverTypeInfo); } LookupMetadataDefinitions(definition, definitionMap); } foreach (var (name, definitions) in definitionMap) GenerateMetadataNodes(childNode, name, definitions); } finally { definitionMap.Free(); } } private void LookupMetadataDefinitions( MetadataDefinition definition, OrderPreservingMultiDictionary<string, MetadataDefinition> definitionMap) { switch (definition.Kind) { case MetadataDefinitionKind.Namespace: LookupMetadataDefinitions(definition.Namespace, definitionMap); break; case MetadataDefinitionKind.Type: LookupMetadataDefinitions(definition.Type, definitionMap); break; } } private void LookupMetadataDefinitions( TypeDefinition typeDefinition, OrderPreservingMultiDictionary<string, MetadataDefinition> definitionMap) { // Only bother looking for extension methods in static types. // Note this check means we would ignore extension methods declared in assemblies // compiled from VB code, since a module in VB is compiled into class with // "sealed" attribute but not "abstract". // Although this can be addressed by checking custom attributes, // we believe this is not a common scenario to warrant potential perf impact. if ((typeDefinition.Attributes & TypeAttributes.Abstract) != 0 && (typeDefinition.Attributes & TypeAttributes.Sealed) != 0) { foreach (var child in typeDefinition.GetMethods()) { var method = _metadataReader.GetMethodDefinition(child); if ((method.Attributes & MethodAttributes.SpecialName) != 0 || (method.Attributes & MethodAttributes.RTSpecialName) != 0) { continue; } // SymbolTreeInfo is only searched for types and extension methods. // So we don't want to pull in all methods here. As a simple approximation // we just pull in methods that have attributes on them. if ((method.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public && (method.Attributes & MethodAttributes.Static) != 0 && method.GetParameters().Count > 0 && method.GetCustomAttributes().Count > 0) { // Decode method signature to get the receiver type name (i.e. type name for the first parameter) var blob = _metadataReader.GetBlobReader(method.Signature); var decoder = new SignatureDecoder<ParameterTypeInfo, object>(ParameterTypeInfoProvider.Instance, _metadataReader, genericContext: null); var signature = decoder.DecodeMethodSignature(ref blob); // It'd be good if we don't need to go through all parameters and make unnecessary allocations. // However, this is not possible with meatadata reader API right now (although it's possible by copying code from meatadata reader implementaion) if (signature.ParameterTypes.Length > 0) { _containsExtensionsMethod = true; var firstParameterTypeInfo = signature.ParameterTypes[0]; var definition = new MetadataDefinition(MetadataDefinitionKind.Member, _metadataReader.GetString(method.Name), firstParameterTypeInfo); definitionMap.Add(definition.Name, definition); } } } } foreach (var child in typeDefinition.GetNestedTypes()) { var type = _metadataReader.GetTypeDefinition(child); // We don't include internals from metadata assemblies. It's less likely that // a project would have IVT to it and so it helps us save on memory. It also // means we can avoid loading lots and lots of obfuscated code in the case the // dll was obfuscated. if (IsPublic(type.Attributes)) { var definition = MetadataDefinition.Create(_metadataReader, type); definitionMap.Add(definition.Name, definition); _allTypeDefinitions.Add(definition); } } } private void LookupMetadataDefinitions( NamespaceDefinition namespaceDefinition, OrderPreservingMultiDictionary<string, MetadataDefinition> definitionMap) { foreach (var child in namespaceDefinition.NamespaceDefinitions) { var definition = MetadataDefinition.Create(_metadataReader, child); definitionMap.Add(definition.Name, definition); } foreach (var child in namespaceDefinition.TypeDefinitions) { var typeDefinition = _metadataReader.GetTypeDefinition(child); if (IsPublic(typeDefinition.Attributes)) { var definition = MetadataDefinition.Create(_metadataReader, typeDefinition); definitionMap.Add(definition.Name, definition); _allTypeDefinitions.Add(definition); } } } private static bool IsPublic(TypeAttributes attributes) { var masked = attributes & TypeAttributes.VisibilityMask; return masked is TypeAttributes.Public or TypeAttributes.NestedPublic; } private void PopulateInheritanceMap() { foreach (var typeDefinition in _allTypeDefinitions) { Debug.Assert(typeDefinition.Kind == MetadataDefinitionKind.Type); PopulateInheritance(typeDefinition); } } private void PopulateInheritance(MetadataDefinition metadataTypeDefinition) { var derivedTypeDefinition = metadataTypeDefinition.Type; var interfaceImplHandles = derivedTypeDefinition.GetInterfaceImplementations(); if (derivedTypeDefinition.BaseType.IsNil && interfaceImplHandles.Count == 0) { return; } var derivedTypeSimpleName = metadataTypeDefinition.Name; PopulateInheritance(derivedTypeSimpleName, derivedTypeDefinition.BaseType); foreach (var interfaceImplHandle in interfaceImplHandles) { if (!interfaceImplHandle.IsNil) { var interfaceImpl = _metadataReader.GetInterfaceImplementation(interfaceImplHandle); PopulateInheritance(derivedTypeSimpleName, interfaceImpl.Interface); } } } private void PopulateInheritance( string derivedTypeSimpleName, EntityHandle baseTypeOrInterfaceHandle) { if (baseTypeOrInterfaceHandle.IsNil) { return; } var baseTypeNameParts = s_stringListPool.Allocate(); try { AddBaseTypeNameParts(baseTypeOrInterfaceHandle, baseTypeNameParts); if (baseTypeNameParts.Count > 0 && baseTypeNameParts.TrueForAll(s_isNotNullOrEmpty)) { var lastPart = baseTypeNameParts.Last(); if (!_inheritanceMap.Contains(lastPart, derivedTypeSimpleName)) { _inheritanceMap.Add(baseTypeNameParts.Last(), derivedTypeSimpleName); } // The parent/child map may not know about this base-type yet (for example, // if the base type is a reference to a type outside of this assembly). // Add the base type to our map so we'll be able to resolve it later if // requested. EnsureParentsAndChildren(baseTypeNameParts); } } finally { s_stringListPool.ClearAndFree(baseTypeNameParts); } } private void AddBaseTypeNameParts( EntityHandle baseTypeOrInterfaceHandle, List<string> simpleNames) { var typeDefOrRefHandle = GetTypeDefOrRefHandle(baseTypeOrInterfaceHandle); if (typeDefOrRefHandle.Kind == HandleKind.TypeDefinition) { AddTypeDefinitionNameParts((TypeDefinitionHandle)typeDefOrRefHandle, simpleNames); } else if (typeDefOrRefHandle.Kind == HandleKind.TypeReference) { AddTypeReferenceNameParts((TypeReferenceHandle)typeDefOrRefHandle, simpleNames); } } private void AddTypeDefinitionNameParts( TypeDefinitionHandle handle, List<string> simpleNames) { var typeDefinition = _metadataReader.GetTypeDefinition(handle); var declaringType = typeDefinition.GetDeclaringType(); if (declaringType.IsNil) { // Not a nested type, just add the containing namespace. AddNamespaceParts(typeDefinition.NamespaceDefinition, simpleNames); } else { // We're a nested type, recurse and add the type we're declared in. // It will handle adding the namespace properly. AddTypeDefinitionNameParts(declaringType, simpleNames); } // Now add the simple name of the type itself. simpleNames.Add(GetMetadataNameWithoutBackticks(_metadataReader, typeDefinition.Name)); } private void AddNamespaceParts( StringHandle namespaceHandle, List<string> simpleNames) { var blobReader = _metadataReader.GetBlobReader(namespaceHandle); while (true) { var dotIndex = blobReader.IndexOf((byte)'.'); unsafe { // Note: we won't get any string sharing as we're just using the // default string decoded. However, that's ok. We only produce // these strings when we first read metadata. Then we create and // persist our own index. In the future when we read in that index // there's no way for us to share strings between us and the // compiler at that point. if (dotIndex == -1) { simpleNames.Add(MetadataStringDecoder.DefaultUTF8.GetString( blobReader.CurrentPointer, blobReader.RemainingBytes)); return; } else { simpleNames.Add(MetadataStringDecoder.DefaultUTF8.GetString( blobReader.CurrentPointer, dotIndex)); blobReader.Offset += dotIndex + 1; } } } } private void AddNamespaceParts( NamespaceDefinitionHandle namespaceHandle, List<string> simpleNames) { if (namespaceHandle.IsNil) { return; } var namespaceDefinition = _metadataReader.GetNamespaceDefinition(namespaceHandle); AddNamespaceParts(namespaceDefinition.Parent, simpleNames); simpleNames.Add(_metadataReader.GetString(namespaceDefinition.Name)); } private void AddTypeReferenceNameParts(TypeReferenceHandle handle, List<string> simpleNames) { var typeReference = _metadataReader.GetTypeReference(handle); AddNamespaceParts(typeReference.Namespace, simpleNames); simpleNames.Add(GetMetadataNameWithoutBackticks(_metadataReader, typeReference.Name)); } private EntityHandle GetTypeDefOrRefHandle(EntityHandle baseTypeOrInterfaceHandle) { switch (baseTypeOrInterfaceHandle.Kind) { case HandleKind.TypeDefinition: case HandleKind.TypeReference: return baseTypeOrInterfaceHandle; case HandleKind.TypeSpecification: return FirstEntityHandleProvider.Instance.GetTypeFromSpecification( _metadataReader, (TypeSpecificationHandle)baseTypeOrInterfaceHandle); default: return default; } } private void EnsureParentsAndChildren(List<string> simpleNames) { var currentNode = _rootNode; foreach (var simpleName in simpleNames) { var childNode = GetOrCreateChildNode(currentNode, simpleName); currentNode = childNode; } } private MetadataNode GetOrCreateChildNode( MetadataNode currentNode, string simpleName) { if (_parentToChildren.TryGetValue(currentNode, static (childNode, simpleName) => childNode.Name == simpleName, simpleName, out var childNode)) { // Found an existing child node. Just return that and all // future parts off of it. return childNode; } // Couldn't find a child node with this name. Make a new node for // it and return that for all future parts to be added to. var newChildNode = MetadataNode.Allocate(simpleName); _parentToChildren.Add(currentNode, newChildNode); return newChildNode; } private ImmutableArray<BuilderNode> GenerateUnsortedNodes(MultiDictionary<string, ExtensionMethodInfo> receiverTypeNameToMethodMap) { var unsortedNodes = ArrayBuilder<BuilderNode>.GetInstance(); unsortedNodes.Add(BuilderNode.RootNode); AddUnsortedNodes(unsortedNodes, receiverTypeNameToMethodMap, parentNode: _rootNode, parentIndex: 0, fullyQualifiedContainerName: _containsExtensionsMethod ? "" : null); return unsortedNodes.ToImmutableAndFree(); } private void AddUnsortedNodes(ArrayBuilder<BuilderNode> unsortedNodes, MultiDictionary<string, ExtensionMethodInfo> receiverTypeNameToMethodMap, MetadataNode parentNode, int parentIndex, string fullyQualifiedContainerName) { foreach (var child in _parentToChildren[parentNode]) { var childNode = new BuilderNode(child.Name, parentIndex, _extensionMethodToParameterTypeInfo[child]); var childIndex = unsortedNodes.Count; unsortedNodes.Add(childNode); if (fullyQualifiedContainerName != null) { foreach (var parameterTypeInfo in _extensionMethodToParameterTypeInfo[child]) { // We do not differentiate array of different kinds for simplicity. // e.g. int[], int[][], int[,], etc. are all represented as int[] in the index. // similar for complex receiver types, "[]" means it's an array type, "" otherwise. var parameterTypeName = (parameterTypeInfo.IsComplexType, parameterTypeInfo.IsArray) switch { (true, true) => Extensions.ComplexArrayReceiverTypeName, // complex array type, e.g. "T[,]" (true, false) => Extensions.ComplexReceiverTypeName, // complex non-array type, e.g. "T" (false, true) => parameterTypeInfo.Name + Extensions.ArrayReceiverTypeNameSuffix, // simple array type, e.g. "int[][,]" (false, false) => parameterTypeInfo.Name // simple non-array type, e.g. "int" }; receiverTypeNameToMethodMap.Add(parameterTypeName, new ExtensionMethodInfo(fullyQualifiedContainerName, child.Name)); } } AddUnsortedNodes(unsortedNodes, receiverTypeNameToMethodMap, child, childIndex, Concat(fullyQualifiedContainerName, child.Name)); } static string Concat(string containerName, string name) { if (containerName == null) { return null; } if (containerName.Length == 0) { return name; } return containerName + "." + name; } } } private class MetadataNode { public string Name { get; private set; } private static readonly ObjectPool<MetadataNode> s_pool = SharedPools.Default<MetadataNode>(); public static MetadataNode Allocate(string name) { var node = s_pool.Allocate(); Debug.Assert(node.Name == null); node.Name = name; return node; } public static void Free(MetadataNode node) { Debug.Assert(node.Name != null); node.Name = null; s_pool.Free(node); } } private enum MetadataDefinitionKind { Namespace, Type, Member, } private struct MetadataDefinition { public string Name { get; } public MetadataDefinitionKind Kind { get; } /// <summary> /// Only applies to member kind. Represents the type info of the first parameter. /// </summary> public ParameterTypeInfo ReceiverTypeInfo { get; } public NamespaceDefinition Namespace { get; private set; } public TypeDefinition Type { get; private set; } public MetadataDefinition(MetadataDefinitionKind kind, string name, ParameterTypeInfo receiverTypeInfo = default) : this() { Kind = kind; Name = name; ReceiverTypeInfo = receiverTypeInfo; } public static MetadataDefinition Create( MetadataReader reader, NamespaceDefinitionHandle namespaceHandle) { var definition = reader.GetNamespaceDefinition(namespaceHandle); return new MetadataDefinition( MetadataDefinitionKind.Namespace, reader.GetString(definition.Name)) { Namespace = definition }; } public static MetadataDefinition Create( MetadataReader reader, TypeDefinition definition) { var typeName = GetMetadataNameWithoutBackticks(reader, definition.Name); return new MetadataDefinition(MetadataDefinitionKind.Type, typeName) { Type = definition }; } } } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/VisualStudio/Core/Impl/CodeModel/Interop/ICSCodeModelRefactoring.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop { [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsDual)] [Guid("376A7817-DB0D-4cfd-956E-5143F71F5CCD")] public interface ICSCodeModelRefactoring { void Rename(EnvDTE.CodeElement element); void RenameNoUI(EnvDTE.CodeElement element, string newName, bool fPreview, bool fSearchComments, bool fOverloads); void ReorderParameters(EnvDTE.CodeElement element); void ReorderParametersNoUI(EnvDTE.CodeElement element, long[] paramIndices, bool fPreview); void RemoveParameter(EnvDTE.CodeElement element); void RemoveParameterNoUI(EnvDTE.CodeElement element, object parameter, bool fPreview); void EncapsulateField(EnvDTE.CodeVariable variable); EnvDTE.CodeProperty EncapsulateFieldNoUI(EnvDTE.CodeVariable variable, string propertyName, EnvDTE.vsCMAccess accessibility, ReferenceSelectionEnum refSelection, PropertyTypeEnum propertyType, bool fPreview, bool fSearchComments); void ExtractInterface(EnvDTE.CodeType codeType); void ImplementInterface(EnvDTE.CodeType implementor, object @interface, bool fExplicit); void ImplementAbstractClass(EnvDTE.CodeType implementor, object abstractClass); EnvDTE.CodeElement ImplementOverride(EnvDTE.CodeElement member, EnvDTE.CodeType implementor); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop { [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsDual)] [Guid("376A7817-DB0D-4cfd-956E-5143F71F5CCD")] public interface ICSCodeModelRefactoring { void Rename(EnvDTE.CodeElement element); void RenameNoUI(EnvDTE.CodeElement element, string newName, bool fPreview, bool fSearchComments, bool fOverloads); void ReorderParameters(EnvDTE.CodeElement element); void ReorderParametersNoUI(EnvDTE.CodeElement element, long[] paramIndices, bool fPreview); void RemoveParameter(EnvDTE.CodeElement element); void RemoveParameterNoUI(EnvDTE.CodeElement element, object parameter, bool fPreview); void EncapsulateField(EnvDTE.CodeVariable variable); EnvDTE.CodeProperty EncapsulateFieldNoUI(EnvDTE.CodeVariable variable, string propertyName, EnvDTE.vsCMAccess accessibility, ReferenceSelectionEnum refSelection, PropertyTypeEnum propertyType, bool fPreview, bool fSearchComments); void ExtractInterface(EnvDTE.CodeType codeType); void ImplementInterface(EnvDTE.CodeType implementor, object @interface, bool fExplicit); void ImplementAbstractClass(EnvDTE.CodeType implementor, object abstractClass); EnvDTE.CodeElement ImplementOverride(EnvDTE.CodeElement member, EnvDTE.CodeType implementor); } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Compilers/CSharp/Portable/Symbols/PublicModel/PreprocessingSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Globalization; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class PreprocessingSymbol : IPreprocessingSymbol { private readonly string _name; internal PreprocessingSymbol(string name) { _name = name; } ISymbol ISymbol.OriginalDefinition => this; ISymbol ISymbol.ContainingSymbol => null; INamedTypeSymbol ISymbol.ContainingType => null; public sealed override int GetHashCode() { return this._name.GetHashCode(); } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) { return true; } if (ReferenceEquals(obj, null)) { return false; } PreprocessingSymbol other = obj as PreprocessingSymbol; return (object)other != null && this._name.Equals(other._name); } bool IEquatable<ISymbol>.Equals(ISymbol other) { return this.Equals(other); } bool ISymbol.Equals(ISymbol other, CodeAnalysis.SymbolEqualityComparer equalityComparer) { return this.Equals(other); } ImmutableArray<Location> ISymbol.Locations => ImmutableArray<Location>.Empty; ImmutableArray<SyntaxReference> ISymbol.DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; ImmutableArray<AttributeData> ISymbol.GetAttributes() => ImmutableArray<AttributeData>.Empty; Accessibility ISymbol.DeclaredAccessibility => Accessibility.NotApplicable; void ISymbol.Accept(SymbolVisitor visitor) => throw new System.NotSupportedException(); TResult ISymbol.Accept<TResult>(SymbolVisitor<TResult> visitor) => throw new System.NotSupportedException(); string ISymbol.GetDocumentationCommentId() => null; string ISymbol.GetDocumentationCommentXml(CultureInfo preferredCulture, bool expandIncludes, CancellationToken cancellationToken) => null; string ISymbol.ToDisplayString(SymbolDisplayFormat format) { return SymbolDisplay.ToDisplayString(this, format); } ImmutableArray<SymbolDisplayPart> ISymbol.ToDisplayParts(SymbolDisplayFormat format) { return SymbolDisplay.ToDisplayParts(this, format); } string ISymbol.ToMinimalDisplayString(SemanticModel semanticModel, int position, SymbolDisplayFormat format) { return SymbolDisplay.ToMinimalDisplayString(this, Symbol.GetCSharpSemanticModel(semanticModel), position, format); } ImmutableArray<SymbolDisplayPart> ISymbol.ToMinimalDisplayParts(SemanticModel semanticModel, int position, SymbolDisplayFormat format) { return SymbolDisplay.ToMinimalDisplayParts(this, Symbol.GetCSharpSemanticModel(semanticModel), position, format); } SymbolKind ISymbol.Kind => SymbolKind.Preprocessing; string ISymbol.Language => LanguageNames.CSharp; string ISymbol.Name => _name; string ISymbol.MetadataName => _name; int ISymbol.MetadataToken => 0; IAssemblySymbol ISymbol.ContainingAssembly => null; IModuleSymbol ISymbol.ContainingModule => null; INamespaceSymbol ISymbol.ContainingNamespace => null; bool ISymbol.IsDefinition => true; bool ISymbol.IsStatic => false; bool ISymbol.IsVirtual => false; bool ISymbol.IsOverride => false; bool ISymbol.IsAbstract => false; bool ISymbol.IsSealed => false; bool ISymbol.IsExtern => false; bool ISymbol.IsImplicitlyDeclared => false; bool ISymbol.CanBeReferencedByName => SyntaxFacts.IsValidIdentifier(_name) && !SyntaxFacts.ContainsDroppedIdentifierCharacters(_name); bool ISymbol.HasUnsupportedMetadata => false; public sealed override string ToString() { return SymbolDisplay.ToDisplayString(this); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Globalization; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class PreprocessingSymbol : IPreprocessingSymbol { private readonly string _name; internal PreprocessingSymbol(string name) { _name = name; } ISymbol ISymbol.OriginalDefinition => this; ISymbol ISymbol.ContainingSymbol => null; INamedTypeSymbol ISymbol.ContainingType => null; public sealed override int GetHashCode() { return this._name.GetHashCode(); } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) { return true; } if (ReferenceEquals(obj, null)) { return false; } PreprocessingSymbol other = obj as PreprocessingSymbol; return (object)other != null && this._name.Equals(other._name); } bool IEquatable<ISymbol>.Equals(ISymbol other) { return this.Equals(other); } bool ISymbol.Equals(ISymbol other, CodeAnalysis.SymbolEqualityComparer equalityComparer) { return this.Equals(other); } ImmutableArray<Location> ISymbol.Locations => ImmutableArray<Location>.Empty; ImmutableArray<SyntaxReference> ISymbol.DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; ImmutableArray<AttributeData> ISymbol.GetAttributes() => ImmutableArray<AttributeData>.Empty; Accessibility ISymbol.DeclaredAccessibility => Accessibility.NotApplicable; void ISymbol.Accept(SymbolVisitor visitor) => throw new System.NotSupportedException(); TResult ISymbol.Accept<TResult>(SymbolVisitor<TResult> visitor) => throw new System.NotSupportedException(); string ISymbol.GetDocumentationCommentId() => null; string ISymbol.GetDocumentationCommentXml(CultureInfo preferredCulture, bool expandIncludes, CancellationToken cancellationToken) => null; string ISymbol.ToDisplayString(SymbolDisplayFormat format) { return SymbolDisplay.ToDisplayString(this, format); } ImmutableArray<SymbolDisplayPart> ISymbol.ToDisplayParts(SymbolDisplayFormat format) { return SymbolDisplay.ToDisplayParts(this, format); } string ISymbol.ToMinimalDisplayString(SemanticModel semanticModel, int position, SymbolDisplayFormat format) { return SymbolDisplay.ToMinimalDisplayString(this, Symbol.GetCSharpSemanticModel(semanticModel), position, format); } ImmutableArray<SymbolDisplayPart> ISymbol.ToMinimalDisplayParts(SemanticModel semanticModel, int position, SymbolDisplayFormat format) { return SymbolDisplay.ToMinimalDisplayParts(this, Symbol.GetCSharpSemanticModel(semanticModel), position, format); } SymbolKind ISymbol.Kind => SymbolKind.Preprocessing; string ISymbol.Language => LanguageNames.CSharp; string ISymbol.Name => _name; string ISymbol.MetadataName => _name; int ISymbol.MetadataToken => 0; IAssemblySymbol ISymbol.ContainingAssembly => null; IModuleSymbol ISymbol.ContainingModule => null; INamespaceSymbol ISymbol.ContainingNamespace => null; bool ISymbol.IsDefinition => true; bool ISymbol.IsStatic => false; bool ISymbol.IsVirtual => false; bool ISymbol.IsOverride => false; bool ISymbol.IsAbstract => false; bool ISymbol.IsSealed => false; bool ISymbol.IsExtern => false; bool ISymbol.IsImplicitlyDeclared => false; bool ISymbol.CanBeReferencedByName => SyntaxFacts.IsValidIdentifier(_name) && !SyntaxFacts.ContainsDroppedIdentifierCharacters(_name); bool ISymbol.HasUnsupportedMetadata => false; public sealed override string ToString() { return SymbolDisplay.ToDisplayString(this); } } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Compilers/Core/Portable/CommandLine/CommonCompiler.CompilerRelativePathResolver.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.IO; using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal abstract partial class CommonCompiler { /// <summary> /// Looks for metadata references among the assembly file references given to the compilation when constructed. /// When scripts are included into a project we don't want #r's to reference other assemblies than those /// specified explicitly in the project references. /// </summary> internal sealed class CompilerRelativePathResolver : RelativePathResolver { internal ICommonCompilerFileSystem FileSystem { get; } internal CompilerRelativePathResolver(ICommonCompilerFileSystem fileSystem, ImmutableArray<string> searchPaths, string? baseDirectory) : base(searchPaths, baseDirectory) { FileSystem = fileSystem; } protected override bool FileExists(string fullPath) => FileSystem.FileExists(fullPath); } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal abstract partial class CommonCompiler { /// <summary> /// Looks for metadata references among the assembly file references given to the compilation when constructed. /// When scripts are included into a project we don't want #r's to reference other assemblies than those /// specified explicitly in the project references. /// </summary> internal sealed class CompilerRelativePathResolver : RelativePathResolver { internal ICommonCompilerFileSystem FileSystem { get; } internal CompilerRelativePathResolver(ICommonCompilerFileSystem fileSystem, ImmutableArray<string> searchPaths, string? baseDirectory) : base(searchPaths, baseDirectory) { FileSystem = fileSystem; } protected override bool FileExists(string fullPath) => FileSystem.FileExists(fullPath); } } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/VisualStudio/Core/Def/Implementation/LanguageClient/AlwaysActivateInProcLanguageClient.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServer.Client; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient { /// <summary> /// Language client responsible for handling C# / VB / F# LSP requests in any scenario (both local and codespaces). /// This powers "LSP only" features (e.g. cntrl+Q code search) that do not use traditional editor APIs. /// It is always activated whenever roslyn is activated. /// </summary> [ContentType(ContentTypeNames.CSharpContentType)] [ContentType(ContentTypeNames.VisualBasicContentType)] [ContentType(ContentTypeNames.FSharpContentType)] [Export(typeof(ILanguageClient))] [Export(typeof(AlwaysActivateInProcLanguageClient))] internal class AlwaysActivateInProcLanguageClient : AbstractInProcLanguageClient { private readonly DefaultCapabilitiesProvider _defaultCapabilitiesProvider; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, true)] public AlwaysActivateInProcLanguageClient( RequestDispatcherFactory csharpVBRequestDispatcherFactory, IGlobalOptionService globalOptions, IAsynchronousOperationListenerProvider listenerProvider, ILspWorkspaceRegistrationService lspWorkspaceRegistrationService, DefaultCapabilitiesProvider defaultCapabilitiesProvider, ILspLoggerFactory lspLoggerFactory, IThreadingContext threadingContext) : base(csharpVBRequestDispatcherFactory, globalOptions, diagnosticService: null, listenerProvider, lspWorkspaceRegistrationService, lspLoggerFactory, threadingContext, diagnosticsClientName: null) { _defaultCapabilitiesProvider = defaultCapabilitiesProvider; } protected override ImmutableArray<string> SupportedLanguages => ProtocolConstants.RoslynLspLanguages; public override string Name => CSharpVisualBasicLanguageServerFactory.UserVisibleName; public override ServerCapabilities GetCapabilities(ClientCapabilities clientCapabilities) { var serverCapabilities = new VSInternalServerCapabilities(); // If the LSP editor feature flag is enabled advertise support for LSP features here so they are available locally and remote. var isLspEditorEnabled = GlobalOptions.GetOption(LspOptions.LspEditorFeatureFlag); if (isLspEditorEnabled) { serverCapabilities = (VSInternalServerCapabilities)_defaultCapabilitiesProvider.GetCapabilities(clientCapabilities); } else { // Even if the flag is off, we want to include text sync capabilities. serverCapabilities.TextDocumentSync = new TextDocumentSyncOptions { Change = TextDocumentSyncKind.Incremental, OpenClose = true, }; } serverCapabilities.SupportsDiagnosticRequests = GlobalOptions.IsPullDiagnostics(InternalDiagnosticsOptions.NormalDiagnosticMode); // This capability is always enabled as we provide cntrl+Q VS search only via LSP in ever scenario. serverCapabilities.WorkspaceSymbolProvider = true; // This capability prevents NavigateTo (cntrl+,) from using LSP symbol search when the server also supports WorkspaceSymbolProvider. // Since WorkspaceSymbolProvider=true always to allow cntrl+Q VS search to function, we set DisableGoToWorkspaceSymbols=true // when not running the experimental LSP editor. This ensures NavigateTo uses the existing editor APIs. // However, when the experimental LSP editor is enabled we want LSP to power NavigateTo, so we set DisableGoToWorkspaceSymbols=false. serverCapabilities.DisableGoToWorkspaceSymbols = !isLspEditorEnabled; return serverCapabilities; } /// <summary> /// When pull diagnostics is enabled, ensure that initialization failures are displayed to the user as /// they will get no diagnostics. When not enabled we don't show the failure box (failure will still be recorded in the task status center) /// as the failure is not catastrophic. /// </summary> public override bool ShowNotificationOnInitializeFailed => GlobalOptions.IsPullDiagnostics(InternalDiagnosticsOptions.NormalDiagnosticMode); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServer.Client; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient { /// <summary> /// Language client responsible for handling C# / VB / F# LSP requests in any scenario (both local and codespaces). /// This powers "LSP only" features (e.g. cntrl+Q code search) that do not use traditional editor APIs. /// It is always activated whenever roslyn is activated. /// </summary> [ContentType(ContentTypeNames.CSharpContentType)] [ContentType(ContentTypeNames.VisualBasicContentType)] [ContentType(ContentTypeNames.FSharpContentType)] [Export(typeof(ILanguageClient))] [Export(typeof(AlwaysActivateInProcLanguageClient))] internal class AlwaysActivateInProcLanguageClient : AbstractInProcLanguageClient { private readonly DefaultCapabilitiesProvider _defaultCapabilitiesProvider; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, true)] public AlwaysActivateInProcLanguageClient( RequestDispatcherFactory csharpVBRequestDispatcherFactory, IGlobalOptionService globalOptions, IAsynchronousOperationListenerProvider listenerProvider, ILspWorkspaceRegistrationService lspWorkspaceRegistrationService, DefaultCapabilitiesProvider defaultCapabilitiesProvider, ILspLoggerFactory lspLoggerFactory, IThreadingContext threadingContext) : base(csharpVBRequestDispatcherFactory, globalOptions, diagnosticService: null, listenerProvider, lspWorkspaceRegistrationService, lspLoggerFactory, threadingContext, diagnosticsClientName: null) { _defaultCapabilitiesProvider = defaultCapabilitiesProvider; } protected override ImmutableArray<string> SupportedLanguages => ProtocolConstants.RoslynLspLanguages; public override string Name => CSharpVisualBasicLanguageServerFactory.UserVisibleName; public override ServerCapabilities GetCapabilities(ClientCapabilities clientCapabilities) { var serverCapabilities = new VSInternalServerCapabilities(); // If the LSP editor feature flag is enabled advertise support for LSP features here so they are available locally and remote. var isLspEditorEnabled = GlobalOptions.GetOption(LspOptions.LspEditorFeatureFlag); if (isLspEditorEnabled) { serverCapabilities = (VSInternalServerCapabilities)_defaultCapabilitiesProvider.GetCapabilities(clientCapabilities); } else { // Even if the flag is off, we want to include text sync capabilities. serverCapabilities.TextDocumentSync = new TextDocumentSyncOptions { Change = TextDocumentSyncKind.Incremental, OpenClose = true, }; } serverCapabilities.SupportsDiagnosticRequests = GlobalOptions.IsPullDiagnostics(InternalDiagnosticsOptions.NormalDiagnosticMode); // This capability is always enabled as we provide cntrl+Q VS search only via LSP in ever scenario. serverCapabilities.WorkspaceSymbolProvider = true; // This capability prevents NavigateTo (cntrl+,) from using LSP symbol search when the server also supports WorkspaceSymbolProvider. // Since WorkspaceSymbolProvider=true always to allow cntrl+Q VS search to function, we set DisableGoToWorkspaceSymbols=true // when not running the experimental LSP editor. This ensures NavigateTo uses the existing editor APIs. // However, when the experimental LSP editor is enabled we want LSP to power NavigateTo, so we set DisableGoToWorkspaceSymbols=false. serverCapabilities.DisableGoToWorkspaceSymbols = !isLspEditorEnabled; return serverCapabilities; } /// <summary> /// When pull diagnostics is enabled, ensure that initialization failures are displayed to the user as /// they will get no diagnostics. When not enabled we don't show the failure box (failure will still be recorded in the task status center) /// as the failure is not catastrophic. /// </summary> public override bool ShowNotificationOnInitializeFailed => GlobalOptions.IsPullDiagnostics(InternalDiagnosticsOptions.NormalDiagnosticMode); } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Compilers/VisualBasic/Test/Semantic/Semantics/BinaryOperators.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.Text Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class BinaryOperators Inherits BasicTestBase <ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")> Public Sub Test1() Dim currCulture = System.Threading.Thread.CurrentThread.CurrentCulture System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("en-US", useUserOverride:=False) Try Dim compilationDef = <compilation name="VBBinaryOperators1"> <file name="lib.vb"> <%= SemanticResourceUtil.PrintResultTestSource %> </file> <file name="a.vb"> <%= SemanticResourceUtil.BinaryOperatorsTestSource1 %> </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.True(compilation.Options.CheckOverflow) CompileAndVerify(compilation, expectedOutput:=SemanticResourceUtil.BinaryOperatorsTestBaseline1) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOverflowChecks(False)) Assert.False(compilation.Options.CheckOverflow) CompileAndVerify(compilation, expectedOutput:=SemanticResourceUtil.BinaryOperatorsTestBaseline1) Catch ex As Exception Assert.Null(ex) Finally System.Threading.Thread.CurrentThread.CurrentCulture = currCulture End Try End Sub <Fact> Public Sub Test1_Date() ' test binary operator between Date value and another type data ' call ToString() on it defeat the purpose of these scenarios Dim currCulture = System.Threading.Thread.CurrentThread.CurrentCulture System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("en-US", useUserOverride:=False) Try Dim compilationDef = <compilation name="VBBinaryOperators11"> <file name="lib.vb"> <%= SemanticResourceUtil.PrintResultTestSource %> </file> <file name="a.vb"> <![CDATA[ Option Strict Off Imports System Module Module1 Sub Main() Dim BoFalse As Boolean Dim BoTrue As Boolean Dim SB As SByte Dim By As Byte Dim Sh As Short Dim US As UShort Dim [In] As Integer Dim UI As UInteger Dim Lo As Long Dim UL As ULong Dim De As Decimal Dim Si As Single Dim [Do] As Double Dim St As String Dim Ob As Object Dim Tc As System.TypeCode Dim Da As Date Dim Ch As Char Dim ChArray() As Char BoFalse = False BoTrue = True SB = -1 Sh = -3 [In] = -5 Lo = -7 De = -9D Si = 10 [Do] = -11 St = "12" Ob = "-13" Da = #8:30:00 AM# Ch = "c"c Tc = TypeCode.Double ChArray = "14" By = 22 US = 24 UI = 26 UL = 28 PrintResult("Da + St", Da + St) PrintResult("Da + Ob", Da + Ob) PrintResult("Da + Da", Da + Da) PrintResult("Da + ChArray", Da + ChArray) PrintResult("ChArray + Da", ChArray + Da) PrintResult("St + Da", St + Da) PrintResult("Ob + Da", Ob + Da) PrintResult("Da & BoFalse", Da & BoFalse) PrintResult("Da & BoTrue", Da & BoTrue) PrintResult("Da & SB", Da & SB) PrintResult("Da & By", Da & By) PrintResult("Da & Sh", Da & Sh) PrintResult("Da & US", Da & US) PrintResult("Da & [In]", Da & [In]) PrintResult("Da & UI", Da & UI) PrintResult("Da & Lo", Da & Lo) PrintResult("Da & UL", Da & UL) PrintResult("Da & De", Da & De) PrintResult("Da & Si", Da & Si) PrintResult("Da & [Do]", Da & [Do]) PrintResult("Da & St", Da & St) PrintResult("Da & Ob", Da & Ob) PrintResult("Da & Tc", Da & Tc) PrintResult("Da & Da", Da & Da) PrintResult("Da & Ch", Da & Ch) PrintResult("Da & ChArray", Da & ChArray) PrintResult("Ch & Da", Ch & Da) PrintResult("ChArray & Da", ChArray & Da) PrintResult("BoFalse & Da", BoFalse & Da) PrintResult("BoTrue & Da", BoTrue & Da) PrintResult("SB & Da", SB & Da) PrintResult("By & Da", By & Da) PrintResult("Sh & Da", Sh & Da) PrintResult("US & Da", US & Da) PrintResult("[In] & Da", [In] & Da) PrintResult("UI & Da", UI & Da) PrintResult("Lo & Da", Lo & Da) PrintResult("UL & Da", UL & Da) PrintResult("De & Da", De & Da) PrintResult("Si & Da", Si & Da) PrintResult("[Do] & Da", [Do] & Da) PrintResult("St & Da", St & Da) PrintResult("Ob & Da", Ob & Da) PrintResult("Tc & Da", Tc & Da) End Sub End Module ]]> </file> </compilation> Dim expected = <![CDATA[[Da + St] String: [8:30:00 AM12] [Da + Ob] Object: 8:30:00 AM-13 [Da + Da] String: [8:30:00 AM8:30:00 AM] [Da + ChArray] String: [8:30:00 AM14] [ChArray + Da] String: [148:30:00 AM] [St + Da] String: [128:30:00 AM] [Ob + Da] Object: -138:30:00 AM [Da & BoFalse] String: [8:30:00 AMFalse] [Da & BoTrue] String: [8:30:00 AMTrue] [Da & SB] String: [8:30:00 AM-1] [Da & By] String: [8:30:00 AM22] [Da & Sh] String: [8:30:00 AM-3] [Da & US] String: [8:30:00 AM24] [Da & [In]] String: [8:30:00 AM-5] [Da & UI] String: [8:30:00 AM26] [Da & Lo] String: [8:30:00 AM-7] [Da & UL] String: [8:30:00 AM28] [Da & De] String: [8:30:00 AM-9] [Da & Si] String: [8:30:00 AM10] [Da & [Do]] String: [8:30:00 AM-11] [Da & St] String: [8:30:00 AM12] [Da & Ob] Object: 8:30:00 AM-13 [Da & Tc] String: [8:30:00 AM14] [Da & Da] String: [8:30:00 AM8:30:00 AM] [Da & Ch] String: [8:30:00 AMc] [Da & ChArray] String: [8:30:00 AM14] [Ch & Da] String: [c8:30:00 AM] [ChArray & Da] String: [148:30:00 AM] [BoFalse & Da] String: [False8:30:00 AM] [BoTrue & Da] String: [True8:30:00 AM] [SB & Da] String: [-18:30:00 AM] [By & Da] String: [228:30:00 AM] [Sh & Da] String: [-38:30:00 AM] [US & Da] String: [248:30:00 AM] [[In] & Da] String: [-58:30:00 AM] [UI & Da] String: [268:30:00 AM] [Lo & Da] String: [-78:30:00 AM] [UL & Da] String: [288:30:00 AM] [De & Da] String: [-98:30:00 AM] [Si & Da] String: [108:30:00 AM] [[Do] & Da] String: [-118:30:00 AM] [St & Da] String: [128:30:00 AM] [Ob & Da] Object: -138:30:00 AM [Tc & Da] String: [148:30:00 AM]]]> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.True(compilation.Options.CheckOverflow) CompileAndVerify(compilation, expectedOutput:=expected) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOverflowChecks(False)) Assert.False(compilation.Options.CheckOverflow) CompileAndVerify(compilation, expectedOutput:=expected) Catch ex As Exception Assert.Null(ex) Finally System.Threading.Thread.CurrentThread.CurrentCulture = currCulture End Try End Sub <Fact> Public Sub Test2() Dim compilationDef = <compilation name="VBBinaryOperators2"> <file name="a.vb"> <%= SemanticResourceUtil.BinaryOperatorsTestSource2 %> </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, SemanticResourceUtil.BinaryOperatorsTestBaseline2) End Sub <Fact> Public Sub Test30() Dim compilationDef = <compilation name="VBBinaryOperators30"> <file name="a.vb"> Option Strict Off Imports System Module Module1 Sub Main() Dim St1 As String Dim St2 As String Dim Ob1 As Object Dim Ob2 As Object St1 = "a" St2 = "a" Ob1 = "a" Ob2 = "a" Console.WriteLine(St1 = St2) Console.WriteLine(Ob1 = Ob2) St1 = "a" St2 = "A" Ob1 = "a" Ob2 = "A" Console.WriteLine(St1 = St2) Console.WriteLine(Ob1 = Ob2) St1 = "a" St2 = "b" Ob1 = "a" Ob2 = "b" Console.WriteLine(St1 = St2) Console.WriteLine(Ob1 = Ob2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.False(compilation.Options.OptionCompareText) CompileAndVerify(compilation, <![CDATA[ True True False False False False ]]>) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOptionCompareText(True)) Assert.True(compilation.Options.OptionCompareText) CompileAndVerify(compilation, <![CDATA[ True True True True False False ]]>) End Sub <Fact> Public Sub Test3() Dim compilationDef = <compilation name="VBBinaryOperators3"> <file name="a.vb"> <%= SemanticResourceUtil.BinaryOperatorsTestSource3 %> </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, SemanticResourceUtil.BinaryOperatorsTestBaseline3) End Sub <Fact> Public Sub Test4() Dim compilationDef = <compilation name="VBBinaryOperators4"> <file name="a.vb"> <%= SemanticResourceUtil.BinaryOperatorsTestSource4 %> </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=SemanticResourceUtil.BinaryOperatorsTestBaseline4) End Sub <ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")> Public Sub Test5() Dim compilationDef = <compilation name="VBBinaryOperators52"> <file name="lib.vb"> <%= SemanticResourceUtil.PrintResultTestSource %> </file> <file name="a.vb"> <%= SemanticResourceUtil.BinaryOperatorsTestSource5 %> </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.True(compilation.Options.CheckOverflow) CompileAndVerify(compilation, expectedOutput:=SemanticResourceUtil.BinaryOperatorsTestBaseline5) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOverflowChecks(False)) Assert.False(compilation.Options.CheckOverflow) CompileAndVerify(compilation, expectedOutput:=SemanticResourceUtil.BinaryOperatorsTestBaseline5) End Sub <Fact> Public Sub Test5_DateConst() ' test binary operator between Date const and another type data ' call ToString() on it defeat the purpose of these scenarios Dim currCulture = System.Threading.Thread.CurrentThread.CurrentCulture System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("en-US", useUserOverride:=False) Try Dim compilationDef = <compilation name="VBBinaryOperators52"> <file name="lib.vb"> <%= SemanticResourceUtil.PrintResultTestSource %> </file> <file name="a.vb"> <![CDATA[ Option Strict Off Imports System Module Module1 Sub Main() PrintResult("#8:30:00 AM# + ""12""", #8:30:00 AM# + "12") PrintResult("#8:30:00 AM# + #8:30:00 AM#", #8:30:00 AM# + #8:30:00 AM#) PrintResult("""12"" + #8:30:00 AM#", "12" + #8:30:00 AM#) PrintResult("#8:30:00 AM# & False", #8:30:00 AM# & False) PrintResult("#8:30:00 AM# & True", #8:30:00 AM# & True) PrintResult("#8:30:00 AM# & System.SByte.MinValue", #8:30:00 AM# & System.SByte.MinValue) PrintResult("#8:30:00 AM# & System.Byte.MaxValue", #8:30:00 AM# & System.Byte.MaxValue) PrintResult("#8:30:00 AM# & -3S", #8:30:00 AM# & -3S) PrintResult("#8:30:00 AM# & 24US", #8:30:00 AM# & 24US) PrintResult("#8:30:00 AM# & -5I", #8:30:00 AM# & -5I) PrintResult("#8:30:00 AM# & 26UI", #8:30:00 AM# & 26UI) PrintResult("#8:30:00 AM# & -7L", #8:30:00 AM# & -7L) PrintResult("#8:30:00 AM# & 28UL", #8:30:00 AM# & 28UL) PrintResult("#8:30:00 AM# & -9D", #8:30:00 AM# & -9D) PrintResult("#8:30:00 AM# & 10.0F", #8:30:00 AM# & 10.0F) PrintResult("#8:30:00 AM# & -11.0R", #8:30:00 AM# & -11.0R) PrintResult("#8:30:00 AM# & ""12""", #8:30:00 AM# & "12") PrintResult("#8:30:00 AM# & TypeCode.Double", #8:30:00 AM# & TypeCode.Double) PrintResult("#8:30:00 AM# & #8:30:00 AM#", #8:30:00 AM# & #8:30:00 AM#) PrintResult("#8:30:00 AM# & ""c""c", #8:30:00 AM# & "c"c) PrintResult("""c""c & #8:30:00 AM#", "c"c & #8:30:00 AM#) PrintResult("False & #8:30:00 AM#", False & #8:30:00 AM#) PrintResult("True & #8:30:00 AM#", True & #8:30:00 AM#) PrintResult("System.SByte.MinValue & #8:30:00 AM#", System.SByte.MinValue & #8:30:00 AM#) PrintResult("System.Byte.MaxValue & #8:30:00 AM#", System.Byte.MaxValue & #8:30:00 AM#) PrintResult("-3S & #8:30:00 AM#", -3S & #8:30:00 AM#) PrintResult("24US & #8:30:00 AM#", 24US & #8:30:00 AM#) PrintResult("-5I & #8:30:00 AM#", -5I & #8:30:00 AM#) PrintResult("26UI & #8:30:00 AM#", 26UI & #8:30:00 AM#) PrintResult("-7L & #8:30:00 AM#", -7L & #8:30:00 AM#) PrintResult("28UL & #8:30:00 AM#", 28UL & #8:30:00 AM#) PrintResult("-9D & #8:30:00 AM#", -9D & #8:30:00 AM#) PrintResult("10.0F & #8:30:00 AM#", 10.0F & #8:30:00 AM#) PrintResult("-11.0R & #8:30:00 AM#", -11.0R & #8:30:00 AM#) PrintResult("""12"" & #8:30:00 AM#", "12" & #8:30:00 AM#) PrintResult("TypeCode.Double & #8:30:00 AM#", TypeCode.Double & #8:30:00 AM#) End Sub End Module ]]> </file> </compilation> Dim expected = <![CDATA[[#8:30:00 AM# + "12"] String: [8:30:00 AM12] [#8:30:00 AM# + #8:30:00 AM#] String: [8:30:00 AM8:30:00 AM] ["12" + #8:30:00 AM#] String: [128:30:00 AM] [#8:30:00 AM# & False] String: [8:30:00 AMFalse] [#8:30:00 AM# & True] String: [8:30:00 AMTrue] [#8:30:00 AM# & System.SByte.MinValue] String: [8:30:00 AM-128] [#8:30:00 AM# & System.Byte.MaxValue] String: [8:30:00 AM255] [#8:30:00 AM# & -3S] String: [8:30:00 AM-3] [#8:30:00 AM# & 24US] String: [8:30:00 AM24] [#8:30:00 AM# & -5I] String: [8:30:00 AM-5] [#8:30:00 AM# & 26UI] String: [8:30:00 AM26] [#8:30:00 AM# & -7L] String: [8:30:00 AM-7] [#8:30:00 AM# & 28UL] String: [8:30:00 AM28] [#8:30:00 AM# & -9D] String: [8:30:00 AM-9] [#8:30:00 AM# & 10.0F] String: [8:30:00 AM10] [#8:30:00 AM# & -11.0R] String: [8:30:00 AM-11] [#8:30:00 AM# & "12"] String: [8:30:00 AM12] [#8:30:00 AM# & TypeCode.Double] String: [8:30:00 AM14] [#8:30:00 AM# & #8:30:00 AM#] String: [8:30:00 AM8:30:00 AM] [#8:30:00 AM# & "c"c] String: [8:30:00 AMc] ["c"c & #8:30:00 AM#] String: [c8:30:00 AM] [False & #8:30:00 AM#] String: [False8:30:00 AM] [True & #8:30:00 AM#] String: [True8:30:00 AM] [System.SByte.MinValue & #8:30:00 AM#] String: [-1288:30:00 AM] [System.Byte.MaxValue & #8:30:00 AM#] String: [2558:30:00 AM] [-3S & #8:30:00 AM#] String: [-38:30:00 AM] [24US & #8:30:00 AM#] String: [248:30:00 AM] [-5I & #8:30:00 AM#] String: [-58:30:00 AM] [26UI & #8:30:00 AM#] String: [268:30:00 AM] [-7L & #8:30:00 AM#] String: [-78:30:00 AM] [28UL & #8:30:00 AM#] String: [288:30:00 AM] [-9D & #8:30:00 AM#] String: [-98:30:00 AM] [10.0F & #8:30:00 AM#] String: [108:30:00 AM] [-11.0R & #8:30:00 AM#] String: [-118:30:00 AM] ["12" & #8:30:00 AM#] String: [128:30:00 AM] [TypeCode.Double & #8:30:00 AM#] String: [148:30:00 AM] ]]> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.True(compilation.Options.CheckOverflow) CompileAndVerify(compilation, expectedOutput:=expected) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOverflowChecks(False)) Assert.False(compilation.Options.CheckOverflow) CompileAndVerify(compilation, expectedOutput:=expected) Catch ex As Exception Assert.Null(ex) Finally System.Threading.Thread.CurrentThread.CurrentCulture = currCulture End Try End Sub <Fact> Public Sub Test7() Dim compilationDef = <compilation name="VBBinaryOperators7"> <file name="a.vb"> Option Strict Off Imports System Module Module1 Sub Main() Dim ob As Object ob = System.SByte.MinValue + (System.SByte.MaxValue + System.SByte.MinValue) ob = System.Byte.MinValue - (System.Byte.MaxValue \ System.Byte.MaxValue) ob = System.Int16.MinValue - 1S ob = System.UInt16.MinValue - 1US ob = System.Int32.MinValue - 1I ob = System.UInt32.MinValue - 1UI ob = System.Int64.MinValue - 1L ob = System.UInt64.MinValue - 1UL ob = -79228162514264337593543950335D - 1D ob = System.SByte.MaxValue - (System.SByte.MaxValue + System.SByte.MinValue) ob = System.Byte.MaxValue + (System.Byte.MaxValue \ System.Byte.MaxValue) ob = System.Int16.MaxValue + 1S ob = System.UInt16.MaxValue + 1US ob = System.Int32.MaxValue + 1I ob = System.UInt32.MaxValue + 1UI ob = System.Int64.MaxValue + 1L ob = System.UInt64.MaxValue + 1UL ob = 79228162514264337593543950335D + 1D ob = (2I \ 0) ob = (1.5F \ 0) ob = (2.5R \ 0) ob = (3.5D \ 0) ob = (2I Mod 0) ob = (3.5D Mod 0) ob = (3.5D / Nothing) ob = (2I \ Nothing) ob = (1.5F \ Nothing) ob = (2.5R \ Nothing) ob = (3.5D \ Nothing) ob = (2I Mod Nothing) ob = (3.5D Mod Nothing) ob = (3.5D / 0) ob = System.UInt64.MaxValue * 2UL ob = System.Int64.MaxValue * 2L ob = System.Int64.MinValue * (-2L) ob = 3L * (System.Int64.MinValue \ 2L) ob = (System.Int64.MinValue \ 2L) * 3L ob = System.Int64.MinValue \ (-1L) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30439: Constant expression not representable in type 'SByte'. ob = System.SByte.MinValue + (System.SByte.MaxValue + System.SByte.MinValue) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Byte'. ob = System.Byte.MinValue - (System.Byte.MaxValue \ System.Byte.MaxValue) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Short'. ob = System.Int16.MinValue - 1S ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'UShort'. ob = System.UInt16.MinValue - 1US ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Integer'. ob = System.Int32.MinValue - 1I ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'UInteger'. ob = System.UInt32.MinValue - 1UI ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Long'. ob = System.Int64.MinValue - 1L ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'ULong'. ob = System.UInt64.MinValue - 1UL ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Decimal'. ob = -79228162514264337593543950335D - 1D ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'SByte'. ob = System.SByte.MaxValue - (System.SByte.MaxValue + System.SByte.MinValue) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Byte'. ob = System.Byte.MaxValue + (System.Byte.MaxValue \ System.Byte.MaxValue) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Short'. ob = System.Int16.MaxValue + 1S ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'UShort'. ob = System.UInt16.MaxValue + 1US ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Integer'. ob = System.Int32.MaxValue + 1I ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'UInteger'. ob = System.UInt32.MaxValue + 1UI ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Long'. ob = System.Int64.MaxValue + 1L ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'ULong'. ob = System.UInt64.MaxValue + 1UL ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Decimal'. ob = 79228162514264337593543950335D + 1D ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (2I \ 0) ~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (1.5F \ 0) ~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (2.5R \ 0) ~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (3.5D \ 0) ~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (2I Mod 0) ~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (3.5D Mod 0) ~~~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (3.5D / Nothing) ~~~~~~~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (2I \ Nothing) ~~~~~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (1.5F \ Nothing) ~~~~~~~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (2.5R \ Nothing) ~~~~~~~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (3.5D \ Nothing) ~~~~~~~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (2I Mod Nothing) ~~~~~~~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (3.5D Mod Nothing) ~~~~~~~~~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (3.5D / 0) ~~~~~~~~ BC30439: Constant expression not representable in type 'ULong'. ob = System.UInt64.MaxValue * 2UL ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Long'. ob = System.Int64.MaxValue * 2L ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Long'. ob = System.Int64.MinValue * (-2L) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Long'. ob = 3L * (System.Int64.MinValue \ 2L) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Long'. ob = (System.Int64.MinValue \ 2L) * 3L ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Long'. ob = System.Int64.MinValue \ (-1L) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub Test8() Dim compilationDef = <compilation name="VBBinaryOperators8"> <file name="a.vb"> Imports System Module Module1 Sub Main() Dim Ob As Object = Nothing Ob = Ob-Ob Ob = Ob = Ob Ob = Ob &lt;&gt; Ob Ob = Ob &gt; Ob End Sub End Module </file> </compilation> Dim expected = <expected> BC42019: Operands of type Object used for operator '-'; runtime errors could occur. Ob = Ob-Ob ~~ BC42019: Operands of type Object used for operator '-'; runtime errors could occur. Ob = Ob-Ob ~~ BC42018: Operands of type Object used for operator '='; use the 'Is' operator to test object identity. Ob = Ob = Ob ~~ BC42018: Operands of type Object used for operator '='; use the 'Is' operator to test object identity. Ob = Ob = Ob ~~ BC42032: Operands of type Object used for operator '&lt;&gt;'; use the 'IsNot' operator to test object identity. Ob = Ob &lt;&gt; Ob ~~ BC42032: Operands of type Object used for operator '&lt;&gt;'; use the 'IsNot' operator to test object identity. Ob = Ob &lt;&gt; Ob ~~ BC42019: Operands of type Object used for operator '&gt;'; runtime errors could occur. Ob = Ob &gt; Ob ~~ BC42019: Operands of type Object used for operator '&gt;'; runtime errors could occur. Ob = Ob &gt; Ob ~~ </expected> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) CompilationUtils.AssertTheseDiagnostics(compilation, expected) End Sub <WorkItem(543387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543387")> <Fact()> Public Sub Test9() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() If Nothing = Function() 5 Then 'BIND1:"Nothing = Function() 5" System.Console.WriteLine("Failed") Else System.Console.WriteLine("Succeeded") End If End Sub End Module ]]></file> </compilation>, options:=TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) CompileAndVerify(compilation, expectedOutput:= <![CDATA[ Succeeded ]]>) AssertTheseDiagnostics(compilation, <expected> </expected>) Dim model = GetSemanticModel(compilation, "a.vb") Dim node As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo = model.GetSymbolInfo(node) Assert.Equal("Public Shared Overloads Operator =(d1 As System.MulticastDelegate, d2 As System.MulticastDelegate) As Boolean", symbolInfo.Symbol.ToDisplayString()) End Sub <WorkItem(544620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")> <Fact()> Public Sub Bug13088() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Public Const Z As Integer = Integer.MaxValue + 1 'BIND:"Public Const Z As Integer = Integer.MaxValue + 1" Sub Main() End Sub End Module ]]></file> </compilation>) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_ExpressionOverflow1, "Integer.MaxValue + 1").WithArguments("Integer")) Dim symbol = compilation.GlobalNamespace.GetTypeMembers("Program").Single.GetMembers("Z").Single Assert.False(DirectCast(symbol, FieldSymbol).HasConstantValue) End Sub <Fact(), WorkItem(531531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531531")> <CompilerTrait(CompilerFeature.IOperation)> Public Sub Bug18257() Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Option Strict On Public Class TestState Shared Function IsImmediateWindow1(line As Integer?) As String Dim s = "Expected: " & line & "." Return s End Function Shared Function IsImmediateWindow2(line As Integer) As String Dim s = "Expected: " & line & "." Return s End Function End Class Module Module1 Sub Main() System.Console.WriteLine(TestState.IsImmediateWindow1(Nothing)) System.Console.WriteLine(TestState.IsImmediateWindow2(Nothing)) End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) Dim compilationVerifier = CompileAndVerify(compilation, expectedOutput:= <![CDATA[ Expected: . Expected: 0. ]]>) Dim tree = compilation.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of LocalDeclarationStatementSyntax)().First() Assert.Equal("Dim s = ""Expected: "" & line & "".""", node.ToString()) compilation.VerifyOperationTree(node.Declarators.Last.Initializer.Value, expectedOperationTree:= <![CDATA[ IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: '"Expected: ... line & "."') Left: IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: '"Expected: " & line') Left: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Expected: ") (Syntax: '"Expected: "') Right: ICoalesceOperation (OperationKind.Coalesce, Type: System.String, IsImplicit) (Syntax: 'line') Expression: IParameterReferenceOperation: line (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'line') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NarrowingString) WhenNull: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: null, IsImplicit) (Syntax: 'line') Right: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ".") (Syntax: '"."') ]]>.Value) End Sub <ConditionalFact(GetType(NoIOperationValidation))> Public Sub IntrinsicSymbols() Dim operators() As BinaryOperatorKind = { BinaryOperatorKind.Add, BinaryOperatorKind.Concatenate, BinaryOperatorKind.Like, BinaryOperatorKind.Equals, BinaryOperatorKind.NotEquals, BinaryOperatorKind.LessThanOrEqual, BinaryOperatorKind.GreaterThanOrEqual, BinaryOperatorKind.LessThan, BinaryOperatorKind.GreaterThan, BinaryOperatorKind.Subtract, BinaryOperatorKind.Multiply, BinaryOperatorKind.Power, BinaryOperatorKind.Divide, BinaryOperatorKind.Modulo, BinaryOperatorKind.IntegerDivide, BinaryOperatorKind.LeftShift, BinaryOperatorKind.RightShift, BinaryOperatorKind.Xor, BinaryOperatorKind.Or, BinaryOperatorKind.And, BinaryOperatorKind.OrElse, BinaryOperatorKind.AndAlso, BinaryOperatorKind.Is, BinaryOperatorKind.IsNot } Dim opTokens = (From op In operators Select SyntaxFacts.GetText(OverloadResolution.GetOperatorTokenKind(op))).ToArray() Dim typeNames() As String = { "System.Object", "System.String", "System.Double", "System.SByte", "System.Int16", "System.Int32", "System.Int64", "System.Decimal", "System.Single", "System.Byte", "System.UInt16", "System.UInt32", "System.UInt64", "System.Boolean", "System.Char", "System.DateTime", "System.TypeCode", "System.StringComparison", "System.Guid", "System.Char()" } Dim builder As New System.Text.StringBuilder Dim n As Integer = 0 For Each arg1 In typeNames For Each arg2 In typeNames n += 1 builder.AppendFormat( "Sub Test{2}(x1 as {0}, y1 As {1}, x2 as System.Nullable(Of {0}), y2 As System.Nullable(Of {1}))" & vbCrLf, arg1, arg2, n) Dim k As Integer = 0 For Each opToken In opTokens builder.AppendFormat( " Dim z{0}_1 = x1 {1} y1" & vbCrLf & " Dim z{0}_2 = x2 {1} y2" & vbCrLf & " Dim z{0}_3 = x2 {1} y1" & vbCrLf & " Dim z{0}_4 = x1 {1} y2" & vbCrLf & " If x1 {1} y1" & vbCrLf & " End If" & vbCrLf & " If x2 {1} y2" & vbCrLf & " End If" & vbCrLf & " If x2 {1} y1" & vbCrLf & " End If" & vbCrLf & " If x1 {1} y2" & vbCrLf & " End If" & vbCrLf, k, opToken) k += 1 Next builder.Append( "End Sub" & vbCrLf) Next Next Dim source = <compilation> <file name="a.vb"> Class Module1 <%= New System.Xml.Linq.XCData(builder.ToString()) %> End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithOverflowChecks(True)) Dim types(typeNames.Length - 1) As NamedTypeSymbol For i As Integer = 0 To typeNames.Length - 2 types(i) = compilation.GetTypeByMetadataName(typeNames(i)) Next Assert.Null(types(types.Length - 1)) types(types.Length - 1) = compilation.GetSpecialType(SpecialType.System_String) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim nodes = (From node In tree.GetRoot().DescendantNodes() Select node = TryCast(node, BinaryExpressionSyntax) Where node IsNot Nothing).ToArray() n = 0 For Each leftType In types For Each rightType In types For Each op In operators TestIntrinsicSymbol( op, leftType, rightType, compilation, semanticModel, nodes(n), nodes(n + 1), nodes(n + 2), nodes(n + 3), nodes(n + 4), nodes(n + 5), nodes(n + 6), nodes(n + 7)) n += 8 Next Next Next Assert.Equal(n, nodes.Length) End Sub Private Sub TestIntrinsicSymbol( op As BinaryOperatorKind, leftType As TypeSymbol, rightType As TypeSymbol, compilation As VisualBasicCompilation, semanticModel As SemanticModel, node1 As BinaryExpressionSyntax, node2 As BinaryExpressionSyntax, node3 As BinaryExpressionSyntax, node4 As BinaryExpressionSyntax, node5 As BinaryExpressionSyntax, node6 As BinaryExpressionSyntax, node7 As BinaryExpressionSyntax, node8 As BinaryExpressionSyntax ) Dim info1 As SymbolInfo = semanticModel.GetSymbolInfo(node1) If (leftType.SpecialType <> SpecialType.System_Object AndAlso Not leftType.IsIntrinsicType()) OrElse (rightType.SpecialType <> SpecialType.System_Object AndAlso Not rightType.IsIntrinsicType()) OrElse (leftType.IsDateTimeType() AndAlso rightType.IsDateTimeType() AndAlso op = BinaryOperatorKind.Subtract) Then ' Let (Date - Date) use operator overloading. If info1.Symbol IsNot Nothing OrElse info1.CandidateSymbols.Length = 0 Then Assert.Equal(CandidateReason.None, info1.CandidateReason) Else Assert.Equal(CandidateReason.OverloadResolutionFailure, info1.CandidateReason) End If Else Assert.Equal(CandidateReason.None, info1.CandidateReason) Assert.Equal(0, info1.CandidateSymbols.Length) End If Dim symbol1 = DirectCast(info1.Symbol, MethodSymbol) Dim symbol2 = semanticModel.GetSymbolInfo(node2).Symbol Dim symbol3 = semanticModel.GetSymbolInfo(node3).Symbol Dim symbol4 = semanticModel.GetSymbolInfo(node4).Symbol Dim symbol5 = DirectCast(semanticModel.GetSymbolInfo(node5).Symbol, MethodSymbol) Dim symbol6 = semanticModel.GetSymbolInfo(node6).Symbol Dim symbol7 = semanticModel.GetSymbolInfo(node7).Symbol Dim symbol8 = semanticModel.GetSymbolInfo(node8).Symbol Assert.Equal(symbol1, symbol5) Assert.Equal(symbol2, symbol6) Assert.Equal(symbol3, symbol7) Assert.Equal(symbol4, symbol8) If symbol1 IsNot Nothing AndAlso symbol1.IsImplicitlyDeclared Then Assert.NotSame(symbol1, symbol5) Assert.Equal(symbol1.GetHashCode(), symbol5.GetHashCode()) For i As Integer = 0 To 1 Assert.Equal(symbol1.Parameters(i), symbol5.Parameters(i)) Assert.Equal(symbol1.Parameters(i).GetHashCode(), symbol5.Parameters(i).GetHashCode()) Next Assert.NotEqual(symbol1.Parameters(0), symbol5.Parameters(1)) End If Select Case op Case BinaryOperatorKind.AndAlso, BinaryOperatorKind.OrElse, BinaryOperatorKind.Is, BinaryOperatorKind.IsNot Assert.Null(symbol1) Assert.Null(symbol2) Assert.Null(symbol3) Assert.Null(symbol4) Return End Select Dim leftSpecial As SpecialType = leftType.GetEnumUnderlyingTypeOrSelf().SpecialType Dim rightSpecial As SpecialType = rightType.GetEnumUnderlyingTypeOrSelf().SpecialType Dim resultType As SpecialType = OverloadResolution.ResolveNotLiftedIntrinsicBinaryOperator(op, leftSpecial, rightSpecial) Dim userDefined As MethodSymbol = Nothing If resultType = SpecialType.None AndAlso (leftSpecial = SpecialType.None OrElse rightSpecial = SpecialType.None OrElse (op = BinaryOperatorKind.Subtract AndAlso leftSpecial = SpecialType.System_DateTime AndAlso rightSpecial = SpecialType.System_DateTime)) Then If leftSpecial = SpecialType.System_Object OrElse rightSpecial = SpecialType.System_Object OrElse TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything) Then If leftSpecial = SpecialType.System_Object OrElse rightSpecial = SpecialType.System_Object Then resultType = SpecialType.System_Object End If Dim nonSpecialType = If(leftSpecial = SpecialType.System_Object, rightType, leftType) For Each m In nonSpecialType.GetMembers(OverloadResolution.TryGetOperatorName(op)) If m.Kind = SymbolKind.Method Then Dim method = DirectCast(m, MethodSymbol) If method.MethodKind = MethodKind.UserDefinedOperator AndAlso method.ParameterCount = 2 AndAlso TypeSymbol.Equals(method.Parameters(0).Type, nonSpecialType, TypeCompareKind.ConsiderEverything) AndAlso TypeSymbol.Equals(method.Parameters(1).Type, nonSpecialType, TypeCompareKind.ConsiderEverything) Then userDefined = method resultType = SpecialType.None End If End If Next Else Assert.Null(symbol1) Assert.Null(symbol2) Assert.Null(symbol3) Assert.Null(symbol4) Return End If End If If resultType = SpecialType.None Then If userDefined IsNot Nothing Then Assert.False(userDefined.IsImplicitlyDeclared) Assert.Same(userDefined, symbol1) If leftType.IsValueType Then If rightType.IsValueType Then Assert.Same(userDefined, symbol2) Assert.Same(userDefined, symbol3) Assert.Same(userDefined, symbol4) Return Else Assert.Null(symbol2) Assert.Same(userDefined, symbol3) Assert.Null(symbol4) Return End If ElseIf rightType.IsValueType Then Assert.Null(symbol2) Assert.Null(symbol3) Assert.Same(userDefined, symbol4) Return Else Assert.Null(symbol2) Assert.Null(symbol3) Assert.Null(symbol4) Return End If End If Assert.Null(symbol1) Assert.Null(symbol2) Assert.Null(symbol3) Assert.Null(symbol4) Return End If Assert.NotNull(symbol1) Dim containerName As String = compilation.GetSpecialType(resultType).ToTestDisplayString() Dim rightName As String = containerName Dim returnName As String = containerName Select Case op Case BinaryOperatorKind.Equals, BinaryOperatorKind.NotEquals, BinaryOperatorKind.LessThanOrEqual, BinaryOperatorKind.GreaterThanOrEqual, BinaryOperatorKind.LessThan, BinaryOperatorKind.GreaterThan, BinaryOperatorKind.Like If resultType <> SpecialType.System_Object Then returnName = compilation.GetSpecialType(SpecialType.System_Boolean).ToTestDisplayString() End If Case BinaryOperatorKind.LeftShift, BinaryOperatorKind.RightShift If resultType <> SpecialType.System_Object Then rightName = compilation.GetSpecialType(SpecialType.System_Int32).ToTestDisplayString() End If Case BinaryOperatorKind.Xor, BinaryOperatorKind.And, BinaryOperatorKind.Or If leftType.IsEnumType() AndAlso TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything) Then containerName = leftType.ToTestDisplayString() rightName = containerName returnName = containerName End If End Select Assert.Equal(String.Format("Function {0}.{1}(left As {0}, right As {2}) As {3}", containerName, OverloadResolution.TryGetOperatorName( If(op = BinaryOperatorKind.Add AndAlso resultType = SpecialType.System_String, BinaryOperatorKind.Concatenate, op)), rightName, returnName), symbol1.ToTestDisplayString()) Assert.Equal(MethodKind.BuiltinOperator, symbol1.MethodKind) Assert.True(symbol1.IsImplicitlyDeclared) Assert.Equal((op = BinaryOperatorKind.Multiply OrElse op = BinaryOperatorKind.Add OrElse op = BinaryOperatorKind.Subtract OrElse op = BinaryOperatorKind.IntegerDivide) AndAlso symbol1.ContainingType.IsIntegralType(), symbol1.IsCheckedBuiltin) Assert.False(symbol1.IsGenericMethod) Assert.False(symbol1.IsExtensionMethod) Assert.False(symbol1.IsExternalMethod) Assert.False(symbol1.CanBeReferencedByName) Assert.Null(symbol1.DeclaringCompilation) Assert.Equal(symbol1.Name, symbol1.MetadataName) Assert.Same(symbol1.ContainingSymbol, symbol1.Parameters(0).Type) Dim match As Integer = 0 If TypeSymbol.Equals(symbol1.ContainingType, symbol1.ReturnType, TypeCompareKind.ConsiderEverything) Then match += 1 End If If TypeSymbol.Equals(symbol1.ContainingType, symbol1.Parameters(0).Type, TypeCompareKind.ConsiderEverything) Then match += 1 End If If TypeSymbol.Equals(symbol1.ContainingType, symbol1.Parameters(1).Type, TypeCompareKind.ConsiderEverything) Then match += 1 End If Assert.True(match >= 2) Assert.Equal(0, symbol1.Locations.Length) Assert.Null(symbol1.GetDocumentationCommentId) Assert.Equal("", symbol1.GetDocumentationCommentXml) Assert.True(symbol1.HasSpecialName) Assert.True(symbol1.IsShared) Assert.Equal(Accessibility.Public, symbol1.DeclaredAccessibility) Assert.False(symbol1.IsOverloads) Assert.False(symbol1.IsOverrides) Assert.False(symbol1.IsOverridable) Assert.False(symbol1.IsMustOverride) Assert.False(symbol1.IsNotOverridable) Assert.Equal(2, symbol1.ParameterCount) Assert.Equal(0, symbol1.Parameters(0).Ordinal) Assert.Equal(1, symbol1.Parameters(1).Ordinal) Dim otherSymbol = DirectCast(semanticModel.GetSymbolInfo(node1).Symbol, MethodSymbol) Assert.Equal(symbol1, otherSymbol) If leftType.IsValueType Then If rightType.IsValueType Then Assert.Equal(symbol1, symbol2) Assert.Equal(symbol1, symbol3) Assert.Equal(symbol1, symbol4) Return Else Assert.Null(symbol2) Assert.Equal(symbol1, symbol3) Assert.Null(symbol4) Return End If ElseIf rightType.IsValueType Then Assert.Null(symbol2) Assert.Null(symbol3) Assert.Equal(symbol1, symbol4) Return End If Assert.Null(symbol2) Assert.Null(symbol3) Assert.Null(symbol4) End Sub <Fact()> Public Sub CheckedIntrinsicSymbols() Dim source = <compilation> <file name="a.vb"> Class Module1 Sub Test(x as Integer, y as Integer) Dim z1 = x + y Dim z2 = x - y Dim z3 = x * y Dim z4 = x \ y End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithOverflowChecks(False)) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim nodes = (From node In tree.GetRoot().DescendantNodes() Select node = TryCast(node, BinaryExpressionSyntax) Where node IsNot Nothing).ToArray() Dim builder1 = ArrayBuilder(Of MethodSymbol).GetInstance() For Each node In nodes Dim symbol = DirectCast(semanticModel.GetSymbolInfo(node).Symbol, MethodSymbol) Assert.False(symbol.IsCheckedBuiltin) builder1.Add(symbol) Next compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOverflowChecks(True)) semanticModel = compilation.GetSemanticModel(tree) Dim builder2 = ArrayBuilder(Of MethodSymbol).GetInstance() For Each node In nodes Dim symbol = DirectCast(semanticModel.GetSymbolInfo(node).Symbol, MethodSymbol) Assert.True(symbol.IsCheckedBuiltin) builder2.Add(symbol) Next For i As Integer = 0 To builder1.Count - 1 Assert.NotEqual(builder1(i), builder2(i)) Next builder1.Free() builder2.Free() End Sub <Fact(), WorkItem(721565, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/721565")> Public Sub Bug721565() Dim source = <compilation> <file name="a.vb"><![CDATA[ Class Module1 Sub Test(x as TestStr?, y as Integer?) Dim z1 = (x Is Nothing) Dim z2 = (Nothing Is x) Dim z3 = (x IsNot Nothing) Dim z4 = (Nothing IsNot x) Dim z5 = (x = Nothing) Dim z6 = (Nothing = x) Dim z7 = (x <> Nothing) Dim z8 = (Nothing <> x) Dim z11 = (y Is Nothing) Dim z12 = (Nothing Is y) Dim z13 = (y IsNot Nothing) Dim z14 = (Nothing IsNot y) Dim z15 = (y = Nothing) Dim z16 = (Nothing = y) Dim z17 = (y <> Nothing) Dim z18 = (Nothing <> y) End Sub End Class Structure TestStr End Structure ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30452: Operator '=' is not defined for types 'TestStr?' and 'TestStr?'. Dim z5 = (x = Nothing) ~~~~~~~~~~~ BC30452: Operator '=' is not defined for types 'TestStr?' and 'TestStr?'. Dim z6 = (Nothing = x) ~~~~~~~~~~~ BC30452: Operator '<>' is not defined for types 'TestStr?' and 'TestStr?'. Dim z7 = (x <> Nothing) ~~~~~~~~~~~~ BC30452: Operator '<>' is not defined for types 'TestStr?' and 'TestStr?'. Dim z8 = (Nothing <> x) ~~~~~~~~~~~~ BC42037: This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is null consider using 'Is Nothing'. Dim z15 = (y = Nothing) ~~~~~~~~~~~ BC42037: This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is null consider using 'Is Nothing'. Dim z16 = (Nothing = y) ~~~~~~~~~~~ BC42038: This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is not null consider using 'IsNot Nothing'. Dim z17 = (y <> Nothing) ~~~~~~~~~~~~ BC42038: This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is not null consider using 'IsNot Nothing'. Dim z18 = (Nothing <> y) ~~~~~~~~~~~~ ]]></expected>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim nodes = (From node In tree.GetRoot().DescendantNodes() Select node = TryCast(node, BinaryExpressionSyntax) Where node IsNot Nothing).ToArray() Assert.Equal(16, nodes.Length) For i As Integer = 0 To nodes.Length - 1 Dim symbol = semanticModel.GetSymbolInfo(nodes(i)).Symbol Select Case i Case 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 Assert.Null(symbol) Case 12, 13 Assert.Equal("Function System.Int32.op_Equality(left As System.Int32, right As System.Int32) As System.Boolean", symbol.ToTestDisplayString()) Case 14, 15 Assert.Equal("Function System.Int32.op_Inequality(left As System.Int32, right As System.Int32) As System.Boolean", symbol.ToTestDisplayString()) Case Else Throw ExceptionUtilities.UnexpectedValue(i) End Select Next End Sub <ConditionalFact(GetType(NoIOperationValidation))> <WorkItem(43019, "https://github.com/dotnet/roslyn/issues/43019"), WorkItem(529600, "DevDiv"), WorkItem(37572, "https://github.com/dotnet/roslyn/issues/37572")> Public Sub Bug529600() Dim compilationDef = <compilation> <file name="a.vb"> Module M Sub Main() End Sub Const c0 = "<%= New String("0"c, 65000) %>" Const C1=C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 Const C2=C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilation(compilationDef) Dim err = compilation.GetDiagnostics().Single() Assert.Equal(ERRID.ERR_ConstantStringTooLong, err.Code) Assert.Equal("Length of String constant resulting from concatenation exceeds System.Int32.MaxValue. Try splitting the string into multiple constants.", err.GetMessage(EnsureEnglishUICulture.PreferredOrNull)) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim fieldInitializerOperations = tree.GetRoot().DescendantNodes().OfType(Of VariableDeclaratorSyntax)(). Select(Function(v) v.Initializer.Value). Select(Function(i) model.GetOperation(i)) Dim numChildren = 0 For Each iop in fieldInitializerOperations EnumerateChildren(iop, numChildren) Next Assert.Equal(1203, numChildren) End Sub Private Sub EnumerateChildren(iop As IOperation, ByRef numChildren as Integer) numChildren += 1 Assert.NotNull(iop) For Each child in iop.Children EnumerateChildren(child, numChildren) Next End Sub <ConditionalFact(GetType(NoIOperationValidation)), WorkItem(43019, "https://github.com/dotnet/roslyn/issues/43019"), WorkItem(37572, "https://github.com/dotnet/roslyn/issues/37572")> Public Sub TestLargeStringConcatenation() Dim mid = New StringBuilder() For i As Integer = 0 To 4999 mid.Append("""Lorem ipsum dolor sit amet"" + "", consectetur adipiscing elit, sed"" + "" do eiusmod tempor incididunt"" + "" ut labore et dolore magna aliqua. "" +" + vbCrLf) Next Dim compilationDef = <compilation> <file name="a.vb"> Module M Sub Main() Dim s As String = "BEGIN "+ <%= mid.ToString() %> "END" System.Console.WriteLine(System.Linq.Enumerable.Sum(s, Function(c As Char) System.Convert.ToInt32(c))) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilation(compilationDef, options:=TestOptions.ReleaseExe) compilation.VerifyDiagnostics() CompileAndVerify(compilation, expectedOutput:="58430604") Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim initializer = tree.GetRoot().DescendantNodes().OfType(Of VariableDeclaratorSyntax).Single().Initializer.Value Dim literalOperation = model.GetOperation(initializer) Dim stringTextBuilder As New StringBuilder() stringTextBuilder.Append("BEGIN ") For i = 0 To 4999 stringTextBuilder.Append("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ") Next stringTextBuilder.Append("END") Assert.Equal(stringTextBuilder.ToString(), literalOperation.ConstantValue.Value) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.IO Imports System.Text Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class BinaryOperators Inherits BasicTestBase <ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")> Public Sub Test1() Dim currCulture = System.Threading.Thread.CurrentThread.CurrentCulture System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("en-US", useUserOverride:=False) Try Dim compilationDef = <compilation name="VBBinaryOperators1"> <file name="lib.vb"> <%= SemanticResourceUtil.PrintResultTestSource %> </file> <file name="a.vb"> <%= SemanticResourceUtil.BinaryOperatorsTestSource1 %> </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.True(compilation.Options.CheckOverflow) CompileAndVerify(compilation, expectedOutput:=SemanticResourceUtil.BinaryOperatorsTestBaseline1) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOverflowChecks(False)) Assert.False(compilation.Options.CheckOverflow) CompileAndVerify(compilation, expectedOutput:=SemanticResourceUtil.BinaryOperatorsTestBaseline1) Catch ex As Exception Assert.Null(ex) Finally System.Threading.Thread.CurrentThread.CurrentCulture = currCulture End Try End Sub <Fact> Public Sub Test1_Date() ' test binary operator between Date value and another type data ' call ToString() on it defeat the purpose of these scenarios Dim currCulture = System.Threading.Thread.CurrentThread.CurrentCulture System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("en-US", useUserOverride:=False) Try Dim compilationDef = <compilation name="VBBinaryOperators11"> <file name="lib.vb"> <%= SemanticResourceUtil.PrintResultTestSource %> </file> <file name="a.vb"> <![CDATA[ Option Strict Off Imports System Module Module1 Sub Main() Dim BoFalse As Boolean Dim BoTrue As Boolean Dim SB As SByte Dim By As Byte Dim Sh As Short Dim US As UShort Dim [In] As Integer Dim UI As UInteger Dim Lo As Long Dim UL As ULong Dim De As Decimal Dim Si As Single Dim [Do] As Double Dim St As String Dim Ob As Object Dim Tc As System.TypeCode Dim Da As Date Dim Ch As Char Dim ChArray() As Char BoFalse = False BoTrue = True SB = -1 Sh = -3 [In] = -5 Lo = -7 De = -9D Si = 10 [Do] = -11 St = "12" Ob = "-13" Da = #8:30:00 AM# Ch = "c"c Tc = TypeCode.Double ChArray = "14" By = 22 US = 24 UI = 26 UL = 28 PrintResult("Da + St", Da + St) PrintResult("Da + Ob", Da + Ob) PrintResult("Da + Da", Da + Da) PrintResult("Da + ChArray", Da + ChArray) PrintResult("ChArray + Da", ChArray + Da) PrintResult("St + Da", St + Da) PrintResult("Ob + Da", Ob + Da) PrintResult("Da & BoFalse", Da & BoFalse) PrintResult("Da & BoTrue", Da & BoTrue) PrintResult("Da & SB", Da & SB) PrintResult("Da & By", Da & By) PrintResult("Da & Sh", Da & Sh) PrintResult("Da & US", Da & US) PrintResult("Da & [In]", Da & [In]) PrintResult("Da & UI", Da & UI) PrintResult("Da & Lo", Da & Lo) PrintResult("Da & UL", Da & UL) PrintResult("Da & De", Da & De) PrintResult("Da & Si", Da & Si) PrintResult("Da & [Do]", Da & [Do]) PrintResult("Da & St", Da & St) PrintResult("Da & Ob", Da & Ob) PrintResult("Da & Tc", Da & Tc) PrintResult("Da & Da", Da & Da) PrintResult("Da & Ch", Da & Ch) PrintResult("Da & ChArray", Da & ChArray) PrintResult("Ch & Da", Ch & Da) PrintResult("ChArray & Da", ChArray & Da) PrintResult("BoFalse & Da", BoFalse & Da) PrintResult("BoTrue & Da", BoTrue & Da) PrintResult("SB & Da", SB & Da) PrintResult("By & Da", By & Da) PrintResult("Sh & Da", Sh & Da) PrintResult("US & Da", US & Da) PrintResult("[In] & Da", [In] & Da) PrintResult("UI & Da", UI & Da) PrintResult("Lo & Da", Lo & Da) PrintResult("UL & Da", UL & Da) PrintResult("De & Da", De & Da) PrintResult("Si & Da", Si & Da) PrintResult("[Do] & Da", [Do] & Da) PrintResult("St & Da", St & Da) PrintResult("Ob & Da", Ob & Da) PrintResult("Tc & Da", Tc & Da) End Sub End Module ]]> </file> </compilation> Dim expected = <![CDATA[[Da + St] String: [8:30:00 AM12] [Da + Ob] Object: 8:30:00 AM-13 [Da + Da] String: [8:30:00 AM8:30:00 AM] [Da + ChArray] String: [8:30:00 AM14] [ChArray + Da] String: [148:30:00 AM] [St + Da] String: [128:30:00 AM] [Ob + Da] Object: -138:30:00 AM [Da & BoFalse] String: [8:30:00 AMFalse] [Da & BoTrue] String: [8:30:00 AMTrue] [Da & SB] String: [8:30:00 AM-1] [Da & By] String: [8:30:00 AM22] [Da & Sh] String: [8:30:00 AM-3] [Da & US] String: [8:30:00 AM24] [Da & [In]] String: [8:30:00 AM-5] [Da & UI] String: [8:30:00 AM26] [Da & Lo] String: [8:30:00 AM-7] [Da & UL] String: [8:30:00 AM28] [Da & De] String: [8:30:00 AM-9] [Da & Si] String: [8:30:00 AM10] [Da & [Do]] String: [8:30:00 AM-11] [Da & St] String: [8:30:00 AM12] [Da & Ob] Object: 8:30:00 AM-13 [Da & Tc] String: [8:30:00 AM14] [Da & Da] String: [8:30:00 AM8:30:00 AM] [Da & Ch] String: [8:30:00 AMc] [Da & ChArray] String: [8:30:00 AM14] [Ch & Da] String: [c8:30:00 AM] [ChArray & Da] String: [148:30:00 AM] [BoFalse & Da] String: [False8:30:00 AM] [BoTrue & Da] String: [True8:30:00 AM] [SB & Da] String: [-18:30:00 AM] [By & Da] String: [228:30:00 AM] [Sh & Da] String: [-38:30:00 AM] [US & Da] String: [248:30:00 AM] [[In] & Da] String: [-58:30:00 AM] [UI & Da] String: [268:30:00 AM] [Lo & Da] String: [-78:30:00 AM] [UL & Da] String: [288:30:00 AM] [De & Da] String: [-98:30:00 AM] [Si & Da] String: [108:30:00 AM] [[Do] & Da] String: [-118:30:00 AM] [St & Da] String: [128:30:00 AM] [Ob & Da] Object: -138:30:00 AM [Tc & Da] String: [148:30:00 AM]]]> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.True(compilation.Options.CheckOverflow) CompileAndVerify(compilation, expectedOutput:=expected) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOverflowChecks(False)) Assert.False(compilation.Options.CheckOverflow) CompileAndVerify(compilation, expectedOutput:=expected) Catch ex As Exception Assert.Null(ex) Finally System.Threading.Thread.CurrentThread.CurrentCulture = currCulture End Try End Sub <Fact> Public Sub Test2() Dim compilationDef = <compilation name="VBBinaryOperators2"> <file name="a.vb"> <%= SemanticResourceUtil.BinaryOperatorsTestSource2 %> </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, SemanticResourceUtil.BinaryOperatorsTestBaseline2) End Sub <Fact> Public Sub Test30() Dim compilationDef = <compilation name="VBBinaryOperators30"> <file name="a.vb"> Option Strict Off Imports System Module Module1 Sub Main() Dim St1 As String Dim St2 As String Dim Ob1 As Object Dim Ob2 As Object St1 = "a" St2 = "a" Ob1 = "a" Ob2 = "a" Console.WriteLine(St1 = St2) Console.WriteLine(Ob1 = Ob2) St1 = "a" St2 = "A" Ob1 = "a" Ob2 = "A" Console.WriteLine(St1 = St2) Console.WriteLine(Ob1 = Ob2) St1 = "a" St2 = "b" Ob1 = "a" Ob2 = "b" Console.WriteLine(St1 = St2) Console.WriteLine(Ob1 = Ob2) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.False(compilation.Options.OptionCompareText) CompileAndVerify(compilation, <![CDATA[ True True False False False False ]]>) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOptionCompareText(True)) Assert.True(compilation.Options.OptionCompareText) CompileAndVerify(compilation, <![CDATA[ True True True True False False ]]>) End Sub <Fact> Public Sub Test3() Dim compilationDef = <compilation name="VBBinaryOperators3"> <file name="a.vb"> <%= SemanticResourceUtil.BinaryOperatorsTestSource3 %> </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, SemanticResourceUtil.BinaryOperatorsTestBaseline3) End Sub <Fact> Public Sub Test4() Dim compilationDef = <compilation name="VBBinaryOperators4"> <file name="a.vb"> <%= SemanticResourceUtil.BinaryOperatorsTestSource4 %> </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:=SemanticResourceUtil.BinaryOperatorsTestBaseline4) End Sub <ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")> Public Sub Test5() Dim compilationDef = <compilation name="VBBinaryOperators52"> <file name="lib.vb"> <%= SemanticResourceUtil.PrintResultTestSource %> </file> <file name="a.vb"> <%= SemanticResourceUtil.BinaryOperatorsTestSource5 %> </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.True(compilation.Options.CheckOverflow) CompileAndVerify(compilation, expectedOutput:=SemanticResourceUtil.BinaryOperatorsTestBaseline5) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOverflowChecks(False)) Assert.False(compilation.Options.CheckOverflow) CompileAndVerify(compilation, expectedOutput:=SemanticResourceUtil.BinaryOperatorsTestBaseline5) End Sub <Fact> Public Sub Test5_DateConst() ' test binary operator between Date const and another type data ' call ToString() on it defeat the purpose of these scenarios Dim currCulture = System.Threading.Thread.CurrentThread.CurrentCulture System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("en-US", useUserOverride:=False) Try Dim compilationDef = <compilation name="VBBinaryOperators52"> <file name="lib.vb"> <%= SemanticResourceUtil.PrintResultTestSource %> </file> <file name="a.vb"> <![CDATA[ Option Strict Off Imports System Module Module1 Sub Main() PrintResult("#8:30:00 AM# + ""12""", #8:30:00 AM# + "12") PrintResult("#8:30:00 AM# + #8:30:00 AM#", #8:30:00 AM# + #8:30:00 AM#) PrintResult("""12"" + #8:30:00 AM#", "12" + #8:30:00 AM#) PrintResult("#8:30:00 AM# & False", #8:30:00 AM# & False) PrintResult("#8:30:00 AM# & True", #8:30:00 AM# & True) PrintResult("#8:30:00 AM# & System.SByte.MinValue", #8:30:00 AM# & System.SByte.MinValue) PrintResult("#8:30:00 AM# & System.Byte.MaxValue", #8:30:00 AM# & System.Byte.MaxValue) PrintResult("#8:30:00 AM# & -3S", #8:30:00 AM# & -3S) PrintResult("#8:30:00 AM# & 24US", #8:30:00 AM# & 24US) PrintResult("#8:30:00 AM# & -5I", #8:30:00 AM# & -5I) PrintResult("#8:30:00 AM# & 26UI", #8:30:00 AM# & 26UI) PrintResult("#8:30:00 AM# & -7L", #8:30:00 AM# & -7L) PrintResult("#8:30:00 AM# & 28UL", #8:30:00 AM# & 28UL) PrintResult("#8:30:00 AM# & -9D", #8:30:00 AM# & -9D) PrintResult("#8:30:00 AM# & 10.0F", #8:30:00 AM# & 10.0F) PrintResult("#8:30:00 AM# & -11.0R", #8:30:00 AM# & -11.0R) PrintResult("#8:30:00 AM# & ""12""", #8:30:00 AM# & "12") PrintResult("#8:30:00 AM# & TypeCode.Double", #8:30:00 AM# & TypeCode.Double) PrintResult("#8:30:00 AM# & #8:30:00 AM#", #8:30:00 AM# & #8:30:00 AM#) PrintResult("#8:30:00 AM# & ""c""c", #8:30:00 AM# & "c"c) PrintResult("""c""c & #8:30:00 AM#", "c"c & #8:30:00 AM#) PrintResult("False & #8:30:00 AM#", False & #8:30:00 AM#) PrintResult("True & #8:30:00 AM#", True & #8:30:00 AM#) PrintResult("System.SByte.MinValue & #8:30:00 AM#", System.SByte.MinValue & #8:30:00 AM#) PrintResult("System.Byte.MaxValue & #8:30:00 AM#", System.Byte.MaxValue & #8:30:00 AM#) PrintResult("-3S & #8:30:00 AM#", -3S & #8:30:00 AM#) PrintResult("24US & #8:30:00 AM#", 24US & #8:30:00 AM#) PrintResult("-5I & #8:30:00 AM#", -5I & #8:30:00 AM#) PrintResult("26UI & #8:30:00 AM#", 26UI & #8:30:00 AM#) PrintResult("-7L & #8:30:00 AM#", -7L & #8:30:00 AM#) PrintResult("28UL & #8:30:00 AM#", 28UL & #8:30:00 AM#) PrintResult("-9D & #8:30:00 AM#", -9D & #8:30:00 AM#) PrintResult("10.0F & #8:30:00 AM#", 10.0F & #8:30:00 AM#) PrintResult("-11.0R & #8:30:00 AM#", -11.0R & #8:30:00 AM#) PrintResult("""12"" & #8:30:00 AM#", "12" & #8:30:00 AM#) PrintResult("TypeCode.Double & #8:30:00 AM#", TypeCode.Double & #8:30:00 AM#) End Sub End Module ]]> </file> </compilation> Dim expected = <![CDATA[[#8:30:00 AM# + "12"] String: [8:30:00 AM12] [#8:30:00 AM# + #8:30:00 AM#] String: [8:30:00 AM8:30:00 AM] ["12" + #8:30:00 AM#] String: [128:30:00 AM] [#8:30:00 AM# & False] String: [8:30:00 AMFalse] [#8:30:00 AM# & True] String: [8:30:00 AMTrue] [#8:30:00 AM# & System.SByte.MinValue] String: [8:30:00 AM-128] [#8:30:00 AM# & System.Byte.MaxValue] String: [8:30:00 AM255] [#8:30:00 AM# & -3S] String: [8:30:00 AM-3] [#8:30:00 AM# & 24US] String: [8:30:00 AM24] [#8:30:00 AM# & -5I] String: [8:30:00 AM-5] [#8:30:00 AM# & 26UI] String: [8:30:00 AM26] [#8:30:00 AM# & -7L] String: [8:30:00 AM-7] [#8:30:00 AM# & 28UL] String: [8:30:00 AM28] [#8:30:00 AM# & -9D] String: [8:30:00 AM-9] [#8:30:00 AM# & 10.0F] String: [8:30:00 AM10] [#8:30:00 AM# & -11.0R] String: [8:30:00 AM-11] [#8:30:00 AM# & "12"] String: [8:30:00 AM12] [#8:30:00 AM# & TypeCode.Double] String: [8:30:00 AM14] [#8:30:00 AM# & #8:30:00 AM#] String: [8:30:00 AM8:30:00 AM] [#8:30:00 AM# & "c"c] String: [8:30:00 AMc] ["c"c & #8:30:00 AM#] String: [c8:30:00 AM] [False & #8:30:00 AM#] String: [False8:30:00 AM] [True & #8:30:00 AM#] String: [True8:30:00 AM] [System.SByte.MinValue & #8:30:00 AM#] String: [-1288:30:00 AM] [System.Byte.MaxValue & #8:30:00 AM#] String: [2558:30:00 AM] [-3S & #8:30:00 AM#] String: [-38:30:00 AM] [24US & #8:30:00 AM#] String: [248:30:00 AM] [-5I & #8:30:00 AM#] String: [-58:30:00 AM] [26UI & #8:30:00 AM#] String: [268:30:00 AM] [-7L & #8:30:00 AM#] String: [-78:30:00 AM] [28UL & #8:30:00 AM#] String: [288:30:00 AM] [-9D & #8:30:00 AM#] String: [-98:30:00 AM] [10.0F & #8:30:00 AM#] String: [108:30:00 AM] [-11.0R & #8:30:00 AM#] String: [-118:30:00 AM] ["12" & #8:30:00 AM#] String: [128:30:00 AM] [TypeCode.Double & #8:30:00 AM#] String: [148:30:00 AM] ]]> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.True(compilation.Options.CheckOverflow) CompileAndVerify(compilation, expectedOutput:=expected) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOverflowChecks(False)) Assert.False(compilation.Options.CheckOverflow) CompileAndVerify(compilation, expectedOutput:=expected) Catch ex As Exception Assert.Null(ex) Finally System.Threading.Thread.CurrentThread.CurrentCulture = currCulture End Try End Sub <Fact> Public Sub Test7() Dim compilationDef = <compilation name="VBBinaryOperators7"> <file name="a.vb"> Option Strict Off Imports System Module Module1 Sub Main() Dim ob As Object ob = System.SByte.MinValue + (System.SByte.MaxValue + System.SByte.MinValue) ob = System.Byte.MinValue - (System.Byte.MaxValue \ System.Byte.MaxValue) ob = System.Int16.MinValue - 1S ob = System.UInt16.MinValue - 1US ob = System.Int32.MinValue - 1I ob = System.UInt32.MinValue - 1UI ob = System.Int64.MinValue - 1L ob = System.UInt64.MinValue - 1UL ob = -79228162514264337593543950335D - 1D ob = System.SByte.MaxValue - (System.SByte.MaxValue + System.SByte.MinValue) ob = System.Byte.MaxValue + (System.Byte.MaxValue \ System.Byte.MaxValue) ob = System.Int16.MaxValue + 1S ob = System.UInt16.MaxValue + 1US ob = System.Int32.MaxValue + 1I ob = System.UInt32.MaxValue + 1UI ob = System.Int64.MaxValue + 1L ob = System.UInt64.MaxValue + 1UL ob = 79228162514264337593543950335D + 1D ob = (2I \ 0) ob = (1.5F \ 0) ob = (2.5R \ 0) ob = (3.5D \ 0) ob = (2I Mod 0) ob = (3.5D Mod 0) ob = (3.5D / Nothing) ob = (2I \ Nothing) ob = (1.5F \ Nothing) ob = (2.5R \ Nothing) ob = (3.5D \ Nothing) ob = (2I Mod Nothing) ob = (3.5D Mod Nothing) ob = (3.5D / 0) ob = System.UInt64.MaxValue * 2UL ob = System.Int64.MaxValue * 2L ob = System.Int64.MinValue * (-2L) ob = 3L * (System.Int64.MinValue \ 2L) ob = (System.Int64.MinValue \ 2L) * 3L ob = System.Int64.MinValue \ (-1L) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30439: Constant expression not representable in type 'SByte'. ob = System.SByte.MinValue + (System.SByte.MaxValue + System.SByte.MinValue) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Byte'. ob = System.Byte.MinValue - (System.Byte.MaxValue \ System.Byte.MaxValue) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Short'. ob = System.Int16.MinValue - 1S ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'UShort'. ob = System.UInt16.MinValue - 1US ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Integer'. ob = System.Int32.MinValue - 1I ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'UInteger'. ob = System.UInt32.MinValue - 1UI ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Long'. ob = System.Int64.MinValue - 1L ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'ULong'. ob = System.UInt64.MinValue - 1UL ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Decimal'. ob = -79228162514264337593543950335D - 1D ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'SByte'. ob = System.SByte.MaxValue - (System.SByte.MaxValue + System.SByte.MinValue) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Byte'. ob = System.Byte.MaxValue + (System.Byte.MaxValue \ System.Byte.MaxValue) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Short'. ob = System.Int16.MaxValue + 1S ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'UShort'. ob = System.UInt16.MaxValue + 1US ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Integer'. ob = System.Int32.MaxValue + 1I ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'UInteger'. ob = System.UInt32.MaxValue + 1UI ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Long'. ob = System.Int64.MaxValue + 1L ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'ULong'. ob = System.UInt64.MaxValue + 1UL ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Decimal'. ob = 79228162514264337593543950335D + 1D ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (2I \ 0) ~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (1.5F \ 0) ~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (2.5R \ 0) ~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (3.5D \ 0) ~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (2I Mod 0) ~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (3.5D Mod 0) ~~~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (3.5D / Nothing) ~~~~~~~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (2I \ Nothing) ~~~~~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (1.5F \ Nothing) ~~~~~~~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (2.5R \ Nothing) ~~~~~~~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (3.5D \ Nothing) ~~~~~~~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (2I Mod Nothing) ~~~~~~~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (3.5D Mod Nothing) ~~~~~~~~~~~~~~~~ BC30542: Division by zero occurred while evaluating this expression. ob = (3.5D / 0) ~~~~~~~~ BC30439: Constant expression not representable in type 'ULong'. ob = System.UInt64.MaxValue * 2UL ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Long'. ob = System.Int64.MaxValue * 2L ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Long'. ob = System.Int64.MinValue * (-2L) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Long'. ob = 3L * (System.Int64.MinValue \ 2L) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Long'. ob = (System.Int64.MinValue \ 2L) * 3L ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Long'. ob = System.Int64.MinValue \ (-1L) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub Test8() Dim compilationDef = <compilation name="VBBinaryOperators8"> <file name="a.vb"> Imports System Module Module1 Sub Main() Dim Ob As Object = Nothing Ob = Ob-Ob Ob = Ob = Ob Ob = Ob &lt;&gt; Ob Ob = Ob &gt; Ob End Sub End Module </file> </compilation> Dim expected = <expected> BC42019: Operands of type Object used for operator '-'; runtime errors could occur. Ob = Ob-Ob ~~ BC42019: Operands of type Object used for operator '-'; runtime errors could occur. Ob = Ob-Ob ~~ BC42018: Operands of type Object used for operator '='; use the 'Is' operator to test object identity. Ob = Ob = Ob ~~ BC42018: Operands of type Object used for operator '='; use the 'Is' operator to test object identity. Ob = Ob = Ob ~~ BC42032: Operands of type Object used for operator '&lt;&gt;'; use the 'IsNot' operator to test object identity. Ob = Ob &lt;&gt; Ob ~~ BC42032: Operands of type Object used for operator '&lt;&gt;'; use the 'IsNot' operator to test object identity. Ob = Ob &lt;&gt; Ob ~~ BC42019: Operands of type Object used for operator '&gt;'; runtime errors could occur. Ob = Ob &gt; Ob ~~ BC42019: Operands of type Object used for operator '&gt;'; runtime errors could occur. Ob = Ob &gt; Ob ~~ </expected> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) CompilationUtils.AssertTheseDiagnostics(compilation, expected) End Sub <WorkItem(543387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543387")> <Fact()> Public Sub Test9() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main() If Nothing = Function() 5 Then 'BIND1:"Nothing = Function() 5" System.Console.WriteLine("Failed") Else System.Console.WriteLine("Succeeded") End If End Sub End Module ]]></file> </compilation>, options:=TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) CompileAndVerify(compilation, expectedOutput:= <![CDATA[ Succeeded ]]>) AssertTheseDiagnostics(compilation, <expected> </expected>) Dim model = GetSemanticModel(compilation, "a.vb") Dim node As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo = model.GetSymbolInfo(node) Assert.Equal("Public Shared Overloads Operator =(d1 As System.MulticastDelegate, d2 As System.MulticastDelegate) As Boolean", symbolInfo.Symbol.ToDisplayString()) End Sub <WorkItem(544620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")> <Fact()> Public Sub Bug13088() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Public Const Z As Integer = Integer.MaxValue + 1 'BIND:"Public Const Z As Integer = Integer.MaxValue + 1" Sub Main() End Sub End Module ]]></file> </compilation>) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_ExpressionOverflow1, "Integer.MaxValue + 1").WithArguments("Integer")) Dim symbol = compilation.GlobalNamespace.GetTypeMembers("Program").Single.GetMembers("Z").Single Assert.False(DirectCast(symbol, FieldSymbol).HasConstantValue) End Sub <Fact(), WorkItem(531531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531531")> <CompilerTrait(CompilerFeature.IOperation)> Public Sub Bug18257() Dim source = <compilation name="ErrorHandling"> <file name="a.vb"> <![CDATA[ Option Strict On Public Class TestState Shared Function IsImmediateWindow1(line As Integer?) As String Dim s = "Expected: " & line & "." Return s End Function Shared Function IsImmediateWindow2(line As Integer) As String Dim s = "Expected: " & line & "." Return s End Function End Class Module Module1 Sub Main() System.Console.WriteLine(TestState.IsImmediateWindow1(Nothing)) System.Console.WriteLine(TestState.IsImmediateWindow2(Nothing)) End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) Dim compilationVerifier = CompileAndVerify(compilation, expectedOutput:= <![CDATA[ Expected: . Expected: 0. ]]>) Dim tree = compilation.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of LocalDeclarationStatementSyntax)().First() Assert.Equal("Dim s = ""Expected: "" & line & "".""", node.ToString()) compilation.VerifyOperationTree(node.Declarators.Last.Initializer.Value, expectedOperationTree:= <![CDATA[ IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: '"Expected: ... line & "."') Left: IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: '"Expected: " & line') Left: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Expected: ") (Syntax: '"Expected: "') Right: ICoalesceOperation (OperationKind.Coalesce, Type: System.String, IsImplicit) (Syntax: 'line') Expression: IParameterReferenceOperation: line (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'line') ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NarrowingString) WhenNull: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: null, IsImplicit) (Syntax: 'line') Right: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ".") (Syntax: '"."') ]]>.Value) End Sub <ConditionalFact(GetType(NoIOperationValidation))> Public Sub IntrinsicSymbols() Dim operators() As BinaryOperatorKind = { BinaryOperatorKind.Add, BinaryOperatorKind.Concatenate, BinaryOperatorKind.Like, BinaryOperatorKind.Equals, BinaryOperatorKind.NotEquals, BinaryOperatorKind.LessThanOrEqual, BinaryOperatorKind.GreaterThanOrEqual, BinaryOperatorKind.LessThan, BinaryOperatorKind.GreaterThan, BinaryOperatorKind.Subtract, BinaryOperatorKind.Multiply, BinaryOperatorKind.Power, BinaryOperatorKind.Divide, BinaryOperatorKind.Modulo, BinaryOperatorKind.IntegerDivide, BinaryOperatorKind.LeftShift, BinaryOperatorKind.RightShift, BinaryOperatorKind.Xor, BinaryOperatorKind.Or, BinaryOperatorKind.And, BinaryOperatorKind.OrElse, BinaryOperatorKind.AndAlso, BinaryOperatorKind.Is, BinaryOperatorKind.IsNot } Dim opTokens = (From op In operators Select SyntaxFacts.GetText(OverloadResolution.GetOperatorTokenKind(op))).ToArray() Dim typeNames() As String = { "System.Object", "System.String", "System.Double", "System.SByte", "System.Int16", "System.Int32", "System.Int64", "System.Decimal", "System.Single", "System.Byte", "System.UInt16", "System.UInt32", "System.UInt64", "System.Boolean", "System.Char", "System.DateTime", "System.TypeCode", "System.StringComparison", "System.Guid", "System.Char()" } Dim builder As New System.Text.StringBuilder Dim n As Integer = 0 For Each arg1 In typeNames For Each arg2 In typeNames n += 1 builder.AppendFormat( "Sub Test{2}(x1 as {0}, y1 As {1}, x2 as System.Nullable(Of {0}), y2 As System.Nullable(Of {1}))" & vbCrLf, arg1, arg2, n) Dim k As Integer = 0 For Each opToken In opTokens builder.AppendFormat( " Dim z{0}_1 = x1 {1} y1" & vbCrLf & " Dim z{0}_2 = x2 {1} y2" & vbCrLf & " Dim z{0}_3 = x2 {1} y1" & vbCrLf & " Dim z{0}_4 = x1 {1} y2" & vbCrLf & " If x1 {1} y1" & vbCrLf & " End If" & vbCrLf & " If x2 {1} y2" & vbCrLf & " End If" & vbCrLf & " If x2 {1} y1" & vbCrLf & " End If" & vbCrLf & " If x1 {1} y2" & vbCrLf & " End If" & vbCrLf, k, opToken) k += 1 Next builder.Append( "End Sub" & vbCrLf) Next Next Dim source = <compilation> <file name="a.vb"> Class Module1 <%= New System.Xml.Linq.XCData(builder.ToString()) %> End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithOverflowChecks(True)) Dim types(typeNames.Length - 1) As NamedTypeSymbol For i As Integer = 0 To typeNames.Length - 2 types(i) = compilation.GetTypeByMetadataName(typeNames(i)) Next Assert.Null(types(types.Length - 1)) types(types.Length - 1) = compilation.GetSpecialType(SpecialType.System_String) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim nodes = (From node In tree.GetRoot().DescendantNodes() Select node = TryCast(node, BinaryExpressionSyntax) Where node IsNot Nothing).ToArray() n = 0 For Each leftType In types For Each rightType In types For Each op In operators TestIntrinsicSymbol( op, leftType, rightType, compilation, semanticModel, nodes(n), nodes(n + 1), nodes(n + 2), nodes(n + 3), nodes(n + 4), nodes(n + 5), nodes(n + 6), nodes(n + 7)) n += 8 Next Next Next Assert.Equal(n, nodes.Length) End Sub Private Sub TestIntrinsicSymbol( op As BinaryOperatorKind, leftType As TypeSymbol, rightType As TypeSymbol, compilation As VisualBasicCompilation, semanticModel As SemanticModel, node1 As BinaryExpressionSyntax, node2 As BinaryExpressionSyntax, node3 As BinaryExpressionSyntax, node4 As BinaryExpressionSyntax, node5 As BinaryExpressionSyntax, node6 As BinaryExpressionSyntax, node7 As BinaryExpressionSyntax, node8 As BinaryExpressionSyntax ) Dim info1 As SymbolInfo = semanticModel.GetSymbolInfo(node1) If (leftType.SpecialType <> SpecialType.System_Object AndAlso Not leftType.IsIntrinsicType()) OrElse (rightType.SpecialType <> SpecialType.System_Object AndAlso Not rightType.IsIntrinsicType()) OrElse (leftType.IsDateTimeType() AndAlso rightType.IsDateTimeType() AndAlso op = BinaryOperatorKind.Subtract) Then ' Let (Date - Date) use operator overloading. If info1.Symbol IsNot Nothing OrElse info1.CandidateSymbols.Length = 0 Then Assert.Equal(CandidateReason.None, info1.CandidateReason) Else Assert.Equal(CandidateReason.OverloadResolutionFailure, info1.CandidateReason) End If Else Assert.Equal(CandidateReason.None, info1.CandidateReason) Assert.Equal(0, info1.CandidateSymbols.Length) End If Dim symbol1 = DirectCast(info1.Symbol, MethodSymbol) Dim symbol2 = semanticModel.GetSymbolInfo(node2).Symbol Dim symbol3 = semanticModel.GetSymbolInfo(node3).Symbol Dim symbol4 = semanticModel.GetSymbolInfo(node4).Symbol Dim symbol5 = DirectCast(semanticModel.GetSymbolInfo(node5).Symbol, MethodSymbol) Dim symbol6 = semanticModel.GetSymbolInfo(node6).Symbol Dim symbol7 = semanticModel.GetSymbolInfo(node7).Symbol Dim symbol8 = semanticModel.GetSymbolInfo(node8).Symbol Assert.Equal(symbol1, symbol5) Assert.Equal(symbol2, symbol6) Assert.Equal(symbol3, symbol7) Assert.Equal(symbol4, symbol8) If symbol1 IsNot Nothing AndAlso symbol1.IsImplicitlyDeclared Then Assert.NotSame(symbol1, symbol5) Assert.Equal(symbol1.GetHashCode(), symbol5.GetHashCode()) For i As Integer = 0 To 1 Assert.Equal(symbol1.Parameters(i), symbol5.Parameters(i)) Assert.Equal(symbol1.Parameters(i).GetHashCode(), symbol5.Parameters(i).GetHashCode()) Next Assert.NotEqual(symbol1.Parameters(0), symbol5.Parameters(1)) End If Select Case op Case BinaryOperatorKind.AndAlso, BinaryOperatorKind.OrElse, BinaryOperatorKind.Is, BinaryOperatorKind.IsNot Assert.Null(symbol1) Assert.Null(symbol2) Assert.Null(symbol3) Assert.Null(symbol4) Return End Select Dim leftSpecial As SpecialType = leftType.GetEnumUnderlyingTypeOrSelf().SpecialType Dim rightSpecial As SpecialType = rightType.GetEnumUnderlyingTypeOrSelf().SpecialType Dim resultType As SpecialType = OverloadResolution.ResolveNotLiftedIntrinsicBinaryOperator(op, leftSpecial, rightSpecial) Dim userDefined As MethodSymbol = Nothing If resultType = SpecialType.None AndAlso (leftSpecial = SpecialType.None OrElse rightSpecial = SpecialType.None OrElse (op = BinaryOperatorKind.Subtract AndAlso leftSpecial = SpecialType.System_DateTime AndAlso rightSpecial = SpecialType.System_DateTime)) Then If leftSpecial = SpecialType.System_Object OrElse rightSpecial = SpecialType.System_Object OrElse TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything) Then If leftSpecial = SpecialType.System_Object OrElse rightSpecial = SpecialType.System_Object Then resultType = SpecialType.System_Object End If Dim nonSpecialType = If(leftSpecial = SpecialType.System_Object, rightType, leftType) For Each m In nonSpecialType.GetMembers(OverloadResolution.TryGetOperatorName(op)) If m.Kind = SymbolKind.Method Then Dim method = DirectCast(m, MethodSymbol) If method.MethodKind = MethodKind.UserDefinedOperator AndAlso method.ParameterCount = 2 AndAlso TypeSymbol.Equals(method.Parameters(0).Type, nonSpecialType, TypeCompareKind.ConsiderEverything) AndAlso TypeSymbol.Equals(method.Parameters(1).Type, nonSpecialType, TypeCompareKind.ConsiderEverything) Then userDefined = method resultType = SpecialType.None End If End If Next Else Assert.Null(symbol1) Assert.Null(symbol2) Assert.Null(symbol3) Assert.Null(symbol4) Return End If End If If resultType = SpecialType.None Then If userDefined IsNot Nothing Then Assert.False(userDefined.IsImplicitlyDeclared) Assert.Same(userDefined, symbol1) If leftType.IsValueType Then If rightType.IsValueType Then Assert.Same(userDefined, symbol2) Assert.Same(userDefined, symbol3) Assert.Same(userDefined, symbol4) Return Else Assert.Null(symbol2) Assert.Same(userDefined, symbol3) Assert.Null(symbol4) Return End If ElseIf rightType.IsValueType Then Assert.Null(symbol2) Assert.Null(symbol3) Assert.Same(userDefined, symbol4) Return Else Assert.Null(symbol2) Assert.Null(symbol3) Assert.Null(symbol4) Return End If End If Assert.Null(symbol1) Assert.Null(symbol2) Assert.Null(symbol3) Assert.Null(symbol4) Return End If Assert.NotNull(symbol1) Dim containerName As String = compilation.GetSpecialType(resultType).ToTestDisplayString() Dim rightName As String = containerName Dim returnName As String = containerName Select Case op Case BinaryOperatorKind.Equals, BinaryOperatorKind.NotEquals, BinaryOperatorKind.LessThanOrEqual, BinaryOperatorKind.GreaterThanOrEqual, BinaryOperatorKind.LessThan, BinaryOperatorKind.GreaterThan, BinaryOperatorKind.Like If resultType <> SpecialType.System_Object Then returnName = compilation.GetSpecialType(SpecialType.System_Boolean).ToTestDisplayString() End If Case BinaryOperatorKind.LeftShift, BinaryOperatorKind.RightShift If resultType <> SpecialType.System_Object Then rightName = compilation.GetSpecialType(SpecialType.System_Int32).ToTestDisplayString() End If Case BinaryOperatorKind.Xor, BinaryOperatorKind.And, BinaryOperatorKind.Or If leftType.IsEnumType() AndAlso TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything) Then containerName = leftType.ToTestDisplayString() rightName = containerName returnName = containerName End If End Select Assert.Equal(String.Format("Function {0}.{1}(left As {0}, right As {2}) As {3}", containerName, OverloadResolution.TryGetOperatorName( If(op = BinaryOperatorKind.Add AndAlso resultType = SpecialType.System_String, BinaryOperatorKind.Concatenate, op)), rightName, returnName), symbol1.ToTestDisplayString()) Assert.Equal(MethodKind.BuiltinOperator, symbol1.MethodKind) Assert.True(symbol1.IsImplicitlyDeclared) Assert.Equal((op = BinaryOperatorKind.Multiply OrElse op = BinaryOperatorKind.Add OrElse op = BinaryOperatorKind.Subtract OrElse op = BinaryOperatorKind.IntegerDivide) AndAlso symbol1.ContainingType.IsIntegralType(), symbol1.IsCheckedBuiltin) Assert.False(symbol1.IsGenericMethod) Assert.False(symbol1.IsExtensionMethod) Assert.False(symbol1.IsExternalMethod) Assert.False(symbol1.CanBeReferencedByName) Assert.Null(symbol1.DeclaringCompilation) Assert.Equal(symbol1.Name, symbol1.MetadataName) Assert.Same(symbol1.ContainingSymbol, symbol1.Parameters(0).Type) Dim match As Integer = 0 If TypeSymbol.Equals(symbol1.ContainingType, symbol1.ReturnType, TypeCompareKind.ConsiderEverything) Then match += 1 End If If TypeSymbol.Equals(symbol1.ContainingType, symbol1.Parameters(0).Type, TypeCompareKind.ConsiderEverything) Then match += 1 End If If TypeSymbol.Equals(symbol1.ContainingType, symbol1.Parameters(1).Type, TypeCompareKind.ConsiderEverything) Then match += 1 End If Assert.True(match >= 2) Assert.Equal(0, symbol1.Locations.Length) Assert.Null(symbol1.GetDocumentationCommentId) Assert.Equal("", symbol1.GetDocumentationCommentXml) Assert.True(symbol1.HasSpecialName) Assert.True(symbol1.IsShared) Assert.Equal(Accessibility.Public, symbol1.DeclaredAccessibility) Assert.False(symbol1.IsOverloads) Assert.False(symbol1.IsOverrides) Assert.False(symbol1.IsOverridable) Assert.False(symbol1.IsMustOverride) Assert.False(symbol1.IsNotOverridable) Assert.Equal(2, symbol1.ParameterCount) Assert.Equal(0, symbol1.Parameters(0).Ordinal) Assert.Equal(1, symbol1.Parameters(1).Ordinal) Dim otherSymbol = DirectCast(semanticModel.GetSymbolInfo(node1).Symbol, MethodSymbol) Assert.Equal(symbol1, otherSymbol) If leftType.IsValueType Then If rightType.IsValueType Then Assert.Equal(symbol1, symbol2) Assert.Equal(symbol1, symbol3) Assert.Equal(symbol1, symbol4) Return Else Assert.Null(symbol2) Assert.Equal(symbol1, symbol3) Assert.Null(symbol4) Return End If ElseIf rightType.IsValueType Then Assert.Null(symbol2) Assert.Null(symbol3) Assert.Equal(symbol1, symbol4) Return End If Assert.Null(symbol2) Assert.Null(symbol3) Assert.Null(symbol4) End Sub <Fact()> Public Sub CheckedIntrinsicSymbols() Dim source = <compilation> <file name="a.vb"> Class Module1 Sub Test(x as Integer, y as Integer) Dim z1 = x + y Dim z2 = x - y Dim z3 = x * y Dim z4 = x \ y End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithOverflowChecks(False)) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim nodes = (From node In tree.GetRoot().DescendantNodes() Select node = TryCast(node, BinaryExpressionSyntax) Where node IsNot Nothing).ToArray() Dim builder1 = ArrayBuilder(Of MethodSymbol).GetInstance() For Each node In nodes Dim symbol = DirectCast(semanticModel.GetSymbolInfo(node).Symbol, MethodSymbol) Assert.False(symbol.IsCheckedBuiltin) builder1.Add(symbol) Next compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOverflowChecks(True)) semanticModel = compilation.GetSemanticModel(tree) Dim builder2 = ArrayBuilder(Of MethodSymbol).GetInstance() For Each node In nodes Dim symbol = DirectCast(semanticModel.GetSymbolInfo(node).Symbol, MethodSymbol) Assert.True(symbol.IsCheckedBuiltin) builder2.Add(symbol) Next For i As Integer = 0 To builder1.Count - 1 Assert.NotEqual(builder1(i), builder2(i)) Next builder1.Free() builder2.Free() End Sub <Fact(), WorkItem(721565, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/721565")> Public Sub Bug721565() Dim source = <compilation> <file name="a.vb"><![CDATA[ Class Module1 Sub Test(x as TestStr?, y as Integer?) Dim z1 = (x Is Nothing) Dim z2 = (Nothing Is x) Dim z3 = (x IsNot Nothing) Dim z4 = (Nothing IsNot x) Dim z5 = (x = Nothing) Dim z6 = (Nothing = x) Dim z7 = (x <> Nothing) Dim z8 = (Nothing <> x) Dim z11 = (y Is Nothing) Dim z12 = (Nothing Is y) Dim z13 = (y IsNot Nothing) Dim z14 = (Nothing IsNot y) Dim z15 = (y = Nothing) Dim z16 = (Nothing = y) Dim z17 = (y <> Nothing) Dim z18 = (Nothing <> y) End Sub End Class Structure TestStr End Structure ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30452: Operator '=' is not defined for types 'TestStr?' and 'TestStr?'. Dim z5 = (x = Nothing) ~~~~~~~~~~~ BC30452: Operator '=' is not defined for types 'TestStr?' and 'TestStr?'. Dim z6 = (Nothing = x) ~~~~~~~~~~~ BC30452: Operator '<>' is not defined for types 'TestStr?' and 'TestStr?'. Dim z7 = (x <> Nothing) ~~~~~~~~~~~~ BC30452: Operator '<>' is not defined for types 'TestStr?' and 'TestStr?'. Dim z8 = (Nothing <> x) ~~~~~~~~~~~~ BC42037: This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is null consider using 'Is Nothing'. Dim z15 = (y = Nothing) ~~~~~~~~~~~ BC42037: This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is null consider using 'Is Nothing'. Dim z16 = (Nothing = y) ~~~~~~~~~~~ BC42038: This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is not null consider using 'IsNot Nothing'. Dim z17 = (y <> Nothing) ~~~~~~~~~~~~ BC42038: This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is not null consider using 'IsNot Nothing'. Dim z18 = (Nothing <> y) ~~~~~~~~~~~~ ]]></expected>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim nodes = (From node In tree.GetRoot().DescendantNodes() Select node = TryCast(node, BinaryExpressionSyntax) Where node IsNot Nothing).ToArray() Assert.Equal(16, nodes.Length) For i As Integer = 0 To nodes.Length - 1 Dim symbol = semanticModel.GetSymbolInfo(nodes(i)).Symbol Select Case i Case 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 Assert.Null(symbol) Case 12, 13 Assert.Equal("Function System.Int32.op_Equality(left As System.Int32, right As System.Int32) As System.Boolean", symbol.ToTestDisplayString()) Case 14, 15 Assert.Equal("Function System.Int32.op_Inequality(left As System.Int32, right As System.Int32) As System.Boolean", symbol.ToTestDisplayString()) Case Else Throw ExceptionUtilities.UnexpectedValue(i) End Select Next End Sub <ConditionalFact(GetType(NoIOperationValidation))> <WorkItem(43019, "https://github.com/dotnet/roslyn/issues/43019"), WorkItem(529600, "DevDiv"), WorkItem(37572, "https://github.com/dotnet/roslyn/issues/37572")> Public Sub Bug529600() Dim compilationDef = <compilation> <file name="a.vb"> Module M Sub Main() End Sub Const c0 = "<%= New String("0"c, 65000) %>" Const C1=C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 Const C2=C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilation(compilationDef) Dim err = compilation.GetDiagnostics().Single() Assert.Equal(ERRID.ERR_ConstantStringTooLong, err.Code) Assert.Equal("Length of String constant resulting from concatenation exceeds System.Int32.MaxValue. Try splitting the string into multiple constants.", err.GetMessage(EnsureEnglishUICulture.PreferredOrNull)) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim fieldInitializerOperations = tree.GetRoot().DescendantNodes().OfType(Of VariableDeclaratorSyntax)(). Select(Function(v) v.Initializer.Value). Select(Function(i) model.GetOperation(i)) Dim numChildren = 0 For Each iop in fieldInitializerOperations EnumerateChildren(iop, numChildren) Next Assert.Equal(1203, numChildren) End Sub Private Sub EnumerateChildren(iop As IOperation, ByRef numChildren as Integer) numChildren += 1 Assert.NotNull(iop) For Each child in iop.Children EnumerateChildren(child, numChildren) Next End Sub <ConditionalFact(GetType(NoIOperationValidation)), WorkItem(43019, "https://github.com/dotnet/roslyn/issues/43019"), WorkItem(37572, "https://github.com/dotnet/roslyn/issues/37572")> Public Sub TestLargeStringConcatenation() Dim mid = New StringBuilder() For i As Integer = 0 To 4999 mid.Append("""Lorem ipsum dolor sit amet"" + "", consectetur adipiscing elit, sed"" + "" do eiusmod tempor incididunt"" + "" ut labore et dolore magna aliqua. "" +" + vbCrLf) Next Dim compilationDef = <compilation> <file name="a.vb"> Module M Sub Main() Dim s As String = "BEGIN "+ <%= mid.ToString() %> "END" System.Console.WriteLine(System.Linq.Enumerable.Sum(s, Function(c As Char) System.Convert.ToInt32(c))) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilation(compilationDef, options:=TestOptions.ReleaseExe) compilation.VerifyDiagnostics() CompileAndVerify(compilation, expectedOutput:="58430604") Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim initializer = tree.GetRoot().DescendantNodes().OfType(Of VariableDeclaratorSyntax).Single().Initializer.Value Dim literalOperation = model.GetOperation(initializer) Dim stringTextBuilder As New StringBuilder() stringTextBuilder.Append("BEGIN ") For i = 0 To 4999 stringTextBuilder.Append("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ") Next stringTextBuilder.Append("END") Assert.Equal(stringTextBuilder.ToString(), literalOperation.ConstantValue.Value) End Sub End Class End Namespace
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./eng/common/cross/armel/tizen-build-rootfs.sh
#!/usr/bin/env bash set -e __ARM_SOFTFP_CrossDir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) __TIZEN_CROSSDIR="$__ARM_SOFTFP_CrossDir/tizen" if [[ -z "$ROOTFS_DIR" ]]; then echo "ROOTFS_DIR is not defined." exit 1; fi TIZEN_TMP_DIR=$ROOTFS_DIR/tizen_tmp mkdir -p $TIZEN_TMP_DIR # Download files echo ">>Start downloading files" VERBOSE=1 $__ARM_SOFTFP_CrossDir/tizen-fetch.sh $TIZEN_TMP_DIR echo "<<Finish downloading files" echo ">>Start constructing Tizen rootfs" TIZEN_RPM_FILES=`ls $TIZEN_TMP_DIR/*.rpm` cd $ROOTFS_DIR for f in $TIZEN_RPM_FILES; do rpm2cpio $f | cpio -idm --quiet done echo "<<Finish constructing Tizen rootfs" # Cleanup tmp rm -rf $TIZEN_TMP_DIR # Configure Tizen rootfs echo ">>Start configuring Tizen rootfs" ln -sfn asm-arm ./usr/include/asm patch -p1 < $__TIZEN_CROSSDIR/tizen.patch echo "<<Finish configuring Tizen rootfs"
#!/usr/bin/env bash set -e __ARM_SOFTFP_CrossDir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) __TIZEN_CROSSDIR="$__ARM_SOFTFP_CrossDir/tizen" if [[ -z "$ROOTFS_DIR" ]]; then echo "ROOTFS_DIR is not defined." exit 1; fi TIZEN_TMP_DIR=$ROOTFS_DIR/tizen_tmp mkdir -p $TIZEN_TMP_DIR # Download files echo ">>Start downloading files" VERBOSE=1 $__ARM_SOFTFP_CrossDir/tizen-fetch.sh $TIZEN_TMP_DIR echo "<<Finish downloading files" echo ">>Start constructing Tizen rootfs" TIZEN_RPM_FILES=`ls $TIZEN_TMP_DIR/*.rpm` cd $ROOTFS_DIR for f in $TIZEN_RPM_FILES; do rpm2cpio $f | cpio -idm --quiet done echo "<<Finish constructing Tizen rootfs" # Cleanup tmp rm -rf $TIZEN_TMP_DIR # Configure Tizen rootfs echo ">>Start configuring Tizen rootfs" ln -sfn asm-arm ./usr/include/asm patch -p1 < $__TIZEN_CROSSDIR/tizen.patch echo "<<Finish configuring Tizen rootfs"
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/EditorFeatures/Test/Diagnostics/MockDiagnosticService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { [Export(typeof(IDiagnosticService))] [Shared] [PartNotDiscoverable] internal class MockDiagnosticService : IDiagnosticService { public const string DiagnosticId = "MockId"; private DiagnosticData? _diagnostic; public event EventHandler<DiagnosticsUpdatedArgs>? DiagnosticsUpdated; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MockDiagnosticService() { } [Obsolete] public ImmutableArray<DiagnosticData> GetDiagnostics(Workspace workspace, ProjectId? projectId, DocumentId? documentId, object? id, bool includeSuppressedDiagnostics, CancellationToken cancellationToken) => GetPushDiagnosticsAsync(workspace, projectId, documentId, id, includeSuppressedDiagnostics, InternalDiagnosticsOptions.NormalDiagnosticMode, cancellationToken).AsTask().WaitAndGetResult_CanCallOnBackground(cancellationToken); public ValueTask<ImmutableArray<DiagnosticData>> GetPullDiagnosticsAsync(Workspace workspace, ProjectId? projectId, DocumentId? documentId, object? id, bool includeSuppressedDiagnostics, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) { return new ValueTask<ImmutableArray<DiagnosticData>>(GetDiagnostics(workspace, projectId, documentId)); } public ValueTask<ImmutableArray<DiagnosticData>> GetPushDiagnosticsAsync(Workspace workspace, ProjectId? projectId, DocumentId? documentId, object? id, bool includeSuppressedDiagnostics, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) { return new ValueTask<ImmutableArray<DiagnosticData>>(GetDiagnostics(workspace, projectId, documentId)); } private ImmutableArray<DiagnosticData> GetDiagnostics(Workspace workspace, ProjectId? projectId, DocumentId? documentId) { Assert.Equal(projectId, GetProjectId(workspace)); Assert.Equal(documentId, GetDocumentId(workspace)); return _diagnostic == null ? ImmutableArray<DiagnosticData>.Empty : ImmutableArray.Create(_diagnostic); } public ImmutableArray<DiagnosticBucket> GetPullDiagnosticBuckets(Workspace workspace, ProjectId? projectId, DocumentId? documentId, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) { return GetDiagnosticBuckets(workspace, projectId, documentId); } public ImmutableArray<DiagnosticBucket> GetPushDiagnosticBuckets(Workspace workspace, ProjectId? projectId, DocumentId? documentId, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) { return GetDiagnosticBuckets(workspace, projectId, documentId); } private ImmutableArray<DiagnosticBucket> GetDiagnosticBuckets(Workspace workspace, ProjectId? projectId, DocumentId? documentId) { Assert.Equal(projectId, GetProjectId(workspace)); Assert.Equal(documentId, GetDocumentId(workspace)); return _diagnostic == null ? ImmutableArray<DiagnosticBucket>.Empty : ImmutableArray.Create(new DiagnosticBucket(this, workspace, GetProjectId(workspace), GetDocumentId(workspace))); } internal void CreateDiagnosticAndFireEvents(Workspace workspace, Location location) { var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); _diagnostic = DiagnosticData.Create(Diagnostic.Create(DiagnosticId, "MockCategory", "MockMessage", DiagnosticSeverity.Error, DiagnosticSeverity.Error, isEnabledByDefault: true, warningLevel: 0, location: location), document); DiagnosticsUpdated?.Invoke(this, DiagnosticsUpdatedArgs.DiagnosticsCreated( this, workspace, workspace.CurrentSolution, GetProjectId(workspace), GetDocumentId(workspace), ImmutableArray.Create(_diagnostic))); } private static DocumentId GetDocumentId(Workspace workspace) => workspace.CurrentSolution.Projects.Single().Documents.Single().Id; private static ProjectId GetProjectId(Workspace workspace) => workspace.CurrentSolution.Projects.Single().Id; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { [Export(typeof(IDiagnosticService))] [Shared] [PartNotDiscoverable] internal class MockDiagnosticService : IDiagnosticService { public const string DiagnosticId = "MockId"; private DiagnosticData? _diagnostic; public event EventHandler<DiagnosticsUpdatedArgs>? DiagnosticsUpdated; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MockDiagnosticService() { } [Obsolete] public ImmutableArray<DiagnosticData> GetDiagnostics(Workspace workspace, ProjectId? projectId, DocumentId? documentId, object? id, bool includeSuppressedDiagnostics, CancellationToken cancellationToken) => GetPushDiagnosticsAsync(workspace, projectId, documentId, id, includeSuppressedDiagnostics, InternalDiagnosticsOptions.NormalDiagnosticMode, cancellationToken).AsTask().WaitAndGetResult_CanCallOnBackground(cancellationToken); public ValueTask<ImmutableArray<DiagnosticData>> GetPullDiagnosticsAsync(Workspace workspace, ProjectId? projectId, DocumentId? documentId, object? id, bool includeSuppressedDiagnostics, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) { return new ValueTask<ImmutableArray<DiagnosticData>>(GetDiagnostics(workspace, projectId, documentId)); } public ValueTask<ImmutableArray<DiagnosticData>> GetPushDiagnosticsAsync(Workspace workspace, ProjectId? projectId, DocumentId? documentId, object? id, bool includeSuppressedDiagnostics, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) { return new ValueTask<ImmutableArray<DiagnosticData>>(GetDiagnostics(workspace, projectId, documentId)); } private ImmutableArray<DiagnosticData> GetDiagnostics(Workspace workspace, ProjectId? projectId, DocumentId? documentId) { Assert.Equal(projectId, GetProjectId(workspace)); Assert.Equal(documentId, GetDocumentId(workspace)); return _diagnostic == null ? ImmutableArray<DiagnosticData>.Empty : ImmutableArray.Create(_diagnostic); } public ImmutableArray<DiagnosticBucket> GetPullDiagnosticBuckets(Workspace workspace, ProjectId? projectId, DocumentId? documentId, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) { return GetDiagnosticBuckets(workspace, projectId, documentId); } public ImmutableArray<DiagnosticBucket> GetPushDiagnosticBuckets(Workspace workspace, ProjectId? projectId, DocumentId? documentId, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) { return GetDiagnosticBuckets(workspace, projectId, documentId); } private ImmutableArray<DiagnosticBucket> GetDiagnosticBuckets(Workspace workspace, ProjectId? projectId, DocumentId? documentId) { Assert.Equal(projectId, GetProjectId(workspace)); Assert.Equal(documentId, GetDocumentId(workspace)); return _diagnostic == null ? ImmutableArray<DiagnosticBucket>.Empty : ImmutableArray.Create(new DiagnosticBucket(this, workspace, GetProjectId(workspace), GetDocumentId(workspace))); } internal void CreateDiagnosticAndFireEvents(Workspace workspace, Location location) { var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); _diagnostic = DiagnosticData.Create(Diagnostic.Create(DiagnosticId, "MockCategory", "MockMessage", DiagnosticSeverity.Error, DiagnosticSeverity.Error, isEnabledByDefault: true, warningLevel: 0, location: location), document); DiagnosticsUpdated?.Invoke(this, DiagnosticsUpdatedArgs.DiagnosticsCreated( this, workspace, workspace.CurrentSolution, GetProjectId(workspace), GetDocumentId(workspace), ImmutableArray.Create(_diagnostic))); } private static DocumentId GetDocumentId(Workspace workspace) => workspace.CurrentSolution.Projects.Single().Documents.Single().Id; private static ProjectId GetProjectId(Workspace workspace) => workspace.CurrentSolution.Projects.Single().Id; } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/TriviaData.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.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { /// <summary> /// it holds onto trivia information between two tokens /// </summary> internal abstract class TriviaData { protected const int TokenPairIndexNotNeeded = int.MinValue; private readonly string _language; protected TriviaData(AnalyzerConfigOptions options, string language) { Contract.ThrowIfNull(options); Options = options; _language = language; } protected AnalyzerConfigOptions Options { get; } protected string Language => _language; public int LineBreaks { get; protected set; } public int Spaces { get; protected set; } public bool SecondTokenIsFirstTokenOnLine { get { return this.LineBreaks > 0; } } public abstract bool TreatAsElastic { get; } public abstract bool IsWhitespaceOnlyTrivia { get; } public abstract bool ContainsChanges { get; } public abstract IEnumerable<TextChange> GetTextChanges(TextSpan span); public abstract TriviaData WithSpace(int space, FormattingContext context, ChainedFormattingRules formattingRules); public abstract TriviaData WithLine(int line, int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken); public abstract TriviaData WithIndentation(int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken); public abstract void Format( FormattingContext context, ChainedFormattingRules formattingRules, Action<int, TokenStream, TriviaData> formattingResultApplier, CancellationToken cancellationToken, int tokenPairIndex = TokenPairIndexNotNeeded); } }
// Licensed to the .NET Foundation under one or more 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.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { /// <summary> /// it holds onto trivia information between two tokens /// </summary> internal abstract class TriviaData { protected const int TokenPairIndexNotNeeded = int.MinValue; private readonly string _language; protected TriviaData(AnalyzerConfigOptions options, string language) { Contract.ThrowIfNull(options); Options = options; _language = language; } protected AnalyzerConfigOptions Options { get; } protected string Language => _language; public int LineBreaks { get; protected set; } public int Spaces { get; protected set; } public bool SecondTokenIsFirstTokenOnLine { get { return this.LineBreaks > 0; } } public abstract bool TreatAsElastic { get; } public abstract bool IsWhitespaceOnlyTrivia { get; } public abstract bool ContainsChanges { get; } public abstract IEnumerable<TextChange> GetTextChanges(TextSpan span); public abstract TriviaData WithSpace(int space, FormattingContext context, ChainedFormattingRules formattingRules); public abstract TriviaData WithLine(int line, int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken); public abstract TriviaData WithIndentation(int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken); public abstract void Format( FormattingContext context, ChainedFormattingRules formattingRules, Action<int, TokenStream, TriviaData> formattingResultApplier, CancellationToken cancellationToken, int tokenPairIndex = TokenPairIndexNotNeeded); } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Features/Core/Portable/Common/NavigationOperation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using Microsoft.CodeAnalysis.Navigation; namespace Microsoft.CodeAnalysis.CodeActions { /// <summary> /// A <see cref="CodeActionOperation"/> for navigating to a specific position in a document. /// When <see cref="CodeAction.GetOperationsAsync(CancellationToken)"/> is called an implementation /// of <see cref="CodeAction"/> can return an instance of this operation along with the other /// operations they want to apply. For example, an implementation could generate a new <see cref="Document"/> /// in one <see cref="CodeActionOperation"/> and then have the host editor navigate to that /// <see cref="Document"/> using this operation. /// </summary> public class DocumentNavigationOperation : CodeActionOperation { private readonly DocumentId _documentId; private readonly int _position; public DocumentNavigationOperation(DocumentId documentId, int position = 0) { _documentId = documentId ?? throw new ArgumentNullException(nameof(documentId)); _position = position; } public override void Apply(Workspace workspace, CancellationToken cancellationToken) { if (workspace.CanOpenDocuments) { var navigationService = workspace.Services.GetService<IDocumentNavigationService>(); navigationService.TryNavigateToPosition(workspace, _documentId, _position, cancellationToken); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using Microsoft.CodeAnalysis.Navigation; namespace Microsoft.CodeAnalysis.CodeActions { /// <summary> /// A <see cref="CodeActionOperation"/> for navigating to a specific position in a document. /// When <see cref="CodeAction.GetOperationsAsync(CancellationToken)"/> is called an implementation /// of <see cref="CodeAction"/> can return an instance of this operation along with the other /// operations they want to apply. For example, an implementation could generate a new <see cref="Document"/> /// in one <see cref="CodeActionOperation"/> and then have the host editor navigate to that /// <see cref="Document"/> using this operation. /// </summary> public class DocumentNavigationOperation : CodeActionOperation { private readonly DocumentId _documentId; private readonly int _position; public DocumentNavigationOperation(DocumentId documentId, int position = 0) { _documentId = documentId ?? throw new ArgumentNullException(nameof(documentId)); _position = position; } public override void Apply(Workspace workspace, CancellationToken cancellationToken) { if (workspace.CanOpenDocuments) { var navigationService = workspace.Services.GetService<IDocumentNavigationService>(); navigationService.TryNavigateToPosition(workspace, _documentId, _position, cancellationToken); } } } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Compilers/VisualBasic/Portable/Binding/Binder_Imports.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Data for Binder.BindImportClause that exposes dictionaries of ''' the members and aliases that have been bound during the ''' execution of BindImportClause. It is the responsibility of derived ''' classes to update the dictionaries in AddMember and AddAlias. ''' </summary> Friend MustInherit Class ImportData Protected Sub New(members As HashSet(Of NamespaceOrTypeSymbol), aliases As Dictionary(Of String, AliasAndImportsClausePosition), xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition)) Me.Members = members Me.Aliases = aliases Me.XmlNamespaces = xmlNamespaces End Sub Public ReadOnly Members As HashSet(Of NamespaceOrTypeSymbol) Public ReadOnly Aliases As Dictionary(Of String, AliasAndImportsClausePosition) Public ReadOnly XmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) Public MustOverride Sub AddMember(syntaxRef As SyntaxReference, member As NamespaceOrTypeSymbol, importsClausePosition As Integer, dependencies As IReadOnlyCollection(Of AssemblySymbol)) Public MustOverride Sub AddAlias(syntaxRef As SyntaxReference, name As String, [alias] As AliasSymbol, importsClausePosition As Integer, dependencies As IReadOnlyCollection(Of AssemblySymbol)) End Class Partial Friend Class Binder ' Bind one import clause, add it to the correct collection of imports. ' Warnings and errors are emitted to the diagnostic bag, including detecting duplicates. ' Note that this binder should have been already been set up to only bind to things in the global namespace. Public Sub BindImportClause(importClauseSyntax As ImportsClauseSyntax, data As ImportData, diagBag As DiagnosticBag) ImportsBinder.BindImportClause(importClauseSyntax, Me, data, diagBag) End Sub ''' <summary> ''' The Imports binder handles binding of Imports statements in files, and also the project-level imports. ''' </summary> Private Class ImportsBinder ' Bind one import clause, add it to the correct collection of imports. ' Warnings and errors are emitted to the diagnostic bag, including detecting duplicates. ' Note that the binder should have been already been set up to only bind to things in the global namespace. Public Shared Sub BindImportClause(importClauseSyntax As ImportsClauseSyntax, binder As Binder, data As ImportData, diagBag As DiagnosticBag) Select Case importClauseSyntax.Kind Case SyntaxKind.SimpleImportsClause Dim simpleImportsClause = DirectCast(importClauseSyntax, SimpleImportsClauseSyntax) If simpleImportsClause.Alias Is Nothing Then BindMembersImportsClause(simpleImportsClause, binder, data, diagBag) Else BindAliasImportsClause(simpleImportsClause, binder, data, diagBag) End If Case SyntaxKind.XmlNamespaceImportsClause BindXmlNamespaceImportsClause(DirectCast(importClauseSyntax, XmlNamespaceImportsClauseSyntax), binder, data, diagBag) Case Else End Select End Sub ' Bind an alias imports clause. If it is OK, and also unique, add it to the dictionary. Private Shared Sub BindAliasImportsClause(aliasImportSyntax As SimpleImportsClauseSyntax, binder As Binder, data As ImportData, diagnostics As DiagnosticBag) Dim dependenciesBag = PooledHashSet(Of AssemblySymbol).GetInstance() Dim diagBag = New BindingDiagnosticBag(diagnostics, dependenciesBag) Dim aliasesName = aliasImportSyntax.Name Dim aliasTarget As NamespaceOrTypeSymbol = binder.BindNamespaceOrTypeSyntax(aliasesName, diagBag) If aliasTarget.Kind <> SymbolKind.Namespace Then Dim type = TryCast(aliasTarget, TypeSymbol) If type Is Nothing OrElse type.IsDelegateType Then Binder.ReportDiagnostic(diagBag, aliasImportSyntax, ERRID.ERR_InvalidTypeForAliasesImport2, aliasTarget, aliasTarget.Name) End If End If Dim aliasIdentifier = aliasImportSyntax.Alias.Identifier Dim aliasText = aliasIdentifier.ValueText ' Parser checks for type characters on alias text, so don't need to check again here. ' Check for duplicate symbol. If data.Aliases.ContainsKey(aliasText) Then Binder.ReportDiagnostic(diagBag, aliasIdentifier, ERRID.ERR_DuplicateNamedImportAlias1, aliasText) Else ' Make sure that the Import's alias doesn't have the same name as a type or a namespace in the global namespace Dim conflictsWith = binder.Compilation.GlobalNamespace.GetMembers(aliasText) If Not conflictsWith.IsEmpty Then ' TODO: Note that symbol's name in this error message is supposed to include Class/Namespace word at the beginning. ' Might need to use special format for that parameter in the error message. Binder.ReportDiagnostic(diagBag, aliasImportSyntax, ERRID.ERR_ImportAliasConflictsWithType2, aliasText, conflictsWith(0)) Else If aliasTarget.Kind <> SymbolKind.ErrorType Then Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = aliasTarget.GetUseSiteInfo() If ShouldReportUseSiteErrorForAlias(useSiteInfo.DiagnosticInfo) Then Binder.ReportUseSite(diagBag, aliasImportSyntax, useSiteInfo) Else diagBag.AddDependencies(useSiteInfo) End If Else dependenciesBag.Clear() End If ' We create the alias symbol even when the target is erroneous, ' so that we can bind to the alias and avoid cascading errors. ' As a result the further consumers of the aliases have to account for the error case. Dim aliasSymbol = New AliasSymbol(binder.Compilation, binder.ContainingNamespaceOrType, aliasText, aliasTarget, If(binder.BindingLocation = BindingLocation.ProjectImportsDeclaration, NoLocation.Singleton, aliasIdentifier.GetLocation())) data.AddAlias(binder.GetSyntaxReference(aliasImportSyntax), aliasText, aliasSymbol, aliasImportSyntax.SpanStart, dependenciesBag) End If End If dependenciesBag.Free() End Sub ''' <summary> ''' Checks use site error and returns True in case it should be reported for the alias. ''' In current implementation checks for errors #36924 and #36925 ''' </summary> Private Shared Function ShouldReportUseSiteErrorForAlias(useSiteErrorInfo As DiagnosticInfo) As Boolean Return useSiteErrorInfo IsNot Nothing AndAlso useSiteErrorInfo.Code <> ERRID.ERR_CannotUseGenericTypeAcrossAssemblyBoundaries AndAlso useSiteErrorInfo.Code <> ERRID.ERR_CannotUseGenericBaseTypeAcrossAssemblyBoundaries End Function ' Bind a members imports clause. If it is OK, and also unique, add it to the members imports set. Private Shared Sub BindMembersImportsClause(membersImportsSyntax As SimpleImportsClauseSyntax, binder As Binder, data As ImportData, diagnostics As DiagnosticBag) Dim dependenciesBag = PooledHashSet(Of AssemblySymbol).GetInstance() Dim diagBag = New BindingDiagnosticBag(diagnostics, dependenciesBag) Debug.Assert(membersImportsSyntax.Alias Is Nothing) Dim importsName = membersImportsSyntax.Name Dim importedSymbol As NamespaceOrTypeSymbol = binder.BindNamespaceOrTypeSyntax(importsName, diagBag) If importedSymbol.Kind <> SymbolKind.Namespace Then Dim type = TryCast(importedSymbol, TypeSymbol) ' Non-aliased interface imports are disallowed If type Is Nothing OrElse type.IsDelegateType OrElse type.IsInterfaceType Then Binder.ReportDiagnostic(diagBag, membersImportsSyntax, ERRID.ERR_NonNamespaceOrClassOnImport2, importedSymbol, importedSymbol.Name) End If End If If importedSymbol.Kind <> SymbolKind.ErrorType Then ' Check for duplicate symbol. If data.Members.Contains(importedSymbol) Then ' NOTE: Dev10 doesn't report this error for project level imports. We still ' generate the error but filter it out when bind project level imports Binder.ReportDiagnostic(diagBag, importsName, ERRID.ERR_DuplicateImport1, importedSymbol) Else Dim importedSymbolIsValid As Boolean = True ' Disallow importing different instantiations of the same generic type. If importedSymbol.Kind = SymbolKind.NamedType Then Dim namedType = DirectCast(importedSymbol, NamedTypeSymbol) If namedType.IsGenericType Then namedType = namedType.OriginalDefinition For Each contender In data.Members If contender.OriginalDefinition Is namedType Then importedSymbolIsValid = False Binder.ReportDiagnostic(diagBag, importsName, ERRID.ERR_DuplicateRawGenericTypeImport1, namedType) Exit For End If Next End If End If If importedSymbolIsValid Then data.AddMember(binder.GetSyntaxReference(importsName), importedSymbol, membersImportsSyntax.SpanStart, dependenciesBag) End If End If End If dependenciesBag.Free() End Sub Private Shared Sub BindXmlNamespaceImportsClause(syntax As XmlNamespaceImportsClauseSyntax, binder As Binder, data As ImportData, diagnostics As DiagnosticBag) #If DEBUG Then Dim dependenciesBag = PooledHashSet(Of AssemblySymbol).GetInstance() Dim diagBag = New BindingDiagnosticBag(diagnostics, dependenciesBag) #Else Dim diagBag = New BindingDiagnosticBag(diagnostics) #End If Dim prefix As String = Nothing Dim namespaceName As String = Nothing Dim [namespace] As BoundExpression = Nothing Dim hasErrors As Boolean = False If binder.TryGetXmlnsAttribute(syntax.XmlNamespace, prefix, namespaceName, [namespace], hasErrors, fromImport:=True, diagnostics:=diagBag) AndAlso Not hasErrors Then Debug.Assert([namespace] Is Nothing) ' Binding should have been skipped. If data.XmlNamespaces.ContainsKey(prefix) Then ' "XML namespace prefix '{0}' is already declared." Binder.ReportDiagnostic(diagBag, syntax, ERRID.ERR_DuplicatePrefix, prefix) Else data.XmlNamespaces.Add(prefix, New XmlNamespaceAndImportsClausePosition(namespaceName, syntax.SpanStart)) End If End If #If DEBUG Then Debug.Assert(dependenciesBag.Count = 0) dependenciesBag.Free() #End If End Sub End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Data for Binder.BindImportClause that exposes dictionaries of ''' the members and aliases that have been bound during the ''' execution of BindImportClause. It is the responsibility of derived ''' classes to update the dictionaries in AddMember and AddAlias. ''' </summary> Friend MustInherit Class ImportData Protected Sub New(members As HashSet(Of NamespaceOrTypeSymbol), aliases As Dictionary(Of String, AliasAndImportsClausePosition), xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition)) Me.Members = members Me.Aliases = aliases Me.XmlNamespaces = xmlNamespaces End Sub Public ReadOnly Members As HashSet(Of NamespaceOrTypeSymbol) Public ReadOnly Aliases As Dictionary(Of String, AliasAndImportsClausePosition) Public ReadOnly XmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) Public MustOverride Sub AddMember(syntaxRef As SyntaxReference, member As NamespaceOrTypeSymbol, importsClausePosition As Integer, dependencies As IReadOnlyCollection(Of AssemblySymbol)) Public MustOverride Sub AddAlias(syntaxRef As SyntaxReference, name As String, [alias] As AliasSymbol, importsClausePosition As Integer, dependencies As IReadOnlyCollection(Of AssemblySymbol)) End Class Partial Friend Class Binder ' Bind one import clause, add it to the correct collection of imports. ' Warnings and errors are emitted to the diagnostic bag, including detecting duplicates. ' Note that this binder should have been already been set up to only bind to things in the global namespace. Public Sub BindImportClause(importClauseSyntax As ImportsClauseSyntax, data As ImportData, diagBag As DiagnosticBag) ImportsBinder.BindImportClause(importClauseSyntax, Me, data, diagBag) End Sub ''' <summary> ''' The Imports binder handles binding of Imports statements in files, and also the project-level imports. ''' </summary> Private Class ImportsBinder ' Bind one import clause, add it to the correct collection of imports. ' Warnings and errors are emitted to the diagnostic bag, including detecting duplicates. ' Note that the binder should have been already been set up to only bind to things in the global namespace. Public Shared Sub BindImportClause(importClauseSyntax As ImportsClauseSyntax, binder As Binder, data As ImportData, diagBag As DiagnosticBag) Select Case importClauseSyntax.Kind Case SyntaxKind.SimpleImportsClause Dim simpleImportsClause = DirectCast(importClauseSyntax, SimpleImportsClauseSyntax) If simpleImportsClause.Alias Is Nothing Then BindMembersImportsClause(simpleImportsClause, binder, data, diagBag) Else BindAliasImportsClause(simpleImportsClause, binder, data, diagBag) End If Case SyntaxKind.XmlNamespaceImportsClause BindXmlNamespaceImportsClause(DirectCast(importClauseSyntax, XmlNamespaceImportsClauseSyntax), binder, data, diagBag) Case Else End Select End Sub ' Bind an alias imports clause. If it is OK, and also unique, add it to the dictionary. Private Shared Sub BindAliasImportsClause(aliasImportSyntax As SimpleImportsClauseSyntax, binder As Binder, data As ImportData, diagnostics As DiagnosticBag) Dim dependenciesBag = PooledHashSet(Of AssemblySymbol).GetInstance() Dim diagBag = New BindingDiagnosticBag(diagnostics, dependenciesBag) Dim aliasesName = aliasImportSyntax.Name Dim aliasTarget As NamespaceOrTypeSymbol = binder.BindNamespaceOrTypeSyntax(aliasesName, diagBag) If aliasTarget.Kind <> SymbolKind.Namespace Then Dim type = TryCast(aliasTarget, TypeSymbol) If type Is Nothing OrElse type.IsDelegateType Then Binder.ReportDiagnostic(diagBag, aliasImportSyntax, ERRID.ERR_InvalidTypeForAliasesImport2, aliasTarget, aliasTarget.Name) End If End If Dim aliasIdentifier = aliasImportSyntax.Alias.Identifier Dim aliasText = aliasIdentifier.ValueText ' Parser checks for type characters on alias text, so don't need to check again here. ' Check for duplicate symbol. If data.Aliases.ContainsKey(aliasText) Then Binder.ReportDiagnostic(diagBag, aliasIdentifier, ERRID.ERR_DuplicateNamedImportAlias1, aliasText) Else ' Make sure that the Import's alias doesn't have the same name as a type or a namespace in the global namespace Dim conflictsWith = binder.Compilation.GlobalNamespace.GetMembers(aliasText) If Not conflictsWith.IsEmpty Then ' TODO: Note that symbol's name in this error message is supposed to include Class/Namespace word at the beginning. ' Might need to use special format for that parameter in the error message. Binder.ReportDiagnostic(diagBag, aliasImportSyntax, ERRID.ERR_ImportAliasConflictsWithType2, aliasText, conflictsWith(0)) Else If aliasTarget.Kind <> SymbolKind.ErrorType Then Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = aliasTarget.GetUseSiteInfo() If ShouldReportUseSiteErrorForAlias(useSiteInfo.DiagnosticInfo) Then Binder.ReportUseSite(diagBag, aliasImportSyntax, useSiteInfo) Else diagBag.AddDependencies(useSiteInfo) End If Else dependenciesBag.Clear() End If ' We create the alias symbol even when the target is erroneous, ' so that we can bind to the alias and avoid cascading errors. ' As a result the further consumers of the aliases have to account for the error case. Dim aliasSymbol = New AliasSymbol(binder.Compilation, binder.ContainingNamespaceOrType, aliasText, aliasTarget, If(binder.BindingLocation = BindingLocation.ProjectImportsDeclaration, NoLocation.Singleton, aliasIdentifier.GetLocation())) data.AddAlias(binder.GetSyntaxReference(aliasImportSyntax), aliasText, aliasSymbol, aliasImportSyntax.SpanStart, dependenciesBag) End If End If dependenciesBag.Free() End Sub ''' <summary> ''' Checks use site error and returns True in case it should be reported for the alias. ''' In current implementation checks for errors #36924 and #36925 ''' </summary> Private Shared Function ShouldReportUseSiteErrorForAlias(useSiteErrorInfo As DiagnosticInfo) As Boolean Return useSiteErrorInfo IsNot Nothing AndAlso useSiteErrorInfo.Code <> ERRID.ERR_CannotUseGenericTypeAcrossAssemblyBoundaries AndAlso useSiteErrorInfo.Code <> ERRID.ERR_CannotUseGenericBaseTypeAcrossAssemblyBoundaries End Function ' Bind a members imports clause. If it is OK, and also unique, add it to the members imports set. Private Shared Sub BindMembersImportsClause(membersImportsSyntax As SimpleImportsClauseSyntax, binder As Binder, data As ImportData, diagnostics As DiagnosticBag) Dim dependenciesBag = PooledHashSet(Of AssemblySymbol).GetInstance() Dim diagBag = New BindingDiagnosticBag(diagnostics, dependenciesBag) Debug.Assert(membersImportsSyntax.Alias Is Nothing) Dim importsName = membersImportsSyntax.Name Dim importedSymbol As NamespaceOrTypeSymbol = binder.BindNamespaceOrTypeSyntax(importsName, diagBag) If importedSymbol.Kind <> SymbolKind.Namespace Then Dim type = TryCast(importedSymbol, TypeSymbol) ' Non-aliased interface imports are disallowed If type Is Nothing OrElse type.IsDelegateType OrElse type.IsInterfaceType Then Binder.ReportDiagnostic(diagBag, membersImportsSyntax, ERRID.ERR_NonNamespaceOrClassOnImport2, importedSymbol, importedSymbol.Name) End If End If If importedSymbol.Kind <> SymbolKind.ErrorType Then ' Check for duplicate symbol. If data.Members.Contains(importedSymbol) Then ' NOTE: Dev10 doesn't report this error for project level imports. We still ' generate the error but filter it out when bind project level imports Binder.ReportDiagnostic(diagBag, importsName, ERRID.ERR_DuplicateImport1, importedSymbol) Else Dim importedSymbolIsValid As Boolean = True ' Disallow importing different instantiations of the same generic type. If importedSymbol.Kind = SymbolKind.NamedType Then Dim namedType = DirectCast(importedSymbol, NamedTypeSymbol) If namedType.IsGenericType Then namedType = namedType.OriginalDefinition For Each contender In data.Members If contender.OriginalDefinition Is namedType Then importedSymbolIsValid = False Binder.ReportDiagnostic(diagBag, importsName, ERRID.ERR_DuplicateRawGenericTypeImport1, namedType) Exit For End If Next End If End If If importedSymbolIsValid Then data.AddMember(binder.GetSyntaxReference(importsName), importedSymbol, membersImportsSyntax.SpanStart, dependenciesBag) End If End If End If dependenciesBag.Free() End Sub Private Shared Sub BindXmlNamespaceImportsClause(syntax As XmlNamespaceImportsClauseSyntax, binder As Binder, data As ImportData, diagnostics As DiagnosticBag) #If DEBUG Then Dim dependenciesBag = PooledHashSet(Of AssemblySymbol).GetInstance() Dim diagBag = New BindingDiagnosticBag(diagnostics, dependenciesBag) #Else Dim diagBag = New BindingDiagnosticBag(diagnostics) #End If Dim prefix As String = Nothing Dim namespaceName As String = Nothing Dim [namespace] As BoundExpression = Nothing Dim hasErrors As Boolean = False If binder.TryGetXmlnsAttribute(syntax.XmlNamespace, prefix, namespaceName, [namespace], hasErrors, fromImport:=True, diagnostics:=diagBag) AndAlso Not hasErrors Then Debug.Assert([namespace] Is Nothing) ' Binding should have been skipped. If data.XmlNamespaces.ContainsKey(prefix) Then ' "XML namespace prefix '{0}' is already declared." Binder.ReportDiagnostic(diagBag, syntax, ERRID.ERR_DuplicatePrefix, prefix) Else data.XmlNamespaces.Add(prefix, New XmlNamespaceAndImportsClausePosition(namespaceName, syntax.SpanStart)) End If End If #If DEBUG Then Debug.Assert(dependenciesBag.Count = 0) dependenciesBag.Free() #End If End Sub End Class End Class End Namespace
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SymbolDisplayPartExtensions.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.Extensions { internal static class SymbolDisplayPartExtensions { public static SymbolDisplayPart MassageErrorTypeNames(this SymbolDisplayPart part, string? replacement = null) { if (part.Kind == SymbolDisplayPartKind.ErrorTypeName) { var text = part.ToString(); if (text == string.Empty) { return replacement == null ? new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, "object") : new SymbolDisplayPart(SymbolDisplayPartKind.Text, null, replacement); } if (SyntaxFacts.GetKeywordKind(text) != SyntaxKind.None) { return new SymbolDisplayPart(SymbolDisplayPartKind.ErrorTypeName, null, string.Format("@{0}", text)); } } return part; } } }
// Licensed to the .NET Foundation under one or more 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.Extensions { internal static class SymbolDisplayPartExtensions { public static SymbolDisplayPart MassageErrorTypeNames(this SymbolDisplayPart part, string? replacement = null) { if (part.Kind == SymbolDisplayPartKind.ErrorTypeName) { var text = part.ToString(); if (text == string.Empty) { return replacement == null ? new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, "object") : new SymbolDisplayPart(SymbolDisplayPartKind.Text, null, replacement); } if (SyntaxFacts.GetKeywordKind(text) != SyntaxKind.None) { return new SymbolDisplayPart(SymbolDisplayPartKind.ErrorTypeName, null, string.Format("@{0}", text)); } } return part; } } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/EditorFeatures/Core/Implementation/EditorLayerExtensionManager.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.Composition; using System.Linq; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.Options; using Microsoft.CodeAnalysis.ErrorLogger; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Internal.Log.FunctionId; using static Microsoft.CodeAnalysis.Internal.Log.Logger; using static Microsoft.CodeAnalysis.RoslynAssemblyHelper; namespace Microsoft.CodeAnalysis.Editor { [ExportWorkspaceServiceFactory(typeof(IExtensionManager), ServiceLayer.Editor), Shared] internal class EditorLayerExtensionManager : IWorkspaceServiceFactory { private readonly List<IExtensionErrorHandler> _errorHandlers; private readonly IGlobalOptionService _optionService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public EditorLayerExtensionManager( IGlobalOptionService optionService, [ImportMany] IEnumerable<IExtensionErrorHandler> errorHandlers) { _optionService = optionService; _errorHandlers = errorHandlers.ToList(); } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { var errorReportingService = workspaceServices.GetRequiredService<IErrorReportingService>(); var errorLoggerService = workspaceServices.GetRequiredService<IErrorLoggerService>(); return new ExtensionManager(_optionService, errorReportingService, errorLoggerService, _errorHandlers); } internal class ExtensionManager : AbstractExtensionManager { private readonly List<IExtensionErrorHandler> _errorHandlers; private readonly IGlobalOptionService _optionsService; private readonly IErrorReportingService _errorReportingService; private readonly IErrorLoggerService _errorLoggerService; public ExtensionManager( IGlobalOptionService optionsService, IErrorReportingService errorReportingService, IErrorLoggerService errorLoggerService, List<IExtensionErrorHandler> errorHandlers) { _optionsService = optionsService; _errorHandlers = errorHandlers; _errorReportingService = errorReportingService; _errorLoggerService = errorLoggerService; } public override void HandleException(object provider, Exception exception) { if (provider is CodeFixProvider or FixAllProvider or CodeRefactoringProvider) { if (!IsIgnored(provider) && _optionsService.GetOption(ExtensionManagerOptions.DisableCrashingExtensions)) { base.HandleException(provider, exception); _errorReportingService?.ShowGlobalErrorInfo(String.Format(WorkspacesResources._0_encountered_an_error_and_has_been_disabled, provider.GetType().Name), new InfoBarUI(WorkspacesResources.Show_Stack_Trace, InfoBarUI.UIKind.HyperLink, () => ShowDetailedErrorInfo(exception), closeAfterAction: false), new InfoBarUI(WorkspacesResources.Enable, InfoBarUI.UIKind.Button, () => { EnableProvider(provider); LogEnableProvider(provider); }), new InfoBarUI(WorkspacesResources.Enable_and_ignore_future_errors, InfoBarUI.UIKind.Button, () => { EnableProvider(provider); IgnoreProvider(provider); LogEnableAndIgnoreProvider(provider); }), new InfoBarUI(String.Empty, InfoBarUI.UIKind.Close, () => LogLeaveDisabled(provider))); } else { LogAction(CodefixInfobar_ErrorIgnored, provider); } } else { if (_optionsService.GetOption(ExtensionManagerOptions.DisableCrashingExtensions)) { base.HandleException(provider, exception); } _errorHandlers.Do(h => h.HandleError(provider, exception)); } _errorLoggerService?.LogException(provider, exception); } private void ShowDetailedErrorInfo(Exception exception) => _errorReportingService.ShowDetailedErrorInfo(exception); private static void LogLeaveDisabled(object provider) => LogAction(CodefixInfobar_LeaveDisabled, provider); private static void LogEnableAndIgnoreProvider(object provider) => LogAction(CodefixInfobar_EnableAndIgnoreFutureErrors, provider); private static void LogEnableProvider(object provider) => LogAction(CodefixInfobar_Enable, provider); private static void LogAction(FunctionId functionId, object provider) { if (IsRoslynCodefix(provider)) { Log(functionId, $"Name: {provider.GetType().FullName} Assembly Version: {provider.GetType().Assembly.GetName().Version}"); } else { Log(functionId); } } private static bool IsRoslynCodefix(object source) => HasRoslynPublicKey(source); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Composition; using System.Linq; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.Options; using Microsoft.CodeAnalysis.ErrorLogger; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Internal.Log.FunctionId; using static Microsoft.CodeAnalysis.Internal.Log.Logger; using static Microsoft.CodeAnalysis.RoslynAssemblyHelper; namespace Microsoft.CodeAnalysis.Editor { [ExportWorkspaceServiceFactory(typeof(IExtensionManager), ServiceLayer.Editor), Shared] internal class EditorLayerExtensionManager : IWorkspaceServiceFactory { private readonly List<IExtensionErrorHandler> _errorHandlers; private readonly IGlobalOptionService _optionService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public EditorLayerExtensionManager( IGlobalOptionService optionService, [ImportMany] IEnumerable<IExtensionErrorHandler> errorHandlers) { _optionService = optionService; _errorHandlers = errorHandlers.ToList(); } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { var errorReportingService = workspaceServices.GetRequiredService<IErrorReportingService>(); var errorLoggerService = workspaceServices.GetRequiredService<IErrorLoggerService>(); return new ExtensionManager(_optionService, errorReportingService, errorLoggerService, _errorHandlers); } internal class ExtensionManager : AbstractExtensionManager { private readonly List<IExtensionErrorHandler> _errorHandlers; private readonly IGlobalOptionService _optionsService; private readonly IErrorReportingService _errorReportingService; private readonly IErrorLoggerService _errorLoggerService; public ExtensionManager( IGlobalOptionService optionsService, IErrorReportingService errorReportingService, IErrorLoggerService errorLoggerService, List<IExtensionErrorHandler> errorHandlers) { _optionsService = optionsService; _errorHandlers = errorHandlers; _errorReportingService = errorReportingService; _errorLoggerService = errorLoggerService; } public override void HandleException(object provider, Exception exception) { if (provider is CodeFixProvider or FixAllProvider or CodeRefactoringProvider) { if (!IsIgnored(provider) && _optionsService.GetOption(ExtensionManagerOptions.DisableCrashingExtensions)) { base.HandleException(provider, exception); _errorReportingService?.ShowGlobalErrorInfo(String.Format(WorkspacesResources._0_encountered_an_error_and_has_been_disabled, provider.GetType().Name), new InfoBarUI(WorkspacesResources.Show_Stack_Trace, InfoBarUI.UIKind.HyperLink, () => ShowDetailedErrorInfo(exception), closeAfterAction: false), new InfoBarUI(WorkspacesResources.Enable, InfoBarUI.UIKind.Button, () => { EnableProvider(provider); LogEnableProvider(provider); }), new InfoBarUI(WorkspacesResources.Enable_and_ignore_future_errors, InfoBarUI.UIKind.Button, () => { EnableProvider(provider); IgnoreProvider(provider); LogEnableAndIgnoreProvider(provider); }), new InfoBarUI(String.Empty, InfoBarUI.UIKind.Close, () => LogLeaveDisabled(provider))); } else { LogAction(CodefixInfobar_ErrorIgnored, provider); } } else { if (_optionsService.GetOption(ExtensionManagerOptions.DisableCrashingExtensions)) { base.HandleException(provider, exception); } _errorHandlers.Do(h => h.HandleError(provider, exception)); } _errorLoggerService?.LogException(provider, exception); } private void ShowDetailedErrorInfo(Exception exception) => _errorReportingService.ShowDetailedErrorInfo(exception); private static void LogLeaveDisabled(object provider) => LogAction(CodefixInfobar_LeaveDisabled, provider); private static void LogEnableAndIgnoreProvider(object provider) => LogAction(CodefixInfobar_EnableAndIgnoreFutureErrors, provider); private static void LogEnableProvider(object provider) => LogAction(CodefixInfobar_Enable, provider); private static void LogAction(FunctionId functionId, object provider) { if (IsRoslynCodefix(provider)) { Log(functionId, $"Name: {provider.GetType().FullName} Assembly Version: {provider.GetType().Assembly.GetName().Version}"); } else { Log(functionId); } } private static bool IsRoslynCodefix(object source) => HasRoslynPublicKey(source); } } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Compilers/Test/Core/FX/PinnedMetadata.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Reflection.Metadata; namespace Roslyn.Test.Utilities { internal sealed class PinnedMetadata : PinnedBlob, IDisposable { public MetadataReader Reader; public unsafe PinnedMetadata(ImmutableArray<byte> metadata) : base(metadata) { this.Reader = new MetadataReader((byte*)Pointer, this.Size, MetadataReaderOptions.None, null); } public override void Dispose() { base.Dispose(); Reader = 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; using System.Collections.Immutable; using System.Reflection.Metadata; namespace Roslyn.Test.Utilities { internal sealed class PinnedMetadata : PinnedBlob, IDisposable { public MetadataReader Reader; public unsafe PinnedMetadata(ImmutableArray<byte> metadata) : base(metadata) { this.Reader = new MetadataReader((byte*)Pointer, this.Size, MetadataReaderOptions.None, null); } public override void Dispose() { base.Dispose(); Reader = null; } } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Features/Lsif/Generator/Graph/ResultSet.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.LanguageServerIndexFormat.Generator.Graph { /// <summary> /// Represents a single ResultSet for serialization. See https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#result-set for further details. /// </summary> internal sealed class ResultSet : Vertex { public ResultSet(IdFactory idFactory) : base(label: "resultSet", idFactory) { } } }
// Licensed to the .NET Foundation under one or more 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.LanguageServerIndexFormat.Generator.Graph { /// <summary> /// Represents a single ResultSet for serialization. See https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#result-set for further details. /// </summary> internal sealed class ResultSet : Vertex { public ResultSet(IdFactory idFactory) : base(label: "resultSet", idFactory) { } } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/EditorFeatures/VisualBasicTest/KeywordHighlighting/ConstructorDeclarationHighlighterTests.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.VisualBasic.KeywordHighlighting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting Public Class ConstructorDeclarationHighlighterTests Inherits AbstractVisualBasicKeywordHighlighterTests Friend Overrides Function GetHighlighterType() As Type Return GetType(ConstructorDeclarationHighlighter) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConstructorExample1_1() As Task Await TestAsync(<Text> Class C {|Cursor:[|Public Sub New|]|}() [|Exit Sub|] [|End Sub|] End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConstructorExample1_2() As Task Await TestAsync(<Text> Class C [|Public Sub New|]() {|Cursor:[|Exit Sub|]|} [|End Sub|] End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConstructorExample1_3() As Task Await TestAsync(<Text> Class C [|Public Sub New|]() [|Exit Sub|] {|Cursor:[|End Sub|]|} End Class</Text>) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting Public Class ConstructorDeclarationHighlighterTests Inherits AbstractVisualBasicKeywordHighlighterTests Friend Overrides Function GetHighlighterType() As Type Return GetType(ConstructorDeclarationHighlighter) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConstructorExample1_1() As Task Await TestAsync(<Text> Class C {|Cursor:[|Public Sub New|]|}() [|Exit Sub|] [|End Sub|] End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConstructorExample1_2() As Task Await TestAsync(<Text> Class C [|Public Sub New|]() {|Cursor:[|Exit Sub|]|} [|End Sub|] End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConstructorExample1_3() As Task Await TestAsync(<Text> Class C [|Public Sub New|]() [|Exit Sub|] {|Cursor:[|End Sub|]|} End Class</Text>) End Function End Class End Namespace
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Workspaces/Core/Portable/ExternalAccess/VSTypeScript/Api/VSTypeScriptTextExtensions.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 Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal static class VSTypeScriptTextExtensions { public static IEnumerable<Document> GetRelatedDocuments(this SourceTextContainer container) => TextExtensions.GetRelatedDocuments(container); public static Document? GetOpenDocumentInCurrentContextWithChanges(this SourceText text) => TextExtensions.GetOpenDocumentInCurrentContextWithChanges(text); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal static class VSTypeScriptTextExtensions { public static IEnumerable<Document> GetRelatedDocuments(this SourceTextContainer container) => TextExtensions.GetRelatedDocuments(container); public static Document? GetOpenDocumentInCurrentContextWithChanges(this SourceText text) => TextExtensions.GetOpenDocumentInCurrentContextWithChanges(text); } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Compilers/VisualBasic/Portable/Binding/DefaultParametersInProgressBinder.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 ''' <summary> ''' This binder keeps track of the set of parameters that are currently being evaluated ''' so that the set can be passed into the next call to ParameterSymbol.DefaultConstantValue (and ''' its callers). ''' </summary> Friend NotInheritable Class DefaultParametersInProgressBinder Inherits SymbolsInProgressBinder(Of ParameterSymbol) Friend Sub New(inProgress As SymbolsInProgress(Of ParameterSymbol), [next] As Binder) MyBase.New(inProgress, [next]) End Sub Friend Overrides ReadOnly Property DefaultParametersInProgress As SymbolsInProgress(Of ParameterSymbol) Get Return inProgress End Get End Property End Class ''' <summary> ''' This binder keeps track of the set of symbols that are currently being evaluated ''' so that the set can be passed to methods to support breaking infinite recursion ''' cycles. ''' </summary> Friend MustInherit Class SymbolsInProgressBinder(Of T As Symbol) Inherits Binder Protected ReadOnly inProgress As SymbolsInProgress(Of T) Protected Sub New(inProgress As SymbolsInProgress(Of T), [next] As Binder) MyBase.New([next]) Me.inProgress = inProgress End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' This binder keeps track of the set of parameters that are currently being evaluated ''' so that the set can be passed into the next call to ParameterSymbol.DefaultConstantValue (and ''' its callers). ''' </summary> Friend NotInheritable Class DefaultParametersInProgressBinder Inherits SymbolsInProgressBinder(Of ParameterSymbol) Friend Sub New(inProgress As SymbolsInProgress(Of ParameterSymbol), [next] As Binder) MyBase.New(inProgress, [next]) End Sub Friend Overrides ReadOnly Property DefaultParametersInProgress As SymbolsInProgress(Of ParameterSymbol) Get Return inProgress End Get End Property End Class ''' <summary> ''' This binder keeps track of the set of symbols that are currently being evaluated ''' so that the set can be passed to methods to support breaking infinite recursion ''' cycles. ''' </summary> Friend MustInherit Class SymbolsInProgressBinder(Of T As Symbol) Inherits Binder Protected ReadOnly inProgress As SymbolsInProgress(Of T) Protected Sub New(inProgress As SymbolsInProgress(Of T), [next] As Binder) MyBase.New([next]) Me.inProgress = inProgress End Sub End Class End Namespace
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./.git/hooks/fsmonitor-watchman.sample
#!/usr/bin/perl use strict; use warnings; use IPC::Open2; # An example hook script to integrate Watchman # (https://facebook.github.io/watchman/) with git to speed up detecting # new and modified files. # # The hook is passed a version (currently 1) and a time in nanoseconds # formatted as a string and outputs to stdout all files that have been # modified since the given time. Paths must be relative to the root of # the working tree and separated by a single NUL. # # To enable this hook, rename this file to "query-watchman" and set # 'git config core.fsmonitor .git/hooks/query-watchman' # my ($version, $time) = @ARGV; # Check the hook interface version if ($version == 1) { # convert nanoseconds to seconds # subtract one second to make sure watchman will return all changes $time = int ($time / 1000000000) - 1; } else { die "Unsupported query-fsmonitor hook version '$version'.\n" . "Falling back to scanning...\n"; } my $git_work_tree; if ($^O =~ 'msys' || $^O =~ 'cygwin') { $git_work_tree = Win32::GetCwd(); $git_work_tree =~ tr/\\/\//; } else { require Cwd; $git_work_tree = Cwd::cwd(); } my $retry = 1; launch_watchman(); sub launch_watchman { my $pid = open2(\*CHLD_OUT, \*CHLD_IN, 'watchman -j --no-pretty') or die "open2() failed: $!\n" . "Falling back to scanning...\n"; # In the query expression below we're asking for names of files that # changed since $time but were not transient (ie created after # $time but no longer exist). # # To accomplish this, we're using the "since" generator to use the # recency index to select candidate nodes and "fields" to limit the # output to file names only. my $query = <<" END"; ["query", "$git_work_tree", { "since": $time, "fields": ["name"] }] END print CHLD_IN $query; close CHLD_IN; my $response = do {local $/; <CHLD_OUT>}; die "Watchman: command returned no output.\n" . "Falling back to scanning...\n" if $response eq ""; die "Watchman: command returned invalid output: $response\n" . "Falling back to scanning...\n" unless $response =~ /^\{/; my $json_pkg; eval { require JSON::XS; $json_pkg = "JSON::XS"; 1; } or do { require JSON::PP; $json_pkg = "JSON::PP"; }; my $o = $json_pkg->new->utf8->decode($response); if ($retry > 0 and $o->{error} and $o->{error} =~ m/unable to resolve root .* directory (.*) is not watched/) { print STDERR "Adding '$git_work_tree' to watchman's watch list.\n"; $retry--; qx/watchman watch "$git_work_tree"/; die "Failed to make watchman watch '$git_work_tree'.\n" . "Falling back to scanning...\n" if $? != 0; # Watchman will always return all files on the first query so # return the fast "everything is dirty" flag to git and do the # Watchman query just to get it over with now so we won't pay # the cost in git to look up each individual file. print "/\0"; eval { launch_watchman() }; exit 0; } die "Watchman: $o->{error}.\n" . "Falling back to scanning...\n" if $o->{error}; binmode STDOUT, ":utf8"; local $, = "\0"; print @{$o->{files}}; }
#!/usr/bin/perl use strict; use warnings; use IPC::Open2; # An example hook script to integrate Watchman # (https://facebook.github.io/watchman/) with git to speed up detecting # new and modified files. # # The hook is passed a version (currently 1) and a time in nanoseconds # formatted as a string and outputs to stdout all files that have been # modified since the given time. Paths must be relative to the root of # the working tree and separated by a single NUL. # # To enable this hook, rename this file to "query-watchman" and set # 'git config core.fsmonitor .git/hooks/query-watchman' # my ($version, $time) = @ARGV; # Check the hook interface version if ($version == 1) { # convert nanoseconds to seconds # subtract one second to make sure watchman will return all changes $time = int ($time / 1000000000) - 1; } else { die "Unsupported query-fsmonitor hook version '$version'.\n" . "Falling back to scanning...\n"; } my $git_work_tree; if ($^O =~ 'msys' || $^O =~ 'cygwin') { $git_work_tree = Win32::GetCwd(); $git_work_tree =~ tr/\\/\//; } else { require Cwd; $git_work_tree = Cwd::cwd(); } my $retry = 1; launch_watchman(); sub launch_watchman { my $pid = open2(\*CHLD_OUT, \*CHLD_IN, 'watchman -j --no-pretty') or die "open2() failed: $!\n" . "Falling back to scanning...\n"; # In the query expression below we're asking for names of files that # changed since $time but were not transient (ie created after # $time but no longer exist). # # To accomplish this, we're using the "since" generator to use the # recency index to select candidate nodes and "fields" to limit the # output to file names only. my $query = <<" END"; ["query", "$git_work_tree", { "since": $time, "fields": ["name"] }] END print CHLD_IN $query; close CHLD_IN; my $response = do {local $/; <CHLD_OUT>}; die "Watchman: command returned no output.\n" . "Falling back to scanning...\n" if $response eq ""; die "Watchman: command returned invalid output: $response\n" . "Falling back to scanning...\n" unless $response =~ /^\{/; my $json_pkg; eval { require JSON::XS; $json_pkg = "JSON::XS"; 1; } or do { require JSON::PP; $json_pkg = "JSON::PP"; }; my $o = $json_pkg->new->utf8->decode($response); if ($retry > 0 and $o->{error} and $o->{error} =~ m/unable to resolve root .* directory (.*) is not watched/) { print STDERR "Adding '$git_work_tree' to watchman's watch list.\n"; $retry--; qx/watchman watch "$git_work_tree"/; die "Failed to make watchman watch '$git_work_tree'.\n" . "Falling back to scanning...\n" if $? != 0; # Watchman will always return all files on the first query so # return the fast "everything is dirty" flag to git and do the # Watchman query just to get it over with now so we won't pay # the cost in git to look up each individual file. print "/\0"; eval { launch_watchman() }; exit 0; } die "Watchman: $o->{error}.\n" . "Falling back to scanning...\n" if $o->{error}; binmode STDOUT, ":utf8"; local $, = "\0"; print @{$o->{files}}; }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/Features/Core/Portable/ExternalAccess/UnitTesting/UnitTestingSolutionCrawlerServiceAccessor.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.ExternalAccess.UnitTesting.Api; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.SolutionCrawler; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting { [Obsolete] internal sealed class UnitTestingSolutionCrawlerServiceAccessor : IUnitTestingSolutionCrawlerServiceAccessor { private readonly ISolutionCrawlerRegistrationService _registrationService; private readonly ISolutionCrawlerService _solutionCrawlerService; private UnitTestingIncrementalAnalyzerProvider _analyzerProvider; [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public UnitTestingSolutionCrawlerServiceAccessor( ISolutionCrawlerRegistrationService registrationService, ISolutionCrawlerService solutionCrawlerService) { _registrationService = registrationService; _solutionCrawlerService = solutionCrawlerService; } public void AddAnalyzerProvider(IUnitTestingIncrementalAnalyzerProviderImplementation provider, UnitTestingIncrementalAnalyzerProviderMetadataWrapper metadata) { if (_analyzerProvider != null) { // NOTE: We expect the analyzer to be a singleton, therefore this method should be called just once. throw new InvalidOperationException(); } _analyzerProvider = new UnitTestingIncrementalAnalyzerProvider(provider); _registrationService.AddAnalyzerProvider(_analyzerProvider, metadata.UnderlyingObject); } // NOTE: For the Reanalyze method to work correctly, the analyzer passed into the Reanalyze method, // must be the same as created when we call the AddAnalyzerProvider method. // As such the analyzer provider instance caches a single instance of the analyzer. public void Reanalyze(Workspace workspace, IEnumerable<ProjectId> projectIds = null, IEnumerable<DocumentId> documentIds = null, bool highPriority = false) { // NOTE: this method must be called after AddAnalyzerProvider was called previously. if (_analyzerProvider == null) { throw new InvalidOperationException(); } _solutionCrawlerService.Reanalyze(workspace, _analyzerProvider.CreateIncrementalAnalyzer(workspace), projectIds, documentIds, highPriority); } public void Register(Workspace workspace) => _registrationService.Register(workspace); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.SolutionCrawler; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting { [Obsolete] internal sealed class UnitTestingSolutionCrawlerServiceAccessor : IUnitTestingSolutionCrawlerServiceAccessor { private readonly ISolutionCrawlerRegistrationService _registrationService; private readonly ISolutionCrawlerService _solutionCrawlerService; private UnitTestingIncrementalAnalyzerProvider _analyzerProvider; [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public UnitTestingSolutionCrawlerServiceAccessor( ISolutionCrawlerRegistrationService registrationService, ISolutionCrawlerService solutionCrawlerService) { _registrationService = registrationService; _solutionCrawlerService = solutionCrawlerService; } public void AddAnalyzerProvider(IUnitTestingIncrementalAnalyzerProviderImplementation provider, UnitTestingIncrementalAnalyzerProviderMetadataWrapper metadata) { if (_analyzerProvider != null) { // NOTE: We expect the analyzer to be a singleton, therefore this method should be called just once. throw new InvalidOperationException(); } _analyzerProvider = new UnitTestingIncrementalAnalyzerProvider(provider); _registrationService.AddAnalyzerProvider(_analyzerProvider, metadata.UnderlyingObject); } // NOTE: For the Reanalyze method to work correctly, the analyzer passed into the Reanalyze method, // must be the same as created when we call the AddAnalyzerProvider method. // As such the analyzer provider instance caches a single instance of the analyzer. public void Reanalyze(Workspace workspace, IEnumerable<ProjectId> projectIds = null, IEnumerable<DocumentId> documentIds = null, bool highPriority = false) { // NOTE: this method must be called after AddAnalyzerProvider was called previously. if (_analyzerProvider == null) { throw new InvalidOperationException(); } _solutionCrawlerService.Reanalyze(workspace, _analyzerProvider.CreateIncrementalAnalyzer(workspace), projectIds, documentIds, highPriority); } public void Register(Workspace workspace) => _registrationService.Register(workspace); } }
-1
dotnet/roslyn
56,357
Fix DefaultAnalyzerAssemblyLoader
Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
genlu
"2021-09-13T20:58:22Z"
"2021-09-21T19:08:56Z"
388f27cab65b3dddb07cc04be839ad603cf0c713
aa7161be66427e809276fb5f2f91cfe8335eadff
Fix DefaultAnalyzerAssemblyLoader. Explicitly reference the AssemblyLoadContext where compiler is being loaded into instead of relying on fallback to AssemblyLoadConext.Default. In Servicehub .Net Core host, each service is assigned a separate ALC (Roslyn is one of them), whereas the Default ALC is used by Servicehub itself. See [here ](https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_git/DevCore?path=/src/clr/hosts/Microsoft.ServiceHub.HostLib/IsolationServiceManager.cs&_a=contents&version=GBdevelop)for more details on the Servicehub implementation. Fix #56254
./src/EditorFeatures/Test2/Rename/CSharp/SourceGeneratorTests.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.UnitTests.Rename.CSharp <[UseExportProvider]> Public Class SourceGeneratorTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameColorColorCaseWithGeneratedClassName(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="ClassLibrary1" CommonReferences="true"> <Document> public class RegularClass { public GeneratedClass [|$$GeneratedClass|]; } </Document> <DocumentFromSourceGenerator> public class GeneratedClass { } </DocumentFromSourceGenerator> </Project> </Workspace>, host:=host, renameTo:="A") End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameWithReferenceInGeneratedFile(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="ClassLibrary1" CommonReferences="true"> <Document> public class [|$$RegularClass|] { } </Document> <DocumentFromSourceGenerator> public class GeneratedClass { public void M(RegularClass c) { } } </DocumentFromSourceGenerator> </Project> </Workspace>, host:=host, renameTo:="A") End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(51537, "https://github.com/dotnet/roslyn/issues/51537")> Public Sub RenameWithCascadeIntoGeneratedFile(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="ClassLibrary1" CommonReferences="true"> <Document> public interface IInterface { int [|$$Property|] { get; set; } } public partial class GeneratedClass : IInterface { } </Document> </Project> </Workspace>, host:=host, renameTo:="A", sourceGenerator:=New GeneratorThatImplementsInterfaceMethod()) End Using End Sub Private Class GeneratorThatImplementsInterfaceMethod Implements ISourceGenerator Public Sub Initialize(context As GeneratorInitializationContext) Implements ISourceGenerator.Initialize End Sub Public Sub Execute(context As GeneratorExecutionContext) Implements ISourceGenerator.Execute Dim [interface] = context.Compilation.GetTypeByMetadataName("IInterface") Dim memberName = [interface].MemberNames.Single() Dim text = "public partial class GeneratedClass { public int " + memberName + " { get; set; } }" context.AddSource("Implementation.cs", text) End Sub End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.CSharp <[UseExportProvider]> Public Class SourceGeneratorTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameColorColorCaseWithGeneratedClassName(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="ClassLibrary1" CommonReferences="true"> <Document> public class RegularClass { public GeneratedClass [|$$GeneratedClass|]; } </Document> <DocumentFromSourceGenerator> public class GeneratedClass { } </DocumentFromSourceGenerator> </Project> </Workspace>, host:=host, renameTo:="A") End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameWithReferenceInGeneratedFile(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="ClassLibrary1" CommonReferences="true"> <Document> public class [|$$RegularClass|] { } </Document> <DocumentFromSourceGenerator> public class GeneratedClass { public void M(RegularClass c) { } } </DocumentFromSourceGenerator> </Project> </Workspace>, host:=host, renameTo:="A") End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(51537, "https://github.com/dotnet/roslyn/issues/51537")> Public Sub RenameWithCascadeIntoGeneratedFile(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="ClassLibrary1" CommonReferences="true"> <Document> public interface IInterface { int [|$$Property|] { get; set; } } public partial class GeneratedClass : IInterface { } </Document> </Project> </Workspace>, host:=host, renameTo:="A", sourceGenerator:=New GeneratorThatImplementsInterfaceMethod()) End Using End Sub Private Class GeneratorThatImplementsInterfaceMethod Implements ISourceGenerator Public Sub Initialize(context As GeneratorInitializationContext) Implements ISourceGenerator.Initialize End Sub Public Sub Execute(context As GeneratorExecutionContext) Implements ISourceGenerator.Execute Dim [interface] = context.Compilation.GetTypeByMetadataName("IInterface") Dim memberName = [interface].MemberNames.Single() Dim text = "public partial class GeneratedClass { public int " + memberName + " { get; set; } }" context.AddSource("Implementation.cs", text) End Sub End Class End Class End Namespace
-1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Features/CSharp/Portable/AddImport/CSharpAddImportFeatureService.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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.AddImport; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CSharp.AddImport.AddImportDiagnosticIds; namespace Microsoft.CodeAnalysis.CSharp.AddImport { [ExportLanguageService(typeof(IAddImportFeatureService), LanguageNames.CSharp), Shared] internal class CSharpAddImportFeatureService : AbstractAddImportFeatureService<SimpleNameSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpAddImportFeatureService() { } protected override bool CanAddImport(SyntaxNode node, bool allowInHiddenRegions, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return node.CanAddUsingDirectives(allowInHiddenRegions, cancellationToken); } protected override bool CanAddImportForMethod( string diagnosticId, ISyntaxFacts syntaxFacts, SyntaxNode node, out SimpleNameSyntax nameNode) { nameNode = null; switch (diagnosticId) { case CS7036: case CS0308: case CS0428: case CS1061: if (node.IsKind(SyntaxKind.ConditionalAccessExpression, out ConditionalAccessExpressionSyntax conditionalAccess)) { node = conditionalAccess.WhenNotNull; } else if (node.IsKind(SyntaxKind.MemberBindingExpression, out MemberBindingExpressionSyntax memberBinding1)) { node = memberBinding1.Name; } else if (node.Parent.IsKind(SyntaxKind.CollectionInitializerExpression)) { return true; } break; case CS0122: case CS1501: if (node is SimpleNameSyntax) { break; } else if (node is MemberBindingExpressionSyntax memberBindingExpr) { node = memberBindingExpr.Name; } break; case CS1929: var memberAccessName = (node.Parent as MemberAccessExpressionSyntax)?.Name; var conditionalAccessName = (((node.Parent as ConditionalAccessExpressionSyntax)?.WhenNotNull as InvocationExpressionSyntax)?.Expression as MemberBindingExpressionSyntax)?.Name; if (memberAccessName == null && conditionalAccessName == null) { return false; } node = memberAccessName ?? conditionalAccessName; break; case CS1503: //// look up its corresponding method name var parent = node.GetAncestor<InvocationExpressionSyntax>(); if (parent == null) { return false; } if (parent.Expression is MemberAccessExpressionSyntax method) { node = method.Name; } break; case CS1955: break; default: return false; } nameNode = node as SimpleNameSyntax; if (!nameNode.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) && !nameNode.IsParentKind(SyntaxKind.MemberBindingExpression)) { return false; } var memberAccess = nameNode.Parent as MemberAccessExpressionSyntax; var memberBinding = nameNode.Parent as MemberBindingExpressionSyntax; if (memberAccess.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) || memberAccess.IsParentKind(SyntaxKind.ElementAccessExpression) || memberBinding.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) || memberBinding.IsParentKind(SyntaxKind.ElementAccessExpression)) { return false; } if (!syntaxFacts.IsNameOfSimpleMemberAccessExpression(node) && !syntaxFacts.IsNameOfMemberBindingExpression(node)) { return false; } return true; } protected override bool CanAddImportForDeconstruct(string diagnosticId, SyntaxNode node) => diagnosticId == CS8129; protected override bool CanAddImportForGetAwaiter(string diagnosticId, ISyntaxFacts syntaxFactsService, SyntaxNode node) => (diagnosticId == CS1061 || // Regular cases diagnosticId == CS4036 || // WinRT async interfaces diagnosticId == CS1929) && // An extension `GetAwaiter()` is in scope, but for another type AncestorOrSelfIsAwaitExpression(syntaxFactsService, node); protected override bool CanAddImportForGetEnumerator(string diagnosticId, ISyntaxFacts syntaxFactsService, SyntaxNode node) => diagnosticId == CS1579 || diagnosticId == CS8414; protected override bool CanAddImportForGetAsyncEnumerator(string diagnosticId, ISyntaxFacts syntaxFactsService, SyntaxNode node) => diagnosticId == CS8411 || diagnosticId == CS8415; protected override bool CanAddImportForNamespace(string diagnosticId, SyntaxNode node, out SimpleNameSyntax nameNode) { nameNode = null; return false; } protected override bool CanAddImportForQuery(string diagnosticId, SyntaxNode node) => (diagnosticId == CS1935 || // Regular cases diagnosticId == CS1929) && // An extension method is in scope, but for another type node.AncestorsAndSelf().Any(n => n is QueryExpressionSyntax && !(n.Parent is QueryContinuationSyntax)); protected override bool CanAddImportForType(string diagnosticId, SyntaxNode node, out SimpleNameSyntax nameNode) { nameNode = null; switch (diagnosticId) { case CS0103: case IDEDiagnosticIds.UnboundIdentifierId: case CS0246: case CS0305: case CS0308: case CS0122: case CS0307: case CS0616: case CS1580: case CS1581: case CS1955: case CS0281: break; case CS1574: case CS1584: if (node is QualifiedCrefSyntax cref) { node = cref.Container; } break; default: return false; } return TryFindStandaloneType(node, out nameNode); } private static bool TryFindStandaloneType(SyntaxNode node, out SimpleNameSyntax nameNode) { if (node is QualifiedNameSyntax qn) { node = GetLeftMostSimpleName(qn); } nameNode = node as SimpleNameSyntax; return nameNode.LooksLikeStandaloneTypeName(); } private static SimpleNameSyntax GetLeftMostSimpleName(QualifiedNameSyntax qn) { while (qn != null) { var left = qn.Left; if (left is SimpleNameSyntax simpleName) { return simpleName; } qn = left as QualifiedNameSyntax; } return null; } protected override ISet<INamespaceSymbol> GetImportNamespacesInScope( SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) { return semanticModel.GetUsingNamespacesInScope(node); } protected override ITypeSymbol GetDeconstructInfo( SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) { return semanticModel.GetTypeInfo(node, cancellationToken).Type; } protected override ITypeSymbol GetQueryClauseInfo( SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) { var query = node.AncestorsAndSelf().OfType<QueryExpressionSyntax>().First(); if (InfoBoundSuccessfully(semanticModel.GetQueryClauseInfo(query.FromClause, cancellationToken))) { return null; } foreach (var clause in query.Body.Clauses) { if (InfoBoundSuccessfully(semanticModel.GetQueryClauseInfo(clause, cancellationToken))) { return null; } } if (InfoBoundSuccessfully(semanticModel.GetSymbolInfo(query.Body.SelectOrGroup, cancellationToken))) { return null; } var fromClause = query.FromClause; return semanticModel.GetTypeInfo(fromClause.Expression, cancellationToken).Type; } private static bool InfoBoundSuccessfully(SymbolInfo symbolInfo) => InfoBoundSuccessfully(symbolInfo.Symbol); private static bool InfoBoundSuccessfully(QueryClauseInfo semanticInfo) => InfoBoundSuccessfully(semanticInfo.OperationInfo); private static bool InfoBoundSuccessfully(ISymbol operation) { operation = operation.GetOriginalUnreducedDefinition(); return operation != null; } protected override string GetDescription(IReadOnlyList<string> nameParts) => $"using { string.Join(".", nameParts) };"; protected override (string description, bool hasExistingImport) GetDescription( Document document, OptionSet options, INamespaceOrTypeSymbol namespaceOrTypeSymbol, SemanticModel semanticModel, SyntaxNode contextNode, CancellationToken cancellationToken) { var root = GetCompilationUnitSyntaxNode(contextNode, cancellationToken); // See if this is a reference to a type from a reference that has a specific alias // associated with it. If that extern alias hasn't already been brought into scope // then add that one. var (externAlias, hasExistingExtern) = GetExternAliasDirective( namespaceOrTypeSymbol, semanticModel, contextNode); var (usingDirective, hasExistingUsing) = GetUsingDirective( document, options, namespaceOrTypeSymbol, semanticModel, root, contextNode); var externAliasString = externAlias != null ? $"extern alias {externAlias.Identifier.ValueText};" : null; var usingDirectiveString = usingDirective != null ? GetUsingDirectiveString(namespaceOrTypeSymbol) : null; if (externAlias == null && usingDirective == null) { return (null, false); } if (externAlias != null && !hasExistingExtern) { return (externAliasString, false); } if (usingDirective != null && !hasExistingUsing) { return (usingDirectiveString, false); } return externAlias != null ? (externAliasString, hasExistingExtern) : (usingDirectiveString, hasExistingUsing); } private static string GetUsingDirectiveString(INamespaceOrTypeSymbol namespaceOrTypeSymbol) { var displayString = namespaceOrTypeSymbol.ToDisplayString(); return namespaceOrTypeSymbol.IsKind(SymbolKind.Namespace) ? $"using {displayString};" : $"using static {displayString};"; } protected override async Task<Document> AddImportAsync( SyntaxNode contextNode, INamespaceOrTypeSymbol namespaceOrTypeSymbol, Document document, bool allowInHiddenRegions, CancellationToken cancellationToken) { var root = GetCompilationUnitSyntaxNode(contextNode, cancellationToken); var newRoot = await AddImportWorkerAsync(document, root, contextNode, namespaceOrTypeSymbol, allowInHiddenRegions, cancellationToken).ConfigureAwait(false); return document.WithSyntaxRoot(newRoot); } private async Task<CompilationUnitSyntax> AddImportWorkerAsync( Document document, CompilationUnitSyntax root, SyntaxNode contextNode, INamespaceOrTypeSymbol namespaceOrTypeSymbol, bool allowInHiddenRegions, CancellationToken cancellationToken) { var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var (externAliasDirective, hasExistingExtern) = GetExternAliasDirective( namespaceOrTypeSymbol, semanticModel, contextNode); var (usingDirective, hasExistingUsing) = GetUsingDirective( document, options, namespaceOrTypeSymbol, semanticModel, root, contextNode); using var _ = ArrayBuilder<SyntaxNode>.GetInstance(out var newImports); if (!hasExistingExtern && externAliasDirective != null) { newImports.Add(externAliasDirective); } if (!hasExistingUsing && usingDirective != null) { newImports.Add(usingDirective); } if (newImports.Count == 0) { return root; } var addImportService = document.GetLanguageService<IAddImportsService>(); var generator = SyntaxGenerator.GetGenerator(document); var newRoot = addImportService.AddImports( semanticModel.Compilation, root, contextNode, newImports, generator, options, allowInHiddenRegions, cancellationToken); return (CompilationUnitSyntax)newRoot; } protected override async Task<Document> AddImportAsync( SyntaxNode contextNode, IReadOnlyList<string> namespaceParts, Document document, bool allowInHiddenRegions, CancellationToken cancellationToken) { var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var root = GetCompilationUnitSyntaxNode(contextNode, cancellationToken); var usingDirective = SyntaxFactory.UsingDirective( CreateNameSyntax(namespaceParts, namespaceParts.Count - 1)); var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var service = document.GetLanguageService<IAddImportsService>(); var generator = SyntaxGenerator.GetGenerator(document); var newRoot = service.AddImport( compilation, root, contextNode, usingDirective, generator, options, allowInHiddenRegions, cancellationToken); return document.WithSyntaxRoot(newRoot); } private NameSyntax CreateNameSyntax(IReadOnlyList<string> namespaceParts, int index) { var part = namespaceParts[index]; if (SyntaxFacts.GetKeywordKind(part) != SyntaxKind.None) { part = "@" + part; } var namePiece = SyntaxFactory.IdentifierName(part); return index == 0 ? (NameSyntax)namePiece : SyntaxFactory.QualifiedName(CreateNameSyntax(namespaceParts, index - 1), namePiece); } private static (ExternAliasDirectiveSyntax, bool hasExistingImport) GetExternAliasDirective( INamespaceOrTypeSymbol namespaceSymbol, SemanticModel semanticModel, SyntaxNode contextNode) { var (val, hasExistingExtern) = GetExternAliasString(namespaceSymbol, semanticModel, contextNode); if (val == null) { return (null, false); } return (SyntaxFactory.ExternAliasDirective(SyntaxFactory.Identifier(val)) .WithAdditionalAnnotations(Formatter.Annotation), hasExistingExtern); } private (UsingDirectiveSyntax, bool hasExistingImport) GetUsingDirective( Document document, OptionSet options, INamespaceOrTypeSymbol namespaceOrTypeSymbol, SemanticModel semanticModel, CompilationUnitSyntax root, SyntaxNode contextNode) { var addImportService = document.GetLanguageService<IAddImportsService>(); var generator = SyntaxGenerator.GetGenerator(document); var nameSyntax = namespaceOrTypeSymbol.GenerateNameSyntax(); // We need to create our using in two passes. This is because we need a using // directive so we can figure out where to put it. Then, once we figure out // where to put it, we might need to change it a bit (e.g. removing 'global' // from it if necessary). So we first create a dummy using directive just to // determine which container we're going in. Then we'll use the container to // help create the final using. var dummyUsing = SyntaxFactory.UsingDirective(nameSyntax); var container = addImportService.GetImportContainer(root, contextNode, dummyUsing, options); var namespaceToAddTo = container as BaseNamespaceDeclarationSyntax; // Replace the alias that GenerateTypeSyntax added if we want this to be looked // up off of an extern alias. var (externAliasDirective, _) = GetExternAliasDirective( namespaceOrTypeSymbol, semanticModel, contextNode); var externAlias = externAliasDirective?.Identifier.ValueText; if (externAlias != null) { nameSyntax = AddOrReplaceAlias(nameSyntax, SyntaxFactory.IdentifierName(externAlias)); } else { // The name we generated will have the global:: alias on it. We only need // that if the name of our symbol is actually ambiguous in this context. // If so, keep global:: on it, otherwise remove it. // // Note: doing this has a couple of benefits. First, it's easy for us to see // if we have an existing using for this with the same syntax. Second, // it's easy to sort usings properly. If "global::" was attached to the // using directive, then it would make both of those operations more difficult // to achieve. nameSyntax = RemoveGlobalAliasIfUnnecessary(semanticModel, nameSyntax, namespaceToAddTo); } var usingDirective = SyntaxFactory.UsingDirective(nameSyntax) .WithAdditionalAnnotations(Formatter.Annotation); usingDirective = namespaceOrTypeSymbol.IsKind(SymbolKind.Namespace) ? usingDirective : usingDirective.WithStaticKeyword(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); return (usingDirective, addImportService.HasExistingImport(semanticModel.Compilation, root, contextNode, usingDirective, generator)); } private static NameSyntax RemoveGlobalAliasIfUnnecessary( SemanticModel semanticModel, NameSyntax nameSyntax, BaseNamespaceDeclarationSyntax namespaceToAddTo) { var aliasQualifiedName = nameSyntax.DescendantNodesAndSelf() .OfType<AliasQualifiedNameSyntax>() .FirstOrDefault(); if (aliasQualifiedName != null) { var rightOfAliasName = aliasQualifiedName.Name.Identifier.ValueText; if (!ConflictsWithExistingMember(semanticModel, namespaceToAddTo, rightOfAliasName)) { // Strip off the alias. return nameSyntax.ReplaceNode(aliasQualifiedName, aliasQualifiedName.Name); } } return nameSyntax; } private static bool ConflictsWithExistingMember( SemanticModel semanticModel, BaseNamespaceDeclarationSyntax namespaceToAddTo, string rightOfAliasName) { if (namespaceToAddTo != null) { var containingNamespaceSymbol = semanticModel.GetDeclaredSymbol(namespaceToAddTo); while (containingNamespaceSymbol != null && !containingNamespaceSymbol.IsGlobalNamespace) { if (containingNamespaceSymbol.GetMembers(rightOfAliasName).Any()) { // A containing namespace had this name in it. We need to stay globally qualified. return true; } containingNamespaceSymbol = containingNamespaceSymbol.ContainingNamespace; } } // Didn't conflict with anything. We should remove the global:: alias. return false; } private NameSyntax AddOrReplaceAlias( NameSyntax nameSyntax, IdentifierNameSyntax alias) { if (nameSyntax is SimpleNameSyntax simpleName) { return SyntaxFactory.AliasQualifiedName(alias, simpleName); } if (nameSyntax is QualifiedNameSyntax qualifiedName) { return qualifiedName.WithLeft(AddOrReplaceAlias(qualifiedName.Left, alias)); } var aliasName = nameSyntax as AliasQualifiedNameSyntax; return aliasName.WithAlias(alias); } private static (string, bool hasExistingImport) GetExternAliasString( INamespaceOrTypeSymbol namespaceSymbol, SemanticModel semanticModel, SyntaxNode contextNode) { string externAliasString = null; var metadataReference = semanticModel.Compilation.GetMetadataReference(namespaceSymbol.ContainingAssembly); if (metadataReference == null) { return (null, false); } var aliases = metadataReference.Properties.Aliases; if (aliases.IsEmpty) { return (null, false); } aliases = metadataReference.Properties.Aliases.Where(a => a != MetadataReferenceProperties.GlobalAlias).ToImmutableArray(); if (!aliases.Any()) { return (null, false); } // Just default to using the first alias we see for this symbol. externAliasString = aliases.First(); return (externAliasString, HasExistingExternAlias(externAliasString, contextNode)); } private static bool HasExistingExternAlias(string alias, SyntaxNode contextNode) { foreach (var externAlias in contextNode.GetEnclosingExternAliasDirectives()) { // We already have this extern alias in scope. No need to add it. if (externAlias.Identifier.ValueText == alias) { return true; } } return false; } private static CompilationUnitSyntax GetCompilationUnitSyntaxNode( SyntaxNode contextNode, CancellationToken cancellationToken) { return (CompilationUnitSyntax)contextNode.SyntaxTree.GetRoot(cancellationToken); } protected override bool IsViableExtensionMethod(IMethodSymbol method, SyntaxNode expression, SemanticModel semanticModel, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken) { var leftExpression = syntaxFacts.GetExpressionOfMemberAccessExpression(expression) ?? syntaxFacts.GetTargetOfMemberBinding(expression); if (leftExpression == null) { if (expression.IsKind(SyntaxKind.CollectionInitializerExpression)) { leftExpression = expression.GetAncestor<ObjectCreationExpressionSyntax>(); } else { return false; } } var semanticInfo = semanticModel.GetTypeInfo(leftExpression, cancellationToken); var leftExpressionType = semanticInfo.Type; return IsViableExtensionMethod(method, leftExpressionType); } protected override bool IsAddMethodContext(SyntaxNode node, SemanticModel semanticModel) { if (node.Parent.IsKind(SyntaxKind.CollectionInitializerExpression)) { var objectCreationExpressionSyntax = node.GetAncestor<ObjectCreationExpressionSyntax>(); if (objectCreationExpressionSyntax == null) { return false; } return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.AddImport; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CSharp.AddImport.AddImportDiagnosticIds; namespace Microsoft.CodeAnalysis.CSharp.AddImport { [ExportLanguageService(typeof(IAddImportFeatureService), LanguageNames.CSharp), Shared] internal class CSharpAddImportFeatureService : AbstractAddImportFeatureService<SimpleNameSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpAddImportFeatureService() { } protected override bool CanAddImport(SyntaxNode node, bool allowInHiddenRegions, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return node.CanAddUsingDirectives(allowInHiddenRegions, cancellationToken); } protected override bool CanAddImportForMethod( string diagnosticId, ISyntaxFacts syntaxFacts, SyntaxNode node, out SimpleNameSyntax nameNode) { nameNode = null; switch (diagnosticId) { case CS7036: case CS0308: case CS0428: case CS1061: if (node.IsKind(SyntaxKind.ConditionalAccessExpression, out ConditionalAccessExpressionSyntax conditionalAccess)) { node = conditionalAccess.WhenNotNull; } else if (node.IsKind(SyntaxKind.MemberBindingExpression, out MemberBindingExpressionSyntax memberBinding1)) { node = memberBinding1.Name; } else if (node.Parent.IsKind(SyntaxKind.CollectionInitializerExpression)) { return true; } break; case CS0122: case CS1501: if (node is SimpleNameSyntax) { break; } else if (node is MemberBindingExpressionSyntax memberBindingExpr) { node = memberBindingExpr.Name; } break; case CS1929: var memberAccessName = (node.Parent as MemberAccessExpressionSyntax)?.Name; var conditionalAccessName = (((node.Parent as ConditionalAccessExpressionSyntax)?.WhenNotNull as InvocationExpressionSyntax)?.Expression as MemberBindingExpressionSyntax)?.Name; if (memberAccessName == null && conditionalAccessName == null) { return false; } node = memberAccessName ?? conditionalAccessName; break; case CS1503: //// look up its corresponding method name var parent = node.GetAncestor<InvocationExpressionSyntax>(); if (parent == null) { return false; } if (parent.Expression is MemberAccessExpressionSyntax method) { node = method.Name; } break; case CS1955: break; default: return false; } nameNode = node as SimpleNameSyntax; if (!nameNode.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) && !nameNode.IsParentKind(SyntaxKind.MemberBindingExpression)) { return false; } var memberAccess = nameNode.Parent as MemberAccessExpressionSyntax; var memberBinding = nameNode.Parent as MemberBindingExpressionSyntax; if (memberAccess.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) || memberAccess.IsParentKind(SyntaxKind.ElementAccessExpression) || memberBinding.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) || memberBinding.IsParentKind(SyntaxKind.ElementAccessExpression)) { return false; } if (!syntaxFacts.IsNameOfSimpleMemberAccessExpression(node) && !syntaxFacts.IsNameOfMemberBindingExpression(node)) { return false; } return true; } protected override bool CanAddImportForDeconstruct(string diagnosticId, SyntaxNode node) => diagnosticId == CS8129; protected override bool CanAddImportForGetAwaiter(string diagnosticId, ISyntaxFacts syntaxFactsService, SyntaxNode node) => (diagnosticId == CS1061 || // Regular cases diagnosticId == CS4036 || // WinRT async interfaces diagnosticId == CS1929) && // An extension `GetAwaiter()` is in scope, but for another type AncestorOrSelfIsAwaitExpression(syntaxFactsService, node); protected override bool CanAddImportForGetEnumerator(string diagnosticId, ISyntaxFacts syntaxFactsService, SyntaxNode node) => diagnosticId == CS1579 || diagnosticId == CS8414; protected override bool CanAddImportForGetAsyncEnumerator(string diagnosticId, ISyntaxFacts syntaxFactsService, SyntaxNode node) => diagnosticId == CS8411 || diagnosticId == CS8415; protected override bool CanAddImportForNamespace(string diagnosticId, SyntaxNode node, out SimpleNameSyntax nameNode) { nameNode = null; return false; } protected override bool CanAddImportForQuery(string diagnosticId, SyntaxNode node) => (diagnosticId == CS1935 || // Regular cases diagnosticId == CS1929) && // An extension method is in scope, but for another type node.AncestorsAndSelf().Any(n => n is QueryExpressionSyntax && !(n.Parent is QueryContinuationSyntax)); protected override bool CanAddImportForType(string diagnosticId, SyntaxNode node, out SimpleNameSyntax nameNode) { nameNode = null; switch (diagnosticId) { case CS0103: case IDEDiagnosticIds.UnboundIdentifierId: case CS0246: case CS0305: case CS0308: case CS0122: case CS0307: case CS0616: case CS1580: case CS1581: case CS1955: case CS0281: break; case CS1574: case CS1584: if (node is QualifiedCrefSyntax cref) { node = cref.Container; } break; default: return false; } return TryFindStandaloneType(node, out nameNode); } private static bool TryFindStandaloneType(SyntaxNode node, out SimpleNameSyntax nameNode) { if (node is QualifiedNameSyntax qn) { node = GetLeftMostSimpleName(qn); } nameNode = node as SimpleNameSyntax; return nameNode.LooksLikeStandaloneTypeName(); } private static SimpleNameSyntax GetLeftMostSimpleName(QualifiedNameSyntax qn) { while (qn != null) { var left = qn.Left; if (left is SimpleNameSyntax simpleName) { return simpleName; } qn = left as QualifiedNameSyntax; } return null; } protected override ISet<INamespaceSymbol> GetImportNamespacesInScope( SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) { return semanticModel.GetUsingNamespacesInScope(node); } protected override ITypeSymbol GetDeconstructInfo( SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) { return semanticModel.GetTypeInfo(node, cancellationToken).Type; } protected override ITypeSymbol GetQueryClauseInfo( SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) { var query = node.AncestorsAndSelf().OfType<QueryExpressionSyntax>().First(); if (InfoBoundSuccessfully(semanticModel.GetQueryClauseInfo(query.FromClause, cancellationToken))) { return null; } foreach (var clause in query.Body.Clauses) { if (InfoBoundSuccessfully(semanticModel.GetQueryClauseInfo(clause, cancellationToken))) { return null; } } if (InfoBoundSuccessfully(semanticModel.GetSymbolInfo(query.Body.SelectOrGroup, cancellationToken))) { return null; } var fromClause = query.FromClause; return semanticModel.GetTypeInfo(fromClause.Expression, cancellationToken).Type; } private static bool InfoBoundSuccessfully(SymbolInfo symbolInfo) => InfoBoundSuccessfully(symbolInfo.Symbol); private static bool InfoBoundSuccessfully(QueryClauseInfo semanticInfo) => InfoBoundSuccessfully(semanticInfo.OperationInfo); private static bool InfoBoundSuccessfully(ISymbol operation) { operation = operation.GetOriginalUnreducedDefinition(); return operation != null; } protected override string GetDescription(IReadOnlyList<string> nameParts) => $"using { string.Join(".", nameParts) };"; protected override (string description, bool hasExistingImport) GetDescription( Document document, OptionSet options, INamespaceOrTypeSymbol namespaceOrTypeSymbol, SemanticModel semanticModel, SyntaxNode contextNode, CancellationToken cancellationToken) { var root = GetCompilationUnitSyntaxNode(contextNode, cancellationToken); // See if this is a reference to a type from a reference that has a specific alias // associated with it. If that extern alias hasn't already been brought into scope // then add that one. var (externAlias, hasExistingExtern) = GetExternAliasDirective( namespaceOrTypeSymbol, semanticModel, contextNode); var (usingDirective, hasExistingUsing) = GetUsingDirective( document, options, namespaceOrTypeSymbol, semanticModel, root, contextNode); var externAliasString = externAlias != null ? $"extern alias {externAlias.Identifier.ValueText};" : null; var usingDirectiveString = usingDirective != null ? GetUsingDirectiveString(namespaceOrTypeSymbol) : null; if (externAlias == null && usingDirective == null) { return (null, false); } if (externAlias != null && !hasExistingExtern) { return (externAliasString, false); } if (usingDirective != null && !hasExistingUsing) { return (usingDirectiveString, false); } return externAlias != null ? (externAliasString, hasExistingExtern) : (usingDirectiveString, hasExistingUsing); } private static string GetUsingDirectiveString(INamespaceOrTypeSymbol namespaceOrTypeSymbol) { var displayString = namespaceOrTypeSymbol.ToDisplayString(); return namespaceOrTypeSymbol.IsKind(SymbolKind.Namespace) ? $"using {displayString};" : $"using static {displayString};"; } protected override async Task<Document> AddImportAsync( SyntaxNode contextNode, INamespaceOrTypeSymbol namespaceOrTypeSymbol, Document document, bool allowInHiddenRegions, CancellationToken cancellationToken) { var root = GetCompilationUnitSyntaxNode(contextNode, cancellationToken); var newRoot = await AddImportWorkerAsync(document, root, contextNode, namespaceOrTypeSymbol, allowInHiddenRegions, cancellationToken).ConfigureAwait(false); return document.WithSyntaxRoot(newRoot); } private async Task<CompilationUnitSyntax> AddImportWorkerAsync( Document document, CompilationUnitSyntax root, SyntaxNode contextNode, INamespaceOrTypeSymbol namespaceOrTypeSymbol, bool allowInHiddenRegions, CancellationToken cancellationToken) { var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var (externAliasDirective, hasExistingExtern) = GetExternAliasDirective( namespaceOrTypeSymbol, semanticModel, contextNode); var (usingDirective, hasExistingUsing) = GetUsingDirective( document, options, namespaceOrTypeSymbol, semanticModel, root, contextNode); using var _ = ArrayBuilder<SyntaxNode>.GetInstance(out var newImports); if (!hasExistingExtern && externAliasDirective != null) { newImports.Add(externAliasDirective); } if (!hasExistingUsing && usingDirective != null) { newImports.Add(usingDirective); } if (newImports.Count == 0) { return root; } var addImportService = document.GetLanguageService<IAddImportsService>(); var generator = SyntaxGenerator.GetGenerator(document); var newRoot = addImportService.AddImports( semanticModel.Compilation, root, contextNode, newImports, generator, options, allowInHiddenRegions, cancellationToken); return (CompilationUnitSyntax)newRoot; } protected override async Task<Document> AddImportAsync( SyntaxNode contextNode, IReadOnlyList<string> namespaceParts, Document document, bool allowInHiddenRegions, CancellationToken cancellationToken) { var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var root = GetCompilationUnitSyntaxNode(contextNode, cancellationToken); var usingDirective = SyntaxFactory.UsingDirective( CreateNameSyntax(namespaceParts, namespaceParts.Count - 1)); var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var service = document.GetLanguageService<IAddImportsService>(); var generator = SyntaxGenerator.GetGenerator(document); var newRoot = service.AddImport( compilation, root, contextNode, usingDirective, generator, options, allowInHiddenRegions, cancellationToken); return document.WithSyntaxRoot(newRoot); } private NameSyntax CreateNameSyntax(IReadOnlyList<string> namespaceParts, int index) { var part = namespaceParts[index]; if (SyntaxFacts.GetKeywordKind(part) != SyntaxKind.None) { part = "@" + part; } var namePiece = SyntaxFactory.IdentifierName(part); return index == 0 ? (NameSyntax)namePiece : SyntaxFactory.QualifiedName(CreateNameSyntax(namespaceParts, index - 1), namePiece); } private static (ExternAliasDirectiveSyntax, bool hasExistingImport) GetExternAliasDirective( INamespaceOrTypeSymbol namespaceSymbol, SemanticModel semanticModel, SyntaxNode contextNode) { var (val, hasExistingExtern) = GetExternAliasString(namespaceSymbol, semanticModel, contextNode); if (val == null) { return (null, false); } return (SyntaxFactory.ExternAliasDirective(SyntaxFactory.Identifier(val)) .WithAdditionalAnnotations(Formatter.Annotation), hasExistingExtern); } private (UsingDirectiveSyntax, bool hasExistingImport) GetUsingDirective( Document document, OptionSet options, INamespaceOrTypeSymbol namespaceOrTypeSymbol, SemanticModel semanticModel, CompilationUnitSyntax root, SyntaxNode contextNode) { var addImportService = document.GetLanguageService<IAddImportsService>(); var generator = SyntaxGenerator.GetGenerator(document); var nameSyntax = namespaceOrTypeSymbol.GenerateNameSyntax(); // We need to create our using in two passes. This is because we need a using // directive so we can figure out where to put it. Then, once we figure out // where to put it, we might need to change it a bit (e.g. removing 'global' // from it if necessary). So we first create a dummy using directive just to // determine which container we're going in. Then we'll use the container to // help create the final using. var dummyUsing = SyntaxFactory.UsingDirective(nameSyntax); var container = addImportService.GetImportContainer(root, contextNode, dummyUsing, options); var namespaceToAddTo = container as BaseNamespaceDeclarationSyntax; // Replace the alias that GenerateTypeSyntax added if we want this to be looked // up off of an extern alias. var (externAliasDirective, _) = GetExternAliasDirective( namespaceOrTypeSymbol, semanticModel, contextNode); var externAlias = externAliasDirective?.Identifier.ValueText; if (externAlias != null) { nameSyntax = AddOrReplaceAlias(nameSyntax, SyntaxFactory.IdentifierName(externAlias)); } else { // The name we generated will have the global:: alias on it. We only need // that if the name of our symbol is actually ambiguous in this context. // If so, keep global:: on it, otherwise remove it. // // Note: doing this has a couple of benefits. First, it's easy for us to see // if we have an existing using for this with the same syntax. Second, // it's easy to sort usings properly. If "global::" was attached to the // using directive, then it would make both of those operations more difficult // to achieve. nameSyntax = RemoveGlobalAliasIfUnnecessary(semanticModel, nameSyntax, namespaceToAddTo); } var usingDirective = SyntaxFactory.UsingDirective(nameSyntax) .WithAdditionalAnnotations(Formatter.Annotation); usingDirective = namespaceOrTypeSymbol.IsKind(SymbolKind.Namespace) ? usingDirective : usingDirective.WithStaticKeyword(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); return (usingDirective, addImportService.HasExistingImport(semanticModel.Compilation, root, contextNode, usingDirective, generator)); } private static NameSyntax RemoveGlobalAliasIfUnnecessary( SemanticModel semanticModel, NameSyntax nameSyntax, BaseNamespaceDeclarationSyntax namespaceToAddTo) { var aliasQualifiedName = nameSyntax.DescendantNodesAndSelf() .OfType<AliasQualifiedNameSyntax>() .FirstOrDefault(); if (aliasQualifiedName != null) { var rightOfAliasName = aliasQualifiedName.Name.Identifier.ValueText; if (!ConflictsWithExistingMember(semanticModel, namespaceToAddTo, rightOfAliasName)) { // Strip off the alias. return nameSyntax.ReplaceNode(aliasQualifiedName, aliasQualifiedName.Name); } } return nameSyntax; } private static bool ConflictsWithExistingMember( SemanticModel semanticModel, BaseNamespaceDeclarationSyntax namespaceToAddTo, string rightOfAliasName) { if (namespaceToAddTo != null) { var containingNamespaceSymbol = semanticModel.GetDeclaredSymbol(namespaceToAddTo); while (containingNamespaceSymbol != null && !containingNamespaceSymbol.IsGlobalNamespace) { if (containingNamespaceSymbol.GetMembers(rightOfAliasName).Any()) { // A containing namespace had this name in it. We need to stay globally qualified. return true; } containingNamespaceSymbol = containingNamespaceSymbol.ContainingNamespace; } } // Didn't conflict with anything. We should remove the global:: alias. return false; } private NameSyntax AddOrReplaceAlias( NameSyntax nameSyntax, IdentifierNameSyntax alias) { if (nameSyntax is SimpleNameSyntax simpleName) { return SyntaxFactory.AliasQualifiedName(alias, simpleName); } if (nameSyntax is QualifiedNameSyntax qualifiedName) { return qualifiedName.WithLeft(AddOrReplaceAlias(qualifiedName.Left, alias)); } var aliasName = nameSyntax as AliasQualifiedNameSyntax; return aliasName.WithAlias(alias); } private static (string, bool hasExistingImport) GetExternAliasString( INamespaceOrTypeSymbol namespaceSymbol, SemanticModel semanticModel, SyntaxNode contextNode) { string externAliasString = null; var metadataReference = semanticModel.Compilation.GetMetadataReference(namespaceSymbol.ContainingAssembly); if (metadataReference == null) { return (null, false); } var aliases = metadataReference.Properties.Aliases; if (aliases.IsEmpty) { return (null, false); } aliases = metadataReference.Properties.Aliases.Where(a => a != MetadataReferenceProperties.GlobalAlias).ToImmutableArray(); if (!aliases.Any()) { return (null, false); } // Just default to using the first alias we see for this symbol. externAliasString = aliases.First(); return (externAliasString, HasExistingExternAlias(externAliasString, contextNode)); } private static bool HasExistingExternAlias(string alias, SyntaxNode contextNode) { foreach (var externAlias in contextNode.GetEnclosingExternAliasDirectives()) { // We already have this extern alias in scope. No need to add it. if (externAlias.Identifier.ValueText == alias) { return true; } } return false; } private static CompilationUnitSyntax GetCompilationUnitSyntaxNode( SyntaxNode contextNode, CancellationToken cancellationToken) { return (CompilationUnitSyntax)contextNode.SyntaxTree.GetRoot(cancellationToken); } protected override bool IsViableExtensionMethod(IMethodSymbol method, SyntaxNode expression, SemanticModel semanticModel, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken) { var leftExpression = syntaxFacts.IsAnyMemberAccessExpression(expression) ? syntaxFacts.GetExpressionOfMemberAccessExpression(expression) : syntaxFacts.GetTargetOfMemberBinding(expression); if (leftExpression == null) { if (expression.IsKind(SyntaxKind.CollectionInitializerExpression)) { leftExpression = expression.GetAncestor<ObjectCreationExpressionSyntax>(); } else { return false; } } var semanticInfo = semanticModel.GetTypeInfo(leftExpression, cancellationToken); var leftExpressionType = semanticInfo.Type; return IsViableExtensionMethod(method, leftExpressionType); } protected override bool IsAddMethodContext(SyntaxNode node, SemanticModel semanticModel) { if (node.Parent.IsKind(SyntaxKind.CollectionInitializerExpression)) { var objectCreationExpressionSyntax = node.GetAncestor<ObjectCreationExpressionSyntax>(); if (objectCreationExpressionSyntax == null) { return false; } return true; } return false; } } }
1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Features/CSharp/Portable/ConvertToInterpolatedString/CSharpConvertPlaceholderToInterpolatedStringRefactoringProvider.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.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertToInterpolatedString; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.ConvertToInterpolatedString { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertPlaceholderToInterpolatedString), Shared] internal partial class CSharpConvertPlaceholderToInterpolatedStringRefactoringProvider : AbstractConvertPlaceholderToInterpolatedStringRefactoringProvider<InvocationExpressionSyntax, ExpressionSyntax, ArgumentSyntax, LiteralExpressionSyntax, ArgumentListSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertPlaceholderToInterpolatedStringRefactoringProvider() { } protected override SyntaxNode GetInterpolatedString(string text) => SyntaxFactory.ParseExpression("$" + text) as InterpolatedStringExpressionSyntax; } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertToInterpolatedString; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.ConvertToInterpolatedString { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertPlaceholderToInterpolatedString), Shared] internal partial class CSharpConvertPlaceholderToInterpolatedStringRefactoringProvider : AbstractConvertPlaceholderToInterpolatedStringRefactoringProvider< InvocationExpressionSyntax, ExpressionSyntax, ArgumentSyntax, LiteralExpressionSyntax, ArgumentListSyntax, InterpolationSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertPlaceholderToInterpolatedStringRefactoringProvider() { } protected override SyntaxNode GetInterpolatedString(string text) => SyntaxFactory.ParseExpression("$" + text) as InterpolatedStringExpressionSyntax; } }
1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Features/Core/Portable/AddImport/SymbolReferenceFinder.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; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolSearch; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Shared.Utilities.EditorBrowsableHelpers; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> { private partial class SymbolReferenceFinder { private const string AttributeSuffix = nameof(Attribute); private readonly string _diagnosticId; private readonly Document _document; private readonly SemanticModel _semanticModel; private readonly ISet<INamespaceSymbol> _namespacesInScope; private readonly ISyntaxFactsService _syntaxFacts; private readonly AbstractAddImportFeatureService<TSimpleNameSyntax> _owner; private readonly SyntaxNode _node; private readonly ISymbolSearchService _symbolSearchService; private readonly bool _searchReferenceAssemblies; private readonly ImmutableArray<PackageSource> _packageSources; public SymbolReferenceFinder( AbstractAddImportFeatureService<TSimpleNameSyntax> owner, Document document, SemanticModel semanticModel, string diagnosticId, SyntaxNode node, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { _owner = owner; _document = document; _semanticModel = semanticModel; _diagnosticId = diagnosticId; _node = node; _symbolSearchService = symbolSearchService; _searchReferenceAssemblies = searchReferenceAssemblies; _packageSources = packageSources; if (_searchReferenceAssemblies || packageSources.Length > 0) { Contract.ThrowIfNull(symbolSearchService); } _syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); _namespacesInScope = GetNamespacesInScope(cancellationToken); } private ISet<INamespaceSymbol> GetNamespacesInScope(CancellationToken cancellationToken) { // Add all the namespaces brought in by imports/usings. var set = _owner.GetImportNamespacesInScope(_semanticModel, _node, cancellationToken); // Also add all the namespaces we're contained in. We don't want // to add imports for these namespaces either. for (var containingNamespace = _semanticModel.GetEnclosingNamespace(_node.SpanStart, cancellationToken); containingNamespace != null; containingNamespace = containingNamespace.ContainingNamespace) { set.Add(MapToCompilationNamespaceIfPossible(containingNamespace)); } return set; } private INamespaceSymbol MapToCompilationNamespaceIfPossible(INamespaceSymbol containingNamespace) => _semanticModel.Compilation.GetCompilationNamespace(containingNamespace) ?? containingNamespace; internal Task<ImmutableArray<SymbolReference>> FindInAllSymbolsInStartingProjectAsync( bool exact, CancellationToken cancellationToken) { var searchScope = new AllSymbolsProjectSearchScope( _owner, _document.Project, exact, cancellationToken); return DoAsync(searchScope); } internal Task<ImmutableArray<SymbolReference>> FindInSourceSymbolsInProjectAsync( ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>> projectToAssembly, Project project, bool exact, CancellationToken cancellationToken) { var searchScope = new SourceSymbolsProjectSearchScope( _owner, projectToAssembly, project, exact, cancellationToken); return DoAsync(searchScope); } internal Task<ImmutableArray<SymbolReference>> FindInMetadataSymbolsAsync( IAssemblySymbol assembly, ProjectId assemblyProjectId, PortableExecutableReference metadataReference, bool exact, CancellationToken cancellationToken) { var searchScope = new MetadataSymbolsSearchScope( _owner, _document.Project.Solution, assembly, assemblyProjectId, metadataReference, exact, cancellationToken); return DoAsync(searchScope); } private async Task<ImmutableArray<SymbolReference>> DoAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); // Spin off tasks to do all our searching in parallel using var _1 = ArrayBuilder<Task<ImmutableArray<SymbolReference>>>.GetInstance(out var tasks); tasks.Add(GetReferencesForMatchingTypesAsync(searchScope)); tasks.Add(GetReferencesForMatchingNamespacesAsync(searchScope)); tasks.Add(GetReferencesForMatchingFieldsAndPropertiesAsync(searchScope)); tasks.Add(GetReferencesForMatchingExtensionMethodsAsync(searchScope)); // Searching for things like "Add" (for collection initializers) and "Select" // (for extension methods) should only be done when doing an 'exact' search. // We should not do fuzzy searches for these names. In this case it's not // like the user was writing Add or Select, but instead we're looking for // viable symbols with those names to make a collection initializer or // query expression valid. if (searchScope.Exact) { tasks.Add(GetReferencesForCollectionInitializerMethodsAsync(searchScope)); tasks.Add(GetReferencesForQueryPatternsAsync(searchScope)); tasks.Add(GetReferencesForDeconstructAsync(searchScope)); tasks.Add(GetReferencesForGetAwaiterAsync(searchScope)); tasks.Add(GetReferencesForGetEnumeratorAsync(searchScope)); tasks.Add(GetReferencesForGetAsyncEnumeratorAsync(searchScope)); } await Task.WhenAll(tasks).ConfigureAwait(false); searchScope.CancellationToken.ThrowIfCancellationRequested(); using var _2 = ArrayBuilder<SymbolReference>.GetInstance(out var allReferences); foreach (var task in tasks) { var taskResult = await task.ConfigureAwait(false); allReferences.AddRange(taskResult); } return DeDupeAndSortReferences(allReferences.ToImmutable()); } private ImmutableArray<SymbolReference> DeDupeAndSortReferences(ImmutableArray<SymbolReference> allReferences) { return allReferences .Distinct() .Where(NotNull) .Where(NotGlobalNamespace) .OrderBy((r1, r2) => r1.CompareTo(_document, r2)) .ToImmutableArray(); } private static void CalculateContext( TSimpleNameSyntax nameNode, ISyntaxFactsService syntaxFacts, out string name, out int arity, out bool inAttributeContext, out bool hasIncompleteParentMember, out bool looksGeneric) { // Has to be a simple identifier or generic name. syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out name, out arity); inAttributeContext = syntaxFacts.IsAttributeName(nameNode); hasIncompleteParentMember = syntaxFacts.HasIncompleteParentMember(nameNode); looksGeneric = syntaxFacts.LooksGeneric(nameNode); } /// <summary> /// Searches for types that match the name the user has written. Returns <see cref="SymbolReference"/>s /// to the <see cref="INamespaceSymbol"/>s or <see cref="INamedTypeSymbol"/>s those types are /// contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingTypesAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (!_owner.CanAddImportForType(_diagnosticId, _node, out var nameNode)) { return ImmutableArray<SymbolReference>.Empty; } CalculateContext( nameNode, _syntaxFacts, out var name, out var arity, out var inAttributeContext, out var hasIncompleteParentMember, out var looksGeneric); if (ExpressionBinds(nameNode, checkForExtensionMethods: false, cancellationToken: searchScope.CancellationToken)) { // If the expression bound, there's nothing to do. return ImmutableArray<SymbolReference>.Empty; } var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Type).ConfigureAwait(false); // also lookup type symbols with the "Attribute" suffix if necessary. if (inAttributeContext) { var attributeSymbols = await searchScope.FindDeclarationsAsync(name + AttributeSuffix, nameNode, SymbolFilter.Type).ConfigureAwait(false); symbols = symbols.AddRange( attributeSymbols.Select(r => r.WithDesiredName(r.DesiredName.GetWithoutAttributeSuffix(isCaseSensitive: false)))); } var typeSymbols = OfType<ITypeSymbol>(symbols); var options = await _document.GetOptionsAsync(searchScope.CancellationToken).ConfigureAwait(false); var hideAdvancedMembers = options.GetOption(CompletionOptions.HideAdvancedMembers); var editorBrowserInfo = new EditorBrowsableInfo(_semanticModel.Compilation); // Only keep symbols which are accessible from the current location and that are allowed by the current // editor browsable rules. var accessibleTypeSymbols = typeSymbols.WhereAsArray( s => ArityAccessibilityAndAttributeContextAreCorrect(s.Symbol, arity, inAttributeContext, hasIncompleteParentMember, looksGeneric) && s.Symbol.IsEditorBrowsable(hideAdvancedMembers, _semanticModel.Compilation, editorBrowserInfo)); // These types may be contained within namespaces, or they may be nested // inside generic types. Record these namespaces/types if it would be // legal to add imports for them. var typesContainedDirectlyInNamespaces = accessibleTypeSymbols.WhereAsArray(s => s.Symbol.ContainingSymbol is INamespaceSymbol); var typesContainedDirectlyInTypes = accessibleTypeSymbols.WhereAsArray(s => s.Symbol.ContainingType != null); var namespaceReferences = GetNamespaceSymbolReferences(searchScope, typesContainedDirectlyInNamespaces.SelectAsArray(r => r.WithSymbol(r.Symbol.ContainingNamespace))); var typeReferences = typesContainedDirectlyInTypes.SelectAsArray( r => searchScope.CreateReference(r.WithSymbol(r.Symbol.ContainingType))); return namespaceReferences.Concat(typeReferences); } private bool ArityAccessibilityAndAttributeContextAreCorrect( ITypeSymbol symbol, int arity, bool inAttributeContext, bool hasIncompleteParentMember, bool looksGeneric) { if (inAttributeContext && !symbol.IsAttribute()) { return false; } if (!symbol.IsAccessibleWithin(_semanticModel.Compilation.Assembly)) { return false; } if (looksGeneric && symbol.GetTypeArguments().Length == 0) { return false; } return arity == 0 || symbol.GetArity() == arity || hasIncompleteParentMember; } /// <summary> /// Searches for namespaces that match the name the user has written. Returns <see cref="SymbolReference"/>s /// to the <see cref="INamespaceSymbol"/>s those namespaces are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingNamespacesAsync( SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForNamespace(_diagnosticId, _node, out var nameNode)) { _syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out var name, out var arity); if (arity == 0 && !ExpressionBinds(nameNode, checkForExtensionMethods: false, cancellationToken: searchScope.CancellationToken)) { var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Namespace).ConfigureAwait(false); var namespaceSymbols = OfType<INamespaceSymbol>(symbols); var containingNamespaceSymbols = OfType<INamespaceSymbol>(symbols).SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, containingNamespaceSymbols); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Specialized finder for the "Color Color" case. Used when we have "Color.Black" and "Color" /// bound to a Field/Property, but not a type. In this case, we want to look for namespaces /// containing 'Color' as if we import them it can resolve this issue. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingFieldsAndPropertiesAsync( SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out var nameNode) && nameNode != null) { // We have code like "Color.Black". "Color" bound to a 'Color Color' property, and // 'Black' did not bind. We want to find a type called 'Color' that will actually // allow 'Black' to bind. var syntaxFacts = _document.GetLanguageService<ISyntaxFactsService>(); if (syntaxFacts.IsNameOfSimpleMemberAccessExpression(nameNode) || syntaxFacts.IsNameOfMemberBindingExpression(nameNode)) { var expression = syntaxFacts.GetExpressionOfMemberAccessExpression(nameNode.Parent, allowImplicitTarget: true) ?? syntaxFacts.GetTargetOfMemberBinding(nameNode.Parent); if (expression is TSimpleNameSyntax) { // Check if the expression before the dot binds to a property or field. var symbol = _semanticModel.GetSymbolInfo(expression, searchScope.CancellationToken).GetAnySymbol(); if (symbol?.Kind is SymbolKind.Property or SymbolKind.Field) { // Check if we have the 'Color Color' case. var propertyOrFieldType = symbol.GetSymbolType(); if (propertyOrFieldType is INamedTypeSymbol propertyType && Equals(propertyType.Name, symbol.Name)) { // Try to look up 'Color' as a type. var symbolResults = await searchScope.FindDeclarationsAsync( symbol.Name, (TSimpleNameSyntax)expression, SymbolFilter.Type).ConfigureAwait(false); // Return results that have accessible members. var namedTypeSymbols = OfType<INamedTypeSymbol>(symbolResults); var name = nameNode.GetFirstToken().ValueText; var namespaceResults = namedTypeSymbols.WhereAsArray(sr => HasAccessibleStaticFieldOrProperty(sr.Symbol, name)) .SelectAsArray(sr => sr.WithSymbol(sr.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceResults); } } } } } return ImmutableArray<SymbolReference>.Empty; } private bool HasAccessibleStaticFieldOrProperty(INamedTypeSymbol namedType, string fieldOrPropertyName) { return namedType.GetMembers(fieldOrPropertyName) .Any(m => (m is IFieldSymbol || m is IPropertySymbol) && m.IsStatic && m.IsAccessibleWithin(_semanticModel.Compilation.Assembly)); } /// <summary> /// Searches for extension methods that match the name the user has written. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingExtensionMethodsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out var nameNode) && nameNode != null) { searchScope.CancellationToken.ThrowIfCancellationRequested(); // See if the name binds. If it does, there's nothing further we need to do. if (!ExpressionBinds(nameNode, checkForExtensionMethods: true, cancellationToken: searchScope.CancellationToken)) { _syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out var name, out var arity); if (name != null) { var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Member).ConfigureAwait(false); var methodSymbols = OfType<IMethodSymbol>(symbols); var extensionMethodSymbols = GetViableExtensionMethods( methodSymbols, nameNode.Parent, searchScope.CancellationToken); var namespaceSymbols = extensionMethodSymbols.SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceSymbols); } } } return ImmutableArray<SymbolReference>.Empty; } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethods( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols, SyntaxNode expression, CancellationToken cancellationToken) { return GetViableExtensionMethodsWorker(methodSymbols).WhereAsArray( s => _owner.IsViableExtensionMethod(s.Symbol, expression, _semanticModel, _syntaxFacts, cancellationToken)); } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethods( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols, ITypeSymbol typeSymbol) { return GetViableExtensionMethodsWorker(methodSymbols).WhereAsArray( s => IsViableExtensionMethod(s.Symbol, typeSymbol)); } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethodsWorker( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols) { return methodSymbols.WhereAsArray( s => s.Symbol.IsExtensionMethod && s.Symbol.IsAccessibleWithin(_semanticModel.Compilation.Assembly)); } /// <summary> /// Searches for extension methods exactly called 'Add'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForCollectionInitializerMethodsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out _) && !_syntaxFacts.IsSimpleName(_node) && _owner.IsAddMethodContext(_node, _semanticModel)) { var symbols = await searchScope.FindDeclarationsAsync( nameof(IList.Add), nameNode: null, filter: SymbolFilter.Member).ConfigureAwait(false); // Note: there is no desiredName for these search results. We're searching for // extension methods called "Add", but we have no intention of renaming any // of the existing user code to that name. var methodSymbols = OfType<IMethodSymbol>(symbols).SelectAsArray(s => s.WithDesiredName(null)); var viableMethods = GetViableExtensionMethods( methodSymbols, _node.Parent, searchScope.CancellationToken); return GetNamespaceSymbolReferences(searchScope, viableMethods.SelectAsArray(m => m.WithSymbol(m.Symbol.ContainingNamespace))); } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'Select'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForQueryPatternsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForQuery(_diagnosticId, _node)) { var type = _owner.GetQueryClauseInfo(_semanticModel, _node, searchScope.CancellationToken); if (type != null) { // find extension methods named "Select" return await GetReferencesForExtensionMethodAsync( searchScope, nameof(Enumerable.Select), type).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetAwaiter'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetAwaiterAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetAwaiter(_diagnosticId, _syntaxFacts, _node)) { var type = GetAwaitInfo(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetAwaiter, type, m => m.IsValidGetAwaiter()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetEnumerator'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetEnumeratorAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetEnumerator(_diagnosticId, _syntaxFacts, _node)) { var type = GetCollectionExpressionType(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetEnumeratorMethodName, type, m => m.IsValidGetEnumerator()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetAsyncEnumerator'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetAsyncEnumeratorAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetAsyncEnumerator(_diagnosticId, _syntaxFacts, _node)) { var type = GetCollectionExpressionType(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetAsyncEnumeratorMethodName, type, m => m.IsValidGetAsyncEnumerator()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'Deconstruct'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForDeconstructAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForDeconstruct(_diagnosticId, _node)) { var type = _owner.GetDeconstructInfo(_semanticModel, _node, searchScope.CancellationToken); if (type != null) { // Note: we could check that the extension methods have the right number of out-params. // But that would involve figuring out what we're trying to deconstruct into. For now // we'll just be permissive, with the assumption that there won't be that many matching // 'Deconstruct' extension methods for the type of node that we're on. return await GetReferencesForExtensionMethodAsync( searchScope, "Deconstruct", type, m => m.ReturnsVoid).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } private async Task<ImmutableArray<SymbolReference>> GetReferencesForExtensionMethodAsync( SearchScope searchScope, string name, ITypeSymbol type, Func<IMethodSymbol, bool> predicate = null) { var symbols = await searchScope.FindDeclarationsAsync( name, nameNode: null, filter: SymbolFilter.Member).ConfigureAwait(false); // Note: there is no "desiredName" when doing this. We're not going to do any // renames of the user code. We're just looking for an extension method called // "Select", but that name has no bearing on the code in question that we're // trying to fix up. var methodSymbols = OfType<IMethodSymbol>(symbols).SelectAsArray(s => s.WithDesiredName(null)); var viableExtensionMethods = GetViableExtensionMethods(methodSymbols, type); if (predicate != null) { viableExtensionMethods = viableExtensionMethods.WhereAsArray(s => predicate(s.Symbol)); } var namespaceSymbols = viableExtensionMethods.SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceSymbols); } protected bool ExpressionBinds( TSimpleNameSyntax nameNode, bool checkForExtensionMethods, CancellationToken cancellationToken) { // See if the name binds to something other then the error type. If it does, there's nothing further we need to do. // For extension methods, however, we will continue to search if there exists any better matched method. cancellationToken.ThrowIfCancellationRequested(); var symbolInfo = _semanticModel.GetSymbolInfo(nameNode, cancellationToken); if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure && !checkForExtensionMethods) { return true; } return symbolInfo.Symbol != null; } private ImmutableArray<SymbolReference> GetNamespaceSymbolReferences( SearchScope scope, ImmutableArray<SymbolResult<INamespaceSymbol>> namespaces) { using var _ = ArrayBuilder<SymbolReference>.GetInstance(out var references); foreach (var namespaceResult in namespaces) { var symbol = namespaceResult.Symbol; var mappedResult = namespaceResult.WithSymbol(MapToCompilationNamespaceIfPossible(namespaceResult.Symbol)); var namespaceIsInScope = _namespacesInScope.Contains(mappedResult.Symbol); if (!symbol.IsGlobalNamespace && !namespaceIsInScope) references.Add(scope.CreateReference(mappedResult)); } return references.ToImmutable(); } private static ImmutableArray<SymbolResult<T>> OfType<T>(ImmutableArray<SymbolResult<ISymbol>> symbols) where T : ISymbol { return symbols.WhereAsArray(s => s.Symbol is T) .SelectAsArray(s => s.WithSymbol((T)s.Symbol)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolSearch; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Shared.Utilities.EditorBrowsableHelpers; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> { private partial class SymbolReferenceFinder { private const string AttributeSuffix = nameof(Attribute); private readonly string _diagnosticId; private readonly Document _document; private readonly SemanticModel _semanticModel; private readonly ISet<INamespaceSymbol> _namespacesInScope; private readonly ISyntaxFactsService _syntaxFacts; private readonly AbstractAddImportFeatureService<TSimpleNameSyntax> _owner; private readonly SyntaxNode _node; private readonly ISymbolSearchService _symbolSearchService; private readonly bool _searchReferenceAssemblies; private readonly ImmutableArray<PackageSource> _packageSources; public SymbolReferenceFinder( AbstractAddImportFeatureService<TSimpleNameSyntax> owner, Document document, SemanticModel semanticModel, string diagnosticId, SyntaxNode node, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { _owner = owner; _document = document; _semanticModel = semanticModel; _diagnosticId = diagnosticId; _node = node; _symbolSearchService = symbolSearchService; _searchReferenceAssemblies = searchReferenceAssemblies; _packageSources = packageSources; if (_searchReferenceAssemblies || packageSources.Length > 0) { Contract.ThrowIfNull(symbolSearchService); } _syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); _namespacesInScope = GetNamespacesInScope(cancellationToken); } private ISet<INamespaceSymbol> GetNamespacesInScope(CancellationToken cancellationToken) { // Add all the namespaces brought in by imports/usings. var set = _owner.GetImportNamespacesInScope(_semanticModel, _node, cancellationToken); // Also add all the namespaces we're contained in. We don't want // to add imports for these namespaces either. for (var containingNamespace = _semanticModel.GetEnclosingNamespace(_node.SpanStart, cancellationToken); containingNamespace != null; containingNamespace = containingNamespace.ContainingNamespace) { set.Add(MapToCompilationNamespaceIfPossible(containingNamespace)); } return set; } private INamespaceSymbol MapToCompilationNamespaceIfPossible(INamespaceSymbol containingNamespace) => _semanticModel.Compilation.GetCompilationNamespace(containingNamespace) ?? containingNamespace; internal Task<ImmutableArray<SymbolReference>> FindInAllSymbolsInStartingProjectAsync( bool exact, CancellationToken cancellationToken) { var searchScope = new AllSymbolsProjectSearchScope( _owner, _document.Project, exact, cancellationToken); return DoAsync(searchScope); } internal Task<ImmutableArray<SymbolReference>> FindInSourceSymbolsInProjectAsync( ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>> projectToAssembly, Project project, bool exact, CancellationToken cancellationToken) { var searchScope = new SourceSymbolsProjectSearchScope( _owner, projectToAssembly, project, exact, cancellationToken); return DoAsync(searchScope); } internal Task<ImmutableArray<SymbolReference>> FindInMetadataSymbolsAsync( IAssemblySymbol assembly, ProjectId assemblyProjectId, PortableExecutableReference metadataReference, bool exact, CancellationToken cancellationToken) { var searchScope = new MetadataSymbolsSearchScope( _owner, _document.Project.Solution, assembly, assemblyProjectId, metadataReference, exact, cancellationToken); return DoAsync(searchScope); } private async Task<ImmutableArray<SymbolReference>> DoAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); // Spin off tasks to do all our searching in parallel using var _1 = ArrayBuilder<Task<ImmutableArray<SymbolReference>>>.GetInstance(out var tasks); tasks.Add(GetReferencesForMatchingTypesAsync(searchScope)); tasks.Add(GetReferencesForMatchingNamespacesAsync(searchScope)); tasks.Add(GetReferencesForMatchingFieldsAndPropertiesAsync(searchScope)); tasks.Add(GetReferencesForMatchingExtensionMethodsAsync(searchScope)); // Searching for things like "Add" (for collection initializers) and "Select" // (for extension methods) should only be done when doing an 'exact' search. // We should not do fuzzy searches for these names. In this case it's not // like the user was writing Add or Select, but instead we're looking for // viable symbols with those names to make a collection initializer or // query expression valid. if (searchScope.Exact) { tasks.Add(GetReferencesForCollectionInitializerMethodsAsync(searchScope)); tasks.Add(GetReferencesForQueryPatternsAsync(searchScope)); tasks.Add(GetReferencesForDeconstructAsync(searchScope)); tasks.Add(GetReferencesForGetAwaiterAsync(searchScope)); tasks.Add(GetReferencesForGetEnumeratorAsync(searchScope)); tasks.Add(GetReferencesForGetAsyncEnumeratorAsync(searchScope)); } await Task.WhenAll(tasks).ConfigureAwait(false); searchScope.CancellationToken.ThrowIfCancellationRequested(); using var _2 = ArrayBuilder<SymbolReference>.GetInstance(out var allReferences); foreach (var task in tasks) { var taskResult = await task.ConfigureAwait(false); allReferences.AddRange(taskResult); } return DeDupeAndSortReferences(allReferences.ToImmutable()); } private ImmutableArray<SymbolReference> DeDupeAndSortReferences(ImmutableArray<SymbolReference> allReferences) { return allReferences .Distinct() .Where(NotNull) .Where(NotGlobalNamespace) .OrderBy((r1, r2) => r1.CompareTo(_document, r2)) .ToImmutableArray(); } private static void CalculateContext( TSimpleNameSyntax nameNode, ISyntaxFactsService syntaxFacts, out string name, out int arity, out bool inAttributeContext, out bool hasIncompleteParentMember, out bool looksGeneric) { // Has to be a simple identifier or generic name. syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out name, out arity); inAttributeContext = syntaxFacts.IsAttributeName(nameNode); hasIncompleteParentMember = syntaxFacts.HasIncompleteParentMember(nameNode); looksGeneric = syntaxFacts.LooksGeneric(nameNode); } /// <summary> /// Searches for types that match the name the user has written. Returns <see cref="SymbolReference"/>s /// to the <see cref="INamespaceSymbol"/>s or <see cref="INamedTypeSymbol"/>s those types are /// contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingTypesAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (!_owner.CanAddImportForType(_diagnosticId, _node, out var nameNode)) { return ImmutableArray<SymbolReference>.Empty; } CalculateContext( nameNode, _syntaxFacts, out var name, out var arity, out var inAttributeContext, out var hasIncompleteParentMember, out var looksGeneric); if (ExpressionBinds(nameNode, checkForExtensionMethods: false, cancellationToken: searchScope.CancellationToken)) { // If the expression bound, there's nothing to do. return ImmutableArray<SymbolReference>.Empty; } var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Type).ConfigureAwait(false); // also lookup type symbols with the "Attribute" suffix if necessary. if (inAttributeContext) { var attributeSymbols = await searchScope.FindDeclarationsAsync(name + AttributeSuffix, nameNode, SymbolFilter.Type).ConfigureAwait(false); symbols = symbols.AddRange( attributeSymbols.Select(r => r.WithDesiredName(r.DesiredName.GetWithoutAttributeSuffix(isCaseSensitive: false)))); } var typeSymbols = OfType<ITypeSymbol>(symbols); var options = await _document.GetOptionsAsync(searchScope.CancellationToken).ConfigureAwait(false); var hideAdvancedMembers = options.GetOption(CompletionOptions.HideAdvancedMembers); var editorBrowserInfo = new EditorBrowsableInfo(_semanticModel.Compilation); // Only keep symbols which are accessible from the current location and that are allowed by the current // editor browsable rules. var accessibleTypeSymbols = typeSymbols.WhereAsArray( s => ArityAccessibilityAndAttributeContextAreCorrect(s.Symbol, arity, inAttributeContext, hasIncompleteParentMember, looksGeneric) && s.Symbol.IsEditorBrowsable(hideAdvancedMembers, _semanticModel.Compilation, editorBrowserInfo)); // These types may be contained within namespaces, or they may be nested // inside generic types. Record these namespaces/types if it would be // legal to add imports for them. var typesContainedDirectlyInNamespaces = accessibleTypeSymbols.WhereAsArray(s => s.Symbol.ContainingSymbol is INamespaceSymbol); var typesContainedDirectlyInTypes = accessibleTypeSymbols.WhereAsArray(s => s.Symbol.ContainingType != null); var namespaceReferences = GetNamespaceSymbolReferences(searchScope, typesContainedDirectlyInNamespaces.SelectAsArray(r => r.WithSymbol(r.Symbol.ContainingNamespace))); var typeReferences = typesContainedDirectlyInTypes.SelectAsArray( r => searchScope.CreateReference(r.WithSymbol(r.Symbol.ContainingType))); return namespaceReferences.Concat(typeReferences); } private bool ArityAccessibilityAndAttributeContextAreCorrect( ITypeSymbol symbol, int arity, bool inAttributeContext, bool hasIncompleteParentMember, bool looksGeneric) { if (inAttributeContext && !symbol.IsAttribute()) { return false; } if (!symbol.IsAccessibleWithin(_semanticModel.Compilation.Assembly)) { return false; } if (looksGeneric && symbol.GetTypeArguments().Length == 0) { return false; } return arity == 0 || symbol.GetArity() == arity || hasIncompleteParentMember; } /// <summary> /// Searches for namespaces that match the name the user has written. Returns <see cref="SymbolReference"/>s /// to the <see cref="INamespaceSymbol"/>s those namespaces are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingNamespacesAsync( SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForNamespace(_diagnosticId, _node, out var nameNode)) { _syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out var name, out var arity); if (arity == 0 && !ExpressionBinds(nameNode, checkForExtensionMethods: false, cancellationToken: searchScope.CancellationToken)) { var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Namespace).ConfigureAwait(false); var namespaceSymbols = OfType<INamespaceSymbol>(symbols); var containingNamespaceSymbols = OfType<INamespaceSymbol>(symbols).SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, containingNamespaceSymbols); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Specialized finder for the "Color Color" case. Used when we have "Color.Black" and "Color" /// bound to a Field/Property, but not a type. In this case, we want to look for namespaces /// containing 'Color' as if we import them it can resolve this issue. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingFieldsAndPropertiesAsync( SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out var nameNode) && nameNode != null) { // We have code like "Color.Black". "Color" bound to a 'Color Color' property, and // 'Black' did not bind. We want to find a type called 'Color' that will actually // allow 'Black' to bind. var syntaxFacts = _document.GetLanguageService<ISyntaxFactsService>(); if (syntaxFacts.IsNameOfSimpleMemberAccessExpression(nameNode) || syntaxFacts.IsNameOfMemberBindingExpression(nameNode)) { var expression = syntaxFacts.IsNameOfSimpleMemberAccessExpression(nameNode) ? syntaxFacts.GetExpressionOfMemberAccessExpression(nameNode.Parent, allowImplicitTarget: true) : syntaxFacts.GetTargetOfMemberBinding(nameNode.Parent); if (expression is TSimpleNameSyntax simpleName) { // Check if the expression before the dot binds to a property or field. var symbol = _semanticModel.GetSymbolInfo(expression, searchScope.CancellationToken).GetAnySymbol(); if (symbol?.Kind is SymbolKind.Property or SymbolKind.Field) { // Check if we have the 'Color Color' case. var propertyOrFieldType = symbol.GetSymbolType(); if (propertyOrFieldType is INamedTypeSymbol propertyType && Equals(propertyType.Name, symbol.Name)) { // Try to look up 'Color' as a type. var symbolResults = await searchScope.FindDeclarationsAsync( symbol.Name, simpleName, SymbolFilter.Type).ConfigureAwait(false); // Return results that have accessible members. var namedTypeSymbols = OfType<INamedTypeSymbol>(symbolResults); var name = nameNode.GetFirstToken().ValueText; var namespaceResults = namedTypeSymbols.WhereAsArray(sr => HasAccessibleStaticFieldOrProperty(sr.Symbol, name)) .SelectAsArray(sr => sr.WithSymbol(sr.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceResults); } } } } } return ImmutableArray<SymbolReference>.Empty; } private bool HasAccessibleStaticFieldOrProperty(INamedTypeSymbol namedType, string fieldOrPropertyName) { return namedType.GetMembers(fieldOrPropertyName) .Any(m => (m is IFieldSymbol || m is IPropertySymbol) && m.IsStatic && m.IsAccessibleWithin(_semanticModel.Compilation.Assembly)); } /// <summary> /// Searches for extension methods that match the name the user has written. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingExtensionMethodsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out var nameNode) && nameNode != null) { searchScope.CancellationToken.ThrowIfCancellationRequested(); // See if the name binds. If it does, there's nothing further we need to do. if (!ExpressionBinds(nameNode, checkForExtensionMethods: true, cancellationToken: searchScope.CancellationToken)) { _syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out var name, out var arity); if (name != null) { var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Member).ConfigureAwait(false); var methodSymbols = OfType<IMethodSymbol>(symbols); var extensionMethodSymbols = GetViableExtensionMethods( methodSymbols, nameNode.Parent, searchScope.CancellationToken); var namespaceSymbols = extensionMethodSymbols.SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceSymbols); } } } return ImmutableArray<SymbolReference>.Empty; } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethods( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols, SyntaxNode expression, CancellationToken cancellationToken) { return GetViableExtensionMethodsWorker(methodSymbols).WhereAsArray( s => _owner.IsViableExtensionMethod(s.Symbol, expression, _semanticModel, _syntaxFacts, cancellationToken)); } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethods( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols, ITypeSymbol typeSymbol) { return GetViableExtensionMethodsWorker(methodSymbols).WhereAsArray( s => IsViableExtensionMethod(s.Symbol, typeSymbol)); } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethodsWorker( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols) { return methodSymbols.WhereAsArray( s => s.Symbol.IsExtensionMethod && s.Symbol.IsAccessibleWithin(_semanticModel.Compilation.Assembly)); } /// <summary> /// Searches for extension methods exactly called 'Add'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForCollectionInitializerMethodsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out _) && !_syntaxFacts.IsSimpleName(_node) && _owner.IsAddMethodContext(_node, _semanticModel)) { var symbols = await searchScope.FindDeclarationsAsync( nameof(IList.Add), nameNode: null, filter: SymbolFilter.Member).ConfigureAwait(false); // Note: there is no desiredName for these search results. We're searching for // extension methods called "Add", but we have no intention of renaming any // of the existing user code to that name. var methodSymbols = OfType<IMethodSymbol>(symbols).SelectAsArray(s => s.WithDesiredName(null)); var viableMethods = GetViableExtensionMethods( methodSymbols, _node.Parent, searchScope.CancellationToken); return GetNamespaceSymbolReferences(searchScope, viableMethods.SelectAsArray(m => m.WithSymbol(m.Symbol.ContainingNamespace))); } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'Select'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForQueryPatternsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForQuery(_diagnosticId, _node)) { var type = _owner.GetQueryClauseInfo(_semanticModel, _node, searchScope.CancellationToken); if (type != null) { // find extension methods named "Select" return await GetReferencesForExtensionMethodAsync( searchScope, nameof(Enumerable.Select), type).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetAwaiter'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetAwaiterAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetAwaiter(_diagnosticId, _syntaxFacts, _node)) { var type = GetAwaitInfo(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetAwaiter, type, m => m.IsValidGetAwaiter()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetEnumerator'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetEnumeratorAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetEnumerator(_diagnosticId, _syntaxFacts, _node)) { var type = GetCollectionExpressionType(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetEnumeratorMethodName, type, m => m.IsValidGetEnumerator()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetAsyncEnumerator'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetAsyncEnumeratorAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetAsyncEnumerator(_diagnosticId, _syntaxFacts, _node)) { var type = GetCollectionExpressionType(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetAsyncEnumeratorMethodName, type, m => m.IsValidGetAsyncEnumerator()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'Deconstruct'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForDeconstructAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForDeconstruct(_diagnosticId, _node)) { var type = _owner.GetDeconstructInfo(_semanticModel, _node, searchScope.CancellationToken); if (type != null) { // Note: we could check that the extension methods have the right number of out-params. // But that would involve figuring out what we're trying to deconstruct into. For now // we'll just be permissive, with the assumption that there won't be that many matching // 'Deconstruct' extension methods for the type of node that we're on. return await GetReferencesForExtensionMethodAsync( searchScope, "Deconstruct", type, m => m.ReturnsVoid).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } private async Task<ImmutableArray<SymbolReference>> GetReferencesForExtensionMethodAsync( SearchScope searchScope, string name, ITypeSymbol type, Func<IMethodSymbol, bool> predicate = null) { var symbols = await searchScope.FindDeclarationsAsync( name, nameNode: null, filter: SymbolFilter.Member).ConfigureAwait(false); // Note: there is no "desiredName" when doing this. We're not going to do any // renames of the user code. We're just looking for an extension method called // "Select", but that name has no bearing on the code in question that we're // trying to fix up. var methodSymbols = OfType<IMethodSymbol>(symbols).SelectAsArray(s => s.WithDesiredName(null)); var viableExtensionMethods = GetViableExtensionMethods(methodSymbols, type); if (predicate != null) { viableExtensionMethods = viableExtensionMethods.WhereAsArray(s => predicate(s.Symbol)); } var namespaceSymbols = viableExtensionMethods.SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceSymbols); } protected bool ExpressionBinds( TSimpleNameSyntax nameNode, bool checkForExtensionMethods, CancellationToken cancellationToken) { // See if the name binds to something other then the error type. If it does, there's nothing further we need to do. // For extension methods, however, we will continue to search if there exists any better matched method. cancellationToken.ThrowIfCancellationRequested(); var symbolInfo = _semanticModel.GetSymbolInfo(nameNode, cancellationToken); if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure && !checkForExtensionMethods) { return true; } return symbolInfo.Symbol != null; } private ImmutableArray<SymbolReference> GetNamespaceSymbolReferences( SearchScope scope, ImmutableArray<SymbolResult<INamespaceSymbol>> namespaces) { using var _ = ArrayBuilder<SymbolReference>.GetInstance(out var references); foreach (var namespaceResult in namespaces) { var symbol = namespaceResult.Symbol; var mappedResult = namespaceResult.WithSymbol(MapToCompilationNamespaceIfPossible(namespaceResult.Symbol)); var namespaceIsInScope = _namespacesInScope.Contains(mappedResult.Symbol); if (!symbol.IsGlobalNamespace && !namespaceIsInScope) references.Add(scope.CreateReference(mappedResult)); } return references.ToImmutable(); } private static ImmutableArray<SymbolResult<T>> OfType<T>(ImmutableArray<SymbolResult<ISymbol>> symbols) where T : ISymbol { return symbols.WhereAsArray(s => s.Symbol is T) .SelectAsArray(s => s.WithSymbol((T)s.Symbol)); } } } }
1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Features/Core/Portable/ConvertToInterpolatedString/AbstractConvertPlaceholderToInterpolatedStringRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ConvertToInterpolatedString { internal abstract class AbstractConvertPlaceholderToInterpolatedStringRefactoringProvider<TInvocationExpressionSyntax, TExpressionSyntax, TArgumentSyntax, TLiteralExpressionSyntax, TArgumentListExpressionSyntax> : CodeRefactoringProvider where TExpressionSyntax : SyntaxNode where TInvocationExpressionSyntax : TExpressionSyntax where TArgumentSyntax : SyntaxNode where TLiteralExpressionSyntax : SyntaxNode where TArgumentListExpressionSyntax : SyntaxNode { // Methods that are not string.Format but still should qualify to be replaced. // Ex: Console.WriteLine("{0}", a) => Console.WriteLine($"{a}"); private static readonly (string typeName, string[] methods)[] CompositeFormattedMethods = new (string, string[])[] { (typeof(Console).FullName!, new[] { nameof(Console.Write), nameof(Console.WriteLine) }), (typeof(Debug).FullName!, new[] { nameof(Debug.WriteLine), nameof(Debug.Print)}), (typeof(Trace).FullName!, new[] { nameof(Trace.TraceError), nameof(Trace.TraceWarning), nameof(Trace.TraceInformation)}), (typeof(TraceSource).FullName!, new[] { nameof(TraceSource.TraceInformation)}) }; protected abstract SyntaxNode GetInterpolatedString(string text); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var stringType = semanticModel.Compilation.GetSpecialType(SpecialType.System_String); if (stringType.IsErrorType()) { return; } var stringInvocationMethods = CollectMethods(stringType, nameof(string.Format)); var compositeFormattedInvocationMethods = CompositeFormattedMethods .SelectMany(pair => CollectMethods(semanticModel.Compilation.GetTypeByMetadataName(pair.typeName), pair.methods)) .ToImmutableArray(); var allInvocationMethods = stringInvocationMethods.AddRange(compositeFormattedInvocationMethods); if (allInvocationMethods.Length == 0) { return; } var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>(); if (syntaxFactsService == null) { return; } var (invocationSyntax, invocationSymbol) = await TryFindInvocationAsync(textSpan, document, semanticModel, allInvocationMethods, syntaxFactsService, context.CancellationToken).ConfigureAwait(false); if (invocationSyntax is null || invocationSymbol is null) { return; } if (!IsArgumentListCorrect(syntaxFactsService.GetArgumentsOfInvocationExpression(invocationSyntax), invocationSymbol, allInvocationMethods, semanticModel, syntaxFactsService, cancellationToken)) { return; } var shouldReplaceInvocation = stringInvocationMethods.Contains(invocationSymbol); context.RegisterRefactoring( new ConvertToInterpolatedStringCodeAction( c => CreateInterpolatedStringAsync(invocationSyntax, document, syntaxFactsService, shouldReplaceInvocation, c)), invocationSyntax.Span); // Local Functions static ImmutableArray<IMethodSymbol> CollectMethods(INamedTypeSymbol? typeSymbol, params string[] methodNames) { if (typeSymbol is null) { return ImmutableArray<IMethodSymbol>.Empty; } return typeSymbol .GetMembers() .OfType<IMethodSymbol>() .Where(m => methodNames.Contains(m.Name)) .Where(ShouldIncludeFormatMethod) .ToImmutableArray(); } } private async Task<(TInvocationExpressionSyntax?, ISymbol?)> TryFindInvocationAsync( TextSpan span, Document document, SemanticModel semanticModel, ImmutableArray<IMethodSymbol> applicableMethods, ISyntaxFactsService syntaxFactsService, CancellationToken cancellationToken) { // If selection is empty there can be multiple matching invocations (we can be deep in), need to go through all of them var possibleInvocations = await document.GetRelevantNodesAsync<TInvocationExpressionSyntax>(span, cancellationToken).ConfigureAwait(false); var invocation = possibleInvocations.FirstOrDefault(invocation => IsValidPlaceholderToInterpolatedString(invocation, syntaxFactsService, semanticModel, applicableMethods, this, cancellationToken)); // User selected the whole invocation of format. if (invocation != null) { return (invocation, semanticModel.GetSymbolInfo(invocation, cancellationToken).Symbol); } // User selected a single argument of the invocation (expression / format string) instead of the whole invocation. var argument = await document.TryGetRelevantNodeAsync<TArgumentSyntax>(span, cancellationToken).ConfigureAwait(false); invocation = argument?.Parent?.Parent as TInvocationExpressionSyntax; if (invocation != null && IsValidPlaceholderToInterpolatedString(invocation, syntaxFactsService, semanticModel, applicableMethods, this, cancellationToken)) { return (invocation, semanticModel.GetSymbolInfo(invocation, cancellationToken).Symbol); } // User selected the whole argument list: string format with placeholders plus all expressions var argumentList = await document.TryGetRelevantNodeAsync<TArgumentListExpressionSyntax>(span, cancellationToken).ConfigureAwait(false); invocation = argumentList?.Parent as TInvocationExpressionSyntax; if (invocation != null && IsValidPlaceholderToInterpolatedString(invocation, syntaxFactsService, semanticModel, applicableMethods, this, cancellationToken)) { return (invocation, semanticModel.GetSymbolInfo(invocation, cancellationToken).Symbol); } return (null, null); static bool IsValidPlaceholderToInterpolatedString(TInvocationExpressionSyntax invocation, ISyntaxFactsService syntaxFactsService, SemanticModel semanticModel, ImmutableArray<IMethodSymbol> applicableMethods, AbstractConvertPlaceholderToInterpolatedStringRefactoringProvider< TInvocationExpressionSyntax, TExpressionSyntax, TArgumentSyntax, TLiteralExpressionSyntax, TArgumentListExpressionSyntax> thisInstance, CancellationToken cancellationToken) { var arguments = syntaxFactsService.GetArgumentsOfInvocationExpression(invocation); if (arguments.Count >= 2) { if (syntaxFactsService.GetExpressionOfArgument(GetFormatArgument(arguments, syntaxFactsService)) is TLiteralExpressionSyntax firstArgumentExpression && syntaxFactsService.IsStringLiteral(firstArgumentExpression.GetFirstToken())) { var invocationSymbol = semanticModel.GetSymbolInfo(invocation, cancellationToken).Symbol; if (applicableMethods.Contains(invocationSymbol)) { return true; } } } return false; } } private static bool IsArgumentListCorrect( SeparatedSyntaxList<TArgumentSyntax> arguments, ISymbol invocationSymbol, ImmutableArray<IMethodSymbol> formatMethods, SemanticModel semanticModel, ISyntaxFactsService syntaxFactsService, CancellationToken cancellationToken) { if (arguments.Count >= 2 && syntaxFactsService.GetExpressionOfArgument(GetFormatArgument(arguments, syntaxFactsService)) is TLiteralExpressionSyntax firstExpression && syntaxFactsService.IsStringLiteral(firstExpression.GetFirstToken())) { // We do not want to substitute the expression if it is being passed to params array argument // Example: // string[] args; // String.Format("{0}{1}{2}", args); return IsArgumentListNotPassingArrayToParams( syntaxFactsService.GetExpressionOfArgument(GetParamsArgument(arguments, syntaxFactsService)), invocationSymbol, formatMethods, semanticModel, cancellationToken); } return false; } private async Task<Document> CreateInterpolatedStringAsync( TInvocationExpressionSyntax invocation, Document document, ISyntaxFactsService syntaxFactsService, bool shouldReplaceInvocation, CancellationToken cancellationToken) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var arguments = syntaxFactsService.GetArgumentsOfInvocationExpression(invocation); var literalExpression = (TLiteralExpressionSyntax?)syntaxFactsService.GetExpressionOfArgument(GetFormatArgument(arguments, syntaxFactsService)); Contract.ThrowIfNull(literalExpression); var text = literalExpression.GetFirstToken().ToString(); var syntaxGenerator = document.GetRequiredLanguageService<SyntaxGenerator>(); var expandedArguments = GetExpandedArguments(semanticModel, arguments, syntaxGenerator, syntaxFactsService); var interpolatedString = GetInterpolatedString(text); var newInterpolatedString = VisitArguments(expandedArguments, interpolatedString, syntaxFactsService); SyntaxNode? replacementNode; if (shouldReplaceInvocation) { replacementNode = newInterpolatedString; } else { replacementNode = syntaxGenerator.InvocationExpression( syntaxFactsService.GetExpressionOfInvocationExpression(invocation), newInterpolatedString); } var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = root.ReplaceNode(invocation, replacementNode.WithTriviaFrom(invocation)); return document.WithSyntaxRoot(newRoot); } private static string GetArgumentName(TArgumentSyntax argument, ISyntaxFacts syntaxFacts) => syntaxFacts.GetNameForArgument(argument); private static SyntaxNode GetParamsArgument(SeparatedSyntaxList<TArgumentSyntax> arguments, ISyntaxFactsService syntaxFactsService) => arguments.FirstOrDefault(argument => string.Equals(GetArgumentName(argument, syntaxFactsService), StringFormatArguments.FormatArgumentName, StringComparison.OrdinalIgnoreCase)) ?? arguments[1]; private static TArgumentSyntax GetFormatArgument(SeparatedSyntaxList<TArgumentSyntax> arguments, ISyntaxFactsService syntaxFactsService) => arguments.FirstOrDefault(argument => string.Equals(GetArgumentName(argument, syntaxFactsService), StringFormatArguments.FormatArgumentName, StringComparison.OrdinalIgnoreCase)) ?? arguments[0]; private static TArgumentSyntax GetArgument(SeparatedSyntaxList<TArgumentSyntax> arguments, int index, ISyntaxFacts syntaxFacts) { if (arguments.Count > 4) { return arguments[index]; } return arguments.FirstOrDefault( argument => string.Equals(GetArgumentName(argument, syntaxFacts), StringFormatArguments.ParamsArgumentNames[index], StringComparison.OrdinalIgnoreCase)) ?? arguments[index]; } private static ImmutableArray<TExpressionSyntax> GetExpandedArguments( SemanticModel semanticModel, SeparatedSyntaxList<TArgumentSyntax> arguments, SyntaxGenerator syntaxGenerator, ISyntaxFacts syntaxFacts) { using var _ = ArrayBuilder<TExpressionSyntax>.GetInstance(out var builder); for (var i = 1; i < arguments.Count; i++) { var argumentExpression = syntaxFacts.GetExpressionOfArgument(GetArgument(arguments, i, syntaxFacts)); var convertedType = argumentExpression == null ? null : semanticModel.GetTypeInfo(argumentExpression).ConvertedType; if (convertedType == null) { builder.Add((TExpressionSyntax)syntaxGenerator.AddParentheses(argumentExpression)); } else { var castExpression = (TExpressionSyntax)syntaxGenerator.CastExpression(convertedType, syntaxGenerator.AddParentheses(argumentExpression)).WithAdditionalAnnotations(Simplifier.Annotation); builder.Add(castExpression); } } return builder.ToImmutable(); } private static SyntaxNode VisitArguments( ImmutableArray<TExpressionSyntax> expandedArguments, SyntaxNode interpolatedString, ISyntaxFactsService syntaxFactsService) { return interpolatedString.ReplaceNodes(syntaxFactsService.GetContentsOfInterpolatedString(interpolatedString), (oldNode, newNode) => { var interpolationSyntaxNode = newNode; if (interpolationSyntaxNode != null) { if (syntaxFactsService.GetExpressionOfInterpolation(interpolationSyntaxNode) is TLiteralExpressionSyntax literalExpression && syntaxFactsService.IsNumericLiteralExpression(literalExpression)) { if (int.TryParse(literalExpression.GetFirstToken().ValueText, out var index)) { if (index >= 0 && index < expandedArguments.Length) { return interpolationSyntaxNode.ReplaceNode( literalExpression, syntaxFactsService.ConvertToSingleLine(expandedArguments[index], useElasticTrivia: true).WithAdditionalAnnotations(Formatter.Annotation)); } } } } return newNode; }); } private static bool ShouldIncludeFormatMethod(IMethodSymbol methodSymbol) { if (!methodSymbol.IsStatic) { return false; } if (methodSymbol.Parameters.Length == 0) { return false; } var firstParameter = methodSymbol.Parameters[0]; if (firstParameter?.Name != StringFormatArguments.FormatArgumentName) { return false; } return true; } private static bool IsArgumentListNotPassingArrayToParams( SyntaxNode? expression, ISymbol invocationSymbol, ImmutableArray<IMethodSymbol> formatMethods, SemanticModel semanticModel, CancellationToken cancellationToken) { if (expression != null) { var formatMethodsAcceptingParamsArray = formatMethods .Where(x => x.Parameters.Length > 1 && x.Parameters[1].Type.Kind == SymbolKind.ArrayType); if (formatMethodsAcceptingParamsArray.Contains(invocationSymbol)) { return semanticModel.GetTypeInfo(expression, cancellationToken).Type?.Kind != SymbolKind.ArrayType; } } return true; } private class ConvertToInterpolatedStringCodeAction : CodeAction.DocumentChangeAction { public ConvertToInterpolatedStringCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(FeaturesResources.Convert_to_interpolated_string, createChangedDocument, nameof(FeaturesResources.Convert_to_interpolated_string)) { } } private static class StringFormatArguments { public const string FormatArgumentName = "format"; public const string ArgsArgumentName = "args"; public static readonly ImmutableArray<string> ParamsArgumentNames = ImmutableArray.Create("", "arg0", "arg1", "arg2"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ConvertToInterpolatedString { internal abstract class AbstractConvertPlaceholderToInterpolatedStringRefactoringProvider< TInvocationExpressionSyntax, TExpressionSyntax, TArgumentSyntax, TLiteralExpressionSyntax, TArgumentListExpressionSyntax, TInterpolationSyntax> : CodeRefactoringProvider where TExpressionSyntax : SyntaxNode where TInvocationExpressionSyntax : TExpressionSyntax where TArgumentSyntax : SyntaxNode where TLiteralExpressionSyntax : SyntaxNode where TArgumentListExpressionSyntax : SyntaxNode where TInterpolationSyntax : SyntaxNode { // Methods that are not string.Format but still should qualify to be replaced. // Ex: Console.WriteLine("{0}", a) => Console.WriteLine($"{a}"); private static readonly (string typeName, string[] methods)[] CompositeFormattedMethods = new (string, string[])[] { (typeof(Console).FullName!, new[] { nameof(Console.Write), nameof(Console.WriteLine) }), (typeof(Debug).FullName!, new[] { nameof(Debug.WriteLine), nameof(Debug.Print)}), (typeof(Trace).FullName!, new[] { nameof(Trace.TraceError), nameof(Trace.TraceWarning), nameof(Trace.TraceInformation)}), (typeof(TraceSource).FullName!, new[] { nameof(TraceSource.TraceInformation)}) }; protected abstract SyntaxNode GetInterpolatedString(string text); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var stringType = semanticModel.Compilation.GetSpecialType(SpecialType.System_String); if (stringType.IsErrorType()) { return; } var stringInvocationMethods = CollectMethods(stringType, nameof(string.Format)); var compositeFormattedInvocationMethods = CompositeFormattedMethods .SelectMany(pair => CollectMethods(semanticModel.Compilation.GetTypeByMetadataName(pair.typeName), pair.methods)) .ToImmutableArray(); var allInvocationMethods = stringInvocationMethods.AddRange(compositeFormattedInvocationMethods); if (allInvocationMethods.Length == 0) { return; } var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>(); if (syntaxFactsService == null) { return; } var (invocationSyntax, invocationSymbol) = await TryFindInvocationAsync(textSpan, document, semanticModel, allInvocationMethods, syntaxFactsService, context.CancellationToken).ConfigureAwait(false); if (invocationSyntax is null || invocationSymbol is null) { return; } if (!IsArgumentListCorrect(syntaxFactsService.GetArgumentsOfInvocationExpression(invocationSyntax), invocationSymbol, allInvocationMethods, semanticModel, syntaxFactsService, cancellationToken)) { return; } var shouldReplaceInvocation = stringInvocationMethods.Contains(invocationSymbol); context.RegisterRefactoring( new ConvertToInterpolatedStringCodeAction( c => CreateInterpolatedStringAsync(invocationSyntax, document, syntaxFactsService, shouldReplaceInvocation, c)), invocationSyntax.Span); // Local Functions static ImmutableArray<IMethodSymbol> CollectMethods(INamedTypeSymbol? typeSymbol, params string[] methodNames) { if (typeSymbol is null) { return ImmutableArray<IMethodSymbol>.Empty; } return typeSymbol .GetMembers() .OfType<IMethodSymbol>() .Where(m => methodNames.Contains(m.Name)) .Where(ShouldIncludeFormatMethod) .ToImmutableArray(); } } private async Task<(TInvocationExpressionSyntax?, ISymbol?)> TryFindInvocationAsync( TextSpan span, Document document, SemanticModel semanticModel, ImmutableArray<IMethodSymbol> applicableMethods, ISyntaxFactsService syntaxFactsService, CancellationToken cancellationToken) { // If selection is empty there can be multiple matching invocations (we can be deep in), need to go through all of them var possibleInvocations = await document.GetRelevantNodesAsync<TInvocationExpressionSyntax>(span, cancellationToken).ConfigureAwait(false); var invocation = possibleInvocations.FirstOrDefault(invocation => IsValidPlaceholderToInterpolatedString(invocation, syntaxFactsService, semanticModel, applicableMethods, this, cancellationToken)); // User selected the whole invocation of format. if (invocation != null) { return (invocation, semanticModel.GetSymbolInfo(invocation, cancellationToken).Symbol); } // User selected a single argument of the invocation (expression / format string) instead of the whole invocation. var argument = await document.TryGetRelevantNodeAsync<TArgumentSyntax>(span, cancellationToken).ConfigureAwait(false); invocation = argument?.Parent?.Parent as TInvocationExpressionSyntax; if (invocation != null && IsValidPlaceholderToInterpolatedString(invocation, syntaxFactsService, semanticModel, applicableMethods, this, cancellationToken)) { return (invocation, semanticModel.GetSymbolInfo(invocation, cancellationToken).Symbol); } // User selected the whole argument list: string format with placeholders plus all expressions var argumentList = await document.TryGetRelevantNodeAsync<TArgumentListExpressionSyntax>(span, cancellationToken).ConfigureAwait(false); invocation = argumentList?.Parent as TInvocationExpressionSyntax; if (invocation != null && IsValidPlaceholderToInterpolatedString(invocation, syntaxFactsService, semanticModel, applicableMethods, this, cancellationToken)) { return (invocation, semanticModel.GetSymbolInfo(invocation, cancellationToken).Symbol); } return (null, null); static bool IsValidPlaceholderToInterpolatedString( TInvocationExpressionSyntax invocation, ISyntaxFactsService syntaxFactsService, SemanticModel semanticModel, ImmutableArray<IMethodSymbol> applicableMethods, AbstractConvertPlaceholderToInterpolatedStringRefactoringProvider< TInvocationExpressionSyntax, TExpressionSyntax, TArgumentSyntax, TLiteralExpressionSyntax, TArgumentListExpressionSyntax, TInterpolationSyntax> thisInstance, CancellationToken cancellationToken) { var arguments = syntaxFactsService.GetArgumentsOfInvocationExpression(invocation); if (arguments.Count >= 2) { if (syntaxFactsService.GetExpressionOfArgument(GetFormatArgument(arguments, syntaxFactsService)) is TLiteralExpressionSyntax firstArgumentExpression && syntaxFactsService.IsStringLiteral(firstArgumentExpression.GetFirstToken())) { var invocationSymbol = semanticModel.GetSymbolInfo(invocation, cancellationToken).Symbol; if (applicableMethods.Contains(invocationSymbol)) { return true; } } } return false; } } private static bool IsArgumentListCorrect( SeparatedSyntaxList<TArgumentSyntax> arguments, ISymbol invocationSymbol, ImmutableArray<IMethodSymbol> formatMethods, SemanticModel semanticModel, ISyntaxFactsService syntaxFactsService, CancellationToken cancellationToken) { if (arguments.Count >= 2 && syntaxFactsService.GetExpressionOfArgument(GetFormatArgument(arguments, syntaxFactsService)) is TLiteralExpressionSyntax firstExpression && syntaxFactsService.IsStringLiteral(firstExpression.GetFirstToken())) { // We do not want to substitute the expression if it is being passed to params array argument // Example: // string[] args; // String.Format("{0}{1}{2}", args); return IsArgumentListNotPassingArrayToParams( syntaxFactsService.GetExpressionOfArgument(GetParamsArgument(arguments, syntaxFactsService)), invocationSymbol, formatMethods, semanticModel, cancellationToken); } return false; } private async Task<Document> CreateInterpolatedStringAsync( TInvocationExpressionSyntax invocation, Document document, ISyntaxFactsService syntaxFactsService, bool shouldReplaceInvocation, CancellationToken cancellationToken) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var arguments = syntaxFactsService.GetArgumentsOfInvocationExpression(invocation); var literalExpression = (TLiteralExpressionSyntax?)syntaxFactsService.GetExpressionOfArgument(GetFormatArgument(arguments, syntaxFactsService)); Contract.ThrowIfNull(literalExpression); var text = literalExpression.GetFirstToken().ToString(); var syntaxGenerator = document.GetRequiredLanguageService<SyntaxGenerator>(); var expandedArguments = GetExpandedArguments(semanticModel, arguments, syntaxGenerator, syntaxFactsService); var interpolatedString = GetInterpolatedString(text); var newInterpolatedString = VisitArguments(expandedArguments, interpolatedString, syntaxFactsService); SyntaxNode? replacementNode; if (shouldReplaceInvocation) { replacementNode = newInterpolatedString; } else { replacementNode = syntaxGenerator.InvocationExpression( syntaxFactsService.GetExpressionOfInvocationExpression(invocation), newInterpolatedString); } var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = root.ReplaceNode(invocation, replacementNode.WithTriviaFrom(invocation)); return document.WithSyntaxRoot(newRoot); } private static string GetArgumentName(TArgumentSyntax argument, ISyntaxFacts syntaxFacts) => syntaxFacts.GetNameForArgument(argument); private static SyntaxNode GetParamsArgument(SeparatedSyntaxList<TArgumentSyntax> arguments, ISyntaxFactsService syntaxFactsService) => arguments.FirstOrDefault(argument => string.Equals(GetArgumentName(argument, syntaxFactsService), StringFormatArguments.FormatArgumentName, StringComparison.OrdinalIgnoreCase)) ?? arguments[1]; private static TArgumentSyntax GetFormatArgument(SeparatedSyntaxList<TArgumentSyntax> arguments, ISyntaxFactsService syntaxFactsService) => arguments.FirstOrDefault(argument => string.Equals(GetArgumentName(argument, syntaxFactsService), StringFormatArguments.FormatArgumentName, StringComparison.OrdinalIgnoreCase)) ?? arguments[0]; private static TArgumentSyntax GetArgument(SeparatedSyntaxList<TArgumentSyntax> arguments, int index, ISyntaxFacts syntaxFacts) { if (arguments.Count > 4) { return arguments[index]; } return arguments.FirstOrDefault( argument => string.Equals(GetArgumentName(argument, syntaxFacts), StringFormatArguments.ParamsArgumentNames[index], StringComparison.OrdinalIgnoreCase)) ?? arguments[index]; } private static ImmutableArray<TExpressionSyntax> GetExpandedArguments( SemanticModel semanticModel, SeparatedSyntaxList<TArgumentSyntax> arguments, SyntaxGenerator syntaxGenerator, ISyntaxFacts syntaxFacts) { using var _ = ArrayBuilder<TExpressionSyntax>.GetInstance(out var builder); for (var i = 1; i < arguments.Count; i++) { var argumentExpression = syntaxFacts.GetExpressionOfArgument(GetArgument(arguments, i, syntaxFacts)); var convertedType = argumentExpression == null ? null : semanticModel.GetTypeInfo(argumentExpression).ConvertedType; if (convertedType == null) { builder.Add((TExpressionSyntax)syntaxGenerator.AddParentheses(argumentExpression)); } else { var castExpression = (TExpressionSyntax)syntaxGenerator.CastExpression(convertedType, syntaxGenerator.AddParentheses(argumentExpression)).WithAdditionalAnnotations(Simplifier.Annotation); builder.Add(castExpression); } } return builder.ToImmutable(); } private static SyntaxNode VisitArguments( ImmutableArray<TExpressionSyntax> expandedArguments, SyntaxNode interpolatedString, ISyntaxFactsService syntaxFactsService) { return interpolatedString.ReplaceNodes(syntaxFactsService.GetContentsOfInterpolatedString(interpolatedString), (oldNode, newNode) => { if (newNode is TInterpolationSyntax interpolation) { if (syntaxFactsService.GetExpressionOfInterpolation(interpolation) is TLiteralExpressionSyntax literalExpression && syntaxFactsService.IsNumericLiteralExpression(literalExpression)) { if (int.TryParse(literalExpression.GetFirstToken().ValueText, out var index)) { if (index >= 0 && index < expandedArguments.Length) { return interpolation.ReplaceNode( literalExpression, syntaxFactsService.ConvertToSingleLine(expandedArguments[index], useElasticTrivia: true).WithAdditionalAnnotations(Formatter.Annotation)); } } } } return newNode; }); } private static bool ShouldIncludeFormatMethod(IMethodSymbol methodSymbol) { if (!methodSymbol.IsStatic) { return false; } if (methodSymbol.Parameters.Length == 0) { return false; } var firstParameter = methodSymbol.Parameters[0]; if (firstParameter?.Name != StringFormatArguments.FormatArgumentName) { return false; } return true; } private static bool IsArgumentListNotPassingArrayToParams( SyntaxNode? expression, ISymbol invocationSymbol, ImmutableArray<IMethodSymbol> formatMethods, SemanticModel semanticModel, CancellationToken cancellationToken) { if (expression != null) { var formatMethodsAcceptingParamsArray = formatMethods .Where(x => x.Parameters.Length > 1 && x.Parameters[1].Type.Kind == SymbolKind.ArrayType); if (formatMethodsAcceptingParamsArray.Contains(invocationSymbol)) { return semanticModel.GetTypeInfo(expression, cancellationToken).Type?.Kind != SymbolKind.ArrayType; } } return true; } private class ConvertToInterpolatedStringCodeAction : CodeAction.DocumentChangeAction { public ConvertToInterpolatedStringCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(FeaturesResources.Convert_to_interpolated_string, createChangedDocument, nameof(FeaturesResources.Convert_to_interpolated_string)) { } } private static class StringFormatArguments { public const string FormatArgumentName = "format"; public const string ArgsArgumentName = "args"; public static readonly ImmutableArray<string> ParamsArgumentNames = ImmutableArray.Create("", "arg0", "arg1", "arg2"); } } }
1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Features/Core/Portable/EmbeddedLanguages/DateAndTime/LanguageServices/DateAndTimePatternDetector.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.DateAndTime.LanguageServices { /// <summary> /// Helper class to detect <see cref="System.DateTime"/> and <see cref="DateTimeOffset"/> format /// strings in a document efficiently. /// </summary> internal sealed class DateAndTimePatternDetector { private const string FormatName = "format"; /// <summary> /// Cache so that we can reuse the same <see cref="DateAndTimePatternDetector"/> when analyzing a particular /// semantic model. This saves the time from having to recreate this for every string literal that features /// examine for a particular semantic model. /// </summary> private static readonly ConditionalWeakTable<SemanticModel, DateAndTimePatternDetector?> _modelToDetector = new(); private readonly EmbeddedLanguageInfo _info; private readonly SemanticModel _semanticModel; private readonly INamedTypeSymbol _dateTimeType; private readonly INamedTypeSymbol _dateTimeOffsetType; public DateAndTimePatternDetector( SemanticModel semanticModel, EmbeddedLanguageInfo info, INamedTypeSymbol dateTimeType, INamedTypeSymbol dateTimeOffsetType) { _info = info; _semanticModel = semanticModel; _dateTimeType = dateTimeType; _dateTimeOffsetType = dateTimeOffsetType; } public static DateAndTimePatternDetector? TryGetOrCreate( SemanticModel semanticModel, EmbeddedLanguageInfo info) { // Do a quick non-allocating check first. if (_modelToDetector.TryGetValue(semanticModel, out var detector)) { return detector; } return _modelToDetector.GetValue( semanticModel, _ => TryCreate(semanticModel, info)); } private static DateAndTimePatternDetector? TryCreate( SemanticModel semanticModel, EmbeddedLanguageInfo info) { var dateTimeType = semanticModel.Compilation.GetTypeByMetadataName(typeof(System.DateTime).FullName!); var dateTimeOffsetType = semanticModel.Compilation.GetTypeByMetadataName(typeof(System.DateTimeOffset).FullName!); if (dateTimeType == null || dateTimeOffsetType == null) return null; return new DateAndTimePatternDetector(semanticModel, info, dateTimeType, dateTimeOffsetType); } /// <summary> /// Checks if this <paramref name="token"/> is possibly a string literal token that could contain a date or time /// format string passed into an method call. If so, <paramref name="argumentNode"/> and <paramref /// name="invocationExpression"/> will be the argument and invocatoin the string literal was passed as. /// </summary> public static bool IsPossiblyDateAndTimeArgumentToken( SyntaxToken token, ISyntaxFacts syntaxFacts, [NotNullWhen(true)] out SyntaxNode? argumentNode, [NotNullWhen(true)] out SyntaxNode? invocationExpression) { // Has to be a string literal passed to a method. argumentNode = null; invocationExpression = null; if (!syntaxFacts.IsStringLiteral(token)) return false; if (!IsMethodArgument(token, syntaxFacts)) return false; if (!syntaxFacts.IsLiteralExpression(token.Parent)) return false; if (!syntaxFacts.IsArgument(token.Parent.Parent)) return false; var argumentList = token.Parent.Parent.Parent; var invocationOrCreation = argumentList?.Parent; if (!syntaxFacts.IsInvocationExpression(invocationOrCreation)) return false; var invokedExpression = syntaxFacts.GetExpressionOfInvocationExpression(invocationOrCreation); var name = GetNameOfInvokedExpression(syntaxFacts, invokedExpression); if (name is not nameof(ToString) and not nameof(DateTime.ParseExact) and not nameof(DateTime.TryParseExact)) return false; // We have a string literal passed to a method called ToString/ParseExact/TryParseExact. // Have to do a more expensive semantic check now. argumentNode = token.Parent.Parent; invocationExpression = invocationOrCreation; return true; } private static string? GetNameOfInvokedExpression(ISyntaxFacts syntaxFacts, SyntaxNode invokedExpression) { if (syntaxFacts.IsSimpleMemberAccessExpression(invokedExpression)) return syntaxFacts.GetIdentifierOfSimpleName(syntaxFacts.GetNameOfMemberAccessExpression(invokedExpression)).ValueText; if (syntaxFacts.IsMemberBindingExpression(invokedExpression)) invokedExpression = syntaxFacts.GetNameOfMemberBindingExpression(invokedExpression); if (syntaxFacts.IsIdentifierName(invokedExpression)) return syntaxFacts.GetIdentifierOfSimpleName(invokedExpression).ValueText; return null; } private static bool IsMethodArgument(SyntaxToken token, ISyntaxFacts syntaxFacts) => syntaxFacts.IsLiteralExpression(token.Parent) && syntaxFacts.IsArgument(token.Parent!.Parent); public bool IsDateAndTimeToken(SyntaxToken token, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken) { if (IsPossiblyDateAndTimeArgumentToken( token, _info.SyntaxFacts, out var argumentNode, out var invocationOrCreation)) { // if we couldn't determine the arg name or arg index, can't proceed. var (argName, argIndex) = GetArgumentNameOrIndex(argumentNode); if (argName == null && argIndex == null) return false; // If we had a specified arg name and it isn't 'format', then it's not a DateTime // 'format' param we care about. if (argName is not null and not FormatName) return false; var symbolInfo = _semanticModel.GetSymbolInfo(invocationOrCreation, cancellationToken); var method = symbolInfo.Symbol; if (TryAnalyzeInvocation(method, argName, argIndex)) return true; foreach (var candidate in symbolInfo.CandidateSymbols) { if (TryAnalyzeInvocation(candidate, argName, argIndex)) return true; } } else if (token.RawKind == syntaxFacts.SyntaxKinds.InterpolatedStringTextToken) { var interpolationFormatClause = token.Parent!; var interpolation = interpolationFormatClause.Parent!; if (interpolation.RawKind == syntaxFacts.SyntaxKinds.Interpolation) { var expression = syntaxFacts.GetExpressionOfInterpolation(interpolation)!; var type = _semanticModel.GetTypeInfo(expression, cancellationToken).Type; return IsDateTimeType(type); } } return false; } private (string? name, int? index) GetArgumentNameOrIndex(SyntaxNode argument) { var syntaxFacts = _info.SyntaxFacts; var argName = syntaxFacts.GetNameForArgument(argument); if (argName != "") return (argName, null); var arguments = syntaxFacts.GetArgumentsOfArgumentList(argument.Parent); var index = arguments.IndexOf(argument); if (index >= 0) return (null, index); return default; } private bool TryAnalyzeInvocation(ISymbol? symbol, string? argName, int? argIndex) => symbol is IMethodSymbol method && method.DeclaredAccessibility == Accessibility.Public && method.MethodKind == MethodKind.Ordinary && IsDateTimeType(method.ContainingType) && AnalyzeStringLiteral(method, argName, argIndex); private bool IsDateTimeType(ITypeSymbol? type) => _dateTimeType.Equals(type) || _dateTimeOffsetType.Equals(type); private static bool AnalyzeStringLiteral(IMethodSymbol method, string? argName, int? argIndex) { Debug.Assert(argName != null || argIndex != null); var parameters = method.Parameters; if (argName != null) return parameters.Any(p => p.Name == argName); var parameter = argIndex < parameters.Length ? parameters[argIndex.Value] : null; return parameter?.Name == FormatName; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.DateAndTime.LanguageServices { /// <summary> /// Helper class to detect <see cref="System.DateTime"/> and <see cref="DateTimeOffset"/> format /// strings in a document efficiently. /// </summary> internal sealed class DateAndTimePatternDetector { private const string FormatName = "format"; /// <summary> /// Cache so that we can reuse the same <see cref="DateAndTimePatternDetector"/> when analyzing a particular /// semantic model. This saves the time from having to recreate this for every string literal that features /// examine for a particular semantic model. /// </summary> private static readonly ConditionalWeakTable<SemanticModel, DateAndTimePatternDetector?> _modelToDetector = new(); private readonly EmbeddedLanguageInfo _info; private readonly SemanticModel _semanticModel; private readonly INamedTypeSymbol _dateTimeType; private readonly INamedTypeSymbol _dateTimeOffsetType; public DateAndTimePatternDetector( SemanticModel semanticModel, EmbeddedLanguageInfo info, INamedTypeSymbol dateTimeType, INamedTypeSymbol dateTimeOffsetType) { _info = info; _semanticModel = semanticModel; _dateTimeType = dateTimeType; _dateTimeOffsetType = dateTimeOffsetType; } public static DateAndTimePatternDetector? TryGetOrCreate( SemanticModel semanticModel, EmbeddedLanguageInfo info) { // Do a quick non-allocating check first. if (_modelToDetector.TryGetValue(semanticModel, out var detector)) { return detector; } return _modelToDetector.GetValue( semanticModel, _ => TryCreate(semanticModel, info)); } private static DateAndTimePatternDetector? TryCreate( SemanticModel semanticModel, EmbeddedLanguageInfo info) { var dateTimeType = semanticModel.Compilation.GetTypeByMetadataName(typeof(System.DateTime).FullName!); var dateTimeOffsetType = semanticModel.Compilation.GetTypeByMetadataName(typeof(System.DateTimeOffset).FullName!); if (dateTimeType == null || dateTimeOffsetType == null) return null; return new DateAndTimePatternDetector(semanticModel, info, dateTimeType, dateTimeOffsetType); } /// <summary> /// Checks if this <paramref name="token"/> is possibly a string literal token that could contain a date or time /// format string passed into an method call. If so, <paramref name="argumentNode"/> and <paramref /// name="invocationExpression"/> will be the argument and invocatoin the string literal was passed as. /// </summary> public static bool IsPossiblyDateAndTimeArgumentToken( SyntaxToken token, ISyntaxFacts syntaxFacts, [NotNullWhen(true)] out SyntaxNode? argumentNode, [NotNullWhen(true)] out SyntaxNode? invocationExpression) { // Has to be a string literal passed to a method. argumentNode = null; invocationExpression = null; if (!syntaxFacts.IsStringLiteral(token)) return false; if (!IsMethodArgument(token, syntaxFacts)) return false; if (!syntaxFacts.IsLiteralExpression(token.Parent)) return false; if (!syntaxFacts.IsArgument(token.Parent.Parent)) return false; var argumentList = token.Parent.Parent.Parent; var invocationOrCreation = argumentList?.Parent; if (!syntaxFacts.IsInvocationExpression(invocationOrCreation)) return false; var invokedExpression = syntaxFacts.GetExpressionOfInvocationExpression(invocationOrCreation); var name = GetNameOfInvokedExpression(syntaxFacts, invokedExpression); if (name is not nameof(ToString) and not nameof(DateTime.ParseExact) and not nameof(DateTime.TryParseExact)) return false; // We have a string literal passed to a method called ToString/ParseExact/TryParseExact. // Have to do a more expensive semantic check now. argumentNode = token.Parent.Parent; invocationExpression = invocationOrCreation; return true; } private static string? GetNameOfInvokedExpression(ISyntaxFacts syntaxFacts, SyntaxNode invokedExpression) { if (syntaxFacts.IsSimpleMemberAccessExpression(invokedExpression)) return syntaxFacts.GetIdentifierOfSimpleName(syntaxFacts.GetNameOfMemberAccessExpression(invokedExpression)).ValueText; if (syntaxFacts.IsMemberBindingExpression(invokedExpression)) invokedExpression = syntaxFacts.GetNameOfMemberBindingExpression(invokedExpression); if (syntaxFacts.IsIdentifierName(invokedExpression)) return syntaxFacts.GetIdentifierOfSimpleName(invokedExpression).ValueText; return null; } private static bool IsMethodArgument(SyntaxToken token, ISyntaxFacts syntaxFacts) => syntaxFacts.IsLiteralExpression(token.Parent) && syntaxFacts.IsArgument(token.Parent!.Parent); public bool IsDateAndTimeToken(SyntaxToken token, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken) { if (IsPossiblyDateAndTimeArgumentToken( token, _info.SyntaxFacts, out var argumentNode, out var invocationOrCreation)) { // if we couldn't determine the arg name or arg index, can't proceed. var (argName, argIndex) = GetArgumentNameOrIndex(argumentNode); if (argName == null && argIndex == null) return false; // If we had a specified arg name and it isn't 'format', then it's not a DateTime // 'format' param we care about. if (argName is not null and not FormatName) return false; var symbolInfo = _semanticModel.GetSymbolInfo(invocationOrCreation, cancellationToken); var method = symbolInfo.Symbol; if (TryAnalyzeInvocation(method, argName, argIndex)) return true; foreach (var candidate in symbolInfo.CandidateSymbols) { if (TryAnalyzeInvocation(candidate, argName, argIndex)) return true; } } else if (token.RawKind == syntaxFacts.SyntaxKinds.InterpolatedStringTextToken) { var interpolationFormatClause = token.Parent!; var interpolation = interpolationFormatClause.Parent!; if (interpolation.RawKind == syntaxFacts.SyntaxKinds.Interpolation) { var expression = syntaxFacts.GetExpressionOfInterpolation(interpolation)!; var type = _semanticModel.GetTypeInfo(expression, cancellationToken).Type; return IsDateTimeType(type); } } return false; } private (string? name, int? index) GetArgumentNameOrIndex(SyntaxNode argument) { var syntaxFacts = _info.SyntaxFacts; var argName = syntaxFacts.GetNameForArgument(argument); if (argName != "") return (argName, null); var arguments = syntaxFacts.GetArgumentsOfArgumentList(argument.GetRequiredParent()); var index = arguments.IndexOf(argument); if (index >= 0) return (null, index); return default; } private bool TryAnalyzeInvocation(ISymbol? symbol, string? argName, int? argIndex) => symbol is IMethodSymbol method && method.DeclaredAccessibility == Accessibility.Public && method.MethodKind == MethodKind.Ordinary && IsDateTimeType(method.ContainingType) && AnalyzeStringLiteral(method, argName, argIndex); private bool IsDateTimeType(ITypeSymbol? type) => _dateTimeType.Equals(type) || _dateTimeOffsetType.Equals(type); private static bool AnalyzeStringLiteral(IMethodSymbol method, string? argName, int? argIndex) { Debug.Assert(argName != null || argIndex != null); var parameters = method.Parameters; if (argName != null) return parameters.Any(p => p.Name == argName); var parameter = argIndex < parameters.Length ? parameters[argIndex.Value] : null; return parameter?.Name == FormatName; } } }
1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Features/Core/Portable/IntroduceVariable/AbstractIntroduceParameterDocumentRewriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.IntroduceVariable { internal abstract partial class AbstractIntroduceParameterService<TExpressionSyntax, TInvocationExpressionSyntax, TObjectCreationExpressionSyntax, TIdentifierNameSyntax> { private class IntroduceParameterDocumentRewriter { private readonly AbstractIntroduceParameterService<TExpressionSyntax, TInvocationExpressionSyntax, TObjectCreationExpressionSyntax, TIdentifierNameSyntax> _service; private readonly Document _originalDocument; private readonly SyntaxGenerator _generator; private readonly ISyntaxFactsService _syntaxFacts; private readonly ISemanticFactsService _semanticFacts; private readonly TExpressionSyntax _expression; private readonly IMethodSymbol _methodSymbol; private readonly SyntaxNode _containerMethod; private readonly IntroduceParameterCodeActionKind _actionKind; private readonly bool _allOccurrences; public IntroduceParameterDocumentRewriter(AbstractIntroduceParameterService<TExpressionSyntax, TInvocationExpressionSyntax, TObjectCreationExpressionSyntax, TIdentifierNameSyntax> service, Document originalDocument, TExpressionSyntax expression, IMethodSymbol methodSymbol, SyntaxNode containingMethod, IntroduceParameterCodeActionKind selectedCodeAction, bool allOccurrences) { _service = service; _originalDocument = originalDocument; _generator = SyntaxGenerator.GetGenerator(originalDocument); _syntaxFacts = originalDocument.GetRequiredLanguageService<ISyntaxFactsService>(); _semanticFacts = originalDocument.GetRequiredLanguageService<ISemanticFactsService>(); _expression = expression; _methodSymbol = methodSymbol; _containerMethod = containingMethod; _actionKind = selectedCodeAction; _allOccurrences = allOccurrences; } public async Task<SyntaxNode> RewriteDocumentAsync(Compilation compilation, Document document, List<SyntaxNode> invocations, CancellationToken cancellationToken) { var insertionIndex = GetInsertionIndex(compilation); if (_actionKind is IntroduceParameterCodeActionKind.Overload or IntroduceParameterCodeActionKind.Trampoline) { return await ModifyDocumentInvocationsTrampolineOverloadAndIntroduceParameterAsync( compilation, document, invocations, insertionIndex, cancellationToken).ConfigureAwait(false); } else { return await ModifyDocumentInvocationsAndIntroduceParameterAsync( compilation, document, insertionIndex, invocations, cancellationToken).ConfigureAwait(false); } } /// <summary> /// Ties the identifiers within the expression back to their associated parameter. /// </summary> private async Task<Dictionary<TIdentifierNameSyntax, IParameterSymbol>> MapExpressionToParametersAsync(CancellationToken cancellationToken) { var nameToParameterDict = new Dictionary<TIdentifierNameSyntax, IParameterSymbol>(); var variablesInExpression = _expression.DescendantNodes().OfType<TIdentifierNameSyntax>(); var semanticModel = await _originalDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var variable in variablesInExpression) { var symbol = semanticModel.GetSymbolInfo(variable, cancellationToken).Symbol; if (symbol is IParameterSymbol parameterSymbol) { nameToParameterDict.Add(variable, parameterSymbol); } } return nameToParameterDict; } /// <summary> /// Gets the parameter name, if the expression's grandparent is a variable declarator then it just gets the /// local declarations name. Otherwise, it generates a name based on the context of the expression. /// </summary> private async Task<string> GetNewParameterNameAsync(CancellationToken cancellationToken) { if (ShouldRemoveVariableDeclaratorContainingExpression(out var varDeclName, out _)) { return varDeclName; } var semanticModel = await _originalDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var semanticFacts = _originalDocument.GetRequiredLanguageService<ISemanticFactsService>(); return semanticFacts.GenerateNameForExpression(semanticModel, _expression, capitalize: false, cancellationToken); } /// <summary> /// Determines if the expression's grandparent is a variable declarator and if so, /// returns the name /// </summary> private bool ShouldRemoveVariableDeclaratorContainingExpression([NotNullWhen(true)] out string? varDeclName, [NotNullWhen(true)] out SyntaxNode? localDeclaration) { var declarator = _expression?.Parent?.Parent; localDeclaration = null; if (!_syntaxFacts.IsVariableDeclarator(declarator)) { varDeclName = null; return false; } localDeclaration = _service.GetLocalDeclarationFromDeclarator(declarator); if (localDeclaration is null) { varDeclName = null; return false; } // TODO: handle in the future if (_syntaxFacts.GetVariablesOfLocalDeclarationStatement(localDeclaration).Count > 1) { varDeclName = null; localDeclaration = null; return false; } varDeclName = _syntaxFacts.GetIdentifierOfVariableDeclarator(declarator).ValueText; return true; } /// <summary> /// Goes through the parameters of the original method to get the location that the parameter /// and argument should be introduced. /// </summary> private int GetInsertionIndex(Compilation compilation) { var parameterList = _syntaxFacts.GetParameterList(_containerMethod); Contract.ThrowIfNull(parameterList); var insertionIndex = 0; foreach (var parameterSymbol in _methodSymbol.Parameters) { // Want to skip optional parameters, params parameters, and CancellationToken since they should be at // the end of the list. if (ShouldParameterBeSkipped(compilation, parameterSymbol)) { insertionIndex++; } } return insertionIndex; } /// <summary> /// For the trampoline case, it goes through the invocations and adds an argument which is a /// call to the extracted method. /// Introduces a new method overload or new trampoline method. /// Updates the original method site with a newly introduced parameter. /// /// ****Trampoline Example:**** /// public void M(int x, int y) /// { /// int f = [|x * y|]; /// Console.WriteLine(f); /// } /// /// public void InvokeMethod() /// { /// M(5, 6); /// } /// /// ----------------------------------------------------> /// /// public int GetF(int x, int y) // Generated method /// { /// return x * y; /// } /// /// public void M(int x, int y, int f) /// { /// Console.WriteLine(f); /// } /// /// public void InvokeMethod() /// { /// M(5, 6, GetF(5, 6)); //Fills in with call to generated method /// } /// /// ----------------------------------------------------------------------- /// ****Overload Example:**** /// public void M(int x, int y) /// { /// int f = [|x * y|]; /// Console.WriteLine(f); /// } /// /// public void InvokeMethod() /// { /// M(5, 6); /// } /// /// ----------------------------------------------------> /// /// public void M(int x, int y) // Generated overload /// { /// M(x, y, x * y) /// } /// /// public void M(int x, int y, int f) /// { /// Console.WriteLine(f); /// } /// /// public void InvokeMethod() /// { /// M(5, 6); /// } /// </summary> private async Task<SyntaxNode> ModifyDocumentInvocationsTrampolineOverloadAndIntroduceParameterAsync(Compilation compilation, Document currentDocument, List<SyntaxNode> invocations, int insertionIndex, CancellationToken cancellationToken) { var invocationSemanticModel = await currentDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await currentDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, _generator); var parameterName = await GetNewParameterNameAsync(cancellationToken).ConfigureAwait(false); var expressionParameterMap = await MapExpressionToParametersAsync(cancellationToken).ConfigureAwait(false); // Creating a new method name by concatenating the parameter name that has been upper-cased. var newMethodIdentifier = "Get" + parameterName.ToPascalCase(); var validParameters = _methodSymbol.Parameters.Intersect(expressionParameterMap.Values).ToImmutableArray(); if (_actionKind is IntroduceParameterCodeActionKind.Trampoline) { // Creating an empty map here to reuse so that we do not create a new dictionary for // every single invocation. var parameterToArgumentMap = new Dictionary<IParameterSymbol, int>(); foreach (var invocation in invocations) { var argumentListSyntax = _syntaxFacts.GetArgumentListOfInvocationExpression(invocation); editor.ReplaceNode(argumentListSyntax, (currentArgumentListSyntax, _) => { return GenerateNewArgumentListSyntaxForTrampoline(compilation, invocationSemanticModel, parameterToArgumentMap, currentArgumentListSyntax, argumentListSyntax, invocation, validParameters, parameterName, newMethodIdentifier, insertionIndex, cancellationToken); }); } } // If you are at the original document, then also introduce the new method and introduce the parameter. if (currentDocument.Id == _originalDocument.Id) { var newMethodNode = _actionKind is IntroduceParameterCodeActionKind.Trampoline ? await ExtractMethodAsync(validParameters, newMethodIdentifier, _generator, cancellationToken).ConfigureAwait(false) : await GenerateNewMethodOverloadAsync(insertionIndex, _generator, cancellationToken).ConfigureAwait(false); editor.InsertBefore(_containerMethod, newMethodNode); await UpdateExpressionInOriginalFunctionAsync(editor, cancellationToken).ConfigureAwait(false); var parameterType = await GetTypeOfExpressionAsync(cancellationToken).ConfigureAwait(false); var parameter = _generator.ParameterDeclaration(parameterName, _generator.TypeExpression(parameterType)); editor.InsertParameter(_containerMethod, insertionIndex, parameter); } return editor.GetChangedRoot(); // Adds an argument which is an invocation of the newly created method to the callsites // of the method invocations where a parameter was added. // Example: // public void M(int x, int y) // { // int f = [|x * y|]; // Console.WriteLine(f); // } // // public void InvokeMethod() // { // M(5, 6); // } // // ----------------------------------------------------> // // public int GetF(int x, int y) // { // return x * y; // } // // public void M(int x, int y) // { // int f = x * y; // Console.WriteLine(f); // } // // public void InvokeMethod() // { // M(5, 6, GetF(5, 6)); // This is the generated invocation which is a new argument at the call site // } SyntaxNode GenerateNewArgumentListSyntaxForTrampoline(Compilation compilation, SemanticModel invocationSemanticModel, Dictionary<IParameterSymbol, int> parameterToArgumentMap, SyntaxNode currentArgumentListSyntax, SyntaxNode argumentListSyntax, SyntaxNode invocation, ImmutableArray<IParameterSymbol> validParameters, string parameterName, string newMethodIdentifier, int insertionIndex, CancellationToken cancellationToken) { var invocationArguments = _syntaxFacts.GetArgumentsOfArgumentList(argumentListSyntax); parameterToArgumentMap.Clear(); MapParameterToArgumentsAtInvocation(parameterToArgumentMap, invocationArguments, invocationSemanticModel, cancellationToken); var currentInvocationArguments = _syntaxFacts.GetArgumentsOfArgumentList(currentArgumentListSyntax); var requiredArguments = new List<SyntaxNode>(); foreach (var parameterSymbol in validParameters) { if (parameterToArgumentMap.TryGetValue(parameterSymbol, out var index)) { requiredArguments.Add(currentInvocationArguments[index]); } } var conditionalRoot = _syntaxFacts.GetRootConditionalAccessExpression(invocation); var named = ShouldArgumentBeNamed(compilation, invocationSemanticModel, invocationArguments, insertionIndex, cancellationToken); var newMethodInvocation = GenerateNewMethodInvocation(invocation, requiredArguments, newMethodIdentifier); SeparatedSyntaxList<SyntaxNode> allArguments; if (conditionalRoot is null) { allArguments = AddArgumentToArgumentList(currentInvocationArguments, newMethodInvocation, parameterName, insertionIndex, named); } else { // Conditional Access expressions are parents of invocations, so it is better to just replace the // invocation in place then rebuild the tree structure. var expressionsWithConditionalAccessors = conditionalRoot.ReplaceNode(invocation, newMethodInvocation); allArguments = AddArgumentToArgumentList(currentInvocationArguments, expressionsWithConditionalAccessors, parameterName, insertionIndex, named); } return _service.UpdateArgumentListSyntax(currentArgumentListSyntax, allArguments); } } private async Task<ITypeSymbol> GetTypeOfExpressionAsync(CancellationToken cancellationToken) { var semanticModel = await _originalDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var typeSymbol = semanticModel.GetTypeInfo(_expression, cancellationToken).ConvertedType ?? semanticModel.Compilation.ObjectType; return typeSymbol; } private SyntaxNode GenerateNewMethodInvocation(SyntaxNode invocation, List<SyntaxNode> arguments, string newMethodIdentifier) { var methodName = _generator.IdentifierName(newMethodIdentifier); var fullExpression = _syntaxFacts.GetExpressionOfInvocationExpression(invocation); if (_syntaxFacts.IsAnyMemberAccessExpression(fullExpression)) { var receiverExpression = _syntaxFacts.GetExpressionOfMemberAccessExpression(fullExpression); methodName = _generator.MemberAccessExpression(receiverExpression, newMethodIdentifier); } else if (_syntaxFacts.IsMemberBindingExpression(fullExpression)) { methodName = _generator.MemberBindingExpression(_generator.IdentifierName(newMethodIdentifier)); } return _generator.InvocationExpression(methodName, arguments); } /// <summary> /// Generates a method declaration containing a return expression of the highlighted expression. /// Example: /// public void M(int x, int y) /// { /// int f = [|x * y|]; /// } /// /// ----------------------------------------------------> /// /// public int GetF(int x, int y) /// { /// return x * y; /// } /// /// public void M(int x, int y) /// { /// int f = x * y; /// } /// </summary> private async Task<SyntaxNode> ExtractMethodAsync(ImmutableArray<IParameterSymbol> validParameters, string newMethodIdentifier, SyntaxGenerator generator, CancellationToken cancellationToken) { // Remove trivia so the expression is in a single line and does not affect the spacing of the following line var returnStatement = generator.ReturnStatement(_expression.WithoutTrivia()); var typeSymbol = await GetTypeOfExpressionAsync(cancellationToken).ConfigureAwait(false); var newMethodDeclaration = await CreateMethodDeclarationAsync(returnStatement, validParameters, newMethodIdentifier, typeSymbol, isTrampoline: true, cancellationToken).ConfigureAwait(false); return newMethodDeclaration; } /// <summary> /// Generates a method declaration containing a call to the method that introduced the parameter. /// Example: /// /// ***This is an intermediary step in which the original function has not be updated yet /// public void M(int x, int y) /// { /// int f = [|x * y|]; /// } /// /// ----------------------------------------------------> /// /// public void M(int x, int y) // Generated overload /// { /// M(x, y, x * y); /// } /// /// public void M(int x, int y) // Original function (which will be mutated in a later step) /// { /// int f = x * y; /// } /// </summary> private async Task<SyntaxNode> GenerateNewMethodOverloadAsync(int insertionIndex, SyntaxGenerator generator, CancellationToken cancellationToken) { // Need the parameters from the original function as arguments for the invocation var arguments = generator.CreateArguments(_methodSymbol.Parameters); // Remove trivia so the expression is in a single line and does not affect the spacing of the following line arguments = arguments.Insert(insertionIndex, generator.Argument(_expression.WithoutTrivia())); var memberName = _methodSymbol.IsGenericMethod ? generator.GenericName(_methodSymbol.Name, _methodSymbol.TypeArguments) : generator.IdentifierName(_methodSymbol.Name); var invocation = generator.InvocationExpression(memberName, arguments); var newStatement = _methodSymbol.ReturnsVoid ? generator.ExpressionStatement(invocation) : generator.ReturnStatement(invocation); var newMethodDeclaration = await CreateMethodDeclarationAsync(newStatement, validParameters: null, newMethodIdentifier: null, typeSymbol: null, isTrampoline: false, cancellationToken).ConfigureAwait(false); return newMethodDeclaration; } private async Task<SyntaxNode> CreateMethodDeclarationAsync(SyntaxNode newStatement, ImmutableArray<IParameterSymbol>? validParameters, string? newMethodIdentifier, ITypeSymbol? typeSymbol, bool isTrampoline, CancellationToken cancellationToken) { var codeGenerationService = _originalDocument.GetRequiredLanguageService<ICodeGenerationService>(); var options = await _originalDocument.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var newMethod = isTrampoline ? CodeGenerationSymbolFactory.CreateMethodSymbol(_methodSymbol, name: newMethodIdentifier, parameters: validParameters, statements: ImmutableArray.Create(newStatement), returnType: typeSymbol) : CodeGenerationSymbolFactory.CreateMethodSymbol(_methodSymbol, statements: ImmutableArray.Create(newStatement), containingType: _methodSymbol.ContainingType); var newMethodDeclaration = codeGenerationService.CreateMethodDeclaration(newMethod, options: new CodeGenerationOptions(options: options, parseOptions: _expression.SyntaxTree.Options)); return newMethodDeclaration; } /// <summary> /// This method goes through all the invocation sites and adds a new argument with the expression to be added. /// It also introduces a parameter at the original method site. /// /// Example: /// public void M(int x, int y) /// { /// int f = [|x * y|]; /// } /// /// public void InvokeMethod() /// { /// M(5, 6); /// } /// /// ----------------------------------------------------> /// /// public void M(int x, int y, int f) // parameter gets introduced /// { /// } /// /// public void InvokeMethod() /// { /// M(5, 6, 5 * 6); // argument gets added to callsite /// } /// </summary> private async Task<SyntaxNode> ModifyDocumentInvocationsAndIntroduceParameterAsync(Compilation compilation, Document document, int insertionIndex, List<SyntaxNode> invocations, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, _generator); var invocationSemanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var parameterToArgumentMap = new Dictionary<IParameterSymbol, int>(); var expressionToParameterMap = await MapExpressionToParametersAsync(cancellationToken).ConfigureAwait(false); var parameterName = await GetNewParameterNameAsync(cancellationToken).ConfigureAwait(false); foreach (var invocation in invocations) { var expressionEditor = new SyntaxEditor(_expression, _generator); var argumentListSyntax = invocation is TObjectCreationExpressionSyntax ? _syntaxFacts.GetArgumentListOfObjectCreationExpression(invocation) : _syntaxFacts.GetArgumentListOfInvocationExpression(invocation); var invocationArguments = _syntaxFacts.GetArgumentsOfArgumentList(argumentListSyntax); parameterToArgumentMap.Clear(); MapParameterToArgumentsAtInvocation(parameterToArgumentMap, invocationArguments, invocationSemanticModel, cancellationToken); if (argumentListSyntax is not null) { editor.ReplaceNode(argumentListSyntax, (currentArgumentListSyntax, _) => { var updatedInvocationArguments = _syntaxFacts.GetArgumentsOfArgumentList(currentArgumentListSyntax); var updatedExpression = CreateNewArgumentExpression(expressionEditor, expressionToParameterMap, parameterToArgumentMap, updatedInvocationArguments); var named = ShouldArgumentBeNamed(compilation, invocationSemanticModel, invocationArguments, insertionIndex, cancellationToken); var allArguments = AddArgumentToArgumentList(updatedInvocationArguments, updatedExpression.WithAdditionalAnnotations(Formatter.Annotation), parameterName, insertionIndex, named); return _service.UpdateArgumentListSyntax(currentArgumentListSyntax, allArguments); }); } } // If you are at the original document, then also introduce the new method and introduce the parameter. if (document.Id == _originalDocument.Id) { await UpdateExpressionInOriginalFunctionAsync(editor, cancellationToken).ConfigureAwait(false); var parameterType = await GetTypeOfExpressionAsync(cancellationToken).ConfigureAwait(false); var parameter = _generator.ParameterDeclaration(name: parameterName, type: _generator.TypeExpression(parameterType)); editor.InsertParameter(_containerMethod, insertionIndex, parameter); } return editor.GetChangedRoot(); } /// <summary> /// This method iterates through the variables in the expression and maps the variables back to the parameter /// it is associated with. It then maps the parameter back to the argument at the invocation site and gets the /// index to retrieve the updated arguments at the invocation. /// </summary> private TExpressionSyntax CreateNewArgumentExpression(SyntaxEditor editor, Dictionary<TIdentifierNameSyntax, IParameterSymbol> mappingDictionary, Dictionary<IParameterSymbol, int> parameterToArgumentMap, SeparatedSyntaxList<SyntaxNode> updatedInvocationArguments) { foreach (var (variable, mappedParameter) in mappingDictionary) { var parameterMapped = parameterToArgumentMap.TryGetValue(mappedParameter, out var index); if (parameterMapped) { var updatedInvocationArgument = updatedInvocationArguments[index]; var argumentExpression = _syntaxFacts.GetExpressionOfArgument(updatedInvocationArgument); var parenthesizedArgumentExpression = editor.Generator.AddParentheses(argumentExpression, includeElasticTrivia: false); editor.ReplaceNode(variable, parenthesizedArgumentExpression); } else if (mappedParameter.HasExplicitDefaultValue) { var generatedExpression = _service.GenerateExpressionFromOptionalParameter(mappedParameter); var parenthesizedGeneratedExpression = editor.Generator.AddParentheses(generatedExpression, includeElasticTrivia: false); editor.ReplaceNode(variable, parenthesizedGeneratedExpression); } } return (TExpressionSyntax)editor.GetChangedRoot(); } /// <summary> /// If the parameter is optional and the invocation does not specify the parameter, then /// a named argument needs to be introduced. /// </summary> private SeparatedSyntaxList<SyntaxNode> AddArgumentToArgumentList( SeparatedSyntaxList<SyntaxNode> invocationArguments, SyntaxNode newArgumentExpression, string parameterName, int insertionIndex, bool named) { var argument = named ? _generator.Argument(parameterName, RefKind.None, newArgumentExpression) : _generator.Argument(newArgumentExpression); return invocationArguments.Insert(insertionIndex, argument); } private bool ShouldArgumentBeNamed(Compilation compilation, SemanticModel semanticModel, SeparatedSyntaxList<SyntaxNode> invocationArguments, int methodInsertionIndex, CancellationToken cancellationToken) { var invocationInsertIndex = 0; foreach (var invocationArgument in invocationArguments) { var argumentParameter = _semanticFacts.FindParameterForArgument(semanticModel, invocationArgument, cancellationToken); if (argumentParameter is not null && ShouldParameterBeSkipped(compilation, argumentParameter)) { invocationInsertIndex++; } else { break; } } return invocationInsertIndex < methodInsertionIndex; } private static bool ShouldParameterBeSkipped(Compilation compilation, IParameterSymbol parameter) => !parameter.HasExplicitDefaultValue && !parameter.IsParams && !parameter.Type.Equals(compilation.GetTypeByMetadataName(typeof(CancellationToken)?.FullName!)); private void MapParameterToArgumentsAtInvocation( Dictionary<IParameterSymbol, int> mapping, SeparatedSyntaxList<SyntaxNode> arguments, SemanticModel invocationSemanticModel, CancellationToken cancellationToken) { for (var i = 0; i < arguments.Count; i++) { var argumentParameter = _semanticFacts.FindParameterForArgument(invocationSemanticModel, arguments[i], cancellationToken); if (argumentParameter is not null) { mapping[argumentParameter] = i; } } } /// <summary> /// Gets the matches of the expression and replaces them with the identifier. /// Special case for the original matching expression, if its parent is a LocalDeclarationStatement then it can /// be removed because assigning the local dec variable to a parameter is repetitive. Does not need a rename /// annotation since the user has already named the local declaration. /// Otherwise, it needs to have a rename annotation added to it because the new parameter gets a randomly /// generated name that the user can immediately change. /// </summary> private async Task UpdateExpressionInOriginalFunctionAsync(SyntaxEditor editor, CancellationToken cancellationToken) { var generator = editor.Generator; var matches = await FindMatchesAsync(cancellationToken).ConfigureAwait(false); var parameterName = await GetNewParameterNameAsync(cancellationToken).ConfigureAwait(false); var replacement = (TIdentifierNameSyntax)generator.IdentifierName(parameterName); foreach (var match in matches) { // Special case the removal of the originating expression to either remove the local declaration // or to add a rename annotation. if (!match.Equals(_expression)) { editor.ReplaceNode(match, replacement); } else { if (ShouldRemoveVariableDeclaratorContainingExpression(out _, out var localDeclaration)) { editor.RemoveNode(localDeclaration); } else { // Found the initially selected expression. Replace it with the new name we choose, but also annotate // that name with the RenameAnnotation so a rename session is started where the user can pick their // own preferred name. replacement = (TIdentifierNameSyntax)generator.IdentifierName(generator.Identifier(parameterName) .WithAdditionalAnnotations(RenameAnnotation.Create())); editor.ReplaceNode(match, replacement); } } } } /// <summary> /// Finds the matches of the expression within the same block. /// </summary> private async Task<IEnumerable<TExpressionSyntax>> FindMatchesAsync(CancellationToken cancellationToken) { if (!_allOccurrences) { return SpecializedCollections.SingletonEnumerable(_expression); } var syntaxFacts = _originalDocument.GetRequiredLanguageService<ISyntaxFactsService>(); var originalSemanticModel = await _originalDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var matches = from nodeInCurrent in _containerMethod.DescendantNodesAndSelf().OfType<TExpressionSyntax>() where NodeMatchesExpression(originalSemanticModel, nodeInCurrent, cancellationToken) select nodeInCurrent; return matches; } private bool NodeMatchesExpression(SemanticModel originalSemanticModel, TExpressionSyntax currentNode, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (currentNode == _expression) { return true; } return SemanticEquivalence.AreEquivalent( originalSemanticModel, originalSemanticModel, _expression, currentNode); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.IntroduceVariable { internal abstract partial class AbstractIntroduceParameterService<TExpressionSyntax, TInvocationExpressionSyntax, TObjectCreationExpressionSyntax, TIdentifierNameSyntax> { private class IntroduceParameterDocumentRewriter { private readonly AbstractIntroduceParameterService<TExpressionSyntax, TInvocationExpressionSyntax, TObjectCreationExpressionSyntax, TIdentifierNameSyntax> _service; private readonly Document _originalDocument; private readonly SyntaxGenerator _generator; private readonly ISyntaxFactsService _syntaxFacts; private readonly ISemanticFactsService _semanticFacts; private readonly TExpressionSyntax _expression; private readonly IMethodSymbol _methodSymbol; private readonly SyntaxNode _containerMethod; private readonly IntroduceParameterCodeActionKind _actionKind; private readonly bool _allOccurrences; public IntroduceParameterDocumentRewriter(AbstractIntroduceParameterService<TExpressionSyntax, TInvocationExpressionSyntax, TObjectCreationExpressionSyntax, TIdentifierNameSyntax> service, Document originalDocument, TExpressionSyntax expression, IMethodSymbol methodSymbol, SyntaxNode containingMethod, IntroduceParameterCodeActionKind selectedCodeAction, bool allOccurrences) { _service = service; _originalDocument = originalDocument; _generator = SyntaxGenerator.GetGenerator(originalDocument); _syntaxFacts = originalDocument.GetRequiredLanguageService<ISyntaxFactsService>(); _semanticFacts = originalDocument.GetRequiredLanguageService<ISemanticFactsService>(); _expression = expression; _methodSymbol = methodSymbol; _containerMethod = containingMethod; _actionKind = selectedCodeAction; _allOccurrences = allOccurrences; } public async Task<SyntaxNode> RewriteDocumentAsync(Compilation compilation, Document document, List<SyntaxNode> invocations, CancellationToken cancellationToken) { var insertionIndex = GetInsertionIndex(compilation); if (_actionKind is IntroduceParameterCodeActionKind.Overload or IntroduceParameterCodeActionKind.Trampoline) { return await ModifyDocumentInvocationsTrampolineOverloadAndIntroduceParameterAsync( compilation, document, invocations, insertionIndex, cancellationToken).ConfigureAwait(false); } else { return await ModifyDocumentInvocationsAndIntroduceParameterAsync( compilation, document, insertionIndex, invocations, cancellationToken).ConfigureAwait(false); } } /// <summary> /// Ties the identifiers within the expression back to their associated parameter. /// </summary> private async Task<Dictionary<TIdentifierNameSyntax, IParameterSymbol>> MapExpressionToParametersAsync(CancellationToken cancellationToken) { var nameToParameterDict = new Dictionary<TIdentifierNameSyntax, IParameterSymbol>(); var variablesInExpression = _expression.DescendantNodes().OfType<TIdentifierNameSyntax>(); var semanticModel = await _originalDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var variable in variablesInExpression) { var symbol = semanticModel.GetSymbolInfo(variable, cancellationToken).Symbol; if (symbol is IParameterSymbol parameterSymbol) { nameToParameterDict.Add(variable, parameterSymbol); } } return nameToParameterDict; } /// <summary> /// Gets the parameter name, if the expression's grandparent is a variable declarator then it just gets the /// local declarations name. Otherwise, it generates a name based on the context of the expression. /// </summary> private async Task<string> GetNewParameterNameAsync(CancellationToken cancellationToken) { if (ShouldRemoveVariableDeclaratorContainingExpression(out var varDeclName, out _)) { return varDeclName; } var semanticModel = await _originalDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var semanticFacts = _originalDocument.GetRequiredLanguageService<ISemanticFactsService>(); return semanticFacts.GenerateNameForExpression(semanticModel, _expression, capitalize: false, cancellationToken); } /// <summary> /// Determines if the expression's grandparent is a variable declarator and if so, /// returns the name /// </summary> private bool ShouldRemoveVariableDeclaratorContainingExpression([NotNullWhen(true)] out string? varDeclName, [NotNullWhen(true)] out SyntaxNode? localDeclaration) { var declarator = _expression?.Parent?.Parent; localDeclaration = null; if (!_syntaxFacts.IsVariableDeclarator(declarator)) { varDeclName = null; return false; } localDeclaration = _service.GetLocalDeclarationFromDeclarator(declarator); if (localDeclaration is null) { varDeclName = null; return false; } // TODO: handle in the future if (_syntaxFacts.GetVariablesOfLocalDeclarationStatement(localDeclaration).Count > 1) { varDeclName = null; localDeclaration = null; return false; } varDeclName = _syntaxFacts.GetIdentifierOfVariableDeclarator(declarator).ValueText; return true; } /// <summary> /// Goes through the parameters of the original method to get the location that the parameter /// and argument should be introduced. /// </summary> private int GetInsertionIndex(Compilation compilation) { var parameterList = _syntaxFacts.GetParameterList(_containerMethod); Contract.ThrowIfNull(parameterList); var insertionIndex = 0; foreach (var parameterSymbol in _methodSymbol.Parameters) { // Want to skip optional parameters, params parameters, and CancellationToken since they should be at // the end of the list. if (ShouldParameterBeSkipped(compilation, parameterSymbol)) { insertionIndex++; } } return insertionIndex; } /// <summary> /// For the trampoline case, it goes through the invocations and adds an argument which is a /// call to the extracted method. /// Introduces a new method overload or new trampoline method. /// Updates the original method site with a newly introduced parameter. /// /// ****Trampoline Example:**** /// public void M(int x, int y) /// { /// int f = [|x * y|]; /// Console.WriteLine(f); /// } /// /// public void InvokeMethod() /// { /// M(5, 6); /// } /// /// ----------------------------------------------------> /// /// public int GetF(int x, int y) // Generated method /// { /// return x * y; /// } /// /// public void M(int x, int y, int f) /// { /// Console.WriteLine(f); /// } /// /// public void InvokeMethod() /// { /// M(5, 6, GetF(5, 6)); //Fills in with call to generated method /// } /// /// ----------------------------------------------------------------------- /// ****Overload Example:**** /// public void M(int x, int y) /// { /// int f = [|x * y|]; /// Console.WriteLine(f); /// } /// /// public void InvokeMethod() /// { /// M(5, 6); /// } /// /// ----------------------------------------------------> /// /// public void M(int x, int y) // Generated overload /// { /// M(x, y, x * y) /// } /// /// public void M(int x, int y, int f) /// { /// Console.WriteLine(f); /// } /// /// public void InvokeMethod() /// { /// M(5, 6); /// } /// </summary> private async Task<SyntaxNode> ModifyDocumentInvocationsTrampolineOverloadAndIntroduceParameterAsync(Compilation compilation, Document currentDocument, List<SyntaxNode> invocations, int insertionIndex, CancellationToken cancellationToken) { var invocationSemanticModel = await currentDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await currentDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, _generator); var parameterName = await GetNewParameterNameAsync(cancellationToken).ConfigureAwait(false); var expressionParameterMap = await MapExpressionToParametersAsync(cancellationToken).ConfigureAwait(false); // Creating a new method name by concatenating the parameter name that has been upper-cased. var newMethodIdentifier = "Get" + parameterName.ToPascalCase(); var validParameters = _methodSymbol.Parameters.Intersect(expressionParameterMap.Values).ToImmutableArray(); if (_actionKind is IntroduceParameterCodeActionKind.Trampoline) { // Creating an empty map here to reuse so that we do not create a new dictionary for // every single invocation. var parameterToArgumentMap = new Dictionary<IParameterSymbol, int>(); foreach (var invocation in invocations) { var argumentListSyntax = _syntaxFacts.GetArgumentListOfInvocationExpression(invocation); editor.ReplaceNode(argumentListSyntax, (currentArgumentListSyntax, _) => { return GenerateNewArgumentListSyntaxForTrampoline(compilation, invocationSemanticModel, parameterToArgumentMap, currentArgumentListSyntax, argumentListSyntax, invocation, validParameters, parameterName, newMethodIdentifier, insertionIndex, cancellationToken); }); } } // If you are at the original document, then also introduce the new method and introduce the parameter. if (currentDocument.Id == _originalDocument.Id) { var newMethodNode = _actionKind is IntroduceParameterCodeActionKind.Trampoline ? await ExtractMethodAsync(validParameters, newMethodIdentifier, _generator, cancellationToken).ConfigureAwait(false) : await GenerateNewMethodOverloadAsync(insertionIndex, _generator, cancellationToken).ConfigureAwait(false); editor.InsertBefore(_containerMethod, newMethodNode); await UpdateExpressionInOriginalFunctionAsync(editor, cancellationToken).ConfigureAwait(false); var parameterType = await GetTypeOfExpressionAsync(cancellationToken).ConfigureAwait(false); var parameter = _generator.ParameterDeclaration(parameterName, _generator.TypeExpression(parameterType)); editor.InsertParameter(_containerMethod, insertionIndex, parameter); } return editor.GetChangedRoot(); // Adds an argument which is an invocation of the newly created method to the callsites // of the method invocations where a parameter was added. // Example: // public void M(int x, int y) // { // int f = [|x * y|]; // Console.WriteLine(f); // } // // public void InvokeMethod() // { // M(5, 6); // } // // ----------------------------------------------------> // // public int GetF(int x, int y) // { // return x * y; // } // // public void M(int x, int y) // { // int f = x * y; // Console.WriteLine(f); // } // // public void InvokeMethod() // { // M(5, 6, GetF(5, 6)); // This is the generated invocation which is a new argument at the call site // } SyntaxNode GenerateNewArgumentListSyntaxForTrampoline(Compilation compilation, SemanticModel invocationSemanticModel, Dictionary<IParameterSymbol, int> parameterToArgumentMap, SyntaxNode currentArgumentListSyntax, SyntaxNode argumentListSyntax, SyntaxNode invocation, ImmutableArray<IParameterSymbol> validParameters, string parameterName, string newMethodIdentifier, int insertionIndex, CancellationToken cancellationToken) { var invocationArguments = _syntaxFacts.GetArgumentsOfArgumentList(argumentListSyntax); parameterToArgumentMap.Clear(); MapParameterToArgumentsAtInvocation(parameterToArgumentMap, invocationArguments, invocationSemanticModel, cancellationToken); var currentInvocationArguments = _syntaxFacts.GetArgumentsOfArgumentList(currentArgumentListSyntax); var requiredArguments = new List<SyntaxNode>(); foreach (var parameterSymbol in validParameters) { if (parameterToArgumentMap.TryGetValue(parameterSymbol, out var index)) { requiredArguments.Add(currentInvocationArguments[index]); } } var conditionalRoot = _syntaxFacts.GetRootConditionalAccessExpression(invocation); var named = ShouldArgumentBeNamed(compilation, invocationSemanticModel, invocationArguments, insertionIndex, cancellationToken); var newMethodInvocation = GenerateNewMethodInvocation(invocation, requiredArguments, newMethodIdentifier); SeparatedSyntaxList<SyntaxNode> allArguments; if (conditionalRoot is null) { allArguments = AddArgumentToArgumentList(currentInvocationArguments, newMethodInvocation, parameterName, insertionIndex, named); } else { // Conditional Access expressions are parents of invocations, so it is better to just replace the // invocation in place then rebuild the tree structure. var expressionsWithConditionalAccessors = conditionalRoot.ReplaceNode(invocation, newMethodInvocation); allArguments = AddArgumentToArgumentList(currentInvocationArguments, expressionsWithConditionalAccessors, parameterName, insertionIndex, named); } return _service.UpdateArgumentListSyntax(currentArgumentListSyntax, allArguments); } } private async Task<ITypeSymbol> GetTypeOfExpressionAsync(CancellationToken cancellationToken) { var semanticModel = await _originalDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var typeSymbol = semanticModel.GetTypeInfo(_expression, cancellationToken).ConvertedType ?? semanticModel.Compilation.ObjectType; return typeSymbol; } private SyntaxNode GenerateNewMethodInvocation(SyntaxNode invocation, List<SyntaxNode> arguments, string newMethodIdentifier) { var methodName = _generator.IdentifierName(newMethodIdentifier); var fullExpression = _syntaxFacts.GetExpressionOfInvocationExpression(invocation); if (_syntaxFacts.IsAnyMemberAccessExpression(fullExpression)) { var receiverExpression = _syntaxFacts.GetExpressionOfMemberAccessExpression(fullExpression); methodName = _generator.MemberAccessExpression(receiverExpression, newMethodIdentifier); } else if (_syntaxFacts.IsMemberBindingExpression(fullExpression)) { methodName = _generator.MemberBindingExpression(_generator.IdentifierName(newMethodIdentifier)); } return _generator.InvocationExpression(methodName, arguments); } /// <summary> /// Generates a method declaration containing a return expression of the highlighted expression. /// Example: /// public void M(int x, int y) /// { /// int f = [|x * y|]; /// } /// /// ----------------------------------------------------> /// /// public int GetF(int x, int y) /// { /// return x * y; /// } /// /// public void M(int x, int y) /// { /// int f = x * y; /// } /// </summary> private async Task<SyntaxNode> ExtractMethodAsync(ImmutableArray<IParameterSymbol> validParameters, string newMethodIdentifier, SyntaxGenerator generator, CancellationToken cancellationToken) { // Remove trivia so the expression is in a single line and does not affect the spacing of the following line var returnStatement = generator.ReturnStatement(_expression.WithoutTrivia()); var typeSymbol = await GetTypeOfExpressionAsync(cancellationToken).ConfigureAwait(false); var newMethodDeclaration = await CreateMethodDeclarationAsync(returnStatement, validParameters, newMethodIdentifier, typeSymbol, isTrampoline: true, cancellationToken).ConfigureAwait(false); return newMethodDeclaration; } /// <summary> /// Generates a method declaration containing a call to the method that introduced the parameter. /// Example: /// /// ***This is an intermediary step in which the original function has not be updated yet /// public void M(int x, int y) /// { /// int f = [|x * y|]; /// } /// /// ----------------------------------------------------> /// /// public void M(int x, int y) // Generated overload /// { /// M(x, y, x * y); /// } /// /// public void M(int x, int y) // Original function (which will be mutated in a later step) /// { /// int f = x * y; /// } /// </summary> private async Task<SyntaxNode> GenerateNewMethodOverloadAsync(int insertionIndex, SyntaxGenerator generator, CancellationToken cancellationToken) { // Need the parameters from the original function as arguments for the invocation var arguments = generator.CreateArguments(_methodSymbol.Parameters); // Remove trivia so the expression is in a single line and does not affect the spacing of the following line arguments = arguments.Insert(insertionIndex, generator.Argument(_expression.WithoutTrivia())); var memberName = _methodSymbol.IsGenericMethod ? generator.GenericName(_methodSymbol.Name, _methodSymbol.TypeArguments) : generator.IdentifierName(_methodSymbol.Name); var invocation = generator.InvocationExpression(memberName, arguments); var newStatement = _methodSymbol.ReturnsVoid ? generator.ExpressionStatement(invocation) : generator.ReturnStatement(invocation); var newMethodDeclaration = await CreateMethodDeclarationAsync(newStatement, validParameters: null, newMethodIdentifier: null, typeSymbol: null, isTrampoline: false, cancellationToken).ConfigureAwait(false); return newMethodDeclaration; } private async Task<SyntaxNode> CreateMethodDeclarationAsync(SyntaxNode newStatement, ImmutableArray<IParameterSymbol>? validParameters, string? newMethodIdentifier, ITypeSymbol? typeSymbol, bool isTrampoline, CancellationToken cancellationToken) { var codeGenerationService = _originalDocument.GetRequiredLanguageService<ICodeGenerationService>(); var options = await _originalDocument.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var newMethod = isTrampoline ? CodeGenerationSymbolFactory.CreateMethodSymbol(_methodSymbol, name: newMethodIdentifier, parameters: validParameters, statements: ImmutableArray.Create(newStatement), returnType: typeSymbol) : CodeGenerationSymbolFactory.CreateMethodSymbol(_methodSymbol, statements: ImmutableArray.Create(newStatement), containingType: _methodSymbol.ContainingType); var newMethodDeclaration = codeGenerationService.CreateMethodDeclaration(newMethod, options: new CodeGenerationOptions(options: options, parseOptions: _expression.SyntaxTree.Options)); return newMethodDeclaration; } /// <summary> /// This method goes through all the invocation sites and adds a new argument with the expression to be added. /// It also introduces a parameter at the original method site. /// /// Example: /// public void M(int x, int y) /// { /// int f = [|x * y|]; /// } /// /// public void InvokeMethod() /// { /// M(5, 6); /// } /// /// ----------------------------------------------------> /// /// public void M(int x, int y, int f) // parameter gets introduced /// { /// } /// /// public void InvokeMethod() /// { /// M(5, 6, 5 * 6); // argument gets added to callsite /// } /// </summary> private async Task<SyntaxNode> ModifyDocumentInvocationsAndIntroduceParameterAsync(Compilation compilation, Document document, int insertionIndex, List<SyntaxNode> invocations, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, _generator); var invocationSemanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var parameterToArgumentMap = new Dictionary<IParameterSymbol, int>(); var expressionToParameterMap = await MapExpressionToParametersAsync(cancellationToken).ConfigureAwait(false); var parameterName = await GetNewParameterNameAsync(cancellationToken).ConfigureAwait(false); foreach (var invocation in invocations) { var expressionEditor = new SyntaxEditor(_expression, _generator); var argumentListSyntax = invocation is TObjectCreationExpressionSyntax ? _syntaxFacts.GetArgumentListOfObjectCreationExpression(invocation) : _syntaxFacts.GetArgumentListOfInvocationExpression(invocation); if (argumentListSyntax == null) continue; var invocationArguments = _syntaxFacts.GetArgumentsOfArgumentList(argumentListSyntax); parameterToArgumentMap.Clear(); MapParameterToArgumentsAtInvocation(parameterToArgumentMap, invocationArguments, invocationSemanticModel, cancellationToken); if (argumentListSyntax is not null) { editor.ReplaceNode(argumentListSyntax, (currentArgumentListSyntax, _) => { var updatedInvocationArguments = _syntaxFacts.GetArgumentsOfArgumentList(currentArgumentListSyntax); var updatedExpression = CreateNewArgumentExpression(expressionEditor, expressionToParameterMap, parameterToArgumentMap, updatedInvocationArguments); var named = ShouldArgumentBeNamed(compilation, invocationSemanticModel, invocationArguments, insertionIndex, cancellationToken); var allArguments = AddArgumentToArgumentList(updatedInvocationArguments, updatedExpression.WithAdditionalAnnotations(Formatter.Annotation), parameterName, insertionIndex, named); return _service.UpdateArgumentListSyntax(currentArgumentListSyntax, allArguments); }); } } // If you are at the original document, then also introduce the new method and introduce the parameter. if (document.Id == _originalDocument.Id) { await UpdateExpressionInOriginalFunctionAsync(editor, cancellationToken).ConfigureAwait(false); var parameterType = await GetTypeOfExpressionAsync(cancellationToken).ConfigureAwait(false); var parameter = _generator.ParameterDeclaration(name: parameterName, type: _generator.TypeExpression(parameterType)); editor.InsertParameter(_containerMethod, insertionIndex, parameter); } return editor.GetChangedRoot(); } /// <summary> /// This method iterates through the variables in the expression and maps the variables back to the parameter /// it is associated with. It then maps the parameter back to the argument at the invocation site and gets the /// index to retrieve the updated arguments at the invocation. /// </summary> private TExpressionSyntax CreateNewArgumentExpression(SyntaxEditor editor, Dictionary<TIdentifierNameSyntax, IParameterSymbol> mappingDictionary, Dictionary<IParameterSymbol, int> parameterToArgumentMap, SeparatedSyntaxList<SyntaxNode> updatedInvocationArguments) { foreach (var (variable, mappedParameter) in mappingDictionary) { var parameterMapped = parameterToArgumentMap.TryGetValue(mappedParameter, out var index); if (parameterMapped) { var updatedInvocationArgument = updatedInvocationArguments[index]; var argumentExpression = _syntaxFacts.GetExpressionOfArgument(updatedInvocationArgument); var parenthesizedArgumentExpression = editor.Generator.AddParentheses(argumentExpression, includeElasticTrivia: false); editor.ReplaceNode(variable, parenthesizedArgumentExpression); } else if (mappedParameter.HasExplicitDefaultValue) { var generatedExpression = _service.GenerateExpressionFromOptionalParameter(mappedParameter); var parenthesizedGeneratedExpression = editor.Generator.AddParentheses(generatedExpression, includeElasticTrivia: false); editor.ReplaceNode(variable, parenthesizedGeneratedExpression); } } return (TExpressionSyntax)editor.GetChangedRoot(); } /// <summary> /// If the parameter is optional and the invocation does not specify the parameter, then /// a named argument needs to be introduced. /// </summary> private SeparatedSyntaxList<SyntaxNode> AddArgumentToArgumentList( SeparatedSyntaxList<SyntaxNode> invocationArguments, SyntaxNode newArgumentExpression, string parameterName, int insertionIndex, bool named) { var argument = named ? _generator.Argument(parameterName, RefKind.None, newArgumentExpression) : _generator.Argument(newArgumentExpression); return invocationArguments.Insert(insertionIndex, argument); } private bool ShouldArgumentBeNamed(Compilation compilation, SemanticModel semanticModel, SeparatedSyntaxList<SyntaxNode> invocationArguments, int methodInsertionIndex, CancellationToken cancellationToken) { var invocationInsertIndex = 0; foreach (var invocationArgument in invocationArguments) { var argumentParameter = _semanticFacts.FindParameterForArgument(semanticModel, invocationArgument, cancellationToken); if (argumentParameter is not null && ShouldParameterBeSkipped(compilation, argumentParameter)) { invocationInsertIndex++; } else { break; } } return invocationInsertIndex < methodInsertionIndex; } private static bool ShouldParameterBeSkipped(Compilation compilation, IParameterSymbol parameter) => !parameter.HasExplicitDefaultValue && !parameter.IsParams && !parameter.Type.Equals(compilation.GetTypeByMetadataName(typeof(CancellationToken)?.FullName!)); private void MapParameterToArgumentsAtInvocation( Dictionary<IParameterSymbol, int> mapping, SeparatedSyntaxList<SyntaxNode> arguments, SemanticModel invocationSemanticModel, CancellationToken cancellationToken) { for (var i = 0; i < arguments.Count; i++) { var argumentParameter = _semanticFacts.FindParameterForArgument(invocationSemanticModel, arguments[i], cancellationToken); if (argumentParameter is not null) { mapping[argumentParameter] = i; } } } /// <summary> /// Gets the matches of the expression and replaces them with the identifier. /// Special case for the original matching expression, if its parent is a LocalDeclarationStatement then it can /// be removed because assigning the local dec variable to a parameter is repetitive. Does not need a rename /// annotation since the user has already named the local declaration. /// Otherwise, it needs to have a rename annotation added to it because the new parameter gets a randomly /// generated name that the user can immediately change. /// </summary> private async Task UpdateExpressionInOriginalFunctionAsync(SyntaxEditor editor, CancellationToken cancellationToken) { var generator = editor.Generator; var matches = await FindMatchesAsync(cancellationToken).ConfigureAwait(false); var parameterName = await GetNewParameterNameAsync(cancellationToken).ConfigureAwait(false); var replacement = (TIdentifierNameSyntax)generator.IdentifierName(parameterName); foreach (var match in matches) { // Special case the removal of the originating expression to either remove the local declaration // or to add a rename annotation. if (!match.Equals(_expression)) { editor.ReplaceNode(match, replacement); } else { if (ShouldRemoveVariableDeclaratorContainingExpression(out _, out var localDeclaration)) { editor.RemoveNode(localDeclaration); } else { // Found the initially selected expression. Replace it with the new name we choose, but also annotate // that name with the RenameAnnotation so a rename session is started where the user can pick their // own preferred name. replacement = (TIdentifierNameSyntax)generator.IdentifierName(generator.Identifier(parameterName) .WithAdditionalAnnotations(RenameAnnotation.Create())); editor.ReplaceNode(match, replacement); } } } } /// <summary> /// Finds the matches of the expression within the same block. /// </summary> private async Task<IEnumerable<TExpressionSyntax>> FindMatchesAsync(CancellationToken cancellationToken) { if (!_allOccurrences) { return SpecializedCollections.SingletonEnumerable(_expression); } var syntaxFacts = _originalDocument.GetRequiredLanguageService<ISyntaxFactsService>(); var originalSemanticModel = await _originalDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var matches = from nodeInCurrent in _containerMethod.DescendantNodesAndSelf().OfType<TExpressionSyntax>() where NodeMatchesExpression(originalSemanticModel, nodeInCurrent, cancellationToken) select nodeInCurrent; return matches; } private bool NodeMatchesExpression(SemanticModel originalSemanticModel, TExpressionSyntax currentNode, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (currentNode == _expression) { return true; } return SemanticEquivalence.AreEquivalent( originalSemanticModel, originalSemanticModel, _expression, currentNode); } } } }
1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Features/VisualBasic/Portable/ConvertToInterpolatedString/VisualBasicConvertPlaceholderToInterpolatedStringRefactoringProvider.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.CodeRefactorings Imports Microsoft.CodeAnalysis.ConvertToInterpolatedString Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertToInterpolatedString <ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.ConvertPlaceholderToInterpolatedString), [Shared]> Partial Friend Class VisualBasicConvertPlaceholderToInterpolatedStringRefactoringProvider Inherits AbstractConvertPlaceholderToInterpolatedStringRefactoringProvider(Of InvocationExpressionSyntax, ExpressionSyntax, ArgumentSyntax, LiteralExpressionSyntax, ArgumentListSyntax) <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 Function GetInterpolatedString(text As String) As SyntaxNode Return TryCast(SyntaxFactory.ParseExpression("$" + text), InterpolatedStringExpressionSyntax) 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 System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.ConvertToInterpolatedString Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertToInterpolatedString <ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.ConvertPlaceholderToInterpolatedString), [Shared]> Partial Friend Class VisualBasicConvertPlaceholderToInterpolatedStringRefactoringProvider Inherits AbstractConvertPlaceholderToInterpolatedStringRefactoringProvider(Of InvocationExpressionSyntax, ExpressionSyntax, ArgumentSyntax, LiteralExpressionSyntax, ArgumentListSyntax, InterpolationSyntax) <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 Function GetInterpolatedString(text As String) As SyntaxNode Return TryCast(SyntaxFactory.ParseExpression("$" + text), InterpolatedStringExpressionSyntax) End Function End Class End Namespace
1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Workspaces/Core/Portable/FindSymbols/SyntaxTree/SyntaxTreeIndex_Persistence.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Storage; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal sealed partial class SyntaxTreeIndex : IObjectWritable { private const string PersistenceName = "<SyntaxTreeIndex>"; private static readonly Checksum SerializationFormatChecksum = Checksum.Create("25"); public readonly Checksum? Checksum; private static Task<SyntaxTreeIndex?> LoadAsync(Document document, Checksum checksum, CancellationToken cancellationToken) { var solution = document.Project.Solution; var database = solution.Options.GetPersistentStorageDatabase(); return LoadAsync(solution.Workspace.Services, DocumentKey.ToDocumentKey(document), checksum, database, GetStringTable(document.Project), cancellationToken); } public static async Task<SyntaxTreeIndex?> LoadAsync( HostWorkspaceServices services, DocumentKey documentKey, Checksum? checksum, StorageDatabase database, StringTable stringTable, CancellationToken cancellationToken) { try { var persistentStorageService = services.GetPersistentStorageService(database); var storage = await persistentStorageService.GetStorageAsync(documentKey.Project.Solution, checkBranchId: false, cancellationToken).ConfigureAwait(false); await using var _ = storage.ConfigureAwait(false); // attempt to load from persisted state using var stream = await storage.ReadStreamAsync(documentKey, PersistenceName, checksum, cancellationToken).ConfigureAwait(false); using var reader = ObjectReader.TryGetReader(stream, cancellationToken: cancellationToken); if (reader != null) return ReadFrom(stringTable, reader, checksum); } catch (Exception e) when (IOUtilities.IsNormalIOException(e)) { // Storage APIs can throw arbitrary exceptions. } return null; } public static async Task<Checksum> GetChecksumAsync( Document document, CancellationToken cancellationToken) { // Since we build the SyntaxTreeIndex from a SyntaxTree, we need our checksum to change // any time the SyntaxTree could have changed. Right now, that can only happen if the // text of the document changes, or the ParseOptions change. So we get the checksums // for both of those, and merge them together to make the final checksum. // // We also want the checksum to change any time our serialization format changes. If // the format has changed, all previous versions should be invalidated. var project = document.Project; var parseOptionsChecksum = project.State.GetParseOptionsChecksum(); var documentChecksumState = await document.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); var textChecksum = documentChecksumState.Text; return Checksum.Create(textChecksum, parseOptionsChecksum, SerializationFormatChecksum); } private async Task<bool> SaveAsync( Document document, CancellationToken cancellationToken) { var solution = document.Project.Solution; var persistentStorageService = solution.Workspace.Services.GetPersistentStorageService(solution.Options); try { var storage = await persistentStorageService.GetStorageAsync(SolutionKey.ToSolutionKey(solution), checkBranchId: false, cancellationToken).ConfigureAwait(false); await using var _ = storage.ConfigureAwait(false); using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken)) { WriteTo(writer); } stream.Position = 0; return await storage.WriteStreamAsync(document, PersistenceName, stream, this.Checksum, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (IOUtilities.IsNormalIOException(e)) { // Storage APIs can throw arbitrary exceptions. } return false; } private static async Task<bool> PrecalculatedAsync( Document document, Checksum checksum, CancellationToken cancellationToken) { var solution = document.Project.Solution; var persistentStorageService = solution.Workspace.Services.GetPersistentStorageService(solution.Options); // check whether we already have info for this document try { var storage = await persistentStorageService.GetStorageAsync(SolutionKey.ToSolutionKey(solution), checkBranchId: false, cancellationToken).ConfigureAwait(false); await using var _ = storage.ConfigureAwait(false); // Check if we've already stored a checksum and it matches the checksum we // expect. If so, we're already precalculated and don't have to recompute // this index. Otherwise if we don't have a checksum, or the checksums don't // match, go ahead and recompute it. return await storage.ChecksumMatchesAsync(document, PersistenceName, checksum, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (IOUtilities.IsNormalIOException(e)) { // Storage APIs can throw arbitrary exceptions. } return false; } bool IObjectWritable.ShouldReuseInSerialization => true; public void WriteTo(ObjectWriter writer) { _literalInfo.WriteTo(writer); _identifierInfo.WriteTo(writer); _contextInfo.WriteTo(writer); _declarationInfo.WriteTo(writer); _extensionMethodInfo.WriteTo(writer); if (_globalAliasInfo == null) { writer.WriteInt32(0); } else { writer.WriteInt32(_globalAliasInfo.Count); foreach (var (alias, name, arity) in _globalAliasInfo) { writer.WriteString(alias); writer.WriteString(name); writer.WriteInt32(arity); } } } private static SyntaxTreeIndex? ReadFrom( StringTable stringTable, ObjectReader reader, Checksum? checksum) { var literalInfo = LiteralInfo.TryReadFrom(reader); var identifierInfo = IdentifierInfo.TryReadFrom(reader); var contextInfo = ContextInfo.TryReadFrom(reader); var declarationInfo = DeclarationInfo.TryReadFrom(stringTable, reader); var extensionMethodInfo = ExtensionMethodInfo.TryReadFrom(reader); if (literalInfo == null || identifierInfo == null || contextInfo == null || declarationInfo == null || extensionMethodInfo == null) return null; var globalAliasInfoCount = reader.ReadInt32(); HashSet<(string alias, string name, int arity)>? globalAliasInfo = null; if (globalAliasInfoCount > 0) { globalAliasInfo = new HashSet<(string alias, string name, int arity)>(); for (var i = 0; i < globalAliasInfoCount; i++) { var alias = reader.ReadString(); var name = reader.ReadString(); var arity = reader.ReadInt32(); globalAliasInfo.Add((alias, name, arity)); } } return new SyntaxTreeIndex( checksum, literalInfo.Value, identifierInfo.Value, contextInfo.Value, declarationInfo.Value, extensionMethodInfo.Value, globalAliasInfo); } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Storage; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal sealed partial class SyntaxTreeIndex : IObjectWritable { private const string PersistenceName = "<SyntaxTreeIndex>"; private static readonly Checksum SerializationFormatChecksum = Checksum.Create("25"); public readonly Checksum? Checksum; private static Task<SyntaxTreeIndex?> LoadAsync(Document document, Checksum checksum, CancellationToken cancellationToken) { var solution = document.Project.Solution; var database = solution.Options.GetPersistentStorageDatabase(); return LoadAsync(solution.Workspace.Services, DocumentKey.ToDocumentKey(document), checksum, database, GetStringTable(document.Project), cancellationToken); } public static async Task<SyntaxTreeIndex?> LoadAsync( HostWorkspaceServices services, DocumentKey documentKey, Checksum? checksum, StorageDatabase database, StringTable stringTable, CancellationToken cancellationToken) { try { var persistentStorageService = services.GetPersistentStorageService(database); var storage = await persistentStorageService.GetStorageAsync(documentKey.Project.Solution, checkBranchId: false, cancellationToken).ConfigureAwait(false); await using var _ = storage.ConfigureAwait(false); // attempt to load from persisted state using var stream = await storage.ReadStreamAsync(documentKey, PersistenceName, checksum, cancellationToken).ConfigureAwait(false); using var reader = ObjectReader.TryGetReader(stream, cancellationToken: cancellationToken); if (reader != null) return ReadFrom(stringTable, reader, checksum); } catch (Exception e) when (IOUtilities.IsNormalIOException(e)) { // Storage APIs can throw arbitrary exceptions. } return null; } public static async Task<Checksum> GetChecksumAsync( Document document, CancellationToken cancellationToken) { // Since we build the SyntaxTreeIndex from a SyntaxTree, we need our checksum to change // any time the SyntaxTree could have changed. Right now, that can only happen if the // text of the document changes, or the ParseOptions change. So we get the checksums // for both of those, and merge them together to make the final checksum. // // We also want the checksum to change any time our serialization format changes. If // the format has changed, all previous versions should be invalidated. var project = document.Project; var parseOptionsChecksum = project.State.GetParseOptionsChecksum(); var documentChecksumState = await document.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); var textChecksum = documentChecksumState.Text; return Checksum.Create(textChecksum, parseOptionsChecksum, SerializationFormatChecksum); } private async Task<bool> SaveAsync( Document document, CancellationToken cancellationToken) { var solution = document.Project.Solution; var persistentStorageService = solution.Workspace.Services.GetPersistentStorageService(solution.Options); try { var storage = await persistentStorageService.GetStorageAsync(SolutionKey.ToSolutionKey(solution), checkBranchId: false, cancellationToken).ConfigureAwait(false); await using var _ = storage.ConfigureAwait(false); using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken)) { WriteTo(writer); } stream.Position = 0; return await storage.WriteStreamAsync(document, PersistenceName, stream, this.Checksum, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (IOUtilities.IsNormalIOException(e)) { // Storage APIs can throw arbitrary exceptions. } return false; } private static async Task<bool> PrecalculatedAsync( Document document, Checksum checksum, CancellationToken cancellationToken) { var solution = document.Project.Solution; var persistentStorageService = solution.Workspace.Services.GetPersistentStorageService(solution.Options); // check whether we already have info for this document try { var storage = await persistentStorageService.GetStorageAsync(SolutionKey.ToSolutionKey(solution), checkBranchId: false, cancellationToken).ConfigureAwait(false); await using var _ = storage.ConfigureAwait(false); // Check if we've already stored a checksum and it matches the checksum we // expect. If so, we're already precalculated and don't have to recompute // this index. Otherwise if we don't have a checksum, or the checksums don't // match, go ahead and recompute it. return await storage.ChecksumMatchesAsync(document, PersistenceName, checksum, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (IOUtilities.IsNormalIOException(e)) { // Storage APIs can throw arbitrary exceptions. } return false; } bool IObjectWritable.ShouldReuseInSerialization => true; public void WriteTo(ObjectWriter writer) { _literalInfo.WriteTo(writer); _identifierInfo.WriteTo(writer); _contextInfo.WriteTo(writer); _declarationInfo.WriteTo(writer); _extensionMethodInfo.WriteTo(writer); if (_globalAliasInfo == null) { writer.WriteInt32(0); } else { writer.WriteInt32(_globalAliasInfo.Count); foreach (var (alias, name, arity) in _globalAliasInfo) { writer.WriteString(alias); writer.WriteString(name); writer.WriteInt32(arity); } } } private static SyntaxTreeIndex? ReadFrom( StringTable stringTable, ObjectReader reader, Checksum? checksum) { var literalInfo = LiteralInfo.TryReadFrom(reader); var identifierInfo = IdentifierInfo.TryReadFrom(reader); var contextInfo = ContextInfo.TryReadFrom(reader); var declarationInfo = DeclarationInfo.TryReadFrom(stringTable, reader); var extensionMethodInfo = ExtensionMethodInfo.TryReadFrom(reader); if (literalInfo == null || identifierInfo == null || contextInfo == null || declarationInfo == null || extensionMethodInfo == null) return null; var globalAliasInfoCount = reader.ReadInt32(); HashSet<(string alias, string name, int arity)>? globalAliasInfo = null; if (globalAliasInfoCount > 0) { globalAliasInfo = new HashSet<(string alias, string name, int arity)>(); for (var i = 0; i < globalAliasInfoCount; i++) { var alias = reader.ReadString(); var name = reader.ReadString(); var arity = reader.ReadInt32(); globalAliasInfo.Add((alias, name, arity)); } } return new SyntaxTreeIndex( checksum, literalInfo.Value, identifierInfo.Value, contextInfo.Value, declarationInfo.Value, extensionMethodInfo.Value, globalAliasInfo); } } }
1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpSyntaxFacts.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.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Shared.Extensions; #if CODE_STYLE using Microsoft.CodeAnalysis.Internal.Editing; #else using Microsoft.CodeAnalysis.Editing; #endif namespace Microsoft.CodeAnalysis.CSharp.LanguageServices { internal class CSharpSyntaxFacts : AbstractSyntaxFacts, ISyntaxFacts { internal static readonly CSharpSyntaxFacts Instance = new(); protected CSharpSyntaxFacts() { } public bool IsCaseSensitive => true; public StringComparer StringComparer { get; } = StringComparer.Ordinal; public SyntaxTrivia ElasticMarker => SyntaxFactory.ElasticMarker; public SyntaxTrivia ElasticCarriageReturnLineFeed => SyntaxFactory.ElasticCarriageReturnLineFeed; public override ISyntaxKinds SyntaxKinds { get; } = CSharpSyntaxKinds.Instance; public bool SupportsIndexingInitializer(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp6; public bool SupportsThrowExpression(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7; public bool SupportsLocalFunctionDeclaration(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7; public bool SupportsRecord(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp9; public bool SupportsRecordStruct(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion.IsCSharp10OrAbove(); public SyntaxToken ParseToken(string text) => SyntaxFactory.ParseToken(text); public SyntaxTriviaList ParseLeadingTrivia(string text) => SyntaxFactory.ParseLeadingTrivia(text); public string EscapeIdentifier(string identifier) { var nullIndex = identifier.IndexOf('\0'); if (nullIndex >= 0) { identifier = identifier.Substring(0, nullIndex); } var needsEscaping = SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None; return needsEscaping ? "@" + identifier : identifier; } public bool IsVerbatimIdentifier(SyntaxToken token) => token.IsVerbatimIdentifier(); public bool IsOperator(SyntaxToken token) { var kind = token.Kind(); return (SyntaxFacts.IsAnyUnaryExpression(kind) && (token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsBinaryExpression(kind) && (token.Parent is BinaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax); } public bool IsReservedKeyword(SyntaxToken token) => SyntaxFacts.IsReservedKeyword(token.Kind()); public bool IsContextualKeyword(SyntaxToken token) => SyntaxFacts.IsContextualKeyword(token.Kind()); public bool IsPreprocessorKeyword(SyntaxToken token) => SyntaxFacts.IsPreprocessorKeyword(token.Kind()); public bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) => syntaxTree.IsPreProcessorDirectiveContext( position, syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true), cancellationToken); public bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken) { if (syntaxTree == null) { return false; } return syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken); } public bool IsDirective([NotNullWhen(true)] SyntaxNode? node) => node is DirectiveTriviaSyntax; public bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? node, out ExternalSourceInfo info) { if (node is LineDirectiveTriviaSyntax lineDirective) { if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword) { info = new ExternalSourceInfo(null, ends: true); return true; } else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken && lineDirective.Line.Value is int) { info = new ExternalSourceInfo((int)lineDirective.Line.Value, false); return true; } } info = default; return false; } public bool IsRightSideOfQualifiedName([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsRightSideOfQualifiedName(); } public void GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var qualifiedName = (QualifiedNameSyntax)node; left = qualifiedName.Left; operatorToken = qualifiedName.DotToken; right = qualifiedName.Right; } public bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsSimpleMemberAccessExpressionName(); } public bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => node?.Parent is MemberAccessExpressionSyntax memberAccess && memberAccess.Name == node; public bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsMemberBindingExpressionName(); } [return: NotNullIfNotNull("node")] public SyntaxNode? GetStandaloneExpression(SyntaxNode? node) => node is ExpressionSyntax expression ? SyntaxFactory.GetStandaloneExpression(expression) : node; public SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node) => node.GetRootConditionalAccessExpression(); public bool IsObjectCreationExpressionType([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.ObjectCreationExpression, out ObjectCreationExpressionSyntax? objectCreation) && objectCreation.Type == node; public bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node) => node is DeclarationExpressionSyntax; public bool IsAttributeName(SyntaxNode node) => SyntaxFacts.IsAttributeName(node); public bool IsAnonymousFunction([NotNullWhen(true)] SyntaxNode? node) { return node is ParenthesizedLambdaExpressionSyntax || node is SimpleLambdaExpressionSyntax || node is AnonymousMethodExpressionSyntax; } public bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node) => node is ArgumentSyntax arg && arg.NameColon != null; public bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node) => node.CheckParent<NameColonSyntax>(p => p.Name == node); public SyntaxToken? GetNameOfParameter(SyntaxNode? node) => (node as ParameterSyntax)?.Identifier; public SyntaxNode? GetDefaultOfParameter(SyntaxNode? node) => (node as ParameterSyntax)?.Default; public SyntaxNode? GetParameterList(SyntaxNode node) => node.GetParameterList(); public bool IsParameterList([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ParameterList, SyntaxKind.BracketedParameterList); public SyntaxToken GetIdentifierOfGenericName(SyntaxNode? genericName) { return genericName is GenericNameSyntax csharpGenericName ? csharpGenericName.Identifier : default; } public bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.UsingDirective, out UsingDirectiveSyntax? usingDirective) && usingDirective.Name == node; public bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node) => node is UsingDirectiveSyntax usingDirectiveNode && usingDirectiveNode.Alias != null; public void GetPartsOfUsingAliasDirective(SyntaxNode node, out SyntaxToken globalKeyword, out SyntaxToken alias, out SyntaxNode name) { var usingDirective = (UsingDirectiveSyntax)node; globalKeyword = usingDirective.GlobalKeyword; alias = usingDirective.Alias!.Name.Identifier; name = usingDirective.Name; } public bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node) => node is ForEachVariableStatementSyntax; public bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node) => node is AssignmentExpressionSyntax assignment && assignment.IsDeconstruction(); public Location GetDeconstructionReferenceLocation(SyntaxNode node) { return node switch { AssignmentExpressionSyntax assignment => assignment.Left.GetLocation(), ForEachVariableStatementSyntax @foreach => @foreach.Variable.GetLocation(), _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()), }; } public bool IsStatement([NotNullWhen(true)] SyntaxNode? node) => node is StatementSyntax; public bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node) => node is StatementSyntax; public bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node) { if (node is BlockSyntax || node is ArrowExpressionClauseSyntax) { return node.Parent is BaseMethodDeclarationSyntax || node.Parent is AccessorDeclarationSyntax; } return false; } public SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode? node) => (node as ReturnStatementSyntax)?.Expression; public bool IsThisConstructorInitializer(SyntaxToken token) => token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) && constructorInit.ThisOrBaseKeyword == token; public bool IsBaseConstructorInitializer(SyntaxToken token) => token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) && constructorInit.ThisOrBaseKeyword == token; public bool IsQueryKeyword(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.FromKeyword: case SyntaxKind.JoinKeyword: case SyntaxKind.LetKeyword: case SyntaxKind.OrderByKeyword: case SyntaxKind.WhereKeyword: case SyntaxKind.OnKeyword: case SyntaxKind.EqualsKeyword: case SyntaxKind.InKeyword: return token.Parent is QueryClauseSyntax; case SyntaxKind.ByKeyword: case SyntaxKind.GroupKeyword: case SyntaxKind.SelectKeyword: return token.Parent is SelectOrGroupClauseSyntax; case SyntaxKind.AscendingKeyword: case SyntaxKind.DescendingKeyword: return token.Parent is OrderingSyntax; case SyntaxKind.IntoKeyword: return token.Parent.IsKind(SyntaxKind.JoinIntoClause, SyntaxKind.QueryContinuation); default: return false; } } public bool IsThrowExpression(SyntaxNode node) => node.Kind() == SyntaxKind.ThrowExpression; public bool IsPredefinedType(SyntaxToken token) => TryGetPredefinedType(token, out _); public bool IsPredefinedType(SyntaxToken token, PredefinedType type) => TryGetPredefinedType(token, out var actualType) && actualType == type; public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type) { type = GetPredefinedType(token); return type != PredefinedType.None; } private static PredefinedType GetPredefinedType(SyntaxToken token) { return (SyntaxKind)token.RawKind switch { SyntaxKind.BoolKeyword => PredefinedType.Boolean, SyntaxKind.ByteKeyword => PredefinedType.Byte, SyntaxKind.SByteKeyword => PredefinedType.SByte, SyntaxKind.IntKeyword => PredefinedType.Int32, SyntaxKind.UIntKeyword => PredefinedType.UInt32, SyntaxKind.ShortKeyword => PredefinedType.Int16, SyntaxKind.UShortKeyword => PredefinedType.UInt16, SyntaxKind.LongKeyword => PredefinedType.Int64, SyntaxKind.ULongKeyword => PredefinedType.UInt64, SyntaxKind.FloatKeyword => PredefinedType.Single, SyntaxKind.DoubleKeyword => PredefinedType.Double, SyntaxKind.DecimalKeyword => PredefinedType.Decimal, SyntaxKind.StringKeyword => PredefinedType.String, SyntaxKind.CharKeyword => PredefinedType.Char, SyntaxKind.ObjectKeyword => PredefinedType.Object, SyntaxKind.VoidKeyword => PredefinedType.Void, _ => PredefinedType.None, }; } public bool IsPredefinedOperator(SyntaxToken token) => TryGetPredefinedOperator(token, out var actualOperator) && actualOperator != PredefinedOperator.None; public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op) => TryGetPredefinedOperator(token, out var actualOperator) && actualOperator == op; public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op) { op = GetPredefinedOperator(token); return op != PredefinedOperator.None; } private static PredefinedOperator GetPredefinedOperator(SyntaxToken token) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.PlusToken: case SyntaxKind.PlusEqualsToken: return PredefinedOperator.Addition; case SyntaxKind.MinusToken: case SyntaxKind.MinusEqualsToken: return PredefinedOperator.Subtraction; case SyntaxKind.AmpersandToken: case SyntaxKind.AmpersandEqualsToken: return PredefinedOperator.BitwiseAnd; case SyntaxKind.BarToken: case SyntaxKind.BarEqualsToken: return PredefinedOperator.BitwiseOr; case SyntaxKind.MinusMinusToken: return PredefinedOperator.Decrement; case SyntaxKind.PlusPlusToken: return PredefinedOperator.Increment; case SyntaxKind.SlashToken: case SyntaxKind.SlashEqualsToken: return PredefinedOperator.Division; case SyntaxKind.EqualsEqualsToken: return PredefinedOperator.Equality; case SyntaxKind.CaretToken: case SyntaxKind.CaretEqualsToken: return PredefinedOperator.ExclusiveOr; case SyntaxKind.GreaterThanToken: return PredefinedOperator.GreaterThan; case SyntaxKind.GreaterThanEqualsToken: return PredefinedOperator.GreaterThanOrEqual; case SyntaxKind.ExclamationEqualsToken: return PredefinedOperator.Inequality; case SyntaxKind.LessThanLessThanToken: case SyntaxKind.LessThanLessThanEqualsToken: return PredefinedOperator.LeftShift; case SyntaxKind.LessThanToken: return PredefinedOperator.LessThan; case SyntaxKind.LessThanEqualsToken: return PredefinedOperator.LessThanOrEqual; case SyntaxKind.AsteriskToken: case SyntaxKind.AsteriskEqualsToken: return PredefinedOperator.Multiplication; case SyntaxKind.PercentToken: case SyntaxKind.PercentEqualsToken: return PredefinedOperator.Modulus; case SyntaxKind.ExclamationToken: case SyntaxKind.TildeToken: return PredefinedOperator.Complement; case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: return PredefinedOperator.RightShift; } return PredefinedOperator.None; } public string GetText(int kind) => SyntaxFacts.GetText((SyntaxKind)kind); public bool IsIdentifierStartCharacter(char c) => SyntaxFacts.IsIdentifierStartCharacter(c); public bool IsIdentifierPartCharacter(char c) => SyntaxFacts.IsIdentifierPartCharacter(c); public bool IsIdentifierEscapeCharacter(char c) => c == '@'; public bool IsValidIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length; } public bool IsVerbatimIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier(); } public bool IsTypeCharacter(char c) => false; public bool IsStartOfUnicodeEscapeSequence(char c) => c == '\\'; public bool IsLiteral(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.NumericLiteralToken: case SyntaxKind.CharacterLiteralToken: case SyntaxKind.StringLiteralToken: case SyntaxKind.NullKeyword: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.InterpolatedStringStartToken: case SyntaxKind.InterpolatedStringEndToken: case SyntaxKind.InterpolatedVerbatimStringStartToken: case SyntaxKind.InterpolatedStringTextToken: return true; default: return false; } } public bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token) => token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken); public bool IsNumericLiteralExpression([NotNullWhen(true)] SyntaxNode? node) => node?.IsKind(SyntaxKind.NumericLiteralExpression) == true; public bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent) { var typedToken = token; var typedParent = parent; if (typedParent.IsKind(SyntaxKind.IdentifierName)) { TypeSyntax? declaredType = null; if (typedParent.IsParentKind(SyntaxKind.VariableDeclaration, out VariableDeclarationSyntax? varDecl)) { declaredType = varDecl.Type; } else if (typedParent.IsParentKind(SyntaxKind.FieldDeclaration, out FieldDeclarationSyntax? fieldDecl)) { declaredType = fieldDecl.Declaration.Type; } return declaredType == typedParent && typedToken.ValueText == "var"; } return false; } public bool IsTypeNamedDynamic(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent) { if (parent is ExpressionSyntax typedParent) { if (SyntaxFacts.IsInTypeOnlyContext(typedParent) && typedParent.IsKind(SyntaxKind.IdentifierName) && token.ValueText == "dynamic") { return true; } } return false; } public bool IsBindableToken(SyntaxToken token) { if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token)) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.DelegateKeyword: case SyntaxKind.VoidKeyword: return false; } return true; } // In the order by clause a comma might be bound to ThenBy or ThenByDescending if (token.Kind() == SyntaxKind.CommaToken && token.Parent.IsKind(SyntaxKind.OrderByClause)) { return true; } return false; } public void GetPartsOfConditionalAccessExpression( SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull) { var conditionalAccess = (ConditionalAccessExpressionSyntax)node; expression = conditionalAccess.Expression; operatorToken = conditionalAccess.OperatorToken; whenNotNull = conditionalAccess.WhenNotNull; } public bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node) => node is PostfixUnaryExpressionSyntax; public bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node) => node is MemberBindingExpressionSyntax; public bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => (node as MemberAccessExpressionSyntax)?.Kind() == SyntaxKind.PointerMemberAccessExpression; public bool IsSimpleName([NotNullWhen(true)] SyntaxNode? node) => node is SimpleNameSyntax; public void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity) { var simpleName = (SimpleNameSyntax)node; name = simpleName.Identifier.ValueText; arity = simpleName.Arity; } public bool LooksGeneric(SyntaxNode simpleName) => simpleName.IsKind(SyntaxKind.GenericName) || simpleName.GetLastToken().GetNextToken().Kind() == SyntaxKind.LessThanToken; public SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node) => (node as MemberBindingExpressionSyntax).GetParentConditionalAccessExpression()?.Expression; public SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node) => ((MemberBindingExpressionSyntax)node).Name; public SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode? node, bool allowImplicitTarget) => (node as MemberAccessExpressionSyntax)?.Expression; public void GetPartsOfElementAccessExpression(SyntaxNode? node, out SyntaxNode? expression, out SyntaxNode? argumentList) { var elementAccess = node as ElementAccessExpressionSyntax; expression = elementAccess?.Expression; argumentList = elementAccess?.ArgumentList; } public SyntaxNode? GetExpressionOfInterpolation(SyntaxNode? node) => (node as InterpolationSyntax)?.Expression; public bool IsInStaticContext(SyntaxNode node) => node.IsInStaticContext(); public bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node) => SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax); public bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.BaseList); public SyntaxNode? GetExpressionOfArgument(SyntaxNode? node) => (node as ArgumentSyntax)?.Expression; public RefKind GetRefKindOfArgument(SyntaxNode? node) => (node as ArgumentSyntax).GetRefKind(); public bool IsArgument([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Argument); public bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node) { return node is ArgumentSyntax argument && argument.RefOrOutKeyword.Kind() == SyntaxKind.None && argument.NameColon == null; } public bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsInConstantContext(); public bool IsInConstructor(SyntaxNode node) => node.GetAncestor<ConstructorDeclarationSyntax>() != null; public bool IsUnsafeContext(SyntaxNode node) => node.IsUnsafeContext(); public SyntaxNode GetNameOfAttribute(SyntaxNode node) => ((AttributeSyntax)node).Name; public SyntaxNode GetExpressionOfParenthesizedExpression(SyntaxNode node) => ((ParenthesizedExpressionSyntax)node).Expression; public bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node) => (node as IdentifierNameSyntax).IsAttributeNamedArgumentIdentifier(); public SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position) { if (root == null) { throw new ArgumentNullException(nameof(root)); } if (position < 0 || position > root.Span.End) { throw new ArgumentOutOfRangeException(nameof(position)); } return root .FindToken(position) .GetAncestors<SyntaxNode>() .FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax); } public SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node) => throw ExceptionUtilities.Unreachable; public SyntaxToken FindTokenOnLeftOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public SyntaxToken FindTokenOnRightOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IdentifierName) && node.IsParentKind(SyntaxKind.NameColon) && node.Parent.IsParentKind(SyntaxKind.Subpattern); public bool IsPropertyPatternClause(SyntaxNode node) => node.Kind() == SyntaxKind.PropertyPatternClause; public bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node) => IsMemberInitializerNamedAssignmentIdentifier(node, out _); public bool IsMemberInitializerNamedAssignmentIdentifier( [NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance) { initializedInstance = null; if (node is IdentifierNameSyntax identifier && identifier.IsLeftSideOfAssignExpression()) { if (identifier.Parent.IsParentKind(SyntaxKind.WithInitializerExpression)) { var withInitializer = identifier.Parent.GetRequiredParent(); initializedInstance = withInitializer.GetRequiredParent(); return true; } else if (identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression)) { var objectInitializer = identifier.Parent.GetRequiredParent(); if (objectInitializer.Parent is BaseObjectCreationExpressionSyntax) { initializedInstance = objectInitializer.Parent; return true; } else if (objectInitializer.IsParentKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment)) { initializedInstance = assignment.Left; return true; } } } return false; } public bool IsElementAccessExpression(SyntaxNode? node) => node.IsKind(SyntaxKind.ElementAccessExpression); [return: NotNullIfNotNull("node")] public SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false) => node.ConvertToSingleLine(useElasticTrivia); public void GetPartsOfParenthesizedExpression( SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen) { var parenthesizedExpression = (ParenthesizedExpressionSyntax)node; openParen = parenthesizedExpression.OpenParenToken; expression = parenthesizedExpression.Expression; closeParen = parenthesizedExpression.CloseParenToken; } public bool IsIndexerMemberCRef(SyntaxNode? node) => node.IsKind(SyntaxKind.IndexerMemberCref); public SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true) { Contract.ThrowIfNull(root, "root"); Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position"); var end = root.FullSpan.End; if (end == 0) { // empty file return null; } // make sure position doesn't touch end of root position = Math.Min(position, end - 1); var node = root.FindToken(position).Parent; while (node != null) { if (useFullSpan || node.Span.Contains(position)) { var kind = node.Kind(); if ((kind != SyntaxKind.GlobalStatement) && (kind != SyntaxKind.IncompleteMember) && (node is MemberDeclarationSyntax)) { return node; } } node = node.Parent; } return null; } public bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node) { return node is BaseMethodDeclarationSyntax || node is BasePropertyDeclarationSyntax || node is EnumMemberDeclarationSyntax || node is BaseFieldDeclarationSyntax; } public bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node) { return node is BaseNamespaceDeclarationSyntax || node is TypeDeclarationSyntax || node is EnumDeclarationSyntax; } private const string dotToken = "."; public string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null) { if (node == null) { return string.Empty; } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; // return type var memberDeclaration = node as MemberDeclarationSyntax; if ((options & DisplayNameOptions.IncludeType) != 0) { var type = memberDeclaration.GetMemberType(); if (type != null && !type.IsMissing) { builder.Append(type); builder.Append(' '); } } var names = ArrayBuilder<string?>.GetInstance(); // containing type(s) var parent = node.GetAncestor<TypeDeclarationSyntax>() ?? node.Parent; while (parent is TypeDeclarationSyntax) { names.Push(GetName(parent, options)); parent = parent.Parent; } // containing namespace(s) in source (if any) if ((options & DisplayNameOptions.IncludeNamespaces) != 0) { while (parent is BaseNamespaceDeclarationSyntax) { names.Add(GetName(parent, options)); parent = parent.Parent; } } while (!names.IsEmpty()) { var name = names.Pop(); if (name != null) { builder.Append(name); builder.Append(dotToken); } } // name (including generic type parameters) builder.Append(GetName(node, options)); // parameter list (if any) if ((options & DisplayNameOptions.IncludeParameters) != 0) { builder.Append(memberDeclaration.GetParameterList()); } return pooled.ToStringAndFree(); } private static string? GetName(SyntaxNode node, DisplayNameOptions options) { const string missingTokenPlaceholder = "?"; switch (node.Kind()) { case SyntaxKind.CompilationUnit: return null; case SyntaxKind.IdentifierName: var identifier = ((IdentifierNameSyntax)node).Identifier; return identifier.IsMissing ? missingTokenPlaceholder : identifier.Text; case SyntaxKind.IncompleteMember: return missingTokenPlaceholder; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return GetName(((BaseNamespaceDeclarationSyntax)node).Name, options); case SyntaxKind.QualifiedName: var qualified = (QualifiedNameSyntax)node; return GetName(qualified.Left, options) + dotToken + GetName(qualified.Right, options); } string? name = null; if (node is MemberDeclarationSyntax memberDeclaration) { if (memberDeclaration.Kind() == SyntaxKind.ConversionOperatorDeclaration) { name = (memberDeclaration as ConversionOperatorDeclarationSyntax)?.Type.ToString(); } else { var nameToken = memberDeclaration.GetNameToken(); if (nameToken != default) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; if (memberDeclaration.Kind() == SyntaxKind.DestructorDeclaration) { name = "~" + name; } if ((options & DisplayNameOptions.IncludeTypeParameters) != 0) { var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append(name); AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()); name = pooled.ToStringAndFree(); } } else { Debug.Assert(memberDeclaration.Kind() == SyntaxKind.IncompleteMember); name = "?"; } } } else { if (node is VariableDeclaratorSyntax fieldDeclarator) { var nameToken = fieldDeclarator.Identifier; if (nameToken != default) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; } } } Debug.Assert(name != null, "Unexpected node type " + node.Kind()); return name; } private static void AppendTypeParameterList(StringBuilder builder, TypeParameterListSyntax typeParameterList) { if (typeParameterList != null && typeParameterList.Parameters.Count > 0) { builder.Append('<'); builder.Append(typeParameterList.Parameters[0].Identifier.ValueText); for (var i = 1; i < typeParameterList.Parameters.Count; i++) { builder.Append(", "); builder.Append(typeParameterList.Parameters[i].Identifier.ValueText); } builder.Append('>'); } } public List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root) { var list = new List<SyntaxNode>(); AppendMembers(root, list, topLevel: true, methodLevel: true); return list; } public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root) { var list = new List<SyntaxNode>(); AppendMembers(root, list, topLevel: false, methodLevel: true); return list; } public bool IsClassDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Kind() == SyntaxKind.ClassDeclaration; public bool IsNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node) => node is BaseNamespaceDeclarationSyntax; public SyntaxNode? GetNameOfNamespaceDeclaration(SyntaxNode? node) => (node as BaseNamespaceDeclarationSyntax)?.Name; public SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration) => ((TypeDeclarationSyntax)typeDeclaration).Members; public SyntaxList<SyntaxNode> GetMembersOfNamespaceDeclaration(SyntaxNode namespaceDeclaration) => ((BaseNamespaceDeclarationSyntax)namespaceDeclaration).Members; public SyntaxList<SyntaxNode> GetMembersOfCompilationUnit(SyntaxNode compilationUnit) => ((CompilationUnitSyntax)compilationUnit).Members; public SyntaxList<SyntaxNode> GetImportsOfNamespaceDeclaration(SyntaxNode namespaceDeclaration) => ((BaseNamespaceDeclarationSyntax)namespaceDeclaration).Usings; public SyntaxList<SyntaxNode> GetImportsOfCompilationUnit(SyntaxNode compilationUnit) => ((CompilationUnitSyntax)compilationUnit).Usings; private void AppendMembers(SyntaxNode? node, List<SyntaxNode> list, bool topLevel, bool methodLevel) { Debug.Assert(topLevel || methodLevel); foreach (var member in node.GetMembers()) { if (IsTopLevelNodeWithMembers(member)) { if (topLevel) { list.Add(member); } AppendMembers(member, list, topLevel, methodLevel); continue; } if (methodLevel && IsMethodLevelMember(member)) { list.Add(member); } } } public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node) { if (node.Span.IsEmpty) { return default; } var member = GetContainingMemberDeclaration(node, node.SpanStart); if (member == null) { return default; } // TODO: currently we only support method for now if (member is BaseMethodDeclarationSyntax method) { if (method.Body == null) { return default; } return GetBlockBodySpan(method.Body); } return default; } public bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span) { switch (node) { case ConstructorDeclarationSyntax constructor: return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) || (constructor.Initializer != null && constructor.Initializer.Span.Contains(span)); case BaseMethodDeclarationSyntax method: return method.Body != null && GetBlockBodySpan(method.Body).Contains(span); case BasePropertyDeclarationSyntax property: return property.AccessorList != null && property.AccessorList.Span.Contains(span); case EnumMemberDeclarationSyntax @enum: return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span); case BaseFieldDeclarationSyntax field: return field.Declaration != null && field.Declaration.Span.Contains(span); } return false; } private static TextSpan GetBlockBodySpan(BlockSyntax body) => TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart); public SyntaxNode? TryGetBindableParent(SyntaxToken token) { var node = token.Parent; while (node != null) { var parent = node.Parent; // If this node is on the left side of a member access expression, don't ascend // further or we'll end up binding to something else. if (parent is MemberAccessExpressionSyntax memberAccess) { if (memberAccess.Expression == node) { break; } } // If this node is on the left side of a qualified name, don't ascend // further or we'll end up binding to something else. if (parent is QualifiedNameSyntax qualifiedName) { if (qualifiedName.Left == node) { break; } } // If this node is on the left side of a alias-qualified name, don't ascend // further or we'll end up binding to something else. if (parent is AliasQualifiedNameSyntax aliasQualifiedName) { if (aliasQualifiedName.Alias == node) { break; } } // If this node is the type of an object creation expression, return the // object creation expression. if (parent is ObjectCreationExpressionSyntax objectCreation) { if (objectCreation.Type == node) { node = parent; break; } } // The inside of an interpolated string is treated as its own token so we // need to force navigation to the parent expression syntax. if (node is InterpolatedStringTextSyntax && parent is InterpolatedStringExpressionSyntax) { node = parent; break; } // If this node is not parented by a name, we're done. if (!(parent is NameSyntax)) { break; } node = parent; } if (node is VarPatternSyntax) { return node; } // Patterns are never bindable (though their constituent types/exprs may be). return node is PatternSyntax ? null : node; } public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken) { if (root is not CompilationUnitSyntax compilationUnit) { return SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } var constructors = new List<SyntaxNode>(); AppendConstructors(compilationUnit.Members, constructors, cancellationToken); return constructors; } private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); switch (member) { case ConstructorDeclarationSyntax constructor: constructors.Add(constructor); continue; case BaseNamespaceDeclarationSyntax @namespace: AppendConstructors(@namespace.Members, constructors, cancellationToken); break; case ClassDeclarationSyntax @class: AppendConstructors(@class.Members, constructors, cancellationToken); break; case RecordDeclarationSyntax record: AppendConstructors(record.Members, constructors, cancellationToken); break; case StructDeclarationSyntax @struct: AppendConstructors(@struct.Members, constructors, cancellationToken); break; } } } public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace) { if (token.Kind() == SyntaxKind.CloseBraceToken) { var tuple = token.Parent.GetBraces(); openBrace = tuple.openBrace; return openBrace.Kind() == SyntaxKind.OpenBraceToken; } openBrace = default; return false; } public TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false); if (trivia.Kind() == SyntaxKind.DisabledTextTrivia) { return trivia.FullSpan; } var token = syntaxTree.FindTokenOrEndToken(position, cancellationToken); if (token.Kind() == SyntaxKind.EndOfFileToken) { var triviaList = token.LeadingTrivia; foreach (var triviaTok in triviaList.Reverse()) { if (triviaTok.Span.Contains(position)) { return default; } if (triviaTok.Span.End < position) { if (!triviaTok.HasStructure) { return default; } var structure = triviaTok.GetStructure(); if (structure is BranchingDirectiveTriviaSyntax branch) { return !branch.IsActive || !branch.BranchTaken ? TextSpan.FromBounds(branch.FullSpan.Start, position) : default; } } } } return default; } public string GetNameForArgument(SyntaxNode? argument) => (argument as ArgumentSyntax)?.NameColon?.Name.Identifier.ValueText ?? string.Empty; public string GetNameForAttributeArgument(SyntaxNode? argument) => (argument as AttributeArgumentSyntax)?.NameEquals?.Name.Identifier.ValueText ?? string.Empty; public bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfDot(); public SyntaxNode? GetRightSideOfDot(SyntaxNode? node) { return (node as QualifiedNameSyntax)?.Right ?? (node as MemberAccessExpressionSyntax)?.Name; } public SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget) { return (node as QualifiedNameSyntax)?.Left ?? (node as MemberAccessExpressionSyntax)?.Expression; } public bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node) => (node as NameSyntax).IsLeftSideOfExplicitInterfaceSpecifier(); public bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfAssignExpression(); public bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfAnyAssignExpression(); public bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfCompoundAssignExpression(); public SyntaxNode? GetRightHandSideOfAssignment(SyntaxNode? node) => (node as AssignmentExpressionSyntax)?.Right; public bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator, out AnonymousObjectMemberDeclaratorSyntax? anonObject) && anonObject.NameEquals == null; public bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.PostIncrementExpression) || node.IsParentKind(SyntaxKind.PreIncrementExpression); public static bool IsOperandOfDecrementExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.PostDecrementExpression) || node.IsParentKind(SyntaxKind.PreDecrementExpression); public bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node) => IsOperandOfIncrementExpression(node) || IsOperandOfDecrementExpression(node); public SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString) => ((InterpolatedStringExpressionSyntax)interpolatedString).Contents; public bool IsVerbatimStringLiteral(SyntaxToken token) => token.IsVerbatimStringLiteral(); public bool IsNumericLiteral(SyntaxToken token) => token.Kind() == SyntaxKind.NumericLiteralToken; public void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList) { var invocation = (InvocationExpressionSyntax)node; expression = invocation.Expression; argumentList = invocation.ArgumentList; } public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode? invocationExpression) => GetArgumentsOfArgumentList((invocationExpression as InvocationExpressionSyntax)?.ArgumentList); public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode? objectCreationExpression) => GetArgumentsOfArgumentList((objectCreationExpression as BaseObjectCreationExpressionSyntax)?.ArgumentList); public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode? argumentList) => (argumentList as BaseArgumentListSyntax)?.Arguments ?? default; public SyntaxNode GetArgumentListOfInvocationExpression(SyntaxNode invocationExpression) => ((InvocationExpressionSyntax)invocationExpression).ArgumentList; public SyntaxNode? GetArgumentListOfObjectCreationExpression(SyntaxNode objectCreationExpression) => ((ObjectCreationExpressionSyntax)objectCreationExpression)!.ArgumentList; public bool IsRegularComment(SyntaxTrivia trivia) => trivia.IsRegularComment(); public bool IsDocumentationComment(SyntaxTrivia trivia) => trivia.IsDocComment(); public bool IsElastic(SyntaxTrivia trivia) => trivia.IsElastic(); public bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes) => trivia.IsPragmaDirective(out isDisable, out isActive, out errorCodes); public bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.DocumentationCommentExteriorTrivia; public bool IsDocumentationComment(SyntaxNode node) => SyntaxFacts.IsDocumentationCommentTrivia(node.Kind()); public bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node) { return node.IsKind(SyntaxKind.UsingDirective) || node.IsKind(SyntaxKind.ExternAliasDirective); } public bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node) => IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword); public bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node) => IsGlobalAttribute(node, SyntaxKind.ModuleKeyword); private static bool IsGlobalAttribute([NotNullWhen(true)] SyntaxNode? node, SyntaxKind attributeTarget) => node.IsKind(SyntaxKind.Attribute) && node.Parent.IsKind(SyntaxKind.AttributeList, out AttributeListSyntax? attributeList) && attributeList.Target?.Identifier.Kind() == attributeTarget; private static bool IsMemberDeclaration(SyntaxNode node) { // From the C# language spec: // class-member-declaration: // constant-declaration // field-declaration // method-declaration // property-declaration // event-declaration // indexer-declaration // operator-declaration // constructor-declaration // destructor-declaration // static-constructor-declaration // type-declaration switch (node.Kind()) { // Because fields declarations can define multiple symbols "public int a, b;" // We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name. case SyntaxKind.VariableDeclarator: return node.Parent.IsParentKind(SyntaxKind.FieldDeclaration) || node.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration); case SyntaxKind.FieldDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.PropertyDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: return true; default: return false; } } public bool IsDeclaration(SyntaxNode node) => SyntaxFacts.IsNamespaceMemberDeclaration(node.Kind()) || IsMemberDeclaration(node); public bool IsTypeDeclaration(SyntaxNode node) => SyntaxFacts.IsTypeDeclaration(node.Kind()); public SyntaxNode? GetObjectCreationInitializer(SyntaxNode node) => ((ObjectCreationExpressionSyntax)node).Initializer; public SyntaxNode GetObjectCreationType(SyntaxNode node) => ((ObjectCreationExpressionSyntax)node).Type; public bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement) => statement.IsKind(SyntaxKind.ExpressionStatement, out ExpressionStatementSyntax? exprStatement) && exprStatement.Expression.IsKind(SyntaxKind.SimpleAssignmentExpression); public void GetPartsOfAssignmentStatement( SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { GetPartsOfAssignmentExpressionOrStatement( ((ExpressionStatementSyntax)statement).Expression, out left, out operatorToken, out right); } public void GetPartsOfAssignmentExpressionOrStatement( SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var expression = statement; if (statement is ExpressionStatementSyntax expressionStatement) { expression = expressionStatement.Expression; } var assignment = (AssignmentExpressionSyntax)expression; left = assignment.Left; operatorToken = assignment.OperatorToken; right = assignment.Right; } public SyntaxNode GetNameOfMemberAccessExpression(SyntaxNode memberAccessExpression) => ((MemberAccessExpressionSyntax)memberAccessExpression).Name; public void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name) { var memberAccess = (MemberAccessExpressionSyntax)node; expression = memberAccess.Expression; operatorToken = memberAccess.OperatorToken; name = memberAccess.Name; } public SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node) => ((SimpleNameSyntax)node).Identifier; public SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node) => ((VariableDeclaratorSyntax)node).Identifier; public SyntaxToken GetIdentifierOfParameter(SyntaxNode node) => ((ParameterSyntax)node).Identifier; public SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node) => node switch { BaseTypeDeclarationSyntax typeDecl => typeDecl.Identifier, DelegateDeclarationSyntax delegateDecl => delegateDecl.Identifier, _ => throw ExceptionUtilities.UnexpectedValue(node), }; public SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node) => ((IdentifierNameSyntax)node).Identifier; public bool IsLocalFunctionStatement([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.LocalFunctionStatement); public bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement) { return ((LocalDeclarationStatementSyntax)localDeclarationStatement).Declaration.Variables.Contains( (VariableDeclaratorSyntax)declarator); } public bool AreEquivalent(SyntaxToken token1, SyntaxToken token2) => SyntaxFactory.AreEquivalent(token1, token2); public bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2) => SyntaxFactory.AreEquivalent(node1, node2); public bool IsExpressionOfInvocationExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as InvocationExpressionSyntax)?.Expression == node; public bool IsExpressionOfAwaitExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as AwaitExpressionSyntax)?.Expression == node; public bool IsExpressionOfMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as MemberAccessExpressionSyntax)?.Expression == node; public static SyntaxNode GetExpressionOfInvocationExpression(SyntaxNode node) => ((InvocationExpressionSyntax)node).Expression; public SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node) => ((AwaitExpressionSyntax)node).Expression; public bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node) => node?.Parent is ForEachStatementSyntax foreachStatement && foreachStatement.Expression == node; public SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node) => ((ExpressionStatementSyntax)node).Expression; public bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node) => node is BinaryExpressionSyntax; public bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IsExpression); public void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var binaryExpression = (BinaryExpressionSyntax)node; left = binaryExpression.Left; operatorToken = binaryExpression.OperatorToken; right = binaryExpression.Right; } public void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse) { var conditionalExpression = (ConditionalExpressionSyntax)node; condition = conditionalExpression.Condition; whenTrue = conditionalExpression.WhenTrue; whenFalse = conditionalExpression.WhenFalse; } [return: NotNullIfNotNull("node")] public SyntaxNode? WalkDownParentheses(SyntaxNode? node) => (node as ExpressionSyntax)?.WalkDownParentheses() ?? node; public void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node, out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode { var tupleExpression = (TupleExpressionSyntax)node; openParen = tupleExpression.OpenParenToken; arguments = (SeparatedSyntaxList<TArgumentSyntax>)(SeparatedSyntaxList<SyntaxNode>)tupleExpression.Arguments; closeParen = tupleExpression.CloseParenToken; } public SyntaxNode GetOperandOfPrefixUnaryExpression(SyntaxNode node) => ((PrefixUnaryExpressionSyntax)node).Operand; public SyntaxToken GetOperatorTokenOfPrefixUnaryExpression(SyntaxNode node) => ((PrefixUnaryExpressionSyntax)node).OperatorToken; public SyntaxNode? GetNextExecutableStatement(SyntaxNode statement) => ((StatementSyntax)statement).GetNextStatement(); public override bool IsPreprocessorDirective(SyntaxTrivia trivia) => SyntaxFacts.IsPreprocessorDirective(trivia.Kind()); public bool IsOnTypeHeader(SyntaxNode root, int position, bool fullHeader, [NotNullWhen(true)] out SyntaxNode? typeDeclaration) { var node = TryGetAncestorForLocation<BaseTypeDeclarationSyntax>(root, position); typeDeclaration = node; if (node == null) return false; var lastToken = (node as TypeDeclarationSyntax)?.TypeParameterList?.GetLastToken() ?? node.Identifier; if (fullHeader) lastToken = node.BaseList?.GetLastToken() ?? lastToken; return IsOnHeader(root, position, node, lastToken); } public bool IsOnPropertyDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? propertyDeclaration) { var node = TryGetAncestorForLocation<PropertyDeclarationSyntax>(root, position); propertyDeclaration = node; if (propertyDeclaration == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.Identifier); } public bool IsOnParameterHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? parameter) { var node = TryGetAncestorForLocation<ParameterSyntax>(root, position); parameter = node; if (parameter == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node); } public bool IsOnMethodHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? method) { var node = TryGetAncestorForLocation<MethodDeclarationSyntax>(root, position); method = node; if (method == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.ParameterList); } public bool IsOnLocalFunctionHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localFunction) { var node = TryGetAncestorForLocation<LocalFunctionStatementSyntax>(root, position); localFunction = node; if (localFunction == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.ParameterList); } public bool IsOnLocalDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localDeclaration) { var node = TryGetAncestorForLocation<LocalDeclarationStatementSyntax>(root, position); localDeclaration = node; if (localDeclaration == null) { return false; } var initializersExpressions = node!.Declaration.Variables .Where(v => v.Initializer != null) .SelectAsArray(initializedV => initializedV.Initializer!.Value); return IsOnHeader(root, position, node, node, holes: initializersExpressions); } public bool IsOnIfStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? ifStatement) { var node = TryGetAncestorForLocation<IfStatementSyntax>(root, position); ifStatement = node; if (ifStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsOnWhileStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? whileStatement) { var node = TryGetAncestorForLocation<WhileStatementSyntax>(root, position); whileStatement = node; if (whileStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsOnForeachHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? foreachStatement) { var node = TryGetAncestorForLocation<ForEachStatementSyntax>(root, position); foreachStatement = node; if (foreachStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration) { var token = root.FindToken(position); var typeDecl = token.GetAncestor<TypeDeclarationSyntax>(); typeDeclaration = typeDecl; if (typeDecl == null) { return false; } RoslynDebug.AssertNotNull(typeDeclaration); if (position < typeDecl.OpenBraceToken.Span.End || position > typeDecl.CloseBraceToken.Span.Start) { return false; } var line = sourceText.Lines.GetLineFromPosition(position); if (!line.IsEmptyOrWhitespace()) { return false; } var member = typeDecl.Members.FirstOrDefault(d => d.FullSpan.Contains(position)); if (member == null) { // There are no members, or we're after the last member. return true; } else { // We're within a member. Make sure we're in the leading whitespace of // the member. if (position < member.SpanStart) { foreach (var trivia in member.GetLeadingTrivia()) { if (!trivia.IsWhitespaceOrEndOfLine()) { return false; } if (trivia.FullSpan.Contains(position)) { return true; } } } } return false; } protected override bool ContainsInterleavedDirective(TextSpan span, SyntaxToken token, CancellationToken cancellationToken) => token.ContainsInterleavedDirective(span, cancellationToken); public SyntaxTokenList GetModifiers(SyntaxNode? node) => node.GetModifiers(); public SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers) => node.WithModifiers(modifiers); public bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node) => node is LiteralExpressionSyntax; public SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node) => ((LocalDeclarationStatementSyntax)node).Declaration.Variables; public SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node) => ((VariableDeclaratorSyntax)node).Initializer; public SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node) => ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)node).Parent!).Type; public SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node) => ((EqualsValueClauseSyntax?)node)?.Value; public bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Block); public bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Block, SyntaxKind.SwitchSection, SyntaxKind.CompilationUnit); public IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node) { return node switch { BlockSyntax block => block.Statements, SwitchSectionSyntax switchSection => switchSection.Statements, CompilationUnitSyntax compilationUnit => compilationUnit.Members.OfType<GlobalStatementSyntax>().SelectAsArray(globalStatement => globalStatement.Statement), _ => throw ExceptionUtilities.UnexpectedValue(node), }; } public SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes) => nodes.FindInnermostCommonNode(node => IsExecutableBlock(node)); public bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node) => IsExecutableBlock(node) || node.IsEmbeddedStatementOwner(); public IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node) { if (IsExecutableBlock(node)) return GetExecutableBlockStatements(node); else if (node.GetEmbeddedStatement() is { } embeddedStatement) return ImmutableArray.Create<SyntaxNode>(embeddedStatement); else return ImmutableArray<SyntaxNode>.Empty; } public bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node) => node is CastExpressionSyntax; public bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node) => node is CastExpressionSyntax; public void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression) { var cast = (CastExpressionSyntax)node; type = cast.Type; expression = cast.Expression; } public SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token) { if (token.Kind() == SyntaxKind.OverrideKeyword && token.Parent is MemberDeclarationSyntax member) { return member.GetNameToken(); } return null; } public override SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node) => node.GetAttributeLists(); public override bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.XmlElement, out XmlElementSyntax? xmlElement) && xmlElement.StartTag.Name.LocalName.ValueText == DocumentationCommentXmlNames.ParameterElementName; public override SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia) { if (trivia.GetStructure() is DocumentationCommentTriviaSyntax documentationCommentTrivia) { return documentationCommentTrivia.Content; } throw ExceptionUtilities.UnexpectedValue(trivia.Kind()); } public override bool CanHaveAccessibility(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return true; case SyntaxKind.VariableDeclaration: case SyntaxKind.VariableDeclarator: var declarationKind = this.GetDeclarationKind(declaration); return declarationKind == DeclarationKind.Field || declarationKind == DeclarationKind.Event; case SyntaxKind.ConstructorDeclaration: // Static constructor can't have accessibility return !((ConstructorDeclarationSyntax)declaration).Modifiers.Any(SyntaxKind.StaticKeyword); case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; if (method.ExplicitInterfaceSpecifier != null) { // explicit interface methods can't have accessibility. return false; } if (method.Modifiers.Any(SyntaxKind.PartialKeyword)) { // partial methods can't have accessibility modifiers. return false; } return true; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; default: return false; } } public override Accessibility GetAccessibility(SyntaxNode declaration) { if (!CanHaveAccessibility(declaration)) { return Accessibility.NotApplicable; } var modifierTokens = GetModifierTokens(declaration); GetAccessibilityAndModifiers(modifierTokens, out var accessibility, out _, out _); return accessibility; } public override void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers modifiers, out bool isDefault) { accessibility = Accessibility.NotApplicable; modifiers = DeclarationModifiers.None; isDefault = false; foreach (var token in modifierList) { accessibility = (token.Kind(), accessibility) switch { (SyntaxKind.PublicKeyword, _) => Accessibility.Public, (SyntaxKind.PrivateKeyword, Accessibility.Protected) => Accessibility.ProtectedAndInternal, (SyntaxKind.PrivateKeyword, _) => Accessibility.Private, (SyntaxKind.InternalKeyword, Accessibility.Protected) => Accessibility.ProtectedOrInternal, (SyntaxKind.InternalKeyword, _) => Accessibility.Internal, (SyntaxKind.ProtectedKeyword, Accessibility.Private) => Accessibility.ProtectedAndInternal, (SyntaxKind.ProtectedKeyword, Accessibility.Internal) => Accessibility.ProtectedOrInternal, (SyntaxKind.ProtectedKeyword, _) => Accessibility.Protected, _ => accessibility, }; modifiers |= token.Kind() switch { SyntaxKind.AbstractKeyword => DeclarationModifiers.Abstract, SyntaxKind.NewKeyword => DeclarationModifiers.New, SyntaxKind.OverrideKeyword => DeclarationModifiers.Override, SyntaxKind.VirtualKeyword => DeclarationModifiers.Virtual, SyntaxKind.StaticKeyword => DeclarationModifiers.Static, SyntaxKind.AsyncKeyword => DeclarationModifiers.Async, SyntaxKind.ConstKeyword => DeclarationModifiers.Const, SyntaxKind.ReadOnlyKeyword => DeclarationModifiers.ReadOnly, SyntaxKind.SealedKeyword => DeclarationModifiers.Sealed, SyntaxKind.UnsafeKeyword => DeclarationModifiers.Unsafe, SyntaxKind.PartialKeyword => DeclarationModifiers.Partial, SyntaxKind.RefKeyword => DeclarationModifiers.Ref, SyntaxKind.VolatileKeyword => DeclarationModifiers.Volatile, SyntaxKind.ExternKeyword => DeclarationModifiers.Extern, _ => DeclarationModifiers.None, }; isDefault |= token.Kind() == SyntaxKind.DefaultKeyword; } } public override SyntaxTokenList GetModifierTokens(SyntaxNode? declaration) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.Modifiers, ParameterSyntax parameter => parameter.Modifiers, LocalDeclarationStatementSyntax localDecl => localDecl.Modifiers, LocalFunctionStatementSyntax localFunc => localFunc.Modifiers, AccessorDeclarationSyntax accessor => accessor.Modifiers, VariableDeclarationSyntax varDecl => GetModifierTokens(varDecl.Parent), VariableDeclaratorSyntax varDecl => GetModifierTokens(varDecl.Parent), AnonymousFunctionExpressionSyntax anonymous => anonymous.Modifiers, _ => default, }; public override DeclarationKind GetDeclarationKind(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: return DeclarationKind.Class; case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: return DeclarationKind.Struct; case SyntaxKind.InterfaceDeclaration: return DeclarationKind.Interface; case SyntaxKind.EnumDeclaration: return DeclarationKind.Enum; case SyntaxKind.DelegateDeclaration: return DeclarationKind.Delegate; case SyntaxKind.MethodDeclaration: return DeclarationKind.Method; case SyntaxKind.OperatorDeclaration: return DeclarationKind.Operator; case SyntaxKind.ConversionOperatorDeclaration: return DeclarationKind.ConversionOperator; case SyntaxKind.ConstructorDeclaration: return DeclarationKind.Constructor; case SyntaxKind.DestructorDeclaration: return DeclarationKind.Destructor; case SyntaxKind.PropertyDeclaration: return DeclarationKind.Property; case SyntaxKind.IndexerDeclaration: return DeclarationKind.Indexer; case SyntaxKind.EventDeclaration: return DeclarationKind.CustomEvent; case SyntaxKind.EnumMemberDeclaration: return DeclarationKind.EnumMember; case SyntaxKind.CompilationUnit: return DeclarationKind.CompilationUnit; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return DeclarationKind.Namespace; case SyntaxKind.UsingDirective: return DeclarationKind.NamespaceImport; case SyntaxKind.Parameter: return DeclarationKind.Parameter; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return DeclarationKind.LambdaExpression; case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)declaration; if (fd.Declaration != null && fd.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Field; } else { return DeclarationKind.None; } case SyntaxKind.EventFieldDeclaration: var ef = (EventFieldDeclarationSyntax)declaration; if (ef.Declaration != null && ef.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Event; } else { return DeclarationKind.None; } case SyntaxKind.LocalDeclarationStatement: var ld = (LocalDeclarationStatementSyntax)declaration; if (ld.Declaration != null && ld.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Variable; } else { return DeclarationKind.None; } case SyntaxKind.VariableDeclaration: { var vd = (VariableDeclarationSyntax)declaration; if (vd.Variables.Count == 1 && vd.Parent == null) { // this node is the declaration if it contains only one variable and has no parent. return DeclarationKind.Variable; } else { return DeclarationKind.None; } } case SyntaxKind.VariableDeclarator: { var vd = declaration.Parent as VariableDeclarationSyntax; // this node is considered the declaration if it is one among many, or it has no parent if (vd == null || vd.Variables.Count > 1) { if (ParentIsFieldDeclaration(vd)) { return DeclarationKind.Field; } else if (ParentIsEventFieldDeclaration(vd)) { return DeclarationKind.Event; } else { return DeclarationKind.Variable; } } break; } case SyntaxKind.AttributeList: var list = (AttributeListSyntax)declaration; if (list.Attributes.Count == 1) { return DeclarationKind.Attribute; } break; case SyntaxKind.Attribute: if (declaration.Parent is not AttributeListSyntax parentList || parentList.Attributes.Count > 1) { return DeclarationKind.Attribute; } break; case SyntaxKind.GetAccessorDeclaration: return DeclarationKind.GetAccessor; case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: return DeclarationKind.SetAccessor; case SyntaxKind.AddAccessorDeclaration: return DeclarationKind.AddAccessor; case SyntaxKind.RemoveAccessorDeclaration: return DeclarationKind.RemoveAccessor; } return DeclarationKind.None; } internal static bool ParentIsFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.FieldDeclaration) ?? false; internal static bool ParentIsEventFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.EventFieldDeclaration) ?? false; internal static bool ParentIsLocalDeclarationStatement([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.LocalDeclarationStatement) ?? false; public bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IsPatternExpression); public void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right) { var isPatternExpression = (IsPatternExpressionSyntax)node; left = isPatternExpression.Expression; isToken = isPatternExpression.IsKeyword; right = isPatternExpression.Pattern; } public bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node) => node is PatternSyntax; public bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ConstantPattern); public bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.DeclarationPattern); public bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.RecursivePattern); public bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.VarPattern); public SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node) => ((ConstantPatternSyntax)node).Expression; public void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation) { var declarationPattern = (DeclarationPatternSyntax)node; type = declarationPattern.Type; designation = declarationPattern.Designation; } public void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation) { var recursivePattern = (RecursivePatternSyntax)node; type = recursivePattern.Type; positionalPart = recursivePattern.PositionalPatternClause; propertyPart = recursivePattern.PropertyPatternClause; designation = recursivePattern.Designation; } public bool SupportsNotPattern(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion.IsCSharp9OrAbove(); public bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.AndPattern); public bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node) => node is BinaryPatternSyntax; public bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.NotPattern); public bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.OrPattern); public bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ParenthesizedPattern); public bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.TypePattern); public bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node) => node is UnaryPatternSyntax; public void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen) { var parenthesizedPattern = (ParenthesizedPatternSyntax)node; openParen = parenthesizedPattern.OpenParenToken; pattern = parenthesizedPattern.Pattern; closeParen = parenthesizedPattern.CloseParenToken; } public void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var binaryPattern = (BinaryPatternSyntax)node; left = binaryPattern.Left; operatorToken = binaryPattern.OperatorToken; right = binaryPattern.Right; } public void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern) { var unaryPattern = (UnaryPatternSyntax)node; operatorToken = unaryPattern.OperatorToken; pattern = unaryPattern.Pattern; } public SyntaxNode GetTypeOfTypePattern(SyntaxNode node) => ((TypePatternSyntax)node).Type; public bool IsImplicitObjectCreation([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ImplicitObjectCreationExpression); public SyntaxNode GetExpressionOfThrowExpression(SyntaxNode throwExpression) => ((ThrowExpressionSyntax)throwExpression).Expression; public bool IsThrowStatement([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ThrowStatement); public bool IsLocalFunction([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.LocalFunctionStatement); public void GetPartsOfInterpolationExpression(SyntaxNode node, out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken) { var interpolatedStringExpression = (InterpolatedStringExpressionSyntax)node; stringStartToken = interpolatedStringExpression.StringStartToken; contents = interpolatedStringExpression.Contents; stringEndToken = interpolatedStringExpression.StringEndToken; } public bool IsVerbatimInterpolatedStringExpression(SyntaxNode node) => node is InterpolatedStringExpressionSyntax interpolatedString && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken); } }
// Licensed to the .NET Foundation under one or more 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.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Shared.Extensions; #if CODE_STYLE using Microsoft.CodeAnalysis.Internal.Editing; #else using Microsoft.CodeAnalysis.Editing; #endif namespace Microsoft.CodeAnalysis.CSharp.LanguageServices { internal class CSharpSyntaxFacts : AbstractSyntaxFacts, ISyntaxFacts { internal static readonly CSharpSyntaxFacts Instance = new(); protected CSharpSyntaxFacts() { } public bool IsCaseSensitive => true; public StringComparer StringComparer { get; } = StringComparer.Ordinal; public SyntaxTrivia ElasticMarker => SyntaxFactory.ElasticMarker; public SyntaxTrivia ElasticCarriageReturnLineFeed => SyntaxFactory.ElasticCarriageReturnLineFeed; public override ISyntaxKinds SyntaxKinds { get; } = CSharpSyntaxKinds.Instance; public bool SupportsIndexingInitializer(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp6; public bool SupportsThrowExpression(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7; public bool SupportsLocalFunctionDeclaration(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7; public bool SupportsRecord(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp9; public bool SupportsRecordStruct(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion.IsCSharp10OrAbove(); public SyntaxToken ParseToken(string text) => SyntaxFactory.ParseToken(text); public SyntaxTriviaList ParseLeadingTrivia(string text) => SyntaxFactory.ParseLeadingTrivia(text); public string EscapeIdentifier(string identifier) { var nullIndex = identifier.IndexOf('\0'); if (nullIndex >= 0) { identifier = identifier.Substring(0, nullIndex); } var needsEscaping = SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None; return needsEscaping ? "@" + identifier : identifier; } public bool IsVerbatimIdentifier(SyntaxToken token) => token.IsVerbatimIdentifier(); public bool IsOperator(SyntaxToken token) { var kind = token.Kind(); return (SyntaxFacts.IsAnyUnaryExpression(kind) && (token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsBinaryExpression(kind) && (token.Parent is BinaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax); } public bool IsReservedKeyword(SyntaxToken token) => SyntaxFacts.IsReservedKeyword(token.Kind()); public bool IsContextualKeyword(SyntaxToken token) => SyntaxFacts.IsContextualKeyword(token.Kind()); public bool IsPreprocessorKeyword(SyntaxToken token) => SyntaxFacts.IsPreprocessorKeyword(token.Kind()); public bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) => syntaxTree.IsPreProcessorDirectiveContext( position, syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true), cancellationToken); public bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken) { if (syntaxTree == null) { return false; } return syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken); } public bool IsDirective([NotNullWhen(true)] SyntaxNode? node) => node is DirectiveTriviaSyntax; public bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? node, out ExternalSourceInfo info) { if (node is LineDirectiveTriviaSyntax lineDirective) { if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword) { info = new ExternalSourceInfo(null, ends: true); return true; } else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken && lineDirective.Line.Value is int) { info = new ExternalSourceInfo((int)lineDirective.Line.Value, false); return true; } } info = default; return false; } public bool IsRightSideOfQualifiedName([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsRightSideOfQualifiedName(); } public void GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var qualifiedName = (QualifiedNameSyntax)node; left = qualifiedName.Left; operatorToken = qualifiedName.DotToken; right = qualifiedName.Right; } public bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsSimpleMemberAccessExpressionName(); } public bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => node?.Parent is MemberAccessExpressionSyntax memberAccess && memberAccess.Name == node; public bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsMemberBindingExpressionName(); } [return: NotNullIfNotNull("node")] public SyntaxNode? GetStandaloneExpression(SyntaxNode? node) => node is ExpressionSyntax expression ? SyntaxFactory.GetStandaloneExpression(expression) : node; public SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node) => node.GetRootConditionalAccessExpression(); public bool IsObjectCreationExpressionType([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.ObjectCreationExpression, out ObjectCreationExpressionSyntax? objectCreation) && objectCreation.Type == node; public bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node) => node is DeclarationExpressionSyntax; public bool IsAttributeName(SyntaxNode node) => SyntaxFacts.IsAttributeName(node); public bool IsAnonymousFunction([NotNullWhen(true)] SyntaxNode? node) { return node is ParenthesizedLambdaExpressionSyntax || node is SimpleLambdaExpressionSyntax || node is AnonymousMethodExpressionSyntax; } public bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node) => node is ArgumentSyntax arg && arg.NameColon != null; public bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node) => node.CheckParent<NameColonSyntax>(p => p.Name == node); public SyntaxToken? GetNameOfParameter(SyntaxNode? node) => (node as ParameterSyntax)?.Identifier; public SyntaxNode? GetDefaultOfParameter(SyntaxNode node) => ((ParameterSyntax)node).Default; public SyntaxNode? GetParameterList(SyntaxNode node) => node.GetParameterList(); public bool IsParameterList([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ParameterList, SyntaxKind.BracketedParameterList); public SyntaxToken GetIdentifierOfGenericName(SyntaxNode? genericName) { return genericName is GenericNameSyntax csharpGenericName ? csharpGenericName.Identifier : default; } public bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.UsingDirective, out UsingDirectiveSyntax? usingDirective) && usingDirective.Name == node; public bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node) => node is UsingDirectiveSyntax usingDirectiveNode && usingDirectiveNode.Alias != null; public void GetPartsOfUsingAliasDirective(SyntaxNode node, out SyntaxToken globalKeyword, out SyntaxToken alias, out SyntaxNode name) { var usingDirective = (UsingDirectiveSyntax)node; globalKeyword = usingDirective.GlobalKeyword; alias = usingDirective.Alias!.Name.Identifier; name = usingDirective.Name; } public bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node) => node is ForEachVariableStatementSyntax; public bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node) => node is AssignmentExpressionSyntax assignment && assignment.IsDeconstruction(); public Location GetDeconstructionReferenceLocation(SyntaxNode node) { return node switch { AssignmentExpressionSyntax assignment => assignment.Left.GetLocation(), ForEachVariableStatementSyntax @foreach => @foreach.Variable.GetLocation(), _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()), }; } public bool IsStatement([NotNullWhen(true)] SyntaxNode? node) => node is StatementSyntax; public bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node) => node is StatementSyntax; public bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node) { if (node is BlockSyntax || node is ArrowExpressionClauseSyntax) { return node.Parent is BaseMethodDeclarationSyntax || node.Parent is AccessorDeclarationSyntax; } return false; } public SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode node) => ((ReturnStatementSyntax)node).Expression; public bool IsThisConstructorInitializer(SyntaxToken token) => token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) && constructorInit.ThisOrBaseKeyword == token; public bool IsBaseConstructorInitializer(SyntaxToken token) => token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) && constructorInit.ThisOrBaseKeyword == token; public bool IsQueryKeyword(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.FromKeyword: case SyntaxKind.JoinKeyword: case SyntaxKind.LetKeyword: case SyntaxKind.OrderByKeyword: case SyntaxKind.WhereKeyword: case SyntaxKind.OnKeyword: case SyntaxKind.EqualsKeyword: case SyntaxKind.InKeyword: return token.Parent is QueryClauseSyntax; case SyntaxKind.ByKeyword: case SyntaxKind.GroupKeyword: case SyntaxKind.SelectKeyword: return token.Parent is SelectOrGroupClauseSyntax; case SyntaxKind.AscendingKeyword: case SyntaxKind.DescendingKeyword: return token.Parent is OrderingSyntax; case SyntaxKind.IntoKeyword: return token.Parent.IsKind(SyntaxKind.JoinIntoClause, SyntaxKind.QueryContinuation); default: return false; } } public bool IsThrowExpression(SyntaxNode node) => node.Kind() == SyntaxKind.ThrowExpression; public bool IsPredefinedType(SyntaxToken token) => TryGetPredefinedType(token, out _); public bool IsPredefinedType(SyntaxToken token, PredefinedType type) => TryGetPredefinedType(token, out var actualType) && actualType == type; public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type) { type = GetPredefinedType(token); return type != PredefinedType.None; } private static PredefinedType GetPredefinedType(SyntaxToken token) { return (SyntaxKind)token.RawKind switch { SyntaxKind.BoolKeyword => PredefinedType.Boolean, SyntaxKind.ByteKeyword => PredefinedType.Byte, SyntaxKind.SByteKeyword => PredefinedType.SByte, SyntaxKind.IntKeyword => PredefinedType.Int32, SyntaxKind.UIntKeyword => PredefinedType.UInt32, SyntaxKind.ShortKeyword => PredefinedType.Int16, SyntaxKind.UShortKeyword => PredefinedType.UInt16, SyntaxKind.LongKeyword => PredefinedType.Int64, SyntaxKind.ULongKeyword => PredefinedType.UInt64, SyntaxKind.FloatKeyword => PredefinedType.Single, SyntaxKind.DoubleKeyword => PredefinedType.Double, SyntaxKind.DecimalKeyword => PredefinedType.Decimal, SyntaxKind.StringKeyword => PredefinedType.String, SyntaxKind.CharKeyword => PredefinedType.Char, SyntaxKind.ObjectKeyword => PredefinedType.Object, SyntaxKind.VoidKeyword => PredefinedType.Void, _ => PredefinedType.None, }; } public bool IsPredefinedOperator(SyntaxToken token) => TryGetPredefinedOperator(token, out var actualOperator) && actualOperator != PredefinedOperator.None; public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op) => TryGetPredefinedOperator(token, out var actualOperator) && actualOperator == op; public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op) { op = GetPredefinedOperator(token); return op != PredefinedOperator.None; } private static PredefinedOperator GetPredefinedOperator(SyntaxToken token) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.PlusToken: case SyntaxKind.PlusEqualsToken: return PredefinedOperator.Addition; case SyntaxKind.MinusToken: case SyntaxKind.MinusEqualsToken: return PredefinedOperator.Subtraction; case SyntaxKind.AmpersandToken: case SyntaxKind.AmpersandEqualsToken: return PredefinedOperator.BitwiseAnd; case SyntaxKind.BarToken: case SyntaxKind.BarEqualsToken: return PredefinedOperator.BitwiseOr; case SyntaxKind.MinusMinusToken: return PredefinedOperator.Decrement; case SyntaxKind.PlusPlusToken: return PredefinedOperator.Increment; case SyntaxKind.SlashToken: case SyntaxKind.SlashEqualsToken: return PredefinedOperator.Division; case SyntaxKind.EqualsEqualsToken: return PredefinedOperator.Equality; case SyntaxKind.CaretToken: case SyntaxKind.CaretEqualsToken: return PredefinedOperator.ExclusiveOr; case SyntaxKind.GreaterThanToken: return PredefinedOperator.GreaterThan; case SyntaxKind.GreaterThanEqualsToken: return PredefinedOperator.GreaterThanOrEqual; case SyntaxKind.ExclamationEqualsToken: return PredefinedOperator.Inequality; case SyntaxKind.LessThanLessThanToken: case SyntaxKind.LessThanLessThanEqualsToken: return PredefinedOperator.LeftShift; case SyntaxKind.LessThanToken: return PredefinedOperator.LessThan; case SyntaxKind.LessThanEqualsToken: return PredefinedOperator.LessThanOrEqual; case SyntaxKind.AsteriskToken: case SyntaxKind.AsteriskEqualsToken: return PredefinedOperator.Multiplication; case SyntaxKind.PercentToken: case SyntaxKind.PercentEqualsToken: return PredefinedOperator.Modulus; case SyntaxKind.ExclamationToken: case SyntaxKind.TildeToken: return PredefinedOperator.Complement; case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: return PredefinedOperator.RightShift; } return PredefinedOperator.None; } public string GetText(int kind) => SyntaxFacts.GetText((SyntaxKind)kind); public bool IsIdentifierStartCharacter(char c) => SyntaxFacts.IsIdentifierStartCharacter(c); public bool IsIdentifierPartCharacter(char c) => SyntaxFacts.IsIdentifierPartCharacter(c); public bool IsIdentifierEscapeCharacter(char c) => c == '@'; public bool IsValidIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length; } public bool IsVerbatimIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier(); } public bool IsTypeCharacter(char c) => false; public bool IsStartOfUnicodeEscapeSequence(char c) => c == '\\'; public bool IsLiteral(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.NumericLiteralToken: case SyntaxKind.CharacterLiteralToken: case SyntaxKind.StringLiteralToken: case SyntaxKind.NullKeyword: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.InterpolatedStringStartToken: case SyntaxKind.InterpolatedStringEndToken: case SyntaxKind.InterpolatedVerbatimStringStartToken: case SyntaxKind.InterpolatedStringTextToken: return true; default: return false; } } public bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token) => token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken); public bool IsNumericLiteralExpression([NotNullWhen(true)] SyntaxNode? node) => node?.IsKind(SyntaxKind.NumericLiteralExpression) == true; public bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent) { var typedToken = token; var typedParent = parent; if (typedParent.IsKind(SyntaxKind.IdentifierName)) { TypeSyntax? declaredType = null; if (typedParent.IsParentKind(SyntaxKind.VariableDeclaration, out VariableDeclarationSyntax? varDecl)) { declaredType = varDecl.Type; } else if (typedParent.IsParentKind(SyntaxKind.FieldDeclaration, out FieldDeclarationSyntax? fieldDecl)) { declaredType = fieldDecl.Declaration.Type; } return declaredType == typedParent && typedToken.ValueText == "var"; } return false; } public bool IsTypeNamedDynamic(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent) { if (parent is ExpressionSyntax typedParent) { if (SyntaxFacts.IsInTypeOnlyContext(typedParent) && typedParent.IsKind(SyntaxKind.IdentifierName) && token.ValueText == "dynamic") { return true; } } return false; } public bool IsBindableToken(SyntaxToken token) { if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token)) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.DelegateKeyword: case SyntaxKind.VoidKeyword: return false; } return true; } // In the order by clause a comma might be bound to ThenBy or ThenByDescending if (token.Kind() == SyntaxKind.CommaToken && token.Parent.IsKind(SyntaxKind.OrderByClause)) { return true; } return false; } public void GetPartsOfConditionalAccessExpression( SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull) { var conditionalAccess = (ConditionalAccessExpressionSyntax)node; expression = conditionalAccess.Expression; operatorToken = conditionalAccess.OperatorToken; whenNotNull = conditionalAccess.WhenNotNull; } public bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node) => node is PostfixUnaryExpressionSyntax; public bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node) => node is MemberBindingExpressionSyntax; public bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => (node as MemberAccessExpressionSyntax)?.Kind() == SyntaxKind.PointerMemberAccessExpression; public bool IsSimpleName([NotNullWhen(true)] SyntaxNode? node) => node is SimpleNameSyntax; public void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity) { var simpleName = (SimpleNameSyntax)node; name = simpleName.Identifier.ValueText; arity = simpleName.Arity; } public bool LooksGeneric(SyntaxNode simpleName) => simpleName.IsKind(SyntaxKind.GenericName) || simpleName.GetLastToken().GetNextToken().Kind() == SyntaxKind.LessThanToken; public SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node) => (node as MemberBindingExpressionSyntax).GetParentConditionalAccessExpression()?.Expression; public SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node) => ((MemberBindingExpressionSyntax)node).Name; public SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode node, bool allowImplicitTarget) => ((MemberAccessExpressionSyntax)node).Expression; public void GetPartsOfElementAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList) { var elementAccess = (ElementAccessExpressionSyntax)node; expression = elementAccess.Expression; argumentList = elementAccess.ArgumentList; } public SyntaxNode GetExpressionOfInterpolation(SyntaxNode node) => ((InterpolationSyntax)node).Expression; public bool IsInStaticContext(SyntaxNode node) => node.IsInStaticContext(); public bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node) => SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax); public bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.BaseList); public SyntaxNode GetExpressionOfArgument(SyntaxNode node) => ((ArgumentSyntax)node).Expression; public RefKind GetRefKindOfArgument(SyntaxNode node) => ((ArgumentSyntax)node).GetRefKind(); public bool IsArgument([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Argument); public bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node) { return node is ArgumentSyntax argument && argument.RefOrOutKeyword.Kind() == SyntaxKind.None && argument.NameColon == null; } public bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsInConstantContext(); public bool IsInConstructor(SyntaxNode node) => node.GetAncestor<ConstructorDeclarationSyntax>() != null; public bool IsUnsafeContext(SyntaxNode node) => node.IsUnsafeContext(); public SyntaxNode GetNameOfAttribute(SyntaxNode node) => ((AttributeSyntax)node).Name; public SyntaxNode GetExpressionOfParenthesizedExpression(SyntaxNode node) => ((ParenthesizedExpressionSyntax)node).Expression; public bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node) => (node as IdentifierNameSyntax).IsAttributeNamedArgumentIdentifier(); public SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position) { if (root == null) { throw new ArgumentNullException(nameof(root)); } if (position < 0 || position > root.Span.End) { throw new ArgumentOutOfRangeException(nameof(position)); } return root .FindToken(position) .GetAncestors<SyntaxNode>() .FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax); } public SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node) => throw ExceptionUtilities.Unreachable; public SyntaxToken FindTokenOnLeftOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public SyntaxToken FindTokenOnRightOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IdentifierName) && node.IsParentKind(SyntaxKind.NameColon) && node.Parent.IsParentKind(SyntaxKind.Subpattern); public bool IsPropertyPatternClause(SyntaxNode node) => node.Kind() == SyntaxKind.PropertyPatternClause; public bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node) => IsMemberInitializerNamedAssignmentIdentifier(node, out _); public bool IsMemberInitializerNamedAssignmentIdentifier( [NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance) { initializedInstance = null; if (node is IdentifierNameSyntax identifier && identifier.IsLeftSideOfAssignExpression()) { if (identifier.Parent.IsParentKind(SyntaxKind.WithInitializerExpression)) { var withInitializer = identifier.Parent.GetRequiredParent(); initializedInstance = withInitializer.GetRequiredParent(); return true; } else if (identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression)) { var objectInitializer = identifier.Parent.GetRequiredParent(); if (objectInitializer.Parent is BaseObjectCreationExpressionSyntax) { initializedInstance = objectInitializer.Parent; return true; } else if (objectInitializer.IsParentKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment)) { initializedInstance = assignment.Left; return true; } } } return false; } public bool IsElementAccessExpression(SyntaxNode? node) => node.IsKind(SyntaxKind.ElementAccessExpression); [return: NotNullIfNotNull("node")] public SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false) => node.ConvertToSingleLine(useElasticTrivia); public void GetPartsOfParenthesizedExpression( SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen) { var parenthesizedExpression = (ParenthesizedExpressionSyntax)node; openParen = parenthesizedExpression.OpenParenToken; expression = parenthesizedExpression.Expression; closeParen = parenthesizedExpression.CloseParenToken; } public bool IsIndexerMemberCRef(SyntaxNode? node) => node.IsKind(SyntaxKind.IndexerMemberCref); public SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true) { Contract.ThrowIfNull(root, "root"); Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position"); var end = root.FullSpan.End; if (end == 0) { // empty file return null; } // make sure position doesn't touch end of root position = Math.Min(position, end - 1); var node = root.FindToken(position).Parent; while (node != null) { if (useFullSpan || node.Span.Contains(position)) { var kind = node.Kind(); if ((kind != SyntaxKind.GlobalStatement) && (kind != SyntaxKind.IncompleteMember) && (node is MemberDeclarationSyntax)) { return node; } } node = node.Parent; } return null; } public bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node) { return node is BaseMethodDeclarationSyntax || node is BasePropertyDeclarationSyntax || node is EnumMemberDeclarationSyntax || node is BaseFieldDeclarationSyntax; } public bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node) { return node is BaseNamespaceDeclarationSyntax || node is TypeDeclarationSyntax || node is EnumDeclarationSyntax; } private const string dotToken = "."; public string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null) { if (node == null) { return string.Empty; } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; // return type var memberDeclaration = node as MemberDeclarationSyntax; if ((options & DisplayNameOptions.IncludeType) != 0) { var type = memberDeclaration.GetMemberType(); if (type != null && !type.IsMissing) { builder.Append(type); builder.Append(' '); } } var names = ArrayBuilder<string?>.GetInstance(); // containing type(s) var parent = node.GetAncestor<TypeDeclarationSyntax>() ?? node.Parent; while (parent is TypeDeclarationSyntax) { names.Push(GetName(parent, options)); parent = parent.Parent; } // containing namespace(s) in source (if any) if ((options & DisplayNameOptions.IncludeNamespaces) != 0) { while (parent is BaseNamespaceDeclarationSyntax) { names.Add(GetName(parent, options)); parent = parent.Parent; } } while (!names.IsEmpty()) { var name = names.Pop(); if (name != null) { builder.Append(name); builder.Append(dotToken); } } // name (including generic type parameters) builder.Append(GetName(node, options)); // parameter list (if any) if ((options & DisplayNameOptions.IncludeParameters) != 0) { builder.Append(memberDeclaration.GetParameterList()); } return pooled.ToStringAndFree(); } private static string? GetName(SyntaxNode node, DisplayNameOptions options) { const string missingTokenPlaceholder = "?"; switch (node.Kind()) { case SyntaxKind.CompilationUnit: return null; case SyntaxKind.IdentifierName: var identifier = ((IdentifierNameSyntax)node).Identifier; return identifier.IsMissing ? missingTokenPlaceholder : identifier.Text; case SyntaxKind.IncompleteMember: return missingTokenPlaceholder; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return GetName(((BaseNamespaceDeclarationSyntax)node).Name, options); case SyntaxKind.QualifiedName: var qualified = (QualifiedNameSyntax)node; return GetName(qualified.Left, options) + dotToken + GetName(qualified.Right, options); } string? name = null; if (node is MemberDeclarationSyntax memberDeclaration) { if (memberDeclaration.Kind() == SyntaxKind.ConversionOperatorDeclaration) { name = (memberDeclaration as ConversionOperatorDeclarationSyntax)?.Type.ToString(); } else { var nameToken = memberDeclaration.GetNameToken(); if (nameToken != default) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; if (memberDeclaration.Kind() == SyntaxKind.DestructorDeclaration) { name = "~" + name; } if ((options & DisplayNameOptions.IncludeTypeParameters) != 0) { var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append(name); AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()); name = pooled.ToStringAndFree(); } } else { Debug.Assert(memberDeclaration.Kind() == SyntaxKind.IncompleteMember); name = "?"; } } } else { if (node is VariableDeclaratorSyntax fieldDeclarator) { var nameToken = fieldDeclarator.Identifier; if (nameToken != default) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; } } } Debug.Assert(name != null, "Unexpected node type " + node.Kind()); return name; } private static void AppendTypeParameterList(StringBuilder builder, TypeParameterListSyntax typeParameterList) { if (typeParameterList != null && typeParameterList.Parameters.Count > 0) { builder.Append('<'); builder.Append(typeParameterList.Parameters[0].Identifier.ValueText); for (var i = 1; i < typeParameterList.Parameters.Count; i++) { builder.Append(", "); builder.Append(typeParameterList.Parameters[i].Identifier.ValueText); } builder.Append('>'); } } public List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root) { var list = new List<SyntaxNode>(); AppendMembers(root, list, topLevel: true, methodLevel: true); return list; } public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root) { var list = new List<SyntaxNode>(); AppendMembers(root, list, topLevel: false, methodLevel: true); return list; } public bool IsClassDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Kind() == SyntaxKind.ClassDeclaration; public bool IsNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node) => node is BaseNamespaceDeclarationSyntax; public SyntaxNode GetNameOfNamespaceDeclaration(SyntaxNode node) => ((BaseNamespaceDeclarationSyntax)node).Name; public SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration) => ((TypeDeclarationSyntax)typeDeclaration).Members; public SyntaxList<SyntaxNode> GetMembersOfNamespaceDeclaration(SyntaxNode namespaceDeclaration) => ((BaseNamespaceDeclarationSyntax)namespaceDeclaration).Members; public SyntaxList<SyntaxNode> GetMembersOfCompilationUnit(SyntaxNode compilationUnit) => ((CompilationUnitSyntax)compilationUnit).Members; public SyntaxList<SyntaxNode> GetImportsOfNamespaceDeclaration(SyntaxNode namespaceDeclaration) => ((BaseNamespaceDeclarationSyntax)namespaceDeclaration).Usings; public SyntaxList<SyntaxNode> GetImportsOfCompilationUnit(SyntaxNode compilationUnit) => ((CompilationUnitSyntax)compilationUnit).Usings; private void AppendMembers(SyntaxNode? node, List<SyntaxNode> list, bool topLevel, bool methodLevel) { Debug.Assert(topLevel || methodLevel); foreach (var member in node.GetMembers()) { if (IsTopLevelNodeWithMembers(member)) { if (topLevel) { list.Add(member); } AppendMembers(member, list, topLevel, methodLevel); continue; } if (methodLevel && IsMethodLevelMember(member)) { list.Add(member); } } } public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node) { if (node.Span.IsEmpty) { return default; } var member = GetContainingMemberDeclaration(node, node.SpanStart); if (member == null) { return default; } // TODO: currently we only support method for now if (member is BaseMethodDeclarationSyntax method) { if (method.Body == null) { return default; } return GetBlockBodySpan(method.Body); } return default; } public bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span) { switch (node) { case ConstructorDeclarationSyntax constructor: return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) || (constructor.Initializer != null && constructor.Initializer.Span.Contains(span)); case BaseMethodDeclarationSyntax method: return method.Body != null && GetBlockBodySpan(method.Body).Contains(span); case BasePropertyDeclarationSyntax property: return property.AccessorList != null && property.AccessorList.Span.Contains(span); case EnumMemberDeclarationSyntax @enum: return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span); case BaseFieldDeclarationSyntax field: return field.Declaration != null && field.Declaration.Span.Contains(span); } return false; } private static TextSpan GetBlockBodySpan(BlockSyntax body) => TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart); public SyntaxNode? TryGetBindableParent(SyntaxToken token) { var node = token.Parent; while (node != null) { var parent = node.Parent; // If this node is on the left side of a member access expression, don't ascend // further or we'll end up binding to something else. if (parent is MemberAccessExpressionSyntax memberAccess) { if (memberAccess.Expression == node) { break; } } // If this node is on the left side of a qualified name, don't ascend // further or we'll end up binding to something else. if (parent is QualifiedNameSyntax qualifiedName) { if (qualifiedName.Left == node) { break; } } // If this node is on the left side of a alias-qualified name, don't ascend // further or we'll end up binding to something else. if (parent is AliasQualifiedNameSyntax aliasQualifiedName) { if (aliasQualifiedName.Alias == node) { break; } } // If this node is the type of an object creation expression, return the // object creation expression. if (parent is ObjectCreationExpressionSyntax objectCreation) { if (objectCreation.Type == node) { node = parent; break; } } // The inside of an interpolated string is treated as its own token so we // need to force navigation to the parent expression syntax. if (node is InterpolatedStringTextSyntax && parent is InterpolatedStringExpressionSyntax) { node = parent; break; } // If this node is not parented by a name, we're done. if (!(parent is NameSyntax)) { break; } node = parent; } if (node is VarPatternSyntax) { return node; } // Patterns are never bindable (though their constituent types/exprs may be). return node is PatternSyntax ? null : node; } public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken) { if (root is not CompilationUnitSyntax compilationUnit) { return SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } var constructors = new List<SyntaxNode>(); AppendConstructors(compilationUnit.Members, constructors, cancellationToken); return constructors; } private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); switch (member) { case ConstructorDeclarationSyntax constructor: constructors.Add(constructor); continue; case BaseNamespaceDeclarationSyntax @namespace: AppendConstructors(@namespace.Members, constructors, cancellationToken); break; case ClassDeclarationSyntax @class: AppendConstructors(@class.Members, constructors, cancellationToken); break; case RecordDeclarationSyntax record: AppendConstructors(record.Members, constructors, cancellationToken); break; case StructDeclarationSyntax @struct: AppendConstructors(@struct.Members, constructors, cancellationToken); break; } } } public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace) { if (token.Kind() == SyntaxKind.CloseBraceToken) { var tuple = token.Parent.GetBraces(); openBrace = tuple.openBrace; return openBrace.Kind() == SyntaxKind.OpenBraceToken; } openBrace = default; return false; } public TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false); if (trivia.Kind() == SyntaxKind.DisabledTextTrivia) { return trivia.FullSpan; } var token = syntaxTree.FindTokenOrEndToken(position, cancellationToken); if (token.Kind() == SyntaxKind.EndOfFileToken) { var triviaList = token.LeadingTrivia; foreach (var triviaTok in triviaList.Reverse()) { if (triviaTok.Span.Contains(position)) { return default; } if (triviaTok.Span.End < position) { if (!triviaTok.HasStructure) { return default; } var structure = triviaTok.GetStructure(); if (structure is BranchingDirectiveTriviaSyntax branch) { return !branch.IsActive || !branch.BranchTaken ? TextSpan.FromBounds(branch.FullSpan.Start, position) : default; } } } } return default; } public string GetNameForArgument(SyntaxNode? argument) => (argument as ArgumentSyntax)?.NameColon?.Name.Identifier.ValueText ?? string.Empty; public string GetNameForAttributeArgument(SyntaxNode? argument) => (argument as AttributeArgumentSyntax)?.NameEquals?.Name.Identifier.ValueText ?? string.Empty; public bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfDot(); public SyntaxNode? GetRightSideOfDot(SyntaxNode? node) { return (node as QualifiedNameSyntax)?.Right ?? (node as MemberAccessExpressionSyntax)?.Name; } public SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget) { return (node as QualifiedNameSyntax)?.Left ?? (node as MemberAccessExpressionSyntax)?.Expression; } public bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node) => (node as NameSyntax).IsLeftSideOfExplicitInterfaceSpecifier(); public bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfAssignExpression(); public bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfAnyAssignExpression(); public bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfCompoundAssignExpression(); public SyntaxNode GetRightHandSideOfAssignment(SyntaxNode node) => ((AssignmentExpressionSyntax)node).Right; public bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator, out AnonymousObjectMemberDeclaratorSyntax? anonObject) && anonObject.NameEquals == null; public bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.PostIncrementExpression) || node.IsParentKind(SyntaxKind.PreIncrementExpression); public static bool IsOperandOfDecrementExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.PostDecrementExpression) || node.IsParentKind(SyntaxKind.PreDecrementExpression); public bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node) => IsOperandOfIncrementExpression(node) || IsOperandOfDecrementExpression(node); public SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString) => ((InterpolatedStringExpressionSyntax)interpolatedString).Contents; public bool IsVerbatimStringLiteral(SyntaxToken token) => token.IsVerbatimStringLiteral(); public bool IsNumericLiteral(SyntaxToken token) => token.Kind() == SyntaxKind.NumericLiteralToken; public void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList) { var invocation = (InvocationExpressionSyntax)node; expression = invocation.Expression; argumentList = invocation.ArgumentList; } public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode invocationExpression) => GetArgumentsOfArgumentList(((InvocationExpressionSyntax)invocationExpression).ArgumentList); public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode objectCreationExpression) => ((BaseObjectCreationExpressionSyntax)objectCreationExpression).ArgumentList is { } argumentList ? GetArgumentsOfArgumentList(argumentList) : default; public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode argumentList) => ((BaseArgumentListSyntax)argumentList).Arguments; public SyntaxNode GetArgumentListOfInvocationExpression(SyntaxNode invocationExpression) => ((InvocationExpressionSyntax)invocationExpression).ArgumentList; public SyntaxNode? GetArgumentListOfObjectCreationExpression(SyntaxNode objectCreationExpression) => ((ObjectCreationExpressionSyntax)objectCreationExpression).ArgumentList; public bool IsRegularComment(SyntaxTrivia trivia) => trivia.IsRegularComment(); public bool IsDocumentationComment(SyntaxTrivia trivia) => trivia.IsDocComment(); public bool IsElastic(SyntaxTrivia trivia) => trivia.IsElastic(); public bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes) => trivia.IsPragmaDirective(out isDisable, out isActive, out errorCodes); public bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.DocumentationCommentExteriorTrivia; public bool IsDocumentationComment(SyntaxNode node) => SyntaxFacts.IsDocumentationCommentTrivia(node.Kind()); public bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node) { return node.IsKind(SyntaxKind.UsingDirective) || node.IsKind(SyntaxKind.ExternAliasDirective); } public bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node) => IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword); public bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node) => IsGlobalAttribute(node, SyntaxKind.ModuleKeyword); private static bool IsGlobalAttribute([NotNullWhen(true)] SyntaxNode? node, SyntaxKind attributeTarget) => node.IsKind(SyntaxKind.Attribute) && node.Parent.IsKind(SyntaxKind.AttributeList, out AttributeListSyntax? attributeList) && attributeList.Target?.Identifier.Kind() == attributeTarget; private static bool IsMemberDeclaration(SyntaxNode node) { // From the C# language spec: // class-member-declaration: // constant-declaration // field-declaration // method-declaration // property-declaration // event-declaration // indexer-declaration // operator-declaration // constructor-declaration // destructor-declaration // static-constructor-declaration // type-declaration switch (node.Kind()) { // Because fields declarations can define multiple symbols "public int a, b;" // We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name. case SyntaxKind.VariableDeclarator: return node.Parent.IsParentKind(SyntaxKind.FieldDeclaration) || node.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration); case SyntaxKind.FieldDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.PropertyDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: return true; default: return false; } } public bool IsDeclaration(SyntaxNode node) => SyntaxFacts.IsNamespaceMemberDeclaration(node.Kind()) || IsMemberDeclaration(node); public bool IsTypeDeclaration(SyntaxNode node) => SyntaxFacts.IsTypeDeclaration(node.Kind()); public SyntaxNode? GetObjectCreationInitializer(SyntaxNode node) => ((ObjectCreationExpressionSyntax)node).Initializer; public SyntaxNode GetObjectCreationType(SyntaxNode node) => ((ObjectCreationExpressionSyntax)node).Type; public bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement) => statement.IsKind(SyntaxKind.ExpressionStatement, out ExpressionStatementSyntax? exprStatement) && exprStatement.Expression.IsKind(SyntaxKind.SimpleAssignmentExpression); public void GetPartsOfAssignmentStatement( SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { GetPartsOfAssignmentExpressionOrStatement( ((ExpressionStatementSyntax)statement).Expression, out left, out operatorToken, out right); } public void GetPartsOfAssignmentExpressionOrStatement( SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var expression = statement; if (statement is ExpressionStatementSyntax expressionStatement) { expression = expressionStatement.Expression; } var assignment = (AssignmentExpressionSyntax)expression; left = assignment.Left; operatorToken = assignment.OperatorToken; right = assignment.Right; } public SyntaxNode GetNameOfMemberAccessExpression(SyntaxNode memberAccessExpression) => ((MemberAccessExpressionSyntax)memberAccessExpression).Name; public void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name) { var memberAccess = (MemberAccessExpressionSyntax)node; expression = memberAccess.Expression; operatorToken = memberAccess.OperatorToken; name = memberAccess.Name; } public SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node) => ((SimpleNameSyntax)node).Identifier; public SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node) => ((VariableDeclaratorSyntax)node).Identifier; public SyntaxToken GetIdentifierOfParameter(SyntaxNode node) => ((ParameterSyntax)node).Identifier; public SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node) => node switch { BaseTypeDeclarationSyntax typeDecl => typeDecl.Identifier, DelegateDeclarationSyntax delegateDecl => delegateDecl.Identifier, _ => throw ExceptionUtilities.UnexpectedValue(node), }; public SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node) => ((IdentifierNameSyntax)node).Identifier; public bool IsLocalFunctionStatement([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.LocalFunctionStatement); public bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement) { return ((LocalDeclarationStatementSyntax)localDeclarationStatement).Declaration.Variables.Contains( (VariableDeclaratorSyntax)declarator); } public bool AreEquivalent(SyntaxToken token1, SyntaxToken token2) => SyntaxFactory.AreEquivalent(token1, token2); public bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2) => SyntaxFactory.AreEquivalent(node1, node2); public bool IsExpressionOfInvocationExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as InvocationExpressionSyntax)?.Expression == node; public bool IsExpressionOfAwaitExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as AwaitExpressionSyntax)?.Expression == node; public bool IsExpressionOfMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as MemberAccessExpressionSyntax)?.Expression == node; public static SyntaxNode GetExpressionOfInvocationExpression(SyntaxNode node) => ((InvocationExpressionSyntax)node).Expression; public SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node) => ((AwaitExpressionSyntax)node).Expression; public bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node) => node?.Parent is ForEachStatementSyntax foreachStatement && foreachStatement.Expression == node; public SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node) => ((ExpressionStatementSyntax)node).Expression; public bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node) => node is BinaryExpressionSyntax; public bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IsExpression); public void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var binaryExpression = (BinaryExpressionSyntax)node; left = binaryExpression.Left; operatorToken = binaryExpression.OperatorToken; right = binaryExpression.Right; } public void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse) { var conditionalExpression = (ConditionalExpressionSyntax)node; condition = conditionalExpression.Condition; whenTrue = conditionalExpression.WhenTrue; whenFalse = conditionalExpression.WhenFalse; } [return: NotNullIfNotNull("node")] public SyntaxNode? WalkDownParentheses(SyntaxNode? node) => (node as ExpressionSyntax)?.WalkDownParentheses() ?? node; public void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node, out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode { var tupleExpression = (TupleExpressionSyntax)node; openParen = tupleExpression.OpenParenToken; arguments = (SeparatedSyntaxList<TArgumentSyntax>)(SeparatedSyntaxList<SyntaxNode>)tupleExpression.Arguments; closeParen = tupleExpression.CloseParenToken; } public SyntaxNode GetOperandOfPrefixUnaryExpression(SyntaxNode node) => ((PrefixUnaryExpressionSyntax)node).Operand; public SyntaxToken GetOperatorTokenOfPrefixUnaryExpression(SyntaxNode node) => ((PrefixUnaryExpressionSyntax)node).OperatorToken; public SyntaxNode? GetNextExecutableStatement(SyntaxNode statement) => ((StatementSyntax)statement).GetNextStatement(); public override bool IsPreprocessorDirective(SyntaxTrivia trivia) => SyntaxFacts.IsPreprocessorDirective(trivia.Kind()); public bool IsOnTypeHeader(SyntaxNode root, int position, bool fullHeader, [NotNullWhen(true)] out SyntaxNode? typeDeclaration) { var node = TryGetAncestorForLocation<BaseTypeDeclarationSyntax>(root, position); typeDeclaration = node; if (node == null) return false; var lastToken = (node as TypeDeclarationSyntax)?.TypeParameterList?.GetLastToken() ?? node.Identifier; if (fullHeader) lastToken = node.BaseList?.GetLastToken() ?? lastToken; return IsOnHeader(root, position, node, lastToken); } public bool IsOnPropertyDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? propertyDeclaration) { var node = TryGetAncestorForLocation<PropertyDeclarationSyntax>(root, position); propertyDeclaration = node; if (propertyDeclaration == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.Identifier); } public bool IsOnParameterHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? parameter) { var node = TryGetAncestorForLocation<ParameterSyntax>(root, position); parameter = node; if (parameter == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node); } public bool IsOnMethodHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? method) { var node = TryGetAncestorForLocation<MethodDeclarationSyntax>(root, position); method = node; if (method == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.ParameterList); } public bool IsOnLocalFunctionHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localFunction) { var node = TryGetAncestorForLocation<LocalFunctionStatementSyntax>(root, position); localFunction = node; if (localFunction == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.ParameterList); } public bool IsOnLocalDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localDeclaration) { var node = TryGetAncestorForLocation<LocalDeclarationStatementSyntax>(root, position); localDeclaration = node; if (localDeclaration == null) { return false; } var initializersExpressions = node!.Declaration.Variables .Where(v => v.Initializer != null) .SelectAsArray(initializedV => initializedV.Initializer!.Value); return IsOnHeader(root, position, node, node, holes: initializersExpressions); } public bool IsOnIfStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? ifStatement) { var node = TryGetAncestorForLocation<IfStatementSyntax>(root, position); ifStatement = node; if (ifStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsOnWhileStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? whileStatement) { var node = TryGetAncestorForLocation<WhileStatementSyntax>(root, position); whileStatement = node; if (whileStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsOnForeachHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? foreachStatement) { var node = TryGetAncestorForLocation<ForEachStatementSyntax>(root, position); foreachStatement = node; if (foreachStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration) { var token = root.FindToken(position); var typeDecl = token.GetAncestor<TypeDeclarationSyntax>(); typeDeclaration = typeDecl; if (typeDecl == null) { return false; } RoslynDebug.AssertNotNull(typeDeclaration); if (position < typeDecl.OpenBraceToken.Span.End || position > typeDecl.CloseBraceToken.Span.Start) { return false; } var line = sourceText.Lines.GetLineFromPosition(position); if (!line.IsEmptyOrWhitespace()) { return false; } var member = typeDecl.Members.FirstOrDefault(d => d.FullSpan.Contains(position)); if (member == null) { // There are no members, or we're after the last member. return true; } else { // We're within a member. Make sure we're in the leading whitespace of // the member. if (position < member.SpanStart) { foreach (var trivia in member.GetLeadingTrivia()) { if (!trivia.IsWhitespaceOrEndOfLine()) { return false; } if (trivia.FullSpan.Contains(position)) { return true; } } } } return false; } protected override bool ContainsInterleavedDirective(TextSpan span, SyntaxToken token, CancellationToken cancellationToken) => token.ContainsInterleavedDirective(span, cancellationToken); public SyntaxTokenList GetModifiers(SyntaxNode? node) => node.GetModifiers(); public SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers) => node.WithModifiers(modifiers); public bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node) => node is LiteralExpressionSyntax; public SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node) => ((LocalDeclarationStatementSyntax)node).Declaration.Variables; public SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node) => ((VariableDeclaratorSyntax)node).Initializer; public SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node) => ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)node).Parent!).Type; public SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node) => ((EqualsValueClauseSyntax?)node)?.Value; public bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Block); public bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Block, SyntaxKind.SwitchSection, SyntaxKind.CompilationUnit); public IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node) { return node switch { BlockSyntax block => block.Statements, SwitchSectionSyntax switchSection => switchSection.Statements, CompilationUnitSyntax compilationUnit => compilationUnit.Members.OfType<GlobalStatementSyntax>().SelectAsArray(globalStatement => globalStatement.Statement), _ => throw ExceptionUtilities.UnexpectedValue(node), }; } public SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes) => nodes.FindInnermostCommonNode(node => IsExecutableBlock(node)); public bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node) => IsExecutableBlock(node) || node.IsEmbeddedStatementOwner(); public IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node) { if (IsExecutableBlock(node)) return GetExecutableBlockStatements(node); else if (node.GetEmbeddedStatement() is { } embeddedStatement) return ImmutableArray.Create<SyntaxNode>(embeddedStatement); else return ImmutableArray<SyntaxNode>.Empty; } public bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node) => node is CastExpressionSyntax; public bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node) => node is CastExpressionSyntax; public void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression) { var cast = (CastExpressionSyntax)node; type = cast.Type; expression = cast.Expression; } public SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token) { if (token.Kind() == SyntaxKind.OverrideKeyword && token.Parent is MemberDeclarationSyntax member) { return member.GetNameToken(); } return null; } public override SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node) => node.GetAttributeLists(); public override bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.XmlElement, out XmlElementSyntax? xmlElement) && xmlElement.StartTag.Name.LocalName.ValueText == DocumentationCommentXmlNames.ParameterElementName; public override SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia) { if (trivia.GetStructure() is DocumentationCommentTriviaSyntax documentationCommentTrivia) { return documentationCommentTrivia.Content; } throw ExceptionUtilities.UnexpectedValue(trivia.Kind()); } public override bool CanHaveAccessibility(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return true; case SyntaxKind.VariableDeclaration: case SyntaxKind.VariableDeclarator: var declarationKind = this.GetDeclarationKind(declaration); return declarationKind == DeclarationKind.Field || declarationKind == DeclarationKind.Event; case SyntaxKind.ConstructorDeclaration: // Static constructor can't have accessibility return !((ConstructorDeclarationSyntax)declaration).Modifiers.Any(SyntaxKind.StaticKeyword); case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; if (method.ExplicitInterfaceSpecifier != null) { // explicit interface methods can't have accessibility. return false; } if (method.Modifiers.Any(SyntaxKind.PartialKeyword)) { // partial methods can't have accessibility modifiers. return false; } return true; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; default: return false; } } public override Accessibility GetAccessibility(SyntaxNode declaration) { if (!CanHaveAccessibility(declaration)) { return Accessibility.NotApplicable; } var modifierTokens = GetModifierTokens(declaration); GetAccessibilityAndModifiers(modifierTokens, out var accessibility, out _, out _); return accessibility; } public override void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers modifiers, out bool isDefault) { accessibility = Accessibility.NotApplicable; modifiers = DeclarationModifiers.None; isDefault = false; foreach (var token in modifierList) { accessibility = (token.Kind(), accessibility) switch { (SyntaxKind.PublicKeyword, _) => Accessibility.Public, (SyntaxKind.PrivateKeyword, Accessibility.Protected) => Accessibility.ProtectedAndInternal, (SyntaxKind.PrivateKeyword, _) => Accessibility.Private, (SyntaxKind.InternalKeyword, Accessibility.Protected) => Accessibility.ProtectedOrInternal, (SyntaxKind.InternalKeyword, _) => Accessibility.Internal, (SyntaxKind.ProtectedKeyword, Accessibility.Private) => Accessibility.ProtectedAndInternal, (SyntaxKind.ProtectedKeyword, Accessibility.Internal) => Accessibility.ProtectedOrInternal, (SyntaxKind.ProtectedKeyword, _) => Accessibility.Protected, _ => accessibility, }; modifiers |= token.Kind() switch { SyntaxKind.AbstractKeyword => DeclarationModifiers.Abstract, SyntaxKind.NewKeyword => DeclarationModifiers.New, SyntaxKind.OverrideKeyword => DeclarationModifiers.Override, SyntaxKind.VirtualKeyword => DeclarationModifiers.Virtual, SyntaxKind.StaticKeyword => DeclarationModifiers.Static, SyntaxKind.AsyncKeyword => DeclarationModifiers.Async, SyntaxKind.ConstKeyword => DeclarationModifiers.Const, SyntaxKind.ReadOnlyKeyword => DeclarationModifiers.ReadOnly, SyntaxKind.SealedKeyword => DeclarationModifiers.Sealed, SyntaxKind.UnsafeKeyword => DeclarationModifiers.Unsafe, SyntaxKind.PartialKeyword => DeclarationModifiers.Partial, SyntaxKind.RefKeyword => DeclarationModifiers.Ref, SyntaxKind.VolatileKeyword => DeclarationModifiers.Volatile, SyntaxKind.ExternKeyword => DeclarationModifiers.Extern, _ => DeclarationModifiers.None, }; isDefault |= token.Kind() == SyntaxKind.DefaultKeyword; } } public override SyntaxTokenList GetModifierTokens(SyntaxNode? declaration) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.Modifiers, ParameterSyntax parameter => parameter.Modifiers, LocalDeclarationStatementSyntax localDecl => localDecl.Modifiers, LocalFunctionStatementSyntax localFunc => localFunc.Modifiers, AccessorDeclarationSyntax accessor => accessor.Modifiers, VariableDeclarationSyntax varDecl => GetModifierTokens(varDecl.Parent), VariableDeclaratorSyntax varDecl => GetModifierTokens(varDecl.Parent), AnonymousFunctionExpressionSyntax anonymous => anonymous.Modifiers, _ => default, }; public override DeclarationKind GetDeclarationKind(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: return DeclarationKind.Class; case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: return DeclarationKind.Struct; case SyntaxKind.InterfaceDeclaration: return DeclarationKind.Interface; case SyntaxKind.EnumDeclaration: return DeclarationKind.Enum; case SyntaxKind.DelegateDeclaration: return DeclarationKind.Delegate; case SyntaxKind.MethodDeclaration: return DeclarationKind.Method; case SyntaxKind.OperatorDeclaration: return DeclarationKind.Operator; case SyntaxKind.ConversionOperatorDeclaration: return DeclarationKind.ConversionOperator; case SyntaxKind.ConstructorDeclaration: return DeclarationKind.Constructor; case SyntaxKind.DestructorDeclaration: return DeclarationKind.Destructor; case SyntaxKind.PropertyDeclaration: return DeclarationKind.Property; case SyntaxKind.IndexerDeclaration: return DeclarationKind.Indexer; case SyntaxKind.EventDeclaration: return DeclarationKind.CustomEvent; case SyntaxKind.EnumMemberDeclaration: return DeclarationKind.EnumMember; case SyntaxKind.CompilationUnit: return DeclarationKind.CompilationUnit; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return DeclarationKind.Namespace; case SyntaxKind.UsingDirective: return DeclarationKind.NamespaceImport; case SyntaxKind.Parameter: return DeclarationKind.Parameter; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return DeclarationKind.LambdaExpression; case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)declaration; if (fd.Declaration != null && fd.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Field; } else { return DeclarationKind.None; } case SyntaxKind.EventFieldDeclaration: var ef = (EventFieldDeclarationSyntax)declaration; if (ef.Declaration != null && ef.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Event; } else { return DeclarationKind.None; } case SyntaxKind.LocalDeclarationStatement: var ld = (LocalDeclarationStatementSyntax)declaration; if (ld.Declaration != null && ld.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Variable; } else { return DeclarationKind.None; } case SyntaxKind.VariableDeclaration: { var vd = (VariableDeclarationSyntax)declaration; if (vd.Variables.Count == 1 && vd.Parent == null) { // this node is the declaration if it contains only one variable and has no parent. return DeclarationKind.Variable; } else { return DeclarationKind.None; } } case SyntaxKind.VariableDeclarator: { var vd = declaration.Parent as VariableDeclarationSyntax; // this node is considered the declaration if it is one among many, or it has no parent if (vd == null || vd.Variables.Count > 1) { if (ParentIsFieldDeclaration(vd)) { return DeclarationKind.Field; } else if (ParentIsEventFieldDeclaration(vd)) { return DeclarationKind.Event; } else { return DeclarationKind.Variable; } } break; } case SyntaxKind.AttributeList: var list = (AttributeListSyntax)declaration; if (list.Attributes.Count == 1) { return DeclarationKind.Attribute; } break; case SyntaxKind.Attribute: if (declaration.Parent is not AttributeListSyntax parentList || parentList.Attributes.Count > 1) { return DeclarationKind.Attribute; } break; case SyntaxKind.GetAccessorDeclaration: return DeclarationKind.GetAccessor; case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: return DeclarationKind.SetAccessor; case SyntaxKind.AddAccessorDeclaration: return DeclarationKind.AddAccessor; case SyntaxKind.RemoveAccessorDeclaration: return DeclarationKind.RemoveAccessor; } return DeclarationKind.None; } internal static bool ParentIsFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.FieldDeclaration) ?? false; internal static bool ParentIsEventFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.EventFieldDeclaration) ?? false; internal static bool ParentIsLocalDeclarationStatement([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.LocalDeclarationStatement) ?? false; public bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IsPatternExpression); public void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right) { var isPatternExpression = (IsPatternExpressionSyntax)node; left = isPatternExpression.Expression; isToken = isPatternExpression.IsKeyword; right = isPatternExpression.Pattern; } public bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node) => node is PatternSyntax; public bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ConstantPattern); public bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.DeclarationPattern); public bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.RecursivePattern); public bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.VarPattern); public SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node) => ((ConstantPatternSyntax)node).Expression; public void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation) { var declarationPattern = (DeclarationPatternSyntax)node; type = declarationPattern.Type; designation = declarationPattern.Designation; } public void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation) { var recursivePattern = (RecursivePatternSyntax)node; type = recursivePattern.Type; positionalPart = recursivePattern.PositionalPatternClause; propertyPart = recursivePattern.PropertyPatternClause; designation = recursivePattern.Designation; } public bool SupportsNotPattern(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion.IsCSharp9OrAbove(); public bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.AndPattern); public bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node) => node is BinaryPatternSyntax; public bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.NotPattern); public bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.OrPattern); public bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ParenthesizedPattern); public bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.TypePattern); public bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node) => node is UnaryPatternSyntax; public void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen) { var parenthesizedPattern = (ParenthesizedPatternSyntax)node; openParen = parenthesizedPattern.OpenParenToken; pattern = parenthesizedPattern.Pattern; closeParen = parenthesizedPattern.CloseParenToken; } public void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var binaryPattern = (BinaryPatternSyntax)node; left = binaryPattern.Left; operatorToken = binaryPattern.OperatorToken; right = binaryPattern.Right; } public void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern) { var unaryPattern = (UnaryPatternSyntax)node; operatorToken = unaryPattern.OperatorToken; pattern = unaryPattern.Pattern; } public SyntaxNode GetTypeOfTypePattern(SyntaxNode node) => ((TypePatternSyntax)node).Type; public bool IsImplicitObjectCreation([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ImplicitObjectCreationExpression); public SyntaxNode GetExpressionOfThrowExpression(SyntaxNode throwExpression) => ((ThrowExpressionSyntax)throwExpression).Expression; public bool IsThrowStatement([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ThrowStatement); public bool IsLocalFunction([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.LocalFunctionStatement); public void GetPartsOfInterpolationExpression(SyntaxNode node, out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken) { var interpolatedStringExpression = (InterpolatedStringExpressionSyntax)node; stringStartToken = interpolatedStringExpression.StringStartToken; contents = interpolatedStringExpression.Contents; stringEndToken = interpolatedStringExpression.StringEndToken; } public bool IsVerbatimInterpolatedStringExpression(SyntaxNode node) => node is InterpolatedStringExpressionSyntax interpolatedString && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken); } }
1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxFacts.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.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.Text; #if CODE_STYLE using Microsoft.CodeAnalysis.Internal.Editing; #else using Microsoft.CodeAnalysis.Editing; #endif namespace Microsoft.CodeAnalysis.LanguageServices { internal interface ISyntaxFacts { bool IsCaseSensitive { get; } StringComparer StringComparer { get; } SyntaxTrivia ElasticMarker { get; } SyntaxTrivia ElasticCarriageReturnLineFeed { get; } ISyntaxKinds SyntaxKinds { get; } bool SupportsIndexingInitializer(ParseOptions options); bool SupportsLocalFunctionDeclaration(ParseOptions options); bool SupportsNotPattern(ParseOptions options); bool SupportsRecord(ParseOptions options); bool SupportsRecordStruct(ParseOptions options); bool SupportsThrowExpression(ParseOptions options); SyntaxToken ParseToken(string text); SyntaxTriviaList ParseLeadingTrivia(string text); string EscapeIdentifier(string identifier); bool IsVerbatimIdentifier(SyntaxToken token); bool IsOperator(SyntaxToken token); bool IsPredefinedType(SyntaxToken token); bool IsPredefinedType(SyntaxToken token, PredefinedType type); bool IsPredefinedOperator(SyntaxToken token); bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op); /// <summary> /// Returns 'true' if this a 'reserved' keyword for the language. A 'reserved' keyword is a /// identifier that is always treated as being a special keyword, regardless of where it is /// found in the token stream. Examples of this are tokens like <see langword="class"/> and /// <see langword="Class"/> in C# and VB respectively. /// /// Importantly, this does *not* include contextual keywords. If contextual keywords are /// important for your scenario, use <see cref="IsContextualKeyword"/> or <see /// cref="ISyntaxFactsExtensions.IsReservedOrContextualKeyword"/>. Also, consider using /// <see cref="ISyntaxFactsExtensions.IsWord"/> if all you need is the ability to know /// if this is effectively any identifier in the language, regardless of whether the language /// is treating it as a keyword or not. /// </summary> bool IsReservedKeyword(SyntaxToken token); /// <summary> /// Returns <see langword="true"/> if this a 'contextual' keyword for the language. A /// 'contextual' keyword is a identifier that is only treated as being a special keyword in /// certain *syntactic* contexts. Examples of this is 'yield' in C#. This is only a /// keyword if used as 'yield return' or 'yield break'. Importantly, identifiers like <see /// langword="var"/>, <see langword="dynamic"/> and <see langword="nameof"/> are *not* /// 'contextual' keywords. This is because they are not treated as keywords depending on /// the syntactic context around them. Instead, the language always treats them identifiers /// that have special *semantic* meaning if they end up not binding to an existing symbol. /// /// Importantly, if <paramref name="token"/> is not in the syntactic construct where the /// language thinks an identifier should be contextually treated as a keyword, then this /// will return <see langword="false"/>. /// /// Or, in other words, the parser must be able to identify these cases in order to be a /// contextual keyword. If identification happens afterwards, it's not contextual. /// </summary> bool IsContextualKeyword(SyntaxToken token); /// <summary> /// The set of identifiers that have special meaning directly after the `#` token in a /// preprocessor directive. For example `if` or `pragma`. /// </summary> bool IsPreprocessorKeyword(SyntaxToken token); bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken); bool IsLiteral(SyntaxToken token); bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token); bool IsNumericLiteral(SyntaxToken token); bool IsVerbatimStringLiteral(SyntaxToken token); bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent); bool IsTypeNamedDynamic(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent); bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node); bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node); bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node); bool IsDeclaration(SyntaxNode node); bool IsTypeDeclaration(SyntaxNode node); bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfUsingAliasDirective(SyntaxNode node, out SyntaxToken globalKeyword, out SyntaxToken alias, out SyntaxNode name); bool IsRegularComment(SyntaxTrivia trivia); bool IsDocumentationComment(SyntaxTrivia trivia); bool IsElastic(SyntaxTrivia trivia); bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes); bool IsSingleLineCommentTrivia(SyntaxTrivia trivia); bool IsMultiLineCommentTrivia(SyntaxTrivia trivia); bool IsSingleLineDocCommentTrivia(SyntaxTrivia trivia); bool IsMultiLineDocCommentTrivia(SyntaxTrivia trivia); bool IsShebangDirectiveTrivia(SyntaxTrivia trivia); bool IsPreprocessorDirective(SyntaxTrivia trivia); bool IsDocumentationComment(SyntaxNode node); bool IsNumericLiteralExpression([NotNullWhen(true)] SyntaxNode? node); bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node); string GetText(int kind); bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken); bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type); bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op); bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? directive, out ExternalSourceInfo info); bool IsObjectCreationExpressionType([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetObjectCreationInitializer(SyntaxNode node); SyntaxNode GetObjectCreationType(SyntaxNode node); bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node); bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right); void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse); bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node); bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression); bool IsExpressionOfInvocationExpression(SyntaxNode? node); void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList); SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node); bool IsExpressionOfAwaitExpression([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node); bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node, out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode; void GetPartsOfInterpolationExpression(SyntaxNode node, out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken); bool IsVerbatimInterpolatedStringExpression(SyntaxNode node); SyntaxNode GetOperandOfPrefixUnaryExpression(SyntaxNode node); SyntaxToken GetOperatorTokenOfPrefixUnaryExpression(SyntaxNode node); // Left side of = assignment. bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node); bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement); void GetPartsOfAssignmentStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfAssignmentExpressionOrStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); // Left side of any assignment (for example = or ??= or *= or += ) bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node); // Left side of compound assignment (for example ??= or *= or += ) bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetRightHandSideOfAssignment(SyntaxNode? node); bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node); bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node); bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node); bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetRightSideOfDot(SyntaxNode? node); /// <summary> /// Get the node on the left side of the dot if given a dotted expression. /// </summary> /// <param name="allowImplicitTarget"> /// In VB, we have a member access expression with a null expression, this may be one of the /// following forms: /// 1) new With { .a = 1, .b = .a .a refers to the anonymous type /// 2) With obj : .m .m refers to the obj type /// 3) new T() With { .a = 1, .b = .a 'a refers to the T type /// If `allowImplicitTarget` is set to true, the returned node will be set to approperiate node, otherwise, it will return null. /// This parameter has no affect on C# node. /// </param> SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget = false); bool IsRightSideOfQualifiedName([NotNullWhen(true)] SyntaxNode? node); bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken dotToken, out SyntaxNode right); bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// Gets the containing expression that is actually a language expression and not just typed /// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side /// of qualified names and member access expressions are not language expressions, yet the /// containing qualified names or member access expressions are indeed expressions. /// </summary> [return: NotNullIfNotNull("node")] SyntaxNode? GetStandaloneExpression(SyntaxNode? node); /// <summary> /// Call on the `.y` part of a `x?.y` to get the entire `x?.y` conditional access expression. This also works /// when there are multiple chained conditional accesses. For example, calling this on '.y' or '.z' in /// `x?.y?.z` will both return the full `x?.y?.z` node. This can be used to effectively get 'out' of the RHS of /// a conditional access, and commonly represents the full standalone expression that can be operated on /// atomically. /// </summary> SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node); bool IsExpressionOfMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetNameOfMemberAccessExpression(SyntaxNode node); /// <summary> /// Returns the expression node the member is being accessed off of. If <paramref name="allowImplicitTarget"/> /// is <see langword="false"/>, this will be the node directly to the left of the dot-token. If <paramref name="allowImplicitTarget"/> /// is <see langword="true"/>, then this can return another node in the tree that the member will be accessed /// off of. For example, in VB, if you have a member-access-expression of the form ".Length" then this /// may return the expression in the surrounding With-statement. /// </summary> SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode? node, bool allowImplicitTarget = false); void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name); SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node); SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node); bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node); SyntaxToken? GetNameOfParameter([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetDefaultOfParameter(SyntaxNode? node); SyntaxNode? GetParameterList(SyntaxNode node); bool IsParameterList([NotNullWhen(true)] SyntaxNode? node); bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia); void GetPartsOfElementAccessExpression(SyntaxNode? node, out SyntaxNode? expression, out SyntaxNode? argumentList); [return: NotNullIfNotNull("node")] SyntaxNode? GetExpressionOfArgument(SyntaxNode? node); SyntaxNode? GetExpressionOfInterpolation(SyntaxNode? node); SyntaxNode GetNameOfAttribute(SyntaxNode node); void GetPartsOfConditionalAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull); bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node); bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfParenthesizedExpression(SyntaxNode node); SyntaxToken GetIdentifierOfGenericName(SyntaxNode? node); SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node); SyntaxToken GetIdentifierOfParameter(SyntaxNode node); SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node); SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node); SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node); SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node); /// <summary> /// True if this is an argument with just an expression and nothing else (i.e. no ref/out, /// no named params, no omitted args). /// </summary> bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node); bool IsArgument([NotNullWhen(true)] SyntaxNode? node); RefKind GetRefKindOfArgument(SyntaxNode? node); bool IsSimpleName([NotNullWhen(true)] SyntaxNode? node); void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity); bool LooksGeneric(SyntaxNode simpleName); SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode? node); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode? node); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode? node); SyntaxNode GetArgumentListOfInvocationExpression(SyntaxNode node); SyntaxNode? GetArgumentListOfObjectCreationExpression(SyntaxNode node); bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node); bool IsAttributeName(SyntaxNode node); SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node); bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node); bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node); bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance); bool IsDirective([NotNullWhen(true)] SyntaxNode? node); bool IsStatement([NotNullWhen(true)] SyntaxNode? node); bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node); bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node); bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// Returns true for nodes that represent the body of a method. /// /// For VB this will be /// MethodBlockBaseSyntax. This will be true for things like constructor, method, operator /// bodies as well as accessor bodies. It will not be true for things like sub() function() /// lambdas. /// /// For C# this will be the BlockSyntax or ArrowExpressionSyntax for a /// method/constructor/deconstructor/operator/accessor. It will not be included for local /// functions. /// </summary> bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode? node); bool IsLocalFunctionStatement([NotNullWhen(true)] SyntaxNode? node); bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement); SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node); SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node); SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node); bool IsThisConstructorInitializer(SyntaxToken token); bool IsBaseConstructorInitializer(SyntaxToken token); bool IsQueryKeyword(SyntaxToken token); bool IsThrowExpression(SyntaxNode node); bool IsElementAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIndexerMemberCRef([NotNullWhen(true)] SyntaxNode? node); bool IsIdentifierStartCharacter(char c); bool IsIdentifierPartCharacter(char c); bool IsIdentifierEscapeCharacter(char c); bool IsStartOfUnicodeEscapeSequence(char c); bool IsValidIdentifier(string identifier); bool IsVerbatimIdentifier(string identifier); /// <summary> /// Returns true if the given character is a character which may be included in an /// identifier to specify the type of a variable. /// </summary> bool IsTypeCharacter(char c); bool IsBindableToken(SyntaxToken token); bool IsInStaticContext(SyntaxNode node); bool IsUnsafeContext(SyntaxNode node); bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node); bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node); bool IsAnonymousFunction([NotNullWhen(true)] SyntaxNode? n); bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node); bool IsInConstructor(SyntaxNode node); bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node); bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node); bool HasIncompleteParentMember([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// A block that has no semantics other than introducing a new scope. That is only C# BlockSyntax. /// </summary> bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// A node that contains a list of statements. In C#, this is BlockSyntax and SwitchSectionSyntax. /// In VB, this includes all block statements such as a MultiLineIfBlockSyntax. /// </summary> bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node); IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node); SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes); /// <summary> /// A node that can host a list of statements or a single statement. In addition to /// every "executable block", this also includes C# embedded statement owners. /// </summary> bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node); IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node); bool AreEquivalent(SyntaxToken token1, SyntaxToken token2); bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2); string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null); SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position); SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true); SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node); SyntaxToken FindTokenOnLeftOfPosition(SyntaxNode node, int position, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false); SyntaxToken FindTokenOnRightOfPosition(SyntaxNode node, int position, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false); void GetPartsOfParenthesizedExpression(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen); [return: NotNullIfNotNull("node")] SyntaxNode? WalkDownParentheses(SyntaxNode? node); [return: NotNullIfNotNull("node")] SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false); bool IsClassDeclaration([NotNullWhen(true)] SyntaxNode? node); bool IsNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetNameOfNamespaceDeclaration(SyntaxNode? node); List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root); List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root); SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration); SyntaxList<SyntaxNode> GetMembersOfNamespaceDeclaration(SyntaxNode namespaceDeclaration); SyntaxList<SyntaxNode> GetMembersOfCompilationUnit(SyntaxNode compilationUnit); SyntaxList<SyntaxNode> GetImportsOfNamespaceDeclaration(SyntaxNode namespaceDeclaration); SyntaxList<SyntaxNode> GetImportsOfCompilationUnit(SyntaxNode compilationUnit); bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span); TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree tree, int position, CancellationToken cancellationToken); /// <summary> /// Given a <see cref="SyntaxNode"/>, return the <see cref="TextSpan"/> representing the span of the member body /// it is contained within. This <see cref="TextSpan"/> is used to determine whether speculative binding should be /// used in performance-critical typing scenarios. Note: if this method fails to find a relevant span, it returns /// an empty <see cref="TextSpan"/> at position 0. /// </summary> TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node); /// <summary> /// Returns the parent node that binds to the symbols that the IDE prefers for features like Quick Info and Find /// All References. For example, if the token is part of the type of an object creation, the parenting object /// creation expression is returned so that binding will return constructor symbols. /// </summary> SyntaxNode? TryGetBindableParent(SyntaxToken token); IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken); bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace); /// <summary> /// Given a <see cref="SyntaxNode"/>, that represents and argument return the string representation of /// that arguments name. /// </summary> string GetNameForArgument(SyntaxNode? argument); /// <summary> /// Given a <see cref="SyntaxNode"/>, that represents an attribute argument return the string representation of /// that arguments name. /// </summary> string GetNameForAttributeArgument(SyntaxNode? argument); bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node); bool IsPropertyPatternClause(SyntaxNode node); bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node); bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node); bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node); bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node); bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node); bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node); bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node); bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node); bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node); bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node); bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node); bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node); void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen); void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation); void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation); void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern); SyntaxNode GetTypeOfTypePattern(SyntaxNode node); /// <summary> /// <paramref name="fullHeader"/> controls how much of the type header should be considered. If <see /// langword="false"/> only the span up through the type name will be considered. If <see langword="true"/> /// then the span through the base-list will be considered. /// </summary> bool IsOnTypeHeader(SyntaxNode root, int position, bool fullHeader, [NotNullWhen(true)] out SyntaxNode? typeDeclaration); bool IsOnPropertyDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? propertyDeclaration); bool IsOnParameterHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? parameter); bool IsOnMethodHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? method); bool IsOnLocalFunctionHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localFunction); bool IsOnLocalDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localDeclaration); bool IsOnIfStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? ifStatement); bool IsOnWhileStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? whileStatement); bool IsOnForeachHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? foreachStatement); bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration); SyntaxNode? GetNextExecutableStatement(SyntaxNode statement); bool ContainsInterleavedDirective(SyntaxNode node, CancellationToken cancellationToken); bool ContainsInterleavedDirective(ImmutableArray<SyntaxNode> nodes, CancellationToken cancellationToken); SyntaxTokenList GetModifiers(SyntaxNode? node); [return: NotNullIfNotNull("node")] SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers); Location GetDeconstructionReferenceLocation(SyntaxNode node); SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token); bool SpansPreprocessorDirective(IEnumerable<SyntaxNode> nodes); bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node); SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia); bool CanHaveAccessibility(SyntaxNode declaration); /// <summary> /// Gets the accessibility of the declaration. /// </summary> Accessibility GetAccessibility(SyntaxNode declaration); void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers modifiers, out bool isDefault); SyntaxTokenList GetModifierTokens(SyntaxNode? declaration); /// <summary> /// Gets the <see cref="DeclarationKind"/> for the declaration. /// </summary> DeclarationKind GetDeclarationKind(SyntaxNode declaration); bool IsImplicitObjectCreation([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfThrowExpression(SyntaxNode throwExpression); bool IsThrowStatement([NotNullWhen(true)] SyntaxNode? node); bool IsLocalFunction([NotNullWhen(true)] SyntaxNode? node); } [Flags] internal enum DisplayNameOptions { None = 0, IncludeMemberKeyword = 1, IncludeNamespaces = 1 << 1, IncludeParameters = 1 << 2, IncludeType = 1 << 3, IncludeTypeParameters = 1 << 4 } }
// Licensed to the .NET Foundation under one or more 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.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.Text; #if CODE_STYLE using Microsoft.CodeAnalysis.Internal.Editing; #else using Microsoft.CodeAnalysis.Editing; #endif namespace Microsoft.CodeAnalysis.LanguageServices { /// <summary> /// Contains helpers to allow features and other algorithms to run over C# and Visual Basic code in a uniform fashion. /// It should be thought of a generalized way to apply type-pattern-matching and syntax-deconstruction in a uniform /// fashion over the languages. Helpers in this type should only be one of the following forms: /// <list type="bullet"> /// <item> /// 'IsXXX' where 'XXX' exactly matches one of the same named syntax (node, token, trivia, list, etc.) constructs that /// both C# and VB have. For example 'IsSimpleName' to correspond to C# and VB's SimpleNameSyntax node. These 'checking' /// methods should never fail. /// </item> /// <item> /// 'GetXxxOfYYY' where 'XXX' matches the name of a property on a 'YYY' syntax construct that both C# and VB have. For /// example 'GetExpressionOfMemberAccessExpression' corresponding to MemberAccessExpressionsyntax.Expression in both C# and /// VB. These functions should throw if passed a node that the corresponding 'IsYYY' did not return <see langword="true"/> for. /// </item> /// <item> /// 'GetPartsOfXXX(SyntaxNode node, out SyntaxNode/SyntaxToken part1, ...)' where 'XXX' one of the same named Syntax constructs /// that both C# and VB have, and where the returned parts correspond to the members those nodes have in common across the /// languages. For example 'GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken dotToken, out SyntaxNode right)' /// VB. These functions should throw if passed a node that the corresponding 'IsXXX' did not return <see langword="true"/> for. /// </item> /// <item> /// Absolutely trivial questions that relate to syntax and can be asked sensibly of each language. For example, /// if certain constructs (like 'patterns') are supported in that language or not. /// </item> /// </list> /// /// <para>Importantly, avoid:</para> /// /// <list type="bullet"> /// <item> /// Functions that attempt to blur the lines between similar constructs in the same language. For example, a QualifiedName /// is not the same as a MemberAccessExpression (despite A.B being representable as either depending on context). /// Features that need to handle both should make it clear that they are doing so, showing that they're doing the right /// thing for the contexts each can arise in (for the above example in 'type' vs 'expression' contexts). /// </item> /// <item> /// Functions which are effectively specific to a single feature are are just trying to find a place to place complex /// feature logic in a place such that it can run over VB or C#. For example, a function to determine if a position /// is on the 'header' of a node. a 'header' is a not a well defined syntax concept that can be trivially asked of /// nodes in either language. It is an excapsulation of a feature (or set of features) level idea that should be in /// its own dedicated service. /// </item> /// <item> /// Functions that mutate or update syntax constructs for example 'WithXXX'. These should be on SyntaxGenerator or /// some other feature specific service. /// </item> /// <item> /// Functions that a single item when one language may allow for multiple. For example 'GetIdentifierOfVariableDeclarator'. /// In VB a VariableDeclarator can itself have several names, so calling code must be written to check for that and handle /// it apropriately. Functions like this make it seem like that doesn't need to be considered, easily allowing for bugs /// to creep in. /// </item> /// </list> /// </summary> /// <remarks> /// Many helpers in this type currently violate the above 'dos' and 'do nots'. They should be removed and either /// inlined directly into the feature that needs if (if only a single feature), or moved into a dedicated service /// for that purpose if needed by multiple features. /// </remarks> internal interface ISyntaxFacts { bool IsCaseSensitive { get; } StringComparer StringComparer { get; } SyntaxTrivia ElasticMarker { get; } SyntaxTrivia ElasticCarriageReturnLineFeed { get; } ISyntaxKinds SyntaxKinds { get; } bool SupportsIndexingInitializer(ParseOptions options); bool SupportsLocalFunctionDeclaration(ParseOptions options); bool SupportsNotPattern(ParseOptions options); bool SupportsRecord(ParseOptions options); bool SupportsRecordStruct(ParseOptions options); bool SupportsThrowExpression(ParseOptions options); SyntaxToken ParseToken(string text); SyntaxTriviaList ParseLeadingTrivia(string text); string EscapeIdentifier(string identifier); bool IsVerbatimIdentifier(SyntaxToken token); bool IsOperator(SyntaxToken token); bool IsPredefinedType(SyntaxToken token); bool IsPredefinedType(SyntaxToken token, PredefinedType type); bool IsPredefinedOperator(SyntaxToken token); bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op); /// <summary> /// Returns 'true' if this a 'reserved' keyword for the language. A 'reserved' keyword is a /// identifier that is always treated as being a special keyword, regardless of where it is /// found in the token stream. Examples of this are tokens like <see langword="class"/> and /// <see langword="Class"/> in C# and VB respectively. /// /// Importantly, this does *not* include contextual keywords. If contextual keywords are /// important for your scenario, use <see cref="IsContextualKeyword"/> or <see /// cref="ISyntaxFactsExtensions.IsReservedOrContextualKeyword"/>. Also, consider using /// <see cref="ISyntaxFactsExtensions.IsWord"/> if all you need is the ability to know /// if this is effectively any identifier in the language, regardless of whether the language /// is treating it as a keyword or not. /// </summary> bool IsReservedKeyword(SyntaxToken token); /// <summary> /// Returns <see langword="true"/> if this a 'contextual' keyword for the language. A /// 'contextual' keyword is a identifier that is only treated as being a special keyword in /// certain *syntactic* contexts. Examples of this is 'yield' in C#. This is only a /// keyword if used as 'yield return' or 'yield break'. Importantly, identifiers like <see /// langword="var"/>, <see langword="dynamic"/> and <see langword="nameof"/> are *not* /// 'contextual' keywords. This is because they are not treated as keywords depending on /// the syntactic context around them. Instead, the language always treats them identifiers /// that have special *semantic* meaning if they end up not binding to an existing symbol. /// /// Importantly, if <paramref name="token"/> is not in the syntactic construct where the /// language thinks an identifier should be contextually treated as a keyword, then this /// will return <see langword="false"/>. /// /// Or, in other words, the parser must be able to identify these cases in order to be a /// contextual keyword. If identification happens afterwards, it's not contextual. /// </summary> bool IsContextualKeyword(SyntaxToken token); /// <summary> /// The set of identifiers that have special meaning directly after the `#` token in a /// preprocessor directive. For example `if` or `pragma`. /// </summary> bool IsPreprocessorKeyword(SyntaxToken token); bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken); bool IsLiteral(SyntaxToken token); bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token); bool IsNumericLiteral(SyntaxToken token); bool IsVerbatimStringLiteral(SyntaxToken token); bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent); bool IsTypeNamedDynamic(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent); bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node); bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node); bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node); bool IsDeclaration(SyntaxNode node); bool IsTypeDeclaration(SyntaxNode node); bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfUsingAliasDirective(SyntaxNode node, out SyntaxToken globalKeyword, out SyntaxToken alias, out SyntaxNode name); bool IsRegularComment(SyntaxTrivia trivia); bool IsDocumentationComment(SyntaxTrivia trivia); bool IsElastic(SyntaxTrivia trivia); bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes); bool IsSingleLineCommentTrivia(SyntaxTrivia trivia); bool IsMultiLineCommentTrivia(SyntaxTrivia trivia); bool IsSingleLineDocCommentTrivia(SyntaxTrivia trivia); bool IsMultiLineDocCommentTrivia(SyntaxTrivia trivia); bool IsShebangDirectiveTrivia(SyntaxTrivia trivia); bool IsPreprocessorDirective(SyntaxTrivia trivia); bool IsDocumentationComment(SyntaxNode node); bool IsNumericLiteralExpression([NotNullWhen(true)] SyntaxNode? node); bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node); string GetText(int kind); bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken); bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type); bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op); bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? directive, out ExternalSourceInfo info); // Violation. Should be named IsTypeOfObjectCreationExpression bool IsObjectCreationExpressionType([NotNullWhen(true)] SyntaxNode? node); // Violation. Should be named GetInitializerOfObjectCreationExpression SyntaxNode? GetObjectCreationInitializer(SyntaxNode node); // Violation. Should be named GetTypeOfObjectCreationExpression SyntaxNode GetObjectCreationType(SyntaxNode node); bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node); bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right); void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse); bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node); bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression); bool IsExpressionOfInvocationExpression(SyntaxNode? node); void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList); SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node); bool IsExpressionOfAwaitExpression([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node); bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node, out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode; void GetPartsOfInterpolationExpression(SyntaxNode node, out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken); bool IsVerbatimInterpolatedStringExpression(SyntaxNode node); SyntaxNode GetOperandOfPrefixUnaryExpression(SyntaxNode node); SyntaxToken GetOperatorTokenOfPrefixUnaryExpression(SyntaxNode node); // Left side of = assignment. bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node); bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement); void GetPartsOfAssignmentStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfAssignmentExpressionOrStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); // Left side of any assignment (for example = or ??= or *= or += ) bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node); // Left side of compound assignment (for example ??= or *= or += ) bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetRightHandSideOfAssignment(SyntaxNode node); bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node); bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node); bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node); bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetRightSideOfDot(SyntaxNode? node); /// <summary> /// Get the node on the left side of the dot if given a dotted expression. /// </summary> /// <param name="allowImplicitTarget"> /// In VB, we have a member access expression with a null expression, this may be one of the /// following forms: /// 1) new With { .a = 1, .b = .a .a refers to the anonymous type /// 2) With obj : .m .m refers to the obj type /// 3) new T() With { .a = 1, .b = .a 'a refers to the T type /// If `allowImplicitTarget` is set to true, the returned node will be set to approperiate node, otherwise, it will return null. /// This parameter has no affect on C# node. /// </param> SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget = false); bool IsRightSideOfQualifiedName([NotNullWhen(true)] SyntaxNode? node); bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node); void GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken dotToken, out SyntaxNode right); bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// Gets the containing expression that is actually a language expression and not just typed /// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side /// of qualified names and member access expressions are not language expressions, yet the /// containing qualified names or member access expressions are indeed expressions. /// </summary> [return: NotNullIfNotNull("node")] SyntaxNode? GetStandaloneExpression(SyntaxNode? node); /// <summary> /// Call on the `.y` part of a `x?.y` to get the entire `x?.y` conditional access expression. This also works /// when there are multiple chained conditional accesses. For example, calling this on '.y' or '.z' in /// `x?.y?.z` will both return the full `x?.y?.z` node. This can be used to effectively get 'out' of the RHS of /// a conditional access, and commonly represents the full standalone expression that can be operated on /// atomically. /// </summary> SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node); bool IsExpressionOfMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetNameOfMemberAccessExpression(SyntaxNode node); /// <summary> /// Returns the expression node the member is being accessed off of. If <paramref name="allowImplicitTarget"/> /// is <see langword="false"/>, this will be the node directly to the left of the dot-token. If <paramref name="allowImplicitTarget"/> /// is <see langword="true"/>, then this can return another node in the tree that the member will be accessed /// off of. For example, in VB, if you have a member-access-expression of the form ".Length" then this /// may return the expression in the surrounding With-statement. /// </summary> SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode node, bool allowImplicitTarget = false); void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name); SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node); SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node); bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node); bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node); SyntaxToken? GetNameOfParameter([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetDefaultOfParameter(SyntaxNode node); SyntaxNode? GetParameterList(SyntaxNode node); bool IsParameterList([NotNullWhen(true)] SyntaxNode? node); bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia); void GetPartsOfElementAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList); SyntaxNode GetExpressionOfArgument(SyntaxNode node); SyntaxNode GetExpressionOfInterpolation(SyntaxNode node); SyntaxNode GetNameOfAttribute(SyntaxNode node); void GetPartsOfConditionalAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull); bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node); bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfParenthesizedExpression(SyntaxNode node); // Violation. Parameter shoudl not nullable. SyntaxToken GetIdentifierOfGenericName(SyntaxNode? node); SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node); SyntaxToken GetIdentifierOfParameter(SyntaxNode node); SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node); SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node); SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node); SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node); /// <summary> /// True if this is an argument with just an expression and nothing else (i.e. no ref/out, /// no named params, no omitted args). /// </summary> bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node); bool IsArgument([NotNullWhen(true)] SyntaxNode? node); RefKind GetRefKindOfArgument(SyntaxNode node); bool IsSimpleName([NotNullWhen(true)] SyntaxNode? node); void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity); bool LooksGeneric(SyntaxNode simpleName); SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode node); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode node); SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode node); // Violation. Return value should be nullable as VB has invocations without an argument list node. SyntaxNode GetArgumentListOfInvocationExpression(SyntaxNode node); SyntaxNode? GetArgumentListOfObjectCreationExpression(SyntaxNode node); bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node); bool IsAttributeName(SyntaxNode node); // Violation. Doesn't correspond to any shared structure for vb/c# SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node); bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node); bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node); bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance); bool IsDirective([NotNullWhen(true)] SyntaxNode? node); bool IsStatement([NotNullWhen(true)] SyntaxNode? node); bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node); bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node); bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// Returns true for nodes that represent the body of a method. /// /// For VB this will be /// MethodBlockBaseSyntax. This will be true for things like constructor, method, operator /// bodies as well as accessor bodies. It will not be true for things like sub() function() /// lambdas. /// /// For C# this will be the BlockSyntax or ArrowExpressionSyntax for a /// method/constructor/deconstructor/operator/accessor. It will not be included for local /// functions. /// </summary> bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node); SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode node); bool IsLocalFunctionStatement([NotNullWhen(true)] SyntaxNode? node); bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement); SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node); SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node); SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node); bool IsThisConstructorInitializer(SyntaxToken token); bool IsBaseConstructorInitializer(SyntaxToken token); bool IsQueryKeyword(SyntaxToken token); bool IsThrowExpression(SyntaxNode node); bool IsElementAccessExpression([NotNullWhen(true)] SyntaxNode? node); bool IsIndexerMemberCRef([NotNullWhen(true)] SyntaxNode? node); bool IsIdentifierStartCharacter(char c); bool IsIdentifierPartCharacter(char c); bool IsIdentifierEscapeCharacter(char c); bool IsStartOfUnicodeEscapeSequence(char c); bool IsValidIdentifier(string identifier); bool IsVerbatimIdentifier(string identifier); /// <summary> /// Returns true if the given character is a character which may be included in an /// identifier to specify the type of a variable. /// </summary> bool IsTypeCharacter(char c); // Violation. This is a feature level API for QuickInfo. bool IsBindableToken(SyntaxToken token); bool IsInStaticContext(SyntaxNode node); bool IsUnsafeContext(SyntaxNode node); // Violation. This is a feature level API. bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node); bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node); bool IsAnonymousFunction([NotNullWhen(true)] SyntaxNode? n); bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node); bool IsInConstructor(SyntaxNode node); bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node); bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node); bool HasIncompleteParentMember([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// A block that has no semantics other than introducing a new scope. That is only C# BlockSyntax. /// </summary> bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node); /// <summary> /// A node that contains a list of statements. In C#, this is BlockSyntax and SwitchSectionSyntax. /// In VB, this includes all block statements such as a MultiLineIfBlockSyntax. /// </summary> bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node); // Violation. This should return a SyntaxList IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node); // Violation. This is a feature level API. SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes); /// <summary> /// A node that can host a list of statements or a single statement. In addition to /// every "executable block", this also includes C# embedded statement owners. /// </summary> // Violation. This is a feature level API. bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node); // Violation. This is a feature level API. IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node); bool AreEquivalent(SyntaxToken token1, SyntaxToken token2); bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2); string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null); // Violation. This is a feature level API. How 'position' relates to 'containment' is not defined. SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position); SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true); SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node); SyntaxToken FindTokenOnLeftOfPosition(SyntaxNode node, int position, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false); SyntaxToken FindTokenOnRightOfPosition(SyntaxNode node, int position, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false); void GetPartsOfParenthesizedExpression(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen); [return: NotNullIfNotNull("node")] SyntaxNode? WalkDownParentheses(SyntaxNode? node); // Violation. This is a feature level API. [return: NotNullIfNotNull("node")] SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false); bool IsClassDeclaration([NotNullWhen(true)] SyntaxNode? node); bool IsNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetNameOfNamespaceDeclaration(SyntaxNode node); // Violation. This is a feature level API. List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root); // Violation. This is a feature level API. List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root); SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration); SyntaxList<SyntaxNode> GetMembersOfNamespaceDeclaration(SyntaxNode namespaceDeclaration); SyntaxList<SyntaxNode> GetMembersOfCompilationUnit(SyntaxNode compilationUnit); SyntaxList<SyntaxNode> GetImportsOfNamespaceDeclaration(SyntaxNode namespaceDeclaration); SyntaxList<SyntaxNode> GetImportsOfCompilationUnit(SyntaxNode compilationUnit); // Violation. This is a feature level API. bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span); // Violation. This is a feature level API. TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree tree, int position, CancellationToken cancellationToken); /// <summary> /// Given a <see cref="SyntaxNode"/>, return the <see cref="TextSpan"/> representing the span of the member body /// it is contained within. This <see cref="TextSpan"/> is used to determine whether speculative binding should be /// used in performance-critical typing scenarios. Note: if this method fails to find a relevant span, it returns /// an empty <see cref="TextSpan"/> at position 0. /// </summary> // Violation. This is a feature level API. TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node); /// <summary> /// Returns the parent node that binds to the symbols that the IDE prefers for features like Quick Info and Find /// All References. For example, if the token is part of the type of an object creation, the parenting object /// creation expression is returned so that binding will return constructor symbols. /// </summary> // Violation. This is a feature level API. SyntaxNode? TryGetBindableParent(SyntaxToken token); // Violation. This is a feature level API. IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken); // Violation. This is a feature level API. bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace); /// <summary> /// Given a <see cref="SyntaxNode"/>, that represents and argument return the string representation of /// that arguments name. /// </summary> // Violation. This is a feature level API. string GetNameForArgument(SyntaxNode? argument); /// <summary> /// Given a <see cref="SyntaxNode"/>, that represents an attribute argument return the string representation of /// that arguments name. /// </summary> // Violation. This is a feature level API. string GetNameForAttributeArgument(SyntaxNode? argument); bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node); bool IsPropertyPatternClause(SyntaxNode node); bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node); bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node); bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node); bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node); bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node); bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node); bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node); bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node); bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node); bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node); bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node); bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node); void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen); void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right); void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation); void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation); void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern); SyntaxNode GetTypeOfTypePattern(SyntaxNode node); /// <summary> /// <paramref name="fullHeader"/> controls how much of the type header should be considered. If <see /// langword="false"/> only the span up through the type name will be considered. If <see langword="true"/> /// then the span through the base-list will be considered. /// </summary> // Violation. This is a feature level API. bool IsOnTypeHeader(SyntaxNode root, int position, bool fullHeader, [NotNullWhen(true)] out SyntaxNode? typeDeclaration); bool IsOnPropertyDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? propertyDeclaration); bool IsOnParameterHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? parameter); bool IsOnMethodHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? method); bool IsOnLocalFunctionHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localFunction); bool IsOnLocalDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localDeclaration); bool IsOnIfStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? ifStatement); bool IsOnWhileStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? whileStatement); bool IsOnForeachHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? foreachStatement); bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration); // Violation. This is a feature level API. SyntaxNode? GetNextExecutableStatement(SyntaxNode statement); bool ContainsInterleavedDirective(SyntaxNode node, CancellationToken cancellationToken); bool ContainsInterleavedDirective(ImmutableArray<SyntaxNode> nodes, CancellationToken cancellationToken); SyntaxTokenList GetModifiers(SyntaxNode? node); // Violation. WithXXX methods should not be here, but should be in SyntaxGenerator. [return: NotNullIfNotNull("node")] SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers); // Violation. This is a feature level API. Location GetDeconstructionReferenceLocation(SyntaxNode node); // Violation. This is a feature level API. SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token); bool SpansPreprocessorDirective(IEnumerable<SyntaxNode> nodes); bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node); SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia); bool CanHaveAccessibility(SyntaxNode declaration); /// <summary> /// Gets the accessibility of the declaration. /// </summary> // Violation. This is a not a concrete syntactic concept over C#/VB syntax nodes. This should be on SyntaxGenerator // (which provide syntactic abstractions like 'Accessibility' questions). Accessibility GetAccessibility(SyntaxNode declaration); void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers modifiers, out bool isDefault); SyntaxTokenList GetModifierTokens(SyntaxNode? declaration); /// <summary> /// Gets the <see cref="DeclarationKind"/> for the declaration. /// </summary> DeclarationKind GetDeclarationKind(SyntaxNode declaration); bool IsImplicitObjectCreation([NotNullWhen(true)] SyntaxNode? node); SyntaxNode GetExpressionOfThrowExpression(SyntaxNode throwExpression); bool IsThrowStatement([NotNullWhen(true)] SyntaxNode? node); bool IsLocalFunction([NotNullWhen(true)] SyntaxNode? node); } [Flags] internal enum DisplayNameOptions { None = 0, IncludeMemberKeyword = 1, IncludeNamespaces = 1 << 1, IncludeParameters = 1 << 2, IncludeType = 1 << 3, IncludeTypeParameters = 1 << 4 } }
1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxFacts.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.Text Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts #If CODE_STYLE Then Imports Microsoft.CodeAnalysis.Internal.Editing #Else Imports Microsoft.CodeAnalysis.Editing #End If Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices Friend Class VisualBasicSyntaxFacts Inherits AbstractSyntaxFacts Implements ISyntaxFacts Public Shared ReadOnly Property Instance As New VisualBasicSyntaxFacts Protected Sub New() End Sub Public ReadOnly Property IsCaseSensitive As Boolean Implements ISyntaxFacts.IsCaseSensitive Get Return False End Get End Property Public ReadOnly Property StringComparer As StringComparer Implements ISyntaxFacts.StringComparer Get Return CaseInsensitiveComparison.Comparer End Get End Property Public ReadOnly Property ElasticMarker As SyntaxTrivia Implements ISyntaxFacts.ElasticMarker Get Return SyntaxFactory.ElasticMarker End Get End Property Public ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia Implements ISyntaxFacts.ElasticCarriageReturnLineFeed Get Return SyntaxFactory.ElasticCarriageReturnLineFeed End Get End Property Public Overrides ReadOnly Property SyntaxKinds As ISyntaxKinds = VisualBasicSyntaxKinds.Instance Implements ISyntaxFacts.SyntaxKinds Public Function SupportsIndexingInitializer(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsIndexingInitializer Return False End Function Public Function SupportsThrowExpression(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsThrowExpression Return False End Function Public Function SupportsLocalFunctionDeclaration(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsLocalFunctionDeclaration Return False End Function Public Function SupportsRecord(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecord Return False End Function Public Function SupportsRecordStruct(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecordStruct Return False End Function Public Function ParseToken(text As String) As SyntaxToken Implements ISyntaxFacts.ParseToken Return SyntaxFactory.ParseToken(text, startStatement:=True) End Function Public Function ParseLeadingTrivia(text As String) As SyntaxTriviaList Implements ISyntaxFacts.ParseLeadingTrivia Return SyntaxFactory.ParseLeadingTrivia(text) End Function Public Function EscapeIdentifier(identifier As String) As String Implements ISyntaxFacts.EscapeIdentifier Dim keywordKind = SyntaxFacts.GetKeywordKind(identifier) Dim needsEscaping = keywordKind <> SyntaxKind.None Return If(needsEscaping, "[" & identifier & "]", identifier) End Function Public Function IsVerbatimIdentifier(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier Return False End Function Public Function IsOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsOperator Return (IsUnaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is UnaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) OrElse (IsBinaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is BinaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) End Function Public Function IsContextualKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsContextualKeyword Return token.IsContextualKeyword() End Function Public Function IsReservedKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsReservedKeyword Return token.IsReservedKeyword() End Function Public Function IsPreprocessorKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPreprocessorKeyword Return token.IsPreprocessorKeyword() End Function Public Function IsPreProcessorDirectiveContext(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsPreProcessorDirectiveContext Return syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken) End Function Public Function TryGetCorrespondingOpenBrace(token As SyntaxToken, ByRef openBrace As SyntaxToken) As Boolean Implements ISyntaxFacts.TryGetCorrespondingOpenBrace If token.Kind = SyntaxKind.CloseBraceToken Then Dim tuples = token.Parent.GetBraces() openBrace = tuples.openBrace Return openBrace.Kind = SyntaxKind.OpenBraceToken End If Return False End Function Public Function IsEntirelyWithinStringOrCharOrNumericLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsEntirelyWithinStringOrCharOrNumericLiteral If syntaxTree Is Nothing Then Return False End If Return syntaxTree.IsEntirelyWithinStringOrCharOrNumericLiteral(position, cancellationToken) End Function Public Function IsDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDirective Return TypeOf node Is DirectiveTriviaSyntax End Function Public Function TryGetExternalSourceInfo(node As SyntaxNode, ByRef info As ExternalSourceInfo) As Boolean Implements ISyntaxFacts.TryGetExternalSourceInfo Select Case node.Kind Case SyntaxKind.ExternalSourceDirectiveTrivia info = New ExternalSourceInfo(CInt(DirectCast(node, ExternalSourceDirectiveTriviaSyntax).LineStart.Value), False) Return True Case SyntaxKind.EndExternalSourceDirectiveTrivia info = New ExternalSourceInfo(Nothing, True) Return True End Select Return False End Function Public Function IsObjectCreationExpressionType(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsObjectCreationExpressionType Return node.IsParentKind(SyntaxKind.ObjectCreationExpression) AndAlso DirectCast(node.Parent, ObjectCreationExpressionSyntax).Type Is node End Function Public Function IsDeclarationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationExpression ' VB doesn't support declaration expressions Return False End Function Public Function IsAttributeName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeName Return node.IsParentKind(SyntaxKind.Attribute) AndAlso DirectCast(node.Parent, AttributeSyntax).Name Is node End Function Public Sub GetPartsOfQualifiedName(node As SyntaxNode, ByRef left As SyntaxNode, ByRef dotToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfQualifiedName Dim qualifiedName = DirectCast(node, QualifiedNameSyntax) left = qualifiedName.Left dotToken = qualifiedName.DotToken right = qualifiedName.Right End Sub Public Function IsRightSideOfQualifiedName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRightSideOfQualifiedName Dim vbNode = TryCast(node, SimpleNameSyntax) Return vbNode IsNot Nothing AndAlso vbNode.IsRightSideOfQualifiedName() End Function Public Function IsNameOfSimpleMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSimpleMemberAccessExpression Dim vbNode = TryCast(node, ExpressionSyntax) Return vbNode IsNot Nothing AndAlso vbNode.IsSimpleMemberAccessExpressionName() End Function Public Function IsNameOfAnyMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfAnyMemberAccessExpression Dim memberAccess = TryCast(node?.Parent, MemberAccessExpressionSyntax) Return memberAccess IsNot Nothing AndAlso memberAccess.Name Is node End Function Public Function GetStandaloneExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetStandaloneExpression Return SyntaxFactory.GetStandaloneExpression(TryCast(node, ExpressionSyntax)) End Function Public Function GetRootConditionalAccessExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRootConditionalAccessExpression Return TryCast(node, ExpressionSyntax).GetRootConditionalAccessExpression() End Function Public Sub GetPartsOfConditionalAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef whenNotNull As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalAccessExpression Dim conditionalAccess = DirectCast(node, ConditionalAccessExpressionSyntax) expression = conditionalAccess.Expression operatorToken = conditionalAccess.QuestionMarkToken whenNotNull = conditionalAccess.WhenNotNull End Sub Public Function IsAnonymousFunction(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnonymousFunction Return TypeOf node Is LambdaExpressionSyntax End Function Public Function IsNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamedArgument Dim arg = TryCast(node, SimpleArgumentSyntax) Return arg?.NameColonEquals IsNot Nothing End Function Public Function IsNameOfNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfNamedArgument Return node.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.IsNamed AndAlso p.NameColonEquals.Name Is node) End Function Public Function GetNameOfParameter(node As SyntaxNode) As SyntaxToken? Implements ISyntaxFacts.GetNameOfParameter Return TryCast(node, ParameterSyntax)?.Identifier?.Identifier End Function Public Function GetDefaultOfParameter(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetDefaultOfParameter Return TryCast(node, ParameterSyntax)?.Default End Function Public Function GetParameterList(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetParameterList Return node.GetParameterList() End Function Public Function IsParameterList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterList Return node.IsKind(SyntaxKind.ParameterList) End Function Public Function ISyntaxFacts_HasIncompleteParentMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.HasIncompleteParentMember Return HasIncompleteParentMember(node) End Function Public Function GetIdentifierOfGenericName(genericName As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfGenericName Dim vbGenericName = TryCast(genericName, GenericNameSyntax) Return If(vbGenericName IsNot Nothing, vbGenericName.Identifier, Nothing) End Function Public Function IsUsingDirectiveName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingDirectiveName Return node.IsParentKind(SyntaxKind.SimpleImportsClause) AndAlso DirectCast(node.Parent, SimpleImportsClauseSyntax).Name Is node End Function Public Function IsDeconstructionAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionAssignment Return False End Function Public Function IsDeconstructionForEachStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionForEachStatement Return False End Function Public Function IsStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatement Return TypeOf node Is StatementSyntax End Function Public Function IsExecutableStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableStatement Return TypeOf node Is ExecutableStatementSyntax End Function Public Function IsMethodBody(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodBody Return TypeOf node Is MethodBlockBaseSyntax End Function Public Function GetExpressionOfReturnStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfReturnStatement Return TryCast(node, ReturnStatementSyntax)?.Expression End Function Public Function IsThisConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsThisConstructorInitializer If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax) Return memberAccess.IsThisConstructorInitializer() End If Return False End Function Public Function IsBaseConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsBaseConstructorInitializer If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax) Return memberAccess.IsBaseConstructorInitializer() End If Return False End Function Public Function IsQueryKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsQueryKeyword Select Case token.Kind() Case _ SyntaxKind.JoinKeyword, SyntaxKind.IntoKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword, SyntaxKind.ByKeyword, SyntaxKind.OrderKeyword, SyntaxKind.WhereKeyword, SyntaxKind.OnKeyword, SyntaxKind.FromKeyword, SyntaxKind.WhileKeyword, SyntaxKind.SelectKeyword Return TypeOf token.Parent Is QueryClauseSyntax Case SyntaxKind.GroupKeyword Return (TypeOf token.Parent Is QueryClauseSyntax) OrElse (token.Parent.IsKind(SyntaxKind.GroupAggregation)) Case SyntaxKind.EqualsKeyword Return TypeOf token.Parent Is JoinConditionSyntax Case SyntaxKind.AscendingKeyword, SyntaxKind.DescendingKeyword Return TypeOf token.Parent Is OrderingSyntax Case SyntaxKind.InKeyword Return TypeOf token.Parent Is CollectionRangeVariableSyntax Case Else Return False End Select End Function Public Function IsThrowExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsThrowExpression ' VB does not support throw expressions currently. Return False End Function Public Function IsPredefinedType(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedType Dim actualType As PredefinedType = PredefinedType.None Return TryGetPredefinedType(token, actualType) AndAlso actualType <> PredefinedType.None End Function Public Function IsPredefinedType(token As SyntaxToken, type As PredefinedType) As Boolean Implements ISyntaxFacts.IsPredefinedType Dim actualType As PredefinedType = PredefinedType.None Return TryGetPredefinedType(token, actualType) AndAlso actualType = type End Function Public Function TryGetPredefinedType(token As SyntaxToken, ByRef type As PredefinedType) As Boolean Implements ISyntaxFacts.TryGetPredefinedType type = GetPredefinedType(token) Return type <> PredefinedType.None End Function Private Shared Function GetPredefinedType(token As SyntaxToken) As PredefinedType Select Case token.Kind Case SyntaxKind.BooleanKeyword Return PredefinedType.Boolean Case SyntaxKind.ByteKeyword Return PredefinedType.Byte Case SyntaxKind.SByteKeyword Return PredefinedType.SByte Case SyntaxKind.IntegerKeyword Return PredefinedType.Int32 Case SyntaxKind.UIntegerKeyword Return PredefinedType.UInt32 Case SyntaxKind.ShortKeyword Return PredefinedType.Int16 Case SyntaxKind.UShortKeyword Return PredefinedType.UInt16 Case SyntaxKind.LongKeyword Return PredefinedType.Int64 Case SyntaxKind.ULongKeyword Return PredefinedType.UInt64 Case SyntaxKind.SingleKeyword Return PredefinedType.Single Case SyntaxKind.DoubleKeyword Return PredefinedType.Double Case SyntaxKind.DecimalKeyword Return PredefinedType.Decimal Case SyntaxKind.StringKeyword Return PredefinedType.String Case SyntaxKind.CharKeyword Return PredefinedType.Char Case SyntaxKind.ObjectKeyword Return PredefinedType.Object Case SyntaxKind.DateKeyword Return PredefinedType.DateTime Case Else Return PredefinedType.None End Select End Function Public Function IsPredefinedOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedOperator Dim actualOp As PredefinedOperator = PredefinedOperator.None Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp <> PredefinedOperator.None End Function Public Function IsPredefinedOperator(token As SyntaxToken, op As PredefinedOperator) As Boolean Implements ISyntaxFacts.IsPredefinedOperator Dim actualOp As PredefinedOperator = PredefinedOperator.None Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp = op End Function Public Function TryGetPredefinedOperator(token As SyntaxToken, ByRef op As PredefinedOperator) As Boolean Implements ISyntaxFacts.TryGetPredefinedOperator op = GetPredefinedOperator(token) Return op <> PredefinedOperator.None End Function Private Shared Function GetPredefinedOperator(token As SyntaxToken) As PredefinedOperator Select Case token.Kind Case SyntaxKind.PlusToken, SyntaxKind.PlusEqualsToken Return PredefinedOperator.Addition Case SyntaxKind.MinusToken, SyntaxKind.MinusEqualsToken Return PredefinedOperator.Subtraction Case SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword Return PredefinedOperator.BitwiseAnd Case SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword Return PredefinedOperator.BitwiseOr Case SyntaxKind.AmpersandToken, SyntaxKind.AmpersandEqualsToken Return PredefinedOperator.Concatenate Case SyntaxKind.SlashToken, SyntaxKind.SlashEqualsToken Return PredefinedOperator.Division Case SyntaxKind.EqualsToken Return PredefinedOperator.Equality Case SyntaxKind.XorKeyword Return PredefinedOperator.ExclusiveOr Case SyntaxKind.CaretToken, SyntaxKind.CaretEqualsToken Return PredefinedOperator.Exponent Case SyntaxKind.GreaterThanToken Return PredefinedOperator.GreaterThan Case SyntaxKind.GreaterThanEqualsToken Return PredefinedOperator.GreaterThanOrEqual Case SyntaxKind.LessThanGreaterThanToken Return PredefinedOperator.Inequality Case SyntaxKind.BackslashToken, SyntaxKind.BackslashEqualsToken Return PredefinedOperator.IntegerDivision Case SyntaxKind.LessThanLessThanToken, SyntaxKind.LessThanLessThanEqualsToken Return PredefinedOperator.LeftShift Case SyntaxKind.LessThanToken Return PredefinedOperator.LessThan Case SyntaxKind.LessThanEqualsToken Return PredefinedOperator.LessThanOrEqual Case SyntaxKind.LikeKeyword Return PredefinedOperator.Like Case SyntaxKind.NotKeyword Return PredefinedOperator.Complement Case SyntaxKind.ModKeyword Return PredefinedOperator.Modulus Case SyntaxKind.AsteriskToken, SyntaxKind.AsteriskEqualsToken Return PredefinedOperator.Multiplication Case SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.GreaterThanGreaterThanEqualsToken Return PredefinedOperator.RightShift Case Else Return PredefinedOperator.None End Select End Function Public Function GetText(kind As Integer) As String Implements ISyntaxFacts.GetText Return SyntaxFacts.GetText(CType(kind, SyntaxKind)) End Function Public Function IsIdentifierPartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierPartCharacter Return SyntaxFacts.IsIdentifierPartCharacter(c) End Function Public Function IsIdentifierStartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierStartCharacter Return SyntaxFacts.IsIdentifierStartCharacter(c) End Function Public Function IsIdentifierEscapeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierEscapeCharacter Return c = "["c OrElse c = "]"c End Function Public Function IsValidIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsValidIdentifier Dim token = SyntaxFactory.ParseToken(identifier) ' TODO: There is no way to get the diagnostics to see if any are actually errors? Return IsIdentifier(token) AndAlso Not token.ContainsDiagnostics AndAlso token.ToString().Length = identifier.Length End Function Public Function IsVerbatimIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier Return IsValidIdentifier(identifier) AndAlso MakeHalfWidthIdentifier(identifier.First()) = "[" AndAlso MakeHalfWidthIdentifier(identifier.Last()) = "]" End Function Public Function IsTypeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsTypeCharacter Return c = "%"c OrElse c = "&"c OrElse c = "@"c OrElse c = "!"c OrElse c = "#"c OrElse c = "$"c End Function Public Function IsStartOfUnicodeEscapeSequence(c As Char) As Boolean Implements ISyntaxFacts.IsStartOfUnicodeEscapeSequence Return False ' VB does not support identifiers with escaped unicode characters End Function Public Function IsLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsLiteral Select Case token.Kind() Case _ SyntaxKind.IntegerLiteralToken, SyntaxKind.CharacterLiteralToken, SyntaxKind.DecimalLiteralToken, SyntaxKind.FloatingLiteralToken, SyntaxKind.DateLiteralToken, SyntaxKind.StringLiteralToken, SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.DoubleQuoteToken, SyntaxKind.InterpolatedStringTextToken, SyntaxKind.TrueKeyword, SyntaxKind.FalseKeyword, SyntaxKind.NothingKeyword Return True End Select Return False End Function Public Function IsStringLiteralOrInterpolatedStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsStringLiteralOrInterpolatedStringLiteral Return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken) End Function Public Function IsNumericLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNumericLiteralExpression Return If(node Is Nothing, False, node.IsKind(SyntaxKind.NumericLiteralExpression)) End Function Public Function IsBindableToken(token As Microsoft.CodeAnalysis.SyntaxToken) As Boolean Implements ISyntaxFacts.IsBindableToken Return Me.IsWord(token) OrElse Me.IsLiteral(token) OrElse Me.IsOperator(token) End Function Public Function IsPointerMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPointerMemberAccessExpression Return False End Function Public Function IsSimpleName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleName Return TypeOf node Is SimpleNameSyntax End Function Public Sub GetNameAndArityOfSimpleName(node As SyntaxNode, ByRef name As String, ByRef arity As Integer) Implements ISyntaxFacts.GetNameAndArityOfSimpleName Dim simpleName = DirectCast(node, SimpleNameSyntax) name = simpleName.Identifier.ValueText arity = simpleName.Arity End Sub Public Function LooksGeneric(name As SyntaxNode) As Boolean Implements ISyntaxFacts.LooksGeneric Return name.IsKind(SyntaxKind.GenericName) End Function Public Function GetExpressionOfMemberAccessExpression(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfMemberAccessExpression Return TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget) End Function Public Function GetTargetOfMemberBinding(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTargetOfMemberBinding ' Member bindings are a C# concept. Return Nothing End Function Public Function GetNameOfMemberBindingExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberBindingExpression ' Member bindings are a C# concept. Return Nothing End Function Public Sub GetPartsOfElementAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfElementAccessExpression Dim invocation = TryCast(node, InvocationExpressionSyntax) If invocation IsNot Nothing Then expression = invocation?.Expression argumentList = invocation?.ArgumentList Return End If If node.Kind() = SyntaxKind.DictionaryAccessExpression Then GetPartsOfMemberAccessExpression(node, expression, argumentList) Return End If Return End Sub Public Function GetExpressionOfInterpolation(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfInterpolation Return TryCast(node, InterpolationSyntax)?.Expression End Function Public Function IsInNamespaceOrTypeContext(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInNamespaceOrTypeContext Return SyntaxFacts.IsInNamespaceOrTypeContext(node) End Function Public Function IsBaseTypeList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBaseTypeList Return TryCast(node, InheritsOrImplementsStatementSyntax) IsNot Nothing End Function Public Function IsInStaticContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInStaticContext Return node.IsInStaticContext() End Function Public Function GetExpressionOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetExpressionOfArgument Return TryCast(node, ArgumentSyntax).GetArgumentExpression() End Function Public Function GetRefKindOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.RefKind Implements ISyntaxFacts.GetRefKindOfArgument ' TODO(cyrusn): Consider the method this argument is passed to, to determine this. Return RefKind.None End Function Public Function IsArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsArgument Return TypeOf node Is ArgumentSyntax End Function Public Function IsSimpleArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleArgument Dim argument = TryCast(node, ArgumentSyntax) Return argument IsNot Nothing AndAlso Not argument.IsNamed AndAlso Not argument.IsOmitted End Function Public Function IsInConstantContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstantContext Return node.IsInConstantContext() End Function Public Function IsInConstructor(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstructor Return node.GetAncestors(Of StatementSyntax).Any(Function(s) s.Kind = SyntaxKind.ConstructorBlock) End Function Public Function IsUnsafeContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnsafeContext Return False End Function Public Function GetNameOfAttribute(node As SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetNameOfAttribute Return DirectCast(node, AttributeSyntax).Name End Function Public Function GetExpressionOfParenthesizedExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfParenthesizedExpression Return DirectCast(node, ParenthesizedExpressionSyntax).Expression End Function Public Function IsAttributeNamedArgumentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeNamedArgumentIdentifier Dim identifierName = TryCast(node, IdentifierNameSyntax) Return identifierName.IsParentKind(SyntaxKind.NameColonEquals) AndAlso identifierName.Parent.IsParentKind(SyntaxKind.SimpleArgument) AndAlso identifierName.Parent.Parent.IsParentKind(SyntaxKind.ArgumentList) AndAlso identifierName.Parent.Parent.Parent.IsParentKind(SyntaxKind.Attribute) End Function Public Function GetContainingTypeDeclaration(root As SyntaxNode, position As Integer) As SyntaxNode Implements ISyntaxFacts.GetContainingTypeDeclaration If root Is Nothing Then Throw New ArgumentNullException(NameOf(root)) End If If position < 0 OrElse position > root.Span.End Then Throw New ArgumentOutOfRangeException(NameOf(position)) End If Return root. FindToken(position). GetAncestors(Of SyntaxNode)(). FirstOrDefault(Function(n) TypeOf n Is TypeBlockSyntax OrElse TypeOf n Is DelegateStatementSyntax) End Function Public Function GetContainingVariableDeclaratorOfFieldDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetContainingVariableDeclaratorOfFieldDeclaration If node Is Nothing Then Throw New ArgumentNullException(NameOf(node)) End If Dim parent = node.Parent While node IsNot Nothing If node.Kind = SyntaxKind.VariableDeclarator AndAlso node.IsParentKind(SyntaxKind.FieldDeclaration) Then Return node End If node = node.Parent End While Return Nothing End Function Public Function FindTokenOnLeftOfPosition(node As SyntaxNode, position As Integer, Optional includeSkipped As Boolean = True, Optional includeDirectives As Boolean = False, Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFacts.FindTokenOnLeftOfPosition Return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments) End Function Public Function FindTokenOnRightOfPosition(node As SyntaxNode, position As Integer, Optional includeSkipped As Boolean = True, Optional includeDirectives As Boolean = False, Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFacts.FindTokenOnRightOfPosition Return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments) End Function Public Function IsMemberInitializerNamedAssignmentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier Dim unused As SyntaxNode = Nothing Return IsMemberInitializerNamedAssignmentIdentifier(node, unused) End Function Public Function IsMemberInitializerNamedAssignmentIdentifier( node As SyntaxNode, ByRef initializedInstance As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier Dim identifier = TryCast(node, IdentifierNameSyntax) If identifier?.IsChildNode(Of NamedFieldInitializerSyntax)(Function(n) n.Name) Then ' .parent is the NamedField. ' .parent.parent is the ObjectInitializer. ' .parent.parent.parent will be the ObjectCreationExpression. initializedInstance = identifier.Parent.Parent.Parent Return True End If Return False End Function Public Function IsNameOfSubpattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSubpattern Return False End Function Public Function IsPropertyPatternClause(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPropertyPatternClause Return False End Function Public Function IsElementAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsElementAccessExpression ' VB doesn't have a specialized node for element access. Instead, it just uses an ' invocation expression or dictionary access expression. Return node.Kind = SyntaxKind.InvocationExpression OrElse node.Kind = SyntaxKind.DictionaryAccessExpression End Function Public Sub GetPartsOfParenthesizedExpression( node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef expression As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedExpression Dim parenthesizedExpression = DirectCast(node, ParenthesizedExpressionSyntax) openParen = parenthesizedExpression.OpenParenToken expression = parenthesizedExpression.Expression closeParen = parenthesizedExpression.CloseParenToken End Sub Public Function IsTypeNamedVarInVariableOrFieldDeclaration(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeNamedVarInVariableOrFieldDeclaration Return False End Function Public Function IsTypeNamedDynamic(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeNamedDynamic Return False End Function Public Function IsIndexerMemberCRef(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIndexerMemberCRef Return False End Function Public Function GetContainingMemberDeclaration(root As SyntaxNode, position As Integer, Optional useFullSpan As Boolean = True) As SyntaxNode Implements ISyntaxFacts.GetContainingMemberDeclaration Contract.ThrowIfNull(root, NameOf(root)) Contract.ThrowIfTrue(position < 0 OrElse position > root.FullSpan.End, NameOf(position)) Dim [end] = root.FullSpan.End If [end] = 0 Then ' empty file Return Nothing End If ' make sure position doesn't touch end of root position = Math.Min(position, [end] - 1) Dim node = root.FindToken(position).Parent While node IsNot Nothing If useFullSpan OrElse node.Span.Contains(position) Then If TypeOf node Is MethodBlockBaseSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return node End If If TypeOf node Is MethodBaseSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return node End If If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return node End If If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then Return node End If If TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is EnumBlockSyntax OrElse TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is EventBlockSyntax OrElse TypeOf node Is FieldDeclarationSyntax Then Return node End If End If node = node.Parent End While Return Nothing End Function Public Function IsMethodLevelMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodLevelMember ' Note: Derived types of MethodBaseSyntax are expanded explicitly, since PropertyStatementSyntax and ' EventStatementSyntax will NOT be parented by MethodBlockBaseSyntax. Additionally, there are things ' like AccessorStatementSyntax and DelegateStatementSyntax that we never want to tread as method level ' members. If TypeOf node Is MethodStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is SubNewStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is OperatorStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return True End If If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then Return True End If If TypeOf node Is DeclareStatementSyntax Then Return True End If Return TypeOf node Is ConstructorBlockSyntax OrElse TypeOf node Is MethodBlockSyntax OrElse TypeOf node Is OperatorBlockSyntax OrElse TypeOf node Is EventBlockSyntax OrElse TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is EnumMemberDeclarationSyntax OrElse TypeOf node Is FieldDeclarationSyntax End Function Public Function GetMemberBodySpanForSpeculativeBinding(node As SyntaxNode) As TextSpan Implements ISyntaxFacts.GetMemberBodySpanForSpeculativeBinding Dim member = GetContainingMemberDeclaration(node, node.SpanStart) If member Is Nothing Then Return Nothing End If ' TODO: currently we only support method for now Dim method = TryCast(member, MethodBlockBaseSyntax) If method IsNot Nothing Then If method.BlockStatement Is Nothing OrElse method.EndBlockStatement Is Nothing Then Return Nothing End If ' We don't want to include the BlockStatement or any trailing trivia up to and including its statement ' terminator in the span. Instead, we use the start of the first statement's leading trivia (if any) up ' to the start of the EndBlockStatement. If there aren't any statements in the block, we use the start ' of the EndBlockStatements leading trivia. Dim firstStatement = method.Statements.FirstOrDefault() Dim spanStart = If(firstStatement IsNot Nothing, firstStatement.FullSpan.Start, method.EndBlockStatement.FullSpan.Start) Return TextSpan.FromBounds(spanStart, method.EndBlockStatement.SpanStart) End If Return Nothing End Function Public Function ContainsInMemberBody(node As SyntaxNode, span As TextSpan) As Boolean Implements ISyntaxFacts.ContainsInMemberBody Dim method = TryCast(node, MethodBlockBaseSyntax) If method IsNot Nothing Then Return method.Statements.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan(method.Statements), span) End If Dim [event] = TryCast(node, EventBlockSyntax) If [event] IsNot Nothing Then Return [event].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([event].Accessors), span) End If Dim [property] = TryCast(node, PropertyBlockSyntax) If [property] IsNot Nothing Then Return [property].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([property].Accessors), span) End If Dim field = TryCast(node, FieldDeclarationSyntax) If field IsNot Nothing Then Return field.Declarators.Count > 0 AndAlso ContainsExclusively(GetSeparatedSyntaxListSpan(field.Declarators), span) End If Dim [enum] = TryCast(node, EnumMemberDeclarationSyntax) If [enum] IsNot Nothing Then Return [enum].Initializer IsNot Nothing AndAlso ContainsExclusively([enum].Initializer.Span, span) End If Dim propStatement = TryCast(node, PropertyStatementSyntax) If propStatement IsNot Nothing Then Return propStatement.Initializer IsNot Nothing AndAlso ContainsExclusively(propStatement.Initializer.Span, span) End If Return False End Function Private Shared Function ContainsExclusively(outerSpan As TextSpan, innerSpan As TextSpan) As Boolean If innerSpan.IsEmpty Then Return outerSpan.Contains(innerSpan.Start) End If Return outerSpan.Contains(innerSpan) End Function Private Shared Function GetSyntaxListSpan(Of T As SyntaxNode)(list As SyntaxList(Of T)) As TextSpan Debug.Assert(list.Count > 0) Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End) End Function Private Shared Function GetSeparatedSyntaxListSpan(Of T As SyntaxNode)(list As SeparatedSyntaxList(Of T)) As TextSpan Debug.Assert(list.Count > 0) Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End) End Function Public Function GetTopLevelAndMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetTopLevelAndMethodLevelMembers Dim list = New List(Of SyntaxNode)() AppendMembers(root, list, topLevel:=True, methodLevel:=True) Return list End Function Public Function GetMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetMethodLevelMembers Dim list = New List(Of SyntaxNode)() AppendMembers(root, list, topLevel:=False, methodLevel:=True) Return list End Function Public Function IsClassDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsClassDeclaration Return node.IsKind(SyntaxKind.ClassBlock) End Function Public Function IsNamespaceDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamespaceDeclaration Return node.IsKind(SyntaxKind.NamespaceBlock) End Function Public Function GetNameOfNamespaceDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfNamespaceDeclaration If IsNamespaceDeclaration(node) Then Return DirectCast(node, NamespaceBlockSyntax).NamespaceStatement.Name End If Return Nothing End Function Public Function GetMembersOfTypeDeclaration(typeDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfTypeDeclaration Return DirectCast(typeDeclaration, TypeBlockSyntax).Members End Function Public Function GetMembersOfNamespaceDeclaration(namespaceDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfNamespaceDeclaration Return DirectCast(namespaceDeclaration, NamespaceBlockSyntax).Members End Function Public Function GetMembersOfCompilationUnit(compilationUnit As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfCompilationUnit Return DirectCast(compilationUnit, CompilationUnitSyntax).Members End Function Public Function GetImportsOfNamespaceDeclaration(namespaceDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetImportsOfNamespaceDeclaration 'Visual Basic doesn't have namespaced imports Return Nothing End Function Public Function GetImportsOfCompilationUnit(compilationUnit As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetImportsOfCompilationUnit Return DirectCast(compilationUnit, CompilationUnitSyntax).Imports End Function Public Function IsTopLevelNodeWithMembers(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTopLevelNodeWithMembers Return TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is EnumBlockSyntax End Function Private Const s_dotToken As String = "." Public Function GetDisplayName(node As SyntaxNode, options As DisplayNameOptions, Optional rootNamespace As String = Nothing) As String Implements ISyntaxFacts.GetDisplayName If node Is Nothing Then Return String.Empty End If Dim pooled = PooledStringBuilder.GetInstance() Dim builder = pooled.Builder ' member keyword (if any) Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax) If (options And DisplayNameOptions.IncludeMemberKeyword) <> 0 Then Dim keywordToken = memberDeclaration.GetMemberKeywordToken() If keywordToken <> Nothing AndAlso Not keywordToken.IsMissing Then builder.Append(keywordToken.Text) builder.Append(" "c) End If End If Dim names = ArrayBuilder(Of String).GetInstance() ' containing type(s) Dim parent = node.Parent While TypeOf parent Is TypeBlockSyntax names.Push(GetName(parent, options, containsGlobalKeyword:=False)) parent = parent.Parent End While If (options And DisplayNameOptions.IncludeNamespaces) <> 0 Then ' containing namespace(s) in source (if any) Dim containsGlobalKeyword As Boolean = False While parent IsNot Nothing AndAlso parent.Kind() = SyntaxKind.NamespaceBlock names.Push(GetName(parent, options, containsGlobalKeyword)) parent = parent.Parent End While ' root namespace (if any) If Not containsGlobalKeyword AndAlso Not String.IsNullOrEmpty(rootNamespace) Then builder.Append(rootNamespace) builder.Append(s_dotToken) End If End If While Not names.IsEmpty() Dim name = names.Pop() If name IsNot Nothing Then builder.Append(name) builder.Append(s_dotToken) End If End While names.Free() ' name (include generic type parameters) builder.Append(GetName(node, options, containsGlobalKeyword:=False)) ' parameter list (if any) If (options And DisplayNameOptions.IncludeParameters) <> 0 Then builder.Append(memberDeclaration.GetParameterList()) End If ' As clause (if any) If (options And DisplayNameOptions.IncludeType) <> 0 Then Dim asClause = memberDeclaration.GetAsClause() If asClause IsNot Nothing Then builder.Append(" "c) builder.Append(asClause) End If End If Return pooled.ToStringAndFree() End Function Private Shared Function GetName(node As SyntaxNode, options As DisplayNameOptions, ByRef containsGlobalKeyword As Boolean) As String Const missingTokenPlaceholder As String = "?" Select Case node.Kind() Case SyntaxKind.CompilationUnit Return Nothing Case SyntaxKind.IdentifierName Dim identifier = DirectCast(node, IdentifierNameSyntax).Identifier Return If(identifier.IsMissing, missingTokenPlaceholder, identifier.Text) Case SyntaxKind.IncompleteMember Return missingTokenPlaceholder Case SyntaxKind.NamespaceBlock Dim nameSyntax = CType(node, NamespaceBlockSyntax).NamespaceStatement.Name If nameSyntax.Kind() = SyntaxKind.GlobalName Then containsGlobalKeyword = True Return Nothing Else Return GetName(nameSyntax, options, containsGlobalKeyword) End If Case SyntaxKind.QualifiedName Dim qualified = CType(node, QualifiedNameSyntax) If qualified.Left.Kind() = SyntaxKind.GlobalName Then containsGlobalKeyword = True Return GetName(qualified.Right, options, containsGlobalKeyword) ' don't use the Global prefix if specified Else Return GetName(qualified.Left, options, containsGlobalKeyword) + s_dotToken + GetName(qualified.Right, options, containsGlobalKeyword) End If End Select Dim name As String = Nothing Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax) If memberDeclaration IsNot Nothing Then Dim nameToken = memberDeclaration.GetNameToken() If nameToken <> Nothing Then name = If(nameToken.IsMissing, missingTokenPlaceholder, nameToken.Text) If (options And DisplayNameOptions.IncludeTypeParameters) <> 0 Then Dim pooled = PooledStringBuilder.GetInstance() Dim builder = pooled.Builder builder.Append(name) AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()) name = pooled.ToStringAndFree() End If End If End If Debug.Assert(name IsNot Nothing, "Unexpected node type " + node.Kind().ToString()) Return name End Function Private Shared Sub AppendTypeParameterList(builder As StringBuilder, typeParameterList As TypeParameterListSyntax) If typeParameterList IsNot Nothing AndAlso typeParameterList.Parameters.Count > 0 Then builder.Append("(Of ") builder.Append(typeParameterList.Parameters(0).Identifier.Text) For i = 1 To typeParameterList.Parameters.Count - 1 builder.Append(", ") builder.Append(typeParameterList.Parameters(i).Identifier.Text) Next builder.Append(")"c) End If End Sub Private Sub AppendMembers(node As SyntaxNode, list As List(Of SyntaxNode), topLevel As Boolean, methodLevel As Boolean) Debug.Assert(topLevel OrElse methodLevel) For Each member In node.GetMembers() If IsTopLevelNodeWithMembers(member) Then If topLevel Then list.Add(member) End If AppendMembers(member, list, topLevel, methodLevel) Continue For End If If methodLevel AndAlso IsMethodLevelMember(member) Then list.Add(member) End If Next End Sub Public Function TryGetBindableParent(token As SyntaxToken) As SyntaxNode Implements ISyntaxFacts.TryGetBindableParent Dim node = token.Parent While node IsNot Nothing Dim parent = node.Parent ' If this node is on the left side of a member access expression, don't ascend ' further or we'll end up binding to something else. Dim memberAccess = TryCast(parent, MemberAccessExpressionSyntax) If memberAccess IsNot Nothing Then If memberAccess.Expression Is node Then Exit While End If End If ' If this node is on the left side of a qualified name, don't ascend ' further or we'll end up binding to something else. Dim qualifiedName = TryCast(parent, QualifiedNameSyntax) If qualifiedName IsNot Nothing Then If qualifiedName.Left Is node Then Exit While End If End If ' If this node is the type of an object creation expression, return the ' object creation expression. Dim objectCreation = TryCast(parent, ObjectCreationExpressionSyntax) If objectCreation IsNot Nothing Then If objectCreation.Type Is node Then node = parent Exit While End If End If ' The inside of an interpolated string is treated as its own token so we ' need to force navigation to the parent expression syntax. If TypeOf node Is InterpolatedStringTextSyntax AndAlso TypeOf parent Is InterpolatedStringExpressionSyntax Then node = parent Exit While End If ' If this node is not parented by a name, we're done. Dim name = TryCast(parent, NameSyntax) If name Is Nothing Then Exit While End If node = parent End While Return node End Function Public Function GetConstructors(root As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode) Implements ISyntaxFacts.GetConstructors Dim compilationUnit = TryCast(root, CompilationUnitSyntax) If compilationUnit Is Nothing Then Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If Dim constructors = New List(Of SyntaxNode)() AppendConstructors(compilationUnit.Members, constructors, cancellationToken) Return constructors End Function Private Sub AppendConstructors(members As SyntaxList(Of StatementSyntax), constructors As List(Of SyntaxNode), cancellationToken As CancellationToken) For Each member As StatementSyntax In members cancellationToken.ThrowIfCancellationRequested() Dim constructor = TryCast(member, ConstructorBlockSyntax) If constructor IsNot Nothing Then constructors.Add(constructor) Continue For End If Dim [namespace] = TryCast(member, NamespaceBlockSyntax) If [namespace] IsNot Nothing Then AppendConstructors([namespace].Members, constructors, cancellationToken) End If Dim [class] = TryCast(member, ClassBlockSyntax) If [class] IsNot Nothing Then AppendConstructors([class].Members, constructors, cancellationToken) End If Dim [struct] = TryCast(member, StructureBlockSyntax) If [struct] IsNot Nothing Then AppendConstructors([struct].Members, constructors, cancellationToken) End If Next End Sub Public Function GetInactiveRegionSpanAroundPosition(tree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As TextSpan Implements ISyntaxFacts.GetInactiveRegionSpanAroundPosition Dim trivia = tree.FindTriviaToLeft(position, cancellationToken) If trivia.Kind = SyntaxKind.DisabledTextTrivia Then Return trivia.FullSpan End If Return Nothing End Function Public Function GetNameForArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForArgument If TryCast(argument, ArgumentSyntax)?.IsNamed Then Return DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.Identifier.ValueText End If Return String.Empty End Function Public Function GetNameForAttributeArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForAttributeArgument ' All argument types are ArgumentSyntax in VB. Return GetNameForArgument(argument) End Function Public Function IsLeftSideOfDot(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfDot Return TryCast(node, ExpressionSyntax).IsLeftSideOfDot() End Function Public Function GetRightSideOfDot(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightSideOfDot Return If(TryCast(node, QualifiedNameSyntax)?.Right, TryCast(node, MemberAccessExpressionSyntax)?.Name) End Function Public Function GetLeftSideOfDot(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetLeftSideOfDot Return If(TryCast(node, QualifiedNameSyntax)?.Left, TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget)) End Function Public Function IsLeftSideOfExplicitInterfaceSpecifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfExplicitInterfaceSpecifier Return IsLeftSideOfDot(node) AndAlso TryCast(node.Parent.Parent, ImplementsClauseSyntax) IsNot Nothing End Function Public Function IsLeftSideOfAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfSimpleAssignmentStatement End Function Public Function IsLeftSideOfAnyAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAnyAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfAnyAssignmentStatement End Function Public Function IsLeftSideOfCompoundAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfCompoundAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfCompoundAssignmentStatement End Function Public Function GetRightHandSideOfAssignment(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightHandSideOfAssignment Return TryCast(node, AssignmentStatementSyntax)?.Right End Function Public Function IsInferredAnonymousObjectMemberDeclarator(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInferredAnonymousObjectMemberDeclarator Return node.IsKind(SyntaxKind.InferredFieldInitializer) End Function Public Function IsOperandOfIncrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementExpression Return False End Function Public Function IsOperandOfIncrementOrDecrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementOrDecrementExpression Return False End Function Public Function GetContentsOfInterpolatedString(interpolatedString As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentsOfInterpolatedString Return (TryCast(interpolatedString, InterpolatedStringExpressionSyntax)?.Contents).Value End Function Public Function IsNumericLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsNumericLiteral Return token.Kind = SyntaxKind.DecimalLiteralToken OrElse token.Kind = SyntaxKind.FloatingLiteralToken OrElse token.Kind = SyntaxKind.IntegerLiteralToken End Function Public Function IsVerbatimStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimStringLiteral ' VB does not have verbatim strings Return False End Function Public Function GetArgumentsOfInvocationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfInvocationExpression Return GetArgumentsOfArgumentList(TryCast(node, InvocationExpressionSyntax)?.ArgumentList) End Function Public Function GetArgumentsOfObjectCreationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfObjectCreationExpression Return GetArgumentsOfArgumentList(TryCast(node, ObjectCreationExpressionSyntax)?.ArgumentList) End Function Public Function GetArgumentsOfArgumentList(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfArgumentList Dim arguments = TryCast(node, ArgumentListSyntax)?.Arguments Return If(arguments.HasValue, arguments.Value, Nothing) End Function Public Function GetArgumentListOfInvocationExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetArgumentListOfInvocationExpression Return DirectCast(node, InvocationExpressionSyntax).ArgumentList End Function Public Function GetArgumentListOfObjectCreationExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetArgumentListOfObjectCreationExpression Return DirectCast(node, ObjectCreationExpressionSyntax).ArgumentList End Function Public Function ConvertToSingleLine(node As SyntaxNode, Optional useElasticTrivia As Boolean = False) As SyntaxNode Implements ISyntaxFacts.ConvertToSingleLine Return node.ConvertToSingleLine(useElasticTrivia) End Function Public Function IsDocumentationComment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDocumentationComment Return node.IsKind(SyntaxKind.DocumentationCommentTrivia) End Function Public Function IsUsingOrExternOrImport(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingOrExternOrImport Return node.IsKind(SyntaxKind.ImportsStatement) End Function Public Function IsGlobalAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalAssemblyAttribute Return IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword) End Function Public Function IsModuleAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalModuleAttribute Return IsGlobalAttribute(node, SyntaxKind.ModuleKeyword) End Function Private Shared Function IsGlobalAttribute(node As SyntaxNode, attributeTarget As SyntaxKind) As Boolean If node.IsKind(SyntaxKind.Attribute) Then Dim attributeNode = CType(node, AttributeSyntax) If attributeNode.Target IsNot Nothing Then Return attributeNode.Target.AttributeModifier.IsKind(attributeTarget) End If End If Return False End Function Public Function IsDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaration ' From the Visual Basic language spec: ' NamespaceMemberDeclaration := ' NamespaceDeclaration | ' TypeDeclaration ' TypeDeclaration ::= ' ModuleDeclaration | ' NonModuleDeclaration ' NonModuleDeclaration ::= ' EnumDeclaration | ' StructureDeclaration | ' InterfaceDeclaration | ' ClassDeclaration | ' DelegateDeclaration ' ClassMemberDeclaration ::= ' NonModuleDeclaration | ' EventMemberDeclaration | ' VariableMemberDeclaration | ' ConstantMemberDeclaration | ' MethodMemberDeclaration | ' PropertyMemberDeclaration | ' ConstructorMemberDeclaration | ' OperatorDeclaration Select Case node.Kind() ' Because fields declarations can define multiple symbols "Public a, b As Integer" ' We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name. Case SyntaxKind.VariableDeclarator If (node.Parent.IsKind(SyntaxKind.FieldDeclaration)) Then Return True End If Return False Case SyntaxKind.NamespaceStatement, SyntaxKind.NamespaceBlock, SyntaxKind.ModuleStatement, SyntaxKind.ModuleBlock, SyntaxKind.EnumStatement, SyntaxKind.EnumBlock, SyntaxKind.StructureStatement, SyntaxKind.StructureBlock, SyntaxKind.InterfaceStatement, SyntaxKind.InterfaceBlock, SyntaxKind.ClassStatement, SyntaxKind.ClassBlock, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement, SyntaxKind.EventStatement, SyntaxKind.EventBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.FieldDeclaration, SyntaxKind.SubStatement, SyntaxKind.SubBlock, SyntaxKind.FunctionStatement, SyntaxKind.FunctionBlock, SyntaxKind.PropertyStatement, SyntaxKind.PropertyBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.SubNewStatement, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorStatement, SyntaxKind.OperatorBlock Return True End Select Return False End Function ' TypeDeclaration ::= ' ModuleDeclaration | ' NonModuleDeclaration ' NonModuleDeclaration ::= ' EnumDeclaration | ' StructureDeclaration | ' InterfaceDeclaration | ' ClassDeclaration | ' DelegateDeclaration Public Function IsTypeDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeDeclaration Select Case node.Kind() Case SyntaxKind.EnumBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ClassBlock, SyntaxKind.ModuleBlock, SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return True End Select Return False End Function Public Function GetObjectCreationInitializer(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetObjectCreationInitializer Return DirectCast(node, ObjectCreationExpressionSyntax).Initializer End Function Public Function GetObjectCreationType(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetObjectCreationType Return DirectCast(node, ObjectCreationExpressionSyntax).Type End Function Public Function IsSimpleAssignmentStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleAssignmentStatement Return node.IsKind(SyntaxKind.SimpleAssignmentStatement) End Function Public Sub GetPartsOfAssignmentStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentStatement ' VB only has assignment statements, so this can just delegate to that helper GetPartsOfAssignmentExpressionOrStatement(statement, left, operatorToken, right) End Sub Public Sub GetPartsOfAssignmentExpressionOrStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentExpressionOrStatement Dim assignment = DirectCast(statement, AssignmentStatementSyntax) left = assignment.Left operatorToken = assignment.OperatorToken right = assignment.Right End Sub Public Function GetNameOfMemberAccessExpression(memberAccessExpression As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberAccessExpression Return DirectCast(memberAccessExpression, MemberAccessExpressionSyntax).Name End Function Public Function GetIdentifierOfSimpleName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfSimpleName Return DirectCast(node, SimpleNameSyntax).Identifier End Function Public Function GetIdentifierOfVariableDeclarator(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfVariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Names.Last().Identifier End Function Public Function GetIdentifierOfParameter(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfParameter Return DirectCast(node, ParameterSyntax).Identifier.Identifier End Function Public Function GetIdentifierOfTypeDeclaration(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfTypeDeclaration Select Case node.Kind() Case SyntaxKind.EnumStatement, SyntaxKind.StructureStatement, SyntaxKind.InterfaceStatement, SyntaxKind.ClassStatement, SyntaxKind.ModuleStatement Return DirectCast(node, TypeStatementSyntax).Identifier Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return DirectCast(node, DelegateStatementSyntax).Identifier End Select Throw ExceptionUtilities.UnexpectedValue(node) End Function Public Function GetIdentifierOfIdentifierName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfIdentifierName Return DirectCast(node, IdentifierNameSyntax).Identifier End Function Public Function IsLocalFunctionStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLocalFunctionStatement ' VB does not have local functions Return False End Function Public Function IsDeclaratorOfLocalDeclarationStatement(declarator As SyntaxNode, localDeclarationStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaratorOfLocalDeclarationStatement Return DirectCast(localDeclarationStatement, LocalDeclarationStatementSyntax).Declarators. Contains(DirectCast(declarator, VariableDeclaratorSyntax)) End Function Public Function AreEquivalent(token1 As SyntaxToken, token2 As SyntaxToken) As Boolean Implements ISyntaxFacts.AreEquivalent Return SyntaxFactory.AreEquivalent(token1, token2) End Function Public Function AreEquivalent(node1 As SyntaxNode, node2 As SyntaxNode) As Boolean Implements ISyntaxFacts.AreEquivalent Return SyntaxFactory.AreEquivalent(node1, node2) End Function Public Function IsExpressionOfInvocationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfInvocationExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, InvocationExpressionSyntax)?.Expression Is node End Function Public Function IsExpressionOfAwaitExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfAwaitExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, AwaitExpressionSyntax)?.Expression Is node End Function Public Function IsExpressionOfMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfMemberAccessExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, MemberAccessExpressionSyntax)?.Expression Is node End Function Public Function GetExpressionOfAwaitExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfAwaitExpression Return DirectCast(node, AwaitExpressionSyntax).Expression End Function Public Function IsExpressionOfForeach(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfForeach Return node IsNot Nothing AndAlso TryCast(node.Parent, ForEachStatementSyntax)?.Expression Is node End Function Public Function GetExpressionOfExpressionStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfExpressionStatement Return DirectCast(node, ExpressionStatementSyntax).Expression End Function Public Function IsBinaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryExpression Return TypeOf node Is BinaryExpressionSyntax End Function Public Function IsIsExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsExpression Return node.IsKind(SyntaxKind.TypeOfIsExpression) End Function Public Sub GetPartsOfBinaryExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryExpression Dim binaryExpression = DirectCast(node, BinaryExpressionSyntax) left = binaryExpression.Left operatorToken = binaryExpression.OperatorToken right = binaryExpression.Right End Sub Public Sub GetPartsOfConditionalExpression(node As SyntaxNode, ByRef condition As SyntaxNode, ByRef whenTrue As SyntaxNode, ByRef whenFalse As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalExpression Dim conditionalExpression = DirectCast(node, TernaryConditionalExpressionSyntax) condition = conditionalExpression.Condition whenTrue = conditionalExpression.WhenTrue whenFalse = conditionalExpression.WhenFalse End Sub Public Function WalkDownParentheses(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.WalkDownParentheses Return If(TryCast(node, ExpressionSyntax)?.WalkDownParentheses(), node) End Function Public Sub GetPartsOfTupleExpression(Of TArgumentSyntax As SyntaxNode)( node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef arguments As SeparatedSyntaxList(Of TArgumentSyntax), ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfTupleExpression Dim tupleExpr = DirectCast(node, TupleExpressionSyntax) openParen = tupleExpr.OpenParenToken arguments = CType(CType(tupleExpr.Arguments, SeparatedSyntaxList(Of SyntaxNode)), SeparatedSyntaxList(Of TArgumentSyntax)) closeParen = tupleExpr.CloseParenToken End Sub Public Function GetOperandOfPrefixUnaryExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetOperandOfPrefixUnaryExpression Return DirectCast(node, UnaryExpressionSyntax).Operand End Function Public Function GetOperatorTokenOfPrefixUnaryExpression(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetOperatorTokenOfPrefixUnaryExpression Return DirectCast(node, UnaryExpressionSyntax).OperatorToken End Function Public Sub GetPartsOfMemberAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef name As SyntaxNode) Implements ISyntaxFacts.GetPartsOfMemberAccessExpression Dim memberAccess = DirectCast(node, MemberAccessExpressionSyntax) expression = memberAccess.Expression operatorToken = memberAccess.OperatorToken name = memberAccess.Name End Sub Public Function GetNextExecutableStatement(statement As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNextExecutableStatement Return DirectCast(statement, StatementSyntax).GetNextStatement()?.FirstAncestorOrSelf(Of ExecutableStatementSyntax) End Function Private Function ISyntaxFacts_IsSingleLineCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsSingleLineCommentTrivia Return MyBase.IsSingleLineCommentTrivia(trivia) End Function Private Function ISyntaxFacts_IsMultiLineCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsMultiLineCommentTrivia Return MyBase.IsMultiLineCommentTrivia(trivia) End Function Private Function ISyntaxFacts_IsSingleLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsSingleLineDocCommentTrivia Return MyBase.IsSingleLineDocCommentTrivia(trivia) End Function Private Function ISyntaxFacts_IsMultiLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsMultiLineDocCommentTrivia Return MyBase.IsMultiLineDocCommentTrivia(trivia) Return False End Function Private Function ISyntaxFacts_IsShebangDirectiveTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsShebangDirectiveTrivia Return MyBase.IsShebangDirectiveTrivia(trivia) End Function Public Overrides Function IsPreprocessorDirective(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsPreprocessorDirective Return SyntaxFacts.IsPreprocessorDirective(trivia.Kind()) End Function Public Function IsRegularComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsRegularComment Return trivia.Kind = SyntaxKind.CommentTrivia End Function Public Function IsDocumentationComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationComment Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia End Function Public Function IsElastic(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsElastic Return trivia.IsElastic() End Function Public Function IsPragmaDirective(trivia As SyntaxTrivia, ByRef isDisable As Boolean, ByRef isActive As Boolean, ByRef errorCodes As SeparatedSyntaxList(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.IsPragmaDirective Return trivia.IsPragmaDirective(isDisable, isActive, errorCodes) End Function Public Function IsOnTypeHeader( root As SyntaxNode, position As Integer, fullHeader As Boolean, ByRef typeDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnTypeHeader Dim typeBlock = TryGetAncestorForLocation(Of TypeBlockSyntax)(root, position) If typeBlock Is Nothing Then Return Nothing End If Dim typeStatement = typeBlock.BlockStatement typeDeclaration = typeStatement Dim lastToken = If(typeStatement.TypeParameterList?.GetLastToken(), typeStatement.Identifier) If fullHeader Then lastToken = If(typeBlock.Implements.LastOrDefault()?.GetLastToken(), If(typeBlock.Inherits.LastOrDefault()?.GetLastToken(), lastToken)) End If Return IsOnHeader(root, position, typeBlock, lastToken) End Function Public Function IsOnPropertyDeclarationHeader(root As SyntaxNode, position As Integer, ByRef propertyDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnPropertyDeclarationHeader Dim node = TryGetAncestorForLocation(Of PropertyStatementSyntax)(root, position) propertyDeclaration = node If propertyDeclaration Is Nothing Then Return False End If If node.AsClause IsNot Nothing Then Return IsOnHeader(root, position, node, node.AsClause) End If Return IsOnHeader(root, position, node, node.Identifier) End Function Public Function IsOnParameterHeader(root As SyntaxNode, position As Integer, ByRef parameter As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnParameterHeader Dim node = TryGetAncestorForLocation(Of ParameterSyntax)(root, position) parameter = node If parameter Is Nothing Then Return False End If Return IsOnHeader(root, position, node, node) End Function Public Function IsOnMethodHeader(root As SyntaxNode, position As Integer, ByRef method As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnMethodHeader Dim node = TryGetAncestorForLocation(Of MethodStatementSyntax)(root, position) method = node If method Is Nothing Then Return False End If If node.HasReturnType() Then Return IsOnHeader(root, position, method, node.GetReturnType()) End If If node.ParameterList IsNot Nothing Then Return IsOnHeader(root, position, method, node.ParameterList) End If Return IsOnHeader(root, position, node, node) End Function Public Function IsOnLocalFunctionHeader(root As SyntaxNode, position As Integer, ByRef localFunction As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnLocalFunctionHeader ' No local functions in VisualBasic Return False End Function Public Function IsOnLocalDeclarationHeader(root As SyntaxNode, position As Integer, ByRef localDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnLocalDeclarationHeader Dim node = TryGetAncestorForLocation(Of LocalDeclarationStatementSyntax)(root, position) localDeclaration = node If localDeclaration Is Nothing Then Return False End If Dim initializersExpressions = node.Declarators. Where(Function(d) d.Initializer IsNot Nothing). SelectAsArray(Function(initialized) initialized.Initializer.Value) Return IsOnHeader(root, position, node, node, initializersExpressions) End Function Public Function IsOnIfStatementHeader(root As SyntaxNode, position As Integer, ByRef ifStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnIfStatementHeader ifStatement = Nothing Dim multipleLineNode = TryGetAncestorForLocation(Of MultiLineIfBlockSyntax)(root, position) If multipleLineNode IsNot Nothing Then ifStatement = multipleLineNode Return IsOnHeader(root, position, multipleLineNode.IfStatement, multipleLineNode.IfStatement) End If Dim singleLineNode = TryGetAncestorForLocation(Of SingleLineIfStatementSyntax)(root, position) If singleLineNode IsNot Nothing Then ifStatement = singleLineNode Return IsOnHeader(root, position, singleLineNode, singleLineNode.Condition) End If Return False End Function Public Function IsOnWhileStatementHeader(root As SyntaxNode, position As Integer, ByRef whileStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnWhileStatementHeader whileStatement = Nothing Dim whileBlock = TryGetAncestorForLocation(Of WhileBlockSyntax)(root, position) If whileBlock IsNot Nothing Then whileStatement = whileBlock Return IsOnHeader(root, position, whileBlock.WhileStatement, whileBlock.WhileStatement) End If Return False End Function Public Function IsOnForeachHeader(root As SyntaxNode, position As Integer, ByRef foreachStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnForeachHeader Dim node = TryGetAncestorForLocation(Of ForEachBlockSyntax)(root, position) foreachStatement = node If foreachStatement Is Nothing Then Return False End If Return IsOnHeader(root, position, node, node.ForEachStatement) End Function Public Function IsBetweenTypeMembers(sourceText As SourceText, root As SyntaxNode, position As Integer, ByRef typeDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBetweenTypeMembers Dim token = root.FindToken(position) Dim typeDecl = token.GetAncestor(Of TypeBlockSyntax) typeDeclaration = typeDecl If typeDecl IsNot Nothing Then Dim start = If(typeDecl.Implements.LastOrDefault()?.Span.End, If(typeDecl.Inherits.LastOrDefault()?.Span.End, typeDecl.BlockStatement.Span.End)) If position >= start AndAlso position <= typeDecl.EndBlockStatement.Span.Start Then Dim line = sourceText.Lines.GetLineFromPosition(position) If Not line.IsEmptyOrWhitespace() Then Return False End If Dim member = typeDecl.Members.FirstOrDefault(Function(d) d.FullSpan.Contains(position)) If member Is Nothing Then ' There are no members, Or we're after the last member. Return True Else ' We're within a member. Make sure we're in the leading whitespace of ' the member. If position < member.SpanStart Then For Each trivia In member.GetLeadingTrivia() If Not trivia.IsWhitespaceOrEndOfLine() Then Return False End If If trivia.FullSpan.Contains(position) Then Return True End If Next End If End If End If End If Return False End Function Protected Overrides Function ContainsInterleavedDirective(span As TextSpan, token As SyntaxToken, cancellationToken As CancellationToken) As Boolean Return token.ContainsInterleavedDirective(span, cancellationToken) End Function Private Function ISyntaxFacts_ContainsInterleavedDirective(node As SyntaxNode, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective Return ContainsInterleavedDirective(node, cancellationToken) End Function Private Function ISyntaxFacts_ContainsInterleavedDirective1(nodes As ImmutableArray(Of SyntaxNode), cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective Return ContainsInterleavedDirective(nodes, cancellationToken) End Function Public Function IsDocumentationCommentExteriorTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationCommentExteriorTrivia Return trivia.Kind() = SyntaxKind.DocumentationCommentExteriorTrivia End Function Public Function GetModifiers(node As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifiers Return node.GetModifiers() End Function Public Function WithModifiers(node As SyntaxNode, modifiers As SyntaxTokenList) As SyntaxNode Implements ISyntaxFacts.WithModifiers Return node.WithModifiers(modifiers) End Function Public Function IsLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLiteralExpression Return TypeOf node Is LiteralExpressionSyntax End Function Public Function GetVariablesOfLocalDeclarationStatement(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetVariablesOfLocalDeclarationStatement Return DirectCast(node, LocalDeclarationStatementSyntax).Declarators End Function Public Function GetInitializerOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetInitializerOfVariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Initializer End Function Public Function GetTypeOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfVariableDeclarator Dim declarator = DirectCast(node, VariableDeclaratorSyntax) Return TryCast(declarator.AsClause, SimpleAsClauseSyntax)?.Type End Function Public Function GetValueOfEqualsValueClause(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetValueOfEqualsValueClause Return DirectCast(node, EqualsValueSyntax).Value End Function Public Function IsScopeBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsScopeBlock ' VB has no equivalent of curly braces. Return False End Function Public Function IsExecutableBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableBlock Return node.IsExecutableBlock() End Function Public Function GetExecutableBlockStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetExecutableBlockStatements Return node.GetExecutableBlockStatements() End Function Public Function FindInnermostCommonExecutableBlock(nodes As IEnumerable(Of SyntaxNode)) As SyntaxNode Implements ISyntaxFacts.FindInnermostCommonExecutableBlock Return nodes.FindInnermostCommonExecutableBlock() End Function Public Function IsStatementContainer(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatementContainer Return IsExecutableBlock(node) End Function Public Function GetStatementContainerStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetStatementContainerStatements Return GetExecutableBlockStatements(node) End Function Public Function IsConversionExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConversionExpression Return node.Kind = SyntaxKind.CTypeExpression End Function Public Function IsCastExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsCastExpression Return node.Kind = SyntaxKind.DirectCastExpression End Function Public Sub GetPartsOfCastExpression(node As SyntaxNode, ByRef type As SyntaxNode, ByRef expression As SyntaxNode) Implements ISyntaxFacts.GetPartsOfCastExpression Dim cast = DirectCast(node, DirectCastExpressionSyntax) type = cast.Type expression = cast.Expression End Sub Public Function GetDeconstructionReferenceLocation(node As SyntaxNode) As Location Implements ISyntaxFacts.GetDeconstructionReferenceLocation Throw New NotImplementedException() End Function Public Function GetDeclarationIdentifierIfOverride(token As SyntaxToken) As SyntaxToken? Implements ISyntaxFacts.GetDeclarationIdentifierIfOverride If token.Kind() = SyntaxKind.OverridesKeyword Then Dim parent = token.Parent Select Case parent.Kind() Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Dim method = DirectCast(parent, MethodStatementSyntax) Return method.Identifier Case SyntaxKind.PropertyStatement Dim [property] = DirectCast(parent, PropertyStatementSyntax) Return [property].Identifier End Select End If Return Nothing End Function Public Shadows Function SpansPreprocessorDirective(nodes As IEnumerable(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.SpansPreprocessorDirective Return MyBase.SpansPreprocessorDirective(nodes) End Function Public Shadows Function SpansPreprocessorDirective(tokens As IEnumerable(Of SyntaxToken)) As Boolean Return MyBase.SpansPreprocessorDirective(tokens) End Function Public Sub GetPartsOfInvocationExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfInvocationExpression Dim invocation = DirectCast(node, InvocationExpressionSyntax) expression = invocation.Expression argumentList = invocation.ArgumentList End Sub Public Function IsPostfixUnaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPostfixUnaryExpression ' Does not exist in VB. Return False End Function Public Function IsMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberBindingExpression ' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target. Return False End Function Public Function IsNameOfMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfMemberBindingExpression ' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target. Return False End Function Public Overrides Function GetAttributeLists(node As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetAttributeLists Return node.GetAttributeLists() End Function Public Function IsUsingAliasDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingAliasDirective Dim importStatement = TryCast(node, ImportsStatementSyntax) If (importStatement IsNot Nothing) Then For Each importsClause In importStatement.ImportsClauses If importsClause.Kind = SyntaxKind.SimpleImportsClause Then Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax) If simpleImportsClause.Alias IsNot Nothing Then Return True End If End If Next End If Return False End Function Public Sub GetPartsOfUsingAliasDirective( node As SyntaxNode, ByRef globalKeyword As SyntaxToken, ByRef [alias] As SyntaxToken, ByRef name As SyntaxNode) Implements ISyntaxFacts.GetPartsOfUsingAliasDirective Dim importStatement = DirectCast(node, ImportsStatementSyntax) For Each importsClause In importStatement.ImportsClauses If importsClause.Kind = SyntaxKind.SimpleImportsClause Then Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax) If simpleImportsClause.Alias IsNot Nothing Then globalKeyword = Nothing [alias] = simpleImportsClause.Alias.Identifier name = simpleImportsClause.Name Return End If End If Next Throw ExceptionUtilities.Unreachable End Sub Public Overrides Function IsParameterNameXmlElementSyntax(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterNameXmlElementSyntax Dim xmlElement = TryCast(node, XmlElementSyntax) If xmlElement IsNot Nothing Then Dim name = TryCast(xmlElement.StartTag.Name, XmlNameSyntax) Return name?.LocalName.ValueText = DocumentationCommentXmlNames.ParameterElementName End If Return False End Function Public Overrides Function GetContentFromDocumentationCommentTriviaSyntax(trivia As SyntaxTrivia) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentFromDocumentationCommentTriviaSyntax Dim documentationCommentTrivia = TryCast(trivia.GetStructure(), DocumentationCommentTriviaSyntax) If documentationCommentTrivia IsNot Nothing Then Return documentationCommentTrivia.Content End If Return Nothing End Function Public Overrides Function CanHaveAccessibility(declaration As SyntaxNode) As Boolean Implements ISyntaxFacts.CanHaveAccessibility Select Case declaration.Kind Case SyntaxKind.ClassBlock, SyntaxKind.ClassStatement, SyntaxKind.StructureBlock, SyntaxKind.StructureStatement, SyntaxKind.InterfaceBlock, SyntaxKind.InterfaceStatement, SyntaxKind.EnumBlock, SyntaxKind.EnumStatement, SyntaxKind.ModuleBlock, SyntaxKind.ModuleStatement, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement, SyntaxKind.FieldDeclaration, SyntaxKind.FunctionBlock, SyntaxKind.SubBlock, SyntaxKind.FunctionStatement, SyntaxKind.SubStatement, SyntaxKind.PropertyBlock, SyntaxKind.PropertyStatement, SyntaxKind.OperatorBlock, SyntaxKind.OperatorStatement, SyntaxKind.EventBlock, SyntaxKind.EventStatement, SyntaxKind.GetAccessorBlock, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorBlock, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorBlock, SyntaxKind.RaiseEventAccessorStatement Return True Case SyntaxKind.ConstructorBlock, SyntaxKind.SubNewStatement ' Shared constructor cannot have modifiers in VB. ' Module constructors are implicitly Shared and can't have accessibility modifier. Return Not declaration.GetModifiers().Any(SyntaxKind.SharedKeyword) AndAlso Not declaration.Parent.IsKind(SyntaxKind.ModuleBlock) Case SyntaxKind.ModifiedIdentifier Return If(IsChildOf(declaration, SyntaxKind.VariableDeclarator), CanHaveAccessibility(declaration.Parent), False) Case SyntaxKind.VariableDeclarator Return If(IsChildOfVariableDeclaration(declaration), CanHaveAccessibility(declaration.Parent), False) Case Else Return False End Select End Function Friend Shared Function IsChildOf(node As SyntaxNode, kind As SyntaxKind) As Boolean Return node.Parent IsNot Nothing AndAlso node.Parent.IsKind(kind) End Function Friend Shared Function IsChildOfVariableDeclaration(node As SyntaxNode) As Boolean Return IsChildOf(node, SyntaxKind.FieldDeclaration) OrElse IsChildOf(node, SyntaxKind.LocalDeclarationStatement) End Function Public Overrides Function GetAccessibility(declaration As SyntaxNode) As Accessibility Implements ISyntaxFacts.GetAccessibility If Not CanHaveAccessibility(declaration) Then Return Accessibility.NotApplicable End If Dim tokens = GetModifierTokens(declaration) Dim acc As Accessibility Dim mods As DeclarationModifiers Dim isDefault As Boolean GetAccessibilityAndModifiers(tokens, acc, mods, isDefault) Return acc End Function Public Overrides Function GetModifierTokens(declaration As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifierTokens Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.ClassStatement Return DirectCast(declaration, ClassStatementSyntax).Modifiers Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.StructureStatement Return DirectCast(declaration, StructureStatementSyntax).Modifiers Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.InterfaceStatement Return DirectCast(declaration, InterfaceStatementSyntax).Modifiers Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).EnumStatement.Modifiers Case SyntaxKind.EnumStatement Return DirectCast(declaration, EnumStatementSyntax).Modifiers Case SyntaxKind.ModuleBlock Return DirectCast(declaration, ModuleBlockSyntax).ModuleStatement.Modifiers Case SyntaxKind.ModuleStatement Return DirectCast(declaration, ModuleStatementSyntax).Modifiers Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).Modifiers Case SyntaxKind.FieldDeclaration Return DirectCast(declaration, FieldDeclarationSyntax).Modifiers Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(declaration, MethodStatementSyntax).Modifiers Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).SubOrFunctionHeader.Modifiers Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return DirectCast(declaration, SingleLineLambdaExpressionSyntax).SubOrFunctionHeader.Modifiers Case SyntaxKind.SubNewStatement Return DirectCast(declaration, SubNewStatementSyntax).Modifiers Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Modifiers Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).Modifiers Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.OperatorStatement Return DirectCast(declaration, OperatorStatementSyntax).Modifiers Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).EventStatement.Modifiers Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).Modifiers Case SyntaxKind.ModifiedIdentifier If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then Return GetModifierTokens(declaration.Parent) End If Case SyntaxKind.LocalDeclarationStatement Return DirectCast(declaration, LocalDeclarationStatementSyntax).Modifiers Case SyntaxKind.VariableDeclarator If IsChildOfVariableDeclaration(declaration) Then Return GetModifierTokens(declaration.Parent) End If Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return GetModifierTokens(DirectCast(declaration, AccessorBlockSyntax).AccessorStatement) Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return DirectCast(declaration, AccessorStatementSyntax).Modifiers Case Else Return Nothing End Select End Function Public Overrides Sub GetAccessibilityAndModifiers(modifierTokens As SyntaxTokenList, ByRef accessibility As Accessibility, ByRef modifiers As DeclarationModifiers, ByRef isDefault As Boolean) Implements ISyntaxFacts.GetAccessibilityAndModifiers accessibility = Accessibility.NotApplicable modifiers = DeclarationModifiers.None isDefault = False For Each token In modifierTokens Select Case token.Kind Case SyntaxKind.DefaultKeyword isDefault = True Case SyntaxKind.PublicKeyword accessibility = Accessibility.Public Case SyntaxKind.PrivateKeyword If accessibility = Accessibility.Protected Then accessibility = Accessibility.ProtectedAndFriend Else accessibility = Accessibility.Private End If Case SyntaxKind.FriendKeyword If accessibility = Accessibility.Protected Then accessibility = Accessibility.ProtectedOrFriend Else accessibility = Accessibility.Friend End If Case SyntaxKind.ProtectedKeyword If accessibility = Accessibility.Friend Then accessibility = Accessibility.ProtectedOrFriend ElseIf accessibility = Accessibility.Private Then accessibility = Accessibility.ProtectedAndFriend Else accessibility = Accessibility.Protected End If Case SyntaxKind.MustInheritKeyword, SyntaxKind.MustOverrideKeyword modifiers = modifiers Or DeclarationModifiers.Abstract Case SyntaxKind.ShadowsKeyword modifiers = modifiers Or DeclarationModifiers.[New] Case SyntaxKind.OverridesKeyword modifiers = modifiers Or DeclarationModifiers.Override Case SyntaxKind.OverridableKeyword modifiers = modifiers Or DeclarationModifiers.Virtual Case SyntaxKind.SharedKeyword modifiers = modifiers Or DeclarationModifiers.Static Case SyntaxKind.AsyncKeyword modifiers = modifiers Or DeclarationModifiers.Async Case SyntaxKind.ConstKeyword modifiers = modifiers Or DeclarationModifiers.Const Case SyntaxKind.ReadOnlyKeyword modifiers = modifiers Or DeclarationModifiers.ReadOnly Case SyntaxKind.WriteOnlyKeyword modifiers = modifiers Or DeclarationModifiers.WriteOnly Case SyntaxKind.NotInheritableKeyword, SyntaxKind.NotOverridableKeyword modifiers = modifiers Or DeclarationModifiers.Sealed Case SyntaxKind.WithEventsKeyword modifiers = modifiers Or DeclarationModifiers.WithEvents Case SyntaxKind.PartialKeyword modifiers = modifiers Or DeclarationModifiers.Partial End Select Next End Sub Public Overrides Function GetDeclarationKind(declaration As SyntaxNode) As DeclarationKind Implements ISyntaxFacts.GetDeclarationKind Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return DeclarationKind.CompilationUnit Case SyntaxKind.NamespaceBlock Return DeclarationKind.Namespace Case SyntaxKind.ImportsStatement Return DeclarationKind.NamespaceImport Case SyntaxKind.ClassBlock Return DeclarationKind.Class Case SyntaxKind.StructureBlock Return DeclarationKind.Struct Case SyntaxKind.InterfaceBlock Return DeclarationKind.Interface Case SyntaxKind.EnumBlock Return DeclarationKind.Enum Case SyntaxKind.EnumMemberDeclaration Return DeclarationKind.EnumMember Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DeclarationKind.Delegate Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DeclarationKind.Method Case SyntaxKind.FunctionStatement If Not IsChildOf(declaration, SyntaxKind.FunctionBlock) Then Return DeclarationKind.Method End If Case SyntaxKind.SubStatement If Not IsChildOf(declaration, SyntaxKind.SubBlock) Then Return DeclarationKind.Method End If Case SyntaxKind.ConstructorBlock Return DeclarationKind.Constructor Case SyntaxKind.PropertyBlock If IsIndexer(declaration) Then Return DeclarationKind.Indexer Else Return DeclarationKind.Property End If Case SyntaxKind.PropertyStatement If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then If IsIndexer(declaration) Then Return DeclarationKind.Indexer Else Return DeclarationKind.Property End If End If Case SyntaxKind.OperatorBlock Return DeclarationKind.Operator Case SyntaxKind.OperatorStatement If Not IsChildOf(declaration, SyntaxKind.OperatorBlock) Then Return DeclarationKind.Operator End If Case SyntaxKind.EventBlock Return DeclarationKind.CustomEvent Case SyntaxKind.EventStatement If Not IsChildOf(declaration, SyntaxKind.EventBlock) Then Return DeclarationKind.Event End If Case SyntaxKind.Parameter Return DeclarationKind.Parameter Case SyntaxKind.FieldDeclaration Return DeclarationKind.Field Case SyntaxKind.LocalDeclarationStatement If GetDeclarationCount(declaration) = 1 Then Return DeclarationKind.Variable End If Case SyntaxKind.ModifiedIdentifier If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then If IsChildOf(declaration.Parent, SyntaxKind.FieldDeclaration) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then Return DeclarationKind.Field ElseIf IsChildOf(declaration.Parent, SyntaxKind.LocalDeclarationStatement) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then Return DeclarationKind.Variable End If End If Case SyntaxKind.Attribute Dim list = TryCast(declaration.Parent, AttributeListSyntax) If list Is Nothing OrElse list.Attributes.Count > 1 Then Return DeclarationKind.Attribute End If Case SyntaxKind.AttributeList Dim list = DirectCast(declaration, AttributeListSyntax) If list.Attributes.Count = 1 Then Return DeclarationKind.Attribute End If Case SyntaxKind.GetAccessorBlock Return DeclarationKind.GetAccessor Case SyntaxKind.SetAccessorBlock Return DeclarationKind.SetAccessor Case SyntaxKind.AddHandlerAccessorBlock Return DeclarationKind.AddAccessor Case SyntaxKind.RemoveHandlerAccessorBlock Return DeclarationKind.RemoveAccessor Case SyntaxKind.RaiseEventAccessorBlock Return DeclarationKind.RaiseAccessor End Select Return DeclarationKind.None End Function Private Shared Function GetDeclarationCount(nodes As IReadOnlyList(Of SyntaxNode)) As Integer Dim count As Integer = 0 For i = 0 To nodes.Count - 1 count = count + GetDeclarationCount(nodes(i)) Next Return count End Function Friend Shared Function GetDeclarationCount(node As SyntaxNode) As Integer Select Case node.Kind Case SyntaxKind.FieldDeclaration Return GetDeclarationCount(DirectCast(node, FieldDeclarationSyntax).Declarators) Case SyntaxKind.LocalDeclarationStatement Return GetDeclarationCount(DirectCast(node, LocalDeclarationStatementSyntax).Declarators) Case SyntaxKind.VariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Names.Count Case SyntaxKind.AttributesStatement Return GetDeclarationCount(DirectCast(node, AttributesStatementSyntax).AttributeLists) Case SyntaxKind.AttributeList Return DirectCast(node, AttributeListSyntax).Attributes.Count Case SyntaxKind.ImportsStatement Return DirectCast(node, ImportsStatementSyntax).ImportsClauses.Count End Select Return 1 End Function Private Shared Function IsIndexer(declaration As SyntaxNode) As Boolean Select Case declaration.Kind Case SyntaxKind.PropertyBlock Dim p = DirectCast(declaration, PropertyBlockSyntax).PropertyStatement Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword) Case SyntaxKind.PropertyStatement If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then Dim p = DirectCast(declaration, PropertyStatementSyntax) Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword) End If End Select Return False End Function Public Function IsImplicitObjectCreation(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsImplicitObjectCreation Return False End Function Public Function SupportsNotPattern(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsNotPattern Return False End Function Public Function IsIsPatternExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsPatternExpression Return False End Function Public Function IsAnyPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnyPattern Return False End Function Public Function IsAndPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAndPattern Return False End Function Public Function IsBinaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryPattern Return False End Function Public Function IsConstantPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConstantPattern Return False End Function Public Function IsDeclarationPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationPattern Return False End Function Public Function IsNotPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNotPattern Return False End Function Public Function IsOrPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOrPattern Return False End Function Public Function IsParenthesizedPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParenthesizedPattern Return False End Function Public Function IsRecursivePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRecursivePattern Return False End Function Public Function IsUnaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnaryPattern Return False End Function Public Function IsTypePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypePattern Return False End Function Public Function IsVarPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVarPattern Return False End Function Public Sub GetPartsOfIsPatternExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef isToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfIsPatternExpression Throw ExceptionUtilities.Unreachable End Sub Public Function GetExpressionOfConstantPattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfConstantPattern Throw ExceptionUtilities.Unreachable End Function Public Sub GetPartsOfParenthesizedPattern(node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef pattern As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfBinaryPattern(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfUnaryPattern(node As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef pattern As SyntaxNode) Implements ISyntaxFacts.GetPartsOfUnaryPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfDeclarationPattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfDeclarationPattern Throw New NotImplementedException() End Sub Public Sub GetPartsOfRecursivePattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef positionalPart As SyntaxNode, ByRef propertyPart As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfRecursivePattern Throw New NotImplementedException() End Sub Public Function GetTypeOfTypePattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfTypePattern Throw New NotImplementedException() End Function Public Function GetExpressionOfThrowExpression(throwExpression As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfThrowExpression ' ThrowExpression doesn't exist in VB Throw New NotImplementedException() End Function Public Function IsThrowStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsThrowStatement Return node.IsKind(SyntaxKind.ThrowStatement) End Function Public Function IsLocalFunction(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLocalFunction Return False End Function Public Sub GetPartsOfInterpolationExpression(node As SyntaxNode, ByRef stringStartToken As SyntaxToken, ByRef contents As SyntaxList(Of SyntaxNode), ByRef stringEndToken As SyntaxToken) Implements ISyntaxFacts.GetPartsOfInterpolationExpression Dim interpolatedStringExpressionSyntax As InterpolatedStringExpressionSyntax = DirectCast(node, InterpolatedStringExpressionSyntax) stringStartToken = interpolatedStringExpressionSyntax.DollarSignDoubleQuoteToken contents = interpolatedStringExpressionSyntax.Contents stringEndToken = interpolatedStringExpressionSyntax.DoubleQuoteToken End Sub Public Function IsVerbatimInterpolatedStringExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVerbatimInterpolatedStringExpression Return False End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts #If CODE_STYLE Then Imports Microsoft.CodeAnalysis.Internal.Editing #Else Imports Microsoft.CodeAnalysis.Editing #End If Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices Friend Class VisualBasicSyntaxFacts Inherits AbstractSyntaxFacts Implements ISyntaxFacts Public Shared ReadOnly Property Instance As New VisualBasicSyntaxFacts Protected Sub New() End Sub Public ReadOnly Property IsCaseSensitive As Boolean Implements ISyntaxFacts.IsCaseSensitive Get Return False End Get End Property Public ReadOnly Property StringComparer As StringComparer Implements ISyntaxFacts.StringComparer Get Return CaseInsensitiveComparison.Comparer End Get End Property Public ReadOnly Property ElasticMarker As SyntaxTrivia Implements ISyntaxFacts.ElasticMarker Get Return SyntaxFactory.ElasticMarker End Get End Property Public ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia Implements ISyntaxFacts.ElasticCarriageReturnLineFeed Get Return SyntaxFactory.ElasticCarriageReturnLineFeed End Get End Property Public Overrides ReadOnly Property SyntaxKinds As ISyntaxKinds = VisualBasicSyntaxKinds.Instance Implements ISyntaxFacts.SyntaxKinds Public Function SupportsIndexingInitializer(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsIndexingInitializer Return False End Function Public Function SupportsThrowExpression(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsThrowExpression Return False End Function Public Function SupportsLocalFunctionDeclaration(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsLocalFunctionDeclaration Return False End Function Public Function SupportsRecord(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecord Return False End Function Public Function SupportsRecordStruct(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecordStruct Return False End Function Public Function ParseToken(text As String) As SyntaxToken Implements ISyntaxFacts.ParseToken Return SyntaxFactory.ParseToken(text, startStatement:=True) End Function Public Function ParseLeadingTrivia(text As String) As SyntaxTriviaList Implements ISyntaxFacts.ParseLeadingTrivia Return SyntaxFactory.ParseLeadingTrivia(text) End Function Public Function EscapeIdentifier(identifier As String) As String Implements ISyntaxFacts.EscapeIdentifier Dim keywordKind = SyntaxFacts.GetKeywordKind(identifier) Dim needsEscaping = keywordKind <> SyntaxKind.None Return If(needsEscaping, "[" & identifier & "]", identifier) End Function Public Function IsVerbatimIdentifier(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier Return False End Function Public Function IsOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsOperator Return (IsUnaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is UnaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) OrElse (IsBinaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is BinaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) End Function Public Function IsContextualKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsContextualKeyword Return token.IsContextualKeyword() End Function Public Function IsReservedKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsReservedKeyword Return token.IsReservedKeyword() End Function Public Function IsPreprocessorKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPreprocessorKeyword Return token.IsPreprocessorKeyword() End Function Public Function IsPreProcessorDirectiveContext(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsPreProcessorDirectiveContext Return syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken) End Function Public Function TryGetCorrespondingOpenBrace(token As SyntaxToken, ByRef openBrace As SyntaxToken) As Boolean Implements ISyntaxFacts.TryGetCorrespondingOpenBrace If token.Kind = SyntaxKind.CloseBraceToken Then Dim tuples = token.Parent.GetBraces() openBrace = tuples.openBrace Return openBrace.Kind = SyntaxKind.OpenBraceToken End If Return False End Function Public Function IsEntirelyWithinStringOrCharOrNumericLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsEntirelyWithinStringOrCharOrNumericLiteral If syntaxTree Is Nothing Then Return False End If Return syntaxTree.IsEntirelyWithinStringOrCharOrNumericLiteral(position, cancellationToken) End Function Public Function IsDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDirective Return TypeOf node Is DirectiveTriviaSyntax End Function Public Function TryGetExternalSourceInfo(node As SyntaxNode, ByRef info As ExternalSourceInfo) As Boolean Implements ISyntaxFacts.TryGetExternalSourceInfo Select Case node.Kind Case SyntaxKind.ExternalSourceDirectiveTrivia info = New ExternalSourceInfo(CInt(DirectCast(node, ExternalSourceDirectiveTriviaSyntax).LineStart.Value), False) Return True Case SyntaxKind.EndExternalSourceDirectiveTrivia info = New ExternalSourceInfo(Nothing, True) Return True End Select Return False End Function Public Function IsObjectCreationExpressionType(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsObjectCreationExpressionType Return node.IsParentKind(SyntaxKind.ObjectCreationExpression) AndAlso DirectCast(node.Parent, ObjectCreationExpressionSyntax).Type Is node End Function Public Function IsDeclarationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationExpression ' VB doesn't support declaration expressions Return False End Function Public Function IsAttributeName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeName Return node.IsParentKind(SyntaxKind.Attribute) AndAlso DirectCast(node.Parent, AttributeSyntax).Name Is node End Function Public Sub GetPartsOfQualifiedName(node As SyntaxNode, ByRef left As SyntaxNode, ByRef dotToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfQualifiedName Dim qualifiedName = DirectCast(node, QualifiedNameSyntax) left = qualifiedName.Left dotToken = qualifiedName.DotToken right = qualifiedName.Right End Sub Public Function IsRightSideOfQualifiedName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRightSideOfQualifiedName Dim vbNode = TryCast(node, SimpleNameSyntax) Return vbNode IsNot Nothing AndAlso vbNode.IsRightSideOfQualifiedName() End Function Public Function IsNameOfSimpleMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSimpleMemberAccessExpression Dim vbNode = TryCast(node, ExpressionSyntax) Return vbNode IsNot Nothing AndAlso vbNode.IsSimpleMemberAccessExpressionName() End Function Public Function IsNameOfAnyMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfAnyMemberAccessExpression Dim memberAccess = TryCast(node?.Parent, MemberAccessExpressionSyntax) Return memberAccess IsNot Nothing AndAlso memberAccess.Name Is node End Function Public Function GetStandaloneExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetStandaloneExpression Return SyntaxFactory.GetStandaloneExpression(TryCast(node, ExpressionSyntax)) End Function Public Function GetRootConditionalAccessExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRootConditionalAccessExpression Return TryCast(node, ExpressionSyntax).GetRootConditionalAccessExpression() End Function Public Sub GetPartsOfConditionalAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef whenNotNull As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalAccessExpression Dim conditionalAccess = DirectCast(node, ConditionalAccessExpressionSyntax) expression = conditionalAccess.Expression operatorToken = conditionalAccess.QuestionMarkToken whenNotNull = conditionalAccess.WhenNotNull End Sub Public Function IsAnonymousFunction(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnonymousFunction Return TypeOf node Is LambdaExpressionSyntax End Function Public Function IsNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamedArgument Dim arg = TryCast(node, SimpleArgumentSyntax) Return arg?.NameColonEquals IsNot Nothing End Function Public Function IsNameOfNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfNamedArgument Return node.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.IsNamed AndAlso p.NameColonEquals.Name Is node) End Function Public Function GetNameOfParameter(node As SyntaxNode) As SyntaxToken? Implements ISyntaxFacts.GetNameOfParameter Return DirectCast(node, ParameterSyntax).Identifier?.Identifier End Function Public Function GetDefaultOfParameter(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetDefaultOfParameter Return DirectCast(node, ParameterSyntax).Default End Function Public Function GetParameterList(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetParameterList Return node.GetParameterList() End Function Public Function IsParameterList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterList Return node.IsKind(SyntaxKind.ParameterList) End Function Public Function ISyntaxFacts_HasIncompleteParentMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.HasIncompleteParentMember Return HasIncompleteParentMember(node) End Function Public Function GetIdentifierOfGenericName(genericName As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfGenericName Return DirectCast(genericName, GenericNameSyntax).Identifier End Function Public Function IsUsingDirectiveName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingDirectiveName Return node.IsParentKind(SyntaxKind.SimpleImportsClause) AndAlso DirectCast(node.Parent, SimpleImportsClauseSyntax).Name Is node End Function Public Function IsDeconstructionAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionAssignment Return False End Function Public Function IsDeconstructionForEachStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionForEachStatement Return False End Function Public Function IsStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatement Return TypeOf node Is StatementSyntax End Function Public Function IsExecutableStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableStatement Return TypeOf node Is ExecutableStatementSyntax End Function Public Function IsMethodBody(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodBody Return TypeOf node Is MethodBlockBaseSyntax End Function Public Function GetExpressionOfReturnStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfReturnStatement Return DirectCast(node, ReturnStatementSyntax).Expression End Function Public Function IsThisConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsThisConstructorInitializer If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax) Return memberAccess.IsThisConstructorInitializer() End If Return False End Function Public Function IsBaseConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsBaseConstructorInitializer If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax) Return memberAccess.IsBaseConstructorInitializer() End If Return False End Function Public Function IsQueryKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsQueryKeyword Select Case token.Kind() Case _ SyntaxKind.JoinKeyword, SyntaxKind.IntoKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword, SyntaxKind.ByKeyword, SyntaxKind.OrderKeyword, SyntaxKind.WhereKeyword, SyntaxKind.OnKeyword, SyntaxKind.FromKeyword, SyntaxKind.WhileKeyword, SyntaxKind.SelectKeyword Return TypeOf token.Parent Is QueryClauseSyntax Case SyntaxKind.GroupKeyword Return (TypeOf token.Parent Is QueryClauseSyntax) OrElse (token.Parent.IsKind(SyntaxKind.GroupAggregation)) Case SyntaxKind.EqualsKeyword Return TypeOf token.Parent Is JoinConditionSyntax Case SyntaxKind.AscendingKeyword, SyntaxKind.DescendingKeyword Return TypeOf token.Parent Is OrderingSyntax Case SyntaxKind.InKeyword Return TypeOf token.Parent Is CollectionRangeVariableSyntax Case Else Return False End Select End Function Public Function IsThrowExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsThrowExpression ' VB does not support throw expressions currently. Return False End Function Public Function IsPredefinedType(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedType Dim actualType As PredefinedType = PredefinedType.None Return TryGetPredefinedType(token, actualType) AndAlso actualType <> PredefinedType.None End Function Public Function IsPredefinedType(token As SyntaxToken, type As PredefinedType) As Boolean Implements ISyntaxFacts.IsPredefinedType Dim actualType As PredefinedType = PredefinedType.None Return TryGetPredefinedType(token, actualType) AndAlso actualType = type End Function Public Function TryGetPredefinedType(token As SyntaxToken, ByRef type As PredefinedType) As Boolean Implements ISyntaxFacts.TryGetPredefinedType type = GetPredefinedType(token) Return type <> PredefinedType.None End Function Private Shared Function GetPredefinedType(token As SyntaxToken) As PredefinedType Select Case token.Kind Case SyntaxKind.BooleanKeyword Return PredefinedType.Boolean Case SyntaxKind.ByteKeyword Return PredefinedType.Byte Case SyntaxKind.SByteKeyword Return PredefinedType.SByte Case SyntaxKind.IntegerKeyword Return PredefinedType.Int32 Case SyntaxKind.UIntegerKeyword Return PredefinedType.UInt32 Case SyntaxKind.ShortKeyword Return PredefinedType.Int16 Case SyntaxKind.UShortKeyword Return PredefinedType.UInt16 Case SyntaxKind.LongKeyword Return PredefinedType.Int64 Case SyntaxKind.ULongKeyword Return PredefinedType.UInt64 Case SyntaxKind.SingleKeyword Return PredefinedType.Single Case SyntaxKind.DoubleKeyword Return PredefinedType.Double Case SyntaxKind.DecimalKeyword Return PredefinedType.Decimal Case SyntaxKind.StringKeyword Return PredefinedType.String Case SyntaxKind.CharKeyword Return PredefinedType.Char Case SyntaxKind.ObjectKeyword Return PredefinedType.Object Case SyntaxKind.DateKeyword Return PredefinedType.DateTime Case Else Return PredefinedType.None End Select End Function Public Function IsPredefinedOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedOperator Dim actualOp As PredefinedOperator = PredefinedOperator.None Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp <> PredefinedOperator.None End Function Public Function IsPredefinedOperator(token As SyntaxToken, op As PredefinedOperator) As Boolean Implements ISyntaxFacts.IsPredefinedOperator Dim actualOp As PredefinedOperator = PredefinedOperator.None Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp = op End Function Public Function TryGetPredefinedOperator(token As SyntaxToken, ByRef op As PredefinedOperator) As Boolean Implements ISyntaxFacts.TryGetPredefinedOperator op = GetPredefinedOperator(token) Return op <> PredefinedOperator.None End Function Private Shared Function GetPredefinedOperator(token As SyntaxToken) As PredefinedOperator Select Case token.Kind Case SyntaxKind.PlusToken, SyntaxKind.PlusEqualsToken Return PredefinedOperator.Addition Case SyntaxKind.MinusToken, SyntaxKind.MinusEqualsToken Return PredefinedOperator.Subtraction Case SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword Return PredefinedOperator.BitwiseAnd Case SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword Return PredefinedOperator.BitwiseOr Case SyntaxKind.AmpersandToken, SyntaxKind.AmpersandEqualsToken Return PredefinedOperator.Concatenate Case SyntaxKind.SlashToken, SyntaxKind.SlashEqualsToken Return PredefinedOperator.Division Case SyntaxKind.EqualsToken Return PredefinedOperator.Equality Case SyntaxKind.XorKeyword Return PredefinedOperator.ExclusiveOr Case SyntaxKind.CaretToken, SyntaxKind.CaretEqualsToken Return PredefinedOperator.Exponent Case SyntaxKind.GreaterThanToken Return PredefinedOperator.GreaterThan Case SyntaxKind.GreaterThanEqualsToken Return PredefinedOperator.GreaterThanOrEqual Case SyntaxKind.LessThanGreaterThanToken Return PredefinedOperator.Inequality Case SyntaxKind.BackslashToken, SyntaxKind.BackslashEqualsToken Return PredefinedOperator.IntegerDivision Case SyntaxKind.LessThanLessThanToken, SyntaxKind.LessThanLessThanEqualsToken Return PredefinedOperator.LeftShift Case SyntaxKind.LessThanToken Return PredefinedOperator.LessThan Case SyntaxKind.LessThanEqualsToken Return PredefinedOperator.LessThanOrEqual Case SyntaxKind.LikeKeyword Return PredefinedOperator.Like Case SyntaxKind.NotKeyword Return PredefinedOperator.Complement Case SyntaxKind.ModKeyword Return PredefinedOperator.Modulus Case SyntaxKind.AsteriskToken, SyntaxKind.AsteriskEqualsToken Return PredefinedOperator.Multiplication Case SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.GreaterThanGreaterThanEqualsToken Return PredefinedOperator.RightShift Case Else Return PredefinedOperator.None End Select End Function Public Function GetText(kind As Integer) As String Implements ISyntaxFacts.GetText Return SyntaxFacts.GetText(CType(kind, SyntaxKind)) End Function Public Function IsIdentifierPartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierPartCharacter Return SyntaxFacts.IsIdentifierPartCharacter(c) End Function Public Function IsIdentifierStartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierStartCharacter Return SyntaxFacts.IsIdentifierStartCharacter(c) End Function Public Function IsIdentifierEscapeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierEscapeCharacter Return c = "["c OrElse c = "]"c End Function Public Function IsValidIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsValidIdentifier Dim token = SyntaxFactory.ParseToken(identifier) ' TODO: There is no way to get the diagnostics to see if any are actually errors? Return IsIdentifier(token) AndAlso Not token.ContainsDiagnostics AndAlso token.ToString().Length = identifier.Length End Function Public Function IsVerbatimIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier Return IsValidIdentifier(identifier) AndAlso MakeHalfWidthIdentifier(identifier.First()) = "[" AndAlso MakeHalfWidthIdentifier(identifier.Last()) = "]" End Function Public Function IsTypeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsTypeCharacter Return c = "%"c OrElse c = "&"c OrElse c = "@"c OrElse c = "!"c OrElse c = "#"c OrElse c = "$"c End Function Public Function IsStartOfUnicodeEscapeSequence(c As Char) As Boolean Implements ISyntaxFacts.IsStartOfUnicodeEscapeSequence Return False ' VB does not support identifiers with escaped unicode characters End Function Public Function IsLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsLiteral Select Case token.Kind() Case _ SyntaxKind.IntegerLiteralToken, SyntaxKind.CharacterLiteralToken, SyntaxKind.DecimalLiteralToken, SyntaxKind.FloatingLiteralToken, SyntaxKind.DateLiteralToken, SyntaxKind.StringLiteralToken, SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.DoubleQuoteToken, SyntaxKind.InterpolatedStringTextToken, SyntaxKind.TrueKeyword, SyntaxKind.FalseKeyword, SyntaxKind.NothingKeyword Return True End Select Return False End Function Public Function IsStringLiteralOrInterpolatedStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsStringLiteralOrInterpolatedStringLiteral Return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken) End Function Public Function IsNumericLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNumericLiteralExpression Return If(node Is Nothing, False, node.IsKind(SyntaxKind.NumericLiteralExpression)) End Function Public Function IsBindableToken(token As Microsoft.CodeAnalysis.SyntaxToken) As Boolean Implements ISyntaxFacts.IsBindableToken Return Me.IsWord(token) OrElse Me.IsLiteral(token) OrElse Me.IsOperator(token) End Function Public Function IsPointerMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPointerMemberAccessExpression Return False End Function Public Function IsSimpleName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleName Return TypeOf node Is SimpleNameSyntax End Function Public Sub GetNameAndArityOfSimpleName(node As SyntaxNode, ByRef name As String, ByRef arity As Integer) Implements ISyntaxFacts.GetNameAndArityOfSimpleName Dim simpleName = DirectCast(node, SimpleNameSyntax) name = simpleName.Identifier.ValueText arity = simpleName.Arity End Sub Public Function LooksGeneric(name As SyntaxNode) As Boolean Implements ISyntaxFacts.LooksGeneric Return name.IsKind(SyntaxKind.GenericName) End Function Public Function GetExpressionOfMemberAccessExpression(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfMemberAccessExpression Return TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget) End Function Public Function GetTargetOfMemberBinding(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTargetOfMemberBinding ' Member bindings are a C# concept. Return Nothing End Function Public Function GetNameOfMemberBindingExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberBindingExpression ' Member bindings are a C# concept. Return Nothing End Function Public Sub GetPartsOfElementAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfElementAccessExpression Dim invocation = TryCast(node, InvocationExpressionSyntax) If invocation IsNot Nothing Then expression = invocation?.Expression argumentList = invocation?.ArgumentList Return End If If node.Kind() = SyntaxKind.DictionaryAccessExpression Then GetPartsOfMemberAccessExpression(node, expression, argumentList) Return End If Throw ExceptionUtilities.UnexpectedValue(node.Kind()) End Sub Public Function GetExpressionOfInterpolation(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfInterpolation Return DirectCast(node, InterpolationSyntax).Expression End Function Public Function IsInNamespaceOrTypeContext(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInNamespaceOrTypeContext Return SyntaxFacts.IsInNamespaceOrTypeContext(node) End Function Public Function IsBaseTypeList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBaseTypeList Return TryCast(node, InheritsOrImplementsStatementSyntax) IsNot Nothing End Function Public Function IsInStaticContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInStaticContext Return node.IsInStaticContext() End Function Public Function GetExpressionOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetExpressionOfArgument Return DirectCast(node, ArgumentSyntax).GetArgumentExpression() End Function Public Function GetRefKindOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.RefKind Implements ISyntaxFacts.GetRefKindOfArgument ' TODO(cyrusn): Consider the method this argument is passed to, to determine this. Return RefKind.None End Function Public Function IsArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsArgument Return TypeOf node Is ArgumentSyntax End Function Public Function IsSimpleArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleArgument Dim argument = TryCast(node, ArgumentSyntax) Return argument IsNot Nothing AndAlso Not argument.IsNamed AndAlso Not argument.IsOmitted End Function Public Function IsInConstantContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstantContext Return node.IsInConstantContext() End Function Public Function IsInConstructor(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstructor Return node.GetAncestors(Of StatementSyntax).Any(Function(s) s.Kind = SyntaxKind.ConstructorBlock) End Function Public Function IsUnsafeContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnsafeContext Return False End Function Public Function GetNameOfAttribute(node As SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetNameOfAttribute Return DirectCast(node, AttributeSyntax).Name End Function Public Function GetExpressionOfParenthesizedExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfParenthesizedExpression Return DirectCast(node, ParenthesizedExpressionSyntax).Expression End Function Public Function IsAttributeNamedArgumentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeNamedArgumentIdentifier Dim identifierName = TryCast(node, IdentifierNameSyntax) Return identifierName.IsParentKind(SyntaxKind.NameColonEquals) AndAlso identifierName.Parent.IsParentKind(SyntaxKind.SimpleArgument) AndAlso identifierName.Parent.Parent.IsParentKind(SyntaxKind.ArgumentList) AndAlso identifierName.Parent.Parent.Parent.IsParentKind(SyntaxKind.Attribute) End Function Public Function GetContainingTypeDeclaration(root As SyntaxNode, position As Integer) As SyntaxNode Implements ISyntaxFacts.GetContainingTypeDeclaration If root Is Nothing Then Throw New ArgumentNullException(NameOf(root)) End If If position < 0 OrElse position > root.Span.End Then Throw New ArgumentOutOfRangeException(NameOf(position)) End If Return root. FindToken(position). GetAncestors(Of SyntaxNode)(). FirstOrDefault(Function(n) TypeOf n Is TypeBlockSyntax OrElse TypeOf n Is DelegateStatementSyntax) End Function Public Function GetContainingVariableDeclaratorOfFieldDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetContainingVariableDeclaratorOfFieldDeclaration If node Is Nothing Then Throw New ArgumentNullException(NameOf(node)) End If Dim parent = node.Parent While node IsNot Nothing If node.Kind = SyntaxKind.VariableDeclarator AndAlso node.IsParentKind(SyntaxKind.FieldDeclaration) Then Return node End If node = node.Parent End While Return Nothing End Function Public Function FindTokenOnLeftOfPosition(node As SyntaxNode, position As Integer, Optional includeSkipped As Boolean = True, Optional includeDirectives As Boolean = False, Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFacts.FindTokenOnLeftOfPosition Return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments) End Function Public Function FindTokenOnRightOfPosition(node As SyntaxNode, position As Integer, Optional includeSkipped As Boolean = True, Optional includeDirectives As Boolean = False, Optional includeDocumentationComments As Boolean = False) As SyntaxToken Implements ISyntaxFacts.FindTokenOnRightOfPosition Return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments) End Function Public Function IsMemberInitializerNamedAssignmentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier Dim unused As SyntaxNode = Nothing Return IsMemberInitializerNamedAssignmentIdentifier(node, unused) End Function Public Function IsMemberInitializerNamedAssignmentIdentifier( node As SyntaxNode, ByRef initializedInstance As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier Dim identifier = TryCast(node, IdentifierNameSyntax) If identifier?.IsChildNode(Of NamedFieldInitializerSyntax)(Function(n) n.Name) Then ' .parent is the NamedField. ' .parent.parent is the ObjectInitializer. ' .parent.parent.parent will be the ObjectCreationExpression. initializedInstance = identifier.Parent.Parent.Parent Return True End If Return False End Function Public Function IsNameOfSubpattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSubpattern Return False End Function Public Function IsPropertyPatternClause(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPropertyPatternClause Return False End Function Public Function IsElementAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsElementAccessExpression ' VB doesn't have a specialized node for element access. Instead, it just uses an ' invocation expression or dictionary access expression. Return node.Kind = SyntaxKind.InvocationExpression OrElse node.Kind = SyntaxKind.DictionaryAccessExpression End Function Public Sub GetPartsOfParenthesizedExpression( node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef expression As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedExpression Dim parenthesizedExpression = DirectCast(node, ParenthesizedExpressionSyntax) openParen = parenthesizedExpression.OpenParenToken expression = parenthesizedExpression.Expression closeParen = parenthesizedExpression.CloseParenToken End Sub Public Function IsTypeNamedVarInVariableOrFieldDeclaration(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeNamedVarInVariableOrFieldDeclaration Return False End Function Public Function IsTypeNamedDynamic(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeNamedDynamic Return False End Function Public Function IsIndexerMemberCRef(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIndexerMemberCRef Return False End Function Public Function GetContainingMemberDeclaration(root As SyntaxNode, position As Integer, Optional useFullSpan As Boolean = True) As SyntaxNode Implements ISyntaxFacts.GetContainingMemberDeclaration Contract.ThrowIfNull(root, NameOf(root)) Contract.ThrowIfTrue(position < 0 OrElse position > root.FullSpan.End, NameOf(position)) Dim [end] = root.FullSpan.End If [end] = 0 Then ' empty file Return Nothing End If ' make sure position doesn't touch end of root position = Math.Min(position, [end] - 1) Dim node = root.FindToken(position).Parent While node IsNot Nothing If useFullSpan OrElse node.Span.Contains(position) Then If TypeOf node Is MethodBlockBaseSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return node End If If TypeOf node Is MethodBaseSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return node End If If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return node End If If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then Return node End If If TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is EnumBlockSyntax OrElse TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is EventBlockSyntax OrElse TypeOf node Is FieldDeclarationSyntax Then Return node End If End If node = node.Parent End While Return Nothing End Function Public Function IsMethodLevelMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodLevelMember ' Note: Derived types of MethodBaseSyntax are expanded explicitly, since PropertyStatementSyntax and ' EventStatementSyntax will NOT be parented by MethodBlockBaseSyntax. Additionally, there are things ' like AccessorStatementSyntax and DelegateStatementSyntax that we never want to tread as method level ' members. If TypeOf node Is MethodStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is SubNewStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is OperatorStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then Return True End If If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then Return True End If If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then Return True End If If TypeOf node Is DeclareStatementSyntax Then Return True End If Return TypeOf node Is ConstructorBlockSyntax OrElse TypeOf node Is MethodBlockSyntax OrElse TypeOf node Is OperatorBlockSyntax OrElse TypeOf node Is EventBlockSyntax OrElse TypeOf node Is PropertyBlockSyntax OrElse TypeOf node Is EnumMemberDeclarationSyntax OrElse TypeOf node Is FieldDeclarationSyntax End Function Public Function GetMemberBodySpanForSpeculativeBinding(node As SyntaxNode) As TextSpan Implements ISyntaxFacts.GetMemberBodySpanForSpeculativeBinding Dim member = GetContainingMemberDeclaration(node, node.SpanStart) If member Is Nothing Then Return Nothing End If ' TODO: currently we only support method for now Dim method = TryCast(member, MethodBlockBaseSyntax) If method IsNot Nothing Then If method.BlockStatement Is Nothing OrElse method.EndBlockStatement Is Nothing Then Return Nothing End If ' We don't want to include the BlockStatement or any trailing trivia up to and including its statement ' terminator in the span. Instead, we use the start of the first statement's leading trivia (if any) up ' to the start of the EndBlockStatement. If there aren't any statements in the block, we use the start ' of the EndBlockStatements leading trivia. Dim firstStatement = method.Statements.FirstOrDefault() Dim spanStart = If(firstStatement IsNot Nothing, firstStatement.FullSpan.Start, method.EndBlockStatement.FullSpan.Start) Return TextSpan.FromBounds(spanStart, method.EndBlockStatement.SpanStart) End If Return Nothing End Function Public Function ContainsInMemberBody(node As SyntaxNode, span As TextSpan) As Boolean Implements ISyntaxFacts.ContainsInMemberBody Dim method = TryCast(node, MethodBlockBaseSyntax) If method IsNot Nothing Then Return method.Statements.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan(method.Statements), span) End If Dim [event] = TryCast(node, EventBlockSyntax) If [event] IsNot Nothing Then Return [event].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([event].Accessors), span) End If Dim [property] = TryCast(node, PropertyBlockSyntax) If [property] IsNot Nothing Then Return [property].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([property].Accessors), span) End If Dim field = TryCast(node, FieldDeclarationSyntax) If field IsNot Nothing Then Return field.Declarators.Count > 0 AndAlso ContainsExclusively(GetSeparatedSyntaxListSpan(field.Declarators), span) End If Dim [enum] = TryCast(node, EnumMemberDeclarationSyntax) If [enum] IsNot Nothing Then Return [enum].Initializer IsNot Nothing AndAlso ContainsExclusively([enum].Initializer.Span, span) End If Dim propStatement = TryCast(node, PropertyStatementSyntax) If propStatement IsNot Nothing Then Return propStatement.Initializer IsNot Nothing AndAlso ContainsExclusively(propStatement.Initializer.Span, span) End If Return False End Function Private Shared Function ContainsExclusively(outerSpan As TextSpan, innerSpan As TextSpan) As Boolean If innerSpan.IsEmpty Then Return outerSpan.Contains(innerSpan.Start) End If Return outerSpan.Contains(innerSpan) End Function Private Shared Function GetSyntaxListSpan(Of T As SyntaxNode)(list As SyntaxList(Of T)) As TextSpan Debug.Assert(list.Count > 0) Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End) End Function Private Shared Function GetSeparatedSyntaxListSpan(Of T As SyntaxNode)(list As SeparatedSyntaxList(Of T)) As TextSpan Debug.Assert(list.Count > 0) Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End) End Function Public Function GetTopLevelAndMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetTopLevelAndMethodLevelMembers Dim list = New List(Of SyntaxNode)() AppendMembers(root, list, topLevel:=True, methodLevel:=True) Return list End Function Public Function GetMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetMethodLevelMembers Dim list = New List(Of SyntaxNode)() AppendMembers(root, list, topLevel:=False, methodLevel:=True) Return list End Function Public Function IsClassDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsClassDeclaration Return node.IsKind(SyntaxKind.ClassBlock) End Function Public Function IsNamespaceDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamespaceDeclaration Return node.IsKind(SyntaxKind.NamespaceBlock) End Function Public Function GetNameOfNamespaceDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfNamespaceDeclaration If IsNamespaceDeclaration(node) Then Return DirectCast(node, NamespaceBlockSyntax).NamespaceStatement.Name End If Return Nothing End Function Public Function GetMembersOfTypeDeclaration(typeDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfTypeDeclaration Return DirectCast(typeDeclaration, TypeBlockSyntax).Members End Function Public Function GetMembersOfNamespaceDeclaration(namespaceDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfNamespaceDeclaration Return DirectCast(namespaceDeclaration, NamespaceBlockSyntax).Members End Function Public Function GetMembersOfCompilationUnit(compilationUnit As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfCompilationUnit Return DirectCast(compilationUnit, CompilationUnitSyntax).Members End Function Public Function GetImportsOfNamespaceDeclaration(namespaceDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetImportsOfNamespaceDeclaration 'Visual Basic doesn't have namespaced imports Return Nothing End Function Public Function GetImportsOfCompilationUnit(compilationUnit As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetImportsOfCompilationUnit Return DirectCast(compilationUnit, CompilationUnitSyntax).Imports End Function Public Function IsTopLevelNodeWithMembers(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTopLevelNodeWithMembers Return TypeOf node Is NamespaceBlockSyntax OrElse TypeOf node Is TypeBlockSyntax OrElse TypeOf node Is EnumBlockSyntax End Function Private Const s_dotToken As String = "." Public Function GetDisplayName(node As SyntaxNode, options As DisplayNameOptions, Optional rootNamespace As String = Nothing) As String Implements ISyntaxFacts.GetDisplayName If node Is Nothing Then Return String.Empty End If Dim pooled = PooledStringBuilder.GetInstance() Dim builder = pooled.Builder ' member keyword (if any) Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax) If (options And DisplayNameOptions.IncludeMemberKeyword) <> 0 Then Dim keywordToken = memberDeclaration.GetMemberKeywordToken() If keywordToken <> Nothing AndAlso Not keywordToken.IsMissing Then builder.Append(keywordToken.Text) builder.Append(" "c) End If End If Dim names = ArrayBuilder(Of String).GetInstance() ' containing type(s) Dim parent = node.Parent While TypeOf parent Is TypeBlockSyntax names.Push(GetName(parent, options, containsGlobalKeyword:=False)) parent = parent.Parent End While If (options And DisplayNameOptions.IncludeNamespaces) <> 0 Then ' containing namespace(s) in source (if any) Dim containsGlobalKeyword As Boolean = False While parent IsNot Nothing AndAlso parent.Kind() = SyntaxKind.NamespaceBlock names.Push(GetName(parent, options, containsGlobalKeyword)) parent = parent.Parent End While ' root namespace (if any) If Not containsGlobalKeyword AndAlso Not String.IsNullOrEmpty(rootNamespace) Then builder.Append(rootNamespace) builder.Append(s_dotToken) End If End If While Not names.IsEmpty() Dim name = names.Pop() If name IsNot Nothing Then builder.Append(name) builder.Append(s_dotToken) End If End While names.Free() ' name (include generic type parameters) builder.Append(GetName(node, options, containsGlobalKeyword:=False)) ' parameter list (if any) If (options And DisplayNameOptions.IncludeParameters) <> 0 Then builder.Append(memberDeclaration.GetParameterList()) End If ' As clause (if any) If (options And DisplayNameOptions.IncludeType) <> 0 Then Dim asClause = memberDeclaration.GetAsClause() If asClause IsNot Nothing Then builder.Append(" "c) builder.Append(asClause) End If End If Return pooled.ToStringAndFree() End Function Private Shared Function GetName(node As SyntaxNode, options As DisplayNameOptions, ByRef containsGlobalKeyword As Boolean) As String Const missingTokenPlaceholder As String = "?" Select Case node.Kind() Case SyntaxKind.CompilationUnit Return Nothing Case SyntaxKind.IdentifierName Dim identifier = DirectCast(node, IdentifierNameSyntax).Identifier Return If(identifier.IsMissing, missingTokenPlaceholder, identifier.Text) Case SyntaxKind.IncompleteMember Return missingTokenPlaceholder Case SyntaxKind.NamespaceBlock Dim nameSyntax = CType(node, NamespaceBlockSyntax).NamespaceStatement.Name If nameSyntax.Kind() = SyntaxKind.GlobalName Then containsGlobalKeyword = True Return Nothing Else Return GetName(nameSyntax, options, containsGlobalKeyword) End If Case SyntaxKind.QualifiedName Dim qualified = CType(node, QualifiedNameSyntax) If qualified.Left.Kind() = SyntaxKind.GlobalName Then containsGlobalKeyword = True Return GetName(qualified.Right, options, containsGlobalKeyword) ' don't use the Global prefix if specified Else Return GetName(qualified.Left, options, containsGlobalKeyword) + s_dotToken + GetName(qualified.Right, options, containsGlobalKeyword) End If End Select Dim name As String = Nothing Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax) If memberDeclaration IsNot Nothing Then Dim nameToken = memberDeclaration.GetNameToken() If nameToken <> Nothing Then name = If(nameToken.IsMissing, missingTokenPlaceholder, nameToken.Text) If (options And DisplayNameOptions.IncludeTypeParameters) <> 0 Then Dim pooled = PooledStringBuilder.GetInstance() Dim builder = pooled.Builder builder.Append(name) AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()) name = pooled.ToStringAndFree() End If End If End If Debug.Assert(name IsNot Nothing, "Unexpected node type " + node.Kind().ToString()) Return name End Function Private Shared Sub AppendTypeParameterList(builder As StringBuilder, typeParameterList As TypeParameterListSyntax) If typeParameterList IsNot Nothing AndAlso typeParameterList.Parameters.Count > 0 Then builder.Append("(Of ") builder.Append(typeParameterList.Parameters(0).Identifier.Text) For i = 1 To typeParameterList.Parameters.Count - 1 builder.Append(", ") builder.Append(typeParameterList.Parameters(i).Identifier.Text) Next builder.Append(")"c) End If End Sub Private Sub AppendMembers(node As SyntaxNode, list As List(Of SyntaxNode), topLevel As Boolean, methodLevel As Boolean) Debug.Assert(topLevel OrElse methodLevel) For Each member In node.GetMembers() If IsTopLevelNodeWithMembers(member) Then If topLevel Then list.Add(member) End If AppendMembers(member, list, topLevel, methodLevel) Continue For End If If methodLevel AndAlso IsMethodLevelMember(member) Then list.Add(member) End If Next End Sub Public Function TryGetBindableParent(token As SyntaxToken) As SyntaxNode Implements ISyntaxFacts.TryGetBindableParent Dim node = token.Parent While node IsNot Nothing Dim parent = node.Parent ' If this node is on the left side of a member access expression, don't ascend ' further or we'll end up binding to something else. Dim memberAccess = TryCast(parent, MemberAccessExpressionSyntax) If memberAccess IsNot Nothing Then If memberAccess.Expression Is node Then Exit While End If End If ' If this node is on the left side of a qualified name, don't ascend ' further or we'll end up binding to something else. Dim qualifiedName = TryCast(parent, QualifiedNameSyntax) If qualifiedName IsNot Nothing Then If qualifiedName.Left Is node Then Exit While End If End If ' If this node is the type of an object creation expression, return the ' object creation expression. Dim objectCreation = TryCast(parent, ObjectCreationExpressionSyntax) If objectCreation IsNot Nothing Then If objectCreation.Type Is node Then node = parent Exit While End If End If ' The inside of an interpolated string is treated as its own token so we ' need to force navigation to the parent expression syntax. If TypeOf node Is InterpolatedStringTextSyntax AndAlso TypeOf parent Is InterpolatedStringExpressionSyntax Then node = parent Exit While End If ' If this node is not parented by a name, we're done. Dim name = TryCast(parent, NameSyntax) If name Is Nothing Then Exit While End If node = parent End While Return node End Function Public Function GetConstructors(root As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode) Implements ISyntaxFacts.GetConstructors Dim compilationUnit = TryCast(root, CompilationUnitSyntax) If compilationUnit Is Nothing Then Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)() End If Dim constructors = New List(Of SyntaxNode)() AppendConstructors(compilationUnit.Members, constructors, cancellationToken) Return constructors End Function Private Sub AppendConstructors(members As SyntaxList(Of StatementSyntax), constructors As List(Of SyntaxNode), cancellationToken As CancellationToken) For Each member As StatementSyntax In members cancellationToken.ThrowIfCancellationRequested() Dim constructor = TryCast(member, ConstructorBlockSyntax) If constructor IsNot Nothing Then constructors.Add(constructor) Continue For End If Dim [namespace] = TryCast(member, NamespaceBlockSyntax) If [namespace] IsNot Nothing Then AppendConstructors([namespace].Members, constructors, cancellationToken) End If Dim [class] = TryCast(member, ClassBlockSyntax) If [class] IsNot Nothing Then AppendConstructors([class].Members, constructors, cancellationToken) End If Dim [struct] = TryCast(member, StructureBlockSyntax) If [struct] IsNot Nothing Then AppendConstructors([struct].Members, constructors, cancellationToken) End If Next End Sub Public Function GetInactiveRegionSpanAroundPosition(tree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As TextSpan Implements ISyntaxFacts.GetInactiveRegionSpanAroundPosition Dim trivia = tree.FindTriviaToLeft(position, cancellationToken) If trivia.Kind = SyntaxKind.DisabledTextTrivia Then Return trivia.FullSpan End If Return Nothing End Function Public Function GetNameForArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForArgument If TryCast(argument, ArgumentSyntax)?.IsNamed Then Return DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.Identifier.ValueText End If Return String.Empty End Function Public Function GetNameForAttributeArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForAttributeArgument ' All argument types are ArgumentSyntax in VB. Return GetNameForArgument(argument) End Function Public Function IsLeftSideOfDot(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfDot Return TryCast(node, ExpressionSyntax).IsLeftSideOfDot() End Function Public Function GetRightSideOfDot(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightSideOfDot Return If(TryCast(node, QualifiedNameSyntax)?.Right, TryCast(node, MemberAccessExpressionSyntax)?.Name) End Function Public Function GetLeftSideOfDot(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetLeftSideOfDot Return If(TryCast(node, QualifiedNameSyntax)?.Left, TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget)) End Function Public Function IsLeftSideOfExplicitInterfaceSpecifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfExplicitInterfaceSpecifier Return IsLeftSideOfDot(node) AndAlso TryCast(node.Parent.Parent, ImplementsClauseSyntax) IsNot Nothing End Function Public Function IsLeftSideOfAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfSimpleAssignmentStatement End Function Public Function IsLeftSideOfAnyAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAnyAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfAnyAssignmentStatement End Function Public Function IsLeftSideOfCompoundAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfCompoundAssignment Return TryCast(node, ExpressionSyntax).IsLeftSideOfCompoundAssignmentStatement End Function Public Function GetRightHandSideOfAssignment(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightHandSideOfAssignment Return DirectCast(node, AssignmentStatementSyntax).Right End Function Public Function IsInferredAnonymousObjectMemberDeclarator(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInferredAnonymousObjectMemberDeclarator Return node.IsKind(SyntaxKind.InferredFieldInitializer) End Function Public Function IsOperandOfIncrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementExpression Return False End Function Public Function IsOperandOfIncrementOrDecrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementOrDecrementExpression Return False End Function Public Function GetContentsOfInterpolatedString(interpolatedString As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentsOfInterpolatedString Return (TryCast(interpolatedString, InterpolatedStringExpressionSyntax)?.Contents).Value End Function Public Function IsNumericLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsNumericLiteral Return token.Kind = SyntaxKind.DecimalLiteralToken OrElse token.Kind = SyntaxKind.FloatingLiteralToken OrElse token.Kind = SyntaxKind.IntegerLiteralToken End Function Public Function IsVerbatimStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimStringLiteral ' VB does not have verbatim strings Return False End Function Public Function GetArgumentsOfInvocationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfInvocationExpression Dim argumentList = DirectCast(node, InvocationExpressionSyntax).ArgumentList Return If(argumentList Is Nothing, Nothing, GetArgumentsOfArgumentList(argumentList)) End Function Public Function GetArgumentsOfObjectCreationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfObjectCreationExpression Dim argumentList = DirectCast(node, ObjectCreationExpressionSyntax).ArgumentList Return If(argumentList Is Nothing, Nothing, GetArgumentsOfArgumentList(argumentList)) End Function Public Function GetArgumentsOfArgumentList(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfArgumentList Return DirectCast(node, ArgumentListSyntax).Arguments End Function Public Function GetArgumentListOfInvocationExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetArgumentListOfInvocationExpression Return DirectCast(node, InvocationExpressionSyntax).ArgumentList End Function Public Function GetArgumentListOfObjectCreationExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetArgumentListOfObjectCreationExpression Return DirectCast(node, ObjectCreationExpressionSyntax).ArgumentList End Function Public Function ConvertToSingleLine(node As SyntaxNode, Optional useElasticTrivia As Boolean = False) As SyntaxNode Implements ISyntaxFacts.ConvertToSingleLine Return node.ConvertToSingleLine(useElasticTrivia) End Function Public Function IsDocumentationComment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDocumentationComment Return node.IsKind(SyntaxKind.DocumentationCommentTrivia) End Function Public Function IsUsingOrExternOrImport(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingOrExternOrImport Return node.IsKind(SyntaxKind.ImportsStatement) End Function Public Function IsGlobalAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalAssemblyAttribute Return IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword) End Function Public Function IsModuleAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalModuleAttribute Return IsGlobalAttribute(node, SyntaxKind.ModuleKeyword) End Function Private Shared Function IsGlobalAttribute(node As SyntaxNode, attributeTarget As SyntaxKind) As Boolean If node.IsKind(SyntaxKind.Attribute) Then Dim attributeNode = CType(node, AttributeSyntax) If attributeNode.Target IsNot Nothing Then Return attributeNode.Target.AttributeModifier.IsKind(attributeTarget) End If End If Return False End Function Public Function IsDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaration ' From the Visual Basic language spec: ' NamespaceMemberDeclaration := ' NamespaceDeclaration | ' TypeDeclaration ' TypeDeclaration ::= ' ModuleDeclaration | ' NonModuleDeclaration ' NonModuleDeclaration ::= ' EnumDeclaration | ' StructureDeclaration | ' InterfaceDeclaration | ' ClassDeclaration | ' DelegateDeclaration ' ClassMemberDeclaration ::= ' NonModuleDeclaration | ' EventMemberDeclaration | ' VariableMemberDeclaration | ' ConstantMemberDeclaration | ' MethodMemberDeclaration | ' PropertyMemberDeclaration | ' ConstructorMemberDeclaration | ' OperatorDeclaration Select Case node.Kind() ' Because fields declarations can define multiple symbols "Public a, b As Integer" ' We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name. Case SyntaxKind.VariableDeclarator If (node.Parent.IsKind(SyntaxKind.FieldDeclaration)) Then Return True End If Return False Case SyntaxKind.NamespaceStatement, SyntaxKind.NamespaceBlock, SyntaxKind.ModuleStatement, SyntaxKind.ModuleBlock, SyntaxKind.EnumStatement, SyntaxKind.EnumBlock, SyntaxKind.StructureStatement, SyntaxKind.StructureBlock, SyntaxKind.InterfaceStatement, SyntaxKind.InterfaceBlock, SyntaxKind.ClassStatement, SyntaxKind.ClassBlock, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement, SyntaxKind.EventStatement, SyntaxKind.EventBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.FieldDeclaration, SyntaxKind.SubStatement, SyntaxKind.SubBlock, SyntaxKind.FunctionStatement, SyntaxKind.FunctionBlock, SyntaxKind.PropertyStatement, SyntaxKind.PropertyBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.SubNewStatement, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorStatement, SyntaxKind.OperatorBlock Return True End Select Return False End Function ' TypeDeclaration ::= ' ModuleDeclaration | ' NonModuleDeclaration ' NonModuleDeclaration ::= ' EnumDeclaration | ' StructureDeclaration | ' InterfaceDeclaration | ' ClassDeclaration | ' DelegateDeclaration Public Function IsTypeDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeDeclaration Select Case node.Kind() Case SyntaxKind.EnumBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ClassBlock, SyntaxKind.ModuleBlock, SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return True End Select Return False End Function Public Function GetObjectCreationInitializer(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetObjectCreationInitializer Return DirectCast(node, ObjectCreationExpressionSyntax).Initializer End Function Public Function GetObjectCreationType(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetObjectCreationType Return DirectCast(node, ObjectCreationExpressionSyntax).Type End Function Public Function IsSimpleAssignmentStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleAssignmentStatement Return node.IsKind(SyntaxKind.SimpleAssignmentStatement) End Function Public Sub GetPartsOfAssignmentStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentStatement ' VB only has assignment statements, so this can just delegate to that helper GetPartsOfAssignmentExpressionOrStatement(statement, left, operatorToken, right) End Sub Public Sub GetPartsOfAssignmentExpressionOrStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentExpressionOrStatement Dim assignment = DirectCast(statement, AssignmentStatementSyntax) left = assignment.Left operatorToken = assignment.OperatorToken right = assignment.Right End Sub Public Function GetNameOfMemberAccessExpression(memberAccessExpression As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberAccessExpression Return DirectCast(memberAccessExpression, MemberAccessExpressionSyntax).Name End Function Public Function GetIdentifierOfSimpleName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfSimpleName Return DirectCast(node, SimpleNameSyntax).Identifier End Function Public Function GetIdentifierOfVariableDeclarator(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfVariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Names.Last().Identifier End Function Public Function GetIdentifierOfParameter(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfParameter Return DirectCast(node, ParameterSyntax).Identifier.Identifier End Function Public Function GetIdentifierOfTypeDeclaration(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfTypeDeclaration Select Case node.Kind() Case SyntaxKind.EnumStatement, SyntaxKind.StructureStatement, SyntaxKind.InterfaceStatement, SyntaxKind.ClassStatement, SyntaxKind.ModuleStatement Return DirectCast(node, TypeStatementSyntax).Identifier Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return DirectCast(node, DelegateStatementSyntax).Identifier End Select Throw ExceptionUtilities.UnexpectedValue(node) End Function Public Function GetIdentifierOfIdentifierName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfIdentifierName Return DirectCast(node, IdentifierNameSyntax).Identifier End Function Public Function IsLocalFunctionStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLocalFunctionStatement ' VB does not have local functions Return False End Function Public Function IsDeclaratorOfLocalDeclarationStatement(declarator As SyntaxNode, localDeclarationStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaratorOfLocalDeclarationStatement Return DirectCast(localDeclarationStatement, LocalDeclarationStatementSyntax).Declarators. Contains(DirectCast(declarator, VariableDeclaratorSyntax)) End Function Public Function AreEquivalent(token1 As SyntaxToken, token2 As SyntaxToken) As Boolean Implements ISyntaxFacts.AreEquivalent Return SyntaxFactory.AreEquivalent(token1, token2) End Function Public Function AreEquivalent(node1 As SyntaxNode, node2 As SyntaxNode) As Boolean Implements ISyntaxFacts.AreEquivalent Return SyntaxFactory.AreEquivalent(node1, node2) End Function Public Function IsExpressionOfInvocationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfInvocationExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, InvocationExpressionSyntax)?.Expression Is node End Function Public Function IsExpressionOfAwaitExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfAwaitExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, AwaitExpressionSyntax)?.Expression Is node End Function Public Function IsExpressionOfMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfMemberAccessExpression Return node IsNot Nothing AndAlso TryCast(node.Parent, MemberAccessExpressionSyntax)?.Expression Is node End Function Public Function GetExpressionOfAwaitExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfAwaitExpression Return DirectCast(node, AwaitExpressionSyntax).Expression End Function Public Function IsExpressionOfForeach(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfForeach Return node IsNot Nothing AndAlso TryCast(node.Parent, ForEachStatementSyntax)?.Expression Is node End Function Public Function GetExpressionOfExpressionStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfExpressionStatement Return DirectCast(node, ExpressionStatementSyntax).Expression End Function Public Function IsBinaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryExpression Return TypeOf node Is BinaryExpressionSyntax End Function Public Function IsIsExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsExpression Return node.IsKind(SyntaxKind.TypeOfIsExpression) End Function Public Sub GetPartsOfBinaryExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryExpression Dim binaryExpression = DirectCast(node, BinaryExpressionSyntax) left = binaryExpression.Left operatorToken = binaryExpression.OperatorToken right = binaryExpression.Right End Sub Public Sub GetPartsOfConditionalExpression(node As SyntaxNode, ByRef condition As SyntaxNode, ByRef whenTrue As SyntaxNode, ByRef whenFalse As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalExpression Dim conditionalExpression = DirectCast(node, TernaryConditionalExpressionSyntax) condition = conditionalExpression.Condition whenTrue = conditionalExpression.WhenTrue whenFalse = conditionalExpression.WhenFalse End Sub Public Function WalkDownParentheses(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.WalkDownParentheses Return If(TryCast(node, ExpressionSyntax)?.WalkDownParentheses(), node) End Function Public Sub GetPartsOfTupleExpression(Of TArgumentSyntax As SyntaxNode)( node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef arguments As SeparatedSyntaxList(Of TArgumentSyntax), ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfTupleExpression Dim tupleExpr = DirectCast(node, TupleExpressionSyntax) openParen = tupleExpr.OpenParenToken arguments = CType(CType(tupleExpr.Arguments, SeparatedSyntaxList(Of SyntaxNode)), SeparatedSyntaxList(Of TArgumentSyntax)) closeParen = tupleExpr.CloseParenToken End Sub Public Function GetOperandOfPrefixUnaryExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetOperandOfPrefixUnaryExpression Return DirectCast(node, UnaryExpressionSyntax).Operand End Function Public Function GetOperatorTokenOfPrefixUnaryExpression(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetOperatorTokenOfPrefixUnaryExpression Return DirectCast(node, UnaryExpressionSyntax).OperatorToken End Function Public Sub GetPartsOfMemberAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef name As SyntaxNode) Implements ISyntaxFacts.GetPartsOfMemberAccessExpression Dim memberAccess = DirectCast(node, MemberAccessExpressionSyntax) expression = memberAccess.Expression operatorToken = memberAccess.OperatorToken name = memberAccess.Name End Sub Public Function GetNextExecutableStatement(statement As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNextExecutableStatement Return DirectCast(statement, StatementSyntax).GetNextStatement()?.FirstAncestorOrSelf(Of ExecutableStatementSyntax) End Function Private Function ISyntaxFacts_IsSingleLineCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsSingleLineCommentTrivia Return MyBase.IsSingleLineCommentTrivia(trivia) End Function Private Function ISyntaxFacts_IsMultiLineCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsMultiLineCommentTrivia Return MyBase.IsMultiLineCommentTrivia(trivia) End Function Private Function ISyntaxFacts_IsSingleLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsSingleLineDocCommentTrivia Return MyBase.IsSingleLineDocCommentTrivia(trivia) End Function Private Function ISyntaxFacts_IsMultiLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsMultiLineDocCommentTrivia Return MyBase.IsMultiLineDocCommentTrivia(trivia) Return False End Function Private Function ISyntaxFacts_IsShebangDirectiveTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsShebangDirectiveTrivia Return MyBase.IsShebangDirectiveTrivia(trivia) End Function Public Overrides Function IsPreprocessorDirective(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsPreprocessorDirective Return SyntaxFacts.IsPreprocessorDirective(trivia.Kind()) End Function Public Function IsRegularComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsRegularComment Return trivia.Kind = SyntaxKind.CommentTrivia End Function Public Function IsDocumentationComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationComment Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia End Function Public Function IsElastic(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsElastic Return trivia.IsElastic() End Function Public Function IsPragmaDirective(trivia As SyntaxTrivia, ByRef isDisable As Boolean, ByRef isActive As Boolean, ByRef errorCodes As SeparatedSyntaxList(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.IsPragmaDirective Return trivia.IsPragmaDirective(isDisable, isActive, errorCodes) End Function Public Function IsOnTypeHeader( root As SyntaxNode, position As Integer, fullHeader As Boolean, ByRef typeDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnTypeHeader Dim typeBlock = TryGetAncestorForLocation(Of TypeBlockSyntax)(root, position) If typeBlock Is Nothing Then Return Nothing End If Dim typeStatement = typeBlock.BlockStatement typeDeclaration = typeStatement Dim lastToken = If(typeStatement.TypeParameterList?.GetLastToken(), typeStatement.Identifier) If fullHeader Then lastToken = If(typeBlock.Implements.LastOrDefault()?.GetLastToken(), If(typeBlock.Inherits.LastOrDefault()?.GetLastToken(), lastToken)) End If Return IsOnHeader(root, position, typeBlock, lastToken) End Function Public Function IsOnPropertyDeclarationHeader(root As SyntaxNode, position As Integer, ByRef propertyDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnPropertyDeclarationHeader Dim node = TryGetAncestorForLocation(Of PropertyStatementSyntax)(root, position) propertyDeclaration = node If propertyDeclaration Is Nothing Then Return False End If If node.AsClause IsNot Nothing Then Return IsOnHeader(root, position, node, node.AsClause) End If Return IsOnHeader(root, position, node, node.Identifier) End Function Public Function IsOnParameterHeader(root As SyntaxNode, position As Integer, ByRef parameter As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnParameterHeader Dim node = TryGetAncestorForLocation(Of ParameterSyntax)(root, position) parameter = node If parameter Is Nothing Then Return False End If Return IsOnHeader(root, position, node, node) End Function Public Function IsOnMethodHeader(root As SyntaxNode, position As Integer, ByRef method As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnMethodHeader Dim node = TryGetAncestorForLocation(Of MethodStatementSyntax)(root, position) method = node If method Is Nothing Then Return False End If If node.HasReturnType() Then Return IsOnHeader(root, position, method, node.GetReturnType()) End If If node.ParameterList IsNot Nothing Then Return IsOnHeader(root, position, method, node.ParameterList) End If Return IsOnHeader(root, position, node, node) End Function Public Function IsOnLocalFunctionHeader(root As SyntaxNode, position As Integer, ByRef localFunction As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnLocalFunctionHeader ' No local functions in VisualBasic Return False End Function Public Function IsOnLocalDeclarationHeader(root As SyntaxNode, position As Integer, ByRef localDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnLocalDeclarationHeader Dim node = TryGetAncestorForLocation(Of LocalDeclarationStatementSyntax)(root, position) localDeclaration = node If localDeclaration Is Nothing Then Return False End If Dim initializersExpressions = node.Declarators. Where(Function(d) d.Initializer IsNot Nothing). SelectAsArray(Function(initialized) initialized.Initializer.Value) Return IsOnHeader(root, position, node, node, initializersExpressions) End Function Public Function IsOnIfStatementHeader(root As SyntaxNode, position As Integer, ByRef ifStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnIfStatementHeader ifStatement = Nothing Dim multipleLineNode = TryGetAncestorForLocation(Of MultiLineIfBlockSyntax)(root, position) If multipleLineNode IsNot Nothing Then ifStatement = multipleLineNode Return IsOnHeader(root, position, multipleLineNode.IfStatement, multipleLineNode.IfStatement) End If Dim singleLineNode = TryGetAncestorForLocation(Of SingleLineIfStatementSyntax)(root, position) If singleLineNode IsNot Nothing Then ifStatement = singleLineNode Return IsOnHeader(root, position, singleLineNode, singleLineNode.Condition) End If Return False End Function Public Function IsOnWhileStatementHeader(root As SyntaxNode, position As Integer, ByRef whileStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnWhileStatementHeader whileStatement = Nothing Dim whileBlock = TryGetAncestorForLocation(Of WhileBlockSyntax)(root, position) If whileBlock IsNot Nothing Then whileStatement = whileBlock Return IsOnHeader(root, position, whileBlock.WhileStatement, whileBlock.WhileStatement) End If Return False End Function Public Function IsOnForeachHeader(root As SyntaxNode, position As Integer, ByRef foreachStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOnForeachHeader Dim node = TryGetAncestorForLocation(Of ForEachBlockSyntax)(root, position) foreachStatement = node If foreachStatement Is Nothing Then Return False End If Return IsOnHeader(root, position, node, node.ForEachStatement) End Function Public Function IsBetweenTypeMembers(sourceText As SourceText, root As SyntaxNode, position As Integer, ByRef typeDeclaration As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBetweenTypeMembers Dim token = root.FindToken(position) Dim typeDecl = token.GetAncestor(Of TypeBlockSyntax) typeDeclaration = typeDecl If typeDecl IsNot Nothing Then Dim start = If(typeDecl.Implements.LastOrDefault()?.Span.End, If(typeDecl.Inherits.LastOrDefault()?.Span.End, typeDecl.BlockStatement.Span.End)) If position >= start AndAlso position <= typeDecl.EndBlockStatement.Span.Start Then Dim line = sourceText.Lines.GetLineFromPosition(position) If Not line.IsEmptyOrWhitespace() Then Return False End If Dim member = typeDecl.Members.FirstOrDefault(Function(d) d.FullSpan.Contains(position)) If member Is Nothing Then ' There are no members, Or we're after the last member. Return True Else ' We're within a member. Make sure we're in the leading whitespace of ' the member. If position < member.SpanStart Then For Each trivia In member.GetLeadingTrivia() If Not trivia.IsWhitespaceOrEndOfLine() Then Return False End If If trivia.FullSpan.Contains(position) Then Return True End If Next End If End If End If End If Return False End Function Protected Overrides Function ContainsInterleavedDirective(span As TextSpan, token As SyntaxToken, cancellationToken As CancellationToken) As Boolean Return token.ContainsInterleavedDirective(span, cancellationToken) End Function Private Function ISyntaxFacts_ContainsInterleavedDirective(node As SyntaxNode, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective Return ContainsInterleavedDirective(node, cancellationToken) End Function Private Function ISyntaxFacts_ContainsInterleavedDirective1(nodes As ImmutableArray(Of SyntaxNode), cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective Return ContainsInterleavedDirective(nodes, cancellationToken) End Function Public Function IsDocumentationCommentExteriorTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationCommentExteriorTrivia Return trivia.Kind() = SyntaxKind.DocumentationCommentExteriorTrivia End Function Public Function GetModifiers(node As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifiers Return node.GetModifiers() End Function Public Function WithModifiers(node As SyntaxNode, modifiers As SyntaxTokenList) As SyntaxNode Implements ISyntaxFacts.WithModifiers Return node.WithModifiers(modifiers) End Function Public Function IsLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLiteralExpression Return TypeOf node Is LiteralExpressionSyntax End Function Public Function GetVariablesOfLocalDeclarationStatement(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetVariablesOfLocalDeclarationStatement Return DirectCast(node, LocalDeclarationStatementSyntax).Declarators End Function Public Function GetInitializerOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetInitializerOfVariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Initializer End Function Public Function GetTypeOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfVariableDeclarator Dim declarator = DirectCast(node, VariableDeclaratorSyntax) Return TryCast(declarator.AsClause, SimpleAsClauseSyntax)?.Type End Function Public Function GetValueOfEqualsValueClause(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetValueOfEqualsValueClause Return DirectCast(node, EqualsValueSyntax).Value End Function Public Function IsScopeBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsScopeBlock ' VB has no equivalent of curly braces. Return False End Function Public Function IsExecutableBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableBlock Return node.IsExecutableBlock() End Function Public Function GetExecutableBlockStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetExecutableBlockStatements Return node.GetExecutableBlockStatements() End Function Public Function FindInnermostCommonExecutableBlock(nodes As IEnumerable(Of SyntaxNode)) As SyntaxNode Implements ISyntaxFacts.FindInnermostCommonExecutableBlock Return nodes.FindInnermostCommonExecutableBlock() End Function Public Function IsStatementContainer(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatementContainer Return IsExecutableBlock(node) End Function Public Function GetStatementContainerStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetStatementContainerStatements Return GetExecutableBlockStatements(node) End Function Public Function IsConversionExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConversionExpression Return node.Kind = SyntaxKind.CTypeExpression End Function Public Function IsCastExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsCastExpression Return node.Kind = SyntaxKind.DirectCastExpression End Function Public Sub GetPartsOfCastExpression(node As SyntaxNode, ByRef type As SyntaxNode, ByRef expression As SyntaxNode) Implements ISyntaxFacts.GetPartsOfCastExpression Dim cast = DirectCast(node, DirectCastExpressionSyntax) type = cast.Type expression = cast.Expression End Sub Public Function GetDeconstructionReferenceLocation(node As SyntaxNode) As Location Implements ISyntaxFacts.GetDeconstructionReferenceLocation Throw New NotImplementedException() End Function Public Function GetDeclarationIdentifierIfOverride(token As SyntaxToken) As SyntaxToken? Implements ISyntaxFacts.GetDeclarationIdentifierIfOverride If token.Kind() = SyntaxKind.OverridesKeyword Then Dim parent = token.Parent Select Case parent.Kind() Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Dim method = DirectCast(parent, MethodStatementSyntax) Return method.Identifier Case SyntaxKind.PropertyStatement Dim [property] = DirectCast(parent, PropertyStatementSyntax) Return [property].Identifier End Select End If Return Nothing End Function Public Shadows Function SpansPreprocessorDirective(nodes As IEnumerable(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.SpansPreprocessorDirective Return MyBase.SpansPreprocessorDirective(nodes) End Function Public Shadows Function SpansPreprocessorDirective(tokens As IEnumerable(Of SyntaxToken)) As Boolean Return MyBase.SpansPreprocessorDirective(tokens) End Function Public Sub GetPartsOfInvocationExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfInvocationExpression Dim invocation = DirectCast(node, InvocationExpressionSyntax) expression = invocation.Expression argumentList = invocation.ArgumentList End Sub Public Function IsPostfixUnaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPostfixUnaryExpression ' Does not exist in VB. Return False End Function Public Function IsMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberBindingExpression ' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target. Return False End Function Public Function IsNameOfMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfMemberBindingExpression ' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target. Return False End Function Public Overrides Function GetAttributeLists(node As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetAttributeLists Return node.GetAttributeLists() End Function Public Function IsUsingAliasDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingAliasDirective Dim importStatement = TryCast(node, ImportsStatementSyntax) If (importStatement IsNot Nothing) Then For Each importsClause In importStatement.ImportsClauses If importsClause.Kind = SyntaxKind.SimpleImportsClause Then Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax) If simpleImportsClause.Alias IsNot Nothing Then Return True End If End If Next End If Return False End Function Public Sub GetPartsOfUsingAliasDirective( node As SyntaxNode, ByRef globalKeyword As SyntaxToken, ByRef [alias] As SyntaxToken, ByRef name As SyntaxNode) Implements ISyntaxFacts.GetPartsOfUsingAliasDirective Dim importStatement = DirectCast(node, ImportsStatementSyntax) For Each importsClause In importStatement.ImportsClauses If importsClause.Kind = SyntaxKind.SimpleImportsClause Then Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax) If simpleImportsClause.Alias IsNot Nothing Then globalKeyword = Nothing [alias] = simpleImportsClause.Alias.Identifier name = simpleImportsClause.Name Return End If End If Next Throw ExceptionUtilities.Unreachable End Sub Public Overrides Function IsParameterNameXmlElementSyntax(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterNameXmlElementSyntax Dim xmlElement = TryCast(node, XmlElementSyntax) If xmlElement IsNot Nothing Then Dim name = TryCast(xmlElement.StartTag.Name, XmlNameSyntax) Return name?.LocalName.ValueText = DocumentationCommentXmlNames.ParameterElementName End If Return False End Function Public Overrides Function GetContentFromDocumentationCommentTriviaSyntax(trivia As SyntaxTrivia) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentFromDocumentationCommentTriviaSyntax Dim documentationCommentTrivia = TryCast(trivia.GetStructure(), DocumentationCommentTriviaSyntax) If documentationCommentTrivia IsNot Nothing Then Return documentationCommentTrivia.Content End If Return Nothing End Function Public Overrides Function CanHaveAccessibility(declaration As SyntaxNode) As Boolean Implements ISyntaxFacts.CanHaveAccessibility Select Case declaration.Kind Case SyntaxKind.ClassBlock, SyntaxKind.ClassStatement, SyntaxKind.StructureBlock, SyntaxKind.StructureStatement, SyntaxKind.InterfaceBlock, SyntaxKind.InterfaceStatement, SyntaxKind.EnumBlock, SyntaxKind.EnumStatement, SyntaxKind.ModuleBlock, SyntaxKind.ModuleStatement, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement, SyntaxKind.FieldDeclaration, SyntaxKind.FunctionBlock, SyntaxKind.SubBlock, SyntaxKind.FunctionStatement, SyntaxKind.SubStatement, SyntaxKind.PropertyBlock, SyntaxKind.PropertyStatement, SyntaxKind.OperatorBlock, SyntaxKind.OperatorStatement, SyntaxKind.EventBlock, SyntaxKind.EventStatement, SyntaxKind.GetAccessorBlock, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorBlock, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorBlock, SyntaxKind.RaiseEventAccessorStatement Return True Case SyntaxKind.ConstructorBlock, SyntaxKind.SubNewStatement ' Shared constructor cannot have modifiers in VB. ' Module constructors are implicitly Shared and can't have accessibility modifier. Return Not declaration.GetModifiers().Any(SyntaxKind.SharedKeyword) AndAlso Not declaration.Parent.IsKind(SyntaxKind.ModuleBlock) Case SyntaxKind.ModifiedIdentifier Return If(IsChildOf(declaration, SyntaxKind.VariableDeclarator), CanHaveAccessibility(declaration.Parent), False) Case SyntaxKind.VariableDeclarator Return If(IsChildOfVariableDeclaration(declaration), CanHaveAccessibility(declaration.Parent), False) Case Else Return False End Select End Function Friend Shared Function IsChildOf(node As SyntaxNode, kind As SyntaxKind) As Boolean Return node.Parent IsNot Nothing AndAlso node.Parent.IsKind(kind) End Function Friend Shared Function IsChildOfVariableDeclaration(node As SyntaxNode) As Boolean Return IsChildOf(node, SyntaxKind.FieldDeclaration) OrElse IsChildOf(node, SyntaxKind.LocalDeclarationStatement) End Function Public Overrides Function GetAccessibility(declaration As SyntaxNode) As Accessibility Implements ISyntaxFacts.GetAccessibility If Not CanHaveAccessibility(declaration) Then Return Accessibility.NotApplicable End If Dim tokens = GetModifierTokens(declaration) Dim acc As Accessibility Dim mods As DeclarationModifiers Dim isDefault As Boolean GetAccessibilityAndModifiers(tokens, acc, mods, isDefault) Return acc End Function Public Overrides Function GetModifierTokens(declaration As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifierTokens Select Case declaration.Kind Case SyntaxKind.ClassBlock Return DirectCast(declaration, ClassBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.ClassStatement Return DirectCast(declaration, ClassStatementSyntax).Modifiers Case SyntaxKind.StructureBlock Return DirectCast(declaration, StructureBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.StructureStatement Return DirectCast(declaration, StructureStatementSyntax).Modifiers Case SyntaxKind.InterfaceBlock Return DirectCast(declaration, InterfaceBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.InterfaceStatement Return DirectCast(declaration, InterfaceStatementSyntax).Modifiers Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).EnumStatement.Modifiers Case SyntaxKind.EnumStatement Return DirectCast(declaration, EnumStatementSyntax).Modifiers Case SyntaxKind.ModuleBlock Return DirectCast(declaration, ModuleBlockSyntax).ModuleStatement.Modifiers Case SyntaxKind.ModuleStatement Return DirectCast(declaration, ModuleStatementSyntax).Modifiers Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(declaration, DelegateStatementSyntax).Modifiers Case SyntaxKind.FieldDeclaration Return DirectCast(declaration, FieldDeclarationSyntax).Modifiers Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DirectCast(declaration, MethodBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.ConstructorBlock Return DirectCast(declaration, ConstructorBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Return DirectCast(declaration, MethodStatementSyntax).Modifiers Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(declaration, MultiLineLambdaExpressionSyntax).SubOrFunctionHeader.Modifiers Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return DirectCast(declaration, SingleLineLambdaExpressionSyntax).SubOrFunctionHeader.Modifiers Case SyntaxKind.SubNewStatement Return DirectCast(declaration, SubNewStatementSyntax).Modifiers Case SyntaxKind.PropertyBlock Return DirectCast(declaration, PropertyBlockSyntax).PropertyStatement.Modifiers Case SyntaxKind.PropertyStatement Return DirectCast(declaration, PropertyStatementSyntax).Modifiers Case SyntaxKind.OperatorBlock Return DirectCast(declaration, OperatorBlockSyntax).BlockStatement.Modifiers Case SyntaxKind.OperatorStatement Return DirectCast(declaration, OperatorStatementSyntax).Modifiers Case SyntaxKind.EventBlock Return DirectCast(declaration, EventBlockSyntax).EventStatement.Modifiers Case SyntaxKind.EventStatement Return DirectCast(declaration, EventStatementSyntax).Modifiers Case SyntaxKind.ModifiedIdentifier If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then Return GetModifierTokens(declaration.Parent) End If Case SyntaxKind.LocalDeclarationStatement Return DirectCast(declaration, LocalDeclarationStatementSyntax).Modifiers Case SyntaxKind.VariableDeclarator If IsChildOfVariableDeclaration(declaration) Then Return GetModifierTokens(declaration.Parent) End If Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return GetModifierTokens(DirectCast(declaration, AccessorBlockSyntax).AccessorStatement) Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return DirectCast(declaration, AccessorStatementSyntax).Modifiers Case Else Return Nothing End Select End Function Public Overrides Sub GetAccessibilityAndModifiers(modifierTokens As SyntaxTokenList, ByRef accessibility As Accessibility, ByRef modifiers As DeclarationModifiers, ByRef isDefault As Boolean) Implements ISyntaxFacts.GetAccessibilityAndModifiers accessibility = Accessibility.NotApplicable modifiers = DeclarationModifiers.None isDefault = False For Each token In modifierTokens Select Case token.Kind Case SyntaxKind.DefaultKeyword isDefault = True Case SyntaxKind.PublicKeyword accessibility = Accessibility.Public Case SyntaxKind.PrivateKeyword If accessibility = Accessibility.Protected Then accessibility = Accessibility.ProtectedAndFriend Else accessibility = Accessibility.Private End If Case SyntaxKind.FriendKeyword If accessibility = Accessibility.Protected Then accessibility = Accessibility.ProtectedOrFriend Else accessibility = Accessibility.Friend End If Case SyntaxKind.ProtectedKeyword If accessibility = Accessibility.Friend Then accessibility = Accessibility.ProtectedOrFriend ElseIf accessibility = Accessibility.Private Then accessibility = Accessibility.ProtectedAndFriend Else accessibility = Accessibility.Protected End If Case SyntaxKind.MustInheritKeyword, SyntaxKind.MustOverrideKeyword modifiers = modifiers Or DeclarationModifiers.Abstract Case SyntaxKind.ShadowsKeyword modifiers = modifiers Or DeclarationModifiers.[New] Case SyntaxKind.OverridesKeyword modifiers = modifiers Or DeclarationModifiers.Override Case SyntaxKind.OverridableKeyword modifiers = modifiers Or DeclarationModifiers.Virtual Case SyntaxKind.SharedKeyword modifiers = modifiers Or DeclarationModifiers.Static Case SyntaxKind.AsyncKeyword modifiers = modifiers Or DeclarationModifiers.Async Case SyntaxKind.ConstKeyword modifiers = modifiers Or DeclarationModifiers.Const Case SyntaxKind.ReadOnlyKeyword modifiers = modifiers Or DeclarationModifiers.ReadOnly Case SyntaxKind.WriteOnlyKeyword modifiers = modifiers Or DeclarationModifiers.WriteOnly Case SyntaxKind.NotInheritableKeyword, SyntaxKind.NotOverridableKeyword modifiers = modifiers Or DeclarationModifiers.Sealed Case SyntaxKind.WithEventsKeyword modifiers = modifiers Or DeclarationModifiers.WithEvents Case SyntaxKind.PartialKeyword modifiers = modifiers Or DeclarationModifiers.Partial End Select Next End Sub Public Overrides Function GetDeclarationKind(declaration As SyntaxNode) As DeclarationKind Implements ISyntaxFacts.GetDeclarationKind Select Case declaration.Kind Case SyntaxKind.CompilationUnit Return DeclarationKind.CompilationUnit Case SyntaxKind.NamespaceBlock Return DeclarationKind.Namespace Case SyntaxKind.ImportsStatement Return DeclarationKind.NamespaceImport Case SyntaxKind.ClassBlock Return DeclarationKind.Class Case SyntaxKind.StructureBlock Return DeclarationKind.Struct Case SyntaxKind.InterfaceBlock Return DeclarationKind.Interface Case SyntaxKind.EnumBlock Return DeclarationKind.Enum Case SyntaxKind.EnumMemberDeclaration Return DeclarationKind.EnumMember Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DeclarationKind.Delegate Case SyntaxKind.FunctionBlock, SyntaxKind.SubBlock Return DeclarationKind.Method Case SyntaxKind.FunctionStatement If Not IsChildOf(declaration, SyntaxKind.FunctionBlock) Then Return DeclarationKind.Method End If Case SyntaxKind.SubStatement If Not IsChildOf(declaration, SyntaxKind.SubBlock) Then Return DeclarationKind.Method End If Case SyntaxKind.ConstructorBlock Return DeclarationKind.Constructor Case SyntaxKind.PropertyBlock If IsIndexer(declaration) Then Return DeclarationKind.Indexer Else Return DeclarationKind.Property End If Case SyntaxKind.PropertyStatement If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then If IsIndexer(declaration) Then Return DeclarationKind.Indexer Else Return DeclarationKind.Property End If End If Case SyntaxKind.OperatorBlock Return DeclarationKind.Operator Case SyntaxKind.OperatorStatement If Not IsChildOf(declaration, SyntaxKind.OperatorBlock) Then Return DeclarationKind.Operator End If Case SyntaxKind.EventBlock Return DeclarationKind.CustomEvent Case SyntaxKind.EventStatement If Not IsChildOf(declaration, SyntaxKind.EventBlock) Then Return DeclarationKind.Event End If Case SyntaxKind.Parameter Return DeclarationKind.Parameter Case SyntaxKind.FieldDeclaration Return DeclarationKind.Field Case SyntaxKind.LocalDeclarationStatement If GetDeclarationCount(declaration) = 1 Then Return DeclarationKind.Variable End If Case SyntaxKind.ModifiedIdentifier If IsChildOf(declaration, SyntaxKind.VariableDeclarator) Then If IsChildOf(declaration.Parent, SyntaxKind.FieldDeclaration) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then Return DeclarationKind.Field ElseIf IsChildOf(declaration.Parent, SyntaxKind.LocalDeclarationStatement) And GetDeclarationCount(declaration.Parent.Parent) > 1 Then Return DeclarationKind.Variable End If End If Case SyntaxKind.Attribute Dim list = TryCast(declaration.Parent, AttributeListSyntax) If list Is Nothing OrElse list.Attributes.Count > 1 Then Return DeclarationKind.Attribute End If Case SyntaxKind.AttributeList Dim list = DirectCast(declaration, AttributeListSyntax) If list.Attributes.Count = 1 Then Return DeclarationKind.Attribute End If Case SyntaxKind.GetAccessorBlock Return DeclarationKind.GetAccessor Case SyntaxKind.SetAccessorBlock Return DeclarationKind.SetAccessor Case SyntaxKind.AddHandlerAccessorBlock Return DeclarationKind.AddAccessor Case SyntaxKind.RemoveHandlerAccessorBlock Return DeclarationKind.RemoveAccessor Case SyntaxKind.RaiseEventAccessorBlock Return DeclarationKind.RaiseAccessor End Select Return DeclarationKind.None End Function Private Shared Function GetDeclarationCount(nodes As IReadOnlyList(Of SyntaxNode)) As Integer Dim count As Integer = 0 For i = 0 To nodes.Count - 1 count = count + GetDeclarationCount(nodes(i)) Next Return count End Function Friend Shared Function GetDeclarationCount(node As SyntaxNode) As Integer Select Case node.Kind Case SyntaxKind.FieldDeclaration Return GetDeclarationCount(DirectCast(node, FieldDeclarationSyntax).Declarators) Case SyntaxKind.LocalDeclarationStatement Return GetDeclarationCount(DirectCast(node, LocalDeclarationStatementSyntax).Declarators) Case SyntaxKind.VariableDeclarator Return DirectCast(node, VariableDeclaratorSyntax).Names.Count Case SyntaxKind.AttributesStatement Return GetDeclarationCount(DirectCast(node, AttributesStatementSyntax).AttributeLists) Case SyntaxKind.AttributeList Return DirectCast(node, AttributeListSyntax).Attributes.Count Case SyntaxKind.ImportsStatement Return DirectCast(node, ImportsStatementSyntax).ImportsClauses.Count End Select Return 1 End Function Private Shared Function IsIndexer(declaration As SyntaxNode) As Boolean Select Case declaration.Kind Case SyntaxKind.PropertyBlock Dim p = DirectCast(declaration, PropertyBlockSyntax).PropertyStatement Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword) Case SyntaxKind.PropertyStatement If Not IsChildOf(declaration, SyntaxKind.PropertyBlock) Then Dim p = DirectCast(declaration, PropertyStatementSyntax) Return p.ParameterList IsNot Nothing AndAlso p.ParameterList.Parameters.Count > 0 AndAlso p.Modifiers.Any(SyntaxKind.DefaultKeyword) End If End Select Return False End Function Public Function IsImplicitObjectCreation(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsImplicitObjectCreation Return False End Function Public Function SupportsNotPattern(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsNotPattern Return False End Function Public Function IsIsPatternExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsPatternExpression Return False End Function Public Function IsAnyPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnyPattern Return False End Function Public Function IsAndPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAndPattern Return False End Function Public Function IsBinaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryPattern Return False End Function Public Function IsConstantPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConstantPattern Return False End Function Public Function IsDeclarationPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationPattern Return False End Function Public Function IsNotPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNotPattern Return False End Function Public Function IsOrPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOrPattern Return False End Function Public Function IsParenthesizedPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParenthesizedPattern Return False End Function Public Function IsRecursivePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRecursivePattern Return False End Function Public Function IsUnaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnaryPattern Return False End Function Public Function IsTypePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypePattern Return False End Function Public Function IsVarPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVarPattern Return False End Function Public Sub GetPartsOfIsPatternExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef isToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfIsPatternExpression Throw ExceptionUtilities.Unreachable End Sub Public Function GetExpressionOfConstantPattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfConstantPattern Throw ExceptionUtilities.Unreachable End Function Public Sub GetPartsOfParenthesizedPattern(node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef pattern As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfBinaryPattern(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfUnaryPattern(node As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef pattern As SyntaxNode) Implements ISyntaxFacts.GetPartsOfUnaryPattern Throw ExceptionUtilities.Unreachable End Sub Public Sub GetPartsOfDeclarationPattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfDeclarationPattern Throw New NotImplementedException() End Sub Public Sub GetPartsOfRecursivePattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef positionalPart As SyntaxNode, ByRef propertyPart As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfRecursivePattern Throw New NotImplementedException() End Sub Public Function GetTypeOfTypePattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfTypePattern Throw New NotImplementedException() End Function Public Function GetExpressionOfThrowExpression(throwExpression As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfThrowExpression ' ThrowExpression doesn't exist in VB Throw New NotImplementedException() End Function Public Function IsThrowStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsThrowStatement Return node.IsKind(SyntaxKind.ThrowStatement) End Function Public Function IsLocalFunction(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLocalFunction Return False End Function Public Sub GetPartsOfInterpolationExpression(node As SyntaxNode, ByRef stringStartToken As SyntaxToken, ByRef contents As SyntaxList(Of SyntaxNode), ByRef stringEndToken As SyntaxToken) Implements ISyntaxFacts.GetPartsOfInterpolationExpression Dim interpolatedStringExpressionSyntax As InterpolatedStringExpressionSyntax = DirectCast(node, InterpolatedStringExpressionSyntax) stringStartToken = interpolatedStringExpressionSyntax.DollarSignDoubleQuoteToken contents = interpolatedStringExpressionSyntax.Contents stringEndToken = interpolatedStringExpressionSyntax.DoubleQuoteToken End Sub Public Function IsVerbatimInterpolatedStringExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVerbatimInterpolatedStringExpression Return False End Function End Class End Namespace
1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/SyntaxFactsService/ISyntaxFactsService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.LanguageServices { internal interface ISyntaxFactsService : ISyntaxFacts, ILanguageService { bool IsInInactiveRegion(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken); bool IsInNonUserCode(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken); bool IsPossibleTupleContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken); Task<ImmutableArray<SyntaxNode>> GetSelectedFieldsAndPropertiesAsync(SyntaxTree syntaxTree, TextSpan textSpan, bool allowPartialSelection, CancellationToken cancellationToken); // Walks the tree, starting from contextNode, looking for the first construct // with a missing close brace. If found, the close brace will be added and the // updates root will be returned. The context node in that new tree will also // be returned. // TODO: This method should be moved out of ISyntaxFactsService. void AddFirstMissingCloseBrace<TContextNode>( SyntaxNode root, TContextNode contextNode, out SyntaxNode newRoot, out TContextNode newContextNode) where TContextNode : SyntaxNode; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.LanguageServices { internal interface ISyntaxFactsService : ISyntaxFacts, ILanguageService { bool IsInInactiveRegion(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken); bool IsInNonUserCode(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken); // Violation. This is feature level code. bool IsPossibleTupleContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken); // Violation. This is feature level code. Task<ImmutableArray<SyntaxNode>> GetSelectedFieldsAndPropertiesAsync(SyntaxTree syntaxTree, TextSpan textSpan, bool allowPartialSelection, CancellationToken cancellationToken); // Walks the tree, starting from contextNode, looking for the first construct // with a missing close brace. If found, the close brace will be added and the // updates root will be returned. The context node in that new tree will also // be returned. // Violation. This is feature level code. void AddFirstMissingCloseBrace<TContextNode>( SyntaxNode root, TContextNode contextNode, out SyntaxNode newRoot, out TContextNode newContextNode) where TContextNode : SyntaxNode; } }
1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Compilers/Core/Portable/CodeGen/ArrayMembers.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.PooledObjects; using Roslyn.Utilities; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; // Contains support for pseudo-methods on multidimensional arrays. // // Opcodes such as newarr, ldelem, ldelema, stelem do not work with // multidimensional arrays and same functionality is available in // a form of well known pseudo-methods "Get", "Set", "Address" and ".ctor" // //========================= // // 14.2 Arrays (From partition II) - //The class that the VES creates for arrays contains several methods whose implementation is supplied by the //VES: // //* A constructor that takes a sequence of int32 arguments, one for each dimension of the array, that specify //the number of elements in each dimension beginning with the first dimension. A lower bound of zero is //assumed. // //* A constructor that takes twice as many int32 arguments as there are dimensions of the array. These //arguments occur in pairs—one pair per dimension—with the first argument of each pair specifying the //lower bound for that dimension, and the second argument specifying the total number of elements in that //dimension. Note that vectors are not created with this constructor, since a zero lower bound is assumed for //vectors. // //* A Get method that takes a sequence of int32 arguments, one for each dimension of the array, and returns //a value whose type is the element type of the array. This method is used to access a specific element of the //array where the arguments specify the index into each dimension, beginning with the first, of the element //to be returned. // //* A Set method that takes a sequence of int32 arguments, one for each dimension of the array, followed by //a value whose type is the element type of the array. The return type of Set is void. This method is used to //set a specific element of the array where the arguments specify the index into each dimension, beginning //with the first, of the element to be set and the final argument specifies the value to be stored into the target //element. // //* An Address method that takes a sequence of int32 arguments, one for each dimension of the array, and //has a return type that is a managed pointer to the array's element type. This method is used to return a //managed pointer to a specific element of the array where the arguments specify the index into each //dimension, beginning with the first, of the element whose address is to be returned. namespace Microsoft.CodeAnalysis.CodeGen { /// <summary> /// Constructs and caches already created pseudo-methods. /// Every compiled module is supposed to have one of this, created lazily /// (multidimensional arrays are not common). /// </summary> internal class ArrayMethods { // There are four kinds of array pseudo-methods // They are specific to a given array type private enum ArrayMethodKind : byte { GET, SET, ADDRESS, CTOR, } /// <summary> /// Acquires an array constructor for a given array type /// </summary> public ArrayMethod GetArrayConstructor(Cci.IArrayTypeReference arrayType) { return GetArrayMethod(arrayType, ArrayMethodKind.CTOR); } /// <summary> /// Acquires an element getter method for a given array type /// </summary> public ArrayMethod GetArrayGet(Cci.IArrayTypeReference arrayType) => GetArrayMethod(arrayType, ArrayMethodKind.GET); /// <summary> /// Acquires an element setter method for a given array type /// </summary> public ArrayMethod GetArraySet(Cci.IArrayTypeReference arrayType) => GetArrayMethod(arrayType, ArrayMethodKind.SET); /// <summary> /// Acquires an element referencer method for a given array type /// </summary> public ArrayMethod GetArrayAddress(Cci.IArrayTypeReference arrayType) => GetArrayMethod(arrayType, ArrayMethodKind.ADDRESS); /// <summary> /// Maps {array type, method kind} tuples to implementing pseudo-methods. /// </summary> private readonly ConcurrentDictionary<(byte methodKind, IReferenceOrISignature arrayType), ArrayMethod> _dict = new ConcurrentDictionary<(byte, IReferenceOrISignature), ArrayMethod>(); /// <summary> /// lazily fetches or creates a new array method. /// </summary> private ArrayMethod GetArrayMethod(Cci.IArrayTypeReference arrayType, ArrayMethodKind id) { var key = ((byte)id, new IReferenceOrISignature(arrayType)); ArrayMethod? result; var dict = _dict; if (!dict.TryGetValue(key, out result)) { result = MakeArrayMethod(arrayType, id); result = dict.GetOrAdd(key, result); } return result; } private static ArrayMethod MakeArrayMethod(Cci.IArrayTypeReference arrayType, ArrayMethodKind id) { switch (id) { case ArrayMethodKind.CTOR: return new ArrayConstructor(arrayType); case ArrayMethodKind.GET: return new ArrayGet(arrayType); case ArrayMethodKind.SET: return new ArraySet(arrayType); case ArrayMethodKind.ADDRESS: return new ArrayAddress(arrayType); } throw ExceptionUtilities.UnexpectedValue(id); } /// <summary> /// "newobj ArrayConstructor" is equivalent of "newarr ElementType" /// when working with multidimensional arrays /// </summary> private sealed class ArrayConstructor : ArrayMethod { public ArrayConstructor(Cci.IArrayTypeReference arrayType) : base(arrayType) { } public override string Name => ".ctor"; public override Cci.ITypeReference GetType(EmitContext context) => context.Module.GetPlatformType(Cci.PlatformType.SystemVoid, context); } /// <summary> /// "call ArrayGet" is equivalent of "ldelem ElementType" /// when working with multidimensional arrays /// </summary> private sealed class ArrayGet : ArrayMethod { public ArrayGet(Cci.IArrayTypeReference arrayType) : base(arrayType) { } public override string Name => "Get"; public override Cci.ITypeReference GetType(EmitContext context) => arrayType.GetElementType(context); } /// <summary> /// "call ArrayAddress" is equivalent of "ldelema ElementType" /// when working with multidimensional arrays /// </summary> private sealed class ArrayAddress : ArrayMethod { public ArrayAddress(Cci.IArrayTypeReference arrayType) : base(arrayType) { } public override bool ReturnValueIsByRef => true; public override Cci.ITypeReference GetType(EmitContext context) => arrayType.GetElementType(context); public override string Name => "Address"; } /// <summary> /// "call ArraySet" is equivalent of "stelem ElementType" /// when working with multidimensional arrays /// </summary> private sealed class ArraySet : ArrayMethod { public ArraySet(Cci.IArrayTypeReference arrayType) : base(arrayType) { } public override string Name => "Set"; public override Cci.ITypeReference GetType(EmitContext context) => context.Module.GetPlatformType(Cci.PlatformType.SystemVoid, context); protected override ImmutableArray<ArrayMethodParameterInfo> MakeParameters() { int rank = (int)arrayType.Rank; var parameters = ArrayBuilder<ArrayMethodParameterInfo>.GetInstance(rank + 1); for (int i = 0; i < rank; i++) { parameters.Add(ArrayMethodParameterInfo.GetIndexParameter((ushort)i)); } parameters.Add(new ArraySetValueParameterInfo((ushort)rank, arrayType)); return parameters.ToImmutableAndFree(); } } } /// <summary> /// Represents a parameter in an array pseudo-method. /// /// NOTE: It appears that only number of indices is used for verification, /// types just have to be Int32. /// Even though actual arguments can be native ints. /// </summary> internal class ArrayMethodParameterInfo : Cci.IParameterTypeInformation { // position in the signature private readonly ushort _index; // cache common parameter instances // (we can do this since the only data we have is the index) private static readonly ArrayMethodParameterInfo s_index0 = new ArrayMethodParameterInfo(0); private static readonly ArrayMethodParameterInfo s_index1 = new ArrayMethodParameterInfo(1); private static readonly ArrayMethodParameterInfo s_index2 = new ArrayMethodParameterInfo(2); private static readonly ArrayMethodParameterInfo s_index3 = new ArrayMethodParameterInfo(3); protected ArrayMethodParameterInfo(ushort index) { _index = index; } public static ArrayMethodParameterInfo GetIndexParameter(ushort index) { switch (index) { case 0: return s_index0; case 1: return s_index1; case 2: return s_index2; case 3: return s_index3; } return new ArrayMethodParameterInfo(index); } public ImmutableArray<Cci.ICustomModifier> RefCustomModifiers => ImmutableArray<Cci.ICustomModifier>.Empty; public ImmutableArray<Cci.ICustomModifier> CustomModifiers => ImmutableArray<Cci.ICustomModifier>.Empty; public bool IsByReference => false; public virtual Cci.ITypeReference GetType(EmitContext context) => context.Module.GetPlatformType(Cci.PlatformType.SystemInt32, context); public ushort Index => _index; } /// <summary> /// Represents the "value" parameter of the Set pseudo-method. /// /// NOTE: unlike index parameters, type of the value parameter must match /// the actual element type. /// </summary> internal sealed class ArraySetValueParameterInfo : ArrayMethodParameterInfo { private readonly Cci.IArrayTypeReference _arrayType; internal ArraySetValueParameterInfo(ushort index, Cci.IArrayTypeReference arrayType) : base(index) { _arrayType = arrayType; } public override Cci.ITypeReference GetType(EmitContext context) => _arrayType.GetElementType(context); } /// <summary> /// Base of all array methods. They have a lot in common. /// </summary> internal abstract class ArrayMethod : Cci.IMethodReference { private readonly ImmutableArray<ArrayMethodParameterInfo> _parameters; protected readonly Cci.IArrayTypeReference arrayType; protected ArrayMethod(Cci.IArrayTypeReference arrayType) { this.arrayType = arrayType; _parameters = MakeParameters(); } public abstract string Name { get; } public abstract Cci.ITypeReference GetType(EmitContext context); // Address overrides this to "true" public virtual bool ReturnValueIsByRef => false; // Set overrides this to include "value" parameter. protected virtual ImmutableArray<ArrayMethodParameterInfo> MakeParameters() { int rank = (int)arrayType.Rank; var parameters = ArrayBuilder<ArrayMethodParameterInfo>.GetInstance(rank); for (int i = 0; i < rank; i++) { parameters.Add(ArrayMethodParameterInfo.GetIndexParameter((ushort)i)); } return parameters.ToImmutableAndFree(); } public ImmutableArray<Cci.IParameterTypeInformation> GetParameters(EmitContext context) => StaticCast<Cci.IParameterTypeInformation>.From(_parameters); public bool AcceptsExtraArguments => false; public ushort GenericParameterCount => 0; public bool IsGeneric => false; public Cci.IMethodDefinition? GetResolvedMethod(EmitContext context) => null; public ImmutableArray<Cci.IParameterTypeInformation> ExtraParameters => ImmutableArray<Cci.IParameterTypeInformation>.Empty; public Cci.IGenericMethodInstanceReference? AsGenericMethodInstanceReference => null; public Cci.ISpecializedMethodReference? AsSpecializedMethodReference => null; public Cci.CallingConvention CallingConvention => Cci.CallingConvention.HasThis; public ushort ParameterCount => (ushort)_parameters.Length; public ImmutableArray<Cci.ICustomModifier> RefCustomModifiers => ImmutableArray<Cci.ICustomModifier>.Empty; public ImmutableArray<Cci.ICustomModifier> ReturnValueCustomModifiers => ImmutableArray<Cci.ICustomModifier>.Empty; public Cci.ITypeReference GetContainingType(EmitContext context) { // We are not translating arrayType. // It is an array type and it is never generic or contained in a generic. return this.arrayType; } public IEnumerable<Cci.ICustomAttribute> GetAttributes(EmitContext context) => SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>(); public void Dispatch(Cci.MetadataVisitor visitor) => visitor.Visit(this); public Cci.IDefinition? AsDefinition(EmitContext context) => null; public override string ToString() => ((object?)arrayType.GetInternalSymbol() ?? arrayType).ToString() + "." + Name; Symbols.ISymbolInternal? Cci.IReference.GetInternalSymbol() => null; public sealed override bool Equals(object? obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; // Contains support for pseudo-methods on multidimensional arrays. // // Opcodes such as newarr, ldelem, ldelema, stelem do not work with // multidimensional arrays and same functionality is available in // a form of well known pseudo-methods "Get", "Set", "Address" and ".ctor" // //========================= // // 14.2 Arrays (From partition II) - //The class that the VES creates for arrays contains several methods whose implementation is supplied by the //VES: // //* A constructor that takes a sequence of int32 arguments, one for each dimension of the array, that specify //the number of elements in each dimension beginning with the first dimension. A lower bound of zero is //assumed. // //* A constructor that takes twice as many int32 arguments as there are dimensions of the array. These //arguments occur in pairs—one pair per dimension—with the first argument of each pair specifying the //lower bound for that dimension, and the second argument specifying the total number of elements in that //dimension. Note that vectors are not created with this constructor, since a zero lower bound is assumed for //vectors. // //* A Get method that takes a sequence of int32 arguments, one for each dimension of the array, and returns //a value whose type is the element type of the array. This method is used to access a specific element of the //array where the arguments specify the index into each dimension, beginning with the first, of the element //to be returned. // //* A Set method that takes a sequence of int32 arguments, one for each dimension of the array, followed by //a value whose type is the element type of the array. The return type of Set is void. This method is used to //set a specific element of the array where the arguments specify the index into each dimension, beginning //with the first, of the element to be set and the final argument specifies the value to be stored into the target //element. // //* An Address method that takes a sequence of int32 arguments, one for each dimension of the array, and //has a return type that is a managed pointer to the array's element type. This method is used to return a //managed pointer to a specific element of the array where the arguments specify the index into each //dimension, beginning with the first, of the element whose address is to be returned. namespace Microsoft.CodeAnalysis.CodeGen { /// <summary> /// Constructs and caches already created pseudo-methods. /// Every compiled module is supposed to have one of this, created lazily /// (multidimensional arrays are not common). /// </summary> internal class ArrayMethods { // There are four kinds of array pseudo-methods // They are specific to a given array type private enum ArrayMethodKind : byte { GET, SET, ADDRESS, CTOR, } /// <summary> /// Acquires an array constructor for a given array type /// </summary> public ArrayMethod GetArrayConstructor(Cci.IArrayTypeReference arrayType) { return GetArrayMethod(arrayType, ArrayMethodKind.CTOR); } /// <summary> /// Acquires an element getter method for a given array type /// </summary> public ArrayMethod GetArrayGet(Cci.IArrayTypeReference arrayType) => GetArrayMethod(arrayType, ArrayMethodKind.GET); /// <summary> /// Acquires an element setter method for a given array type /// </summary> public ArrayMethod GetArraySet(Cci.IArrayTypeReference arrayType) => GetArrayMethod(arrayType, ArrayMethodKind.SET); /// <summary> /// Acquires an element referencer method for a given array type /// </summary> public ArrayMethod GetArrayAddress(Cci.IArrayTypeReference arrayType) => GetArrayMethod(arrayType, ArrayMethodKind.ADDRESS); /// <summary> /// Maps {array type, method kind} tuples to implementing pseudo-methods. /// </summary> private readonly ConcurrentDictionary<(byte methodKind, IReferenceOrISignature arrayType), ArrayMethod> _dict = new ConcurrentDictionary<(byte, IReferenceOrISignature), ArrayMethod>(); /// <summary> /// lazily fetches or creates a new array method. /// </summary> private ArrayMethod GetArrayMethod(Cci.IArrayTypeReference arrayType, ArrayMethodKind id) { var key = ((byte)id, new IReferenceOrISignature(arrayType)); ArrayMethod? result; var dict = _dict; if (!dict.TryGetValue(key, out result)) { result = MakeArrayMethod(arrayType, id); result = dict.GetOrAdd(key, result); } return result; } private static ArrayMethod MakeArrayMethod(Cci.IArrayTypeReference arrayType, ArrayMethodKind id) { switch (id) { case ArrayMethodKind.CTOR: return new ArrayConstructor(arrayType); case ArrayMethodKind.GET: return new ArrayGet(arrayType); case ArrayMethodKind.SET: return new ArraySet(arrayType); case ArrayMethodKind.ADDRESS: return new ArrayAddress(arrayType); } throw ExceptionUtilities.UnexpectedValue(id); } /// <summary> /// "newobj ArrayConstructor" is equivalent of "newarr ElementType" /// when working with multidimensional arrays /// </summary> private sealed class ArrayConstructor : ArrayMethod { public ArrayConstructor(Cci.IArrayTypeReference arrayType) : base(arrayType) { } public override string Name => ".ctor"; public override Cci.ITypeReference GetType(EmitContext context) => context.Module.GetPlatformType(Cci.PlatformType.SystemVoid, context); } /// <summary> /// "call ArrayGet" is equivalent of "ldelem ElementType" /// when working with multidimensional arrays /// </summary> private sealed class ArrayGet : ArrayMethod { public ArrayGet(Cci.IArrayTypeReference arrayType) : base(arrayType) { } public override string Name => "Get"; public override Cci.ITypeReference GetType(EmitContext context) => arrayType.GetElementType(context); } /// <summary> /// "call ArrayAddress" is equivalent of "ldelema ElementType" /// when working with multidimensional arrays /// </summary> private sealed class ArrayAddress : ArrayMethod { public ArrayAddress(Cci.IArrayTypeReference arrayType) : base(arrayType) { } public override bool ReturnValueIsByRef => true; public override Cci.ITypeReference GetType(EmitContext context) => arrayType.GetElementType(context); public override string Name => "Address"; } /// <summary> /// "call ArraySet" is equivalent of "stelem ElementType" /// when working with multidimensional arrays /// </summary> private sealed class ArraySet : ArrayMethod { public ArraySet(Cci.IArrayTypeReference arrayType) : base(arrayType) { } public override string Name => "Set"; public override Cci.ITypeReference GetType(EmitContext context) => context.Module.GetPlatformType(Cci.PlatformType.SystemVoid, context); protected override ImmutableArray<ArrayMethodParameterInfo> MakeParameters() { int rank = (int)arrayType.Rank; var parameters = ArrayBuilder<ArrayMethodParameterInfo>.GetInstance(rank + 1); for (int i = 0; i < rank; i++) { parameters.Add(ArrayMethodParameterInfo.GetIndexParameter((ushort)i)); } parameters.Add(new ArraySetValueParameterInfo((ushort)rank, arrayType)); return parameters.ToImmutableAndFree(); } } } /// <summary> /// Represents a parameter in an array pseudo-method. /// /// NOTE: It appears that only number of indices is used for verification, /// types just have to be Int32. /// Even though actual arguments can be native ints. /// </summary> internal class ArrayMethodParameterInfo : Cci.IParameterTypeInformation { // position in the signature private readonly ushort _index; // cache common parameter instances // (we can do this since the only data we have is the index) private static readonly ArrayMethodParameterInfo s_index0 = new ArrayMethodParameterInfo(0); private static readonly ArrayMethodParameterInfo s_index1 = new ArrayMethodParameterInfo(1); private static readonly ArrayMethodParameterInfo s_index2 = new ArrayMethodParameterInfo(2); private static readonly ArrayMethodParameterInfo s_index3 = new ArrayMethodParameterInfo(3); protected ArrayMethodParameterInfo(ushort index) { _index = index; } public static ArrayMethodParameterInfo GetIndexParameter(ushort index) { switch (index) { case 0: return s_index0; case 1: return s_index1; case 2: return s_index2; case 3: return s_index3; } return new ArrayMethodParameterInfo(index); } public ImmutableArray<Cci.ICustomModifier> RefCustomModifiers => ImmutableArray<Cci.ICustomModifier>.Empty; public ImmutableArray<Cci.ICustomModifier> CustomModifiers => ImmutableArray<Cci.ICustomModifier>.Empty; public bool IsByReference => false; public virtual Cci.ITypeReference GetType(EmitContext context) => context.Module.GetPlatformType(Cci.PlatformType.SystemInt32, context); public ushort Index => _index; } /// <summary> /// Represents the "value" parameter of the Set pseudo-method. /// /// NOTE: unlike index parameters, type of the value parameter must match /// the actual element type. /// </summary> internal sealed class ArraySetValueParameterInfo : ArrayMethodParameterInfo { private readonly Cci.IArrayTypeReference _arrayType; internal ArraySetValueParameterInfo(ushort index, Cci.IArrayTypeReference arrayType) : base(index) { _arrayType = arrayType; } public override Cci.ITypeReference GetType(EmitContext context) => _arrayType.GetElementType(context); } /// <summary> /// Base of all array methods. They have a lot in common. /// </summary> internal abstract class ArrayMethod : Cci.IMethodReference { private readonly ImmutableArray<ArrayMethodParameterInfo> _parameters; protected readonly Cci.IArrayTypeReference arrayType; protected ArrayMethod(Cci.IArrayTypeReference arrayType) { this.arrayType = arrayType; _parameters = MakeParameters(); } public abstract string Name { get; } public abstract Cci.ITypeReference GetType(EmitContext context); // Address overrides this to "true" public virtual bool ReturnValueIsByRef => false; // Set overrides this to include "value" parameter. protected virtual ImmutableArray<ArrayMethodParameterInfo> MakeParameters() { int rank = (int)arrayType.Rank; var parameters = ArrayBuilder<ArrayMethodParameterInfo>.GetInstance(rank); for (int i = 0; i < rank; i++) { parameters.Add(ArrayMethodParameterInfo.GetIndexParameter((ushort)i)); } return parameters.ToImmutableAndFree(); } public ImmutableArray<Cci.IParameterTypeInformation> GetParameters(EmitContext context) => StaticCast<Cci.IParameterTypeInformation>.From(_parameters); public bool AcceptsExtraArguments => false; public ushort GenericParameterCount => 0; public bool IsGeneric => false; public Cci.IMethodDefinition? GetResolvedMethod(EmitContext context) => null; public ImmutableArray<Cci.IParameterTypeInformation> ExtraParameters => ImmutableArray<Cci.IParameterTypeInformation>.Empty; public Cci.IGenericMethodInstanceReference? AsGenericMethodInstanceReference => null; public Cci.ISpecializedMethodReference? AsSpecializedMethodReference => null; public Cci.CallingConvention CallingConvention => Cci.CallingConvention.HasThis; public ushort ParameterCount => (ushort)_parameters.Length; public ImmutableArray<Cci.ICustomModifier> RefCustomModifiers => ImmutableArray<Cci.ICustomModifier>.Empty; public ImmutableArray<Cci.ICustomModifier> ReturnValueCustomModifiers => ImmutableArray<Cci.ICustomModifier>.Empty; public Cci.ITypeReference GetContainingType(EmitContext context) { // We are not translating arrayType. // It is an array type and it is never generic or contained in a generic. return this.arrayType; } public IEnumerable<Cci.ICustomAttribute> GetAttributes(EmitContext context) => SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>(); public void Dispatch(Cci.MetadataVisitor visitor) => visitor.Visit(this); public Cci.IDefinition? AsDefinition(EmitContext context) => null; public override string ToString() => ((object?)arrayType.GetInternalSymbol() ?? arrayType).ToString() + "." + Name; Symbols.ISymbolInternal? Cci.IReference.GetInternalSymbol() => null; public sealed override bool Equals(object? obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } } }
-1
dotnet/roslyn
56,351
Follow syntaxfacts pattern
I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
CyrusNajmabadi
"2021-09-13T17:58:02Z"
"2021-09-15T23:37:04Z"
5aa5223fc3a55b6c4ec91694aafa71c918e368e8
3f2908b43d85793d386181ab785712705568c053
Follow syntaxfacts pattern. I recommend starting the review at: https://github.com/dotnet/roslyn/pull/56351/files#diff-f8a376be87a8123f285a06533c2e3fff86d3b0a36044b1f398fe0ee75738b375R77
./src/Compilers/CSharp/Portable/Syntax/GlobalStatementSyntax.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.Syntax { public partial class GlobalStatementSyntax { public GlobalStatementSyntax Update(StatementSyntax statement) => this.Update(this.AttributeLists, this.Modifiers, statement); } }
// Licensed to the .NET Foundation under one or more 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.Syntax { public partial class GlobalStatementSyntax { public GlobalStatementSyntax Update(StatementSyntax statement) => this.Update(this.AttributeLists, this.Modifiers, statement); } }
-1