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 | 55,971 | Theme some dialogs | Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ryzngard | "2021-08-27T20:10:35Z" | "2022-07-12T20:08:34Z" | 07297d927b3ffd4d44f048602950947e9a040dd2 | 2cd995df98f17f1ceebba0d93729d8a4336ebe26 | Theme some dialogs. Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ./src/Workspaces/Remote/Core/xlf/RemoteWorkspacesResources.fr.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="fr" original="../RemoteWorkspacesResources.resx">
<body>
<trans-unit id="FeatureName_AssetSynchronization">
<source>Asset synchronization</source>
<target state="translated">Synchronisation des ressources</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_AsynchronousOperationListener">
<source>Asynchronous operation listener</source>
<target state="translated">Écouteur d'opérations asynchrones</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_CodeLensReferences">
<source>CodeLens references</source>
<target state="translated">Références CodeLens</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_CompilationAvailable">
<source>Project semantics availability</source>
<target state="translated">Disponibilité de la sémantique du projet</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_ConvertTupleToStructCodeRefactoring">
<source>Convert tuple to struct refactoring</source>
<target state="translated">Refactorisation de la conversion de tuple en struct</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_DependentTypeFinder">
<source>Dependent type finder</source>
<target state="translated">Outil de recherche de type dépendant</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_DesignerAttributeDiscovery">
<source>DesignerAttribute discovery</source>
<target state="translated">Détection de DesignerAttribute</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_DiagnosticAnalyzer">
<source>Diagnostic analyzer runner</source>
<target state="translated">Exécuteur d'analyseur de diagnostic</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_DocumentHighlights">
<source>Document highlights</source>
<target state="translated">Grandes lignes du document</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_EditAndContinue">
<source>Edit and Continue</source>
<target state="translated">Modifier et continuer</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_EncapsulateField">
<source>Encapsulate field refactoring</source>
<target state="translated">Refactorisation de l'encapsulation de champ</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_ExtensionMethodImportCompletion">
<source>Extension method import completion</source>
<target state="translated">Exécution de l'importation de méthode d'extension</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_FindUsages">
<source>Find usages</source>
<target state="translated">Recherche d'usages</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_GlobalNotificationDelivery">
<source>Global notification delivery</source>
<target state="translated">Remise de notification globale</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_InheritanceMargin">
<source>Inheritance margin</source>
<target state="translated">Marge d’héritage</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_MissingImportDiscovery">
<source>Missing import discovery</source>
<target state="translated">Détection d'importation manquante</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_NavigateToSearch">
<source>Navigate to</source>
<target state="translated">Accéder à</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_NavigationBarItem">
<source>Navigation bar</source>
<target state="translated">Barre de navigation</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_ProcessTelemetry">
<source>Process telemetry</source>
<target state="translated">Télémétrie du processus</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_ProjectTelemetry">
<source>Project telemetry collection</source>
<target state="translated">Collecte de la télémétrie du projet</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_Renamer">
<source>Rename</source>
<target state="translated">Renommer</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_SemanticClassification">
<source>Semantic classification</source>
<target state="translated">Classification sémantique</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_SolutionAssetProvider">
<source>Asset provider</source>
<target state="translated">Fournisseur de ressources</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_StackTraceExplorer">
<source>Stack Trace Explorer</source>
<target state="translated">Explorateur de traces de pile</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_SymbolFinder">
<source>Symbol finder</source>
<target state="translated">Outil de recherche de symboles</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_SymbolSearchUpdate">
<source>Symbol search</source>
<target state="translated">Recherche de symboles</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_TodoCommentsDiscovery">
<source>TODO comments discovery</source>
<target state="translated">Détection de commentaires TODO</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_UnusedReferenceAnalysis">
<source>Unused reference analysis</source>
<target state="translated">Analyse de référence inutilisée</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_ValueTracking">
<source>Value Tracking</source>
<target state="translated">Suivi de la valeur</target>
<note />
</trans-unit>
<trans-unit id="Feature_0_is_currently_unavailable_due_to_an_intermittent_error">
<source>Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}'</source>
<target state="translated">La fonctionnalité '{0}' est non disponible en raison d'une erreur intermittente. Réessayez plus tard : '{1}'</target>
<note />
</trans-unit>
<trans-unit id="Feature_0_is_currently_unavailable_due_to_an_internal_error">
<source>Feature '{0}' is currently unavailable due to an internal error.</source>
<target state="translated">La fonctionnalité '{0}' est non disponible en raison d'une erreur interne.</target>
<note />
</trans-unit>
<trans-unit id="Feature_0_is_currently_unavailable_host_shutting_down">
<source>Feature '{0}' is currently unavailable since {1} is shutting down.</source>
<target state="translated">La fonctionnalité '{0}' est non disponible, car {1} est en cours d'arrêt.</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="fr" original="../RemoteWorkspacesResources.resx">
<body>
<trans-unit id="FeatureName_AssetSynchronization">
<source>Asset synchronization</source>
<target state="translated">Synchronisation des ressources</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_AsynchronousOperationListener">
<source>Asynchronous operation listener</source>
<target state="translated">Écouteur d'opérations asynchrones</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_CodeLensReferences">
<source>CodeLens references</source>
<target state="translated">Références CodeLens</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_CompilationAvailable">
<source>Project semantics availability</source>
<target state="translated">Disponibilité de la sémantique du projet</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_ConvertTupleToStructCodeRefactoring">
<source>Convert tuple to struct refactoring</source>
<target state="translated">Refactorisation de la conversion de tuple en struct</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_DependentTypeFinder">
<source>Dependent type finder</source>
<target state="translated">Outil de recherche de type dépendant</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_DesignerAttributeDiscovery">
<source>DesignerAttribute discovery</source>
<target state="translated">Détection de DesignerAttribute</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_DiagnosticAnalyzer">
<source>Diagnostic analyzer runner</source>
<target state="translated">Exécuteur d'analyseur de diagnostic</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_DocumentHighlights">
<source>Document highlights</source>
<target state="translated">Grandes lignes du document</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_EditAndContinue">
<source>Edit and Continue</source>
<target state="translated">Modifier et continuer</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_EncapsulateField">
<source>Encapsulate field refactoring</source>
<target state="translated">Refactorisation de l'encapsulation de champ</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_ExtensionMethodImportCompletion">
<source>Extension method import completion</source>
<target state="translated">Exécution de l'importation de méthode d'extension</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_FindUsages">
<source>Find usages</source>
<target state="translated">Recherche d'usages</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_GlobalNotificationDelivery">
<source>Global notification delivery</source>
<target state="translated">Remise de notification globale</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_InheritanceMargin">
<source>Inheritance margin</source>
<target state="translated">Marge d’héritage</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_MissingImportDiscovery">
<source>Missing import discovery</source>
<target state="translated">Détection d'importation manquante</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_NavigateToSearch">
<source>Navigate to</source>
<target state="translated">Accéder à</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_NavigationBarItem">
<source>Navigation bar</source>
<target state="translated">Barre de navigation</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_ProcessTelemetry">
<source>Process telemetry</source>
<target state="translated">Télémétrie du processus</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_ProjectTelemetry">
<source>Project telemetry collection</source>
<target state="translated">Collecte de la télémétrie du projet</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_Renamer">
<source>Rename</source>
<target state="translated">Renommer</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_SemanticClassification">
<source>Semantic classification</source>
<target state="translated">Classification sémantique</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_SolutionAssetProvider">
<source>Asset provider</source>
<target state="translated">Fournisseur de ressources</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_StackTraceExplorer">
<source>Stack Trace Explorer</source>
<target state="translated">Explorateur de traces de pile</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_SymbolFinder">
<source>Symbol finder</source>
<target state="translated">Outil de recherche de symboles</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_SymbolSearchUpdate">
<source>Symbol search</source>
<target state="translated">Recherche de symboles</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_TodoCommentsDiscovery">
<source>TODO comments discovery</source>
<target state="translated">Détection de commentaires TODO</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_UnusedReferenceAnalysis">
<source>Unused reference analysis</source>
<target state="translated">Analyse de référence inutilisée</target>
<note />
</trans-unit>
<trans-unit id="FeatureName_ValueTracking">
<source>Value Tracking</source>
<target state="translated">Suivi de la valeur</target>
<note />
</trans-unit>
<trans-unit id="Feature_0_is_currently_unavailable_due_to_an_intermittent_error">
<source>Feature '{0}' is currently unavailable due to an intermittent error, please try again later: '{1}'</source>
<target state="translated">La fonctionnalité '{0}' est non disponible en raison d'une erreur intermittente. Réessayez plus tard : '{1}'</target>
<note />
</trans-unit>
<trans-unit id="Feature_0_is_currently_unavailable_due_to_an_internal_error">
<source>Feature '{0}' is currently unavailable due to an internal error.</source>
<target state="translated">La fonctionnalité '{0}' est non disponible en raison d'une erreur interne.</target>
<note />
</trans-unit>
<trans-unit id="Feature_0_is_currently_unavailable_host_shutting_down">
<source>Feature '{0}' is currently unavailable since {1} is shutting down.</source>
<target state="translated">La fonctionnalité '{0}' est non disponible, car {1} est en cours d'arrêt.</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,971 | Theme some dialogs | Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ryzngard | "2021-08-27T20:10:35Z" | "2022-07-12T20:08:34Z" | 07297d927b3ffd4d44f048602950947e9a040dd2 | 2cd995df98f17f1ceebba0d93729d8a4336ebe26 | Theme some dialogs. Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ./src/Compilers/CSharp/Portable/FlowAnalysis/UnassignedAddressTakenVariablesWalker.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// An analysis that computes all cases where the address is taken of a variable that has not yet been assigned
/// </summary>
internal class UnassignedAddressTakenVariablesWalker : DefiniteAssignmentPass
{
private UnassignedAddressTakenVariablesWalker(CSharpCompilation compilation, Symbol member, BoundNode node)
: base(compilation, member, node, strictAnalysis: true)
{
}
internal static HashSet<PrefixUnaryExpressionSyntax> Analyze(CSharpCompilation compilation, Symbol member, BoundNode node)
{
var walker = new UnassignedAddressTakenVariablesWalker(compilation, member, node);
try
{
bool badRegion = false;
var result = walker.Analyze(ref badRegion);
Debug.Assert(!badRegion);
return result;
}
finally
{
walker.Free();
}
}
private readonly HashSet<PrefixUnaryExpressionSyntax> _result = new HashSet<PrefixUnaryExpressionSyntax>();
private HashSet<PrefixUnaryExpressionSyntax> Analyze(ref bool badRegion)
{
// It might seem necessary to clear this.result after each Scan performed by base.Analyze, however,
// finding new execution paths (via new backwards branches) can only make variables "less" definitely
// assigned, not more. That is, if there was formerly a path on which the variable was not definitely
// assigned, then adding another path will not make the variable definitely assigned. Therefore,
// subsequent scans can only re-add elements to this.result, and the HashSet will naturally de-dup.
base.Analyze(ref badRegion, null);
return _result;
}
protected override void ReportUnassigned(Symbol symbol, SyntaxNode node, int slot, bool skipIfUseBeforeDeclaration)
{
if (node.Parent.Kind() == SyntaxKind.AddressOfExpression)
{
_result.Add((PrefixUnaryExpressionSyntax)node.Parent);
}
}
public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node)
{
// Pretend address-of is a pure read (i.e. no write) - would we see an
// unassigned diagnostic?
VisitRvalue(node.Operand);
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.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// An analysis that computes all cases where the address is taken of a variable that has not yet been assigned
/// </summary>
internal class UnassignedAddressTakenVariablesWalker : DefiniteAssignmentPass
{
private UnassignedAddressTakenVariablesWalker(CSharpCompilation compilation, Symbol member, BoundNode node)
: base(compilation, member, node, strictAnalysis: true)
{
}
internal static HashSet<PrefixUnaryExpressionSyntax> Analyze(CSharpCompilation compilation, Symbol member, BoundNode node)
{
var walker = new UnassignedAddressTakenVariablesWalker(compilation, member, node);
try
{
bool badRegion = false;
var result = walker.Analyze(ref badRegion);
Debug.Assert(!badRegion);
return result;
}
finally
{
walker.Free();
}
}
private readonly HashSet<PrefixUnaryExpressionSyntax> _result = new HashSet<PrefixUnaryExpressionSyntax>();
private HashSet<PrefixUnaryExpressionSyntax> Analyze(ref bool badRegion)
{
// It might seem necessary to clear this.result after each Scan performed by base.Analyze, however,
// finding new execution paths (via new backwards branches) can only make variables "less" definitely
// assigned, not more. That is, if there was formerly a path on which the variable was not definitely
// assigned, then adding another path will not make the variable definitely assigned. Therefore,
// subsequent scans can only re-add elements to this.result, and the HashSet will naturally de-dup.
base.Analyze(ref badRegion, null);
return _result;
}
protected override void ReportUnassigned(Symbol symbol, SyntaxNode node, int slot, bool skipIfUseBeforeDeclaration)
{
if (node.Parent.Kind() == SyntaxKind.AddressOfExpression)
{
_result.Add((PrefixUnaryExpressionSyntax)node.Parent);
}
}
public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node)
{
// Pretend address-of is a pure read (i.e. no write) - would we see an
// unassigned diagnostic?
VisitRvalue(node.Operand);
return null;
}
}
}
| -1 |
dotnet/roslyn | 55,971 | Theme some dialogs | Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ryzngard | "2021-08-27T20:10:35Z" | "2022-07-12T20:08:34Z" | 07297d927b3ffd4d44f048602950947e9a040dd2 | 2cd995df98f17f1ceebba0d93729d8a4336ebe26 | Theme some dialogs. Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ./src/Features/CSharp/Portable/Highlighting/KeywordHighlighters/CheckedStatementHighlighter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Composition;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Highlighting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.KeywordHighlighting.KeywordHighlighters
{
[ExportHighlighter(LanguageNames.CSharp), Shared]
internal class CheckedStatementHighlighter : AbstractKeywordHighlighter<CheckedStatementSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CheckedStatementHighlighter()
{
}
protected override void AddHighlights(CheckedStatementSyntax checkedStatement, List<TextSpan> highlights, CancellationToken cancellationToken)
=> highlights.Add(checkedStatement.Keyword.Span);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Composition;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Highlighting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.KeywordHighlighting.KeywordHighlighters
{
[ExportHighlighter(LanguageNames.CSharp), Shared]
internal class CheckedStatementHighlighter : AbstractKeywordHighlighter<CheckedStatementSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CheckedStatementHighlighter()
{
}
protected override void AddHighlights(CheckedStatementSyntax checkedStatement, List<TextSpan> highlights, CancellationToken cancellationToken)
=> highlights.Add(checkedStatement.Keyword.Span);
}
}
| -1 |
dotnet/roslyn | 55,971 | Theme some dialogs | Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ryzngard | "2021-08-27T20:10:35Z" | "2022-07-12T20:08:34Z" | 07297d927b3ffd4d44f048602950947e9a040dd2 | 2cd995df98f17f1ceebba0d93729d8a4336ebe26 | Theme some dialogs. Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ./src/Features/VisualBasic/Portable/Highlighting/KeywordHighlighters/TryBlockHighlighter.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.Threading
Imports Microsoft.CodeAnalysis.Highlighting
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.KeywordHighlighting
<ExportHighlighter(LanguageNames.VisualBasic), [Shared]>
Friend Class TryBlockHighlighter
Inherits AbstractKeywordHighlighter(Of SyntaxNode)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overloads Overrides Sub AddHighlights(node As SyntaxNode, highlights As List(Of TextSpan), cancellationToken As CancellationToken)
If TypeOf node Is ExitStatementSyntax AndAlso node.Kind <> SyntaxKind.ExitTryStatement Then
Return
End If
Dim tryBlock = node.GetAncestor(Of TryBlockSyntax)()
If tryBlock Is Nothing Then
Return
End If
With tryBlock
highlights.Add(.TryStatement.TryKeyword.Span)
HighlightRelatedStatements(tryBlock, highlights)
For Each catchBlock In .CatchBlocks
With catchBlock.CatchStatement
highlights.Add(.CatchKeyword.Span)
If .WhenClause IsNot Nothing Then
highlights.Add(.WhenClause.WhenKeyword.Span)
End If
End With
HighlightRelatedStatements(catchBlock, highlights)
Next
If .FinallyBlock IsNot Nothing Then
highlights.Add(.FinallyBlock.FinallyStatement.FinallyKeyword.Span)
End If
highlights.Add(.EndTryStatement.Span)
End With
End Sub
Private Sub HighlightRelatedStatements(node As SyntaxNode, highlights As List(Of TextSpan))
If node.Kind = SyntaxKind.ExitTryStatement Then
highlights.Add(node.Span)
Else
For Each childNodeOrToken In node.ChildNodesAndTokens()
If childNodeOrToken.IsToken Then
Continue For
End If
Dim child = childNodeOrToken.AsNode()
If Not TypeOf child Is TryBlockSyntax AndAlso Not TypeOf child Is LambdaExpressionSyntax Then
HighlightRelatedStatements(child, highlights)
End If
Next
End If
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Highlighting
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.KeywordHighlighting
<ExportHighlighter(LanguageNames.VisualBasic), [Shared]>
Friend Class TryBlockHighlighter
Inherits AbstractKeywordHighlighter(Of SyntaxNode)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overloads Overrides Sub AddHighlights(node As SyntaxNode, highlights As List(Of TextSpan), cancellationToken As CancellationToken)
If TypeOf node Is ExitStatementSyntax AndAlso node.Kind <> SyntaxKind.ExitTryStatement Then
Return
End If
Dim tryBlock = node.GetAncestor(Of TryBlockSyntax)()
If tryBlock Is Nothing Then
Return
End If
With tryBlock
highlights.Add(.TryStatement.TryKeyword.Span)
HighlightRelatedStatements(tryBlock, highlights)
For Each catchBlock In .CatchBlocks
With catchBlock.CatchStatement
highlights.Add(.CatchKeyword.Span)
If .WhenClause IsNot Nothing Then
highlights.Add(.WhenClause.WhenKeyword.Span)
End If
End With
HighlightRelatedStatements(catchBlock, highlights)
Next
If .FinallyBlock IsNot Nothing Then
highlights.Add(.FinallyBlock.FinallyStatement.FinallyKeyword.Span)
End If
highlights.Add(.EndTryStatement.Span)
End With
End Sub
Private Sub HighlightRelatedStatements(node As SyntaxNode, highlights As List(Of TextSpan))
If node.Kind = SyntaxKind.ExitTryStatement Then
highlights.Add(node.Span)
Else
For Each childNodeOrToken In node.ChildNodesAndTokens()
If childNodeOrToken.IsToken Then
Continue For
End If
Dim child = childNodeOrToken.AsNode()
If Not TypeOf child Is TryBlockSyntax AndAlso Not TypeOf child Is LambdaExpressionSyntax Then
HighlightRelatedStatements(child, highlights)
End If
Next
End If
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,971 | Theme some dialogs | Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ryzngard | "2021-08-27T20:10:35Z" | "2022-07-12T20:08:34Z" | 07297d927b3ffd4d44f048602950947e9a040dd2 | 2cd995df98f17f1ceebba0d93729d8a4336ebe26 | Theme some dialogs. Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ./src/Workspaces/Core/Portable/Workspace/Workspace_Editor.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
// The parts of a workspace that deal with open documents
public abstract partial class Workspace
{
// open documents
private readonly Dictionary<ProjectId, HashSet<DocumentId>> _projectToOpenDocumentsMap = new();
// text buffer maps
/// <summary>
/// Tracks the document ID in the current context for a source text container for an opened text buffer.
/// </summary>
/// <remarks>For each entry in this map, there must be a corresponding entry in <see cref="_bufferToAssociatedDocumentsMap"/> where the document ID in current context is one of associated document IDs.</remarks>
private readonly Dictionary<SourceTextContainer, DocumentId> _bufferToDocumentInCurrentContextMap = new();
/// <summary>
/// Tracks all the associated document IDs for a source text container for an opened text buffer.
/// </summary>
private readonly Dictionary<SourceTextContainer, OneOrMany<DocumentId>> _bufferToAssociatedDocumentsMap = new();
private readonly Dictionary<DocumentId, TextTracker> _textTrackers = new();
private readonly Dictionary<DocumentId, SourceTextContainer> _documentToAssociatedBufferMap = new();
private readonly Dictionary<DocumentId, SourceGeneratedDocumentIdentity> _openSourceGeneratedDocumentIdentities = new();
/// <summary>
/// True if this workspace supports manually opening and closing documents.
/// </summary>
public virtual bool CanOpenDocuments => false;
/// <summary>
/// True if this workspace supports manually changing the active context document of a text buffer by calling <see cref="SetDocumentContext(DocumentId)" />.
/// </summary>
internal virtual bool CanChangeActiveContextDocument => false;
private protected void ClearOpenDocuments()
{
List<DocumentId> docIds;
using (_stateLock.DisposableWait())
{
docIds = _projectToOpenDocumentsMap.Values.SelectMany(x => x).ToList();
}
foreach (var docId in docIds)
{
this.ClearOpenDocument(docId);
}
}
private void ClearOpenDocuments(ProjectId projectId)
{
HashSet<DocumentId>? openDocs;
using (_stateLock.DisposableWait())
{
_projectToOpenDocumentsMap.TryGetValue(projectId, out openDocs);
}
if (openDocs != null)
{
// ClearOpenDocument will remove the document from the original set.
var copyOfOpenDocs = openDocs.ToList();
foreach (var docId in copyOfOpenDocs)
{
this.ClearOpenDocument(docId);
}
}
}
protected void ClearOpenDocument(DocumentId documentId)
{
using (_stateLock.DisposableWait())
{
_projectToOpenDocumentsMap.MultiRemove(documentId.ProjectId, documentId);
// Stop tracking the buffer or update the documentId associated with the buffer.
if (_documentToAssociatedBufferMap.TryGetValue(documentId, out var textContainer))
{
_documentToAssociatedBufferMap.Remove(documentId);
if (_textTrackers.TryGetValue(documentId, out var tracker))
{
tracker.Disconnect();
_textTrackers.Remove(documentId);
}
var currentContextDocumentId = RemoveDocumentFromCurrentContextMapping_NoLock(textContainer, documentId);
if (currentContextDocumentId == null)
{
// No documentIds are attached to this buffer, so stop tracking it.
this.UnregisterText(textContainer);
}
}
}
}
[Obsolete("The isSolutionClosing parameter is now obsolete. Please call the overload without that parameter.")]
protected void ClearOpenDocument(DocumentId documentId, bool isSolutionClosing)
=> ClearOpenDocument(documentId);
/// <summary>
/// Open the specified document in the host environment.
/// </summary>
public virtual void OpenDocument(DocumentId documentId, bool activate = true)
=> this.CheckCanOpenDocuments();
/// <summary>
/// Close the specified document in the host environment.
/// </summary>
public virtual void CloseDocument(DocumentId documentId)
=> this.CheckCanOpenDocuments();
/// <summary>
/// Open the specified additional document in the host environment.
/// </summary>
public virtual void OpenAdditionalDocument(DocumentId documentId, bool activate = true)
=> this.CheckCanOpenDocuments();
/// <summary>
/// Close the specified additional document in the host environment.
/// </summary>
public virtual void CloseAdditionalDocument(DocumentId documentId)
=> this.CheckCanOpenDocuments();
/// <summary>
/// Open the specified analyzer config document in the host environment.
/// </summary>
public virtual void OpenAnalyzerConfigDocument(DocumentId documentId, bool activate = true)
=> this.CheckCanOpenDocuments();
/// <summary>
/// Close the specified analyzer config document in the host environment.
/// </summary>
public virtual void CloseAnalyzerConfigDocument(DocumentId documentId)
=> this.CheckCanOpenDocuments();
protected void CheckCanOpenDocuments()
{
if (!this.CanOpenDocuments)
{
throw new NotSupportedException(WorkspacesResources.This_workspace_does_not_support_opening_and_closing_documents);
}
}
protected void CheckProjectDoesNotContainOpenDocuments(ProjectId projectId)
{
if (ProjectHasOpenDocuments(projectId))
{
throw new ArgumentException(string.Format(WorkspacesResources._0_still_contains_open_documents, this.GetProjectName(projectId)));
}
}
private bool ProjectHasOpenDocuments(ProjectId projectId)
{
using (_stateLock.DisposableWait())
{
return _projectToOpenDocumentsMap.ContainsKey(projectId);
}
}
/// <summary>
/// Determines if the document is currently open in the host environment.
/// </summary>
public virtual bool IsDocumentOpen(DocumentId documentId)
{
using (_stateLock.DisposableWait())
{
return _projectToOpenDocumentsMap.TryGetValue(documentId.ProjectId, out var openDocuments) &&
openDocuments.Contains(documentId);
}
}
/// <summary>
/// Gets a list of the currently opened documents.
/// </summary>
public virtual IEnumerable<DocumentId> GetOpenDocumentIds(ProjectId? projectId = null)
{
using (_stateLock.DisposableWait())
{
if (_projectToOpenDocumentsMap.Count == 0)
{
return SpecializedCollections.EmptyEnumerable<DocumentId>();
}
if (projectId != null)
{
if (_projectToOpenDocumentsMap.TryGetValue(projectId, out var documentIds))
{
return documentIds;
}
return SpecializedCollections.EmptyEnumerable<DocumentId>();
}
return _projectToOpenDocumentsMap.SelectMany(kvp => kvp.Value).ToImmutableArray();
}
}
/// <summary>
/// Gets the ids for documents in the <see cref="CurrentSolution"/> snapshot associated with the given <paramref name="container"/>.
/// Documents are normally associated with a text container when the documents are opened.
/// </summary>
public virtual IEnumerable<DocumentId> GetRelatedDocumentIds(SourceTextContainer container)
{
if (container == null)
{
throw new ArgumentNullException(nameof(container));
}
var documentId = GetDocumentIdInCurrentContext(container);
if (documentId == null)
{
return ImmutableArray<DocumentId>.Empty;
}
return CurrentSolution.GetRelatedDocumentIds(documentId);
}
/// <summary>
/// Gets the id for the document associated with the given text container in its current context.
/// Documents are normally associated with a text container when the documents are opened.
/// </summary>
public virtual DocumentId? GetDocumentIdInCurrentContext(SourceTextContainer container)
{
if (container == null)
{
throw new ArgumentNullException(nameof(container));
}
using (_stateLock.DisposableWait())
{
return GetDocumentIdInCurrentContext_NoLock(container);
}
}
private DocumentId? GetDocumentIdInCurrentContext_NoLock(SourceTextContainer container)
=> _bufferToDocumentInCurrentContextMap.TryGetValue(container, out var documentId) ? documentId : null;
/// <summary>
/// Finds the <see cref="DocumentId"/> related to the given <see cref="DocumentId"/> that
/// is in the current context. If the <see cref="DocumentId"/> is currently closed, then
/// it is returned directly. If it is open, then this returns the same result that
/// <see cref="GetDocumentIdInCurrentContext(SourceTextContainer)"/> would return for the
/// <see cref="SourceTextContainer"/>.
/// </summary>
internal DocumentId GetDocumentIdInCurrentContext(DocumentId documentId)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
using (_stateLock.DisposableWait())
{
var container = GetOpenDocumentSourceTextContainer_NoLock(documentId);
if (container != null)
{
var currentContextId = GetDocumentIdInCurrentContext_NoLock(container);
Contract.ThrowIfNull(currentContextId, "The document is open, so we should have had some context ID.");
return currentContextId;
}
return documentId;
}
}
private SourceTextContainer? GetOpenDocumentSourceTextContainer_NoLock(DocumentId documentId)
{
// TODO: remove linear search
return _bufferToAssociatedDocumentsMap.Where(kvp => kvp.Value.Contains(documentId)).Select(kvp => kvp.Key).FirstOrDefault();
}
internal bool TryGetOpenSourceGeneratedDocumentIdentity(DocumentId id, out SourceGeneratedDocumentIdentity documentIdentity)
{
using (_serializationLock.DisposableWait())
{
return _openSourceGeneratedDocumentIdentities.TryGetValue(id, out documentIdentity);
}
}
/// <summary>
/// Call this method to tell the host environment to change the current active context to this document. Only supported if
/// <see cref="CanChangeActiveContextDocument"/> returns true.
/// </summary>
internal virtual void SetDocumentContext(DocumentId documentId)
=> throw new NotSupportedException();
/// <summary>
/// Call this method when a document has been made the active context in the host environment.
/// </summary>
protected internal void OnDocumentContextUpdated(DocumentId documentId)
{
using (_serializationLock.DisposableWait())
{
DocumentId oldActiveContextDocumentId;
SourceTextContainer? container;
using (_stateLock.DisposableWait())
{
container = GetOpenDocumentSourceTextContainer_NoLock(documentId);
if (container == null)
{
return;
}
oldActiveContextDocumentId = _bufferToDocumentInCurrentContextMap[container];
if (documentId == oldActiveContextDocumentId)
{
return;
}
UpdateCurrentContextMapping_NoLock(container, documentId, isCurrentContext: true);
}
// fire and forget
this.RaiseDocumentActiveContextChangedEventAsync(container, oldActiveContextDocumentId: oldActiveContextDocumentId, newActiveContextDocumentId: documentId);
}
}
protected void CheckDocumentIsClosed(DocumentId documentId)
{
if (this.IsDocumentOpen(documentId))
{
throw new ArgumentException(
string.Format(WorkspacesResources._0_is_still_open,
this.GetDocumentName(documentId)));
}
}
protected void CheckDocumentIsOpen(DocumentId documentId)
{
if (!this.IsDocumentOpen(documentId))
{
throw new ArgumentException(string.Format(
WorkspacesResources._0_is_not_open,
this.GetDocumentName(documentId)));
}
}
protected internal void OnDocumentOpened(
DocumentId documentId, SourceTextContainer textContainer,
bool isCurrentContext = true)
{
using (_serializationLock.DisposableWait())
{
CheckDocumentIsInCurrentSolution(documentId);
CheckDocumentIsClosed(documentId);
var oldSolution = this.CurrentSolution;
var oldDocument = oldSolution.GetRequiredDocument(documentId);
var oldDocumentState = oldDocument.State;
AddToOpenDocumentMap(documentId);
var newText = textContainer.CurrentText;
Solution currentSolution;
if (oldDocument.TryGetText(out var oldText) &&
oldDocument.TryGetTextVersion(out var version))
{
// Optimize the case where we've already got the previous text and version.
var newTextAndVersion = GetProperTextAndVersion(oldText, newText, version, oldDocumentState.FilePath);
// keep open document text alive by using PreserveIdentity
currentSolution = oldSolution.WithDocumentText(documentId, newTextAndVersion, PreservationMode.PreserveIdentity);
}
else
{
// We don't have the old text or version. And we don't want to retrieve them
// just yet (as that would cause blocking in this synchronous method). So just
// make a simple loader to do that for us later when requested.
//
// keep open document text alive by using PreserveIdentity
//
// Note: we pass along the newText here so that clients can easily get the text
// of an opened document just by calling TryGetText without any blocking.
currentSolution = oldSolution.UpdateDocumentTextLoader(documentId,
new ReuseVersionLoader((DocumentState)oldDocument.State, newText), newText, PreservationMode.PreserveIdentity);
}
var newSolution = this.SetCurrentSolution(currentSolution);
SignupForTextChanges(documentId, textContainer, isCurrentContext, (w, id, text, mode) => w.OnDocumentTextChanged(id, text, mode));
var newDoc = newSolution.GetRequiredDocument(documentId);
this.OnDocumentTextChanged(newDoc);
// Fire and forget that the workspace is changing.
RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentChanged, oldSolution, newSolution, documentId: documentId);
// We fire 2 events on source document opened.
this.RaiseDocumentOpenedEventAsync(newDoc);
this.RaiseTextDocumentOpenedEventAsync(newDoc);
}
this.RegisterText(textContainer);
}
/// <summary>
/// Registers a SourceTextContainer to a source generated document. Unlike <see cref="OnDocumentOpened" />,
/// this doesn't result in the workspace being updated any time the contents of the container is changed; instead
/// this ensures that features going from the text container to the buffer back to a document get a usable document.
/// </summary>
// TODO: switch this protected once we have confidence in API shape
internal void OnSourceGeneratedDocumentOpened(
SourceTextContainer textContainer,
SourceGeneratedDocument document)
{
using (_serializationLock.DisposableWait())
{
var documentId = document.Identity.DocumentId;
CheckDocumentIsClosed(documentId);
AddToOpenDocumentMap(documentId);
_documentToAssociatedBufferMap.Add(documentId, textContainer);
_openSourceGeneratedDocumentIdentities.Add(documentId, document.Identity);
UpdateCurrentContextMapping_NoLock(textContainer, documentId, isCurrentContext: true);
// Fire and forget that the workspace is changing.
// We raise 2 events for source document opened.
var token = _taskQueue.Listener.BeginAsyncOperation(nameof(OnSourceGeneratedDocumentOpened));
_ = RaiseDocumentOpenedEventAsync(document).CompletesAsyncOperation(token);
token = _taskQueue.Listener.BeginAsyncOperation(TextDocumentOpenedEventName);
_ = RaiseTextDocumentOpenedEventAsync(document).CompletesAsyncOperation(token);
}
this.RegisterText(textContainer);
}
internal void OnSourceGeneratedDocumentClosed(SourceGeneratedDocument document)
{
using (_serializationLock.DisposableWait())
{
CheckDocumentIsOpen(document.Id);
Contract.ThrowIfFalse(_openSourceGeneratedDocumentIdentities.Remove(document.Id));
ClearOpenDocument(document.Id);
// Fire and forget that the workspace is changing.
// We raise 2 events for source document closed.
var token = _taskQueue.Listener.BeginAsyncOperation(nameof(OnSourceGeneratedDocumentClosed));
_ = RaiseDocumentClosedEventAsync(document).CompletesAsyncOperation(token);
token = _taskQueue.Listener.BeginAsyncOperation(TextDocumentClosedEventName);
_ = RaiseTextDocumentClosedEventAsync(document).CompletesAsyncOperation(token);
}
}
private class ReuseVersionLoader : TextLoader
{
// Capture DocumentState instead of Document so that we don't hold onto the old solution.
private readonly DocumentState _oldDocumentState;
private readonly SourceText _newText;
public ReuseVersionLoader(DocumentState oldDocumentState, SourceText newText)
{
_oldDocumentState = oldDocumentState;
_newText = newText;
}
public override async Task<TextAndVersion> LoadTextAndVersionAsync(
Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
{
var oldText = await _oldDocumentState.GetTextAsync(cancellationToken).ConfigureAwait(false);
var version = await _oldDocumentState.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
return GetProperTextAndVersion(oldText, _newText, version, _oldDocumentState.FilePath);
}
internal override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
{
var oldText = _oldDocumentState.GetTextSynchronously(cancellationToken);
var version = _oldDocumentState.GetTextVersionSynchronously(cancellationToken);
return GetProperTextAndVersion(oldText, _newText, version, _oldDocumentState.FilePath);
}
}
private static TextAndVersion GetProperTextAndVersion(SourceText oldText, SourceText newText, VersionStamp version, string? filePath)
{
// if the supplied text is the same as the previous text, then also use same version
// otherwise use new version
return oldText.ContentEquals(newText)
? TextAndVersion.Create(newText, version, filePath)
: TextAndVersion.Create(newText, version.GetNewerVersion(), filePath);
}
private void SignupForTextChanges(DocumentId documentId, SourceTextContainer textContainer, bool isCurrentContext, Action<Workspace, DocumentId, SourceText, PreservationMode> onChangedHandler)
{
var tracker = new TextTracker(this, documentId, textContainer, onChangedHandler);
_textTrackers.Add(documentId, tracker);
_documentToAssociatedBufferMap.Add(documentId, textContainer);
this.UpdateCurrentContextMapping_NoLock(textContainer, documentId, isCurrentContext);
tracker.Connect();
}
private void AddToOpenDocumentMap(DocumentId documentId)
{
using (_stateLock.DisposableWait())
{
_projectToOpenDocumentsMap.MultiAdd(documentId.ProjectId, documentId);
}
}
protected internal void OnAdditionalDocumentOpened(DocumentId documentId, SourceTextContainer textContainer, bool isCurrentContext = true)
{
OnAdditionalOrAnalyzerConfigDocumentOpened(
documentId,
textContainer,
isCurrentContext,
WorkspaceChangeKind.AdditionalDocumentChanged,
CheckAdditionalDocumentIsInCurrentSolution,
withDocumentText: (oldSolution, documentId, newText, mode) => oldSolution.WithAdditionalDocumentText(documentId, newText, mode),
withDocumentTextAndVersion: (oldSolution, documentId, newTextAndVersion, mode) => oldSolution.WithAdditionalDocumentText(documentId, newTextAndVersion, mode),
onDocumentTextChanged: (w, id, text, mode) => w.OnAdditionalDocumentTextChanged(id, text, mode));
}
protected internal void OnAnalyzerConfigDocumentOpened(DocumentId documentId, SourceTextContainer textContainer, bool isCurrentContext = true)
{
OnAdditionalOrAnalyzerConfigDocumentOpened(
documentId,
textContainer,
isCurrentContext,
WorkspaceChangeKind.AnalyzerConfigDocumentChanged,
CheckAnalyzerConfigDocumentIsInCurrentSolution,
withDocumentText: (oldSolution, documentId, newText, mode) => oldSolution.WithAnalyzerConfigDocumentText(documentId, newText, mode),
withDocumentTextAndVersion: (oldSolution, documentId, newTextAndVersion, mode) => oldSolution.WithAnalyzerConfigDocumentText(documentId, newTextAndVersion, mode),
onDocumentTextChanged: (w, id, text, mode) => w.OnAnalyzerConfigDocumentTextChanged(id, text, mode));
}
// NOTE: We are only sharing this code between additional documents and analyzer config documents,
// which are essentially plain text documents. Regular source documents need special handling
// and hence have a different implementation.
private void OnAdditionalOrAnalyzerConfigDocumentOpened(
DocumentId documentId,
SourceTextContainer textContainer,
bool isCurrentContext,
WorkspaceChangeKind workspaceChangeKind,
Action<DocumentId> checkTextDocumentIsInCurrentSolution,
Func<Solution, DocumentId, SourceText, PreservationMode, Solution> withDocumentText,
Func<Solution, DocumentId, TextAndVersion, PreservationMode, Solution> withDocumentTextAndVersion,
Action<Workspace, DocumentId, SourceText, PreservationMode> onDocumentTextChanged)
{
using (_serializationLock.DisposableWait())
{
checkTextDocumentIsInCurrentSolution(documentId);
CheckDocumentIsClosed(documentId);
var oldSolution = this.CurrentSolution;
var oldDocument = oldSolution.GetRequiredTextDocument(documentId);
Debug.Assert(oldDocument.Kind is TextDocumentKind.AdditionalDocument or TextDocumentKind.AnalyzerConfigDocument);
var oldText = oldDocument.GetTextSynchronously(CancellationToken.None);
AddToOpenDocumentMap(documentId);
// keep open document text alive by using PreserveIdentity
var newText = textContainer.CurrentText;
Solution currentSolution;
if (oldText == newText || oldText.ContentEquals(newText))
{
// if the supplied text is the same as the previous text, then also use same version
var version = oldDocument.GetTextVersionSynchronously(CancellationToken.None);
var newTextAndVersion = TextAndVersion.Create(newText, version, oldDocument.FilePath);
currentSolution = withDocumentTextAndVersion(oldSolution, documentId, newTextAndVersion, PreservationMode.PreserveIdentity);
}
else
{
currentSolution = withDocumentText(oldSolution, documentId, newText, PreservationMode.PreserveIdentity);
}
var newSolution = this.SetCurrentSolution(currentSolution);
SignupForTextChanges(documentId, textContainer, isCurrentContext, onDocumentTextChanged);
// Fire and forget.
this.RaiseWorkspaceChangedEventAsync(workspaceChangeKind, oldSolution, newSolution, documentId: documentId);
// Fire and forget.
var newDoc = newSolution.GetRequiredTextDocument(documentId);
this.RaiseTextDocumentOpenedEventAsync(newDoc);
}
this.RegisterText(textContainer);
}
#pragma warning disable IDE0060 // Remove unused parameter 'updateActiveContext' - shipped public API.
protected internal void OnDocumentClosed(DocumentId documentId, TextLoader reloader, bool updateActiveContext = false)
#pragma warning restore IDE0060 // Remove unused parameter
{
// The try/catch here is to find additional telemetry for https://devdiv.visualstudio.com/DevDiv/_queries/query/71ee8553-7220-4b2a-98cf-20edab701fd1/,
// where we have one theory that OnDocumentClosed is running but failing somewhere in the middle and thus failing to get to the RaiseDocumentClosedEventAsync() line.
// We are choosing ReportWithoutCrashAndPropagate because this is a public API that has callers outside VS and also non-VisualStudioWorkspace callers inside VS, and
// we don't want to be crashing underneath them if they were already handling exceptions or (worse) was using those exceptions for expected code flow.
try
{
using (_serializationLock.DisposableWait())
{
this.CheckDocumentIsInCurrentSolution(documentId);
this.CheckDocumentIsOpen(documentId);
// forget any open document info
ClearOpenDocument(documentId);
var oldSolution = this.CurrentSolution;
var oldDocument = oldSolution.GetDocument(documentId);
this.OnDocumentClosing(documentId);
var newSolution = oldSolution.WithDocumentTextLoader(documentId, reloader, PreservationMode.PreserveValue);
newSolution = this.SetCurrentSolution(newSolution);
var newDoc = newSolution.GetRequiredDocument(documentId);
this.OnDocumentTextChanged(newDoc);
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentChanged, oldSolution, newSolution, documentId: documentId); // don't wait for this
// We fire and forget 2 events on source document closed.
this.RaiseDocumentClosedEventAsync(newDoc);
this.RaiseTextDocumentClosedEventAsync(newDoc);
}
}
catch (Exception e) when (FatalError.ReportAndPropagate(e, ErrorSeverity.General))
{
throw ExceptionUtilities.Unreachable;
}
}
protected internal void OnAdditionalDocumentClosed(DocumentId documentId, TextLoader reloader)
{
OnAdditionalOrAnalyzerConfigDocumentClosed(
documentId,
reloader,
WorkspaceChangeKind.AdditionalDocumentChanged,
CheckAdditionalDocumentIsInCurrentSolution,
withTextDocumentTextLoader: (oldSolution, documentId, textLoader, mode) => oldSolution.WithAdditionalDocumentTextLoader(documentId, textLoader, mode));
}
protected internal void OnAnalyzerConfigDocumentClosed(DocumentId documentId, TextLoader reloader)
{
OnAdditionalOrAnalyzerConfigDocumentClosed(
documentId,
reloader,
WorkspaceChangeKind.AnalyzerConfigDocumentChanged,
CheckAnalyzerConfigDocumentIsInCurrentSolution,
withTextDocumentTextLoader: (oldSolution, documentId, textLoader, mode) => oldSolution.WithAnalyzerConfigDocumentTextLoader(documentId, textLoader, mode));
}
// NOTE: We are only sharing this code between additional documents and analyzer config documents,
// which are essentially plain text documents. Regular source documents need special handling
// and hence have a different implementation.
private void OnAdditionalOrAnalyzerConfigDocumentClosed(
DocumentId documentId,
TextLoader reloader,
WorkspaceChangeKind workspaceChangeKind,
Action<DocumentId> checkTextDocumentIsInCurrentSolution,
Func<Solution, DocumentId, TextLoader, PreservationMode, Solution> withTextDocumentTextLoader)
{
using (_serializationLock.DisposableWait())
{
checkTextDocumentIsInCurrentSolution(documentId);
this.CheckDocumentIsOpen(documentId);
// forget any open document info
ClearOpenDocument(documentId);
var oldSolution = this.CurrentSolution;
var oldDocument = oldSolution.GetRequiredTextDocument(documentId);
Debug.Assert(oldDocument.Kind is TextDocumentKind.AdditionalDocument or TextDocumentKind.AnalyzerConfigDocument);
var newSolution = withTextDocumentTextLoader(oldSolution, documentId, reloader, PreservationMode.PreserveValue);
newSolution = this.SetCurrentSolution(newSolution);
this.RaiseWorkspaceChangedEventAsync(workspaceChangeKind, oldSolution, newSolution, documentId: documentId); // don't wait for this
var newDoc = newSolution.GetRequiredTextDocument(documentId);
this.RaiseTextDocumentClosedEventAsync(newDoc); // don't wait for this
}
}
private void UpdateCurrentContextMapping_NoLock(SourceTextContainer textContainer, DocumentId id, bool isCurrentContext)
{
if (_bufferToAssociatedDocumentsMap.TryGetValue(textContainer, out var docIds))
{
Contract.ThrowIfFalse(_bufferToDocumentInCurrentContextMap.ContainsKey(textContainer));
if (!docIds.Contains(id))
{
docIds = docIds.Add(id);
}
}
else
{
Contract.ThrowIfFalse(!_bufferToDocumentInCurrentContextMap.ContainsKey(textContainer));
docIds = new OneOrMany<DocumentId>(id);
}
if (isCurrentContext || !_bufferToDocumentInCurrentContextMap.ContainsKey(textContainer))
{
_bufferToDocumentInCurrentContextMap[textContainer] = id;
}
_bufferToAssociatedDocumentsMap[textContainer] = docIds;
}
/// <returns>The DocumentId of the current context document attached to the textContainer, if any.</returns>
private DocumentId? RemoveDocumentFromCurrentContextMapping_NoLock(SourceTextContainer textContainer, DocumentId closedDocumentId)
{
// Check if we are tracking this textContainer.
if (!_bufferToAssociatedDocumentsMap.TryGetValue(textContainer, out var docIds))
{
Contract.ThrowIfFalse(!_bufferToDocumentInCurrentContextMap.ContainsKey(textContainer));
return null;
}
Contract.ThrowIfFalse(_bufferToDocumentInCurrentContextMap.ContainsKey(textContainer));
// Remove closedDocumentId
docIds = docIds.RemoveAll(closedDocumentId);
// Remove the entry if there are no more documents attached to given textContainer.
if (docIds.Equals(default(OneOrMany<DocumentId>)))
{
_bufferToAssociatedDocumentsMap.Remove(textContainer);
_bufferToDocumentInCurrentContextMap.Remove(textContainer);
return null;
}
// Update the new list of documents attached to the given textContainer and the current context document, and return the latter.
_bufferToAssociatedDocumentsMap[textContainer] = docIds;
_bufferToDocumentInCurrentContextMap[textContainer] = docIds[0];
return docIds[0];
}
private SourceText GetOpenDocumentText(Solution solution, DocumentId documentId)
{
CheckDocumentIsOpen(documentId);
var doc = solution.GetRequiredTextDocument(documentId);
// text should always be preserved, so TryGetText will succeed.
Contract.ThrowIfFalse(doc.TryGetText(out var text));
return text;
}
/// <summary>
/// This method is called during OnSolutionReload. Override this method if you want to manipulate
/// the reloaded solution.
/// </summary>
protected virtual Solution AdjustReloadedSolution(Solution oldSolution, Solution reloadedSolution)
{
var newSolution = reloadedSolution;
// keep open documents using same text
foreach (var docId in this.GetOpenDocumentIds())
{
var document = newSolution.GetTextDocument(docId);
if (document != null)
{
newSolution = document.WithText(this.GetOpenDocumentText(oldSolution, docId)).Project.Solution;
}
}
return newSolution;
}
protected virtual Project AdjustReloadedProject(Project oldProject, Project reloadedProject)
{
var oldSolution = oldProject.Solution;
var newSolution = reloadedProject.Solution;
// keep open documents open using same text
foreach (var docId in this.GetOpenDocumentIds(oldProject.Id))
{
var document = newSolution.GetTextDocument(docId);
if (document != null)
{
newSolution = document.WithText(this.GetOpenDocumentText(oldSolution, docId)).Project.Solution;
}
}
return newSolution.GetRequiredProject(oldProject.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.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
// The parts of a workspace that deal with open documents
public abstract partial class Workspace
{
// open documents
private readonly Dictionary<ProjectId, HashSet<DocumentId>> _projectToOpenDocumentsMap = new();
// text buffer maps
/// <summary>
/// Tracks the document ID in the current context for a source text container for an opened text buffer.
/// </summary>
/// <remarks>For each entry in this map, there must be a corresponding entry in <see cref="_bufferToAssociatedDocumentsMap"/> where the document ID in current context is one of associated document IDs.</remarks>
private readonly Dictionary<SourceTextContainer, DocumentId> _bufferToDocumentInCurrentContextMap = new();
/// <summary>
/// Tracks all the associated document IDs for a source text container for an opened text buffer.
/// </summary>
private readonly Dictionary<SourceTextContainer, OneOrMany<DocumentId>> _bufferToAssociatedDocumentsMap = new();
private readonly Dictionary<DocumentId, TextTracker> _textTrackers = new();
private readonly Dictionary<DocumentId, SourceTextContainer> _documentToAssociatedBufferMap = new();
private readonly Dictionary<DocumentId, SourceGeneratedDocumentIdentity> _openSourceGeneratedDocumentIdentities = new();
/// <summary>
/// True if this workspace supports manually opening and closing documents.
/// </summary>
public virtual bool CanOpenDocuments => false;
/// <summary>
/// True if this workspace supports manually changing the active context document of a text buffer by calling <see cref="SetDocumentContext(DocumentId)" />.
/// </summary>
internal virtual bool CanChangeActiveContextDocument => false;
private protected void ClearOpenDocuments()
{
List<DocumentId> docIds;
using (_stateLock.DisposableWait())
{
docIds = _projectToOpenDocumentsMap.Values.SelectMany(x => x).ToList();
}
foreach (var docId in docIds)
{
this.ClearOpenDocument(docId);
}
}
private void ClearOpenDocuments(ProjectId projectId)
{
HashSet<DocumentId>? openDocs;
using (_stateLock.DisposableWait())
{
_projectToOpenDocumentsMap.TryGetValue(projectId, out openDocs);
}
if (openDocs != null)
{
// ClearOpenDocument will remove the document from the original set.
var copyOfOpenDocs = openDocs.ToList();
foreach (var docId in copyOfOpenDocs)
{
this.ClearOpenDocument(docId);
}
}
}
protected void ClearOpenDocument(DocumentId documentId)
{
using (_stateLock.DisposableWait())
{
_projectToOpenDocumentsMap.MultiRemove(documentId.ProjectId, documentId);
// Stop tracking the buffer or update the documentId associated with the buffer.
if (_documentToAssociatedBufferMap.TryGetValue(documentId, out var textContainer))
{
_documentToAssociatedBufferMap.Remove(documentId);
if (_textTrackers.TryGetValue(documentId, out var tracker))
{
tracker.Disconnect();
_textTrackers.Remove(documentId);
}
var currentContextDocumentId = RemoveDocumentFromCurrentContextMapping_NoLock(textContainer, documentId);
if (currentContextDocumentId == null)
{
// No documentIds are attached to this buffer, so stop tracking it.
this.UnregisterText(textContainer);
}
}
}
}
[Obsolete("The isSolutionClosing parameter is now obsolete. Please call the overload without that parameter.")]
protected void ClearOpenDocument(DocumentId documentId, bool isSolutionClosing)
=> ClearOpenDocument(documentId);
/// <summary>
/// Open the specified document in the host environment.
/// </summary>
public virtual void OpenDocument(DocumentId documentId, bool activate = true)
=> this.CheckCanOpenDocuments();
/// <summary>
/// Close the specified document in the host environment.
/// </summary>
public virtual void CloseDocument(DocumentId documentId)
=> this.CheckCanOpenDocuments();
/// <summary>
/// Open the specified additional document in the host environment.
/// </summary>
public virtual void OpenAdditionalDocument(DocumentId documentId, bool activate = true)
=> this.CheckCanOpenDocuments();
/// <summary>
/// Close the specified additional document in the host environment.
/// </summary>
public virtual void CloseAdditionalDocument(DocumentId documentId)
=> this.CheckCanOpenDocuments();
/// <summary>
/// Open the specified analyzer config document in the host environment.
/// </summary>
public virtual void OpenAnalyzerConfigDocument(DocumentId documentId, bool activate = true)
=> this.CheckCanOpenDocuments();
/// <summary>
/// Close the specified analyzer config document in the host environment.
/// </summary>
public virtual void CloseAnalyzerConfigDocument(DocumentId documentId)
=> this.CheckCanOpenDocuments();
protected void CheckCanOpenDocuments()
{
if (!this.CanOpenDocuments)
{
throw new NotSupportedException(WorkspacesResources.This_workspace_does_not_support_opening_and_closing_documents);
}
}
protected void CheckProjectDoesNotContainOpenDocuments(ProjectId projectId)
{
if (ProjectHasOpenDocuments(projectId))
{
throw new ArgumentException(string.Format(WorkspacesResources._0_still_contains_open_documents, this.GetProjectName(projectId)));
}
}
private bool ProjectHasOpenDocuments(ProjectId projectId)
{
using (_stateLock.DisposableWait())
{
return _projectToOpenDocumentsMap.ContainsKey(projectId);
}
}
/// <summary>
/// Determines if the document is currently open in the host environment.
/// </summary>
public virtual bool IsDocumentOpen(DocumentId documentId)
{
using (_stateLock.DisposableWait())
{
return _projectToOpenDocumentsMap.TryGetValue(documentId.ProjectId, out var openDocuments) &&
openDocuments.Contains(documentId);
}
}
/// <summary>
/// Gets a list of the currently opened documents.
/// </summary>
public virtual IEnumerable<DocumentId> GetOpenDocumentIds(ProjectId? projectId = null)
{
using (_stateLock.DisposableWait())
{
if (_projectToOpenDocumentsMap.Count == 0)
{
return SpecializedCollections.EmptyEnumerable<DocumentId>();
}
if (projectId != null)
{
if (_projectToOpenDocumentsMap.TryGetValue(projectId, out var documentIds))
{
return documentIds;
}
return SpecializedCollections.EmptyEnumerable<DocumentId>();
}
return _projectToOpenDocumentsMap.SelectMany(kvp => kvp.Value).ToImmutableArray();
}
}
/// <summary>
/// Gets the ids for documents in the <see cref="CurrentSolution"/> snapshot associated with the given <paramref name="container"/>.
/// Documents are normally associated with a text container when the documents are opened.
/// </summary>
public virtual IEnumerable<DocumentId> GetRelatedDocumentIds(SourceTextContainer container)
{
if (container == null)
{
throw new ArgumentNullException(nameof(container));
}
var documentId = GetDocumentIdInCurrentContext(container);
if (documentId == null)
{
return ImmutableArray<DocumentId>.Empty;
}
return CurrentSolution.GetRelatedDocumentIds(documentId);
}
/// <summary>
/// Gets the id for the document associated with the given text container in its current context.
/// Documents are normally associated with a text container when the documents are opened.
/// </summary>
public virtual DocumentId? GetDocumentIdInCurrentContext(SourceTextContainer container)
{
if (container == null)
{
throw new ArgumentNullException(nameof(container));
}
using (_stateLock.DisposableWait())
{
return GetDocumentIdInCurrentContext_NoLock(container);
}
}
private DocumentId? GetDocumentIdInCurrentContext_NoLock(SourceTextContainer container)
=> _bufferToDocumentInCurrentContextMap.TryGetValue(container, out var documentId) ? documentId : null;
/// <summary>
/// Finds the <see cref="DocumentId"/> related to the given <see cref="DocumentId"/> that
/// is in the current context. If the <see cref="DocumentId"/> is currently closed, then
/// it is returned directly. If it is open, then this returns the same result that
/// <see cref="GetDocumentIdInCurrentContext(SourceTextContainer)"/> would return for the
/// <see cref="SourceTextContainer"/>.
/// </summary>
internal DocumentId GetDocumentIdInCurrentContext(DocumentId documentId)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
using (_stateLock.DisposableWait())
{
var container = GetOpenDocumentSourceTextContainer_NoLock(documentId);
if (container != null)
{
var currentContextId = GetDocumentIdInCurrentContext_NoLock(container);
Contract.ThrowIfNull(currentContextId, "The document is open, so we should have had some context ID.");
return currentContextId;
}
return documentId;
}
}
private SourceTextContainer? GetOpenDocumentSourceTextContainer_NoLock(DocumentId documentId)
{
// TODO: remove linear search
return _bufferToAssociatedDocumentsMap.Where(kvp => kvp.Value.Contains(documentId)).Select(kvp => kvp.Key).FirstOrDefault();
}
internal bool TryGetOpenSourceGeneratedDocumentIdentity(DocumentId id, out SourceGeneratedDocumentIdentity documentIdentity)
{
using (_serializationLock.DisposableWait())
{
return _openSourceGeneratedDocumentIdentities.TryGetValue(id, out documentIdentity);
}
}
/// <summary>
/// Call this method to tell the host environment to change the current active context to this document. Only supported if
/// <see cref="CanChangeActiveContextDocument"/> returns true.
/// </summary>
internal virtual void SetDocumentContext(DocumentId documentId)
=> throw new NotSupportedException();
/// <summary>
/// Call this method when a document has been made the active context in the host environment.
/// </summary>
protected internal void OnDocumentContextUpdated(DocumentId documentId)
{
using (_serializationLock.DisposableWait())
{
DocumentId oldActiveContextDocumentId;
SourceTextContainer? container;
using (_stateLock.DisposableWait())
{
container = GetOpenDocumentSourceTextContainer_NoLock(documentId);
if (container == null)
{
return;
}
oldActiveContextDocumentId = _bufferToDocumentInCurrentContextMap[container];
if (documentId == oldActiveContextDocumentId)
{
return;
}
UpdateCurrentContextMapping_NoLock(container, documentId, isCurrentContext: true);
}
// fire and forget
this.RaiseDocumentActiveContextChangedEventAsync(container, oldActiveContextDocumentId: oldActiveContextDocumentId, newActiveContextDocumentId: documentId);
}
}
protected void CheckDocumentIsClosed(DocumentId documentId)
{
if (this.IsDocumentOpen(documentId))
{
throw new ArgumentException(
string.Format(WorkspacesResources._0_is_still_open,
this.GetDocumentName(documentId)));
}
}
protected void CheckDocumentIsOpen(DocumentId documentId)
{
if (!this.IsDocumentOpen(documentId))
{
throw new ArgumentException(string.Format(
WorkspacesResources._0_is_not_open,
this.GetDocumentName(documentId)));
}
}
protected internal void OnDocumentOpened(
DocumentId documentId, SourceTextContainer textContainer,
bool isCurrentContext = true)
{
using (_serializationLock.DisposableWait())
{
CheckDocumentIsInCurrentSolution(documentId);
CheckDocumentIsClosed(documentId);
var oldSolution = this.CurrentSolution;
var oldDocument = oldSolution.GetRequiredDocument(documentId);
var oldDocumentState = oldDocument.State;
AddToOpenDocumentMap(documentId);
var newText = textContainer.CurrentText;
Solution currentSolution;
if (oldDocument.TryGetText(out var oldText) &&
oldDocument.TryGetTextVersion(out var version))
{
// Optimize the case where we've already got the previous text and version.
var newTextAndVersion = GetProperTextAndVersion(oldText, newText, version, oldDocumentState.FilePath);
// keep open document text alive by using PreserveIdentity
currentSolution = oldSolution.WithDocumentText(documentId, newTextAndVersion, PreservationMode.PreserveIdentity);
}
else
{
// We don't have the old text or version. And we don't want to retrieve them
// just yet (as that would cause blocking in this synchronous method). So just
// make a simple loader to do that for us later when requested.
//
// keep open document text alive by using PreserveIdentity
//
// Note: we pass along the newText here so that clients can easily get the text
// of an opened document just by calling TryGetText without any blocking.
currentSolution = oldSolution.UpdateDocumentTextLoader(documentId,
new ReuseVersionLoader((DocumentState)oldDocument.State, newText), newText, PreservationMode.PreserveIdentity);
}
var newSolution = this.SetCurrentSolution(currentSolution);
SignupForTextChanges(documentId, textContainer, isCurrentContext, (w, id, text, mode) => w.OnDocumentTextChanged(id, text, mode));
var newDoc = newSolution.GetRequiredDocument(documentId);
this.OnDocumentTextChanged(newDoc);
// Fire and forget that the workspace is changing.
RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentChanged, oldSolution, newSolution, documentId: documentId);
// We fire 2 events on source document opened.
this.RaiseDocumentOpenedEventAsync(newDoc);
this.RaiseTextDocumentOpenedEventAsync(newDoc);
}
this.RegisterText(textContainer);
}
/// <summary>
/// Registers a SourceTextContainer to a source generated document. Unlike <see cref="OnDocumentOpened" />,
/// this doesn't result in the workspace being updated any time the contents of the container is changed; instead
/// this ensures that features going from the text container to the buffer back to a document get a usable document.
/// </summary>
// TODO: switch this protected once we have confidence in API shape
internal void OnSourceGeneratedDocumentOpened(
SourceTextContainer textContainer,
SourceGeneratedDocument document)
{
using (_serializationLock.DisposableWait())
{
var documentId = document.Identity.DocumentId;
CheckDocumentIsClosed(documentId);
AddToOpenDocumentMap(documentId);
_documentToAssociatedBufferMap.Add(documentId, textContainer);
_openSourceGeneratedDocumentIdentities.Add(documentId, document.Identity);
UpdateCurrentContextMapping_NoLock(textContainer, documentId, isCurrentContext: true);
// Fire and forget that the workspace is changing.
// We raise 2 events for source document opened.
var token = _taskQueue.Listener.BeginAsyncOperation(nameof(OnSourceGeneratedDocumentOpened));
_ = RaiseDocumentOpenedEventAsync(document).CompletesAsyncOperation(token);
token = _taskQueue.Listener.BeginAsyncOperation(TextDocumentOpenedEventName);
_ = RaiseTextDocumentOpenedEventAsync(document).CompletesAsyncOperation(token);
}
this.RegisterText(textContainer);
}
internal void OnSourceGeneratedDocumentClosed(SourceGeneratedDocument document)
{
using (_serializationLock.DisposableWait())
{
CheckDocumentIsOpen(document.Id);
Contract.ThrowIfFalse(_openSourceGeneratedDocumentIdentities.Remove(document.Id));
ClearOpenDocument(document.Id);
// Fire and forget that the workspace is changing.
// We raise 2 events for source document closed.
var token = _taskQueue.Listener.BeginAsyncOperation(nameof(OnSourceGeneratedDocumentClosed));
_ = RaiseDocumentClosedEventAsync(document).CompletesAsyncOperation(token);
token = _taskQueue.Listener.BeginAsyncOperation(TextDocumentClosedEventName);
_ = RaiseTextDocumentClosedEventAsync(document).CompletesAsyncOperation(token);
}
}
private class ReuseVersionLoader : TextLoader
{
// Capture DocumentState instead of Document so that we don't hold onto the old solution.
private readonly DocumentState _oldDocumentState;
private readonly SourceText _newText;
public ReuseVersionLoader(DocumentState oldDocumentState, SourceText newText)
{
_oldDocumentState = oldDocumentState;
_newText = newText;
}
public override async Task<TextAndVersion> LoadTextAndVersionAsync(
Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
{
var oldText = await _oldDocumentState.GetTextAsync(cancellationToken).ConfigureAwait(false);
var version = await _oldDocumentState.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
return GetProperTextAndVersion(oldText, _newText, version, _oldDocumentState.FilePath);
}
internal override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
{
var oldText = _oldDocumentState.GetTextSynchronously(cancellationToken);
var version = _oldDocumentState.GetTextVersionSynchronously(cancellationToken);
return GetProperTextAndVersion(oldText, _newText, version, _oldDocumentState.FilePath);
}
}
private static TextAndVersion GetProperTextAndVersion(SourceText oldText, SourceText newText, VersionStamp version, string? filePath)
{
// if the supplied text is the same as the previous text, then also use same version
// otherwise use new version
return oldText.ContentEquals(newText)
? TextAndVersion.Create(newText, version, filePath)
: TextAndVersion.Create(newText, version.GetNewerVersion(), filePath);
}
private void SignupForTextChanges(DocumentId documentId, SourceTextContainer textContainer, bool isCurrentContext, Action<Workspace, DocumentId, SourceText, PreservationMode> onChangedHandler)
{
var tracker = new TextTracker(this, documentId, textContainer, onChangedHandler);
_textTrackers.Add(documentId, tracker);
_documentToAssociatedBufferMap.Add(documentId, textContainer);
this.UpdateCurrentContextMapping_NoLock(textContainer, documentId, isCurrentContext);
tracker.Connect();
}
private void AddToOpenDocumentMap(DocumentId documentId)
{
using (_stateLock.DisposableWait())
{
_projectToOpenDocumentsMap.MultiAdd(documentId.ProjectId, documentId);
}
}
protected internal void OnAdditionalDocumentOpened(DocumentId documentId, SourceTextContainer textContainer, bool isCurrentContext = true)
{
OnAdditionalOrAnalyzerConfigDocumentOpened(
documentId,
textContainer,
isCurrentContext,
WorkspaceChangeKind.AdditionalDocumentChanged,
CheckAdditionalDocumentIsInCurrentSolution,
withDocumentText: (oldSolution, documentId, newText, mode) => oldSolution.WithAdditionalDocumentText(documentId, newText, mode),
withDocumentTextAndVersion: (oldSolution, documentId, newTextAndVersion, mode) => oldSolution.WithAdditionalDocumentText(documentId, newTextAndVersion, mode),
onDocumentTextChanged: (w, id, text, mode) => w.OnAdditionalDocumentTextChanged(id, text, mode));
}
protected internal void OnAnalyzerConfigDocumentOpened(DocumentId documentId, SourceTextContainer textContainer, bool isCurrentContext = true)
{
OnAdditionalOrAnalyzerConfigDocumentOpened(
documentId,
textContainer,
isCurrentContext,
WorkspaceChangeKind.AnalyzerConfigDocumentChanged,
CheckAnalyzerConfigDocumentIsInCurrentSolution,
withDocumentText: (oldSolution, documentId, newText, mode) => oldSolution.WithAnalyzerConfigDocumentText(documentId, newText, mode),
withDocumentTextAndVersion: (oldSolution, documentId, newTextAndVersion, mode) => oldSolution.WithAnalyzerConfigDocumentText(documentId, newTextAndVersion, mode),
onDocumentTextChanged: (w, id, text, mode) => w.OnAnalyzerConfigDocumentTextChanged(id, text, mode));
}
// NOTE: We are only sharing this code between additional documents and analyzer config documents,
// which are essentially plain text documents. Regular source documents need special handling
// and hence have a different implementation.
private void OnAdditionalOrAnalyzerConfigDocumentOpened(
DocumentId documentId,
SourceTextContainer textContainer,
bool isCurrentContext,
WorkspaceChangeKind workspaceChangeKind,
Action<DocumentId> checkTextDocumentIsInCurrentSolution,
Func<Solution, DocumentId, SourceText, PreservationMode, Solution> withDocumentText,
Func<Solution, DocumentId, TextAndVersion, PreservationMode, Solution> withDocumentTextAndVersion,
Action<Workspace, DocumentId, SourceText, PreservationMode> onDocumentTextChanged)
{
using (_serializationLock.DisposableWait())
{
checkTextDocumentIsInCurrentSolution(documentId);
CheckDocumentIsClosed(documentId);
var oldSolution = this.CurrentSolution;
var oldDocument = oldSolution.GetRequiredTextDocument(documentId);
Debug.Assert(oldDocument.Kind is TextDocumentKind.AdditionalDocument or TextDocumentKind.AnalyzerConfigDocument);
var oldText = oldDocument.GetTextSynchronously(CancellationToken.None);
AddToOpenDocumentMap(documentId);
// keep open document text alive by using PreserveIdentity
var newText = textContainer.CurrentText;
Solution currentSolution;
if (oldText == newText || oldText.ContentEquals(newText))
{
// if the supplied text is the same as the previous text, then also use same version
var version = oldDocument.GetTextVersionSynchronously(CancellationToken.None);
var newTextAndVersion = TextAndVersion.Create(newText, version, oldDocument.FilePath);
currentSolution = withDocumentTextAndVersion(oldSolution, documentId, newTextAndVersion, PreservationMode.PreserveIdentity);
}
else
{
currentSolution = withDocumentText(oldSolution, documentId, newText, PreservationMode.PreserveIdentity);
}
var newSolution = this.SetCurrentSolution(currentSolution);
SignupForTextChanges(documentId, textContainer, isCurrentContext, onDocumentTextChanged);
// Fire and forget.
this.RaiseWorkspaceChangedEventAsync(workspaceChangeKind, oldSolution, newSolution, documentId: documentId);
// Fire and forget.
var newDoc = newSolution.GetRequiredTextDocument(documentId);
this.RaiseTextDocumentOpenedEventAsync(newDoc);
}
this.RegisterText(textContainer);
}
#pragma warning disable IDE0060 // Remove unused parameter 'updateActiveContext' - shipped public API.
protected internal void OnDocumentClosed(DocumentId documentId, TextLoader reloader, bool updateActiveContext = false)
#pragma warning restore IDE0060 // Remove unused parameter
{
// The try/catch here is to find additional telemetry for https://devdiv.visualstudio.com/DevDiv/_queries/query/71ee8553-7220-4b2a-98cf-20edab701fd1/,
// where we have one theory that OnDocumentClosed is running but failing somewhere in the middle and thus failing to get to the RaiseDocumentClosedEventAsync() line.
// We are choosing ReportWithoutCrashAndPropagate because this is a public API that has callers outside VS and also non-VisualStudioWorkspace callers inside VS, and
// we don't want to be crashing underneath them if they were already handling exceptions or (worse) was using those exceptions for expected code flow.
try
{
using (_serializationLock.DisposableWait())
{
this.CheckDocumentIsInCurrentSolution(documentId);
this.CheckDocumentIsOpen(documentId);
// forget any open document info
ClearOpenDocument(documentId);
var oldSolution = this.CurrentSolution;
var oldDocument = oldSolution.GetDocument(documentId);
this.OnDocumentClosing(documentId);
var newSolution = oldSolution.WithDocumentTextLoader(documentId, reloader, PreservationMode.PreserveValue);
newSolution = this.SetCurrentSolution(newSolution);
var newDoc = newSolution.GetRequiredDocument(documentId);
this.OnDocumentTextChanged(newDoc);
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentChanged, oldSolution, newSolution, documentId: documentId); // don't wait for this
// We fire and forget 2 events on source document closed.
this.RaiseDocumentClosedEventAsync(newDoc);
this.RaiseTextDocumentClosedEventAsync(newDoc);
}
}
catch (Exception e) when (FatalError.ReportAndPropagate(e, ErrorSeverity.General))
{
throw ExceptionUtilities.Unreachable;
}
}
protected internal void OnAdditionalDocumentClosed(DocumentId documentId, TextLoader reloader)
{
OnAdditionalOrAnalyzerConfigDocumentClosed(
documentId,
reloader,
WorkspaceChangeKind.AdditionalDocumentChanged,
CheckAdditionalDocumentIsInCurrentSolution,
withTextDocumentTextLoader: (oldSolution, documentId, textLoader, mode) => oldSolution.WithAdditionalDocumentTextLoader(documentId, textLoader, mode));
}
protected internal void OnAnalyzerConfigDocumentClosed(DocumentId documentId, TextLoader reloader)
{
OnAdditionalOrAnalyzerConfigDocumentClosed(
documentId,
reloader,
WorkspaceChangeKind.AnalyzerConfigDocumentChanged,
CheckAnalyzerConfigDocumentIsInCurrentSolution,
withTextDocumentTextLoader: (oldSolution, documentId, textLoader, mode) => oldSolution.WithAnalyzerConfigDocumentTextLoader(documentId, textLoader, mode));
}
// NOTE: We are only sharing this code between additional documents and analyzer config documents,
// which are essentially plain text documents. Regular source documents need special handling
// and hence have a different implementation.
private void OnAdditionalOrAnalyzerConfigDocumentClosed(
DocumentId documentId,
TextLoader reloader,
WorkspaceChangeKind workspaceChangeKind,
Action<DocumentId> checkTextDocumentIsInCurrentSolution,
Func<Solution, DocumentId, TextLoader, PreservationMode, Solution> withTextDocumentTextLoader)
{
using (_serializationLock.DisposableWait())
{
checkTextDocumentIsInCurrentSolution(documentId);
this.CheckDocumentIsOpen(documentId);
// forget any open document info
ClearOpenDocument(documentId);
var oldSolution = this.CurrentSolution;
var oldDocument = oldSolution.GetRequiredTextDocument(documentId);
Debug.Assert(oldDocument.Kind is TextDocumentKind.AdditionalDocument or TextDocumentKind.AnalyzerConfigDocument);
var newSolution = withTextDocumentTextLoader(oldSolution, documentId, reloader, PreservationMode.PreserveValue);
newSolution = this.SetCurrentSolution(newSolution);
this.RaiseWorkspaceChangedEventAsync(workspaceChangeKind, oldSolution, newSolution, documentId: documentId); // don't wait for this
var newDoc = newSolution.GetRequiredTextDocument(documentId);
this.RaiseTextDocumentClosedEventAsync(newDoc); // don't wait for this
}
}
private void UpdateCurrentContextMapping_NoLock(SourceTextContainer textContainer, DocumentId id, bool isCurrentContext)
{
if (_bufferToAssociatedDocumentsMap.TryGetValue(textContainer, out var docIds))
{
Contract.ThrowIfFalse(_bufferToDocumentInCurrentContextMap.ContainsKey(textContainer));
if (!docIds.Contains(id))
{
docIds = docIds.Add(id);
}
}
else
{
Contract.ThrowIfFalse(!_bufferToDocumentInCurrentContextMap.ContainsKey(textContainer));
docIds = new OneOrMany<DocumentId>(id);
}
if (isCurrentContext || !_bufferToDocumentInCurrentContextMap.ContainsKey(textContainer))
{
_bufferToDocumentInCurrentContextMap[textContainer] = id;
}
_bufferToAssociatedDocumentsMap[textContainer] = docIds;
}
/// <returns>The DocumentId of the current context document attached to the textContainer, if any.</returns>
private DocumentId? RemoveDocumentFromCurrentContextMapping_NoLock(SourceTextContainer textContainer, DocumentId closedDocumentId)
{
// Check if we are tracking this textContainer.
if (!_bufferToAssociatedDocumentsMap.TryGetValue(textContainer, out var docIds))
{
Contract.ThrowIfFalse(!_bufferToDocumentInCurrentContextMap.ContainsKey(textContainer));
return null;
}
Contract.ThrowIfFalse(_bufferToDocumentInCurrentContextMap.ContainsKey(textContainer));
// Remove closedDocumentId
docIds = docIds.RemoveAll(closedDocumentId);
// Remove the entry if there are no more documents attached to given textContainer.
if (docIds.Equals(default(OneOrMany<DocumentId>)))
{
_bufferToAssociatedDocumentsMap.Remove(textContainer);
_bufferToDocumentInCurrentContextMap.Remove(textContainer);
return null;
}
// Update the new list of documents attached to the given textContainer and the current context document, and return the latter.
_bufferToAssociatedDocumentsMap[textContainer] = docIds;
_bufferToDocumentInCurrentContextMap[textContainer] = docIds[0];
return docIds[0];
}
private SourceText GetOpenDocumentText(Solution solution, DocumentId documentId)
{
CheckDocumentIsOpen(documentId);
var doc = solution.GetRequiredTextDocument(documentId);
// text should always be preserved, so TryGetText will succeed.
Contract.ThrowIfFalse(doc.TryGetText(out var text));
return text;
}
/// <summary>
/// This method is called during OnSolutionReload. Override this method if you want to manipulate
/// the reloaded solution.
/// </summary>
protected virtual Solution AdjustReloadedSolution(Solution oldSolution, Solution reloadedSolution)
{
var newSolution = reloadedSolution;
// keep open documents using same text
foreach (var docId in this.GetOpenDocumentIds())
{
var document = newSolution.GetTextDocument(docId);
if (document != null)
{
newSolution = document.WithText(this.GetOpenDocumentText(oldSolution, docId)).Project.Solution;
}
}
return newSolution;
}
protected virtual Project AdjustReloadedProject(Project oldProject, Project reloadedProject)
{
var oldSolution = oldProject.Solution;
var newSolution = reloadedProject.Solution;
// keep open documents open using same text
foreach (var docId in this.GetOpenDocumentIds(oldProject.Id))
{
var document = newSolution.GetTextDocument(docId);
if (document != null)
{
newSolution = document.WithText(this.GetOpenDocumentText(oldSolution, docId)).Project.Solution;
}
}
return newSolution.GetRequiredProject(oldProject.Id);
}
}
}
| -1 |
dotnet/roslyn | 55,971 | Theme some dialogs | Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ryzngard | "2021-08-27T20:10:35Z" | "2022-07-12T20:08:34Z" | 07297d927b3ffd4d44f048602950947e9a040dd2 | 2cd995df98f17f1ceebba0d93729d8a4336ebe26 | Theme some dialogs. Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ./src/EditorFeatures/VisualBasic/xlf/VBEditorResources.pt-BR.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="pt-BR" original="../VBEditorResources.resx">
<body>
<trans-unit id="Add_Missing_Imports_on_Paste">
<source>Add Missing Imports on Paste</source>
<target state="translated">Adicionar as Importações Ausentes ao Colar</target>
<note>"imports" is a language specific term and should not be localized</note>
</trans-unit>
<trans-unit id="Adding_missing_imports">
<source>Adding missing imports...</source>
<target state="translated">Adicionando as importações ausentes...</target>
<note>Thread awaited dialog text. "imports" is a language specific term and should not be localized</note>
</trans-unit>
<trans-unit id="Case_Correction">
<source>Case Correction</source>
<target state="translated">Correção de Caso</target>
<note />
</trans-unit>
<trans-unit id="Correcting_word_casing">
<source>Correcting word casing...</source>
<target state="translated">Corrigindo maiúsculas e minúsculas de palavras...</target>
<note />
</trans-unit>
<trans-unit id="This_call_is_required_by_the_designer">
<source>This call is required by the designer.</source>
<target state="translated">Esta chamada é requerida pelo designer.</target>
<note />
</trans-unit>
<trans-unit id="Add_any_initialization_after_the_InitializeComponent_call">
<source>Add any initialization after the InitializeComponent() call.</source>
<target state="translated">Adicione qualquer inicialização após a chamada InitializeComponent().</target>
<note />
</trans-unit>
<trans-unit id="End_Construct">
<source>End Construct</source>
<target state="translated">Finalizar Construção</target>
<note />
</trans-unit>
<trans-unit id="Smart_Indenting">
<source>Smart Indenting</source>
<target state="translated">Recuo Inteligente</target>
<note />
</trans-unit>
<trans-unit id="Formatting_Document">
<source>Formatting Document...</source>
<target state="translated">Formatando documento...</target>
<note />
</trans-unit>
<trans-unit id="Insert_new_line">
<source>Insert new line</source>
<target state="translated">Inserir Nova Linha</target>
<note />
</trans-unit>
<trans-unit id="Format_Paste">
<source>Format Paste</source>
<target state="translated">Colar Formato</target>
<note />
</trans-unit>
<trans-unit id="Formatting_pasted_text">
<source>Formatting pasted text...</source>
<target state="translated">Formatando texto colado...</target>
<note />
</trans-unit>
<trans-unit id="Paste">
<source>Paste</source>
<target state="translated">Colar</target>
<note />
</trans-unit>
<trans-unit id="Format_on_Save">
<source>Format on Save</source>
<target state="translated">Formatar em Salvar</target>
<note />
</trans-unit>
<trans-unit id="Committing_line">
<source>Committing line</source>
<target state="translated">Confirmando linha</target>
<note />
</trans-unit>
<trans-unit id="Visual_Basic_Pretty_List">
<source>Visual Basic Pretty List</source>
<target state="translated">Reformatação Automática do Visual Basic</target>
<note />
</trans-unit>
<trans-unit id="not_supported">
<source>not supported</source>
<target state="translated">não suportado</target>
<note />
</trans-unit>
<trans-unit id="Generate_Member">
<source>Generate Member</source>
<target state="translated">Gerar Membro</target>
<note />
</trans-unit>
<trans-unit id="Line_commit">
<source>Line commit</source>
<target state="translated">Confirmação de linha</target>
<note />
</trans-unit>
<trans-unit id="Implement_Abstract_Class_Or_Interface">
<source>Implement Abstract Class Or Interface</source>
<target state="translated">Implementar Classe Abstrata ou Interface</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="pt-BR" original="../VBEditorResources.resx">
<body>
<trans-unit id="Add_Missing_Imports_on_Paste">
<source>Add Missing Imports on Paste</source>
<target state="translated">Adicionar as Importações Ausentes ao Colar</target>
<note>"imports" is a language specific term and should not be localized</note>
</trans-unit>
<trans-unit id="Adding_missing_imports">
<source>Adding missing imports...</source>
<target state="translated">Adicionando as importações ausentes...</target>
<note>Thread awaited dialog text. "imports" is a language specific term and should not be localized</note>
</trans-unit>
<trans-unit id="Case_Correction">
<source>Case Correction</source>
<target state="translated">Correção de Caso</target>
<note />
</trans-unit>
<trans-unit id="Correcting_word_casing">
<source>Correcting word casing...</source>
<target state="translated">Corrigindo maiúsculas e minúsculas de palavras...</target>
<note />
</trans-unit>
<trans-unit id="This_call_is_required_by_the_designer">
<source>This call is required by the designer.</source>
<target state="translated">Esta chamada é requerida pelo designer.</target>
<note />
</trans-unit>
<trans-unit id="Add_any_initialization_after_the_InitializeComponent_call">
<source>Add any initialization after the InitializeComponent() call.</source>
<target state="translated">Adicione qualquer inicialização após a chamada InitializeComponent().</target>
<note />
</trans-unit>
<trans-unit id="End_Construct">
<source>End Construct</source>
<target state="translated">Finalizar Construção</target>
<note />
</trans-unit>
<trans-unit id="Smart_Indenting">
<source>Smart Indenting</source>
<target state="translated">Recuo Inteligente</target>
<note />
</trans-unit>
<trans-unit id="Formatting_Document">
<source>Formatting Document...</source>
<target state="translated">Formatando documento...</target>
<note />
</trans-unit>
<trans-unit id="Insert_new_line">
<source>Insert new line</source>
<target state="translated">Inserir Nova Linha</target>
<note />
</trans-unit>
<trans-unit id="Format_Paste">
<source>Format Paste</source>
<target state="translated">Colar Formato</target>
<note />
</trans-unit>
<trans-unit id="Formatting_pasted_text">
<source>Formatting pasted text...</source>
<target state="translated">Formatando texto colado...</target>
<note />
</trans-unit>
<trans-unit id="Paste">
<source>Paste</source>
<target state="translated">Colar</target>
<note />
</trans-unit>
<trans-unit id="Format_on_Save">
<source>Format on Save</source>
<target state="translated">Formatar em Salvar</target>
<note />
</trans-unit>
<trans-unit id="Committing_line">
<source>Committing line</source>
<target state="translated">Confirmando linha</target>
<note />
</trans-unit>
<trans-unit id="Visual_Basic_Pretty_List">
<source>Visual Basic Pretty List</source>
<target state="translated">Reformatação Automática do Visual Basic</target>
<note />
</trans-unit>
<trans-unit id="not_supported">
<source>not supported</source>
<target state="translated">não suportado</target>
<note />
</trans-unit>
<trans-unit id="Generate_Member">
<source>Generate Member</source>
<target state="translated">Gerar Membro</target>
<note />
</trans-unit>
<trans-unit id="Line_commit">
<source>Line commit</source>
<target state="translated">Confirmação de linha</target>
<note />
</trans-unit>
<trans-unit id="Implement_Abstract_Class_Or_Interface">
<source>Implement Abstract Class Or Interface</source>
<target state="translated">Implementar Classe Abstrata ou Interface</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,971 | Theme some dialogs | Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ryzngard | "2021-08-27T20:10:35Z" | "2022-07-12T20:08:34Z" | 07297d927b3ffd4d44f048602950947e9a040dd2 | 2cd995df98f17f1ceebba0d93729d8a4336ebe26 | Theme some dialogs. Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ForStatement.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter
{
public override BoundNode VisitForStatement(BoundForStatement node)
{
Debug.Assert(node != null);
var rewrittenInitializer = VisitStatement(node.Initializer);
var rewrittenCondition = VisitExpression(node.Condition);
var rewrittenIncrement = VisitStatement(node.Increment);
var rewrittenBody = VisitStatement(node.Body);
Debug.Assert(rewrittenBody is { });
// EnC: We need to insert a hidden sequence point to handle function remapping in case
// the containing method is edited while methods invoked in the condition are being executed.
if (rewrittenCondition != null && this.Instrument)
{
rewrittenCondition = _instrumenter.InstrumentForStatementCondition(node, rewrittenCondition, _factory);
}
return RewriteForStatement(
node,
rewrittenInitializer,
rewrittenCondition,
rewrittenIncrement,
rewrittenBody);
}
private BoundStatement RewriteForStatementWithoutInnerLocals(
BoundLoopStatement original,
ImmutableArray<LocalSymbol> outerLocals,
BoundStatement? rewrittenInitializer,
BoundExpression? rewrittenCondition,
BoundStatement? rewrittenIncrement,
BoundStatement rewrittenBody,
GeneratedLabelSymbol breakLabel,
GeneratedLabelSymbol continueLabel,
bool hasErrors)
{
Debug.Assert(original.Kind == BoundKind.ForStatement || original.Kind == BoundKind.ForEachStatement);
Debug.Assert(rewrittenBody != null);
// The sequence point behavior exhibited here is different from that of the native compiler. In the native
// compiler, if you have something like
//
// for([|int i = 0, j = 0|]; ; [|i++, j++|])
//
// then all the initializers are treated as a single sequence point, as are
// all the loop incrementors.
//
// We now make each one individually a sequence point:
//
// for([|int i = 0|], [|j = 0|]; ; [|i++|], [|j++|])
//
// If we decide that we want to preserve the native compiler stepping behavior
// then we'll need to be a bit fancy here. The initializer and increment statements
// can contain lambdas whose bodies need to have sequence points inserted, so we
// need to make sure we visit the children. But we'll also need to make sure that
// we do not generate one sequence point for each statement in the initializers
// and the incrementors.
SyntaxNode syntax = original.Syntax;
var statementBuilder = ArrayBuilder<BoundStatement>.GetInstance();
if (rewrittenInitializer != null)
{
statementBuilder.Add(rewrittenInitializer);
}
var startLabel = new GeneratedLabelSymbol("start");
// for (initializer; condition; increment)
// body;
//
// becomes the following (with block added for locals)
//
// {
// initializer;
// goto end;
// start:
// body;
// continue:
// increment;
// end:
// GotoIfTrue condition start;
// break:
// }
var endLabel = new GeneratedLabelSymbol("end");
// initializer;
// goto end;
BoundStatement gotoEnd = new BoundGotoStatement(syntax, endLabel);
if (this.Instrument)
{
// Mark the initial jump as hidden.
// We do it to tell that this is not a part of previous statement.
// This jump may be a target of another jump (for example if loops are nested) and that will make
// impression of the previous statement being re-executed
gotoEnd = BoundSequencePoint.CreateHidden(gotoEnd);
}
statementBuilder.Add(gotoEnd);
// start:
// body;
statementBuilder.Add(new BoundLabelStatement(syntax, startLabel));
statementBuilder.Add(rewrittenBody);
// continue:
// increment;
statementBuilder.Add(new BoundLabelStatement(syntax, continueLabel));
if (rewrittenIncrement != null)
{
statementBuilder.Add(rewrittenIncrement);
}
// end:
// GotoIfTrue condition start;
statementBuilder.Add(new BoundLabelStatement(syntax, endLabel));
BoundStatement? branchBack = null;
if (rewrittenCondition != null)
{
branchBack = new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, true, startLabel);
}
else
{
branchBack = new BoundGotoStatement(syntax, startLabel);
}
if (this.Instrument)
{
switch (original.Kind)
{
case BoundKind.ForEachStatement:
branchBack = _instrumenter.InstrumentForEachStatementConditionalGotoStart((BoundForEachStatement)original, branchBack);
break;
case BoundKind.ForStatement:
branchBack = _instrumenter.InstrumentForStatementConditionalGotoStartOrBreak((BoundForStatement)original, branchBack);
break;
default:
throw ExceptionUtilities.UnexpectedValue(original.Kind);
}
}
statementBuilder.Add(branchBack);
// break:
statementBuilder.Add(new BoundLabelStatement(syntax, breakLabel));
var statements = statementBuilder.ToImmutableAndFree();
return new BoundBlock(syntax, outerLocals, statements, hasErrors);
}
private BoundStatement RewriteForStatement(
BoundForStatement node,
BoundStatement? rewrittenInitializer,
BoundExpression? rewrittenCondition,
BoundStatement? rewrittenIncrement,
BoundStatement rewrittenBody)
{
if (node.InnerLocals.IsEmpty)
{
return RewriteForStatementWithoutInnerLocals(
node,
node.OuterLocals,
rewrittenInitializer,
rewrittenCondition,
rewrittenIncrement,
rewrittenBody,
node.BreakLabel,
node.ContinueLabel, node.HasErrors);
}
// We need to enter inner_scope-block from the top, that is where an instance of a display class will be created
// if any local is captured within a lambda.
// for (initializer; condition; increment)
// body;
//
// becomes the following (with block added for locals)
//
// {
// initializer;
// start:
// {
// GotoIfFalse condition break;
// body;
// continue:
// increment;
// goto start;
// }
// break:
// }
Debug.Assert(rewrittenBody != null);
SyntaxNode syntax = node.Syntax;
var statementBuilder = ArrayBuilder<BoundStatement>.GetInstance();
// initializer;
if (rewrittenInitializer != null)
{
statementBuilder.Add(rewrittenInitializer);
}
var startLabel = new GeneratedLabelSymbol("start");
// start:
BoundStatement startLabelStatement = new BoundLabelStatement(syntax, startLabel);
if (Instrument)
{
startLabelStatement = BoundSequencePoint.CreateHidden(startLabelStatement);
}
statementBuilder.Add(startLabelStatement);
var blockBuilder = ArrayBuilder<BoundStatement>.GetInstance();
// GotoIfFalse condition break;
if (rewrittenCondition != null)
{
BoundStatement ifNotConditionGotoBreak = new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, false, node.BreakLabel);
if (this.Instrument)
{
ifNotConditionGotoBreak = _instrumenter.InstrumentForStatementConditionalGotoStartOrBreak(node, ifNotConditionGotoBreak);
}
blockBuilder.Add(ifNotConditionGotoBreak);
}
// body;
blockBuilder.Add(rewrittenBody);
// continue:
// increment;
blockBuilder.Add(new BoundLabelStatement(syntax, node.ContinueLabel));
if (rewrittenIncrement != null)
{
blockBuilder.Add(rewrittenIncrement);
}
// goto start;
blockBuilder.Add(new BoundGotoStatement(syntax, startLabel));
statementBuilder.Add(new BoundBlock(syntax, node.InnerLocals, blockBuilder.ToImmutableAndFree()));
// break:
statementBuilder.Add(new BoundLabelStatement(syntax, node.BreakLabel));
var statements = statementBuilder.ToImmutableAndFree();
return new BoundBlock(syntax, node.OuterLocals, statements, node.HasErrors);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter
{
public override BoundNode VisitForStatement(BoundForStatement node)
{
Debug.Assert(node != null);
var rewrittenInitializer = VisitStatement(node.Initializer);
var rewrittenCondition = VisitExpression(node.Condition);
var rewrittenIncrement = VisitStatement(node.Increment);
var rewrittenBody = VisitStatement(node.Body);
Debug.Assert(rewrittenBody is { });
// EnC: We need to insert a hidden sequence point to handle function remapping in case
// the containing method is edited while methods invoked in the condition are being executed.
if (rewrittenCondition != null && this.Instrument)
{
rewrittenCondition = _instrumenter.InstrumentForStatementCondition(node, rewrittenCondition, _factory);
}
return RewriteForStatement(
node,
rewrittenInitializer,
rewrittenCondition,
rewrittenIncrement,
rewrittenBody);
}
private BoundStatement RewriteForStatementWithoutInnerLocals(
BoundLoopStatement original,
ImmutableArray<LocalSymbol> outerLocals,
BoundStatement? rewrittenInitializer,
BoundExpression? rewrittenCondition,
BoundStatement? rewrittenIncrement,
BoundStatement rewrittenBody,
GeneratedLabelSymbol breakLabel,
GeneratedLabelSymbol continueLabel,
bool hasErrors)
{
Debug.Assert(original.Kind == BoundKind.ForStatement || original.Kind == BoundKind.ForEachStatement);
Debug.Assert(rewrittenBody != null);
// The sequence point behavior exhibited here is different from that of the native compiler. In the native
// compiler, if you have something like
//
// for([|int i = 0, j = 0|]; ; [|i++, j++|])
//
// then all the initializers are treated as a single sequence point, as are
// all the loop incrementors.
//
// We now make each one individually a sequence point:
//
// for([|int i = 0|], [|j = 0|]; ; [|i++|], [|j++|])
//
// If we decide that we want to preserve the native compiler stepping behavior
// then we'll need to be a bit fancy here. The initializer and increment statements
// can contain lambdas whose bodies need to have sequence points inserted, so we
// need to make sure we visit the children. But we'll also need to make sure that
// we do not generate one sequence point for each statement in the initializers
// and the incrementors.
SyntaxNode syntax = original.Syntax;
var statementBuilder = ArrayBuilder<BoundStatement>.GetInstance();
if (rewrittenInitializer != null)
{
statementBuilder.Add(rewrittenInitializer);
}
var startLabel = new GeneratedLabelSymbol("start");
// for (initializer; condition; increment)
// body;
//
// becomes the following (with block added for locals)
//
// {
// initializer;
// goto end;
// start:
// body;
// continue:
// increment;
// end:
// GotoIfTrue condition start;
// break:
// }
var endLabel = new GeneratedLabelSymbol("end");
// initializer;
// goto end;
BoundStatement gotoEnd = new BoundGotoStatement(syntax, endLabel);
if (this.Instrument)
{
// Mark the initial jump as hidden.
// We do it to tell that this is not a part of previous statement.
// This jump may be a target of another jump (for example if loops are nested) and that will make
// impression of the previous statement being re-executed
gotoEnd = BoundSequencePoint.CreateHidden(gotoEnd);
}
statementBuilder.Add(gotoEnd);
// start:
// body;
statementBuilder.Add(new BoundLabelStatement(syntax, startLabel));
statementBuilder.Add(rewrittenBody);
// continue:
// increment;
statementBuilder.Add(new BoundLabelStatement(syntax, continueLabel));
if (rewrittenIncrement != null)
{
statementBuilder.Add(rewrittenIncrement);
}
// end:
// GotoIfTrue condition start;
statementBuilder.Add(new BoundLabelStatement(syntax, endLabel));
BoundStatement? branchBack = null;
if (rewrittenCondition != null)
{
branchBack = new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, true, startLabel);
}
else
{
branchBack = new BoundGotoStatement(syntax, startLabel);
}
if (this.Instrument)
{
switch (original.Kind)
{
case BoundKind.ForEachStatement:
branchBack = _instrumenter.InstrumentForEachStatementConditionalGotoStart((BoundForEachStatement)original, branchBack);
break;
case BoundKind.ForStatement:
branchBack = _instrumenter.InstrumentForStatementConditionalGotoStartOrBreak((BoundForStatement)original, branchBack);
break;
default:
throw ExceptionUtilities.UnexpectedValue(original.Kind);
}
}
statementBuilder.Add(branchBack);
// break:
statementBuilder.Add(new BoundLabelStatement(syntax, breakLabel));
var statements = statementBuilder.ToImmutableAndFree();
return new BoundBlock(syntax, outerLocals, statements, hasErrors);
}
private BoundStatement RewriteForStatement(
BoundForStatement node,
BoundStatement? rewrittenInitializer,
BoundExpression? rewrittenCondition,
BoundStatement? rewrittenIncrement,
BoundStatement rewrittenBody)
{
if (node.InnerLocals.IsEmpty)
{
return RewriteForStatementWithoutInnerLocals(
node,
node.OuterLocals,
rewrittenInitializer,
rewrittenCondition,
rewrittenIncrement,
rewrittenBody,
node.BreakLabel,
node.ContinueLabel, node.HasErrors);
}
// We need to enter inner_scope-block from the top, that is where an instance of a display class will be created
// if any local is captured within a lambda.
// for (initializer; condition; increment)
// body;
//
// becomes the following (with block added for locals)
//
// {
// initializer;
// start:
// {
// GotoIfFalse condition break;
// body;
// continue:
// increment;
// goto start;
// }
// break:
// }
Debug.Assert(rewrittenBody != null);
SyntaxNode syntax = node.Syntax;
var statementBuilder = ArrayBuilder<BoundStatement>.GetInstance();
// initializer;
if (rewrittenInitializer != null)
{
statementBuilder.Add(rewrittenInitializer);
}
var startLabel = new GeneratedLabelSymbol("start");
// start:
BoundStatement startLabelStatement = new BoundLabelStatement(syntax, startLabel);
if (Instrument)
{
startLabelStatement = BoundSequencePoint.CreateHidden(startLabelStatement);
}
statementBuilder.Add(startLabelStatement);
var blockBuilder = ArrayBuilder<BoundStatement>.GetInstance();
// GotoIfFalse condition break;
if (rewrittenCondition != null)
{
BoundStatement ifNotConditionGotoBreak = new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, false, node.BreakLabel);
if (this.Instrument)
{
ifNotConditionGotoBreak = _instrumenter.InstrumentForStatementConditionalGotoStartOrBreak(node, ifNotConditionGotoBreak);
}
blockBuilder.Add(ifNotConditionGotoBreak);
}
// body;
blockBuilder.Add(rewrittenBody);
// continue:
// increment;
blockBuilder.Add(new BoundLabelStatement(syntax, node.ContinueLabel));
if (rewrittenIncrement != null)
{
blockBuilder.Add(rewrittenIncrement);
}
// goto start;
blockBuilder.Add(new BoundGotoStatement(syntax, startLabel));
statementBuilder.Add(new BoundBlock(syntax, node.InnerLocals, blockBuilder.ToImmutableAndFree()));
// break:
statementBuilder.Add(new BoundLabelStatement(syntax, node.BreakLabel));
var statements = statementBuilder.ToImmutableAndFree();
return new BoundBlock(syntax, node.OuterLocals, statements, node.HasErrors);
}
}
}
| -1 |
dotnet/roslyn | 55,971 | Theme some dialogs | Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ryzngard | "2021-08-27T20:10:35Z" | "2022-07-12T20:08:34Z" | 07297d927b3ffd4d44f048602950947e9a040dd2 | 2cd995df98f17f1ceebba0d93729d8a4336ebe26 | Theme some dialogs. Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ./src/Compilers/Core/Portable/Desktop/AssemblyVersion.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Microsoft.CodeAnalysis
{
internal struct AssemblyVersion : IEquatable<AssemblyVersion>, IComparable<AssemblyVersion>
{
private readonly ushort _major;
private readonly ushort _minor;
private readonly ushort _build;
private readonly ushort _revision;
public AssemblyVersion(ushort major, ushort minor, ushort build, ushort revision)
{
_major = major;
_minor = minor;
_build = build;
_revision = revision;
}
public int Major
{
get { return _major; }
}
public int Minor
{
get { return _minor; }
}
public int Build
{
get { return _build; }
}
public int Revision
{
get { return _revision; }
}
private ulong ToInteger()
{
return ((ulong)_major << 48) | ((ulong)_minor << 32) | ((ulong)_build << 16) | _revision;
}
public int CompareTo(AssemblyVersion other)
{
var left = ToInteger();
var right = other.ToInteger();
return (left == right) ? 0 : (left < right) ? -1 : +1;
}
public bool Equals(AssemblyVersion other)
{
return ToInteger() == other.ToInteger();
}
public override bool Equals(object obj)
{
return obj is AssemblyVersion && Equals((AssemblyVersion)obj);
}
public override int GetHashCode()
{
return ((_major & 0x000f) << 28) | ((_minor & 0x00ff) << 20) | ((_build & 0x00ff) << 12) | (_revision & 0x0fff);
}
public static bool operator ==(AssemblyVersion left, AssemblyVersion right)
{
return left.Equals(right);
}
public static bool operator !=(AssemblyVersion left, AssemblyVersion right)
{
return !left.Equals(right);
}
public static bool operator <(AssemblyVersion left, AssemblyVersion right)
{
return left.ToInteger() < right.ToInteger();
}
public static bool operator <=(AssemblyVersion left, AssemblyVersion right)
{
return left.ToInteger() <= right.ToInteger();
}
public static bool operator >(AssemblyVersion left, AssemblyVersion right)
{
return left.ToInteger() > right.ToInteger();
}
public static bool operator >=(AssemblyVersion left, AssemblyVersion right)
{
return left.ToInteger() >= right.ToInteger();
}
/// <summary>
/// Converts <see cref="Version"/> to <see cref="AssemblyVersion"/>.
/// </summary>
/// <exception cref="InvalidCastException">Major, minor, build or revision number are less than 0 or greater than 0xFFFF.</exception>
public static explicit operator AssemblyVersion(Version version)
{
return new AssemblyVersion((ushort)version.Major, (ushort)version.Minor, (ushort)version.Build, (ushort)version.Revision);
}
public static explicit operator Version(AssemblyVersion version)
{
return new Version(version.Major, version.Minor, version.Build, version.Revision);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Microsoft.CodeAnalysis
{
internal struct AssemblyVersion : IEquatable<AssemblyVersion>, IComparable<AssemblyVersion>
{
private readonly ushort _major;
private readonly ushort _minor;
private readonly ushort _build;
private readonly ushort _revision;
public AssemblyVersion(ushort major, ushort minor, ushort build, ushort revision)
{
_major = major;
_minor = minor;
_build = build;
_revision = revision;
}
public int Major
{
get { return _major; }
}
public int Minor
{
get { return _minor; }
}
public int Build
{
get { return _build; }
}
public int Revision
{
get { return _revision; }
}
private ulong ToInteger()
{
return ((ulong)_major << 48) | ((ulong)_minor << 32) | ((ulong)_build << 16) | _revision;
}
public int CompareTo(AssemblyVersion other)
{
var left = ToInteger();
var right = other.ToInteger();
return (left == right) ? 0 : (left < right) ? -1 : +1;
}
public bool Equals(AssemblyVersion other)
{
return ToInteger() == other.ToInteger();
}
public override bool Equals(object obj)
{
return obj is AssemblyVersion && Equals((AssemblyVersion)obj);
}
public override int GetHashCode()
{
return ((_major & 0x000f) << 28) | ((_minor & 0x00ff) << 20) | ((_build & 0x00ff) << 12) | (_revision & 0x0fff);
}
public static bool operator ==(AssemblyVersion left, AssemblyVersion right)
{
return left.Equals(right);
}
public static bool operator !=(AssemblyVersion left, AssemblyVersion right)
{
return !left.Equals(right);
}
public static bool operator <(AssemblyVersion left, AssemblyVersion right)
{
return left.ToInteger() < right.ToInteger();
}
public static bool operator <=(AssemblyVersion left, AssemblyVersion right)
{
return left.ToInteger() <= right.ToInteger();
}
public static bool operator >(AssemblyVersion left, AssemblyVersion right)
{
return left.ToInteger() > right.ToInteger();
}
public static bool operator >=(AssemblyVersion left, AssemblyVersion right)
{
return left.ToInteger() >= right.ToInteger();
}
/// <summary>
/// Converts <see cref="Version"/> to <see cref="AssemblyVersion"/>.
/// </summary>
/// <exception cref="InvalidCastException">Major, minor, build or revision number are less than 0 or greater than 0xFFFF.</exception>
public static explicit operator AssemblyVersion(Version version)
{
return new AssemblyVersion((ushort)version.Major, (ushort)version.Minor, (ushort)version.Build, (ushort)version.Revision);
}
public static explicit operator Version(AssemblyVersion version)
{
return new Version(version.Major, version.Minor, version.Build, version.Revision);
}
}
}
| -1 |
dotnet/roslyn | 55,971 | Theme some dialogs | Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ryzngard | "2021-08-27T20:10:35Z" | "2022-07-12T20:08:34Z" | 07297d927b3ffd4d44f048602950947e9a040dd2 | 2cd995df98f17f1ceebba0d93729d8a4336ebe26 | Theme some dialogs. Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ./src/Compilers/CSharp/Portable/Symbols/MissingAssemblySymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Collections.ObjectModel;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// A <see cref="MissingAssemblySymbol"/> is a special kind of <see cref="AssemblySymbol"/> that represents
/// an assembly that couldn't be found.
/// </summary>
internal class MissingAssemblySymbol : AssemblySymbol
{
protected readonly AssemblyIdentity identity;
protected readonly MissingModuleSymbol moduleSymbol;
private ImmutableArray<ModuleSymbol> _lazyModules;
public MissingAssemblySymbol(AssemblyIdentity identity)
{
Debug.Assert(identity != null);
this.identity = identity;
moduleSymbol = new MissingModuleSymbol(this, 0);
}
internal sealed override bool IsMissing
{
get
{
return true;
}
}
internal override bool IsLinked
{
get
{
return false;
}
}
internal override Symbol GetDeclaredSpecialTypeMember(SpecialMember member)
{
return null;
}
public override AssemblyIdentity Identity
{
get
{
return identity;
}
}
public override Version AssemblyVersionPattern => null;
internal override ImmutableArray<byte> PublicKey
{
get { return Identity.PublicKey; }
}
public override ImmutableArray<ModuleSymbol> Modules
{
get
{
if (_lazyModules.IsDefault)
{
_lazyModules = ImmutableArray.Create<ModuleSymbol>(moduleSymbol);
}
return _lazyModules;
}
}
public override int GetHashCode()
{
return identity.GetHashCode();
}
public override bool Equals(Symbol obj, TypeCompareKind compareKind)
{
return Equals(obj as MissingAssemblySymbol);
}
public bool Equals(MissingAssemblySymbol other)
{
if ((object)other == null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return identity.Equals(other.Identity);
}
public override ImmutableArray<Location> Locations
{
get
{
return ImmutableArray<Location>.Empty;
}
}
internal override void SetLinkedReferencedAssemblies(ImmutableArray<AssemblySymbol> assemblies)
{
throw ExceptionUtilities.Unreachable;
}
internal override ImmutableArray<AssemblySymbol> GetLinkedReferencedAssemblies()
{
return ImmutableArray<AssemblySymbol>.Empty;
}
internal override void SetNoPiaResolutionAssemblies(ImmutableArray<AssemblySymbol> assemblies)
{
throw ExceptionUtilities.Unreachable;
}
internal override ImmutableArray<AssemblySymbol> GetNoPiaResolutionAssemblies()
{
return ImmutableArray<AssemblySymbol>.Empty;
}
public sealed override NamespaceSymbol GlobalNamespace
{
get
{
return this.moduleSymbol.GlobalNamespace;
}
}
public override ICollection<string> TypeNames
{
get
{
return SpecializedCollections.EmptyCollection<string>();
}
}
public override ICollection<string> NamespaceNames
{
get
{
return SpecializedCollections.EmptyCollection<string>();
}
}
internal override NamedTypeSymbol LookupTopLevelMetadataTypeWithCycleDetection(ref MetadataTypeName emittedName, ConsList<AssemblySymbol> visitedAssemblies, bool digThroughForwardedTypes)
{
var result = this.moduleSymbol.LookupTopLevelMetadataType(ref emittedName);
Debug.Assert(result is MissingMetadataTypeSymbol);
return result;
}
internal override NamedTypeSymbol GetDeclaredSpecialType(SpecialType type)
{
throw ExceptionUtilities.Unreachable;
}
internal override bool AreInternalsVisibleToThisAssembly(AssemblySymbol other)
{
return false;
}
internal override IEnumerable<ImmutableArray<byte>> GetInternalsVisibleToPublicKeys(string simpleName)
{
return SpecializedCollections.EmptyEnumerable<ImmutableArray<byte>>();
}
public override bool MightContainExtensionMethods
{
get
{
return false;
}
}
public override AssemblyMetadata GetMetadata() => null;
internal sealed override IEnumerable<NamedTypeSymbol> GetAllTopLevelForwardedTypes()
{
return SpecializedCollections.EmptyEnumerable<NamedTypeSymbol>();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Collections.ObjectModel;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// A <see cref="MissingAssemblySymbol"/> is a special kind of <see cref="AssemblySymbol"/> that represents
/// an assembly that couldn't be found.
/// </summary>
internal class MissingAssemblySymbol : AssemblySymbol
{
protected readonly AssemblyIdentity identity;
protected readonly MissingModuleSymbol moduleSymbol;
private ImmutableArray<ModuleSymbol> _lazyModules;
public MissingAssemblySymbol(AssemblyIdentity identity)
{
Debug.Assert(identity != null);
this.identity = identity;
moduleSymbol = new MissingModuleSymbol(this, 0);
}
internal sealed override bool IsMissing
{
get
{
return true;
}
}
internal override bool IsLinked
{
get
{
return false;
}
}
internal override Symbol GetDeclaredSpecialTypeMember(SpecialMember member)
{
return null;
}
public override AssemblyIdentity Identity
{
get
{
return identity;
}
}
public override Version AssemblyVersionPattern => null;
internal override ImmutableArray<byte> PublicKey
{
get { return Identity.PublicKey; }
}
public override ImmutableArray<ModuleSymbol> Modules
{
get
{
if (_lazyModules.IsDefault)
{
_lazyModules = ImmutableArray.Create<ModuleSymbol>(moduleSymbol);
}
return _lazyModules;
}
}
public override int GetHashCode()
{
return identity.GetHashCode();
}
public override bool Equals(Symbol obj, TypeCompareKind compareKind)
{
return Equals(obj as MissingAssemblySymbol);
}
public bool Equals(MissingAssemblySymbol other)
{
if ((object)other == null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return identity.Equals(other.Identity);
}
public override ImmutableArray<Location> Locations
{
get
{
return ImmutableArray<Location>.Empty;
}
}
internal override void SetLinkedReferencedAssemblies(ImmutableArray<AssemblySymbol> assemblies)
{
throw ExceptionUtilities.Unreachable;
}
internal override ImmutableArray<AssemblySymbol> GetLinkedReferencedAssemblies()
{
return ImmutableArray<AssemblySymbol>.Empty;
}
internal override void SetNoPiaResolutionAssemblies(ImmutableArray<AssemblySymbol> assemblies)
{
throw ExceptionUtilities.Unreachable;
}
internal override ImmutableArray<AssemblySymbol> GetNoPiaResolutionAssemblies()
{
return ImmutableArray<AssemblySymbol>.Empty;
}
public sealed override NamespaceSymbol GlobalNamespace
{
get
{
return this.moduleSymbol.GlobalNamespace;
}
}
public override ICollection<string> TypeNames
{
get
{
return SpecializedCollections.EmptyCollection<string>();
}
}
public override ICollection<string> NamespaceNames
{
get
{
return SpecializedCollections.EmptyCollection<string>();
}
}
internal override NamedTypeSymbol LookupTopLevelMetadataTypeWithCycleDetection(ref MetadataTypeName emittedName, ConsList<AssemblySymbol> visitedAssemblies, bool digThroughForwardedTypes)
{
var result = this.moduleSymbol.LookupTopLevelMetadataType(ref emittedName);
Debug.Assert(result is MissingMetadataTypeSymbol);
return result;
}
internal override NamedTypeSymbol GetDeclaredSpecialType(SpecialType type)
{
throw ExceptionUtilities.Unreachable;
}
internal override bool AreInternalsVisibleToThisAssembly(AssemblySymbol other)
{
return false;
}
internal override IEnumerable<ImmutableArray<byte>> GetInternalsVisibleToPublicKeys(string simpleName)
{
return SpecializedCollections.EmptyEnumerable<ImmutableArray<byte>>();
}
public override bool MightContainExtensionMethods
{
get
{
return false;
}
}
public override AssemblyMetadata GetMetadata() => null;
internal sealed override IEnumerable<NamedTypeSymbol> GetAllTopLevelForwardedTypes()
{
return SpecializedCollections.EmptyEnumerable<NamedTypeSymbol>();
}
}
}
| -1 |
dotnet/roslyn | 55,971 | Theme some dialogs | Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ryzngard | "2021-08-27T20:10:35Z" | "2022-07-12T20:08:34Z" | 07297d927b3ffd4d44f048602950947e9a040dd2 | 2cd995df98f17f1ceebba0d93729d8a4336ebe26 | Theme some dialogs. Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ./src/Compilers/Core/CodeAnalysisTest/Collections/TestExtensionsMethods.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections.Immutable/tests/TestExtensionsMethods.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
internal static partial class TestExtensionsMethods
{
internal static void ValidateDefaultThisBehavior(Action a)
{
Assert.Throws<NullReferenceException>(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.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections.Immutable/tests/TestExtensionsMethods.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
internal static partial class TestExtensionsMethods
{
internal static void ValidateDefaultThisBehavior(Action a)
{
Assert.Throws<NullReferenceException>(a);
}
}
}
| -1 |
dotnet/roslyn | 55,971 | Theme some dialogs | Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ryzngard | "2021-08-27T20:10:35Z" | "2022-07-12T20:08:34Z" | 07297d927b3ffd4d44f048602950947e9a040dd2 | 2cd995df98f17f1ceebba0d93729d8a4336ebe26 | Theme some dialogs. Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ./src/VisualStudio/Core/Def/TableDataSource/VisualStudioBaseDiagnosticListTable.LiveTableDataSource.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Threading;
using System.Windows;
using System.Windows.Controls;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Common;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Options;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Shell.TableManager;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
{
internal abstract partial class VisualStudioBaseDiagnosticListTable
{
/// <summary>
/// Used by the editor to signify that errors added to the error list
/// should not be copied to the guest. Instead they will be published via LSP.
/// </summary>
private const string DoNotPropogateToGuestProperty = "DoNotPropagateToGuests";
/// <summary>
/// Error list diagnostic source for "Build + Intellisense" setting.
/// See <see cref="VisualStudioDiagnosticListTableWorkspaceEventListener.VisualStudioDiagnosticListTable.BuildTableDataSource"/>
/// for error list diagnostic source for "Build only" setting.
/// </summary>
protected class LiveTableDataSource : AbstractRoslynTableDataSource<DiagnosticTableItem, DiagnosticsUpdatedArgs>
{
private readonly string _identifier;
private readonly IDiagnosticService _diagnosticService;
private readonly Workspace _workspace;
private readonly OpenDocumentTracker<DiagnosticTableItem> _tracker;
/// <summary>
/// Flag indicating if a build inside Visual Studio is in progress.
/// We get build progress updates from <see cref="ExternalErrorDiagnosticUpdateSource.BuildProgressChanged"/>.
/// Build progress events are guaranteed to be invoked in a serial fashion during build.
/// </summary>
private bool _isBuildRunning;
public LiveTableDataSource(Workspace workspace, IThreadingContext threadingContext, IDiagnosticService diagnosticService, string identifier, ExternalErrorDiagnosticUpdateSource? buildUpdateSource = null)
: base(workspace, threadingContext)
{
_workspace = workspace;
_identifier = identifier;
_tracker = new OpenDocumentTracker<DiagnosticTableItem>(_workspace);
_diagnosticService = diagnosticService;
ConnectToDiagnosticService(workspace, diagnosticService);
ConnectToBuildUpdateSource(buildUpdateSource);
}
public IGlobalOptionService GlobalOptions => _diagnosticService.GlobalOptions;
public override string DisplayName => ServicesVSResources.CSharp_VB_Diagnostics_Table_Data_Source;
public override string SourceTypeIdentifier => StandardTableDataSources.ErrorTableDataSource;
public override string Identifier => _identifier;
public override object GetItemKey(DiagnosticsUpdatedArgs data) => data.Id;
private void ConnectToBuildUpdateSource(ExternalErrorDiagnosticUpdateSource? buildUpdateSource)
{
if (buildUpdateSource == null)
{
// it can be null in unit test
return;
}
OnBuildProgressChanged(buildUpdateSource.IsInProgress);
buildUpdateSource.BuildProgressChanged +=
(_, progress) => OnBuildProgressChanged(running: progress != ExternalErrorDiagnosticUpdateSource.BuildProgress.Done);
}
private void OnBuildProgressChanged(bool running)
{
_isBuildRunning = running;
// We mark error list "Build + Intellisense" setting as stable,
// i.e. shown as "Error List" without the trailing "...", if both the following are true:
// 1. User invoked build is not running inside Visual Studio AND
// 2. Solution crawler is not running in background to compute intellisense diagnostics.
ChangeStableStateIfRequired(newIsStable: !_isBuildRunning && !IsSolutionCrawlerRunning);
}
public override AbstractTableEntriesSnapshot<DiagnosticTableItem> CreateSnapshot(
AbstractTableEntriesSource<DiagnosticTableItem> source,
int version,
ImmutableArray<DiagnosticTableItem> items,
ImmutableArray<ITrackingPoint> trackingPoints)
{
var diagnosticSource = (DiagnosticTableEntriesSource)source;
var snapshot = new TableEntriesSnapshot(ThreadingContext, diagnosticSource, version, items, trackingPoints);
if (diagnosticSource.SupportSpanTracking && !trackingPoints.IsDefaultOrEmpty)
{
// track the open document so that we can throw away tracking points on document close properly
_tracker.TrackOpenDocument(diagnosticSource.TrackingDocumentId, diagnosticSource.Key, snapshot);
}
return snapshot;
}
protected override object GetOrUpdateAggregationKey(DiagnosticsUpdatedArgs data)
{
var key = TryGetAggregateKey(data);
if (key == null)
{
key = CreateAggregationKey(data);
AddAggregateKey(data, key);
return key;
}
if (!CheckAggregateKey(key as AggregatedKey, data))
{
RemoveStaledData(data);
key = CreateAggregationKey(data);
AddAggregateKey(data, key);
}
return key;
}
private bool CheckAggregateKey(AggregatedKey? key, DiagnosticsUpdatedArgs? args)
{
if (key == null)
{
return true;
}
if (args?.DocumentId == null || args?.Solution == null)
{
return true;
}
var documents = GetDocumentsWithSameFilePath(args.Solution, args.DocumentId);
return key.DocumentIds == documents;
}
private object CreateAggregationKey(DiagnosticsUpdatedArgs data)
{
if (data.DocumentId == null || data.Solution == null)
return GetItemKey(data);
if (data.Id is not LiveDiagnosticUpdateArgsId liveArgsId)
return GetItemKey(data);
var documents = GetDocumentsWithSameFilePath(data.Solution, data.DocumentId);
return new AggregatedKey(documents, liveArgsId.Analyzer, liveArgsId.Kind);
}
private void PopulateInitialData(Workspace workspace, IDiagnosticService diagnosticService)
{
var diagnosticMode = GlobalOptions.GetDiagnosticMode(InternalDiagnosticsOptions.NormalDiagnosticMode);
var diagnostics = diagnosticService.GetPushDiagnosticBuckets(
workspace, projectId: null, documentId: null, diagnosticMode, cancellationToken: CancellationToken.None);
foreach (var bucket in diagnostics)
{
// We only need to issue an event to VS that these docs have diagnostics associated with them. So
// we create a dummy notification for this. It doesn't matter that it is 'DiagnosticsRemoved' as
// this doesn't actually change any data. All that will happen now is that VS will call back into
// us for these IDs and we'll fetch the diagnostics at that point.
OnDataAddedOrChanged(DiagnosticsUpdatedArgs.DiagnosticsRemoved(
bucket.Id, bucket.Workspace, solution: null, bucket.ProjectId, bucket.DocumentId));
}
}
private void OnDiagnosticsUpdated(object sender, DiagnosticsUpdatedArgs e)
{
using (Logger.LogBlock(FunctionId.LiveTableDataSource_OnDiagnosticsUpdated, static arg => GetDiagnosticUpdatedMessage(arg.globalOptions, arg.e), (globalOptions: GlobalOptions, e), CancellationToken.None))
{
if (_workspace != e.Workspace)
{
return;
}
var diagnostics = e.GetPushDiagnostics(GlobalOptions, InternalDiagnosticsOptions.NormalDiagnosticMode);
if (diagnostics.Length == 0)
{
OnDataRemoved(e);
return;
}
var count = diagnostics.Where(ShouldInclude).Count();
if (count <= 0)
{
OnDataRemoved(e);
return;
}
OnDataAddedOrChanged(e);
}
}
public override AbstractTableEntriesSource<DiagnosticTableItem> CreateTableEntriesSource(object data)
{
var item = (UpdatedEventArgs)data;
return new TableEntriesSource(this, item.Workspace, GlobalOptions, item.ProjectId, item.DocumentId, item.Id);
}
private void ConnectToDiagnosticService(Workspace workspace, IDiagnosticService diagnosticService)
{
if (diagnosticService == null)
{
// it can be null in unit test
return;
}
_diagnosticService.DiagnosticsUpdated += OnDiagnosticsUpdated;
PopulateInitialData(workspace, diagnosticService);
}
private static bool ShouldInclude(DiagnosticData diagnostic)
{
if (diagnostic == null)
{
// guard us from wrong provider that gives null diagnostic
Debug.Assert(false, "Let's see who does this");
return false;
}
// If this diagnostic is for LSP only, then we won't show it here
if (diagnostic.Properties.ContainsKey(nameof(DocumentPropertiesService.DiagnosticsLspClientName)))
{
return false;
}
switch (diagnostic.Severity)
{
case DiagnosticSeverity.Info:
case DiagnosticSeverity.Warning:
case DiagnosticSeverity.Error:
return true;
case DiagnosticSeverity.Hidden:
default:
return false;
}
}
public override IEqualityComparer<DiagnosticTableItem> GroupingComparer
=> DiagnosticTableItem.GroupingComparer.Instance;
public override IEnumerable<DiagnosticTableItem> Order(IEnumerable<DiagnosticTableItem> groupedItems)
{
// this should make order of result always deterministic. we only need these 6 values since data with
// all these same will merged to one.
return groupedItems.OrderBy(d => d.Data.DataLocation?.OriginalStartLine ?? 0)
.ThenBy(d => d.Data.DataLocation?.OriginalStartColumn ?? 0)
.ThenBy(d => d.Data.Id)
.ThenBy(d => d.Data.Message)
.ThenBy(d => d.Data.DataLocation?.OriginalEndLine ?? 0)
.ThenBy(d => d.Data.DataLocation?.OriginalEndColumn ?? 0);
}
private class TableEntriesSource : DiagnosticTableEntriesSource
{
private readonly LiveTableDataSource _source;
private readonly Workspace _workspace;
private readonly IGlobalOptionService _globalOptions;
private readonly ProjectId? _projectId;
private readonly DocumentId? _documentId;
private readonly object _id;
private readonly string _buildTool;
public TableEntriesSource(LiveTableDataSource source, Workspace workspace, IGlobalOptionService globalOptions, ProjectId? projectId, DocumentId? documentId, object id)
{
_source = source;
_workspace = workspace;
_globalOptions = globalOptions;
_projectId = projectId;
_documentId = documentId;
_id = id;
_buildTool = (id as BuildToolId)?.BuildTool ?? string.Empty;
}
public override object Key => _id;
public override string BuildTool => _buildTool;
public override bool SupportSpanTracking => _documentId != null;
public override DocumentId? TrackingDocumentId => _documentId;
public override ImmutableArray<DiagnosticTableItem> GetItems()
{
var diagnosticMode = _globalOptions.GetDiagnosticMode(InternalDiagnosticsOptions.NormalDiagnosticMode);
var provider = _source._diagnosticService;
var items = provider.GetPushDiagnosticsAsync(_workspace, _projectId, _documentId, _id, includeSuppressedDiagnostics: true, diagnosticMode, cancellationToken: CancellationToken.None)
.AsTask()
.WaitAndGetResult_CanCallOnBackground(CancellationToken.None)
.Where(ShouldInclude)
.Select(data => DiagnosticTableItem.Create(_workspace, data));
return items.ToImmutableArray();
}
public override ImmutableArray<ITrackingPoint> GetTrackingPoints(ImmutableArray<DiagnosticTableItem> items)
=> _workspace.CreateTrackingPoints(_documentId, items);
}
private class TableEntriesSnapshot : AbstractTableEntriesSnapshot<DiagnosticTableItem>, IWpfTableEntriesSnapshot
{
private readonly DiagnosticTableEntriesSource _source;
private FrameworkElement[]? _descriptions;
public TableEntriesSnapshot(
IThreadingContext threadingContext,
DiagnosticTableEntriesSource source,
int version,
ImmutableArray<DiagnosticTableItem> items,
ImmutableArray<ITrackingPoint> trackingPoints)
: base(threadingContext, version, items, trackingPoints)
{
_source = source;
}
public override bool TryGetValue(int index, string columnName, [NotNullWhen(returnValue: true)] out object? content)
{
// REVIEW: this method is too-chatty to make async, but otherwise, how one can implement it async?
// also, what is cancellation mechanism?
var item = GetItem(index);
if (item == null)
{
content = null;
return false;
}
var data = item.Data;
switch (columnName)
{
case StandardTableKeyNames.ErrorRank:
content = ValueTypeCache.GetOrCreate(GetErrorRank(data));
return content != null;
case StandardTableKeyNames.ErrorSeverity:
content = ValueTypeCache.GetOrCreate(GetErrorCategory(data.Severity));
return content != null;
case StandardTableKeyNames.ErrorCode:
content = data.Id;
return content != null;
case StandardTableKeyNames.ErrorCodeToolTip:
content = (data.GetValidHelpLinkUri() != null) ? string.Format(EditorFeaturesResources.Get_help_for_0, data.Id) : null;
return content != null;
case StandardTableKeyNames.HelpKeyword:
content = data.Id;
return content != null;
case StandardTableKeyNames.HelpLink:
content = data.GetValidHelpLinkUri()?.AbsoluteUri;
return content != null;
case StandardTableKeyNames.ErrorCategory:
content = data.Category;
return content != null;
case StandardTableKeyNames.ErrorSource:
content = ValueTypeCache.GetOrCreate(GetErrorSource(_source.BuildTool));
return content != null;
case StandardTableKeyNames.BuildTool:
content = GetBuildTool(_source.BuildTool);
return content != null;
case StandardTableKeyNames.Text:
content = data.Message;
return content != null;
case StandardTableKeyNames.DocumentName:
content = data.DataLocation?.GetFilePath();
return content != null;
case StandardTableKeyNames.Line:
content = data.DataLocation?.MappedStartLine ?? 0;
return true;
case StandardTableKeyNames.Column:
content = data.DataLocation?.MappedStartColumn ?? 0;
return true;
case StandardTableKeyNames.ProjectName:
content = item.ProjectName;
return content != null;
case ProjectNames:
var names = item.ProjectNames;
content = names;
return names.Length > 0;
case StandardTableKeyNames.ProjectGuid:
content = ValueTypeCache.GetOrCreate(item.ProjectGuid);
return (Guid)content != Guid.Empty;
case ProjectGuids:
var guids = item.ProjectGuids;
content = guids;
return guids.Length > 0;
case StandardTableKeyNames.SuppressionState:
content = data.IsSuppressed ? SuppressionState.Suppressed : SuppressionState.Active;
return true;
case DoNotPropogateToGuestProperty:
content = true;
return true;
default:
content = null;
return false;
}
}
private string GetBuildTool(string buildTool)
{
// for build tool, regardless where error is coming from ("build" or "live"),
// we show "compiler" to users.
if (buildTool == PredefinedBuildTools.Live)
{
return PredefinedBuildTools.Build;
}
return _source.BuildTool;
}
private static ErrorSource GetErrorSource(string buildTool)
{
if (buildTool == PredefinedBuildTools.Build)
{
return ErrorSource.Build;
}
return ErrorSource.Other;
}
private static ErrorRank GetErrorRank(DiagnosticData item)
{
if (!item.Properties.TryGetValue(WellKnownDiagnosticPropertyNames.Origin, out var value))
{
return ErrorRank.Other;
}
switch (value)
{
case WellKnownDiagnosticTags.Build:
// any error from build gets lowest priority
// see https://github.com/dotnet/roslyn/issues/28807
//
// this is only used when intellisense (live) errors are involved.
// with "build only" filter on, we use order of errors came in from build for ordering
// and doesn't use ErrorRank for ordering (by giving same rank for all errors)
//
// when live errors are involved, by default, error list will use the following to sort errors
// error rank > project rank > project name > file name > line > column
// which will basically make syntax errors show up before declaration error and method body semantic errors
// among same type of errors, leaf project's error will show up first and then projects that depends on the leaf projects
//
// any build errors mixed with live errors will show up at the end. when live errors are on, some of errors
// still left as build errors such as errors produced after CompilationStages.Compile or ones listed here
// http://source.roslyn.io/#Microsoft.CodeAnalysis.CSharp/Compilation/CSharpCompilerDiagnosticAnalyzer.cs,23 or similar ones for VB
// and etc.
return ErrorRank.PostBuild;
case nameof(ErrorRank.Lexical):
return ErrorRank.Lexical;
case nameof(ErrorRank.Syntactic):
return ErrorRank.Syntactic;
case nameof(ErrorRank.Declaration):
return ErrorRank.Declaration;
case nameof(ErrorRank.Semantic):
return ErrorRank.Semantic;
case nameof(ErrorRank.Emit):
return ErrorRank.Emit;
case nameof(ErrorRank.PostBuild):
return ErrorRank.PostBuild;
default:
return ErrorRank.Other;
}
}
public override bool TryNavigateTo(int index, NavigationOptions options, CancellationToken cancellationToken)
=> TryNavigateToItem(index, options, cancellationToken);
#region IWpfTableEntriesSnapshot
public bool CanCreateDetailsContent(int index)
{
var item = GetItem(index)?.Data;
if (item == null)
{
return false;
}
return !string.IsNullOrWhiteSpace(item.Description);
}
public bool TryCreateDetailsContent(int index, [NotNullWhen(returnValue: true)] out FrameworkElement? expandedContent)
{
var item = GetItem(index)?.Data;
if (item == null)
{
expandedContent = null;
return false;
}
expandedContent = GetOrCreateTextBlock(ref _descriptions, this.Count, index, item, i => GetDescriptionTextBlock(i));
return true;
}
public bool TryCreateDetailsStringContent(int index, [NotNullWhen(returnValue: true)] out string? content)
{
var item = GetItem(index)?.Data;
if (item == null)
{
content = null;
return false;
}
if (string.IsNullOrWhiteSpace(item.Description))
{
content = null;
return false;
}
content = item.Description;
return content != null;
}
private static FrameworkElement GetDescriptionTextBlock(DiagnosticData item)
{
return new TextBlock()
{
Background = null,
Padding = new Thickness(10, 6, 10, 8),
TextWrapping = TextWrapping.Wrap,
Text = item.Description
};
}
private static FrameworkElement GetOrCreateTextBlock(
[NotNull] ref FrameworkElement[]? caches, int count, int index, DiagnosticData item, Func<DiagnosticData, FrameworkElement> elementCreator)
{
caches ??= new FrameworkElement[count];
if (caches[index] == null)
{
caches[index] = elementCreator(item);
}
return caches[index];
}
// unused ones
public bool TryCreateColumnContent(int index, string columnName, bool singleColumnView, [NotNullWhen(returnValue: true)] out FrameworkElement? content)
{
content = null;
return false;
}
public bool TryCreateImageContent(int index, string columnName, bool singleColumnView, out ImageMoniker content)
{
content = default;
return false;
}
public bool TryCreateStringContent(int index, string columnName, bool truncatedText, bool singleColumnView, [NotNullWhen(returnValue: true)] out string? content)
{
content = null;
return false;
}
public bool TryCreateToolTip(int index, string columnName, [NotNullWhen(returnValue: true)] out object? toolTip)
{
toolTip = null;
return false;
}
#pragma warning disable IDE0060 // Remove unused parameter - TODO: remove this once we moved to new drop
public static bool TryCreateStringContent(int index, string columnName, bool singleColumnView, [NotNullWhen(returnValue: true)] out string? content)
#pragma warning restore IDE0060 // Remove unused parameter
{
content = null;
return false;
}
#endregion
}
private static string GetDiagnosticUpdatedMessage(IGlobalOptionService globalOptions, DiagnosticsUpdatedArgs e)
{
var id = e.Id.ToString();
if (e.Id is LiveDiagnosticUpdateArgsId live)
{
id = $"{live.Analyzer}/{live.Kind}";
}
else if (e.Id is AnalyzerUpdateArgsId analyzer)
{
id = analyzer.Analyzer.ToString();
}
var diagnostics = e.GetPushDiagnostics(globalOptions, InternalDiagnosticsOptions.NormalDiagnosticMode);
return $"Kind:{e.Workspace.Kind}, Analyzer:{id}, Update:{e.Kind}, {(object?)e.DocumentId ?? e.ProjectId}, ({string.Join(Environment.NewLine, diagnostics)})";
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Common;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Options;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Shell.TableManager;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
{
internal abstract partial class VisualStudioBaseDiagnosticListTable
{
/// <summary>
/// Used by the editor to signify that errors added to the error list
/// should not be copied to the guest. Instead they will be published via LSP.
/// </summary>
private const string DoNotPropogateToGuestProperty = "DoNotPropagateToGuests";
/// <summary>
/// Error list diagnostic source for "Build + Intellisense" setting.
/// See <see cref="VisualStudioDiagnosticListTableWorkspaceEventListener.VisualStudioDiagnosticListTable.BuildTableDataSource"/>
/// for error list diagnostic source for "Build only" setting.
/// </summary>
protected class LiveTableDataSource : AbstractRoslynTableDataSource<DiagnosticTableItem, DiagnosticsUpdatedArgs>
{
private readonly string _identifier;
private readonly IDiagnosticService _diagnosticService;
private readonly Workspace _workspace;
private readonly OpenDocumentTracker<DiagnosticTableItem> _tracker;
/// <summary>
/// Flag indicating if a build inside Visual Studio is in progress.
/// We get build progress updates from <see cref="ExternalErrorDiagnosticUpdateSource.BuildProgressChanged"/>.
/// Build progress events are guaranteed to be invoked in a serial fashion during build.
/// </summary>
private bool _isBuildRunning;
public LiveTableDataSource(Workspace workspace, IThreadingContext threadingContext, IDiagnosticService diagnosticService, string identifier, ExternalErrorDiagnosticUpdateSource? buildUpdateSource = null)
: base(workspace, threadingContext)
{
_workspace = workspace;
_identifier = identifier;
_tracker = new OpenDocumentTracker<DiagnosticTableItem>(_workspace);
_diagnosticService = diagnosticService;
ConnectToDiagnosticService(workspace, diagnosticService);
ConnectToBuildUpdateSource(buildUpdateSource);
}
public IGlobalOptionService GlobalOptions => _diagnosticService.GlobalOptions;
public override string DisplayName => ServicesVSResources.CSharp_VB_Diagnostics_Table_Data_Source;
public override string SourceTypeIdentifier => StandardTableDataSources.ErrorTableDataSource;
public override string Identifier => _identifier;
public override object GetItemKey(DiagnosticsUpdatedArgs data) => data.Id;
private void ConnectToBuildUpdateSource(ExternalErrorDiagnosticUpdateSource? buildUpdateSource)
{
if (buildUpdateSource == null)
{
// it can be null in unit test
return;
}
OnBuildProgressChanged(buildUpdateSource.IsInProgress);
buildUpdateSource.BuildProgressChanged +=
(_, progress) => OnBuildProgressChanged(running: progress != ExternalErrorDiagnosticUpdateSource.BuildProgress.Done);
}
private void OnBuildProgressChanged(bool running)
{
_isBuildRunning = running;
// We mark error list "Build + Intellisense" setting as stable,
// i.e. shown as "Error List" without the trailing "...", if both the following are true:
// 1. User invoked build is not running inside Visual Studio AND
// 2. Solution crawler is not running in background to compute intellisense diagnostics.
ChangeStableStateIfRequired(newIsStable: !_isBuildRunning && !IsSolutionCrawlerRunning);
}
public override AbstractTableEntriesSnapshot<DiagnosticTableItem> CreateSnapshot(
AbstractTableEntriesSource<DiagnosticTableItem> source,
int version,
ImmutableArray<DiagnosticTableItem> items,
ImmutableArray<ITrackingPoint> trackingPoints)
{
var diagnosticSource = (DiagnosticTableEntriesSource)source;
var snapshot = new TableEntriesSnapshot(ThreadingContext, diagnosticSource, version, items, trackingPoints);
if (diagnosticSource.SupportSpanTracking && !trackingPoints.IsDefaultOrEmpty)
{
// track the open document so that we can throw away tracking points on document close properly
_tracker.TrackOpenDocument(diagnosticSource.TrackingDocumentId, diagnosticSource.Key, snapshot);
}
return snapshot;
}
protected override object GetOrUpdateAggregationKey(DiagnosticsUpdatedArgs data)
{
var key = TryGetAggregateKey(data);
if (key == null)
{
key = CreateAggregationKey(data);
AddAggregateKey(data, key);
return key;
}
if (!CheckAggregateKey(key as AggregatedKey, data))
{
RemoveStaledData(data);
key = CreateAggregationKey(data);
AddAggregateKey(data, key);
}
return key;
}
private bool CheckAggregateKey(AggregatedKey? key, DiagnosticsUpdatedArgs? args)
{
if (key == null)
{
return true;
}
if (args?.DocumentId == null || args?.Solution == null)
{
return true;
}
var documents = GetDocumentsWithSameFilePath(args.Solution, args.DocumentId);
return key.DocumentIds == documents;
}
private object CreateAggregationKey(DiagnosticsUpdatedArgs data)
{
if (data.DocumentId == null || data.Solution == null)
return GetItemKey(data);
if (data.Id is not LiveDiagnosticUpdateArgsId liveArgsId)
return GetItemKey(data);
var documents = GetDocumentsWithSameFilePath(data.Solution, data.DocumentId);
return new AggregatedKey(documents, liveArgsId.Analyzer, liveArgsId.Kind);
}
private void PopulateInitialData(Workspace workspace, IDiagnosticService diagnosticService)
{
var diagnosticMode = GlobalOptions.GetDiagnosticMode(InternalDiagnosticsOptions.NormalDiagnosticMode);
var diagnostics = diagnosticService.GetPushDiagnosticBuckets(
workspace, projectId: null, documentId: null, diagnosticMode, cancellationToken: CancellationToken.None);
foreach (var bucket in diagnostics)
{
// We only need to issue an event to VS that these docs have diagnostics associated with them. So
// we create a dummy notification for this. It doesn't matter that it is 'DiagnosticsRemoved' as
// this doesn't actually change any data. All that will happen now is that VS will call back into
// us for these IDs and we'll fetch the diagnostics at that point.
OnDataAddedOrChanged(DiagnosticsUpdatedArgs.DiagnosticsRemoved(
bucket.Id, bucket.Workspace, solution: null, bucket.ProjectId, bucket.DocumentId));
}
}
private void OnDiagnosticsUpdated(object sender, DiagnosticsUpdatedArgs e)
{
using (Logger.LogBlock(FunctionId.LiveTableDataSource_OnDiagnosticsUpdated, static arg => GetDiagnosticUpdatedMessage(arg.globalOptions, arg.e), (globalOptions: GlobalOptions, e), CancellationToken.None))
{
if (_workspace != e.Workspace)
{
return;
}
var diagnostics = e.GetPushDiagnostics(GlobalOptions, InternalDiagnosticsOptions.NormalDiagnosticMode);
if (diagnostics.Length == 0)
{
OnDataRemoved(e);
return;
}
var count = diagnostics.Where(ShouldInclude).Count();
if (count <= 0)
{
OnDataRemoved(e);
return;
}
OnDataAddedOrChanged(e);
}
}
public override AbstractTableEntriesSource<DiagnosticTableItem> CreateTableEntriesSource(object data)
{
var item = (UpdatedEventArgs)data;
return new TableEntriesSource(this, item.Workspace, GlobalOptions, item.ProjectId, item.DocumentId, item.Id);
}
private void ConnectToDiagnosticService(Workspace workspace, IDiagnosticService diagnosticService)
{
if (diagnosticService == null)
{
// it can be null in unit test
return;
}
_diagnosticService.DiagnosticsUpdated += OnDiagnosticsUpdated;
PopulateInitialData(workspace, diagnosticService);
}
private static bool ShouldInclude(DiagnosticData diagnostic)
{
if (diagnostic == null)
{
// guard us from wrong provider that gives null diagnostic
Debug.Assert(false, "Let's see who does this");
return false;
}
// If this diagnostic is for LSP only, then we won't show it here
if (diagnostic.Properties.ContainsKey(nameof(DocumentPropertiesService.DiagnosticsLspClientName)))
{
return false;
}
switch (diagnostic.Severity)
{
case DiagnosticSeverity.Info:
case DiagnosticSeverity.Warning:
case DiagnosticSeverity.Error:
return true;
case DiagnosticSeverity.Hidden:
default:
return false;
}
}
public override IEqualityComparer<DiagnosticTableItem> GroupingComparer
=> DiagnosticTableItem.GroupingComparer.Instance;
public override IEnumerable<DiagnosticTableItem> Order(IEnumerable<DiagnosticTableItem> groupedItems)
{
// this should make order of result always deterministic. we only need these 6 values since data with
// all these same will merged to one.
return groupedItems.OrderBy(d => d.Data.DataLocation?.OriginalStartLine ?? 0)
.ThenBy(d => d.Data.DataLocation?.OriginalStartColumn ?? 0)
.ThenBy(d => d.Data.Id)
.ThenBy(d => d.Data.Message)
.ThenBy(d => d.Data.DataLocation?.OriginalEndLine ?? 0)
.ThenBy(d => d.Data.DataLocation?.OriginalEndColumn ?? 0);
}
private class TableEntriesSource : DiagnosticTableEntriesSource
{
private readonly LiveTableDataSource _source;
private readonly Workspace _workspace;
private readonly IGlobalOptionService _globalOptions;
private readonly ProjectId? _projectId;
private readonly DocumentId? _documentId;
private readonly object _id;
private readonly string _buildTool;
public TableEntriesSource(LiveTableDataSource source, Workspace workspace, IGlobalOptionService globalOptions, ProjectId? projectId, DocumentId? documentId, object id)
{
_source = source;
_workspace = workspace;
_globalOptions = globalOptions;
_projectId = projectId;
_documentId = documentId;
_id = id;
_buildTool = (id as BuildToolId)?.BuildTool ?? string.Empty;
}
public override object Key => _id;
public override string BuildTool => _buildTool;
public override bool SupportSpanTracking => _documentId != null;
public override DocumentId? TrackingDocumentId => _documentId;
public override ImmutableArray<DiagnosticTableItem> GetItems()
{
var diagnosticMode = _globalOptions.GetDiagnosticMode(InternalDiagnosticsOptions.NormalDiagnosticMode);
var provider = _source._diagnosticService;
var items = provider.GetPushDiagnosticsAsync(_workspace, _projectId, _documentId, _id, includeSuppressedDiagnostics: true, diagnosticMode, cancellationToken: CancellationToken.None)
.AsTask()
.WaitAndGetResult_CanCallOnBackground(CancellationToken.None)
.Where(ShouldInclude)
.Select(data => DiagnosticTableItem.Create(_workspace, data));
return items.ToImmutableArray();
}
public override ImmutableArray<ITrackingPoint> GetTrackingPoints(ImmutableArray<DiagnosticTableItem> items)
=> _workspace.CreateTrackingPoints(_documentId, items);
}
private class TableEntriesSnapshot : AbstractTableEntriesSnapshot<DiagnosticTableItem>, IWpfTableEntriesSnapshot
{
private readonly DiagnosticTableEntriesSource _source;
private FrameworkElement[]? _descriptions;
public TableEntriesSnapshot(
IThreadingContext threadingContext,
DiagnosticTableEntriesSource source,
int version,
ImmutableArray<DiagnosticTableItem> items,
ImmutableArray<ITrackingPoint> trackingPoints)
: base(threadingContext, version, items, trackingPoints)
{
_source = source;
}
public override bool TryGetValue(int index, string columnName, [NotNullWhen(returnValue: true)] out object? content)
{
// REVIEW: this method is too-chatty to make async, but otherwise, how one can implement it async?
// also, what is cancellation mechanism?
var item = GetItem(index);
if (item == null)
{
content = null;
return false;
}
var data = item.Data;
switch (columnName)
{
case StandardTableKeyNames.ErrorRank:
content = ValueTypeCache.GetOrCreate(GetErrorRank(data));
return content != null;
case StandardTableKeyNames.ErrorSeverity:
content = ValueTypeCache.GetOrCreate(GetErrorCategory(data.Severity));
return content != null;
case StandardTableKeyNames.ErrorCode:
content = data.Id;
return content != null;
case StandardTableKeyNames.ErrorCodeToolTip:
content = (data.GetValidHelpLinkUri() != null) ? string.Format(EditorFeaturesResources.Get_help_for_0, data.Id) : null;
return content != null;
case StandardTableKeyNames.HelpKeyword:
content = data.Id;
return content != null;
case StandardTableKeyNames.HelpLink:
content = data.GetValidHelpLinkUri()?.AbsoluteUri;
return content != null;
case StandardTableKeyNames.ErrorCategory:
content = data.Category;
return content != null;
case StandardTableKeyNames.ErrorSource:
content = ValueTypeCache.GetOrCreate(GetErrorSource(_source.BuildTool));
return content != null;
case StandardTableKeyNames.BuildTool:
content = GetBuildTool(_source.BuildTool);
return content != null;
case StandardTableKeyNames.Text:
content = data.Message;
return content != null;
case StandardTableKeyNames.DocumentName:
content = data.DataLocation?.GetFilePath();
return content != null;
case StandardTableKeyNames.Line:
content = data.DataLocation?.MappedStartLine ?? 0;
return true;
case StandardTableKeyNames.Column:
content = data.DataLocation?.MappedStartColumn ?? 0;
return true;
case StandardTableKeyNames.ProjectName:
content = item.ProjectName;
return content != null;
case ProjectNames:
var names = item.ProjectNames;
content = names;
return names.Length > 0;
case StandardTableKeyNames.ProjectGuid:
content = ValueTypeCache.GetOrCreate(item.ProjectGuid);
return (Guid)content != Guid.Empty;
case ProjectGuids:
var guids = item.ProjectGuids;
content = guids;
return guids.Length > 0;
case StandardTableKeyNames.SuppressionState:
content = data.IsSuppressed ? SuppressionState.Suppressed : SuppressionState.Active;
return true;
case DoNotPropogateToGuestProperty:
content = true;
return true;
default:
content = null;
return false;
}
}
private string GetBuildTool(string buildTool)
{
// for build tool, regardless where error is coming from ("build" or "live"),
// we show "compiler" to users.
if (buildTool == PredefinedBuildTools.Live)
{
return PredefinedBuildTools.Build;
}
return _source.BuildTool;
}
private static ErrorSource GetErrorSource(string buildTool)
{
if (buildTool == PredefinedBuildTools.Build)
{
return ErrorSource.Build;
}
return ErrorSource.Other;
}
private static ErrorRank GetErrorRank(DiagnosticData item)
{
if (!item.Properties.TryGetValue(WellKnownDiagnosticPropertyNames.Origin, out var value))
{
return ErrorRank.Other;
}
switch (value)
{
case WellKnownDiagnosticTags.Build:
// any error from build gets lowest priority
// see https://github.com/dotnet/roslyn/issues/28807
//
// this is only used when intellisense (live) errors are involved.
// with "build only" filter on, we use order of errors came in from build for ordering
// and doesn't use ErrorRank for ordering (by giving same rank for all errors)
//
// when live errors are involved, by default, error list will use the following to sort errors
// error rank > project rank > project name > file name > line > column
// which will basically make syntax errors show up before declaration error and method body semantic errors
// among same type of errors, leaf project's error will show up first and then projects that depends on the leaf projects
//
// any build errors mixed with live errors will show up at the end. when live errors are on, some of errors
// still left as build errors such as errors produced after CompilationStages.Compile or ones listed here
// http://source.roslyn.io/#Microsoft.CodeAnalysis.CSharp/Compilation/CSharpCompilerDiagnosticAnalyzer.cs,23 or similar ones for VB
// and etc.
return ErrorRank.PostBuild;
case nameof(ErrorRank.Lexical):
return ErrorRank.Lexical;
case nameof(ErrorRank.Syntactic):
return ErrorRank.Syntactic;
case nameof(ErrorRank.Declaration):
return ErrorRank.Declaration;
case nameof(ErrorRank.Semantic):
return ErrorRank.Semantic;
case nameof(ErrorRank.Emit):
return ErrorRank.Emit;
case nameof(ErrorRank.PostBuild):
return ErrorRank.PostBuild;
default:
return ErrorRank.Other;
}
}
public override bool TryNavigateTo(int index, NavigationOptions options, CancellationToken cancellationToken)
=> TryNavigateToItem(index, options, cancellationToken);
#region IWpfTableEntriesSnapshot
public bool CanCreateDetailsContent(int index)
{
var item = GetItem(index)?.Data;
if (item == null)
{
return false;
}
return !string.IsNullOrWhiteSpace(item.Description);
}
public bool TryCreateDetailsContent(int index, [NotNullWhen(returnValue: true)] out FrameworkElement? expandedContent)
{
var item = GetItem(index)?.Data;
if (item == null)
{
expandedContent = null;
return false;
}
expandedContent = GetOrCreateTextBlock(ref _descriptions, this.Count, index, item, i => GetDescriptionTextBlock(i));
return true;
}
public bool TryCreateDetailsStringContent(int index, [NotNullWhen(returnValue: true)] out string? content)
{
var item = GetItem(index)?.Data;
if (item == null)
{
content = null;
return false;
}
if (string.IsNullOrWhiteSpace(item.Description))
{
content = null;
return false;
}
content = item.Description;
return content != null;
}
private static FrameworkElement GetDescriptionTextBlock(DiagnosticData item)
{
return new TextBlock()
{
Background = null,
Padding = new Thickness(10, 6, 10, 8),
TextWrapping = TextWrapping.Wrap,
Text = item.Description
};
}
private static FrameworkElement GetOrCreateTextBlock(
[NotNull] ref FrameworkElement[]? caches, int count, int index, DiagnosticData item, Func<DiagnosticData, FrameworkElement> elementCreator)
{
caches ??= new FrameworkElement[count];
if (caches[index] == null)
{
caches[index] = elementCreator(item);
}
return caches[index];
}
// unused ones
public bool TryCreateColumnContent(int index, string columnName, bool singleColumnView, [NotNullWhen(returnValue: true)] out FrameworkElement? content)
{
content = null;
return false;
}
public bool TryCreateImageContent(int index, string columnName, bool singleColumnView, out ImageMoniker content)
{
content = default;
return false;
}
public bool TryCreateStringContent(int index, string columnName, bool truncatedText, bool singleColumnView, [NotNullWhen(returnValue: true)] out string? content)
{
content = null;
return false;
}
public bool TryCreateToolTip(int index, string columnName, [NotNullWhen(returnValue: true)] out object? toolTip)
{
toolTip = null;
return false;
}
#pragma warning disable IDE0060 // Remove unused parameter - TODO: remove this once we moved to new drop
public static bool TryCreateStringContent(int index, string columnName, bool singleColumnView, [NotNullWhen(returnValue: true)] out string? content)
#pragma warning restore IDE0060 // Remove unused parameter
{
content = null;
return false;
}
#endregion
}
private static string GetDiagnosticUpdatedMessage(IGlobalOptionService globalOptions, DiagnosticsUpdatedArgs e)
{
var id = e.Id.ToString();
if (e.Id is LiveDiagnosticUpdateArgsId live)
{
id = $"{live.Analyzer}/{live.Kind}";
}
else if (e.Id is AnalyzerUpdateArgsId analyzer)
{
id = analyzer.Analyzer.ToString();
}
var diagnostics = e.GetPushDiagnostics(globalOptions, InternalDiagnosticsOptions.NormalDiagnosticMode);
return $"Kind:{e.Workspace.Kind}, Analyzer:{id}, Update:{e.Kind}, {(object?)e.DocumentId ?? e.ProjectId}, ({string.Join(Environment.NewLine, diagnostics)})";
}
}
}
}
| -1 |
dotnet/roslyn | 55,971 | Theme some dialogs | Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ryzngard | "2021-08-27T20:10:35Z" | "2022-07-12T20:08:34Z" | 07297d927b3ffd4d44f048602950947e9a040dd2 | 2cd995df98f17f1ceebba0d93729d8a4336ebe26 | Theme some dialogs. Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ./src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Formatting/AbstractFormatDocumentHandlerBase.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Formatting;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler
{
internal abstract class AbstractFormatDocumentHandlerBase<RequestType, ResponseType> : IRequestHandler<RequestType, ResponseType>
{
public bool MutatesSolutionState => false;
public bool RequiresLSPSolution => true;
public abstract TextDocumentIdentifier? GetTextDocumentIdentifier(RequestType request);
public abstract Task<ResponseType> HandleRequestAsync(RequestType request, RequestContext context, CancellationToken cancellationToken);
protected async Task<LSP.TextEdit[]> GetTextEditsAsync(LSP.FormattingOptions formattingOptions, RequestContext context, CancellationToken cancellationToken, LSP.Range? range = null)
{
using var _ = ArrayBuilder<LSP.TextEdit>.GetInstance(out var edits);
var document = context.Document;
var formattingService = document?.Project.LanguageServices.GetService<IXamlFormattingService>();
if (document != null && formattingService != null)
{
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
TextSpan? textSpan = null;
if (range != null)
{
textSpan = ProtocolConversions.RangeToTextSpan(range, text);
}
var options = new XamlFormattingOptions { InsertSpaces = formattingOptions.InsertSpaces, TabSize = formattingOptions.TabSize, OtherOptions = formattingOptions.OtherOptions };
var textChanges = await formattingService.GetFormattingChangesAsync(document, options, textSpan, cancellationToken).ConfigureAwait(false);
edits.AddRange(textChanges.Select(change => ProtocolConversions.TextChangeToTextEdit(change, text)));
}
return edits.ToArray();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Formatting;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler
{
internal abstract class AbstractFormatDocumentHandlerBase<RequestType, ResponseType> : IRequestHandler<RequestType, ResponseType>
{
public bool MutatesSolutionState => false;
public bool RequiresLSPSolution => true;
public abstract TextDocumentIdentifier? GetTextDocumentIdentifier(RequestType request);
public abstract Task<ResponseType> HandleRequestAsync(RequestType request, RequestContext context, CancellationToken cancellationToken);
protected async Task<LSP.TextEdit[]> GetTextEditsAsync(LSP.FormattingOptions formattingOptions, RequestContext context, CancellationToken cancellationToken, LSP.Range? range = null)
{
using var _ = ArrayBuilder<LSP.TextEdit>.GetInstance(out var edits);
var document = context.Document;
var formattingService = document?.Project.LanguageServices.GetService<IXamlFormattingService>();
if (document != null && formattingService != null)
{
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
TextSpan? textSpan = null;
if (range != null)
{
textSpan = ProtocolConversions.RangeToTextSpan(range, text);
}
var options = new XamlFormattingOptions { InsertSpaces = formattingOptions.InsertSpaces, TabSize = formattingOptions.TabSize, OtherOptions = formattingOptions.OtherOptions };
var textChanges = await formattingService.GetFormattingChangesAsync(document, options, textSpan, cancellationToken).ConfigureAwait(false);
edits.AddRange(textChanges.Select(change => ProtocolConversions.TextChangeToTextEdit(change, text)));
}
return edits.ToArray();
}
}
}
| -1 |
dotnet/roslyn | 55,971 | Theme some dialogs | Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ryzngard | "2021-08-27T20:10:35Z" | "2022-07-12T20:08:34Z" | 07297d927b3ffd4d44f048602950947e9a040dd2 | 2cd995df98f17f1ceebba0d93729d8a4336ebe26 | Theme some dialogs. Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/DecimalKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class DecimalKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender
{
public DecimalKeywordRecommender()
: base(SyntaxKind.DecimalKeyword)
{
}
protected override bool IsValidContextWorker(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
var syntaxTree = context.SyntaxTree;
return
context.IsAnyExpressionContext ||
context.IsDefiniteCastTypeContext ||
context.IsStatementContext ||
context.IsGlobalStatementContext ||
context.IsObjectCreationTypeContext ||
(context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) ||
context.IsFunctionPointerTypeArgumentContext ||
context.IsIsOrAsTypeContext ||
context.IsLocalVariableDeclarationContext ||
context.IsFixedVariableDeclarationContext ||
context.IsParameterTypeContext ||
context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
context.IsLocalFunctionDeclarationContext ||
context.IsImplicitOrExplicitOperatorTypeContext ||
context.IsPrimaryFunctionExpressionContext ||
context.IsCrefContext ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
context.IsDelegateReturnTypeContext ||
syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
context.IsPossibleTupleContext ||
context.IsMemberDeclarationContext(
validModifiers: SyntaxKindSet.AllMemberModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: false,
cancellationToken: cancellationToken);
}
protected override SpecialType SpecialType => SpecialType.System_Decimal;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class DecimalKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender
{
public DecimalKeywordRecommender()
: base(SyntaxKind.DecimalKeyword)
{
}
protected override bool IsValidContextWorker(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
var syntaxTree = context.SyntaxTree;
return
context.IsAnyExpressionContext ||
context.IsDefiniteCastTypeContext ||
context.IsStatementContext ||
context.IsGlobalStatementContext ||
context.IsObjectCreationTypeContext ||
(context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) ||
context.IsFunctionPointerTypeArgumentContext ||
context.IsIsOrAsTypeContext ||
context.IsLocalVariableDeclarationContext ||
context.IsFixedVariableDeclarationContext ||
context.IsParameterTypeContext ||
context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
context.IsLocalFunctionDeclarationContext ||
context.IsImplicitOrExplicitOperatorTypeContext ||
context.IsPrimaryFunctionExpressionContext ||
context.IsCrefContext ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
context.IsDelegateReturnTypeContext ||
syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
context.IsPossibleTupleContext ||
context.IsMemberDeclarationContext(
validModifiers: SyntaxKindSet.AllMemberModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: false,
cancellationToken: cancellationToken);
}
protected override SpecialType SpecialType => SpecialType.System_Decimal;
}
}
| -1 |
dotnet/roslyn | 55,971 | Theme some dialogs | Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ryzngard | "2021-08-27T20:10:35Z" | "2022-07-12T20:08:34Z" | 07297d927b3ffd4d44f048602950947e9a040dd2 | 2cd995df98f17f1ceebba0d93729d8a4336ebe26 | Theme some dialogs. Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ./src/Features/CSharp/Portable/Debugging/BreakpointResolver.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Debugging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Debugging
{
internal class BreakpointResolver : AbstractBreakpointResolver
{
public BreakpointResolver(Solution solution, string text)
: base(solution, text, LanguageNames.CSharp, EqualityComparer<string>.Default)
{
}
protected override IEnumerable<ISymbol> GetMembers(INamedTypeSymbol type, string name)
{
var members = type.GetMembers()
.Where(m => m.Name == name ||
m.ExplicitInterfaceImplementations()
.Where(i => i.Name == name)
.Any());
return (type.Name == name) ? members.Concat(type.Constructors) : members;
}
protected override bool HasMethodBody(IMethodSymbol method, CancellationToken cancellationToken)
{
var location = method.Locations.First(loc => loc.IsInSource);
var tree = location.SourceTree;
var token = tree.GetRoot(cancellationToken).FindToken(location.SourceSpan.Start);
return token.GetAncestor<MemberDeclarationSyntax>().GetBody() != null;
}
protected override void ParseText(
out IList<NameAndArity> nameParts,
out int? parameterCount)
{
var text = Text;
Debug.Assert(text != null);
var name = SyntaxFactory.ParseName(text, consumeFullText: false);
var lengthOfParsedText = name.FullSpan.End;
var parameterList = SyntaxFactory.ParseParameterList(text, lengthOfParsedText, consumeFullText: false);
var foundIncompleteParameterList = false;
parameterCount = null;
if (!parameterList.IsMissing)
{
if (parameterList.OpenParenToken.IsMissing || parameterList.CloseParenToken.IsMissing)
{
foundIncompleteParameterList = true;
}
else
{
lengthOfParsedText += parameterList.FullSpan.End;
parameterCount = parameterList.Parameters.Count;
}
}
// If there is remaining text to parse, attempt to eat a trailing semicolon.
if (lengthOfParsedText < text.Length)
{
var token = SyntaxFactory.ParseToken(text, lengthOfParsedText);
if (token.IsKind(SyntaxKind.SemicolonToken))
{
lengthOfParsedText += token.FullSpan.End;
}
}
// It's not obvious, but this method can handle the case where name "IsMissing" (no suitable name was be parsed).
var parts = name.GetNameParts();
// If we could not parse a valid parameter list or there was additional trailing text that could not be
// interpreted, don't return any names or parameters.
// Also, "Break at Function" doesn't seem to support alias qualified names with the old language service,
// and aliases don't seem meaningful for the purposes of resolving symbols from source. Since we don't
// have precedent or a clear user scenario, we won't resolve any alias qualified names (alias qualified
// parameters are accepted, but we still only validate parameter count, similar to the old implementation).
if (!foundIncompleteParameterList && (lengthOfParsedText == text.Length) &&
!parts.Any(p => p.IsKind(SyntaxKind.AliasQualifiedName)))
{
nameParts = parts.Cast<SimpleNameSyntax>().Select(p => new NameAndArity(p.Identifier.ValueText, p.Arity)).ToList();
}
else
{
nameParts = SpecializedCollections.EmptyList<NameAndArity>();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Debugging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Debugging
{
internal class BreakpointResolver : AbstractBreakpointResolver
{
public BreakpointResolver(Solution solution, string text)
: base(solution, text, LanguageNames.CSharp, EqualityComparer<string>.Default)
{
}
protected override IEnumerable<ISymbol> GetMembers(INamedTypeSymbol type, string name)
{
var members = type.GetMembers()
.Where(m => m.Name == name ||
m.ExplicitInterfaceImplementations()
.Where(i => i.Name == name)
.Any());
return (type.Name == name) ? members.Concat(type.Constructors) : members;
}
protected override bool HasMethodBody(IMethodSymbol method, CancellationToken cancellationToken)
{
var location = method.Locations.First(loc => loc.IsInSource);
var tree = location.SourceTree;
var token = tree.GetRoot(cancellationToken).FindToken(location.SourceSpan.Start);
return token.GetAncestor<MemberDeclarationSyntax>().GetBody() != null;
}
protected override void ParseText(
out IList<NameAndArity> nameParts,
out int? parameterCount)
{
var text = Text;
Debug.Assert(text != null);
var name = SyntaxFactory.ParseName(text, consumeFullText: false);
var lengthOfParsedText = name.FullSpan.End;
var parameterList = SyntaxFactory.ParseParameterList(text, lengthOfParsedText, consumeFullText: false);
var foundIncompleteParameterList = false;
parameterCount = null;
if (!parameterList.IsMissing)
{
if (parameterList.OpenParenToken.IsMissing || parameterList.CloseParenToken.IsMissing)
{
foundIncompleteParameterList = true;
}
else
{
lengthOfParsedText += parameterList.FullSpan.End;
parameterCount = parameterList.Parameters.Count;
}
}
// If there is remaining text to parse, attempt to eat a trailing semicolon.
if (lengthOfParsedText < text.Length)
{
var token = SyntaxFactory.ParseToken(text, lengthOfParsedText);
if (token.IsKind(SyntaxKind.SemicolonToken))
{
lengthOfParsedText += token.FullSpan.End;
}
}
// It's not obvious, but this method can handle the case where name "IsMissing" (no suitable name was be parsed).
var parts = name.GetNameParts();
// If we could not parse a valid parameter list or there was additional trailing text that could not be
// interpreted, don't return any names or parameters.
// Also, "Break at Function" doesn't seem to support alias qualified names with the old language service,
// and aliases don't seem meaningful for the purposes of resolving symbols from source. Since we don't
// have precedent or a clear user scenario, we won't resolve any alias qualified names (alias qualified
// parameters are accepted, but we still only validate parameter count, similar to the old implementation).
if (!foundIncompleteParameterList && (lengthOfParsedText == text.Length) &&
!parts.Any(p => p.IsKind(SyntaxKind.AliasQualifiedName)))
{
nameParts = parts.Cast<SimpleNameSyntax>().Select(p => new NameAndArity(p.Identifier.ValueText, p.Arity)).ToList();
}
else
{
nameParts = SpecializedCollections.EmptyList<NameAndArity>();
}
}
}
}
| -1 |
dotnet/roslyn | 55,971 | Theme some dialogs | Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ryzngard | "2021-08-27T20:10:35Z" | "2022-07-12T20:08:34Z" | 07297d927b3ffd4d44f048602950947e9a040dd2 | 2cd995df98f17f1ceebba0d93729d8a4336ebe26 | Theme some dialogs. Theme pull members up, extract interface, and extract class.
### Extract Class


### Extract Interface


### Pull Members Up


| ./src/Compilers/Test/Resources/Core/SymbolsTests/Fields/CSFields.dll | MZ @ !L!This program cannot be run in DOS mode.
$ PE L qL ! N# @ @ @ " W @ ` H .text T `.rsrc @ @ @.reloc `
@ B 0# H d
*(
*(
* BSJB v4.0.30319 l #~ | #Strings 4 #US < #GUID L D #Blob W %3
4 - [ ; w ; ; f
i P m S q [ q q ! q q . . $ $ <Module> CSFields.dll CSFields FFF mscorlib System Object System.Runtime.CompilerServices IsVolatile F6 Fff FfF .ctor CompilationRelaxationsAttribute RuntimeCompatibilityAttribute Y:NKH3
z\V4 TWrapNonExceptionThrows # ># 0# _CorDllMain mscoree.dll % @ 0 H X@ L L4 V S _ V E R S I O N _ I N F O ? D V a r F i l e I n f o $ T r a n s l a t i o n S t r i n g F i l e I n f o 0 0 0 0 0 4 b 0 , F i l e D e s c r i p t i o n 0 F i l e V e r s i o n 0 . 0 . 0 . 0 < |