Skip to content

Allow AnalyzeDataFlow for ConstructorInitializerSyntax #57577

@bernd5

Description

@bernd5

Background and Motivation

For analyzers and rewriters it is sometimes required to analyze the data flow of a constructor initializer which is very similar to an implicit first expression statement.
Unfortenately it is not an expression nor a statement and the public API allows only to analyze statements or expressions (specified in the comment).

Proposed API

The current public API accepts all SyntaxNode but throws expections if the node is not a statement nor an expression.
Therefore we don't need to change the public API. We should just change the comment.

using System.Collections.Immutable;
using System.Threading;

namespace Microsoft.CodeAnalysis
{
    public static class ModelExtensions
    {
        ...

        /// <summary>
        /// Analyze data-flow within a part of a method body.
+       /// note (for C#): ConstructorInitializerSyntax and PrimaryConstructorBaseTypeSyntax are treated by this API as regular statements
        /// </summary>
        public static DataFlowAnalysis AnalyzeDataFlow(this SemanticModel semanticModel, SyntaxNode statementOrExpression)
        {
            //impl
        }
    }
}

Optional API extension:

To make the support for ConstructorInitializerSyntax and PrimaryConstructorBaseTypeSyntax more obvious we could add the folowing extension methods:

namespace Microsoft.CodeAnalysis
{
    public static class CSharpExtensions
    {
+        /// <summary>
+        /// Analyze data-flow within a constructor initializer.
+        /// </summary>
+        public static DataFlowAnalysis? AnalyzeDataFlow(this SemanticModel? semanticModel, ConstructorInitializerSyntax constructorInitializer)
+        {
+            //impl
+        }
+
+        /// <summary>
+        /// Analyze data-flow within a primary constructor base type.
+        /// </summary>
+        public static DataFlowAnalysis? AnalyzeDataFlow(this SemanticModel? semanticModel, PrimaryConstructorBaseTypeSyntax primaryConstructorBaseType)
+        {
+            //impl
+        }
    }
}

Usage Examples

analysis = model.AnalyzeDataFlow(ctorInit);

Alternative Designs

Some user hacked around this missing feature and created a corresponding object creation expression for the analysis which produces a quite good result. The downside is just the mapping of symbols between two different models - which can become quite complicated and error prone.

Risks

No known risk

Implementation

#57576

Metadata

Metadata

Assignees

Labels

Area-CompilersConcept-APIThis issue involves adding, removing, clarification, or modification of an API.Feature Requestapi-approvedAPI was approved in API review, it can be implemented

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions