diff --git a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForFluentDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForFluentDiagnosticAnalyzer.cs index a91372467c795..39ad7f7fddeb5 100644 --- a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForFluentDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForFluentDiagnosticAnalyzer.cs @@ -21,6 +21,7 @@ namespace Microsoft.CodeAnalysis.CSharp.UseCollectionExpression; using static UseCollectionExpressionHelpers; +using static SyntaxFactory; using FluentState = UpdateExpressionState; [DiagnosticAnalyzer(LanguageNames.CSharp)] @@ -42,7 +43,7 @@ internal sealed partial class CSharpUseCollectionExpressionForFluentDiagnosticAn nameof(Array), nameof(Span), nameof(ReadOnlySpan), - nameof(List), + nameof(System.Collections.Generic.List), nameof(HashSet), nameof(LinkedList), nameof(Queue), @@ -293,7 +294,7 @@ void AddFinalMatch(ExpressionSyntax expression) { // Remove any whitespace around the `.`, making the singly-wrapped fluent expression into a single line. matchesInReverse.Add(new CollectionExpressionMatch( - SyntaxFactory.Argument(innerInvocation.WithExpression( + Argument(innerInvocation.WithExpression( memberAccess.Update( memberAccess.Expression.WithoutTrailingTrivia(), memberAccess.OperatorToken.WithoutTrivia(), @@ -302,7 +303,7 @@ void AddFinalMatch(ExpressionSyntax expression) return; } - matchesInReverse.Add(new CollectionExpressionMatch(SyntaxFactory.Argument(expression), UseSpread: true)); + matchesInReverse.Add(new CollectionExpressionMatch(Argument(expression), UseSpread: true)); } // We only want to offer this feature when the original collection was list-like (as opposed to being something diff --git a/src/Analyzers/CSharp/Analyzers/UseCollectionInitializer/CSharpUpdateExpressionSyntaxHelper.cs b/src/Analyzers/CSharp/Analyzers/UseCollectionInitializer/CSharpUpdateExpressionSyntaxHelper.cs index 79de454fef8ff..cea36e32a7aa2 100644 --- a/src/Analyzers/CSharp/Analyzers/UseCollectionInitializer/CSharpUpdateExpressionSyntaxHelper.cs +++ b/src/Analyzers/CSharp/Analyzers/UseCollectionInitializer/CSharpUpdateExpressionSyntaxHelper.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.UseCollectionInitializer; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseCollectionInitializer; @@ -40,5 +39,5 @@ public void GetPartsOfIfStatement( } private static IEnumerable ExtractEmbeddedStatements(StatementSyntax embeddedStatement) - => embeddedStatement is BlockSyntax block ? block.Statements : SpecializedCollections.SingletonEnumerable(embeddedStatement); + => embeddedStatement is BlockSyntax block ? [.. block.Statements] : [embeddedStatement]; } diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper`1.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper`1.cs index 6873b47873a82..4be8de50c4037 100644 --- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper`1.cs +++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper`1.cs @@ -8,7 +8,6 @@ using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; @@ -17,6 +16,8 @@ namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody; +using static SyntaxFactory; + /// /// Helper class that allows us to share lots of logic between the diagnostic analyzer and the /// code refactoring provider. Those can't share a common base class due to their own inheritance @@ -160,7 +161,7 @@ protected bool TryConvertToExpressionBodyForBaseProperty( if (getAccessor?.ExpressionBody != null && BlockSyntaxExtensions.MatchesPreference(getAccessor.ExpressionBody.Expression, conversionPreference)) { - arrowExpression = SyntaxFactory.ArrowExpressionClause(getAccessor.ExpressionBody.Expression); + arrowExpression = ArrowExpressionClause(getAccessor.ExpressionBody.Expression); semicolonToken = getAccessor.SemicolonToken; return true; } @@ -180,7 +181,7 @@ public bool CanOfferUseBlockBody( expressionBody = GetExpressionBody(declaration); if (expressionBody?.TryConvertToBlock( - SyntaxFactory.Token(SyntaxKind.SemicolonToken), false, block: out _) != true) + Token(SyntaxKind.SemicolonToken), false, block: out _) != true) { fixesError = false; return false; @@ -296,13 +297,13 @@ protected TDeclaration WithAccessorList(SemanticModel semanticModel, TDeclaratio CreateReturnStatementForExpression(semanticModel, declaration), out var block); - var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration); + var accessor = AccessorDeclaration(SyntaxKind.GetAccessorDeclaration); accessor = block != null ? accessor.WithBody(block) : accessor.WithExpressionBody(expressionBody) .WithSemicolonToken(semicolonToken); - return WithAccessorList(declaration, SyntaxFactory.AccessorList([accessor])); + return WithAccessorList(declaration, AccessorList([accessor])); } protected virtual TDeclaration WithAccessorList(TDeclaration declaration, AccessorListSyntax accessorListSyntax) diff --git a/src/Analyzers/CSharp/Analyzers/UsePatternCombinators/AnalyzedPattern.cs b/src/Analyzers/CSharp/Analyzers/UsePatternCombinators/AnalyzedPattern.cs index 63ad0ed28673d..3fec548f72e15 100644 --- a/src/Analyzers/CSharp/Analyzers/UsePatternCombinators/AnalyzedPattern.cs +++ b/src/Analyzers/CSharp/Analyzers/UsePatternCombinators/AnalyzedPattern.cs @@ -9,6 +9,8 @@ namespace Microsoft.CodeAnalysis.CSharp.UsePatternCombinators; +using static SyntaxFactory; + /// /// Base class to represent a pattern constructed from various checks /// @@ -48,12 +50,12 @@ internal sealed class Type : AnalyzedPattern // semantics, and for 'C.X' could be a compile error. // // So lets create a pattern syntax and make sure the result is the same - var dummyStatement = SyntaxFactory.ExpressionStatement(SyntaxFactory.AssignmentExpression( + var dummyStatement = ExpressionStatement(AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, - SyntaxFactory.IdentifierName("_"), - SyntaxFactory.IsPatternExpression( + IdentifierName("_"), + IsPatternExpression( binaryExpression.Left, - SyntaxFactory.ConstantPattern(SyntaxFactory.ParenthesizedExpression(binaryExpression.Right.WithAdditionalAnnotations(s_annotation))) + ConstantPattern(ParenthesizedExpression(binaryExpression.Right.WithAdditionalAnnotations(s_annotation))) ) )); @@ -149,7 +151,7 @@ private Binary(AnalyzedPattern leftPattern, AnalyzedPattern rightPattern, bool i return null; var compareTarget = target == leftTarget ? rightTarget : leftTarget; - if (!SyntaxFactory.AreEquivalent(target.Syntax, compareTarget.Syntax)) + if (!AreEquivalent(target.Syntax, compareTarget.Syntax)) return null; return new Binary(leftPattern, rightPattern, isDisjunctive, token, target); diff --git a/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceTransform.cs b/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceTransform.cs index 40175de4cf443..a11070f46e455 100644 --- a/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceTransform.cs +++ b/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceTransform.cs @@ -18,6 +18,8 @@ namespace Microsoft.CodeAnalysis.CSharp.ConvertNamespace; +using static SyntaxFactory; + internal static class ConvertNamespaceTransform { public static Task ConvertAsync(Document document, BaseNamespaceDeclarationSyntax baseNamespace, CSharpSyntaxFormattingOptions options, CancellationToken cancellationToken) @@ -271,7 +273,7 @@ private static SyntaxNode ReplaceWithBlockScopedNamespace( if (triviaBeforeSplit.Length > 0) { if (needsAdditionalLineEnding) - triviaBeforeSplit = triviaBeforeSplit.Append(SyntaxFactory.EndOfLine(lineEnding)); + triviaBeforeSplit = triviaBeforeSplit.Append(EndOfLine(lineEnding)); converted = converted.WithCloseBraceToken(converted.CloseBraceToken.WithPrependedLeadingTrivia(triviaBeforeSplit)); } @@ -320,7 +322,7 @@ private static bool HasLeadingBlankLine( private static FileScopedNamespaceDeclarationSyntax ConvertNamespaceDeclaration(NamespaceDeclarationSyntax namespaceDeclaration) { // If the open-brace token has any special trivia, then move them to after the semicolon. - var semiColon = SyntaxFactory.Token(SyntaxKind.SemicolonToken) + var semiColon = Token(SyntaxKind.SemicolonToken) .WithoutTrivia() .WithTrailingTrivia(namespaceDeclaration.Name.GetTrailingTrivia()) .WithAppendedTrailingTrivia(namespaceDeclaration.OpenBraceToken.LeadingTrivia); @@ -329,7 +331,7 @@ private static FileScopedNamespaceDeclarationSyntax ConvertNamespaceDeclaration( semiColon = semiColon.WithAppendedTrailingTrivia(namespaceDeclaration.OpenBraceToken.TrailingTrivia); // Move trivia after the original name token to now be after the new semicolon token. - var fileScopedNamespace = SyntaxFactory.FileScopedNamespaceDeclaration( + var fileScopedNamespace = FileScopedNamespaceDeclaration( namespaceDeclaration.AttributeLists, namespaceDeclaration.Modifiers, namespaceDeclaration.NamespaceKeyword, @@ -379,16 +381,16 @@ private static FileScopedNamespaceDeclarationSyntax ConvertNamespaceDeclaration( private static NamespaceDeclarationSyntax ConvertFileScopedNamespace(ParsedDocument document, FileScopedNamespaceDeclarationSyntax fileScopedNamespace, string lineEnding, NewLinePlacement newLinePlacement) { var nameSyntax = fileScopedNamespace.Name.WithAppendedTrailingTrivia(fileScopedNamespace.SemicolonToken.LeadingTrivia) - .WithAppendedTrailingTrivia(newLinePlacement.HasFlag(NewLinePlacement.BeforeOpenBraceInTypes) ? SyntaxFactory.EndOfLine(lineEnding) : SyntaxFactory.Space); - var openBraceToken = SyntaxFactory.Token(SyntaxKind.OpenBraceToken).WithoutLeadingTrivia().WithTrailingTrivia(fileScopedNamespace.SemicolonToken.TrailingTrivia); + .WithAppendedTrailingTrivia(newLinePlacement.HasFlag(NewLinePlacement.BeforeOpenBraceInTypes) ? EndOfLine(lineEnding) : Space); + var openBraceToken = Token(SyntaxKind.OpenBraceToken).WithoutLeadingTrivia().WithTrailingTrivia(fileScopedNamespace.SemicolonToken.TrailingTrivia); if (openBraceToken.TrailingTrivia is not [.., SyntaxTrivia(SyntaxKind.EndOfLineTrivia)]) { - openBraceToken = openBraceToken.WithAppendedTrailingTrivia(SyntaxFactory.EndOfLine(lineEnding)); + openBraceToken = openBraceToken.WithAppendedTrailingTrivia(EndOfLine(lineEnding)); } FileScopedNamespaceDeclarationSyntax adjustedFileScopedNamespace; - var closeBraceToken = SyntaxFactory.Token(SyntaxKind.CloseBraceToken).WithoutLeadingTrivia().WithoutTrailingTrivia(); + var closeBraceToken = Token(SyntaxKind.CloseBraceToken).WithoutLeadingTrivia().WithoutTrailingTrivia(); // Normally the block scoped namespace will have a newline after the closing brace. The only exception to // this occurs when there are no tokens after the closing brace and the document with a file scoped @@ -397,7 +399,7 @@ private static NamespaceDeclarationSyntax ConvertFileScopedNamespace(ParsedDocum if (!fileScopedNamespace.GetLastToken().GetNextTokenOrEndOfFile().IsKind(SyntaxKind.EndOfFileToken) || document.Text.Lines.GetLinePosition(document.Text.Length).Character == 0) { - closeBraceToken = closeBraceToken.WithAppendedTrailingTrivia(SyntaxFactory.EndOfLine(lineEnding)); + closeBraceToken = closeBraceToken.WithAppendedTrailingTrivia(EndOfLine(lineEnding)); adjustedFileScopedNamespace = fileScopedNamespace; } else @@ -405,7 +407,7 @@ private static NamespaceDeclarationSyntax ConvertFileScopedNamespace(ParsedDocum // Make sure the body of the file scoped namespace ends with a trailing new line (so the closing brace // of the converted block-body namespace appears on its own line), but don't add a new line after the // closing brace. - adjustedFileScopedNamespace = fileScopedNamespace.WithAppendedTrailingTrivia(SyntaxFactory.EndOfLine(lineEnding)); + adjustedFileScopedNamespace = fileScopedNamespace.WithAppendedTrailingTrivia(EndOfLine(lineEnding)); } // If the file scoped namespace is indented, also indent the newly added braces to match @@ -413,12 +415,12 @@ private static NamespaceDeclarationSyntax ConvertFileScopedNamespace(ParsedDocum if (outerIndentation.Length > 0) { if (newLinePlacement.HasFlag(NewLinePlacement.BeforeOpenBraceInTypes)) - openBraceToken = openBraceToken.WithLeadingTrivia(openBraceToken.LeadingTrivia.Add(SyntaxFactory.Whitespace(outerIndentation))); + openBraceToken = openBraceToken.WithLeadingTrivia(openBraceToken.LeadingTrivia.Add(Whitespace(outerIndentation))); - closeBraceToken = closeBraceToken.WithLeadingTrivia(closeBraceToken.LeadingTrivia.Add(SyntaxFactory.Whitespace(outerIndentation))); + closeBraceToken = closeBraceToken.WithLeadingTrivia(closeBraceToken.LeadingTrivia.Add(Whitespace(outerIndentation))); } - var namespaceDeclaration = SyntaxFactory.NamespaceDeclaration( + var namespaceDeclaration = NamespaceDeclaration( adjustedFileScopedNamespace.AttributeLists, adjustedFileScopedNamespace.Modifiers, adjustedFileScopedNamespace.NamespaceKeyword, diff --git a/src/Analyzers/CSharp/CodeFixes/ConvertToRecord/ConvertToRecordEngine.cs b/src/Analyzers/CSharp/CodeFixes/ConvertToRecord/ConvertToRecordEngine.cs index e3ed6efd59edb..dc98aca5c16d1 100644 --- a/src/Analyzers/CSharp/CodeFixes/ConvertToRecord/ConvertToRecordEngine.cs +++ b/src/Analyzers/CSharp/CodeFixes/ConvertToRecord/ConvertToRecordEngine.cs @@ -20,6 +20,8 @@ namespace Microsoft.CodeAnalysis.CSharp.ConvertToRecord; +using static SyntaxFactory; + internal static class ConvertToRecordEngine { private const SyntaxRemoveOptions RemovalOptions = @@ -124,8 +126,8 @@ await RefactorInitializersAsync(type, solutionEditor, propertiesToAssign, cancel // add an initializer that links the property to the primary constructor parameter documentEditor.ReplaceNode(property, property .WithInitializer( - SyntaxFactory.EqualsValueClause(SyntaxFactory.IdentifierName(property.Identifier.WithoutTrivia()))) - .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))); + EqualsValueClause(IdentifierName(property.Identifier.WithoutTrivia()))) + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken))); } else { @@ -186,9 +188,9 @@ await RefactorInitializersAsync(type, solutionEditor, propertiesToAssign, cancel var modifiedConstructor = constructor .RemoveNodes(expressionStatementsToRemove, RemovalOptions)! - .WithInitializer(SyntaxFactory.ConstructorInitializer( + .WithInitializer(ConstructorInitializer( SyntaxKind.ThisConstructorInitializer, - SyntaxFactory.ArgumentList([.. expressions.Select(SyntaxFactory.Argument)]))); + ArgumentList([.. expressions.Select(Argument)]))); documentEditor.ReplaceNode(constructor, modifiedConstructor); } @@ -251,10 +253,10 @@ await RefactorInitializersAsync(type, solutionEditor, propertiesToAssign, cancel ? result.Symbol.Type.GenerateTypeSyntax() : result.Declaration.Type; var identifier = result.IsInherited - ? SyntaxFactory.Identifier(result.Symbol.Name) + ? Identifier(result.Symbol.Name) : result.Declaration.Identifier; - return SyntaxFactory.Parameter( + return Parameter( GetModifiedAttributeListsForProperty(result), modifiers: default, type, @@ -264,7 +266,7 @@ await RefactorInitializersAsync(type, solutionEditor, propertiesToAssign, cancel // if we have a class, move trivia from class keyword to record keyword // if struct, split trivia and leading goes to record keyword, trailing goes to struct keyword - var recordKeyword = SyntaxFactory.Token(SyntaxKind.RecordKeyword); + var recordKeyword = Token(SyntaxKind.RecordKeyword); recordKeyword = type.TypeKind == TypeKind.Class ? recordKeyword.WithTriviaFrom(typeDeclaration.Keyword) : recordKeyword.WithLeadingTrivia(typeDeclaration.Keyword.LeadingTrivia); @@ -312,11 +314,11 @@ await RefactorInitializersAsync(type, solutionEditor, propertiesToAssign, cancel var inheritedPositionalParams = PositionalParameterInfo .GetInheritedPositionalParams(type, cancellationToken) .SelectAsArray(prop => - SyntaxFactory.Argument(SyntaxFactory.IdentifierName(prop.Name))); + Argument(IdentifierName(prop.Name))); typeList = typeList.Replace(baseRecord, - SyntaxFactory.PrimaryConstructorBaseType(baseRecord.Type.WithoutTrailingTrivia(), - SyntaxFactory.ArgumentList([.. inheritedPositionalParams]) + PrimaryConstructorBaseType(baseRecord.Type.WithoutTrailingTrivia(), + ArgumentList([.. inheritedPositionalParams]) .WithTrailingTrivia(baseTrailingTrivia))); } @@ -389,16 +391,16 @@ private static RecordDeclarationSyntax CreateRecordDeclaration( openBrace = default; closeBrace = default; semicolon = typeDeclaration.SemicolonToken == default - ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) + ? Token(SyntaxKind.SemicolonToken) : typeDeclaration.SemicolonToken; } else { openBrace = typeDeclaration.OpenBraceToken == default - ? SyntaxFactory.Token(SyntaxKind.OpenBraceToken) + ? Token(SyntaxKind.OpenBraceToken) : typeDeclaration.OpenBraceToken; closeBrace = typeDeclaration.CloseBraceToken == default - ? SyntaxFactory.Token(SyntaxKind.CloseBraceToken) + ? Token(SyntaxKind.CloseBraceToken) : typeDeclaration.CloseBraceToken; semicolon = default; @@ -409,7 +411,7 @@ private static RecordDeclarationSyntax CreateRecordDeclaration( typeDeclaration.Members[0], typeDeclaration.Members[0].GetNodeWithoutLeadingBlankLines()); } - return SyntaxFactory.RecordDeclaration( + return RecordDeclaration( type.TypeKind == TypeKind.Class ? SyntaxKind.RecordDeclaration : SyntaxKind.RecordStructDeclaration, @@ -418,11 +420,11 @@ private static RecordDeclarationSyntax CreateRecordDeclaration( recordKeyword, type.TypeKind == TypeKind.Class ? default - : typeDeclaration.Keyword.WithTrailingTrivia(SyntaxFactory.ElasticMarker), + : typeDeclaration.Keyword.WithTrailingTrivia(ElasticMarker), // remove trailing trivia from places where we would want to insert the parameter list before a line break - typeDeclaration.Identifier.WithTrailingTrivia(SyntaxFactory.ElasticMarker), - typeDeclaration.TypeParameterList?.WithTrailingTrivia(SyntaxFactory.ElasticMarker), - SyntaxFactory.ParameterList([.. propertiesToAddAsParams]) + typeDeclaration.Identifier.WithTrailingTrivia(ElasticMarker), + typeDeclaration.TypeParameterList?.WithTrailingTrivia(ElasticMarker), + ParameterList([.. propertiesToAddAsParams]) .WithAppendedTrailingTrivia(constructorTrivia), baseList, typeDeclaration.ConstraintClauses, @@ -457,7 +459,7 @@ private static SyntaxList GetModifiedAttributeListsForPrope { // convert attributes attached to the property with no target into "property :" targeted attributes return attributeList - .WithTarget(SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.PropertyKeyword))) + .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.PropertyKeyword))) .WithoutTrivia(); } else @@ -553,10 +555,10 @@ private static async Task RefactorInitializersAsync( // replace: new C { Foo = 0; Bar = false; }; // with: new C(0, false); - return SyntaxFactory.ObjectCreationExpression( + return ObjectCreationExpression( updatedObjectCreation.NewKeyword, updatedObjectCreation.Type.WithoutTrailingTrivia(), - SyntaxFactory.ArgumentList([.. updatedExpressions.Select(expression => SyntaxFactory.Argument(expression.WithoutTrivia()))]), + ArgumentList([.. updatedExpressions.Select(expression => Argument(expression.WithoutTrivia()))]), newInitializer); }); } @@ -645,28 +647,28 @@ node is XmlElementSyntax element && propDoc.IsMultilineDocComment()) { // add /** and */ - newClassDocComment = SyntaxFactory.DocumentationCommentTrivia( + newClassDocComment = DocumentationCommentTrivia( SyntaxKind.MultiLineDocumentationCommentTrivia, // Our parameter method gives a newline (without leading trivia) to start // because we assume we're following some other comment, we replace that newline to add // the start of comment leading trivia as well since we're not following another comment [.. propertyParamComments.Skip(1) - .Prepend(SyntaxFactory.XmlText(SyntaxFactory.XmlTextNewLine(lineFormattingOptions.NewLine, continueXmlDocumentationComment: false) - .WithLeadingTrivia(SyntaxFactory.DocumentationCommentExterior("/**")) + .Prepend(XmlText(XmlTextNewLine(lineFormattingOptions.NewLine, continueXmlDocumentationComment: false) + .WithLeadingTrivia(DocumentationCommentExterior("/**")) .WithTrailingTrivia(exteriorTrivia))) - .Append(SyntaxFactory.XmlText(SyntaxFactory.XmlTextNewLine(lineFormattingOptions.NewLine, continueXmlDocumentationComment: false)))], - SyntaxFactory.Token(SyntaxKind.EndOfDocumentationCommentToken) - .WithTrailingTrivia(SyntaxFactory.DocumentationCommentExterior("*/"), SyntaxFactory.ElasticCarriageReturnLineFeed)); + .Append(XmlText(XmlTextNewLine(lineFormattingOptions.NewLine, continueXmlDocumentationComment: false)))], + Token(SyntaxKind.EndOfDocumentationCommentToken) + .WithTrailingTrivia(DocumentationCommentExterior("*/"), ElasticCarriageReturnLineFeed)); } else { // add extra line at end to end doc comment // also skip first newline and replace with non-newline - newClassDocComment = SyntaxFactory.DocumentationCommentTrivia( + newClassDocComment = DocumentationCommentTrivia( SyntaxKind.MultiLineDocumentationCommentTrivia, [.. propertyParamComments.Skip(1) - .Prepend(SyntaxFactory.XmlText(SyntaxFactory.XmlTextLiteral(" ").WithLeadingTrivia(exteriorTrivia)))]) - .WithAppendedTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed); + .Prepend(XmlText(XmlTextLiteral(" ").WithLeadingTrivia(exteriorTrivia)))]) + .WithAppendedTrailingTrivia(ElasticCarriageReturnLineFeed); } } @@ -677,14 +679,14 @@ [.. propertyParamComments.Skip(1) return [.. classTrivia .Where(trivia => !trivia.IsDocComment()) .Concat(propertyNonDocComments) - .Append(SyntaxFactory.Trivia(newClassDocComment)) + .Append(Trivia(newClassDocComment)) .Select(trivia => trivia.AsElastic())]; } else { // there were comments after doc comment return [.. classTrivia - .Replace(classDocComment.Value, SyntaxFactory.Trivia(newClassDocComment)) + .Replace(classDocComment.Value, Trivia(newClassDocComment)) .Concat(propertyNonDocComments) .Select(trivia => trivia.AsElastic())]; } @@ -756,15 +758,15 @@ private static IEnumerable CreateParamComments( // add an extra line and space with the exterior trivia, so that our params start on the next line and each // param goes on a new line with the continuation trivia // when adding a new line, the continue flag adds a single line documentation trivia, but we don't necessarily want that - yield return SyntaxFactory.XmlText( - SyntaxFactory.XmlTextNewLine(lineFormattingOptions.NewLine, continueXmlDocumentationComment: false), - SyntaxFactory.XmlTextLiteral(" ").WithLeadingTrivia(exteriorTrivia)); + yield return XmlText( + XmlTextNewLine(lineFormattingOptions.NewLine, continueXmlDocumentationComment: false), + XmlTextLiteral(" ").WithLeadingTrivia(exteriorTrivia)); if (result.IsInherited) { // generate a param comment with an inherited doc - yield return SyntaxFactory.XmlParamElement(result.Symbol.Name, SyntaxFactory.XmlEmptyElement( - SyntaxFactory.XmlName(DocumentationCommentXmlNames.InheritdocElementName))); + yield return XmlParamElement(result.Symbol.Name, XmlEmptyElement( + XmlName(DocumentationCommentXmlNames.InheritdocElementName))); } else { @@ -820,7 +822,7 @@ tokens is [(kind: SyntaxKind.XmlTextLiteralNewLineToken), _, ..]) } } - yield return SyntaxFactory.XmlParamElement(result.Declaration.Identifier.ValueText, paramContent.AsArray()); + yield return XmlParamElement(result.Declaration.Identifier.ValueText, paramContent.AsArray()); } } } diff --git a/src/Analyzers/CSharp/CodeFixes/InlineDeclaration/CSharpInlineDeclarationCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/InlineDeclaration/CSharpInlineDeclarationCodeFixProvider.cs index baa760caa134a..19967461ade4f 100644 --- a/src/Analyzers/CSharp/CodeFixes/InlineDeclaration/CSharpInlineDeclarationCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/InlineDeclaration/CSharpInlineDeclarationCodeFixProvider.cs @@ -4,7 +4,6 @@ #nullable disable -using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; @@ -14,21 +13,20 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; -using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.InlineDeclaration; +using static SyntaxFactory; + [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.InlineDeclaration), Shared] internal partial class CSharpInlineDeclarationCodeFixProvider : SyntaxEditorBasedCodeFixProvider { @@ -215,7 +213,7 @@ private static SyntaxNode ReplaceIdentifierWithInlineDeclaration( { editor.ReplaceNode( declaration.Type, - (t, g) => t.WithTrailingTrivia(SyntaxFactory.ElasticSpace).WithoutAnnotations(Formatter.Annotation)); + (t, g) => t.WithTrailingTrivia(ElasticSpace).WithoutAnnotations(Formatter.Annotation)); } } } @@ -243,7 +241,7 @@ private static SyntaxNode ReplaceIdentifierWithInlineDeclaration( // If the user originally wrote it something other than 'var', then use what they // wrote. Otherwise, synthesize the actual type of the local. var explicitType = declaration.Type.IsVar ? local.Type?.GenerateTypeSyntax() : declaration.Type; - declarationExpression = SyntaxFactory.DeclarationExpression(explicitType, declarationExpression.Designation); + declarationExpression = DeclarationExpression(explicitType, declarationExpression.Designation); } editor.ReplaceNode(identifier, declarationExpression); @@ -261,7 +259,7 @@ public static TypeSyntax GenerateTypeSyntaxOrVar( // analyze those due to limitations between how it uses Speculative SemanticModels // and how those don't handle new declarations well. return useVar - ? SyntaxFactory.IdentifierName("var") + ? IdentifierName("var") : symbol.GenerateTypeSyntax(); } @@ -281,7 +279,7 @@ private static DeclarationExpressionSyntax GetDeclarationExpression( SourceText sourceText, IdentifierNameSyntax identifier, TypeSyntax newType, VariableDeclaratorSyntax declaratorOpt) { - var designation = SyntaxFactory.SingleVariableDesignation(identifier.Identifier); + var designation = SingleVariableDesignation(identifier.Identifier); if (declaratorOpt != null) { @@ -308,10 +306,10 @@ private static DeclarationExpressionSyntax GetDeclarationExpression( // designation and in those cases adding elastic trivia will break formatting. if (!designation.HasLeadingTrivia) { - newType = newType.WithAppendedTrailingTrivia(SyntaxFactory.ElasticSpace); + newType = newType.WithAppendedTrailingTrivia(ElasticSpace); } - return SyntaxFactory.DeclarationExpression(newType, designation); + return DeclarationExpression(newType, designation); } private static IEnumerable MassageTrivia(IEnumerable triviaList) @@ -328,7 +326,7 @@ private static IEnumerable MassageTrivia(IEnumerable // indentation spaces to be inserted in the out-var location. It is appropriate // though to have single spaces to help separate out things like comments and // tokens though. - yield return SyntaxFactory.Space; + yield return Space; } } } diff --git a/src/Analyzers/CSharp/CodeFixes/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessCodeFixProvider.cs index d7a0179652e19..137af59d50036 100644 --- a/src/Analyzers/CSharp/CodeFixes/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessCodeFixProvider.cs @@ -22,6 +22,8 @@ namespace Microsoft.CodeAnalysis.CSharp.InvokeDelegateWithConditionalAccess; +using static SyntaxFactory; + [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.InvokeDelegateWithConditionalAccess), Shared] internal partial class InvokeDelegateWithConditionalAccessCodeFixProvider : SyntaxEditorBasedCodeFixProvider { @@ -93,13 +95,13 @@ private static void HandleSingleIfStatementForm( var (invokedExpression, invokeName) = invocationExpression.Expression is MemberAccessExpressionSyntax { Name: IdentifierNameSyntax { Identifier.ValueText: nameof(Action.Invoke) } } memberAccessExpression ? (memberAccessExpression.Expression, memberAccessExpression.Name) - : (invocationExpression.Expression, SyntaxFactory.IdentifierName(nameof(Action.Invoke))); + : (invocationExpression.Expression, IdentifierName(nameof(Action.Invoke))); StatementSyntax newStatement = expressionStatement.WithExpression( - SyntaxFactory.ConditionalAccessExpression( + ConditionalAccessExpression( invokedExpression, - SyntaxFactory.InvocationExpression( - SyntaxFactory.MemberBindingExpression(invokeName), invocationExpression.ArgumentList))); + InvocationExpression( + MemberBindingExpression(invokeName), invocationExpression.ArgumentList))); newStatement = newStatement.WithPrependedLeadingTrivia(ifStatement.GetLeadingTrivia()); if (ifStatement.Parent.IsKind(SyntaxKind.ElseClause) && @@ -140,13 +142,13 @@ private static void HandleVariableAndIfStatementForm( var invokeName = invocationExpression.Expression is MemberAccessExpressionSyntax { Name: IdentifierNameSyntax { Identifier.ValueText: nameof(Action.Invoke) } } memberAccessExpression ? memberAccessExpression.Name - : SyntaxFactory.IdentifierName(nameof(Action.Invoke)); + : IdentifierName(nameof(Action.Invoke)); var newStatement = expressionStatement.WithExpression( - SyntaxFactory.ConditionalAccessExpression( + ConditionalAccessExpression( localDeclarationStatement.Declaration.Variables[0].Initializer!.Value.Parenthesize(), - SyntaxFactory.InvocationExpression( - SyntaxFactory.MemberBindingExpression(invokeName), invocationExpression.ArgumentList))); + InvocationExpression( + MemberBindingExpression(invokeName), invocationExpression.ArgumentList))); newStatement = newStatement.WithAdditionalAnnotations(Formatter.Annotation); newStatement = AppendTriviaWithoutEndOfLines(newStatement, ifStatement); diff --git a/src/Analyzers/CSharp/CodeFixes/MakeMethodAsynchronous/CSharpMakeMethodAsynchronousCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/MakeMethodAsynchronous/CSharpMakeMethodAsynchronousCodeFixProvider.cs index 40fd90e48f730..2d4eb7019566a 100644 --- a/src/Analyzers/CSharp/CodeFixes/MakeMethodAsynchronous/CSharpMakeMethodAsynchronousCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/MakeMethodAsynchronous/CSharpMakeMethodAsynchronousCodeFixProvider.cs @@ -14,10 +14,11 @@ using Microsoft.CodeAnalysis.MakeMethodAsynchronous; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.MakeMethodAsynchronous; +using static SyntaxFactory; + [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.AddAsync), Shared] internal class CSharpMakeMethodAsynchronousCodeFixProvider : AbstractMakeMethodAsynchronousCodeFixProvider { @@ -26,7 +27,7 @@ internal class CSharpMakeMethodAsynchronousCodeFixProvider : AbstractMakeMethodA private const string CS4034 = nameof(CS4034); // The 'await' operator can only be used within an async lambda expression. Consider marking this method with the 'async' modifier. private const string CS0246 = nameof(CS0246); // The type or namespace name 'await' could not be found - private static readonly SyntaxToken s_asyncToken = SyntaxFactory.Token(SyntaxKind.AsyncKeyword); + private static readonly SyntaxToken s_asyncToken = Token(SyntaxKind.AsyncKeyword); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] @@ -155,9 +156,9 @@ private static TypeSyntax FixMethodReturnType( static TypeSyntax MakeGenericType(string type, ITypeSymbol typeArgumentFrom) { - var result = SyntaxFactory.GenericName( - SyntaxFactory.Identifier(type), - SyntaxFactory.TypeArgumentList([typeArgumentFrom.GetTypeArguments()[0].GenerateTypeSyntax()])); + var result = GenericName( + Identifier(type), + TypeArgumentList([typeArgumentFrom.GetTypeArguments()[0].GenerateTypeSyntax()])); return result.WithAdditionalAnnotations(Simplifier.Annotation); } @@ -182,7 +183,7 @@ private static SyntaxTokenList AddAsyncModifierWithCorrectedTrivia(SyntaxTokenLi return modifiers.Add(s_asyncToken); // Move the leading trivia from the return type to the new modifiers list. - var result = SyntaxFactory.TokenList(s_asyncToken.WithLeadingTrivia(newReturnType.GetLeadingTrivia())); + var result = TokenList(s_asyncToken.WithLeadingTrivia(newReturnType.GetLeadingTrivia())); newReturnType = newReturnType.WithoutLeadingTrivia(); return result; } diff --git a/src/Analyzers/CSharp/CodeFixes/MakeStatementAsynchronous/CSharpMakeStatementAsynchronousCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/MakeStatementAsynchronous/CSharpMakeStatementAsynchronousCodeFixProvider.cs index 5b08afa5ecbd9..8ccbda8c1aada 100644 --- a/src/Analyzers/CSharp/CodeFixes/MakeStatementAsynchronous/CSharpMakeStatementAsynchronousCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/MakeStatementAsynchronous/CSharpMakeStatementAsynchronousCodeFixProvider.cs @@ -19,6 +19,8 @@ namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.MakeStatementAsynchronous; +using static SyntaxFactory; + [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MakeStatementAsynchronous), Shared] internal class CSharpMakeStatementAsynchronousCodeFixProvider : SyntaxEditorBasedCodeFixProvider { @@ -72,22 +74,22 @@ private static void MakeStatementAsynchronous(SyntaxEditor editor, SyntaxNode st case ForEachStatementSyntax forEach: newStatement = forEach .WithForEachKeyword(forEach.ForEachKeyword.WithLeadingTrivia()) - .WithAwaitKeyword(SyntaxFactory.Token(SyntaxKind.AwaitKeyword).WithLeadingTrivia(forEach.GetLeadingTrivia())); + .WithAwaitKeyword(Token(SyntaxKind.AwaitKeyword).WithLeadingTrivia(forEach.GetLeadingTrivia())); break; case ForEachVariableStatementSyntax forEachDeconstruction: newStatement = forEachDeconstruction .WithForEachKeyword(forEachDeconstruction.ForEachKeyword.WithLeadingTrivia()) - .WithAwaitKeyword(SyntaxFactory.Token(SyntaxKind.AwaitKeyword).WithLeadingTrivia(forEachDeconstruction.GetLeadingTrivia())); + .WithAwaitKeyword(Token(SyntaxKind.AwaitKeyword).WithLeadingTrivia(forEachDeconstruction.GetLeadingTrivia())); break; case UsingStatementSyntax usingStatement: newStatement = usingStatement .WithUsingKeyword(usingStatement.UsingKeyword.WithLeadingTrivia()) - .WithAwaitKeyword(SyntaxFactory.Token(SyntaxKind.AwaitKeyword).WithLeadingTrivia(usingStatement.GetLeadingTrivia())); + .WithAwaitKeyword(Token(SyntaxKind.AwaitKeyword).WithLeadingTrivia(usingStatement.GetLeadingTrivia())); break; case LocalDeclarationStatementSyntax localDeclaration: newStatement = localDeclaration .WithUsingKeyword(localDeclaration.UsingKeyword.WithLeadingTrivia()) - .WithAwaitKeyword(SyntaxFactory.Token(SyntaxKind.AwaitKeyword).WithLeadingTrivia(localDeclaration.GetLeadingTrivia())); + .WithAwaitKeyword(Token(SyntaxKind.AwaitKeyword).WithLeadingTrivia(localDeclaration.GetLeadingTrivia())); break; default: return; diff --git a/src/Analyzers/CSharp/CodeFixes/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementCodeFixProvider.cs index 3d54e0573d54d..6b05c0c12e76f 100644 --- a/src/Analyzers/CSharp/CodeFixes/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementCodeFixProvider.cs @@ -14,12 +14,13 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; -using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.NewLines.EmbeddedStatementPlacement; +using static SyntaxFactory; + [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.EmbeddedStatementPlacement), Shared] internal sealed class EmbeddedStatementPlacementCodeFixProvider : CodeFixProvider { @@ -52,7 +53,7 @@ public static async Task FixAllAsync(Document document, ImmutableArray var options = await document.GetCSharpCodeFixOptionsProviderAsync(codeActionOptionsProvider, cancellationToken).ConfigureAwait(false); - var endOfLineTrivia = SyntaxFactory.ElasticEndOfLine(options.NewLine); + var endOfLineTrivia = ElasticEndOfLine(options.NewLine); foreach (var diagnostic in diagnostics) FixOne(editor, diagnostic, endOfLineTrivia, cancellationToken); @@ -95,7 +96,7 @@ private static void FixOne( blockSyntax.Statements.Count == 0) { updatedStatement = blockSyntax.WithCloseBraceToken( - AddLeadingTrivia(blockSyntax.CloseBraceToken, SyntaxFactory.ElasticMarker)); + AddLeadingTrivia(blockSyntax.CloseBraceToken, ElasticMarker)); } return updatedStatement; @@ -118,11 +119,11 @@ private static void FixOne( if (!EmbeddedStatementPlacementDiagnosticAnalyzer.ContainsEndOfLineBetween(previousToken, openBrace)) { currentBlock = currentBlock.WithOpenBraceToken( - AddLeadingTrivia(currentBlock.OpenBraceToken, SyntaxFactory.ElasticMarker)); + AddLeadingTrivia(currentBlock.OpenBraceToken, ElasticMarker)); } return currentBlock.WithCloseBraceToken( - AddLeadingTrivia(currentBlock.CloseBraceToken, SyntaxFactory.ElasticMarker)); + AddLeadingTrivia(currentBlock.CloseBraceToken, ElasticMarker)); }); } } diff --git a/src/Analyzers/CSharp/CodeFixes/RemoveUnusedParametersAndValues/CSharpRemoveUnusedValuesCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/RemoveUnusedParametersAndValues/CSharpRemoveUnusedValuesCodeFixProvider.cs index 703e7c6d2210d..d80b9b34b4eaa 100644 --- a/src/Analyzers/CSharp/CodeFixes/RemoveUnusedParametersAndValues/CSharpRemoveUnusedValuesCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/RemoveUnusedParametersAndValues/CSharpRemoveUnusedValuesCodeFixProvider.cs @@ -21,6 +21,8 @@ namespace Microsoft.CodeAnalysis.CSharp.RemoveUnusedParametersAndValues; +using static SyntaxFactory; + [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveUnusedValues), Shared] [ExtensionOrder(After = PredefinedCodeFixProviderNames.AddImport)] internal class CSharpRemoveUnusedValuesCodeFixProvider : @@ -38,7 +40,7 @@ protected override ISyntaxFormatting GetSyntaxFormatting() => CSharpSyntaxFormatting.Instance; protected override BlockSyntax WrapWithBlockIfNecessary(IEnumerable statements) - => SyntaxFactory.Block(statements); + => Block(statements); protected override SyntaxToken GetForEachStatementIdentifier(ForEachStatementSyntax node) => node.Identifier; @@ -63,7 +65,7 @@ protected override SyntaxNode TryUpdateNameForFlaggedNode(SyntaxNode node, Synta // If we are generating a discard on the left of an initialization with an implicit object creation on the right, // then we need to replace the implicit object creation with an explicit one. // For example: 'TypeName v = new();' must be changed to '_ = new TypeName();' - var objectCreationNode = SyntaxFactory.ObjectCreationExpression( + var objectCreationNode = ObjectCreationExpression( newKeyword: implicitObjectCreation.NewKeyword, type: parent.Type, argumentList: implicitObjectCreation.ArgumentList, @@ -75,8 +77,8 @@ protected override SyntaxNode TryUpdateNameForFlaggedNode(SyntaxNode node, Synta case SyntaxKind.SingleVariableDesignation: return newName.ValueText == AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.DiscardVariableName - ? SyntaxFactory.DiscardDesignation().WithTriviaFrom(node) - : SyntaxFactory.SingleVariableDesignation(newName).WithTriviaFrom(node); + ? DiscardDesignation().WithTriviaFrom(node) + : SingleVariableDesignation(newName).WithTriviaFrom(node); case SyntaxKind.CatchDeclaration: var catchDeclaration = (CatchDeclarationSyntax)node; @@ -84,8 +86,8 @@ protected override SyntaxNode TryUpdateNameForFlaggedNode(SyntaxNode node, Synta case SyntaxKind.VarPattern: return node.IsParentKind(SyntaxKind.Subpattern) - ? SyntaxFactory.DiscardPattern().WithTriviaFrom(node) - : SyntaxFactory.DiscardDesignation(); + ? DiscardPattern().WithTriviaFrom(node) + : DiscardDesignation(); default: Debug.Fail($"Unexpected node kind for local/parameter declaration or reference: '{node.Kind()}'"); @@ -105,7 +107,7 @@ protected override SyntaxNode TryUpdateParentOfUpdatedNode(SyntaxNode parent, Sy parent.SyntaxTree.Options.LanguageVersion() >= LanguageVersion.CSharp9) { var trailingTrivia = declarationPattern.Type.GetTrailingTrivia().AddRange(triviaToAppend); - return SyntaxFactory.TypePattern(declarationPattern.Type).WithTrailingTrivia(trailingTrivia); + return TypePattern(declarationPattern.Type).WithTrailingTrivia(trailingTrivia); } // 1) `... is { } variable` -> `... is { }` @@ -132,7 +134,7 @@ assignment.Right is ImplicitObjectCreationExpressionSyntax implicitObjectCreatio // If we are generating a discard on the left of an assignment with an implicit object creation on the right, // then we need to replace the implicit object creation with an explicit one. // For example: 'v = new();' must be changed to '_ = new TypeOfV();' - var objectCreationNode = SyntaxFactory.ObjectCreationExpression( + var objectCreationNode = ObjectCreationExpression( newKeyword: implicitObjectCreation.NewKeyword, type: type.GenerateTypeSyntax(allowVar: false), argumentList: implicitObjectCreation.ArgumentList, @@ -227,7 +229,7 @@ protected override SyntaxNode GetReplacementNodeForCompoundAssignment( // Remove leading trivia from 'leftOfAssignment' as it should have been moved to 'newAssignmentTarget'. leftOfAssignment = leftOfAssignment.WithoutLeadingTrivia(); return editor.Generator.AssignmentStatement(newAssignmentTarget, - SyntaxFactory.BinaryExpression(SyntaxKind.CoalesceExpression, leftOfAssignment, rightOfAssignment)); + BinaryExpression(SyntaxKind.CoalesceExpression, leftOfAssignment, rightOfAssignment)); } } else @@ -239,7 +241,7 @@ protected override SyntaxNode GetReplacementNodeForCompoundAssignment( return originalCompoundAssignment; } - return SyntaxFactory.BinaryExpression(mappedBinaryExpressionKind, leftOfAssignment, rightOfAssignment); + return BinaryExpression(mappedBinaryExpressionKind, leftOfAssignment, rightOfAssignment); } } diff --git a/src/Analyzers/CSharp/CodeFixes/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentCodeFixProvider.cs index d35d0cdf512cf..f4befd313a277 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentCodeFixProvider.cs @@ -21,6 +21,8 @@ namespace Microsoft.CodeAnalysis.CSharp.UseCompoundAssignment; +using static SyntaxFactory; + [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseCompoundCoalesceAssignment), Shared] internal class CSharpUseCompoundCoalesceAssignmentCodeFixProvider : SyntaxEditorBasedCodeFixProvider { @@ -59,10 +61,10 @@ protected override async Task FixAllAsync( // we have `if (x is null) x = y;`. Update `x = y` to be `x ??= y`, then replace the entire // if-statement with that assignment statement. - var newAssignment = SyntaxFactory.AssignmentExpression( + var newAssignment = AssignmentExpression( SyntaxKind.CoalesceAssignmentExpression, assignment.Left, - SyntaxFactory.Token(SyntaxKind.QuestionQuestionEqualsToken).WithTriviaFrom(assignment.OperatorToken), + Token(SyntaxKind.QuestionQuestionEqualsToken).WithTriviaFrom(assignment.OperatorToken), assignment.Right).WithTriviaFrom(assignment); var newWhenTrueStatement = whenTrueStatement.ReplaceNode(assignment, newAssignment); @@ -105,8 +107,8 @@ protected override async Task FixAllAsync( var coalesceRight = (ParenthesizedExpressionSyntax)currentCoalesce.Right; var assignment = (AssignmentExpressionSyntax)coalesceRight.Expression; - var compoundOperator = SyntaxFactory.Token(SyntaxKind.QuestionQuestionEqualsToken); - var finalAssignment = SyntaxFactory.AssignmentExpression( + var compoundOperator = Token(SyntaxKind.QuestionQuestionEqualsToken); + var finalAssignment = AssignmentExpression( SyntaxKind.CoalesceAssignmentExpression, assignment.Left, compoundOperator.WithTriviaFrom(assignment.OperatorToken), diff --git a/src/Analyzers/CSharp/CodeFixes/UseDeconstruction/CSharpUseDeconstructionCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseDeconstruction/CSharpUseDeconstructionCodeFixProvider.cs index 388f25d9c52c8..7a6408f8eefbe 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseDeconstruction/CSharpUseDeconstructionCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseDeconstruction/CSharpUseDeconstructionCodeFixProvider.cs @@ -21,6 +21,8 @@ namespace Microsoft.CodeAnalysis.CSharp.UseDeconstruction; +using static SyntaxFactory; + [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseDeconstruction), Shared] internal sealed class CSharpUseDeconstructionCodeFixProvider : SyntaxEditorBasedCodeFixProvider { @@ -121,7 +123,7 @@ private ForEachVariableStatementSyntax CreateForEachVariableStatement(INamedType // Copy all the tokens/nodes from the existing foreach statement to the new foreach statement. // However, convert the existing declaration over to a "var (x, y)" declaration or (int x, int y) // tuple expression. - return SyntaxFactory.ForEachVariableStatement( + return ForEachVariableStatement( forEachStatement.AttributeLists, forEachStatement.AwaitKeyword, forEachStatement.ForEachKeyword, @@ -139,8 +141,8 @@ private ExpressionStatementSyntax CreateDeconstructionStatement( // Copy all the tokens/nodes from the existing declaration statement to the new assignment // statement. However, convert the existing declaration over to a "var (x, y)" declaration // or (int x, int y) tuple expression. - return SyntaxFactory.ExpressionStatement( - SyntaxFactory.AssignmentExpression( + return ExpressionStatement( + AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, CreateTupleOrDeclarationExpression(tupleType, declarationStatement.Declaration.Type), variableDeclarator.Initializer.EqualsToken, @@ -160,15 +162,15 @@ private ExpressionSyntax CreateTupleOrDeclarationExpression(INamedTypeSymbol tup } private static DeclarationExpressionSyntax CreateDeclarationExpression(INamedTypeSymbol tupleType, TypeSyntax typeNode) - => SyntaxFactory.DeclarationExpression( - typeNode, SyntaxFactory.ParenthesizedVariableDesignation( + => DeclarationExpression( + typeNode, ParenthesizedVariableDesignation( [.. tupleType.TupleElements.Select( - e => SyntaxFactory.SingleVariableDesignation(SyntaxFactory.Identifier(e.Name.EscapeIdentifier())))])); + e => SingleVariableDesignation(Identifier(e.Name.EscapeIdentifier())))])); private TupleExpressionSyntax CreateTupleExpression(TupleTypeSyntax typeNode) - => SyntaxFactory.TupleExpression( + => TupleExpression( typeNode.OpenParenToken, - SyntaxFactory.SeparatedList(new SyntaxNodeOrTokenList(typeNode.Elements.GetWithSeparators().Select(ConvertTupleTypeElementComponent))), + SeparatedList(new SyntaxNodeOrTokenList(typeNode.Elements.GetWithSeparators().Select(ConvertTupleTypeElementComponent))), typeNode.CloseParenToken); private SyntaxNodeOrToken ConvertTupleTypeElementComponent(SyntaxNodeOrToken nodeOrToken) @@ -182,9 +184,9 @@ private SyntaxNodeOrToken ConvertTupleTypeElementComponent(SyntaxNodeOrToken nod // "int x" as a tuple element directly translates to "int x" (a declaration expression // with a variable designation 'x'). var node = (TupleElementSyntax)nodeOrToken.AsNode(); - return SyntaxFactory.Argument( - SyntaxFactory.DeclarationExpression( + return Argument( + DeclarationExpression( node.Type, - SyntaxFactory.SingleVariableDesignation(node.Identifier))); + SingleVariableDesignation(node.Identifier))); } } diff --git a/src/Analyzers/CSharp/CodeFixes/UseExpressionBodyForLambda/UseExpressionBodyForLambdaCodeActionHelpers.cs b/src/Analyzers/CSharp/CodeFixes/UseExpressionBodyForLambda/UseExpressionBodyForLambdaCodeActionHelpers.cs index 1eed151ee7e16..720b7efe502e2 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseExpressionBodyForLambda/UseExpressionBodyForLambdaCodeActionHelpers.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseExpressionBodyForLambda/UseExpressionBodyForLambdaCodeActionHelpers.cs @@ -14,6 +14,8 @@ namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.UseExpressionBodyForLambda; +using static SyntaxFactory; + internal static class UseExpressionBodyForLambdaCodeActionHelpers { internal static LambdaExpressionSyntax Update(SemanticModel semanticModel, LambdaExpressionSyntax originalDeclaration, LambdaExpressionSyntax currentDeclaration, CancellationToken cancellationToken) @@ -43,7 +45,7 @@ private static LambdaExpressionSyntax WithExpressionBody(LambdaExpressionSyntax if (declaration.ArrowToken.TrailingTrivia.All(t => t.IsWhitespaceOrEndOfLine()) && expressionBody.GetLeadingTrivia().All(t => t.IsWhitespaceOrEndOfLine())) { - updatedDecl = updatedDecl.WithArrowToken(updatedDecl.ArrowToken.WithTrailingTrivia(SyntaxFactory.ElasticSpace)); + updatedDecl = updatedDecl.WithArrowToken(updatedDecl.ArrowToken.WithTrailingTrivia(ElasticSpace)); } return updatedDecl; @@ -66,10 +68,10 @@ private static LambdaExpressionSyntax WithBlockBody( // If the user is converting to a block, it's likely they intend to add multiple // statements to it. So make a multi-line block so that things are formatted properly // for them to do so. - return currentDeclaration.WithBody(SyntaxFactory.Block( - SyntaxFactory.Token(SyntaxKind.OpenBraceToken).WithAppendedTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed), + return currentDeclaration.WithBody(Block( + Token(SyntaxKind.OpenBraceToken).WithAppendedTrailingTrivia(ElasticCarriageReturnLineFeed), [statement], - SyntaxFactory.Token(SyntaxKind.CloseBraceToken))); + Token(SyntaxKind.CloseBraceToken))); } private static bool CreateReturnStatementForExpression( diff --git a/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseExplicitTypeCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseExplicitTypeCodeFixProvider.cs index 81e2b0a3a5647..b1eff1dd46a0d 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseExplicitTypeCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseImplicitOrExplicitType/UseExplicitTypeCodeFixProvider.cs @@ -22,6 +22,8 @@ namespace Microsoft.CodeAnalysis.CSharp.TypeStyle; +using static SyntaxFactory; + [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseExplicitType), Shared] internal class UseExplicitTypeCodeFixProvider : SyntaxEditorBasedCodeFixProvider { @@ -182,7 +184,7 @@ private static ExpressionSyntax GenerateTupleDeclaration(ITypeSymbol typeSymbol, case SyntaxKind.SingleVariableDesignation: case SyntaxKind.DiscardDesignation: var typeName = type.GenerateTypeSyntax(allowVar: false); - newDeclaration = SyntaxFactory.DeclarationExpression(typeName, designation); + newDeclaration = DeclarationExpression(typeName, designation); break; case SyntaxKind.ParenthesizedVariableDesignation: newDeclaration = GenerateTupleDeclaration(type, (ParenthesizedVariableDesignationSyntax)designation); @@ -195,15 +197,15 @@ private static ExpressionSyntax GenerateTupleDeclaration(ITypeSymbol typeSymbol, .WithLeadingTrivia(designation.GetAllPrecedingTriviaToPreviousToken()) .WithTrailingTrivia(designation.GetTrailingTrivia()); - builder.Add(SyntaxFactory.Argument(newDeclaration)); + builder.Add(Argument(newDeclaration)); } - var separatorBuilder = ArrayBuilder.GetInstance(builder.Count - 1, SyntaxFactory.Token(leading: default, SyntaxKind.CommaToken, trailing: default)); + var separatorBuilder = ArrayBuilder.GetInstance(builder.Count - 1, Token(leading: default, SyntaxKind.CommaToken, trailing: default)); - return SyntaxFactory.TupleExpression( - SyntaxFactory.Token(SyntaxKind.OpenParenToken).WithTrailingTrivia(), - SyntaxFactory.SeparatedList(builder.ToImmutable(), separatorBuilder.ToImmutableAndFree()), - SyntaxFactory.Token(SyntaxKind.CloseParenToken)) + return TupleExpression( + Token(SyntaxKind.OpenParenToken).WithTrailingTrivia(), + SeparatedList(builder.ToImmutable(), separatorBuilder.ToImmutableAndFree()), + Token(SyntaxKind.CloseParenToken)) .WithTrailingTrivia(parensDesignation.GetTrailingTrivia()); } diff --git a/src/Analyzers/CSharp/CodeFixes/UseLocalFunction/CSharpUseLocalFunctionCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseLocalFunction/CSharpUseLocalFunctionCodeFixProvider.cs index d49db09283500..f31d3acd8d152 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseLocalFunction/CSharpUseLocalFunctionCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseLocalFunction/CSharpUseLocalFunctionCodeFixProvider.cs @@ -28,10 +28,12 @@ namespace Microsoft.CodeAnalysis.CSharp.UseLocalFunction; +using static SyntaxFactory; + [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseLocalFunction), Shared] internal class CSharpUseLocalFunctionCodeFixProvider : SyntaxEditorBasedCodeFixProvider { - private static readonly TypeSyntax s_objectType = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)); + private static readonly TypeSyntax s_objectType = PredefinedType(Token(SyntaxKind.ObjectKeyword)); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] @@ -212,7 +214,7 @@ private static LocalFunctionStatementSyntax CreateLocalFunctionStatement( var modifiers = new SyntaxTokenList(); if (makeStatic) { - modifiers = modifiers.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); + modifiers = modifiers.Add(Token(SyntaxKind.StaticKeyword)); } if (anonymousFunction.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword)) @@ -232,14 +234,14 @@ private static LocalFunctionStatementSyntax CreateLocalFunctionStatement( : null; var expressionBody = anonymousFunction.Body is ExpressionSyntax expression - ? SyntaxFactory.ArrowExpressionClause(((LambdaExpressionSyntax)anonymousFunction).ArrowToken, expression) + ? ArrowExpressionClause(((LambdaExpressionSyntax)anonymousFunction).ArrowToken, expression) : null; var semicolonToken = anonymousFunction.Body is ExpressionSyntax ? localDeclaration.SemicolonToken : default; - return SyntaxFactory.LocalFunctionStatement( + return LocalFunctionStatement( modifiers, returnType, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken); } @@ -252,8 +254,8 @@ private static ParameterListSyntax GenerateParameterList( return parameterList != null ? parameterList.ReplaceNodes(parameterList.Parameters, (parameterNode, _) => PromoteParameter(generator, parameterNode, delegateMethod.Parameters.ElementAtOrDefault(i++))) - : SyntaxFactory.ParameterList([.. delegateMethod.Parameters.Select(parameter => - PromoteParameter(generator, SyntaxFactory.Parameter(parameter.Name.ToIdentifierToken()), parameter))]); + : ParameterList([.. delegateMethod.Parameters.Select(parameter => + PromoteParameter(generator, Parameter(parameter.Name.ToIdentifierToken()), parameter))]); static ParameterSyntax PromoteParameter(SyntaxGenerator generator, ParameterSyntax parameterNode, IParameterSymbol delegateParameter) { @@ -279,7 +281,7 @@ private static ParameterListSyntax TryGetOrCreateParameterList(AnonymousFunction switch (anonymousFunction) { case SimpleLambdaExpressionSyntax simpleLambda: - return SyntaxFactory.ParameterList([simpleLambda.Parameter]); + return ParameterList([simpleLambda.Parameter]); case ParenthesizedLambdaExpressionSyntax parenthesizedLambda: return parenthesizedLambda.ParameterList; case AnonymousMethodExpressionSyntax anonymousMethod: @@ -310,7 +312,7 @@ private static InvocationExpressionSyntax WithNewParameterNames(InvocationExpres return argumentNode; } - return argumentNode.WithNameColon(argumentNode.NameColon.WithName(SyntaxFactory.IdentifierName(newParameter.Identifier))); + return argumentNode.WithNameColon(argumentNode.NameColon.WithName(IdentifierName(newParameter.Identifier))); }); } @@ -321,5 +323,5 @@ private static int TryDetermineParameterIndex(NameColonSyntax argumentNameColon, } private static EqualsValueClauseSyntax GetDefaultValue(SyntaxGenerator generator, IParameterSymbol parameter) - => SyntaxFactory.EqualsValueClause(ExpressionGenerator.GenerateExpression(generator, parameter.Type, parameter.ExplicitDefaultValue, canUseFieldReference: true)); + => EqualsValueClause(ExpressionGenerator.GenerateExpression(generator, parameter.Type, parameter.ExplicitDefaultValue, canUseFieldReference: true)); } diff --git a/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpAsAndNullCheckCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpAsAndNullCheckCodeFixProvider.cs index a9fd0a6291559..c69d4c00c093f 100644 --- a/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpAsAndNullCheckCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpAsAndNullCheckCodeFixProvider.cs @@ -20,6 +20,8 @@ namespace Microsoft.CodeAnalysis.CSharp.UsePatternMatching; +using static SyntaxFactory; + [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UsePatternMatchingAsAndNullCheck), Shared] internal partial class CSharpAsAndNullCheckCodeFixProvider : SyntaxEditorBasedCodeFixProvider { @@ -103,9 +105,9 @@ private static void AddEdits( var newIdentifier = declarator.Identifier .WithoutTrivia().WithTrailingTrivia(rightSideOfComparison.GetTrailingTrivia()); - var declarationPattern = SyntaxFactory.DeclarationPattern( - GetPatternType().WithoutTrivia().WithTrailingTrivia(SyntaxFactory.ElasticMarker), - SyntaxFactory.SingleVariableDesignation(newIdentifier)); + var declarationPattern = DeclarationPattern( + GetPatternType().WithoutTrivia().WithTrailingTrivia(ElasticMarker), + SingleVariableDesignation(newIdentifier)); var condition = GetCondition(languageVersion, comparison, asExpression, declarationPattern); @@ -165,7 +167,7 @@ private static ExpressionSyntax GetCondition( BinaryExpressionSyntax asExpression, DeclarationPatternSyntax declarationPattern) { - var isPatternExpression = SyntaxFactory.IsPatternExpression(asExpression.Left, declarationPattern); + var isPatternExpression = IsPatternExpression(asExpression.Left, declarationPattern); // We should negate the is-expression if we have something like "x == null" or "x is null" if (comparison.Kind() is not (SyntaxKind.EqualsExpression or SyntaxKind.IsPatternExpression)) @@ -175,10 +177,10 @@ private static ExpressionSyntax GetCondition( { // In C# 9 and higher, convert to `x is not string s`. return isPatternExpression.WithPattern( - SyntaxFactory.UnaryPattern(SyntaxFactory.Token(SyntaxKind.NotKeyword), isPatternExpression.Pattern)); + UnaryPattern(Token(SyntaxKind.NotKeyword), isPatternExpression.Pattern)); } // In C# 8 and lower, convert to `!(x is string s)` - return SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, isPatternExpression.Parenthesize()); + return PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, isPatternExpression.Parenthesize()); } } diff --git a/src/Analyzers/CSharp/CodeFixes/UseUtf8StringLiteral/UseUtf8StringLiteralCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseUtf8StringLiteral/UseUtf8StringLiteralCodeFixProvider.cs index 4ad6082755661..2d77751619c70 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseUtf8StringLiteral/UseUtf8StringLiteralCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseUtf8StringLiteral/UseUtf8StringLiteralCodeFixProvider.cs @@ -21,6 +21,8 @@ namespace Microsoft.CodeAnalysis.CSharp.UseUtf8StringLiteral; +using static SyntaxFactory; + [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseUtf8StringLiteral), Shared] internal sealed class UseUtf8StringLiteralCodeFixProvider : SyntaxEditorBasedCodeFixProvider { @@ -173,14 +175,14 @@ private static SyntaxNode CreateArgumentListWithUtf8String(BaseArgumentListSynta // We don't need to worry about leading trivia here, because anything before the current // argument will have been trailing trivia on the previous comma. var stringLiteral = CreateUtf8String(SyntaxTriviaList.Empty, stringValue, argumentList.Arguments.Last().GetTrailingTrivia(), isConvertedToReadOnlySpan); - arguments.Add(SyntaxFactory.Argument(stringLiteral)); + arguments.Add(Argument(stringLiteral)); break; } arguments.Add(argument); } - return argumentList.WithArguments(SyntaxFactory.SeparatedList(arguments)); + return argumentList.WithArguments(SeparatedList(arguments)); } private static ExpressionSyntax CreateUtf8String(SyntaxNode nodeToTakeTriviaFrom, string stringValue, bool isConvertedToReadOnlySpan) @@ -190,8 +192,8 @@ private static ExpressionSyntax CreateUtf8String(SyntaxNode nodeToTakeTriviaFrom private static ExpressionSyntax CreateUtf8String(SyntaxTriviaList leadingTrivia, string stringValue, SyntaxTriviaList trailingTrivia, bool isConvertedToReadOnlySpan) { - var stringLiteral = SyntaxFactory.LiteralExpression(SyntaxKind.Utf8StringLiteralExpression, - SyntaxFactory.Token( + var stringLiteral = LiteralExpression(SyntaxKind.Utf8StringLiteralExpression, + Token( leading: leadingTrivia, kind: SyntaxKind.Utf8StringLiteralToken, text: QuoteCharacter + stringValue + QuoteCharacter + Suffix, @@ -205,11 +207,11 @@ private static ExpressionSyntax CreateUtf8String(SyntaxTriviaList leadingTrivia, // We're replacing a byte array with a ReadOnlySpan, so if that byte array wasn't originally being // converted to the same, then we need to call .ToArray() to get things back to a byte array. - return SyntaxFactory.InvocationExpression( - SyntaxFactory.MemberAccessExpression( + return InvocationExpression( + MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, stringLiteral, - SyntaxFactory.IdentifierName(nameof(ReadOnlySpan.ToArray)))) + IdentifierName(nameof(ReadOnlySpan.ToArray)))) .WithTrailingTrivia(trailingTrivia); } } diff --git a/src/EditorFeatures/CSharp/AutomaticCompletion/AutomaticLineEnderCommandHandler_Helpers.cs b/src/EditorFeatures/CSharp/AutomaticCompletion/AutomaticLineEnderCommandHandler_Helpers.cs index 4f2b7ca71e26b..dd1212001bfba 100644 --- a/src/EditorFeatures/CSharp/AutomaticCompletion/AutomaticLineEnderCommandHandler_Helpers.cs +++ b/src/EditorFeatures/CSharp/AutomaticCompletion/AutomaticLineEnderCommandHandler_Helpers.cs @@ -18,6 +18,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.AutomaticCompletion; +using static SyntaxFactory; + internal partial class AutomaticLineEnderCommandHandler { #region NodeReplacementHelpers @@ -394,7 +396,7 @@ private static (SyntaxNode newNode, SyntaxNode oldNode) ModifyObjectCreationExpr (_, _) => objectCreationNodeWithCorrectInitializer.WithoutTrailingTrivia(), tokens: [nextToken], computeReplacementToken: (_, _) => - SyntaxFactory.Token(SyntaxKind.SemicolonToken).WithTrailingTrivia(objectCreationNodeWithCorrectInitializer.GetTrailingTrivia()), + Token(SyntaxKind.SemicolonToken).WithTrailingTrivia(objectCreationNodeWithCorrectInitializer.GetTrailingTrivia()), trivia: [], computeReplacementTrivia: (_, syntaxTrivia) => syntaxTrivia); return (replacementContainerNode, objectCreationNodeContainer); @@ -427,15 +429,15 @@ private static BaseObjectCreationExpressionSyntax WithArgumentListIfNeeded(BaseO // There is only 'new' keyword in the object creation expression. Treat it as an ImplicitObjectCreationExpression. // This could happen because when only type 'new', parser would think it is an ObjectCreationExpression. var newKeywordToken = baseObjectCreationExpressionNode.NewKeyword; - var newArgumentList = SyntaxFactory.ArgumentList().WithTrailingTrivia(newKeywordToken.TrailingTrivia); - return SyntaxFactory.ImplicitObjectCreationExpression(newKeywordToken.WithoutTrailingTrivia(), newArgumentList, baseObjectCreationExpressionNode.Initializer); + var newArgumentList = ArgumentList().WithTrailingTrivia(newKeywordToken.TrailingTrivia); + return ImplicitObjectCreationExpression(newKeywordToken.WithoutTrailingTrivia(), newArgumentList, baseObjectCreationExpressionNode.Initializer); } else { // Make sure the trailing trivia is passed to the argument list // like var l = new List\r\n => // var l = new List()\r\r - var newArgumentList = SyntaxFactory.ArgumentList().WithTrailingTrivia(typeNode.GetTrailingTrivia()); + var newArgumentList = ArgumentList().WithTrailingTrivia(typeNode.GetTrailingTrivia()); var newTypeNode = typeNode.WithoutTrivia(); return objectCreationExpressionNode.WithType(newTypeNode).WithArgumentList(newArgumentList); } @@ -444,8 +446,8 @@ private static BaseObjectCreationExpressionSyntax WithArgumentListIfNeeded(BaseO if (baseObjectCreationExpressionNode is ImplicitObjectCreationExpressionSyntax implicitObjectCreationExpressionNode) { var newKeywordToken = implicitObjectCreationExpressionNode.NewKeyword; - var newArgumentList = SyntaxFactory.ArgumentList().WithTrailingTrivia(newKeywordToken.TrailingTrivia); - return SyntaxFactory.ImplicitObjectCreationExpression(newKeywordToken.WithoutTrailingTrivia(), newArgumentList, baseObjectCreationExpressionNode.Initializer); + var newArgumentList = ArgumentList().WithTrailingTrivia(newKeywordToken.TrailingTrivia); + return ImplicitObjectCreationExpression(newKeywordToken.WithoutTrailingTrivia(), newArgumentList, baseObjectCreationExpressionNode.Initializer); } RoslynDebug.Assert(false, $"New derived type of {nameof(BaseObjectCreationExpressionSyntax)} is added"); @@ -834,24 +836,24 @@ private static bool ShouldRemoveBraceForEventDeclaration(EventDeclarationSyntax #region AddBrace private static AccessorListSyntax GetAccessorListNode(SyntaxFormattingOptions formattingOptions) - => SyntaxFactory.AccessorList().WithOpenBraceToken(GetOpenBrace(formattingOptions)).WithCloseBraceToken(GetCloseBrace(formattingOptions)); + => AccessorList().WithOpenBraceToken(GetOpenBrace(formattingOptions)).WithCloseBraceToken(GetCloseBrace(formattingOptions)); private static InitializerExpressionSyntax GetInitializerExpressionNode(SyntaxFormattingOptions formattingOptions) - => SyntaxFactory.InitializerExpression(SyntaxKind.ObjectInitializerExpression) + => InitializerExpression(SyntaxKind.ObjectInitializerExpression) .WithOpenBraceToken(GetOpenBrace(formattingOptions)); private static BlockSyntax GetBlockNode(SyntaxFormattingOptions formattingOptions) - => SyntaxFactory.Block().WithOpenBraceToken(GetOpenBrace(formattingOptions)).WithCloseBraceToken(GetCloseBrace(formattingOptions)); + => Block().WithOpenBraceToken(GetOpenBrace(formattingOptions)).WithCloseBraceToken(GetCloseBrace(formattingOptions)); private static SyntaxToken GetOpenBrace(SyntaxFormattingOptions formattingOptions) - => SyntaxFactory.Token( + => Token( leading: SyntaxTriviaList.Empty, kind: SyntaxKind.OpenBraceToken, trailing: [GetNewLineTrivia(formattingOptions)]) .WithAdditionalAnnotations(s_openBracePositionAnnotation); private static SyntaxToken GetCloseBrace(SyntaxFormattingOptions formattingOptions) - => SyntaxFactory.Token( + => Token( leading: SyntaxTriviaList.Empty, kind: SyntaxKind.CloseBraceToken, trailing: [GetNewLineTrivia(formattingOptions)]); @@ -859,7 +861,7 @@ private static SyntaxToken GetCloseBrace(SyntaxFormattingOptions formattingOptio private static SyntaxTrivia GetNewLineTrivia(SyntaxFormattingOptions formattingOptions) { var newLineString = formattingOptions.NewLine; - return SyntaxFactory.EndOfLine(newLineString); + return EndOfLine(newLineString); } /// @@ -885,7 +887,7 @@ private static BaseTypeDeclarationSyntax WithBracesForBaseTypeDeclaration( BaseTypeDeclarationSyntax baseTypeDeclarationNode, SyntaxFormattingOptions formattingOptions) => baseTypeDeclarationNode.WithOpenBraceToken(GetOpenBrace(formattingOptions)) - .WithCloseBraceToken(SyntaxFactory.Token(SyntaxKind.CloseBraceToken)); + .WithCloseBraceToken(Token(SyntaxKind.CloseBraceToken)); /// /// Add an empty initializer to . @@ -903,7 +905,7 @@ private static BaseMethodDeclarationSyntax AddBlockToBaseMethodDeclaration( SyntaxFormattingOptions formattingOptions) => baseMethodDeclarationNode.WithBody(GetBlockNode(formattingOptions)) // When the method declaration with no body is parsed, it has an invisible trailing semicolon. Make sure it is removed. - .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)); + .WithSemicolonToken(Token(SyntaxKind.None)); /// /// Add an empty block to . @@ -913,7 +915,7 @@ private static LocalFunctionStatementSyntax AddBlockToLocalFunctionDeclaration( SyntaxFormattingOptions formattingOptions) => localFunctionStatementNode.WithBody(GetBlockNode(formattingOptions)) // When the local method declaration with no body is parsed, it has an invisible trailing semicolon. Make sure it is removed. - .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)); + .WithSemicolonToken(Token(SyntaxKind.None)); /// /// Add an empty block to . @@ -923,7 +925,7 @@ private static AccessorDeclarationSyntax AddBlockToAccessorDeclaration( SyntaxFormattingOptions formattingOptions) => accessorDeclarationNode.WithBody(GetBlockNode(formattingOptions)) // When the accessor with no body is parsed, it has an invisible trailing semicolon. Make sure it is removed. - .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)); + .WithSemicolonToken(Token(SyntaxKind.None)); /// /// Add a block with to @@ -1001,25 +1003,25 @@ private static BaseObjectCreationExpressionSyntax RemoveInitializerForBaseObject /// private static FieldDeclarationSyntax ConvertPropertyDeclarationToFieldDeclaration( PropertyDeclarationSyntax propertyDeclarationNode) - => SyntaxFactory.FieldDeclaration( + => FieldDeclaration( propertyDeclarationNode.AttributeLists, propertyDeclarationNode.Modifiers, - SyntaxFactory.VariableDeclaration( + VariableDeclaration( propertyDeclarationNode.Type, - [SyntaxFactory.VariableDeclarator(propertyDeclarationNode.Identifier)]), - SyntaxFactory.Token(SyntaxKind.SemicolonToken)); + [VariableDeclarator(propertyDeclarationNode.Identifier)]), + Token(SyntaxKind.SemicolonToken)); /// /// Convert to EventFieldDeclaration. /// private static EventFieldDeclarationSyntax ConvertEventDeclarationToEventFieldDeclaration( EventDeclarationSyntax eventDeclarationNode) - => SyntaxFactory.EventFieldDeclaration( + => EventFieldDeclaration( eventDeclarationNode.AttributeLists, eventDeclarationNode.Modifiers, - SyntaxFactory.VariableDeclaration( + VariableDeclaration( eventDeclarationNode.Type, - [SyntaxFactory.VariableDeclarator(eventDeclarationNode.Identifier)])); + [VariableDeclarator(eventDeclarationNode.Identifier)])); /// /// Remove the body of . @@ -1027,7 +1029,7 @@ private static EventFieldDeclarationSyntax ConvertEventDeclarationToEventFieldDe private static AccessorDeclarationSyntax RemoveBodyForAccessorDeclarationNode(AccessorDeclarationSyntax accessorDeclarationNode) => accessorDeclarationNode .WithBody(null).WithoutTrailingTrivia().WithSemicolonToken( - SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.SemicolonToken, SyntaxTriviaList.Empty)); + Token(SyntaxTriviaList.Empty, SyntaxKind.SemicolonToken, SyntaxTriviaList.Empty)); #endregion } diff --git a/src/Features/CSharp/Portable/AddImport/CSharpAddImportFeatureService.cs b/src/Features/CSharp/Portable/AddImport/CSharpAddImportFeatureService.cs index 3e6f09860dc1e..34f2fc68518d3 100644 --- a/src/Features/CSharp/Portable/AddImport/CSharpAddImportFeatureService.cs +++ b/src/Features/CSharp/Portable/AddImport/CSharpAddImportFeatureService.cs @@ -13,8 +13,6 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.AddImport; -using Microsoft.CodeAnalysis.CodeGeneration; -using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; @@ -23,7 +21,6 @@ using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageService; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; @@ -31,6 +28,8 @@ namespace Microsoft.CodeAnalysis.CSharp.AddImport; +using static SyntaxFactory; + [ExportLanguageService(typeof(IAddImportFeatureService), LanguageNames.CSharp), Shared] internal class CSharpAddImportFeatureService : AbstractAddImportFeatureService { @@ -386,7 +385,7 @@ protected override async Task AddImportAsync( { var root = GetCompilationUnitSyntaxNode(contextNode, cancellationToken); - var usingDirective = SyntaxFactory.UsingDirective( + var usingDirective = UsingDirective( CreateNameSyntax(namespaceParts, namespaceParts.Count - 1)); var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); @@ -406,10 +405,10 @@ private static NameSyntax CreateNameSyntax(IReadOnlyList namespaceParts, part = "@" + part; } - var namePiece = SyntaxFactory.IdentifierName(part); + var namePiece = IdentifierName(part); return index == 0 ? namePiece - : SyntaxFactory.QualifiedName(CreateNameSyntax(namespaceParts, index - 1), namePiece); + : QualifiedName(CreateNameSyntax(namespaceParts, index - 1), namePiece); } private static (ExternAliasDirectiveSyntax, bool hasExistingImport) GetExternAliasDirective( @@ -423,7 +422,7 @@ private static (ExternAliasDirectiveSyntax, bool hasExistingImport) GetExternAli return (null, false); } - return (SyntaxFactory.ExternAliasDirective(SyntaxFactory.Identifier(val)) + return (ExternAliasDirective(Identifier(val)) .WithAdditionalAnnotations(Formatter.Annotation), hasExistingExtern); } @@ -447,7 +446,7 @@ private static (UsingDirectiveSyntax, bool hasExistingImport) GetUsingDirective( // from it if necessary). So we first create a dummy using directive just to // determine which container we're going in. Then we'll use the container to // help create the final using. - var dummyUsing = SyntaxFactory.UsingDirective(nameSyntax); + var dummyUsing = UsingDirective(nameSyntax); var container = addImportService.GetImportContainer(root, contextNode, dummyUsing, options); var namespaceToAddTo = container as BaseNamespaceDeclarationSyntax; @@ -460,7 +459,7 @@ private static (UsingDirectiveSyntax, bool hasExistingImport) GetUsingDirective( var externAlias = externAliasDirective?.Identifier.ValueText; if (externAlias != null) { - nameSyntax = AddOrReplaceAlias(nameSyntax, SyntaxFactory.IdentifierName(externAlias)); + nameSyntax = AddOrReplaceAlias(nameSyntax, IdentifierName(externAlias)); } else { @@ -476,12 +475,12 @@ private static (UsingDirectiveSyntax, bool hasExistingImport) GetUsingDirective( nameSyntax = RemoveGlobalAliasIfUnnecessary(semanticModel, nameSyntax, namespaceToAddTo); } - var usingDirective = SyntaxFactory.UsingDirective(nameSyntax) + var usingDirective = UsingDirective(nameSyntax) .WithAdditionalAnnotations(Formatter.Annotation); usingDirective = namespaceOrTypeSymbol.IsKind(SymbolKind.Namespace) ? usingDirective - : usingDirective.WithStaticKeyword(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); + : usingDirective.WithStaticKeyword(Token(SyntaxKind.StaticKeyword)); return (usingDirective, addImportService.HasExistingImport(semanticModel.Compilation, root, contextNode, usingDirective, generator)); } @@ -537,7 +536,7 @@ private static NameSyntax AddOrReplaceAlias( { if (nameSyntax is SimpleNameSyntax simpleName) { - return SyntaxFactory.AliasQualifiedName(alias, simpleName); + return AliasQualifiedName(alias, simpleName); } if (nameSyntax is QualifiedNameSyntax qualifiedName) diff --git a/src/Features/CSharp/Portable/CodeFixes/Suppression/CSharpSuppressionCodeFixProvider.cs b/src/Features/CSharp/Portable/CodeFixes/Suppression/CSharpSuppressionCodeFixProvider.cs index e1d5eb92ca431..46f2562b73467 100644 --- a/src/Features/CSharp/Portable/CodeFixes/Suppression/CSharpSuppressionCodeFixProvider.cs +++ b/src/Features/CSharp/Portable/CodeFixes/Suppression/CSharpSuppressionCodeFixProvider.cs @@ -23,6 +23,8 @@ namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.Suppression; +using static SyntaxFactory; + [ExportConfigurationFixProvider(PredefinedConfigurationFixProviderNames.Suppression, LanguageNames.CSharp), Shared] internal class CSharpSuppressionCodeFixProvider : AbstractSuppressionCodeFixProvider { @@ -34,14 +36,14 @@ public CSharpSuppressionCodeFixProvider() protected override SyntaxTriviaList CreatePragmaRestoreDirectiveTrivia(Diagnostic diagnostic, Func formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine, CancellationToken cancellationToken) { - var restoreKeyword = SyntaxFactory.Token(SyntaxKind.RestoreKeyword); + var restoreKeyword = Token(SyntaxKind.RestoreKeyword); return CreatePragmaDirectiveTrivia(restoreKeyword, diagnostic, formatNode, needsLeadingEndOfLine, needsTrailingEndOfLine, cancellationToken); } protected override SyntaxTriviaList CreatePragmaDisableDirectiveTrivia( Diagnostic diagnostic, Func formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine, CancellationToken cancellationToken) { - var disableKeyword = SyntaxFactory.Token(SyntaxKind.DisableKeyword); + var disableKeyword = Token(SyntaxKind.DisableKeyword); return CreatePragmaDirectiveTrivia(disableKeyword, diagnostic, formatNode, needsLeadingEndOfLine, needsTrailingEndOfLine, cancellationToken); } @@ -49,18 +51,18 @@ private static SyntaxTriviaList CreatePragmaDirectiveTrivia( SyntaxToken disableOrRestoreKeyword, Diagnostic diagnostic, Func formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine, CancellationToken cancellationToken) { var diagnosticId = GetOrMapDiagnosticId(diagnostic, out var includeTitle); - var id = SyntaxFactory.IdentifierName(diagnosticId); + var id = IdentifierName(diagnosticId); var ids = new SeparatedSyntaxList().Add(id); - var pragmaDirective = SyntaxFactory.PragmaWarningDirectiveTrivia(disableOrRestoreKeyword, ids, true); + var pragmaDirective = PragmaWarningDirectiveTrivia(disableOrRestoreKeyword, ids, true); pragmaDirective = (PragmaWarningDirectiveTriviaSyntax)formatNode(pragmaDirective, cancellationToken); - var pragmaDirectiveTrivia = SyntaxFactory.Trivia(pragmaDirective); - var endOfLineTrivia = SyntaxFactory.CarriageReturnLineFeed; - var triviaList = SyntaxFactory.TriviaList(pragmaDirectiveTrivia); + var pragmaDirectiveTrivia = Trivia(pragmaDirective); + var endOfLineTrivia = CarriageReturnLineFeed; + var triviaList = TriviaList(pragmaDirectiveTrivia); var title = includeTitle ? diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture) : null; if (!string.IsNullOrWhiteSpace(title)) { - var titleComment = SyntaxFactory.Comment(string.Format(" // {0}", title)).WithAdditionalAnnotations(Formatter.Annotation); + var titleComment = Comment(string.Format(" // {0}", title)).WithAdditionalAnnotations(Formatter.Annotation); triviaList = triviaList.Add(titleComment); } @@ -119,7 +121,7 @@ protected override SyntaxNode AddGlobalSuppressMessageAttribute( leadingTrivia: default)); if (isFirst && !newRoot.HasLeadingTrivia) - compilationRoot = compilationRoot.WithLeadingTrivia(SyntaxFactory.Comment(GlobalSuppressionsFileHeaderComment)); + compilationRoot = compilationRoot.WithLeadingTrivia(Comment(GlobalSuppressionsFileHeaderComment)); return compilationRoot; } @@ -156,17 +158,17 @@ private static AttributeListSyntax CreateAttributeList( var attributeArguments = CreateAttributeArguments(targetSymbol, diagnostic, isAssemblyAttribute); var attributes = new SeparatedSyntaxList() - .Add(SyntaxFactory.Attribute(attributeName, attributeArguments)); + .Add(Attribute(attributeName, attributeArguments)); AttributeListSyntax attributeList; if (isAssemblyAttribute) { - var targetSpecifier = SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword)); - attributeList = SyntaxFactory.AttributeList(targetSpecifier, attributes); + var targetSpecifier = AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)); + attributeList = AttributeList(targetSpecifier, attributes); } else { - attributeList = SyntaxFactory.AttributeList(attributes); + attributeList = AttributeList(attributes); } return attributeList.WithLeadingTrivia(leadingTrivia); @@ -175,30 +177,30 @@ private static AttributeListSyntax CreateAttributeList( private static AttributeArgumentListSyntax CreateAttributeArguments(ISymbol targetSymbol, Diagnostic diagnostic, bool isAssemblyAttribute) { // SuppressMessage("Rule Category", "Rule Id", Justification = nameof(Justification), Scope = nameof(Scope), Target = nameof(Target)) - var category = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(diagnostic.Descriptor.Category)); - var categoryArgument = SyntaxFactory.AttributeArgument(category); + var category = LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(diagnostic.Descriptor.Category)); + var categoryArgument = AttributeArgument(category); var title = diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture); var ruleIdText = string.IsNullOrWhiteSpace(title) ? diagnostic.Id : string.Format("{0}:{1}", diagnostic.Id, title); - var ruleId = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(ruleIdText)); - var ruleIdArgument = SyntaxFactory.AttributeArgument(ruleId); + var ruleId = LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(ruleIdText)); + var ruleIdArgument = AttributeArgument(ruleId); - var justificationExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(FeaturesResources.Pending)); - var justificationArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Justification"), nameColon: null, expression: justificationExpr); + var justificationExpr = LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(FeaturesResources.Pending)); + var justificationArgument = AttributeArgument(NameEquals("Justification"), nameColon: null, expression: justificationExpr); - var attributeArgumentList = SyntaxFactory.AttributeArgumentList().AddArguments(categoryArgument, ruleIdArgument, justificationArgument); + var attributeArgumentList = AttributeArgumentList().AddArguments(categoryArgument, ruleIdArgument, justificationArgument); if (isAssemblyAttribute) { var scopeString = GetScopeString(targetSymbol.Kind); if (scopeString != null) { - var scopeExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(scopeString)); - var scopeArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Scope"), nameColon: null, expression: scopeExpr); + var scopeExpr = LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(scopeString)); + var scopeArgument = AttributeArgument(NameEquals("Scope"), nameColon: null, expression: scopeExpr); var targetString = GetTargetString(targetSymbol); - var targetExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(targetString)); - var targetArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Target"), nameColon: null, expression: targetExpr); + var targetExpr = LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(targetString)); + var targetArgument = AttributeArgument(NameEquals("Target"), nameColon: null, expression: targetExpr); attributeArgumentList = attributeArgumentList.AddArguments(scopeArgument, targetArgument); } @@ -237,9 +239,9 @@ protected override SyntaxTrivia TogglePragmaDirective(SyntaxTrivia trivia) var pragmaWarning = (PragmaWarningDirectiveTriviaSyntax)trivia.GetStructure(); var currentKeyword = pragmaWarning.DisableOrRestoreKeyword; var toggledKeywordKind = currentKeyword.Kind() == SyntaxKind.DisableKeyword ? SyntaxKind.RestoreKeyword : SyntaxKind.DisableKeyword; - var toggledToken = SyntaxFactory.Token(currentKeyword.LeadingTrivia, toggledKeywordKind, currentKeyword.TrailingTrivia); + var toggledToken = Token(currentKeyword.LeadingTrivia, toggledKeywordKind, currentKeyword.TrailingTrivia); var newPragmaWarning = pragmaWarning.WithDisableOrRestoreKeyword(toggledToken); - return SyntaxFactory.Trivia(newPragmaWarning); + return Trivia(newPragmaWarning); } protected override SyntaxNode GetContainingStatement(SyntaxToken token) diff --git a/src/Features/CSharp/Portable/CodeRefactorings/SyncNamespace/CSharpChangeNamespaceService.cs b/src/Features/CSharp/Portable/CodeRefactorings/SyncNamespace/CSharpChangeNamespaceService.cs index 6ade75c9f0742..4289e4e9a9c27 100644 --- a/src/Features/CSharp/Portable/CodeRefactorings/SyncNamespace/CSharpChangeNamespaceService.cs +++ b/src/Features/CSharp/Portable/CodeRefactorings/SyncNamespace/CSharpChangeNamespaceService.cs @@ -23,6 +23,8 @@ namespace Microsoft.CodeAnalysis.CSharp.ChangeNamespace; +using static SyntaxFactory; + [ExportLanguageService(typeof(IChangeNamespaceService), LanguageNames.CSharp), Shared] internal sealed class CSharpChangeNamespaceService : AbstractChangeNamespaceService @@ -139,7 +141,7 @@ public override bool TryGetReplacementReferenceSyntax( if (!TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode)) { var qualifiedNamespaceName = CreateNamespaceAsQualifiedName(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1); - newNode = SyntaxFactory.QualifiedName(qualifiedNamespaceName, nameRef.WithoutTrivia()); + newNode = QualifiedName(qualifiedNamespaceName, nameRef.WithoutTrivia()); } // We might lose some trivia associated with children of `oldNode`. @@ -156,7 +158,7 @@ public override bool TryGetReplacementReferenceSyntax( if (!TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode)) { var memberAccessNamespaceName = CreateNamespaceAsMemberAccess(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1); - newNode = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, memberAccessNamespaceName, nameRef.WithoutTrivia()); + newNode = MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, memberAccessNamespaceName, nameRef.WithoutTrivia()); } // We might lose some trivia associated with children of `oldNode`. @@ -179,7 +181,7 @@ public override bool TryGetReplacementReferenceSyntax( // We will replace entire `QualifiedCrefSyntax` with a `TypeCrefSyntax`, // which is a alias qualified simple name, similar to the regular case above. oldNode = qualifiedCref; - newNode = SyntaxFactory.TypeCref((AliasQualifiedNameSyntax)newNode!); + newNode = TypeCref((AliasQualifiedNameSyntax)newNode!); } else { @@ -208,8 +210,8 @@ private static bool TryGetGlobalQualifiedName( { // If new namespace is "", then name will be declared in global namespace. // We will replace qualified reference with simple name qualified with alias (global if it's not alias qualified) - var aliasNode = aliasQualifier?.ToIdentifierName() ?? SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)); - newNode = SyntaxFactory.AliasQualifiedName(aliasNode, nameNode.WithoutTrivia()); + var aliasNode = aliasQualifier?.ToIdentifierName() ?? IdentifierName(Token(SyntaxKind.GlobalKeyword)); + newNode = AliasQualifiedName(aliasNode, nameNode.WithoutTrivia()); return true; } @@ -310,7 +312,7 @@ private static CompilationUnitSyntax MoveMembersFromGlobalToNamespace(Compilatio { Debug.Assert(!compilationUnit.Members.Any(m => m is BaseNamespaceDeclarationSyntax)); - var targetNamespaceDecl = SyntaxFactory.NamespaceDeclaration( + var targetNamespaceDecl = NamespaceDeclaration( name: CreateNamespaceAsQualifiedName(targetNamespaceParts, aliasQualifier: null, targetNamespaceParts.Length - 1) .WithAdditionalAnnotations(WarningAnnotation), externs: default, @@ -413,12 +415,12 @@ private static NameSyntax CreateNamespaceAsQualifiedName(ImmutableArray var part = namespaceParts[index].EscapeIdentifier(); Debug.Assert(part.Length > 0); - var namePiece = SyntaxFactory.IdentifierName(part); + var namePiece = IdentifierName(part); if (index == 0) - return aliasQualifier == null ? namePiece : SyntaxFactory.AliasQualifiedName(aliasQualifier, namePiece); + return aliasQualifier == null ? namePiece : AliasQualifiedName(aliasQualifier, namePiece); - return SyntaxFactory.QualifiedName(CreateNamespaceAsQualifiedName(namespaceParts, aliasQualifier, index - 1), namePiece); + return QualifiedName(CreateNamespaceAsQualifiedName(namespaceParts, aliasQualifier, index - 1), namePiece); } private static ExpressionSyntax CreateNamespaceAsMemberAccess(ImmutableArray namespaceParts, string? aliasQualifier, int index) @@ -426,16 +428,16 @@ private static ExpressionSyntax CreateNamespaceAsMemberAccess(ImmutableArray 0); - var namePiece = SyntaxFactory.IdentifierName(part); + var namePiece = IdentifierName(part); if (index == 0) { return aliasQualifier == null ? namePiece - : SyntaxFactory.AliasQualifiedName(aliasQualifier, namePiece); + : AliasQualifiedName(aliasQualifier, namePiece); } - return SyntaxFactory.MemberAccessExpression( + return MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, CreateNamespaceAsMemberAccess(namespaceParts, aliasQualifier, index - 1), namePiece); diff --git a/src/Features/CSharp/Portable/Completion/Providers/OutVariableArgumentProvider.cs b/src/Features/CSharp/Portable/Completion/Providers/OutVariableArgumentProvider.cs index 825dfcc78c207..aa718dac3202b 100644 --- a/src/Features/CSharp/Portable/Completion/Providers/OutVariableArgumentProvider.cs +++ b/src/Features/CSharp/Portable/Completion/Providers/OutVariableArgumentProvider.cs @@ -10,6 +10,8 @@ namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers; +using static SyntaxFactory; + [ExportArgumentProvider(nameof(OutVariableArgumentProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(ContextVariableArgumentProvider))] [Shared] @@ -44,12 +46,12 @@ public override Task ProvideArgumentAsync(ArgumentContext context) name = "@" + name; } - var syntax = SyntaxFactory.Argument( + var syntax = Argument( nameColon: null, - refKindKeyword: SyntaxFactory.Token(SyntaxKind.OutKeyword), - SyntaxFactory.DeclarationExpression( - type: SyntaxFactory.IdentifierName("var"), - designation: SyntaxFactory.SingleVariableDesignation(SyntaxFactory.Identifier( + refKindKeyword: Token(SyntaxKind.OutKeyword), + DeclarationExpression( + type: IdentifierName("var"), + designation: SingleVariableDesignation(Identifier( [], contextualKind: SyntaxKind.None, text: name, diff --git a/src/Features/CSharp/Portable/ConvertAnonymousType/CSharpConvertAnonymousTypeToTupleCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/ConvertAnonymousType/CSharpConvertAnonymousTypeToTupleCodeRefactoringProvider.cs index 89747fef64d27..a94d8b39e6e42 100644 --- a/src/Features/CSharp/Portable/ConvertAnonymousType/CSharpConvertAnonymousTypeToTupleCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/ConvertAnonymousType/CSharpConvertAnonymousTypeToTupleCodeRefactoringProvider.cs @@ -12,6 +12,8 @@ namespace Microsoft.CodeAnalysis.CSharp.ConvertAnonymousType; +using static SyntaxFactory; + [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertAnonymousTypeToTuple), Shared] internal class CSharpConvertAnonymousTypeToTupleCodeRefactoringProvider : AbstractConvertAnonymousTypeToTupleCodeRefactoringProvider< @@ -29,23 +31,23 @@ protected override int GetInitializerCount(AnonymousObjectCreationExpressionSynt => anonymousType.Initializers.Count; protected override TupleExpressionSyntax ConvertToTuple(AnonymousObjectCreationExpressionSyntax anonCreation) - => SyntaxFactory.TupleExpression( - SyntaxFactory.Token(SyntaxKind.OpenParenToken).WithTriviaFrom(anonCreation.OpenBraceToken), + => TupleExpression( + Token(SyntaxKind.OpenParenToken).WithTriviaFrom(anonCreation.OpenBraceToken), ConvertInitializers(anonCreation.Initializers), - SyntaxFactory.Token(SyntaxKind.CloseParenToken).WithTriviaFrom(anonCreation.CloseBraceToken)) + Token(SyntaxKind.CloseParenToken).WithTriviaFrom(anonCreation.CloseBraceToken)) .WithPrependedLeadingTrivia(anonCreation.GetLeadingTrivia()); private static SeparatedSyntaxList ConvertInitializers(SeparatedSyntaxList initializers) - => SyntaxFactory.SeparatedList(initializers.Select(ConvertInitializer), initializers.GetSeparators()); + => SeparatedList(initializers.Select(ConvertInitializer), initializers.GetSeparators()); private static ArgumentSyntax ConvertInitializer(AnonymousObjectMemberDeclaratorSyntax declarator) - => SyntaxFactory.Argument(ConvertName(declarator.NameEquals), default, declarator.Expression) + => Argument(ConvertName(declarator.NameEquals), default, declarator.Expression) .WithTriviaFrom(declarator); private static NameColonSyntax? ConvertName(NameEqualsSyntax? nameEquals) => nameEquals == null ? null - : SyntaxFactory.NameColon( + : NameColon( nameEquals.Name, - SyntaxFactory.Token(SyntaxKind.ColonToken).WithTriviaFrom(nameEquals.EqualsToken)); + Token(SyntaxKind.ColonToken).WithTriviaFrom(nameEquals.EqualsToken)); } diff --git a/src/Features/CSharp/Portable/ConvertForEachToFor/CSharpConvertForEachToForCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/ConvertForEachToFor/CSharpConvertForEachToForCodeRefactoringProvider.cs index 8b9bed742f338..cddfa8d70cd2b 100644 --- a/src/Features/CSharp/Portable/ConvertForEachToFor/CSharpConvertForEachToForCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/ConvertForEachToFor/CSharpConvertForEachToForCodeRefactoringProvider.cs @@ -18,6 +18,8 @@ namespace Microsoft.CodeAnalysis.CSharp.ConvertForEachToFor; +using static SyntaxFactory; + [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertForEachToFor), Shared] internal sealed class CSharpConvertForEachToForCodeRefactoringProvider : AbstractConvertForEachToForCodeRefactoringProvider @@ -84,19 +86,19 @@ protected override void ConvertToForStatement( var bodyStatement = GetForLoopBody(generator, foreachInfo, collectionVariable, indexVariable, donotCastElement); // create for statement from foreach statement - var forStatement = SyntaxFactory.ForStatement( - SyntaxFactory.VariableDeclaration( + var forStatement = ForStatement( + VariableDeclaration( model.Compilation.GetSpecialType(SpecialType.System_Int32).GenerateTypeSyntax(), - [SyntaxFactory.VariableDeclarator( + [VariableDeclarator( indexVariable.WithAdditionalAnnotations(RenameAnnotation.Create()), argumentList: null, - SyntaxFactory.EqualsValueClause((ExpressionSyntax)generator.LiteralExpression(0)))]), + EqualsValueClause((ExpressionSyntax)generator.LiteralExpression(0)))]), initializers: [], (ExpressionSyntax)generator.LessThanExpression( generator.IdentifierName(indexVariable), generator.MemberAccessExpression(collectionVariable, foreachInfo.CountName)), - [SyntaxFactory.PostfixUnaryExpression( - SyntaxKind.PostIncrementExpression, SyntaxFactory.IdentifierName(indexVariable))], + [PostfixUnaryExpression( + SyntaxKind.PostIncrementExpression, IdentifierName(indexVariable))], bodyStatement); if (!foreachInfo.RequireCollectionStatement) @@ -127,7 +129,7 @@ private StatementSyntax GetForLoopBody( foreachStatement.Identifier, donotCastElement ? null : foreachInfo.ForEachElementType, collectionVariableName, indexVariable); - var bodyBlock = foreachStatement.Statement is BlockSyntax block ? block : SyntaxFactory.Block(foreachStatement.Statement); + var bodyBlock = foreachStatement.Statement is BlockSyntax block ? block : Block(foreachStatement.Statement); if (bodyBlock.Statements.Count == 0) { // If the block was empty, still put the new variable inside of it. This handles the case where the user diff --git a/src/Features/CSharp/Portable/ConvertLinq/CSharpConvertLinqQueryToForEachProvider.cs b/src/Features/CSharp/Portable/ConvertLinq/CSharpConvertLinqQueryToForEachProvider.cs index a012eb4b00093..1dd58807c564e 100644 --- a/src/Features/CSharp/Portable/ConvertLinq/CSharpConvertLinqQueryToForEachProvider.cs +++ b/src/Features/CSharp/Portable/ConvertLinq/CSharpConvertLinqQueryToForEachProvider.cs @@ -24,10 +24,12 @@ namespace Microsoft.CodeAnalysis.CSharp.ConvertLinq; +using static SyntaxFactory; + [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertLinqQueryToForEach), Shared] internal sealed class CSharpConvertLinqQueryToForEachProvider : AbstractConvertLinqQueryToForEachProvider { - private static readonly TypeSyntax VarNameIdentifier = SyntaxFactory.IdentifierName("var"); + private static readonly TypeSyntax VarNameIdentifier = IdentifierName("var"); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] @@ -92,7 +94,7 @@ SyntaxKind.MultiLineCommentTrivia or if (!documentUpdateInfo.Source.IsParentKind(SyntaxKind.Block) && documentUpdateInfo.Destinations.Length > 1) { - documentUpdateInfo = new DocumentUpdateInfo(documentUpdateInfo.Source, SyntaxFactory.Block(documentUpdateInfo.Destinations)); + documentUpdateInfo = new DocumentUpdateInfo(documentUpdateInfo.Source, Block(documentUpdateInfo.Destinations)); } return true; @@ -113,7 +115,7 @@ private StatementSyntax ProcessClause( switch (node.Kind()) { case SyntaxKind.WhereClause: - return SyntaxFactory.Block(SyntaxFactory.IfStatement(((WhereClauseSyntax)node).Condition.WithAdditionalAnnotations(Simplifier.Annotation).WithoutTrivia(), statement)); + return Block(IfStatement(((WhereClauseSyntax)node).Condition.WithAdditionalAnnotations(Simplifier.Annotation).WithoutTrivia(), statement)); case SyntaxKind.FromClause: var fromClause = (FromClauseSyntax)node; @@ -130,14 +132,14 @@ private StatementSyntax ProcessClause( _cancellationToken); var variable = GetFreeSymbolNameAndMarkUsed(expressionName); extraStatementToAddAbove = CreateLocalDeclarationStatement(variable, fromClause.Expression, generateTypeFromExpression: false); - expression1 = SyntaxFactory.IdentifierName(variable); + expression1 = IdentifierName(variable); } else { expression1 = fromClause.Expression.WithoutTrivia(); } - return SyntaxFactory.ForEachStatement( + return ForEachStatement( fromClause.Type ?? VarNameIdentifier, fromClause.Identifier, expression1, @@ -175,7 +177,7 @@ private StatementSyntax ProcessClause( extraStatementToAddAbove = CreateLocalDeclarationStatement(variable, joinClause.InExpression, generateTypeFromExpression: false); // Replace YY() with yy declared above. - expression2 = SyntaxFactory.IdentifierName(variable); + expression2 = IdentifierName(variable); } // Output for the join @@ -186,21 +188,21 @@ private StatementSyntax ProcessClause( // if (object.Equals(x, y)) // { // ... - return SyntaxFactory.Block( - SyntaxFactory.ForEachStatement( + return Block( + ForEachStatement( joinClause.Type ?? VarNameIdentifier, joinClause.Identifier, expression2, - SyntaxFactory.Block( - SyntaxFactory.IfStatement( - SyntaxFactory.InvocationExpression( - SyntaxFactory.MemberAccessExpression( + Block( + IfStatement( + InvocationExpression( + MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, - SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)), - SyntaxFactory.IdentifierName(nameof(object.Equals))), - SyntaxFactory.ArgumentList([ - SyntaxFactory.Argument(joinClause.LeftExpression), - SyntaxFactory.Argument(joinClause.RightExpression.WithoutTrailingTrivia())])), + PredefinedType(Token(SyntaxKind.ObjectKeyword)), + IdentifierName(nameof(object.Equals))), + ArgumentList([ + Argument(joinClause.LeftExpression), + Argument(joinClause.RightExpression.WithoutTrailingTrivia())])), statement)))).WithAdditionalAnnotations(Simplifier.Annotation); } case SyntaxKind.SelectClause: @@ -312,9 +314,9 @@ private bool TryConvertIfInCountInvocation( invocationExpression, queryExpressionProcessingInfo, IsInt, - (variableIdentifier, expression) => SyntaxFactory.ExpressionStatement( - SyntaxFactory.PostfixUnaryExpression(SyntaxKind.PostIncrementExpression, variableIdentifier)), // Generating 'count++' - SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(0)), // count = 0 + (variableIdentifier, expression) => ExpressionStatement( + PostfixUnaryExpression(SyntaxKind.PostIncrementExpression, variableIdentifier)), // Generating 'count++' + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)), // count = 0 variableName: "count", out documentUpdateInfo); } @@ -344,15 +346,15 @@ private bool TryConvertIfInToListInvocation( invocationExpression, queryExpressionProcessingInfo, IsList, - (listIdentifier, expression) => SyntaxFactory.ExpressionStatement(SyntaxFactory.InvocationExpression( - SyntaxFactory.MemberAccessExpression( + (listIdentifier, expression) => ExpressionStatement(InvocationExpression( + MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, listIdentifier, - SyntaxFactory.IdentifierName(nameof(IList.Add))), - SyntaxFactory.ArgumentList([SyntaxFactory.Argument(expression)]))), - SyntaxFactory.ObjectCreationExpression( + IdentifierName(nameof(IList.Add))), + ArgumentList([Argument(expression)]))), + ObjectCreationExpression( methodSymbol.GenerateReturnTypeSyntax().WithAdditionalAnnotations(Simplifier.Annotation), - SyntaxFactory.ArgumentList(), + ArgumentList(), initializer: null), variableName: "list", out documentUpdateInfo); @@ -446,7 +448,7 @@ void Convert( // var list = new List(); or assignment // foreach(...) // IReadOnlyList a = list; - variableLocal = SyntaxFactory.IdentifierName(symbolName); + variableLocal = IdentifierName(symbolName); nodesBeforeLocal = new[] { CreateLocalDeclarationStatement(symbolName, initializer, generateTypeFromExpression: false) }; nodesAfterLocal = [parentStatement.ReplaceNode(invocationExpression, variableLocal.WithAdditionalAnnotations(Simplifier.Annotation))]; } @@ -465,7 +467,7 @@ SyntaxKind.VariableDeclaration or { var variableDeclarator = ((VariableDeclaratorSyntax)invocationParent.Parent); Convert( - SyntaxFactory.IdentifierName(variableDeclarator.Identifier), + IdentifierName(variableDeclarator.Identifier), ((VariableDeclarationSyntax)variableDeclarator.Parent).Type, checkForLocalOrParameter: false, out variable, @@ -495,9 +497,9 @@ SyntaxKind.VariableDeclaration or // after var list = new List(); // foreach(...) // return list; - variable = SyntaxFactory.IdentifierName(symbolName); + variable = IdentifierName(symbolName); nodesBefore = new[] { CreateLocalDeclarationStatement(symbolName, initializer, generateTypeFromExpression: false) }; - nodesAfter = new[] { SyntaxFactory.ReturnStatement(variable).WithAdditionalAnnotations(Simplifier.Annotation) }; + nodesAfter = new[] { ReturnStatement(variable).WithAdditionalAnnotations(Simplifier.Annotation) }; return true; // SyntaxKind.Argument: // SyntaxKind.ArrowExpressionClause is not supported @@ -518,13 +520,13 @@ private LocalDeclarationStatementSyntax CreateLocalDeclarationStatement( var typeSyntax = generateTypeFromExpression ? _semanticModel.GetTypeInfo(expression, _cancellationToken).ConvertedType.GenerateTypeSyntax() : VarNameIdentifier; - return SyntaxFactory.LocalDeclarationStatement( - SyntaxFactory.VariableDeclaration( + return LocalDeclarationStatement( + VariableDeclaration( typeSyntax, - [SyntaxFactory.VariableDeclarator( + [VariableDeclarator( identifier, argumentList: null, - SyntaxFactory.EqualsValueClause(expression))])).WithAdditionalAnnotations(Simplifier.Annotation); + EqualsValueClause(expression))])).WithAdditionalAnnotations(Simplifier.Annotation); } private bool TryReplaceWithLocalFunction(QueryExpressionProcessingInfo queryExpressionProcessingInfo, out DocumentUpdateInfo documentUpdateInfo) @@ -567,7 +569,7 @@ private bool TryReplaceWithLocalFunction(QueryExpressionProcessingInfo queryExpr } static StatementSyntax internalNodeMethod(ExpressionSyntax expression) - => SyntaxFactory.YieldStatement(SyntaxKind.YieldReturnStatement, expression); + => YieldStatement(SyntaxKind.YieldReturnStatement, expression); var statements = GenerateStatements(internalNodeMethod, queryExpressionProcessingInfo); var localFunctionNamePrefix = _semanticFacts.GenerateNameForExpression( @@ -576,23 +578,23 @@ static StatementSyntax internalNodeMethod(ExpressionSyntax expression) capitalize: false, _cancellationToken); var localFunctionToken = GetFreeSymbolNameAndMarkUsed(localFunctionNamePrefix); - var localFunctionDeclaration = SyntaxFactory.LocalFunctionStatement( + var localFunctionDeclaration = LocalFunctionStatement( modifiers: default, returnType: returnedType.GenerateTypeSyntax().WithAdditionalAnnotations(Simplifier.Annotation), identifier: localFunctionToken, typeParameterList: null, - parameterList: SyntaxFactory.ParameterList(), + parameterList: ParameterList(), constraintClauses: default, - body: SyntaxFactory.Block( - SyntaxFactory.Token( + body: Block( + Token( [], SyntaxKind.OpenBraceToken, - [SyntaxFactory.EndOfLine(Environment.NewLine)]), + [EndOfLine(Environment.NewLine)]), [.. statements], - SyntaxFactory.Token(SyntaxKind.CloseBraceToken)), + Token(SyntaxKind.CloseBraceToken)), expressionBody: null); - var localFunctionInvocation = SyntaxFactory.InvocationExpression(SyntaxFactory.IdentifierName(localFunctionToken)).WithAdditionalAnnotations(Simplifier.Annotation); + var localFunctionInvocation = InvocationExpression(IdentifierName(localFunctionToken)).WithAdditionalAnnotations(Simplifier.Annotation); var newParentExpressionStatement = parentStatement.ReplaceNode(_source.WalkUpParentheses(), localFunctionInvocation.WithAdditionalAnnotations(Simplifier.Annotation)); documentUpdateInfo = new DocumentUpdateInfo(parentStatement, [localFunctionDeclaration, newParentExpressionStatement]); return true; @@ -688,13 +690,13 @@ private DocumentUpdateInfo ConvertIfInToForeachWithExtraVariableDeclaration( // dosomething(x); // } var statements = GenerateStatements( - expression => AddToBlockTop(SyntaxFactory.LocalDeclarationStatement( - SyntaxFactory.VariableDeclaration( + expression => AddToBlockTop(LocalDeclarationStatement( + VariableDeclaration( forEachStatement.Type, - [SyntaxFactory.VariableDeclarator( + [VariableDeclarator( forEachStatement.Identifier, argumentList: null, - SyntaxFactory.EqualsValueClause(expression))])), + EqualsValueClause(expression))])), forEachStatement.Statement).WithAdditionalAnnotations(Formatter.Annotation), queryExpressionProcessingInfo); return new DocumentUpdateInfo(forEachStatement, statements); } @@ -759,10 +761,10 @@ private bool TryConvertIfInReturnStatement( // // yield break; var statements = GenerateStatements((ExpressionSyntax expression) - => SyntaxFactory.YieldStatement(SyntaxKind.YieldReturnStatement, expression), queryExpressionProcessingInfo); + => YieldStatement(SyntaxKind.YieldReturnStatement, expression), queryExpressionProcessingInfo); // add an yield break to avoid throws after the return. - var yieldBreakStatement = SyntaxFactory.YieldStatement(SyntaxKind.YieldBreakStatement); + var yieldBreakStatement = YieldStatement(SyntaxKind.YieldBreakStatement); documentUpdateInfo = new DocumentUpdateInfo(returnStatement, statements.Concat(new[] { yieldBreakStatement })); return true; } @@ -896,7 +898,7 @@ private static BlockSyntax AddToBlockTop(StatementSyntax newStatement, Statement } else { - return SyntaxFactory.Block(newStatement, statement); + return Block(newStatement, statement); } } @@ -914,7 +916,7 @@ private static bool IsLocalOrParameterSymbol(IOperation operation) } private static BlockSyntax WrapWithBlock(StatementSyntax statement) - => statement is BlockSyntax block ? block : SyntaxFactory.Block(statement); + => statement is BlockSyntax block ? block : Block(statement); // Checks if the node is within an immediate lambda or within an immediate anonymous method. // 'lambda => node' returns true diff --git a/src/Features/CSharp/Portable/ConvertLinq/ConvertForEachToLinqQuery/AbstractConverter.cs b/src/Features/CSharp/Portable/ConvertLinq/ConvertForEachToLinqQuery/AbstractConverter.cs index 2602bf63af3ef..3c72eb3443530 100644 --- a/src/Features/CSharp/Portable/ConvertLinq/ConvertForEachToLinqQuery/AbstractConverter.cs +++ b/src/Features/CSharp/Portable/ConvertLinq/ConvertForEachToLinqQuery/AbstractConverter.cs @@ -18,6 +18,8 @@ namespace Microsoft.CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery; +using static SyntaxFactory; + internal abstract class AbstractConverter(ForEachInfo forEachInfo) : IConverter { public ForEachInfo ForEachInfo { get; } = forEachInfo; @@ -54,11 +56,11 @@ private QueryExpressionSyntax CreateQueryExpression( ExpressionSyntax selectExpression, IEnumerable leadingTokensForSelect, IEnumerable trailingTokensForSelect) - => SyntaxFactory.QueryExpression( + => QueryExpression( CreateFromClause(ForEachInfo.ForEachStatement, ForEachInfo.LeadingTokens.GetTrivia(), []), - SyntaxFactory.QueryBody( + QueryBody( [.. ForEachInfo.ConvertingExtendedNodes.Select(node => CreateQueryClause(node))], - SyntaxFactory.SelectClause(selectExpression) + SelectClause(selectExpression) .WithCommentsFrom(leadingTokensForSelect, ForEachInfo.TrailingTokens.Concat(trailingTokensForSelect)), continuation: null)) // The current coverage of foreach statements to support does not need to use query continuations. .WithAdditionalAnnotations(Formatter.Annotation); @@ -69,8 +71,8 @@ private static QueryClauseSyntax CreateQueryClause(ExtendedSyntaxNode node) { case SyntaxKind.VariableDeclarator: var variable = (VariableDeclaratorSyntax)node.Node; - return SyntaxFactory.LetClause( - SyntaxFactory.Token(SyntaxKind.LetKeyword), + return LetClause( + Token(SyntaxKind.LetKeyword), variable.Identifier, variable.Initializer.EqualsToken, variable.Initializer.Value) @@ -81,8 +83,8 @@ private static QueryClauseSyntax CreateQueryClause(ExtendedSyntaxNode node) case SyntaxKind.IfStatement: var ifStatement = (IfStatementSyntax)node.Node; - return SyntaxFactory.WhereClause( - SyntaxFactory.Token(SyntaxKind.WhereKeyword) + return WhereClause( + Token(SyntaxKind.WhereKeyword) .WithCommentsFrom(ifStatement.IfKeyword.LeadingTrivia, ifStatement.IfKeyword.TrailingTrivia), ifStatement.Condition.WithCommentsFrom(ifStatement.OpenParenToken, ifStatement.CloseParenToken)) .WithCommentsFrom(node.ExtraLeadingComments, node.ExtraTrailingComments); @@ -95,8 +97,8 @@ private static FromClauseSyntax CreateFromClause( ForEachStatementSyntax forEachStatement, IEnumerable extraLeadingTrivia, IEnumerable extraTrailingTrivia) - => SyntaxFactory.FromClause( - fromKeyword: SyntaxFactory.Token(SyntaxKind.FromKeyword) + => FromClause( + fromKeyword: Token(SyntaxKind.FromKeyword) .WithCommentsFrom( forEachStatement.ForEachKeyword.LeadingTrivia, forEachStatement.ForEachKeyword.TrailingTrivia, @@ -162,8 +164,8 @@ private ExpressionSyntax CreateLinqInvocationOrSimpleExpression( // var hasForEachChild = false; var lambdaBody = CreateLinqInvocationForExtendedNode(selectExpression, ref currentExtendedNodeIndex, ref receiverForInvocation, ref hasForEachChild); - var lambda = SyntaxFactory.SimpleLambdaExpression( - SyntaxFactory.Parameter( + var lambda = SimpleLambdaExpression( + Parameter( forEachStatement.Identifier.WithPrependedLeadingTrivia( SyntaxNodeOrTokenExtensions.GetTrivia(forEachStatement.Type.GetFirstToken()) .FilterComments(addElasticMarker: false))), @@ -201,12 +203,12 @@ lambdaBody is IdentifierNameSyntax identifier && return receiverForInvocation.WithAppendedTrailingTrivia(droppedTrivia); } - return SyntaxFactory.InvocationExpression( - SyntaxFactory.MemberAccessExpression( + return InvocationExpression( + MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, receiverForInvocation.Parenthesize(), - SyntaxFactory.IdentifierName(invokedMethodName)), - SyntaxFactory.ArgumentList([SyntaxFactory.Argument(lambda)])); + IdentifierName(invokedMethodName)), + ArgumentList([Argument(lambda)])); } /// @@ -269,19 +271,19 @@ private ExpressionSyntax CreateLinqInvocationForExtendedNode( case SyntaxKind.IfStatement: var ifStatement = (IfStatementSyntax)node.Node; var parentForEachStatement = ifStatement.GetAncestor(); - var lambdaParameter = SyntaxFactory.Parameter(SyntaxFactory.Identifier(parentForEachStatement.Identifier.ValueText)); - var lambda = SyntaxFactory.SimpleLambdaExpression( - SyntaxFactory.Parameter( - SyntaxFactory.Identifier(parentForEachStatement.Identifier.ValueText)), + var lambdaParameter = Parameter(Identifier(parentForEachStatement.Identifier.ValueText)); + var lambda = SimpleLambdaExpression( + Parameter( + Identifier(parentForEachStatement.Identifier.ValueText)), ifStatement.Condition.WithCommentsFrom(ifStatement.OpenParenToken, ifStatement.CloseParenToken)) .WithCommentsFrom(ifStatement.IfKeyword.GetAllTrivia().Concat(node.ExtraLeadingComments), node.ExtraTrailingComments); - receiver = SyntaxFactory.InvocationExpression( - SyntaxFactory.MemberAccessExpression( + receiver = InvocationExpression( + MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, receiver.Parenthesize(), - SyntaxFactory.IdentifierName(nameof(Enumerable.Where))), - SyntaxFactory.ArgumentList([SyntaxFactory.Argument(lambda)])); + IdentifierName(nameof(Enumerable.Where))), + ArgumentList([Argument(lambda)])); ++extendedNodeIndex; return CreateLinqInvocationForExtendedNode(selectExpression, ref extendedNodeIndex, ref receiver, ref hasForEachChild); diff --git a/src/Features/CSharp/Portable/ConvertLinq/ConvertForEachToLinqQuery/DefaultConverter.cs b/src/Features/CSharp/Portable/ConvertLinq/ConvertForEachToLinqQuery/DefaultConverter.cs index 53c5142fa885b..0df51188be9a8 100644 --- a/src/Features/CSharp/Portable/ConvertLinq/ConvertForEachToLinqQuery/DefaultConverter.cs +++ b/src/Features/CSharp/Portable/ConvertLinq/ConvertForEachToLinqQuery/DefaultConverter.cs @@ -16,9 +16,11 @@ namespace Microsoft.CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery; +using static SyntaxFactory; + internal sealed class DefaultConverter(ForEachInfo forEachInfo) : AbstractConverter(forEachInfo) { - private static readonly TypeSyntax VarNameIdentifier = SyntaxFactory.IdentifierName("var"); + private static readonly TypeSyntax VarNameIdentifier = IdentifierName("var"); public override void Convert(SyntaxEditor editor, bool convertToQuery, CancellationToken cancellationToken) { @@ -48,11 +50,11 @@ private StatementSyntax CreateDefaultReplacementStatement( if (identifiersCount == 0) { // Generate foreach(var _ ... select new {}) - return SyntaxFactory.ForEachStatement( + return ForEachStatement( VarNameIdentifier, - SyntaxFactory.Identifier("_"), + Identifier("_"), CreateQueryExpressionOrLinqInvocation( - SyntaxFactory.AnonymousObjectCreationExpression(), + AnonymousObjectCreationExpression(), [], [], convertToQuery), @@ -61,11 +63,11 @@ private StatementSyntax CreateDefaultReplacementStatement( else if (identifiersCount == 1) { // Generate foreach(var singleIdentifier from ... select singleIdentifier) - return SyntaxFactory.ForEachStatement( + return ForEachStatement( VarNameIdentifier, identifiers.Single(), CreateQueryExpressionOrLinqInvocation( - SyntaxFactory.IdentifierName(identifiers.Single()), + IdentifierName(identifiers.Single()), [], [], convertToQuery), @@ -73,16 +75,16 @@ private StatementSyntax CreateDefaultReplacementStatement( } else { - var tupleForSelectExpression = SyntaxFactory.TupleExpression( + var tupleForSelectExpression = TupleExpression( [.. identifiers.Select( - identifier => SyntaxFactory.Argument(SyntaxFactory.IdentifierName(identifier)))]); - var declaration = SyntaxFactory.DeclarationExpression( + identifier => Argument(IdentifierName(identifier)))]); + var declaration = DeclarationExpression( VarNameIdentifier, - SyntaxFactory.ParenthesizedVariableDesignation( - [.. identifiers.Select(SyntaxFactory.SingleVariableDesignation)])); + ParenthesizedVariableDesignation( + [.. identifiers.Select(SingleVariableDesignation)])); // Generate foreach(var (a,b) ... select (a, b)) - return SyntaxFactory.ForEachVariableStatement( + return ForEachVariableStatement( declaration, CreateQueryExpressionOrLinqInvocation( tupleForSelectExpression, @@ -94,5 +96,5 @@ [.. identifiers.Select( } private static BlockSyntax WrapWithBlockIfNecessary(ImmutableArray statements) - => statements is [BlockSyntax block] ? block : SyntaxFactory.Block(statements); + => statements is [BlockSyntax block] ? block : Block(statements); } diff --git a/src/Features/CSharp/Portable/EncapsulateField/CSharpEncapsulateFieldService.cs b/src/Features/CSharp/Portable/EncapsulateField/CSharpEncapsulateFieldService.cs index c7be2c182fab3..f88a618821d07 100644 --- a/src/Features/CSharp/Portable/EncapsulateField/CSharpEncapsulateFieldService.cs +++ b/src/Features/CSharp/Portable/EncapsulateField/CSharpEncapsulateFieldService.cs @@ -25,6 +25,8 @@ namespace Microsoft.CodeAnalysis.CSharp.EncapsulateField; +using static SyntaxFactory; + [ExportLanguageService(typeof(AbstractEncapsulateFieldService), LanguageNames.CSharp), Shared] internal class CSharpEncapsulateFieldService : AbstractEncapsulateFieldService { @@ -49,12 +51,12 @@ protected override async Task RewriteFieldNameAndAccessibilityAsync( var tempAnnotation = new SyntaxAnnotation(); var escapedName = originalFieldName.EscapeIdentifier(); - var newIdentifier = SyntaxFactory.Identifier( - leading: [SyntaxFactory.ElasticMarker], + var newIdentifier = Identifier( + leading: [ElasticMarker], contextualKind: SyntaxKind.IdentifierName, text: escapedName, valueText: originalFieldName, - trailing: [SyntaxFactory.ElasticMarker]) + trailing: [ElasticMarker]) .WithTrailingTrivia(declarator.Identifier.TrailingTrivia) .WithLeadingTrivia(declarator.Identifier.LeadingTrivia); @@ -73,7 +75,7 @@ protected override async Task RewriteFieldNameAndAccessibilityAsync( if (makePrivate) { - var modifiers = SpecializedCollections.SingletonEnumerable(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)) + var modifiers = SpecializedCollections.SingletonEnumerable(Token(SyntaxKind.PrivateKeyword)) .Concat(fieldSyntax.Modifiers.Where(m => !modifierKinds.Contains(m.Kind()))); root = root.ReplaceNode(fieldSyntax, fieldSyntax diff --git a/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.cs b/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.cs index 0e54600c081c6..cb2b9570070bc 100644 --- a/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.cs +++ b/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.cs @@ -178,8 +178,8 @@ private static bool IsExpressionBodiedAccessor(SyntaxNode node) private SimpleNameSyntax CreateMethodNameForInvocation() { return AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0 - ? SyntaxFactory.IdentifierName(_methodName) - : SyntaxFactory.GenericName(_methodName, SyntaxFactory.TypeArgumentList(CreateMethodCallTypeVariables())); + ? IdentifierName(_methodName) + : GenericName(_methodName, TypeArgumentList(CreateMethodCallTypeVariables())); } private SeparatedSyntaxList CreateMethodCallTypeVariables() @@ -278,8 +278,8 @@ private ImmutableArray WrapInCheckStatementIfNeeded(ImmutableAr return statements; return statements is [BlockSyntax block] - ? [SyntaxFactory.CheckedStatement(kind, block)] - : [SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))]; + ? [CheckedStatement(kind, block)] + : [CheckedStatement(kind, Block(statements))]; } private static ImmutableArray CleanupCode(ImmutableArray statements) @@ -394,9 +394,9 @@ private ImmutableArray MoveDeclarationOutFromMethodDefinition( // return survived var decls if (list.Count > 0) { - result.Add(SyntaxFactory.LocalDeclarationStatement( + result.Add(LocalDeclarationStatement( declarationStatement.Modifiers, - SyntaxFactory.VariableDeclaration( + VariableDeclaration( declarationStatement.Declaration.Type, [.. list]), declarationStatement.SemicolonToken.WithPrependedLeadingTrivia(triviaList))); @@ -447,7 +447,7 @@ private static StatementSyntax FixDeclarationExpressionsAndDeclarationPatterns(S newLeadingTrivia = newLeadingTrivia.AddRange(declaration.Type.GetTrailingTrivia()); newLeadingTrivia = newLeadingTrivia.AddRange(designation.GetLeadingTrivia()); - replacements.Add(declaration, SyntaxFactory.IdentifierName(designation.Identifier) + replacements.Add(declaration, IdentifierName(designation.Identifier) .WithLeadingTrivia(newLeadingTrivia)); } @@ -520,9 +520,9 @@ private ImmutableArray SplitOrMoveDeclarationIntoMethodDefiniti private static ExpressionSyntax CreateAssignmentExpression(SyntaxToken identifier, ExpressionSyntax rvalue) { - return SyntaxFactory.AssignmentExpression( + return AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, - SyntaxFactory.IdentifierName(identifier), + IdentifierName(identifier), rvalue); } @@ -555,13 +555,13 @@ protected override bool LastStatementOrHasReturnStatementInReturnableConstruct() } protected override SyntaxToken CreateIdentifier(string name) - => SyntaxFactory.Identifier(name); + => Identifier(name); protected override StatementSyntax CreateReturnStatement(string identifierName = null) { return string.IsNullOrEmpty(identifierName) - ? SyntaxFactory.ReturnStatement() - : SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName(identifierName)); + ? ReturnStatement() + : ReturnStatement(IdentifierName(identifierName)); } protected override ExpressionSyntax CreateCallSignature() @@ -611,7 +611,7 @@ protected override ExpressionSyntax CreateCallSignature() } protected override StatementSyntax CreateAssignmentExpressionStatement(SyntaxToken identifier, ExpressionSyntax rvalue) - => SyntaxFactory.ExpressionStatement(CreateAssignmentExpression(identifier, rvalue)); + => ExpressionStatement(CreateAssignmentExpression(identifier, rvalue)); protected override StatementSyntax CreateDeclarationStatement( VariableInfo variable, @@ -626,14 +626,14 @@ protected override StatementSyntax CreateDeclarationStatement( // Hierarchy being checked for to see if a using keyword is needed is // Token -> VariableDeclarator -> VariableDeclaration -> LocalDeclaration var usingKeyword = originalIdentifierToken.Parent?.Parent?.Parent is LocalDeclarationStatementSyntax { UsingKeyword.FullSpan.IsEmpty: false } - ? SyntaxFactory.Token(SyntaxKind.UsingKeyword) + ? Token(SyntaxKind.UsingKeyword) : default; - var equalsValueClause = initialValue == null ? null : SyntaxFactory.EqualsValueClause(value: initialValue); + var equalsValueClause = initialValue == null ? null : EqualsValueClause(value: initialValue); - return SyntaxFactory.LocalDeclarationStatement( - SyntaxFactory.VariableDeclaration(typeNode) - .AddVariables(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(variable.Name)) + return LocalDeclarationStatement( + VariableDeclaration(typeNode) + .AddVariables(VariableDeclarator(Identifier(variable.Name)) .WithInitializer(equalsValueClause))) .WithUsingKeyword(usingKeyword); } @@ -673,14 +673,14 @@ private static TDeclarationNode TweakNewLinesInMethod(TDeclara return method.ReplaceToken( body.OpenBraceToken, body.OpenBraceToken.WithAppendedTrailingTrivia( - SyntaxFactory.ElasticCarriageReturnLineFeed)); + ElasticCarriageReturnLineFeed)); } else if (expressionBody != null) { return method.ReplaceToken( expressionBody.ArrowToken, expressionBody.ArrowToken.WithPrependedLeadingTrivia( - SyntaxFactory.ElasticCarriageReturnLineFeed)); + ElasticCarriageReturnLineFeed)); } else { @@ -695,10 +695,10 @@ protected StatementSyntax GetStatementContainingInvocationToExtractedMethodWorke if (AnalyzerResult.HasReturnType) { Contract.ThrowIfTrue(AnalyzerResult.HasVariableToUseAsReturnValue); - return SyntaxFactory.ReturnStatement(callSignature); + return ReturnStatement(callSignature); } - return SyntaxFactory.ExpressionStatement(callSignature); + return ExpressionStatement(callSignature); } protected override async Task UpdateMethodAfterGenerationAsync( @@ -794,7 +794,7 @@ protected SyntaxToken GenerateMethodNameForStatementGenerators() scope = this.SelectionResult.GetFirstTokenInSelection().Parent; } - return SyntaxFactory.Identifier(nameGenerator.CreateUniqueMethodName(scope, GenerateMethodNameFromUserPreference())); + return Identifier(nameGenerator.CreateUniqueMethodName(scope, GenerateMethodNameFromUserPreference())); } protected string GenerateMethodNameFromUserPreference() diff --git a/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.PostProcessor.cs b/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.PostProcessor.cs index 51c77bc339f61..b9573ad911765 100644 --- a/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.PostProcessor.cs +++ b/src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.PostProcessor.cs @@ -14,6 +14,8 @@ namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod; +using static SyntaxFactory; + internal partial class CSharpMethodExtractor { private class PostProcessor @@ -141,8 +143,8 @@ private static IEnumerable GetMergedDeclaration // and create one decl statement // use type name from the first decl statement yield return - SyntaxFactory.LocalDeclarationStatement( - SyntaxFactory.VariableDeclaration(keyValuePair.Value.First().Declaration.Type, [.. variables])); + LocalDeclarationStatement( + VariableDeclaration(keyValuePair.Value.First().Declaration.Type, [.. variables])); } map.Clear(); @@ -256,7 +258,7 @@ declaration.Declaration.Variables[0].Initializer.Value is StackAllocArrayCreatio return statements; } - return [SyntaxFactory.ReturnStatement(declaration.Declaration.Variables[0].Initializer.Value)]; + return [ReturnStatement(declaration.Declaration.Variables[0].Initializer.Value)]; } public static ImmutableArray RemoveDeclarationAssignmentPattern(ImmutableArray statements) @@ -291,7 +293,7 @@ public static ImmutableArray RemoveDeclarationAssignmentPattern return statements; } - var variable = declaration.Declaration.Variables[0].WithInitializer(SyntaxFactory.EqualsValueClause(assignmentExpression.Right)); + var variable = declaration.Declaration.Variables[0].WithInitializer(EqualsValueClause(assignmentExpression.Right)); return [ declaration.WithDeclaration( diff --git a/src/Features/CSharp/Portable/GenerateMember/GenerateVariable/CSharpGenerateVariableService.cs b/src/Features/CSharp/Portable/GenerateMember/GenerateVariable/CSharpGenerateVariableService.cs index dff654471beb5..d5edd33fdae68 100644 --- a/src/Features/CSharp/Portable/GenerateMember/GenerateVariable/CSharpGenerateVariableService.cs +++ b/src/Features/CSharp/Portable/GenerateMember/GenerateVariable/CSharpGenerateVariableService.cs @@ -18,6 +18,8 @@ namespace Microsoft.CodeAnalysis.CSharp.GenerateMember.GenerateVariable; +using static SyntaxFactory; + [ExportLanguageService(typeof(IGenerateVariableService), LanguageNames.CSharp), Shared] internal partial class CSharpGenerateVariableService : AbstractGenerateVariableService @@ -151,7 +153,7 @@ private static bool IsProbablyGeneric(SimpleNameSyntax identifierName, Cancellat var localText = localRoot.ToString(); var startIndex = identifierName.Span.Start - localRoot.Span.Start; - var parsedType = SyntaxFactory.ParseTypeName(localText, startIndex, consumeFullText: false); + var parsedType = ParseTypeName(localText, startIndex, consumeFullText: false); return parsedType.IsKind(SyntaxKind.GenericName) && !parsedType.ContainsDiagnostics; } @@ -202,10 +204,10 @@ protected override bool TryConvertToLocalDeclaration(ITypeSymbol type, SyntaxTok var assignExpression = (AssignmentExpressionSyntax)node.Parent; var expressionStatement = (StatementSyntax)assignExpression.Parent; - var declarationStatement = SyntaxFactory.LocalDeclarationStatement( - SyntaxFactory.VariableDeclaration( + var declarationStatement = LocalDeclarationStatement( + VariableDeclaration( type.GenerateTypeSyntax(), - [SyntaxFactory.VariableDeclarator(token, null, SyntaxFactory.EqualsValueClause( + [VariableDeclarator(token, null, EqualsValueClause( assignExpression.OperatorToken, assignExpression.Right))])); declarationStatement = declarationStatement.WithAdditionalAnnotations(Formatter.Annotation); diff --git a/src/Features/CSharp/Portable/IntroduceUsingStatement/CSharpIntroduceUsingStatementCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/IntroduceUsingStatement/CSharpIntroduceUsingStatementCodeRefactoringProvider.cs index 251d67e7eee03..0309287ff4190 100644 --- a/src/Features/CSharp/Portable/IntroduceUsingStatement/CSharpIntroduceUsingStatementCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/IntroduceUsingStatement/CSharpIntroduceUsingStatementCodeRefactoringProvider.cs @@ -13,6 +13,8 @@ namespace Microsoft.CodeAnalysis.CSharp.IntroduceUsingStatement; +using static SyntaxFactory; + [ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.IntroduceVariable)] [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.IntroduceUsingStatement), Shared] internal sealed class CSharpIntroduceUsingStatementCodeRefactoringProvider @@ -52,13 +54,13 @@ protected override SyntaxNode WithStatements(SyntaxNode parentOfStatementsToSurr } protected override StatementSyntax CreateUsingStatement(LocalDeclarationStatementSyntax declarationStatement, SyntaxList statementsToSurround) - => SyntaxFactory.UsingStatement( - SyntaxFactory.Token(SyntaxKind.UsingKeyword).WithLeadingTrivia(declarationStatement.GetLeadingTrivia()), - SyntaxFactory.Token(SyntaxKind.OpenParenToken), + => UsingStatement( + Token(SyntaxKind.UsingKeyword).WithLeadingTrivia(declarationStatement.GetLeadingTrivia()), + Token(SyntaxKind.OpenParenToken), declaration: declarationStatement.Declaration.WithoutTrivia(), expression: null, // Declaration already has equals token and expression - SyntaxFactory.Token(SyntaxKind.CloseParenToken).WithTrailingTrivia(declarationStatement.GetTrailingTrivia()), - statement: SyntaxFactory.Block(statementsToSurround)); + Token(SyntaxKind.CloseParenToken).WithTrailingTrivia(declarationStatement.GetTrailingTrivia()), + statement: Block(statementsToSurround)); protected override bool TryCreateUsingLocalDeclaration( ParseOptions options, @@ -76,7 +78,7 @@ protected override bool TryCreateUsingLocalDeclaration( usingDeclarationStatement = declarationStatement .WithoutLeadingTrivia() - .WithUsingKeyword(SyntaxFactory.Token(declarationStatement.GetLeadingTrivia(), SyntaxKind.UsingKeyword, [SyntaxFactory.Space])); + .WithUsingKeyword(Token(declarationStatement.GetLeadingTrivia(), SyntaxKind.UsingKeyword, [Space])); return true; } } diff --git a/src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceField.cs b/src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceField.cs index 16794661e4dda..9010bc15b2e9f 100644 --- a/src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceField.cs +++ b/src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceField.cs @@ -16,6 +16,8 @@ namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable; +using static SyntaxFactory; + internal partial class CSharpIntroduceVariableService { protected override Task IntroduceFieldAsync( @@ -34,20 +36,20 @@ protected override Task IntroduceFieldAsync( var typeDisplayString = oldType.ToMinimalDisplayString(document.SemanticModel, expression.SpanStart); var newQualifiedName = oldTypeDeclaration != null - ? SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ParseName(typeDisplayString), SyntaxFactory.IdentifierName(newNameToken)) - : (ExpressionSyntax)SyntaxFactory.IdentifierName(newNameToken); + ? MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, ParseName(typeDisplayString), IdentifierName(newNameToken)) + : (ExpressionSyntax)IdentifierName(newNameToken); newQualifiedName = newQualifiedName.WithAdditionalAnnotations(Simplifier.Annotation); - var newFieldDeclaration = SyntaxFactory.FieldDeclaration( + var newFieldDeclaration = FieldDeclaration( default, MakeFieldModifiers(isConstant, inScript: oldType.IsScriptClass), - SyntaxFactory.VariableDeclaration( + VariableDeclaration( GetTypeSymbol(document, expression, cancellationToken).GenerateTypeSyntax(), - [SyntaxFactory.VariableDeclarator( + [VariableDeclarator( newNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()), null, - SyntaxFactory.EqualsValueClause(expression.WithoutTrivia()))])).WithAdditionalAnnotations(Formatter.Annotation); + EqualsValueClause(expression.WithoutTrivia()))])).WithAdditionalAnnotations(Formatter.Annotation); if (oldTypeDeclaration != null) { @@ -161,7 +163,7 @@ protected static int DetermineFirstChange(SyntaxList ol { for (var i = 0; i < oldMembers.Count; i++) { - if (!SyntaxFactory.AreEquivalent(oldMembers[i], newMembers[i], topLevel: false)) + if (!AreEquivalent(oldMembers[i], newMembers[i], topLevel: false)) { return i; } @@ -183,15 +185,15 @@ private static SyntaxTokenList MakeFieldModifiers(bool isConstant, bool inScript { if (isConstant) { - return [SyntaxFactory.Token(SyntaxKind.PrivateKeyword), SyntaxFactory.Token(SyntaxKind.ConstKeyword)]; + return [Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.ConstKeyword)]; } else if (inScript) { - return [SyntaxFactory.Token(SyntaxKind.PrivateKeyword), SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)]; + return [Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.ReadOnlyKeyword)]; } else { - return [SyntaxFactory.Token(SyntaxKind.PrivateKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword), SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)]; + return [Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.StaticKeyword), Token(SyntaxKind.ReadOnlyKeyword)]; } } } diff --git a/src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceLocal.cs b/src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceLocal.cs index ba1b5efdbcf11..960378906f6c7 100644 --- a/src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceLocal.cs +++ b/src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceLocal.cs @@ -20,6 +20,8 @@ namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable; +using static SyntaxFactory; + internal partial class CSharpIntroduceVariableService { protected override async Task IntroduceLocalAsync( @@ -34,20 +36,20 @@ protected override async Task IntroduceLocalAsync( var newLocalNameToken = GenerateUniqueLocalName( document, expression, isConstant, containerToGenerateInto, cancellationToken); - var newLocalName = SyntaxFactory.IdentifierName(newLocalNameToken); + var newLocalName = IdentifierName(newLocalNameToken); var modifiers = isConstant - ? SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ConstKeyword)) + ? TokenList(Token(SyntaxKind.ConstKeyword)) : default; - var declarationStatement = SyntaxFactory.LocalDeclarationStatement( + var declarationStatement = LocalDeclarationStatement( modifiers, - SyntaxFactory.VariableDeclaration( + VariableDeclaration( GetTypeSyntax(document, expression, cancellationToken), - [SyntaxFactory.VariableDeclarator( + [VariableDeclarator( newLocalNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()), null, - SyntaxFactory.EqualsValueClause(expression.WithoutTrivia()))])); + EqualsValueClause(expression.WithoutTrivia()))])); // If we're inserting into a multi-line parent, then add a newline after the local-var // we're adding. That way we don't end up having it and the starting statement be on @@ -55,7 +57,7 @@ protected override async Task IntroduceLocalAsync( var text = await document.Document.GetValueTextAsync(cancellationToken).ConfigureAwait(false); if (!text.AreOnSameLine(containerToGenerateInto.GetFirstToken(), containerToGenerateInto.GetLastToken())) { - declarationStatement = declarationStatement.WithAppendedTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed); + declarationStatement = declarationStatement.WithAppendedTrailingTrivia(ElasticCarriageReturnLineFeed); } switch (containerToGenerateInto) @@ -106,7 +108,7 @@ private Document IntroduceLocalDeclarationIntoLambda( declarationStatement, isEntireLambdaBodySelected, rewrittenBody, shouldIncludeReturnStatement); // Add an elastic newline so that the formatter will place this new lambda body across multiple lines. - newBody = newBody.WithOpenBraceToken(newBody.OpenBraceToken.WithAppendedTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed)) + newBody = newBody.WithOpenBraceToken(newBody.OpenBraceToken.WithAppendedTrailingTrivia(ElasticCarriageReturnLineFeed)) .WithAdditionalAnnotations(Formatter.Annotation); var newLambda = oldLambda.WithBody(newBody); @@ -171,7 +173,7 @@ private static BlockSyntax GetNewBlockBodyForLambda( // var v = x + 1; // return v; // }; - return SyntaxFactory.Block(declarationStatement, SyntaxFactory.ReturnStatement(rewrittenBody)); + return Block(declarationStatement, ReturnStatement(rewrittenBody)); } // For lambdas with void return types, we don't need to include the rewritten body if the entire lambda body @@ -188,7 +190,7 @@ private static BlockSyntax GetNewBlockBodyForLambda( // { // string v = x.ToString(); // }; - return SyntaxFactory.Block(declarationStatement); + return Block(declarationStatement); } // Case 2b: The lambda has a void return type, and the user didn't select the entire lambda body. @@ -201,9 +203,9 @@ private static BlockSyntax GetNewBlockBodyForLambda( // string destFileName = Path.Combine("dir", "file"); // File.Copy("src", destFileName); // }); - return SyntaxFactory.Block( + return Block( declarationStatement, - SyntaxFactory.ExpressionStatement(rewrittenBody, SyntaxFactory.Token(SyntaxKind.SemicolonToken))); + ExpressionStatement(rewrittenBody, Token(SyntaxKind.SemicolonToken))); } private static TypeSyntax GetTypeSyntax(SemanticDocument document, ExpressionSyntax expression, CancellationToken cancellationToken) @@ -230,15 +232,15 @@ private Document RewriteExpressionBodiedMemberAndIntroduceLocalDeclaration( var newExpression = Rewrite(document, expression, newLocalName, document, oldBody.Expression, allOccurrences, cancellationToken); var convertedStatement = createReturnStatement - ? SyntaxFactory.ReturnStatement(newExpression) - : (StatementSyntax)SyntaxFactory.ExpressionStatement(newExpression); + ? ReturnStatement(newExpression) + : (StatementSyntax)ExpressionStatement(newExpression); - var newBody = SyntaxFactory.Block(declarationStatement, convertedStatement) + var newBody = Block(declarationStatement, convertedStatement) .WithLeadingTrivia(leadingTrivia) .WithTrailingTrivia(oldBody.GetTrailingTrivia()); // Add an elastic newline so that the formatter will place this new block across multiple lines. - newBody = newBody.WithOpenBraceToken(newBody.OpenBraceToken.WithAppendedTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed)) + newBody = newBody.WithOpenBraceToken(newBody.OpenBraceToken.WithAppendedTrailingTrivia(ElasticCarriageReturnLineFeed)) .WithAdditionalAnnotations(Formatter.Annotation); var newRoot = document.Root.ReplaceNode(oldParentingNode, WithBlockBody(oldParentingNode, newBody)); @@ -250,30 +252,30 @@ private static SyntaxNode WithBlockBody(SyntaxNode node, BlockSyntax body) switch (node) { case BasePropertyDeclarationSyntax baseProperty: - var accessorList = SyntaxFactory.AccessorList( - [SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, body)]); + var accessorList = AccessorList( + [AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, body)]); return baseProperty .TryWithExpressionBody(null) .WithAccessorList(accessorList) - .TryWithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)) + .TryWithSemicolonToken(Token(SyntaxKind.None)) .WithTriviaFrom(baseProperty); case AccessorDeclarationSyntax accessor: return accessor .WithExpressionBody(null) .WithBody(body) - .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)) + .WithSemicolonToken(Token(SyntaxKind.None)) .WithTriviaFrom(accessor); case BaseMethodDeclarationSyntax baseMethod: return baseMethod .WithExpressionBody(null) .WithBody(body) - .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)) + .WithSemicolonToken(Token(SyntaxKind.None)) .WithTriviaFrom(baseMethod); case LocalFunctionStatementSyntax localFunction: return localFunction .WithExpressionBody(null) .WithBody(body) - .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)) + .WithSemicolonToken(Token(SyntaxKind.None)) .WithTriviaFrom(localFunction); default: throw ExceptionUtilities.UnexpectedValue(node); @@ -326,7 +328,7 @@ private async Task IntroduceLocalDeclarationIntoBlockAsync( { root = root.TrackNodes(allAffectedStatements.Concat(new SyntaxNode[] { expression, statement })); root = root.ReplaceNode(root.GetCurrentNode(statement), - SyntaxFactory.Block(root.GetCurrentNode(statement)).WithAdditionalAnnotations(Formatter.Annotation)); + Block(root.GetCurrentNode(statement)).WithAdditionalAnnotations(Formatter.Annotation)); expression = root.GetCurrentNode(expression); allAffectedStatements = allAffectedStatements.Select(root.GetCurrentNode).ToSet(); diff --git a/src/Features/CSharp/Portable/InvertIf/CSharpInvertIfCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/InvertIf/CSharpInvertIfCodeRefactoringProvider.cs index 125273e608a2a..3daf3339608c8 100644 --- a/src/Features/CSharp/Portable/InvertIf/CSharpInvertIfCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/InvertIf/CSharpInvertIfCodeRefactoringProvider.cs @@ -18,6 +18,8 @@ namespace Microsoft.CodeAnalysis.CSharp.InvertIf; +using static SyntaxFactory; + [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.InvertIf), Shared] internal sealed class CSharpInvertIfCodeRefactoringProvider : AbstractInvertIfCodeRefactoringProvider< SyntaxKind, StatementSyntax, IfStatementSyntax, StatementSyntax> @@ -59,7 +61,7 @@ protected override StatementSyntax GetIfBody(IfStatementSyntax ifNode) => ifNode.Statement; protected override StatementSyntax GetEmptyEmbeddedStatement() - => SyntaxFactory.Block(); + => Block(); protected override StatementSyntax GetElseBody(IfStatementSyntax ifNode) => ifNode.Else?.Statement ?? throw new InvalidOperationException(); @@ -108,10 +110,10 @@ CommonForEachStatementSyntax or DoStatementSyntax or WhileStatementSyntax or For protected override StatementSyntax GetJumpStatement(SyntaxKind kind) => kind switch { - SyntaxKind.ContinueStatement => SyntaxFactory.ContinueStatement(), - SyntaxKind.BreakStatement => SyntaxFactory.BreakStatement(), - SyntaxKind.ReturnStatement => SyntaxFactory.ReturnStatement(), - SyntaxKind.YieldBreakStatement => SyntaxFactory.YieldStatement(SyntaxKind.YieldBreakStatement), + SyntaxKind.ContinueStatement => ContinueStatement(), + SyntaxKind.BreakStatement => BreakStatement(), + SyntaxKind.ReturnStatement => ReturnStatement(), + SyntaxKind.YieldBreakStatement => YieldStatement(SyntaxKind.YieldBreakStatement), _ => throw ExceptionUtilities.UnexpectedValue(kind), }; @@ -127,7 +129,7 @@ protected override StatementSyntax AsEmbeddedStatement(IEnumerable AddAssemblyInfoRegionAsync(Document docu var assemblyInfo = MetadataAsSourceHelpers.GetAssemblyInfo(symbol.ContainingAssembly); var assemblyPath = MetadataAsSourceHelpers.GetAssemblyDisplay(symbolCompilation, symbol.ContainingAssembly); - var regionTrivia = SyntaxFactory.RegionDirectiveTrivia(true) - .WithTrailingTrivia(new[] { SyntaxFactory.Space, SyntaxFactory.PreprocessingMessage(assemblyInfo) }); + var regionTrivia = RegionDirectiveTrivia(true) + .WithTrailingTrivia(new[] { Space, PreprocessingMessage(assemblyInfo) }); var oldRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = oldRoot.WithPrependedLeadingTrivia( - SyntaxFactory.Trivia(regionTrivia), - SyntaxFactory.CarriageReturnLineFeed, - SyntaxFactory.Comment("// " + assemblyPath), - SyntaxFactory.CarriageReturnLineFeed, - SyntaxFactory.Trivia(SyntaxFactory.EndRegionDirectiveTrivia(true)), - SyntaxFactory.CarriageReturnLineFeed, - SyntaxFactory.CarriageReturnLineFeed); + Trivia(regionTrivia), + CarriageReturnLineFeed, + Comment("// " + assemblyPath), + CarriageReturnLineFeed, + Trivia(EndRegionDirectiveTrivia(true)), + CarriageReturnLineFeed, + CarriageReturnLineFeed); return document.WithSyntaxRoot(newRoot); } @@ -140,9 +142,9 @@ private static SyntaxTrivia[] CreateNullableTrivia(bool enable) var keyword = enable ? SyntaxKind.EnableKeyword : SyntaxKind.DisableKeyword; return [ - SyntaxFactory.Trivia(SyntaxFactory.NullableDirectiveTrivia(SyntaxFactory.Token(keyword), isActive: enable)), - SyntaxFactory.ElasticCarriageReturnLineFeed, - SyntaxFactory.ElasticCarriageReturnLineFeed, + Trivia(NullableDirectiveTrivia(Token(keyword), isActive: enable)), + ElasticCarriageReturnLineFeed, + ElasticCarriageReturnLineFeed, ]; } diff --git a/src/Features/CSharp/Portable/ReplaceMethodWithProperty/CSharpReplaceMethodWithPropertyService.cs b/src/Features/CSharp/Portable/ReplaceMethodWithProperty/CSharpReplaceMethodWithPropertyService.cs index 72a1f9d82fd06..c95e2fe7268e4 100644 --- a/src/Features/CSharp/Portable/ReplaceMethodWithProperty/CSharpReplaceMethodWithPropertyService.cs +++ b/src/Features/CSharp/Portable/ReplaceMethodWithProperty/CSharpReplaceMethodWithPropertyService.cs @@ -21,6 +21,8 @@ namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.ReplaceMethodWithProperty; +using static SyntaxFactory; + [ExportLanguageService(typeof(IReplaceMethodWithPropertyService), LanguageNames.CSharp), Shared] internal class CSharpReplaceMethodWithPropertyService : AbstractReplaceMethodWithPropertyService, IReplaceMethodWithPropertyService { @@ -96,10 +98,10 @@ public static SyntaxNode ConvertMethodsToProperty( block: out var block)) { var accessor = - SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) + AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .WithBody(block); - var accessorList = SyntaxFactory.AccessorList([accessor]); + var accessorList = AccessorList([accessor]); return propertyDeclaration.WithAccessorList(accessorList) .WithExpressionBody(null) .WithSemicolonToken(default); @@ -126,7 +128,7 @@ public static PropertyDeclarationSyntax ConvertMethodsToPropertyWorker( nameToken = nameToken.WithAdditionalAnnotations(WarningAnnotation.Create(warning)); } - var property = SyntaxFactory.PropertyDeclaration( + var property = PropertyDeclaration( getMethodDeclaration.AttributeLists, getMethodDeclaration.Modifiers, getMethodDeclaration.ReturnType, getMethodDeclaration.ExplicitInterfaceSpecifier, nameToken, accessorList: null); @@ -135,13 +137,13 @@ public static PropertyDeclarationSyntax ConvertMethodsToPropertyWorker( if (setMethodDeclaration?.Modifiers.Any(SyntaxKind.UnsafeKeyword) == true && !property.Modifiers.Any(SyntaxKind.UnsafeKeyword)) { - property = property.AddModifiers(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); + property = property.AddModifiers(Token(SyntaxKind.UnsafeKeyword)); } property = SetLeadingTrivia( CSharpSyntaxFacts.Instance, getAndSetMethods, property); - var accessorList = SyntaxFactory.AccessorList([getAccessor]); + var accessorList = AccessorList([getAccessor]); if (setAccessor != null) { accessorList = accessorList.AddAccessors(setAccessor); @@ -155,7 +157,7 @@ public static PropertyDeclarationSyntax ConvertMethodsToPropertyWorker( private static SyntaxToken GetPropertyName(SyntaxToken identifier, string propertyName, bool nameChanged) { return nameChanged - ? SyntaxFactory.Identifier(propertyName) + ? Identifier(propertyName) : identifier; } @@ -206,7 +208,7 @@ private static AccessorDeclarationSyntax CreateGetAccessorWorker(GetAndSetMethod { var getMethodDeclaration = getAndSetMethods.GetMethodDeclaration as MethodDeclarationSyntax; - var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration); + var accessor = AccessorDeclaration(SyntaxKind.GetAccessorDeclaration); if (getMethodDeclaration.ExpressionBody != null) { @@ -245,7 +247,7 @@ private static AccessorDeclarationSyntax CreateSetAccessorWorker( } var getMethod = getAndSetMethods.GetMethod; - var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration); + var accessor = AccessorDeclaration(SyntaxKind.SetAccessorDeclaration); if (getMethod.DeclaredAccessibility != setMethod.DeclaredAccessibility) { @@ -292,7 +294,7 @@ public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node) { if (_parameter.Equals(_semanticModel.GetSymbolInfo(node).Symbol)) { - return SyntaxFactory.IdentifierName("value").WithTriviaFrom(node); + return IdentifierName("value").WithTriviaFrom(node); } return node; @@ -336,7 +338,7 @@ public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node) // But also add a simplification annotation so we can remove the parens if possible. var argumentExpression = currentInvocation.ArgumentList.Arguments[0].Expression.Parenthesize(); - var expression = SyntaxFactory.AssignmentExpression( + var expression = AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, currentInvocation.Expression, argumentExpression); return expression.Parenthesize(); @@ -367,7 +369,7 @@ public static void ReplaceInvocation(SyntaxEditor editor, SyntaxToken nameToken, var newName = nameNode; if (nameChanged) { - newName = SyntaxFactory.IdentifierName(SyntaxFactory.Identifier(propertyName)); + newName = IdentifierName(Identifier(propertyName)); } newName = newName.WithTriviaFrom(invocation is null ? nameToken.Parent : invocation); diff --git a/src/Features/CSharp/Portable/ReplacePropertyWithMethods/CSharpReplacePropertyWithMethodsService.cs b/src/Features/CSharp/Portable/ReplacePropertyWithMethods/CSharpReplacePropertyWithMethodsService.cs index 1316a5b5038c2..277e0850572c1 100644 --- a/src/Features/CSharp/Portable/ReplacePropertyWithMethods/CSharpReplacePropertyWithMethodsService.cs +++ b/src/Features/CSharp/Portable/ReplacePropertyWithMethods/CSharpReplacePropertyWithMethodsService.cs @@ -23,6 +23,8 @@ namespace Microsoft.CodeAnalysis.CSharp.ReplacePropertyWithMethods; +using static SyntaxFactory; + [ExportLanguageService(typeof(IReplacePropertyWithMethodsService), LanguageNames.CSharp), Shared] internal partial class CSharpReplacePropertyWithMethodsService : AbstractReplacePropertyWithMethodsService @@ -129,7 +131,7 @@ MethodDeclarationSyntax GetSetMethodWorker() if (propertyDeclaration.Modifiers.Any(SyntaxKind.UnsafeKeyword) && !methodDeclaration.Modifiers.Any(SyntaxKind.UnsafeKeyword)) { - methodDeclaration = methodDeclaration.AddModifiers(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); + methodDeclaration = methodDeclaration.AddModifiers(Token(SyntaxKind.UnsafeKeyword)); } methodDeclaration = methodDeclaration.WithAttributeLists(setAccessorDeclaration.AttributeLists); @@ -147,7 +149,7 @@ MethodDeclarationSyntax GetSetMethodWorker() } else if (propertyBackingField != null) { - return methodDeclaration.WithBody(SyntaxFactory.Block( + return methodDeclaration.WithBody(Block( (StatementSyntax)generator.ExpressionStatement( generator.AssignmentStatement( GetFieldReference(generator, propertyBackingField), @@ -184,7 +186,7 @@ MethodDeclarationSyntax GetGetMethodWorker() if (propertyDeclaration.Modifiers.Any(SyntaxKind.UnsafeKeyword) && !methodDeclaration.Modifiers.Any(SyntaxKind.UnsafeKeyword)) { - methodDeclaration = methodDeclaration.AddModifiers(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); + methodDeclaration = methodDeclaration.AddModifiers(Token(SyntaxKind.UnsafeKeyword)); } if (propertyDeclaration.ExpressionBody != null) @@ -214,7 +216,7 @@ MethodDeclarationSyntax GetGetMethodWorker() { var fieldReference = GetFieldReference(generator, propertyBackingField); return methodDeclaration.WithBody( - SyntaxFactory.Block( + Block( (StatementSyntax)generator.ReturnStatement(fieldReference))); } } @@ -248,7 +250,7 @@ private static SyntaxTrivia ConvertDocumentationComment(SyntaxTrivia trivia, CSh var structure = trivia.GetStructure(); var rewritten = rewriter.Visit(structure); Contract.ThrowIfNull(rewritten); - return SyntaxFactory.Trivia((StructuredTriviaSyntax)rewritten); + return Trivia((StructuredTriviaSyntax)rewritten); } private static SyntaxNode UseExpressionOrBlockBodyIfDesired( @@ -306,17 +308,17 @@ protected override NameMemberCrefSyntax CreateCrefSyntax(NameMemberCrefSyntax or CrefParameterListSyntax parameterList; if (parameterType is TypeSyntax typeSyntax) { - var parameter = SyntaxFactory.CrefParameter(typeSyntax); - parameterList = SyntaxFactory.CrefParameterList([parameter]); + var parameter = CrefParameter(typeSyntax); + parameterList = CrefParameterList([parameter]); } else { - parameterList = SyntaxFactory.CrefParameterList(); + parameterList = CrefParameterList(); } // XmlCrefAttribute replaces with {T}, which is required for C# documentation comments - var crefAttribute = SyntaxFactory.XmlCrefAttribute( - SyntaxFactory.NameMemberCref(SyntaxFactory.IdentifierName(identifierToken), parameterList)); + var crefAttribute = XmlCrefAttribute( + NameMemberCref(IdentifierName(identifierToken), parameterList)); return (NameMemberCrefSyntax)crefAttribute.Cref; } @@ -345,6 +347,6 @@ protected override ExpressionSyntax UnwrapCompoundAssignment( if (operatorKind is SyntaxKind.None) return parent; - return SyntaxFactory.BinaryExpression(operatorKind, readExpression, parent.Right.Parenthesize()); + return BinaryExpression(operatorKind, readExpression, parent.Right.Parenthesize()); } } diff --git a/src/Features/CSharp/Portable/ReverseForStatement/CSharpReverseForStatementCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/ReverseForStatement/CSharpReverseForStatementCodeRefactoringProvider.cs index 2da8982c62456..57bca3d683538 100644 --- a/src/Features/CSharp/Portable/ReverseForStatement/CSharpReverseForStatementCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/ReverseForStatement/CSharpReverseForStatementCodeRefactoringProvider.cs @@ -20,6 +20,7 @@ namespace Microsoft.CodeAnalysis.CSharp.ReverseForStatement; using static IntegerUtilities; +using static SyntaxFactory; [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ReverseForStatement), Shared] internal class CSharpReverseForStatementCodeRefactoringProvider : CodeRefactoringProvider @@ -334,7 +335,7 @@ reducedRight is BinaryExpressionSyntax innerRight && innerRight.Kind() == SyntaxKind.SubtractExpression && IsLiteralOne(innerRight.Right)) { - var newOperator = SyntaxFactory.Token(SyntaxKind.LessThanToken).WithTriviaFrom(outerBinary.OperatorToken); + var newOperator = Token(SyntaxKind.LessThanToken).WithTriviaFrom(outerBinary.OperatorToken); return Reduce(outerBinary.WithRight(innerRight.Left) .WithOperatorToken(newOperator)); } @@ -344,7 +345,7 @@ reducedLeft is BinaryExpressionSyntax innerLeft && innerLeft.Kind() == SyntaxKind.SubtractExpression && IsLiteralOne(innerLeft.Right)) { - var newOperator = SyntaxFactory.Token(SyntaxKind.GreaterThanToken).WithTriviaFrom(outerBinary.OperatorToken); + var newOperator = Token(SyntaxKind.GreaterThanToken).WithTriviaFrom(outerBinary.OperatorToken); return Reduce(outerBinary.WithRight(innerLeft.Left) .WithOperatorToken(newOperator)); } @@ -369,8 +370,8 @@ private static BinaryExpressionSyntax Invert( ? SyntaxKind.GreaterThanOrEqualExpression : SyntaxKind.LessThanOrEqualExpression; - var newOperator = SyntaxFactory.Token(newOperatorKind).WithTriviaFrom(condition.OperatorToken); - return SyntaxFactory.BinaryExpression(newExpressionKind, left, newOperator, right); + var newOperator = Token(newOperatorKind).WithTriviaFrom(condition.OperatorToken); + return BinaryExpression(newExpressionKind, left, newOperator, right); } private static ExpressionSyntax InvertAfter(ExpressionSyntax after) @@ -392,7 +393,7 @@ private static ExpressionSyntax InvertAfter(ExpressionSyntax after) _ => throw ExceptionUtilities.UnexpectedValue(opToken.Kind()) }; - var newOpToken = SyntaxFactory.Token(newKind).WithTriviaFrom(opToken); + var newOpToken = Token(newKind).WithTriviaFrom(opToken); return after.ReplaceToken(opToken, newOpToken); } } diff --git a/src/Features/CSharp/Portable/SignatureHelp/ElementAccessExpressionSignatureHelpProvider.cs b/src/Features/CSharp/Portable/SignatureHelp/ElementAccessExpressionSignatureHelpProvider.cs index 273a01b267485..0aa0ec4939dc5 100644 --- a/src/Features/CSharp/Portable/SignatureHelp/ElementAccessExpressionSignatureHelpProvider.cs +++ b/src/Features/CSharp/Portable/SignatureHelp/ElementAccessExpressionSignatureHelpProvider.cs @@ -11,7 +11,6 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DocumentationComments; @@ -24,6 +23,8 @@ namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp; +using static SyntaxFactory; + [ExportSignatureHelpProvider("ElementAccessExpressionSignatureHelpProvider", LanguageNames.CSharp), Shared] internal sealed class ElementAccessExpressionSignatureHelpProvider : AbstractCSharpSignatureHelpProvider { @@ -153,12 +154,12 @@ private static TextSpan GetTextSpan(ExpressionSyntax expression, SyntaxToken ope // and then we need to account for this and offset the position check accordingly. int offset; BracketedArgumentListSyntax argumentList; - var newBracketedArgumentList = SyntaxFactory.ParseBracketedArgumentList(openBracket.Parent!.ToString()); + var newBracketedArgumentList = ParseBracketedArgumentList(openBracket.Parent!.ToString()); if (expression.Parent is ConditionalAccessExpressionSyntax) { // The typed code looks like: ?[ - var elementBinding = SyntaxFactory.ElementBindingExpression(newBracketedArgumentList); - var conditionalAccessExpression = SyntaxFactory.ConditionalAccessExpression(expression, elementBinding); + var elementBinding = ElementBindingExpression(newBracketedArgumentList); + var conditionalAccessExpression = ConditionalAccessExpression(expression, elementBinding); offset = expression.SpanStart - conditionalAccessExpression.SpanStart; argumentList = ((ElementBindingExpressionSyntax)conditionalAccessExpression.WhenNotNull).ArgumentList; } @@ -168,7 +169,7 @@ private static TextSpan GetTextSpan(ExpressionSyntax expression, SyntaxToken ope // [ // or // ?[ - var elementAccessExpression = SyntaxFactory.ElementAccessExpression(expression, newBracketedArgumentList); + var elementAccessExpression = ElementAccessExpression(expression, newBracketedArgumentList); offset = expression.SpanStart - elementAccessExpression.SpanStart; argumentList = elementAccessExpression.ArgumentList; } diff --git a/src/Features/CSharp/Portable/Snippets/CSharpForEachLoopSnippetProvider.cs b/src/Features/CSharp/Portable/Snippets/CSharpForEachLoopSnippetProvider.cs index 71545a0b5d9ec..59e140c31d291 100644 --- a/src/Features/CSharp/Portable/Snippets/CSharpForEachLoopSnippetProvider.cs +++ b/src/Features/CSharp/Portable/Snippets/CSharpForEachLoopSnippetProvider.cs @@ -22,6 +22,8 @@ namespace Microsoft.CodeAnalysis.CSharp.Snippets; +using static SyntaxFactory; + [ExportSnippetProvider(nameof(ISnippetProvider), LanguageNames.CSharp), Shared] [method: ImportingConstructor] [method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] @@ -53,7 +55,7 @@ protected override ForEachStatementSyntax GenerateStatement(SyntaxGenerator gene var semanticModel = syntaxContext.SemanticModel; var position = syntaxContext.Position; - var varIdentifier = SyntaxFactory.IdentifierName("var"); + var varIdentifier = IdentifierName("var"); var collectionIdentifier = (ExpressionSyntax?)inlineExpressionInfo?.Node; if (collectionIdentifier is null) @@ -63,8 +65,8 @@ protected override ForEachStatementSyntax GenerateStatement(SyntaxGenerator gene (isAsync ? symbolType.CanBeAsynchronouslyEnumerated(semanticModel.Compilation) : symbolType.CanBeEnumerated()) && symbol.Kind is SymbolKind.Local or SymbolKind.Field or SymbolKind.Parameter or SymbolKind.Property); collectionIdentifier = enumerationSymbol is null - ? SyntaxFactory.IdentifierName("collection") - : SyntaxFactory.IdentifierName(enumerationSymbol.Name); + ? IdentifierName("collection") + : IdentifierName(enumerationSymbol.Name); } var itemString = NameGenerator.GenerateUniqueName( @@ -75,24 +77,24 @@ protected override ForEachStatementSyntax GenerateStatement(SyntaxGenerator gene if (inlineExpressionInfo is { TypeInfo: var typeInfo } && typeInfo.Type!.CanBeAsynchronouslyEnumerated(semanticModel.Compilation)) { - forEachStatement = SyntaxFactory.ForEachStatement( - SyntaxFactory.Token(SyntaxKind.AwaitKeyword), - SyntaxFactory.Token(SyntaxKind.ForEachKeyword), - SyntaxFactory.Token(SyntaxKind.OpenParenToken), + forEachStatement = ForEachStatement( + Token(SyntaxKind.AwaitKeyword), + Token(SyntaxKind.ForEachKeyword), + Token(SyntaxKind.OpenParenToken), varIdentifier, - SyntaxFactory.Identifier(itemString), - SyntaxFactory.Token(SyntaxKind.InKeyword), + Identifier(itemString), + Token(SyntaxKind.InKeyword), collectionIdentifier.WithoutLeadingTrivia(), - SyntaxFactory.Token(SyntaxKind.CloseParenToken), - SyntaxFactory.Block()); + Token(SyntaxKind.CloseParenToken), + Block()); } else { - forEachStatement = SyntaxFactory.ForEachStatement( + forEachStatement = ForEachStatement( varIdentifier, itemString, collectionIdentifier.WithoutLeadingTrivia(), - SyntaxFactory.Block()); + Block()); } return forEachStatement.NormalizeWhitespace(); diff --git a/src/Features/CSharp/Portable/SplitOrMergeIfStatements/CSharpIfLikeStatementGenerator.cs b/src/Features/CSharp/Portable/SplitOrMergeIfStatements/CSharpIfLikeStatementGenerator.cs index b9c07e20eea64..5963590fad5e3 100644 --- a/src/Features/CSharp/Portable/SplitOrMergeIfStatements/CSharpIfLikeStatementGenerator.cs +++ b/src/Features/CSharp/Portable/SplitOrMergeIfStatements/CSharpIfLikeStatementGenerator.cs @@ -15,6 +15,8 @@ namespace Microsoft.CodeAnalysis.CSharp.SplitOrMergeIfStatements; +using static SyntaxFactory; + [ExportLanguageService(typeof(IIfLikeStatementGenerator), LanguageNames.CSharp), Shared] internal sealed class CSharpIfLikeStatementGenerator : IIfLikeStatementGenerator { @@ -110,7 +112,7 @@ public SyntaxNode WithCondition(SyntaxNode ifOrElseIf, SyntaxNode condition) public SyntaxNode WithStatementInBlock(SyntaxNode ifOrElseIf, SyntaxNode statement) { var ifStatement = (IfStatementSyntax)ifOrElseIf; - return ifStatement.WithStatement(SyntaxFactory.Block((StatementSyntax)statement)); + return ifStatement.WithStatement(Block((StatementSyntax)statement)); } public SyntaxNode WithStatementsOf(SyntaxNode ifOrElseIf, SyntaxNode otherIfOrElseIf) @@ -137,14 +139,14 @@ public void InsertElseIfClause(SyntaxEditor editor, SyntaxNode afterIfOrElseIf, var elseIfStatement = (IfStatementSyntax)elseIfClause; var newElseIfStatement = elseIfStatement.WithElse(ifStatement.Else); - var newIfStatement = ifStatement.WithElse(SyntaxFactory.ElseClause(newElseIfStatement)); + var newIfStatement = ifStatement.WithElse(ElseClause(newElseIfStatement)); if (ifStatement.Else == null && ContainsEmbeddedIfStatement(ifStatement)) { // If the if statement contains an embedded if statement (not wrapped inside a block), adding an else // clause might introduce a dangling else problem (the 'else' would bind to the inner if statement), // so if there used to be no else clause, we'll insert a new block to prevent that. - newIfStatement = newIfStatement.WithStatement(SyntaxFactory.Block(newIfStatement.Statement)); + newIfStatement = newIfStatement.WithStatement(Block(newIfStatement.Statement)); } return newIfStatement; diff --git a/src/Features/CSharp/Portable/SplitStringLiteral/InterpolatedStringSplitter.cs b/src/Features/CSharp/Portable/SplitStringLiteral/InterpolatedStringSplitter.cs index 6fa367b2bc8a8..9d55e9bd582a3 100644 --- a/src/Features/CSharp/Portable/SplitStringLiteral/InterpolatedStringSplitter.cs +++ b/src/Features/CSharp/Portable/SplitStringLiteral/InterpolatedStringSplitter.cs @@ -8,12 +8,13 @@ using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Indentation; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.SplitStringLiteral; +using static SyntaxFactory; + internal abstract partial class StringSplitter { private sealed class InterpolatedStringSplitter( @@ -58,18 +59,18 @@ protected override BinaryExpressionSyntax CreateSplitString() } } - var leftExpression = SyntaxFactory.InterpolatedStringExpression( + var leftExpression = InterpolatedStringExpression( _interpolatedStringExpression.StringStartToken, [.. beforeSplitContents], - SyntaxFactory.Token(SyntaxKind.InterpolatedStringEndToken) - .WithTrailingTrivia(SyntaxFactory.ElasticSpace)); + Token(SyntaxKind.InterpolatedStringEndToken) + .WithTrailingTrivia(ElasticSpace)); - var rightExpression = SyntaxFactory.InterpolatedStringExpression( - SyntaxFactory.Token(SyntaxKind.InterpolatedStringStartToken), + var rightExpression = InterpolatedStringExpression( + Token(SyntaxKind.InterpolatedStringStartToken), [.. afterSplitContents], _interpolatedStringExpression.StringEndToken); - return SyntaxFactory.BinaryExpression( + return BinaryExpression( SyntaxKind.AddExpression, leftExpression, PlusNewLineToken, @@ -79,8 +80,8 @@ protected override BinaryExpressionSyntax CreateSplitString() private InterpolatedStringTextSyntax CreateInterpolatedStringText(int start, int end) { var content = Document.Text.ToString(TextSpan.FromBounds(start, end)); - return SyntaxFactory.InterpolatedStringText( - SyntaxFactory.Token( + return InterpolatedStringText( + Token( leading: default, kind: SyntaxKind.InterpolatedStringTextToken, text: content, diff --git a/src/Features/CSharp/Portable/UseAutoProperty/CSharpUseAutoPropertyCodeFixProvider.cs b/src/Features/CSharp/Portable/UseAutoProperty/CSharpUseAutoPropertyCodeFixProvider.cs index 6a12f660c1851..746225d1020fd 100644 --- a/src/Features/CSharp/Portable/UseAutoProperty/CSharpUseAutoPropertyCodeFixProvider.cs +++ b/src/Features/CSharp/Portable/UseAutoProperty/CSharpUseAutoPropertyCodeFixProvider.cs @@ -20,6 +20,8 @@ namespace Microsoft.CodeAnalysis.CSharp.UseAutoProperty; +using static SyntaxFactory; + [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseAutoProperty), Shared] internal class CSharpUseAutoPropertyCodeFixProvider : AbstractUseAutoPropertyCodeFixProvider @@ -49,14 +51,14 @@ protected override async Task UpdatePropertyAsync( var updatedProperty = propertyDeclaration.WithAccessorList(UpdateAccessorList(propertyDeclaration.AccessorList)) .WithExpressionBody(null) - .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)); + .WithSemicolonToken(Token(SyntaxKind.None)); // We may need to add a setter if the field is written to outside of the constructor // of it's class. if (NeedsSetter(compilation, propertyDeclaration, isWrittenOutsideOfConstructor)) { - var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration) - .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); + var accessor = AccessorDeclaration(SyntaxKind.SetAccessorDeclaration) + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); var generator = SyntaxGenerator.GetGenerator(project); if (fieldSymbol.DeclaredAccessibility != propertySymbol.DeclaredAccessibility) @@ -64,7 +66,7 @@ protected override async Task UpdatePropertyAsync( accessor = (AccessorDeclarationSyntax)generator.WithAccessibility(accessor, fieldSymbol.DeclaredAccessibility); } - var modifiers = SyntaxFactory.TokenList( + var modifiers = TokenList( updatedProperty.Modifiers.Where(token => !token.IsKind(SyntaxKind.ReadOnlyKeyword))); updatedProperty = updatedProperty.WithModifiers(modifiers) @@ -74,8 +76,8 @@ protected override async Task UpdatePropertyAsync( var fieldInitializer = await GetFieldInitializerAsync(fieldSymbol, cancellationToken).ConfigureAwait(false); if (fieldInitializer != null) { - updatedProperty = updatedProperty.WithInitializer(SyntaxFactory.EqualsValueClause(fieldInitializer)) - .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); + updatedProperty = updatedProperty.WithInitializer(EqualsValueClause(fieldInitializer)) + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); } return updatedProperty.WithTrailingTrivia(trailingTrivia).WithAdditionalAnnotations(SpecializedFormattingAnnotation); @@ -164,9 +166,9 @@ private static AccessorListSyntax UpdateAccessorList(AccessorListSyntax accessor { if (accessorList == null) { - var getter = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) - .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); - return SyntaxFactory.AccessorList([getter]); + var getter = AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + return AccessorList([getter]); } return accessorList.WithAccessors([.. GetAccessors(accessorList.Accessors)]); @@ -178,7 +180,7 @@ private static IEnumerable GetAccessors(SyntaxList GetArguments(BaseArgument protected override BaseArgumentListSyntax WithArguments( BaseArgumentListSyntax argumentList, IEnumerable namedArguments, IEnumerable separators) - => argumentList.WithArguments(SyntaxFactory.SeparatedList(namedArguments, separators)); + => argumentList.WithArguments(SeparatedList(namedArguments, separators)); protected override ArgumentSyntax WithName(ArgumentSyntax argument, string name) - => argument.WithNameColon(SyntaxFactory.NameColon(name.ToIdentifierName())); + => argument.WithNameColon(NameColon(name.ToIdentifierName())); protected override ExpressionSyntax GetArgumentExpression(ArgumentSyntax argumentSyntax) => argumentSyntax.Expression; @@ -86,10 +88,10 @@ protected override SeparatedSyntaxList GetArguments(Att protected override AttributeArgumentListSyntax WithArguments( AttributeArgumentListSyntax argumentList, IEnumerable namedArguments, IEnumerable separators) - => argumentList.WithArguments(SyntaxFactory.SeparatedList(namedArguments, separators)); + => argumentList.WithArguments(SeparatedList(namedArguments, separators)); protected override AttributeArgumentSyntax WithName(AttributeArgumentSyntax argument, string name) - => argument.WithNameColon(SyntaxFactory.NameColon(name.ToIdentifierName())); + => argument.WithNameColon(NameColon(name.ToIdentifierName())); protected override ExpressionSyntax GetArgumentExpression(AttributeArgumentSyntax argumentSyntax) => argumentSyntax.Expression; diff --git a/src/Workspaces/CSharp/Portable/Simplification/CSharpSimplificationService.Expander.cs b/src/Workspaces/CSharp/Portable/Simplification/CSharpSimplificationService.Expander.cs index cc7644984d66e..de7e89fd807b8 100644 --- a/src/Workspaces/CSharp/Portable/Simplification/CSharpSimplificationService.Expander.cs +++ b/src/Workspaces/CSharp/Portable/Simplification/CSharpSimplificationService.Expander.cs @@ -24,11 +24,13 @@ namespace Microsoft.CodeAnalysis.CSharp.Simplification; +using static SyntaxFactory; + internal partial class CSharpSimplificationService { private class Expander : CSharpSyntaxRewriter { - private static readonly SyntaxTrivia s_oneWhitespaceSeparator = SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " "); + private static readonly SyntaxTrivia s_oneWhitespaceSeparator = SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " "); private static readonly SymbolDisplayFormat s_typeNameFormatWithGenerics = new( @@ -224,9 +226,9 @@ public override SyntaxNode VisitSimpleLambdaExpression(SimpleLambdaExpressionSyn var typeSyntax = parameterSymbol.Type.GenerateTypeSyntax().WithTrailingTrivia(s_oneWhitespaceSeparator); var newSimpleLambdaParameter = simpleLambda.Parameter.WithType(typeSyntax).WithoutTrailingTrivia(); - var parenthesizedLambda = SyntaxFactory.ParenthesizedLambdaExpression( + var parenthesizedLambda = ParenthesizedLambdaExpression( simpleLambda.AsyncKeyword, - SyntaxFactory.ParameterList([newSimpleLambdaParameter]) + ParameterList([newSimpleLambdaParameter]) .WithTrailingTrivia(simpleLambda.Parameter.GetTrailingTrivia()) .WithLeadingTrivia(simpleLambda.Parameter.GetLeadingTrivia()), simpleLambda.ArrowToken, @@ -255,12 +257,12 @@ public override SyntaxNode VisitArgument(ArgumentSyntax node) var inferredName = node.Expression.TryGetInferredMemberName(); if (CanMakeNameExplicitInTuple(tuple, inferredName)) { - var identifier = SyntaxFactory.Identifier(inferredName); + var identifier = Identifier(inferredName); identifier = TryEscapeIdentifierToken(identifier, node); newArgument = newArgument .WithoutLeadingTrivia() - .WithNameColon(SyntaxFactory.NameColon(SyntaxFactory.IdentifierName(identifier))) + .WithNameColon(NameColon(IdentifierName(identifier))) .WithAdditionalAnnotations(Simplifier.Annotation) .WithLeadingTrivia(node.GetLeadingTrivia()); } @@ -325,12 +327,12 @@ public override SyntaxNode VisitAnonymousObjectMemberDeclarator(AnonymousObjectM if (inferredName != null) { // Creating identifier without elastic trivia to avoid unexpected line break - var identifier = SyntaxFactory.Identifier(SyntaxTriviaList.Empty, inferredName, SyntaxTriviaList.Empty); + var identifier = Identifier(SyntaxTriviaList.Empty, inferredName, SyntaxTriviaList.Empty); identifier = TryEscapeIdentifierToken(identifier, node); newDeclarator = newDeclarator .WithoutLeadingTrivia() - .WithNameEquals(SyntaxFactory.NameEquals(SyntaxFactory.IdentifierName(identifier)) + .WithNameEquals(NameEquals(IdentifierName(identifier)) .WithLeadingTrivia(node.GetLeadingTrivia())) .WithAdditionalAnnotations(Simplifier.Annotation); } @@ -394,10 +396,10 @@ public override SyntaxNode VisitNameMemberCref(NameMemberCrefSyntax node) if (rewrittenname.Kind() == SyntaxKind.QualifiedName) { - return node.CopyAnnotationsTo(SyntaxFactory.QualifiedCref( + return node.CopyAnnotationsTo(QualifiedCref( ((QualifiedNameSyntax)rewrittenname).Left .WithAdditionalAnnotations(Simplifier.Annotation), - SyntaxFactory.NameMemberCref(((QualifiedNameSyntax)rewrittenname).Right, parameters) + NameMemberCref(((QualifiedNameSyntax)rewrittenname).Right, parameters) .WithLeadingTrivia(SyntaxTriviaList.Empty)) .WithLeadingTrivia(node.GetLeadingTrivia()) .WithTrailingTrivia(node.GetTrailingTrivia())) @@ -405,7 +407,7 @@ public override SyntaxNode VisitNameMemberCref(NameMemberCrefSyntax node) } else if (rewrittenname.Kind() == SyntaxKind.AliasQualifiedName) { - return node.CopyAnnotationsTo(SyntaxFactory.TypeCref( + return node.CopyAnnotationsTo(TypeCref( rewrittenname).WithLeadingTrivia(node.GetLeadingTrivia()) .WithTrailingTrivia(node.GetTrailingTrivia())) .WithAdditionalAnnotations(Simplifier.Annotation); @@ -597,7 +599,7 @@ SyntaxToken GetNewIdentifier(SyntaxToken _identifier) identifier = identifier.WithAdditionalAnnotations(SimplificationHelpers.DoNotSimplifyAnnotation); } - identifier = identifier.CopyAnnotationsTo(SyntaxFactory.VerbatimIdentifier(identifier.LeadingTrivia, name, name, identifier.TrailingTrivia)); + identifier = identifier.CopyAnnotationsTo(VerbatimIdentifier(identifier.LeadingTrivia, name, name, identifier.TrailingTrivia)); } } @@ -688,18 +690,18 @@ SymbolKind.Field or // Assumption here is, if the enclosing and containing types are different then there is inheritance relationship if (!Equals(_semanticModel.GetEnclosingNamedType(originalSimpleName.SpanStart, _cancellationToken), symbol.ContainingType)) { - left = SyntaxFactory.BaseExpression(); + left = BaseExpression(); } else { - left = SyntaxFactory.ThisExpression(); + left = ThisExpression(); } var identifiersLeadingTrivia = newNode.GetLeadingTrivia(); newNode = TryAddTypeArgumentToIdentifierName(newNode, symbol); newNode = newNode.CopyAnnotationsTo( - SyntaxFactory.MemberAccessExpression( + MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, left, (SimpleNameSyntax)newNode.WithLeadingTrivia(null)) @@ -745,10 +747,10 @@ private static ExpressionSyntax TryAddTypeArgumentToIdentifierName(ExpressionSyn var typeArguments = ((IMethodSymbol)symbol).TypeArguments; if (!typeArguments.Any(static t => t.ContainsAnonymousType())) { - var genericName = SyntaxFactory.GenericName( + var genericName = GenericName( ((IdentifierNameSyntax)newNode).Identifier, - SyntaxFactory.TypeArgumentList( - [.. typeArguments.Select(p => SyntaxFactory.ParseTypeName(p.ToDisplayString(s_typeNameFormatWithGenerics)))])) + TypeArgumentList( + [.. typeArguments.Select(p => ParseTypeName(p.ToDisplayString(s_typeNameFormatWithGenerics)))])) .WithLeadingTrivia(newNode.GetLeadingTrivia()) .WithTrailingTrivia(newNode.GetTrailingTrivia()) .WithAdditionalAnnotations(Simplifier.Annotation); @@ -912,8 +914,8 @@ private ExpressionSyntax FullyQualifyIdentifierName( if (!replaceNode && symbol.ContainingType == null && symbol.ContainingNamespace.IsGlobalNamespace) { return rewrittenNode.CopyAnnotationsTo( - SyntaxFactory.AliasQualifiedName( - SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)), + AliasQualifiedName( + IdentifierName(Token(SyntaxKind.GlobalKeyword)), (SimpleNameSyntax)rewrittenNode.WithLeadingTrivia(null)) .WithLeadingTrivia(rewrittenNode.GetLeadingTrivia())); } @@ -932,7 +934,7 @@ private ExpressionSyntax FullyQualifyIdentifierName( var displayString = displaySymbol.ToDisplayString(s_typeNameFormatWithGenerics); - ExpressionSyntax left = SyntaxFactory.ParseTypeName(displayString); + ExpressionSyntax left = ParseTypeName(displayString); // Replaces the '<' token with the '{' token since we are inside crefs left = TryReplaceAngleBracesWithCurlyBraces(left, isInsideCref); @@ -953,7 +955,7 @@ private ExpressionSyntax FullyQualifyIdentifierName( { case SyntaxKind.QualifiedName: result = rewrittenNode.CopyAnnotationsTo( - SyntaxFactory.QualifiedName( + QualifiedName( (NameSyntax)left, (SimpleNameSyntax)rewrittenNode)); @@ -961,7 +963,7 @@ private ExpressionSyntax FullyQualifyIdentifierName( case SyntaxKind.SimpleMemberAccessExpression: result = rewrittenNode.CopyAnnotationsTo( - SyntaxFactory.MemberAccessExpression( + MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, left, (SimpleNameSyntax)rewrittenNode)); @@ -974,17 +976,17 @@ private ExpressionSyntax FullyQualifyIdentifierName( if (SyntaxFacts.IsInNamespaceOrTypeContext(originalNode)) { var right = (SimpleNameSyntax)rewrittenNode; - result = rewrittenNode.CopyAnnotationsTo(SyntaxFactory.QualifiedName((NameSyntax)left, right.WithAdditionalAnnotations(Simplifier.SpecialTypeAnnotation))); + result = rewrittenNode.CopyAnnotationsTo(QualifiedName((NameSyntax)left, right.WithAdditionalAnnotations(Simplifier.SpecialTypeAnnotation))); } else if (originalNode.Parent is CrefSyntax) { var right = (SimpleNameSyntax)rewrittenNode; - result = rewrittenNode.CopyAnnotationsTo(SyntaxFactory.QualifiedName((NameSyntax)left, right)); + result = rewrittenNode.CopyAnnotationsTo(QualifiedName((NameSyntax)left, right)); } else { result = rewrittenNode.CopyAnnotationsTo( - SyntaxFactory.MemberAccessExpression( + MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, left, (SimpleNameSyntax)rewrittenNode)); @@ -1004,12 +1006,12 @@ private SyntaxToken ReplaceTokenForCref(SyntaxToken oldToken, SyntaxToken dummyS { if (oldToken.Kind() == SyntaxKind.LessThanToken) { - return SyntaxFactory.Token(oldToken.LeadingTrivia, SyntaxKind.LessThanToken, "{", "{", oldToken.TrailingTrivia); + return Token(oldToken.LeadingTrivia, SyntaxKind.LessThanToken, "{", "{", oldToken.TrailingTrivia); } if (oldToken.Kind() == SyntaxKind.GreaterThanToken) { - return SyntaxFactory.Token(oldToken.LeadingTrivia, SyntaxKind.GreaterThanToken, "}", "}", oldToken.TrailingTrivia); + return Token(oldToken.LeadingTrivia, SyntaxKind.GreaterThanToken, "}", "}", oldToken.TrailingTrivia); } Debug.Assert(false, "This method is used only replacing the '<' and '>' to '{' and '}' respectively"); @@ -1097,7 +1099,7 @@ private InvocationExpressionSyntax RewriteExtensionMethodInvocation( // We use .ParseExpression here, and not .GenerateTypeSyntax as we want this to be a property // MemberAccessExpression, and not a QualifiedNameSyntax. - var containingTypeSyntax = SyntaxFactory.ParseExpression(containingTypeString); + var containingTypeSyntax = ParseExpression(containingTypeString); var newContainingType = _semanticModel.GetSpeculativeSymbolInfo(speculationPosition, containingTypeSyntax, SpeculativeBindingOption.BindAsExpression).Symbol; if (newContainingType == null || !newContainingType.Equals(reducedExtensionMethod.ContainingType)) return originalNode; @@ -1109,13 +1111,13 @@ private InvocationExpressionSyntax RewriteExtensionMethodInvocation( // Copies the annotation for the member access expression newMemberAccess = originalNode.Expression.CopyAnnotationsTo(newMemberAccess).WithAdditionalAnnotations(Simplifier.Annotation); - var thisArgument = SyntaxFactory.Argument(thisExpression).WithLeadingTrivia(SyntaxTriviaList.Empty); + var thisArgument = Argument(thisExpression).WithLeadingTrivia(SyntaxTriviaList.Empty); // Copies the annotation for the left hand side of the member access expression to the first argument in the complexified form thisArgument = originalMemberAccess.Expression.CopyAnnotationsTo(thisArgument); var arguments = originalNode.ArgumentList.Arguments.Insert(0, thisArgument); - var replacementNode = SyntaxFactory.InvocationExpression( + var replacementNode = InvocationExpression( newMemberAccess, originalNode.ArgumentList.WithArguments(arguments)); diff --git a/src/Workspaces/CSharp/Portable/Simplification/Simplifiers/NameSimplifier.cs b/src/Workspaces/CSharp/Portable/Simplification/Simplifiers/NameSimplifier.cs index d9aee0b2ac3eb..31b5cfc0da3ca 100644 --- a/src/Workspaces/CSharp/Portable/Simplification/Simplifiers/NameSimplifier.cs +++ b/src/Workspaces/CSharp/Portable/Simplification/Simplifiers/NameSimplifier.cs @@ -21,6 +21,7 @@ namespace Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers; using Microsoft.CodeAnalysis.Rename.ConflictEngine; +using static SyntaxFactory; internal class NameSimplifier : AbstractCSharpSimplifier { @@ -85,7 +86,7 @@ public override bool TrySimplify( if (symbol.Kind == SymbolKind.Method && name.Kind() == SyntaxKind.GenericName) { var genericName = (GenericNameSyntax)name; - replacementNode = SyntaxFactory.IdentifierName(genericName.Identifier) + replacementNode = IdentifierName(genericName.Identifier) .WithLeadingTrivia(genericName.GetLeadingTrivia()) .WithTrailingTrivia(genericName.GetTrailingTrivia()); @@ -125,7 +126,7 @@ public override bool TrySimplify( text = declIdentifier.IsVerbatimIdentifier() ? declIdentifier.ToString()[1..] : declIdentifier.ToString(); } - var identifierToken = SyntaxFactory.Identifier( + var identifierToken = Identifier( name.GetLeadingTrivia(), SyntaxKind.IdentifierToken, text, @@ -133,7 +134,7 @@ public override bool TrySimplify( name.GetTrailingTrivia()); identifierToken = CSharpSimplificationService.TryEscapeIdentifierToken(identifierToken, name); - replacementNode = SyntaxFactory.IdentifierName(identifierToken); + replacementNode = IdentifierName(identifierToken); // Merge annotation to new syntax node var annotatedNodesOrTokens = name.GetAnnotatedNodesAndTokens(RenameAnnotation.Kind); @@ -290,7 +291,7 @@ public override bool TrySimplify( return false; } - replacementNode = SyntaxFactory.NullableType(oldType) + replacementNode = NullableType(oldType) .WithLeadingTrivia(name.GetLeadingTrivia()) .WithTrailingTrivia(name.GetTrailingTrivia()); issueSpan = name.Span; @@ -379,7 +380,7 @@ private static bool TryReduceCrefColorColor( // A.B.C with C. In this case the parent of A.B.C is A.B.C.D which is a // QualifiedCrefSyntax - var qualifiedReplacement = SyntaxFactory.QualifiedCref(replacement, qualifiedCrefParent.Member); + var qualifiedReplacement = QualifiedCref(replacement, qualifiedCrefParent.Member); if (QualifiedCrefSimplifier.CanSimplifyWithReplacement(qualifiedCrefParent, semanticModel, qualifiedReplacement, cancellationToken)) return true; } @@ -390,7 +391,7 @@ private static bool TryReduceCrefColorColor( // A.B with B. In this case the parent of A.B is A.B.C which is a // QualifiedNameSyntax - var qualifiedReplacement = SyntaxFactory.QualifiedName(replacementName, qualifiedParent.Right); + var qualifiedReplacement = QualifiedName(replacementName, qualifiedParent.Right); return CanReplaceWithReducedName( qualifiedParent, qualifiedReplacement, semanticModel, cancellationToken); } @@ -510,12 +511,12 @@ private static bool TryReduceAttributeSuffix( // if this attribute name in source contained Unicode escaping, we will loose it now // because there is no easy way to determine the substring from identifier->ToString() - // which would be needed to pass to SyntaxFactory.Identifier + // which would be needed to pass to Identifier // The result is an unescaped Unicode character in source. // once we remove the Attribute suffix, we can't use an escaped identifier var newIdentifierToken = identifierToken.CopyAnnotationsTo( - SyntaxFactory.Identifier( + Identifier( identifierToken.LeadingTrivia, newAttributeName, identifierToken.TrailingTrivia)); @@ -523,12 +524,12 @@ private static bool TryReduceAttributeSuffix( switch (name) { case GenericNameSyntax generic: - replacementNode = SyntaxFactory.GenericName(newIdentifierToken, generic.TypeArgumentList) + replacementNode = GenericName(newIdentifierToken, generic.TypeArgumentList) .WithLeadingTrivia(name.GetLeadingTrivia()); break; default: - replacementNode = SyntaxFactory.IdentifierName(newIdentifierToken) + replacementNode = IdentifierName(newIdentifierToken) .WithLeadingTrivia(name.GetLeadingTrivia()); break; } @@ -664,7 +665,7 @@ private static bool IsAmbiguousCast(ExpressionSyntax expression, ExpressionSynta castExpression.Type == expression) { var newCastExpression = castExpression.ReplaceNode(castExpression.Type, simplifiedNode); - var reparsedCastExpression = SyntaxFactory.ParseExpression(newCastExpression.ToString()); + var reparsedCastExpression = ParseExpression(newCastExpression.ToString()); if (!reparsedCastExpression.IsKind(SyntaxKind.CastExpression)) { diff --git a/src/Workspaces/CSharpTest/CodeGeneration/AddAttributesTests.cs b/src/Workspaces/CSharpTest/CodeGeneration/AddAttributesTests.cs index 27fa2160a9024..3522df7a833b9 100644 --- a/src/Workspaces/CSharpTest/CodeGeneration/AddAttributesTests.cs +++ b/src/Workspaces/CSharpTest/CodeGeneration/AddAttributesTests.cs @@ -15,6 +15,8 @@ namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGeneration { + using static SyntaxFactory; + [UseExportProvider] public class AddAttributesTests { @@ -38,12 +40,12 @@ private static async Task TestAsync(string initialText, string attributeAddedTex var doc = GetDocument(initialText); var attributeList = - SyntaxFactory.AttributeList( - [SyntaxFactory.Attribute( - SyntaxFactory.IdentifierName("System.Reflection.AssemblyVersion(\"1.0.0.0\")"))]) + AttributeList( + [Attribute( + IdentifierName("System.Reflection.AssemblyVersion(\"1.0.0.0\")"))]) .WithTarget( - SyntaxFactory.AttributeTargetSpecifier( - SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))); + AttributeTargetSpecifier( + Token(SyntaxKind.AssemblyKeyword))); var syntaxRoot = await doc.GetSyntaxRootAsync(); var editor = await DocumentEditor.CreateAsync(doc); diff --git a/src/Workspaces/CSharpTest/CodeGeneration/SyntaxGeneratorTests.cs b/src/Workspaces/CSharpTest/CodeGeneration/SyntaxGeneratorTests.cs index 29e15cbaddf39..3981b249210e6 100644 --- a/src/Workspaces/CSharpTest/CodeGeneration/SyntaxGeneratorTests.cs +++ b/src/Workspaces/CSharpTest/CodeGeneration/SyntaxGeneratorTests.cs @@ -21,6 +21,8 @@ namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Editing { + using static SyntaxFactory; + [UseExportProvider] public class SyntaxGeneratorTests { @@ -44,7 +46,7 @@ public static Compilation Compile(string code) { return CSharpCompilation.Create("test") .AddReferences(TestMetadata.Net451.mscorlib, TestMetadata.Net451.System, TestMetadata.Net451.SystemCore, TestMetadata.Net451.SystemRuntime, TestReferences.NetFx.ValueTuple.tuplelib) - .AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(code)); + .AddSyntaxTrees(ParseSyntaxTree(code)); } private static void VerifySyntax(SyntaxNode node, string expectedText) where TSyntax : SyntaxNode @@ -1188,266 +1190,266 @@ public void TestAsPublicInterfaceImplementation() #region ExpressionBodyTests VerifySyntax( Generator.AsPublicInterfaceImplementation( - SyntaxFactory.MethodDeclaration( - SyntaxFactory.PredefinedType( - SyntaxFactory.Token( + MethodDeclaration( + PredefinedType( + Token( [], SyntaxKind.ObjectKeyword, - SyntaxFactory.TriviaList( - SyntaxFactory.Space))), - SyntaxFactory.Identifier("DoSomething")) + TriviaList( + Space))), + Identifier("DoSomething")) .WithExplicitInterfaceSpecifier( - SyntaxFactory.ExplicitInterfaceSpecifier( - SyntaxFactory.IdentifierName("IGeneral"))) + ExplicitInterfaceSpecifier( + IdentifierName("IGeneral"))) .WithParameterList( - SyntaxFactory.ParameterList() + ParameterList() .WithCloseParenToken( - SyntaxFactory.Token( + Token( [], SyntaxKind.CloseParenToken, - SyntaxFactory.TriviaList( - SyntaxFactory.Space)))) + TriviaList( + Space)))) .WithExpressionBody( - SyntaxFactory.ArrowExpressionClause( - SyntaxFactory.ImplicitObjectCreationExpression()) + ArrowExpressionClause( + ImplicitObjectCreationExpression()) .WithArrowToken( - SyntaxFactory.Token( + Token( [], SyntaxKind.EqualsGreaterThanToken, - SyntaxFactory.TriviaList( - SyntaxFactory.Space)))) + TriviaList( + Space)))) .WithSemicolonToken( - SyntaxFactory.Token(SyntaxKind.SemicolonToken)), + Token(SyntaxKind.SemicolonToken)), Generator.IdentifierName("i")), "public object DoSomething() => new();"); VerifySyntax( Generator.AsPublicInterfaceImplementation( - SyntaxFactory.OperatorDeclaration( - SyntaxFactory.PredefinedType( - SyntaxFactory.Token(SyntaxKind.IntKeyword)), - SyntaxFactory.Token(SyntaxKind.PlusToken)) + OperatorDeclaration( + PredefinedType( + Token(SyntaxKind.IntKeyword)), + Token(SyntaxKind.PlusToken)) .WithModifiers([ - SyntaxFactory.Token(SyntaxKind.PublicKeyword), - SyntaxFactory.Token(SyntaxKind.StaticKeyword)]) + Token(SyntaxKind.PublicKeyword), + Token(SyntaxKind.StaticKeyword)]) .WithExplicitInterfaceSpecifier( - SyntaxFactory.ExplicitInterfaceSpecifier( - SyntaxFactory.GenericName( - SyntaxFactory.Identifier("IGeneral")) + ExplicitInterfaceSpecifier( + GenericName( + Identifier("IGeneral")) .WithTypeArgumentList( - SyntaxFactory.TypeArgumentList([SyntaxFactory.IdentifierName("C")])))) + TypeArgumentList([IdentifierName("C")])))) .WithParameterList( - SyntaxFactory.ParameterList( - SyntaxFactory.SeparatedList( + ParameterList( + SeparatedList( new SyntaxNodeOrToken[]{ - SyntaxFactory.Parameter( - SyntaxFactory.Identifier("x")) + Parameter( + Identifier("x")) .WithType( - SyntaxFactory.IdentifierName("C")), - SyntaxFactory.Token(SyntaxKind.CommaToken), - SyntaxFactory.Parameter( - SyntaxFactory.Identifier("y")) + IdentifierName("C")), + Token(SyntaxKind.CommaToken), + Parameter( + Identifier("y")) .WithType( - SyntaxFactory.IdentifierName("C"))}))) + IdentifierName("C"))}))) .WithExpressionBody( - SyntaxFactory.ArrowExpressionClause( - SyntaxFactory.LiteralExpression( + ArrowExpressionClause( + LiteralExpression( SyntaxKind.NumericLiteralExpression, - SyntaxFactory.Literal(0)))) + Literal(0)))) .WithSemicolonToken( - SyntaxFactory.Token(SyntaxKind.SemicolonToken)) + Token(SyntaxKind.SemicolonToken)) .NormalizeWhitespace(), Generator.IdentifierName("i")), "public static int operator +(C x, C y) => 0;"); VerifySyntax( Generator.AsPublicInterfaceImplementation( - SyntaxFactory.ConversionOperatorDeclaration( - SyntaxFactory.Token( + ConversionOperatorDeclaration( + Token( [], SyntaxKind.ImplicitKeyword, - SyntaxFactory.TriviaList( - SyntaxFactory.Space)), - SyntaxFactory.PredefinedType( - SyntaxFactory.Token(SyntaxKind.StringKeyword))) + TriviaList( + Space)), + PredefinedType( + Token(SyntaxKind.StringKeyword))) .WithModifiers( - [SyntaxFactory.Token( + [Token( [], SyntaxKind.StaticKeyword, - SyntaxFactory.TriviaList( - SyntaxFactory.Space))]) + TriviaList( + Space))]) .WithExplicitInterfaceSpecifier( - SyntaxFactory.ExplicitInterfaceSpecifier( - SyntaxFactory.GenericName( - SyntaxFactory.Identifier("IGeneral")) + ExplicitInterfaceSpecifier( + GenericName( + Identifier("IGeneral")) .WithTypeArgumentList( - SyntaxFactory.TypeArgumentList([SyntaxFactory.IdentifierName("C")])))) + TypeArgumentList([IdentifierName("C")])))) .WithOperatorKeyword( - SyntaxFactory.Token( + Token( [], SyntaxKind.OperatorKeyword, - SyntaxFactory.TriviaList( - SyntaxFactory.Space))) + TriviaList( + Space))) .WithParameterList( - SyntaxFactory.ParameterList( - [SyntaxFactory.Parameter( - SyntaxFactory.Identifier("x")) + ParameterList( + [Parameter( + Identifier("x")) .WithType( - SyntaxFactory.IdentifierName( - SyntaxFactory.Identifier( + IdentifierName( + Identifier( [], "C", - SyntaxFactory.TriviaList( - SyntaxFactory.Space))))]) + TriviaList( + Space))))]) .WithCloseParenToken( - SyntaxFactory.Token( + Token( [], SyntaxKind.CloseParenToken, - SyntaxFactory.TriviaList( - SyntaxFactory.Space)))) + TriviaList( + Space)))) .WithExpressionBody( - SyntaxFactory.ArrowExpressionClause( - SyntaxFactory.LiteralExpression( + ArrowExpressionClause( + LiteralExpression( SyntaxKind.NullLiteralExpression)) .WithArrowToken( - SyntaxFactory.Token( + Token( [], SyntaxKind.EqualsGreaterThanToken, - SyntaxFactory.TriviaList( - SyntaxFactory.Space)))) + TriviaList( + Space)))) .WithSemicolonToken( - SyntaxFactory.Token(SyntaxKind.SemicolonToken)) + Token(SyntaxKind.SemicolonToken)) .NormalizeWhitespace(), Generator.IdentifierName("i")), "public static implicit operator string (C x) => null;"); VerifySyntax( Generator.AsPublicInterfaceImplementation( - SyntaxFactory.PropertyDeclaration( - SyntaxFactory.PredefinedType( - SyntaxFactory.Token(SyntaxKind.IntKeyword)), - SyntaxFactory.Identifier("Num")) + PropertyDeclaration( + PredefinedType( + Token(SyntaxKind.IntKeyword)), + Identifier("Num")) .WithExplicitInterfaceSpecifier( - SyntaxFactory.ExplicitInterfaceSpecifier( - SyntaxFactory.IdentifierName("IGeneral"))) + ExplicitInterfaceSpecifier( + IdentifierName("IGeneral"))) .WithExpressionBody( - SyntaxFactory.ArrowExpressionClause( - SyntaxFactory.LiteralExpression( + ArrowExpressionClause( + LiteralExpression( SyntaxKind.NumericLiteralExpression, - SyntaxFactory.Literal(0)))) + Literal(0)))) .WithSemicolonToken( - SyntaxFactory.Token(SyntaxKind.SemicolonToken)) + Token(SyntaxKind.SemicolonToken)) .NormalizeWhitespace(), Generator.IdentifierName("i")), "public int Num => 0;"); VerifySyntax( Generator.AsPublicInterfaceImplementation( - SyntaxFactory.PropertyDeclaration( - SyntaxFactory.PredefinedType( - SyntaxFactory.Token(SyntaxKind.IntKeyword)), - SyntaxFactory.Identifier("Num")) + PropertyDeclaration( + PredefinedType( + Token(SyntaxKind.IntKeyword)), + Identifier("Num")) .WithExplicitInterfaceSpecifier( - SyntaxFactory.ExplicitInterfaceSpecifier( - SyntaxFactory.IdentifierName("IGeneral"))) + ExplicitInterfaceSpecifier( + IdentifierName("IGeneral"))) .WithAccessorList( - SyntaxFactory.AccessorList([ - SyntaxFactory.AccessorDeclaration( + AccessorList([ + AccessorDeclaration( SyntaxKind.GetAccessorDeclaration) .WithExpressionBody( - SyntaxFactory.ArrowExpressionClause( - SyntaxFactory.LiteralExpression( + ArrowExpressionClause( + LiteralExpression( SyntaxKind.NumericLiteralExpression, - SyntaxFactory.Literal(0)))) + Literal(0)))) .WithSemicolonToken( - SyntaxFactory.Token(SyntaxKind.SemicolonToken))])) + Token(SyntaxKind.SemicolonToken))])) .NormalizeWhitespace(), Generator.IdentifierName("i")), "public int Num { get => 0; }"); VerifySyntax( Generator.AsPublicInterfaceImplementation( - SyntaxFactory.IndexerDeclaration( - SyntaxFactory.PredefinedType( - SyntaxFactory.Token(SyntaxKind.IntKeyword))) + IndexerDeclaration( + PredefinedType( + Token(SyntaxKind.IntKeyword))) .WithExplicitInterfaceSpecifier( - SyntaxFactory.ExplicitInterfaceSpecifier( - SyntaxFactory.IdentifierName("IGeneral"))) + ExplicitInterfaceSpecifier( + IdentifierName("IGeneral"))) .WithParameterList( - SyntaxFactory.BracketedParameterList( - [SyntaxFactory.Parameter( - SyntaxFactory.Identifier("index")) + BracketedParameterList( + [Parameter( + Identifier("index")) .WithType( - SyntaxFactory.PredefinedType( - SyntaxFactory.Token(SyntaxKind.IntKeyword)))])) + PredefinedType( + Token(SyntaxKind.IntKeyword)))])) .WithExpressionBody( - SyntaxFactory.ArrowExpressionClause( - SyntaxFactory.LiteralExpression( + ArrowExpressionClause( + LiteralExpression( SyntaxKind.NumericLiteralExpression, - SyntaxFactory.Literal(0)))) + Literal(0)))) .WithSemicolonToken( - SyntaxFactory.Token(SyntaxKind.SemicolonToken)) + Token(SyntaxKind.SemicolonToken)) .NormalizeWhitespace(), Generator.IdentifierName("i")), "public int this[int index] => 0;"); VerifySyntax( Generator.AsPublicInterfaceImplementation( - SyntaxFactory.IndexerDeclaration( - SyntaxFactory.PredefinedType( - SyntaxFactory.Token(SyntaxKind.IntKeyword))) + IndexerDeclaration( + PredefinedType( + Token(SyntaxKind.IntKeyword))) .WithExplicitInterfaceSpecifier( - SyntaxFactory.ExplicitInterfaceSpecifier( - SyntaxFactory.IdentifierName("IGeneral"))) + ExplicitInterfaceSpecifier( + IdentifierName("IGeneral"))) .WithParameterList( - SyntaxFactory.BracketedParameterList( - [SyntaxFactory.Parameter( - SyntaxFactory.Identifier("index")) + BracketedParameterList( + [Parameter( + Identifier("index")) .WithType( - SyntaxFactory.PredefinedType( - SyntaxFactory.Token(SyntaxKind.IntKeyword)))])) + PredefinedType( + Token(SyntaxKind.IntKeyword)))])) .WithAccessorList( - SyntaxFactory.AccessorList( - SyntaxFactory.SingletonList( - SyntaxFactory.AccessorDeclaration( + AccessorList( + SingletonList( + AccessorDeclaration( SyntaxKind.GetAccessorDeclaration) .WithExpressionBody( - SyntaxFactory.ArrowExpressionClause( - SyntaxFactory.LiteralExpression( + ArrowExpressionClause( + LiteralExpression( SyntaxKind.NumericLiteralExpression, - SyntaxFactory.Literal(0)))) + Literal(0)))) .WithSemicolonToken( - SyntaxFactory.Token(SyntaxKind.SemicolonToken))))) + Token(SyntaxKind.SemicolonToken))))) .NormalizeWhitespace(), Generator.IdentifierName("i")), "public int this[int index] { get => 0; }"); VerifySyntax( Generator.AsPublicInterfaceImplementation( - SyntaxFactory.EventDeclaration( - SyntaxFactory.IdentifierName("EventHandler"), - SyntaxFactory.Identifier("Event")) + EventDeclaration( + IdentifierName("EventHandler"), + Identifier("Event")) .WithExplicitInterfaceSpecifier( - SyntaxFactory.ExplicitInterfaceSpecifier( - SyntaxFactory.IdentifierName("IGeneral"))) + ExplicitInterfaceSpecifier( + IdentifierName("IGeneral"))) .WithAccessorList( - SyntaxFactory.AccessorList([ - SyntaxFactory.AccessorDeclaration( + AccessorList([ + AccessorDeclaration( SyntaxKind.AddAccessorDeclaration) .WithExpressionBody( - SyntaxFactory.ArrowExpressionClause( - SyntaxFactory.LiteralExpression( + ArrowExpressionClause( + LiteralExpression( SyntaxKind.NullLiteralExpression))) .WithSemicolonToken( - SyntaxFactory.Token(SyntaxKind.SemicolonToken)), - SyntaxFactory.AccessorDeclaration( + Token(SyntaxKind.SemicolonToken)), + AccessorDeclaration( SyntaxKind.RemoveAccessorDeclaration) .WithExpressionBody( - SyntaxFactory.ArrowExpressionClause( - SyntaxFactory.LiteralExpression( + ArrowExpressionClause( + LiteralExpression( SyntaxKind.NullLiteralExpression))) .WithSemicolonToken( - SyntaxFactory.Token(SyntaxKind.SemicolonToken))])) + Token(SyntaxKind.SemicolonToken))])) .NormalizeWhitespace(), Generator.IdentifierName("i")), "public event EventHandler Event { add => null; remove => null; }"); @@ -1504,7 +1506,7 @@ public interface IFace void Method() where T : class; }"; - var cu = SyntaxFactory.ParseCompilationUnit(code); + var cu = ParseCompilationUnit(code); var iface = cu.Members[0]; var method = Generator.GetMembers(iface)[0]; @@ -1923,19 +1925,19 @@ public void TestAddAttributes() VerifySyntax( Generator.AddAttributes( - SyntaxFactory.BreakStatement(), + BreakStatement(), Generator.Attribute("a")), "[a]\r\nbreak;"); VerifySyntax( Generator.AddAttributes( - SyntaxFactory.TypeParameter("T"), + TypeParameter("T"), Generator.Attribute("a")), "[a]\r\nT"); VerifySyntax( Generator.AddAttributes( - SyntaxFactory.ParenthesizedLambdaExpression(), + ParenthesizedLambdaExpression(), Generator.Attribute("a")), "[a]\r\n() =>"); } @@ -1968,7 +1970,7 @@ private void CheckAddRemoveAttribute(SyntaxNode declaration) [Fact] public void TestAddRemoveAttributesPerservesTrivia() { - var cls = SyntaxFactory.ParseCompilationUnit(@"// comment + var cls = ParseCompilationUnit(@"// comment public class C { } // end").Members[0]; var added = Generator.AddAttributes(cls, Generator.Attribute("a")); @@ -2190,7 +2192,7 @@ public void TestEnumWithUnderlyingTypeFromSymbol() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66381")] public void TestDelegateDeclarationFromSymbol() { - var compilation = _emptyCompilation.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(""" + var compilation = _emptyCompilation.AddSyntaxTrees(ParseSyntaxTree(""" public delegate void D(); """)); @@ -2204,7 +2206,7 @@ public void TestDelegateDeclarationFromSymbol() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65638")] public void TestMethodDeclarationFromSymbol1() { - var compilation = _emptyCompilation.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(""" + var compilation = _emptyCompilation.AddSyntaxTrees(ParseSyntaxTree(""" class C { void M(int i = int.MaxValue) { } @@ -2225,7 +2227,7 @@ private void M(global::System.Int32 i = global::System.Int32.MaxValue) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65835")] public void TestMethodDeclarationFromSymbol2() { - var compilation = _emptyCompilation.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(""" + var compilation = _emptyCompilation.AddSyntaxTrees(ParseSyntaxTree(""" class C { void M(params int[] arr) { } @@ -2246,7 +2248,7 @@ private void M(params global::System.Int32[] arr) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65835")] public void TestMethodDeclarationFromSymbol3() { - var compilation = _emptyCompilation.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(""" + var compilation = _emptyCompilation.AddSyntaxTrees(ParseSyntaxTree(""" static class C { static void M(this int i) { } @@ -2267,7 +2269,7 @@ private static void M(this global::System.Int32 i) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65835")] public void TestMethodDeclarationFromSymbol4() { - var compilation = _emptyCompilation.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(""" + var compilation = _emptyCompilation.AddSyntaxTrees(ParseSyntaxTree(""" static class C { static void M(this ref int i) { } @@ -2288,7 +2290,7 @@ private static void M(this ref global::System.Int32 i) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65638")] public void TestConstructorDeclarationFromSymbol1() { - var compilation = _emptyCompilation.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(""" + var compilation = _emptyCompilation.AddSyntaxTrees(ParseSyntaxTree(""" class C { public C(int i = int.MaxValue) { } @@ -2310,7 +2312,7 @@ public C(global::System.Int32 i = global::System.Int32.MaxValue) [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66379")] public void TestPropertyDeclarationFromSymbol1() { - var compilation = _emptyCompilation.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(""" + var compilation = _emptyCompilation.AddSyntaxTrees(ParseSyntaxTree(""" class C { public int Prop { get; protected set; } @@ -2328,7 +2330,7 @@ class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66379")] public void TestPropertyDeclarationFromSymbol2() { - var compilation = _emptyCompilation.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(""" + var compilation = _emptyCompilation.AddSyntaxTrees(ParseSyntaxTree(""" class C { public int Prop { protected get; set; } @@ -2346,7 +2348,7 @@ class C [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66382")] public void TestOverrideDefaultConstraint1() { - var compilation = _emptyCompilation.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(""" + var compilation = _emptyCompilation.AddSyntaxTrees(ParseSyntaxTree(""" public abstract partial class A { public abstract TResult? Accept(int a); @@ -2374,7 +2376,7 @@ public sealed partial class B : A [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66382")] public void TestOverrideDefaultConstraint2() { - var compilation = _emptyCompilation.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(""" + var compilation = _emptyCompilation.AddSyntaxTrees(ParseSyntaxTree(""" public abstract partial class A { public abstract TResult? Accept(int a) where TResult : class; @@ -2402,7 +2404,7 @@ public sealed partial class B : A [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66382")] public void TestOverrideDefaultConstraint3() { - var compilation = _emptyCompilation.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(""" + var compilation = _emptyCompilation.AddSyntaxTrees(ParseSyntaxTree(""" public abstract partial class A { public abstract TResult? Accept(int a) where TResult : struct; @@ -2429,7 +2431,7 @@ public sealed partial class B : A [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66382")] public void TestOverrideDefaultConstraint4() { - var compilation = _emptyCompilation.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(""" + var compilation = _emptyCompilation.AddSyntaxTrees(ParseSyntaxTree(""" public class X { } @@ -2461,7 +2463,7 @@ public sealed partial class B : A [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66375")] public void TestExplicitInterface1() { - var compilation = _emptyCompilation.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(""" + var compilation = _emptyCompilation.AddSyntaxTrees(ParseSyntaxTree(""" public interface IGoo { void BarMethod(); @@ -2515,7 +2517,7 @@ event System.Action IGoo.E { add { } remove { } } [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66380")] public void TestConstantFieldDeclarations() { - var compilation = _emptyCompilation.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(""" + var compilation = _emptyCompilation.AddSyntaxTrees(ParseSyntaxTree(""" class C { public const int F; @@ -2535,7 +2537,7 @@ public void TestConstantDecimalFieldDeclarationFromMetadata() { var compilation = _emptyCompilation. WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)). - AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(""" + AddSyntaxTrees(ParseSyntaxTree(""" class C { public const decimal F = 8675309000000M; @@ -2566,7 +2568,7 @@ public void TestConstantFieldDeclarationSpecialTypes() [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/66374")] public void TestDestructor1() { - var compilation = _emptyCompilation.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(""" + var compilation = _emptyCompilation.AddSyntaxTrees(ParseSyntaxTree(""" class C { ~C() @@ -2645,7 +2647,7 @@ public class C { }"; - var cu = SyntaxFactory.ParseCompilationUnit(code); + var cu = ParseCompilationUnit(code); var cls = cu.Members[0]; var summary = cls.DescendantNodes(descendIntoTrivia: true).OfType().First(); @@ -2669,7 +2671,7 @@ public class C { }"; - var cu = SyntaxFactory.ParseCompilationUnit(code); + var cu = ParseCompilationUnit(code); var cls = cu.Members[0]; var summary = cls.DescendantNodes(descendIntoTrivia: true).OfType().First(); @@ -2694,7 +2696,7 @@ public class C { }"; - var cu = SyntaxFactory.ParseCompilationUnit(code); + var cu = ParseCompilationUnit(code); var cls = cu.Members[0]; var text = cls.DescendantNodes(descendIntoTrivia: true).OfType().First(); @@ -2717,7 +2719,7 @@ public class C { }"; - var cu = SyntaxFactory.ParseCompilationUnit(code); + var cu = ParseCompilationUnit(code); var cls = cu.Members[0]; var text = cls.DescendantNodes(descendIntoTrivia: true).OfType().First(); @@ -2785,8 +2787,8 @@ interface i public void TestAddExpressionBodyMembersToInterface() { var method = (MethodDeclarationSyntax)Generator.MethodDeclaration("m"); - method = method.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); - method = method.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); + method = method.WithBody(null).WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + method = method.WithExpressionBody(ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); VerifySyntax(Generator.AddMembers(Generator.InterfaceDeclaration("i"), [method]), @@ -2798,12 +2800,12 @@ interface i """); var getAccessor = (AccessorDeclarationSyntax)Generator.GetAccessorDeclaration(); - getAccessor = getAccessor.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); - getAccessor = getAccessor.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); + getAccessor = getAccessor.WithBody(null).WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + getAccessor = getAccessor.WithExpressionBody(ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); var setAccessor = (AccessorDeclarationSyntax)Generator.SetAccessorDeclaration(); - setAccessor = setAccessor.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); - setAccessor = setAccessor.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.InvocationExpression(Generator.IdentifierName("x")))); + setAccessor = setAccessor.WithBody(null).WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + setAccessor = setAccessor.WithExpressionBody(ArrowExpressionClause((ExpressionSyntax)Generator.InvocationExpression(Generator.IdentifierName("x")))); var property = (PropertyDeclarationSyntax) Generator.WithAccessorDeclarations( @@ -2946,7 +2948,7 @@ public void TestGetAccessibility() Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.Attribute("a"))); - Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(SyntaxFactory.TypeParameter("tp"))); + Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(TypeParameter("tp"))); } [Fact] @@ -2970,8 +2972,8 @@ public void TestWithAccessibility() Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.NamespaceImportDeclaration("u"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.Attribute("a"), Accessibility.Private))); - Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(SyntaxFactory.TypeParameter("tp"), Accessibility.Private))); - Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(SyntaxFactory.AccessorDeclaration(SyntaxKind.InitAccessorDeclaration), Accessibility.Private))); + Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(TypeParameter("tp"), Accessibility.Private))); + Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(AccessorDeclaration(SyntaxKind.InitAccessorDeclaration), Accessibility.Private))); } [Fact] @@ -2994,7 +2996,7 @@ public void TestGetModifiers() Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.Attribute("a"))); - Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(SyntaxFactory.TypeParameter("tp"))); + Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(TypeParameter("tp"))); } [Fact] @@ -3017,7 +3019,7 @@ public void TestWithModifiers() Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.NamespaceImportDeclaration("u"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.Attribute("a"), DeclarationModifiers.Abstract))); - Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.TypeParameter("tp"), DeclarationModifiers.Abstract))); + Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(TypeParameter("tp"), DeclarationModifiers.Abstract))); } [Fact] @@ -3055,7 +3057,7 @@ public void TestWithModifiers_AllowedModifiers() Assert.Equal( DeclarationModifiers.Unsafe, - Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.DestructorDeclaration("c"), allModifiers))); + Generator.GetModifiers(Generator.WithModifiers(DestructorDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.Async | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, @@ -3079,7 +3081,7 @@ public void TestWithModifiers_AllowedModifiers() Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Virtual | DeclarationModifiers.ReadOnly, - Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration), allModifiers))); + Generator.GetModifiers(Generator.WithModifiers(AccessorDeclaration(SyntaxKind.GetAccessorDeclaration), allModifiers))); } [Fact] @@ -3113,7 +3115,7 @@ public void TestAddStaticToPublicConstructor() [Fact] public void TestAddAbstractToFileClass() { - var fileClass = (ClassDeclarationSyntax)SyntaxFactory.ParseMemberDeclaration("file class C { }"); + var fileClass = (ClassDeclarationSyntax)ParseMemberDeclaration("file class C { }"); var fileAbstractClass = Generator.WithModifiers(fileClass, Generator.GetModifiers(fileClass).WithIsAbstract(true)); VerifySyntax(fileAbstractClass, @"file abstract class C { @@ -3123,7 +3125,7 @@ public void TestAddAbstractToFileClass() [Fact] public void TestAddPublicToFileClass() { - var fileClass = (ClassDeclarationSyntax)SyntaxFactory.ParseMemberDeclaration("file class C { }"); + var fileClass = (ClassDeclarationSyntax)ParseMemberDeclaration("file class C { }"); var filePublicClass = Generator.WithAccessibility(fileClass, Accessibility.Public); VerifySyntax(filePublicClass, @"public class C { @@ -3133,7 +3135,7 @@ public void TestAddPublicToFileClass() [Fact] public void TestAddFileModifierToAbstractClass() { - var abstractClass = (ClassDeclarationSyntax)SyntaxFactory.ParseMemberDeclaration("abstract class C { }"); + var abstractClass = (ClassDeclarationSyntax)ParseMemberDeclaration("abstract class C { }"); var fileAbstractClass = Generator.WithModifiers(abstractClass, Generator.GetModifiers(abstractClass).WithIsFile(true)); VerifySyntax(fileAbstractClass, @"file abstract class C { @@ -3143,7 +3145,7 @@ public void TestAddFileModifierToAbstractClass() [Fact] public void TestAddFileModifierToPublicClass() { - var publicClass = (ClassDeclarationSyntax)SyntaxFactory.ParseMemberDeclaration("public class C { }"); + var publicClass = (ClassDeclarationSyntax)ParseMemberDeclaration("public class C { }"); var filePublicClass = Generator.WithModifiers(publicClass, Generator.GetModifiers(publicClass).WithIsFile(true)); VerifySyntax(filePublicClass, @"file class C { @@ -3153,7 +3155,7 @@ public void TestAddFileModifierToPublicClass() [Fact] public void TestAddRequiredModifierToVirtualProperty() { - var property = (PropertyDeclarationSyntax)SyntaxFactory.ParseMemberDeclaration("public virtual int P { get; }"); + var property = (PropertyDeclarationSyntax)ParseMemberDeclaration("public virtual int P { get; }"); var updatedProperty = Generator.WithModifiers(property, Generator.GetModifiers(property).WithIsRequired(true)); VerifySyntax(updatedProperty, "public virtual required int P { get; }"); } @@ -3161,7 +3163,7 @@ public void TestAddRequiredModifierToVirtualProperty() [Fact] public void TestAddVirtualModifierToRequiredProperty() { - var property = (PropertyDeclarationSyntax)SyntaxFactory.ParseMemberDeclaration("public required int P { get; }"); + var property = (PropertyDeclarationSyntax)ParseMemberDeclaration("public required int P { get; }"); var updatedProperty = Generator.WithModifiers(property, Generator.GetModifiers(property).WithIsVirtual(true)); VerifySyntax(updatedProperty, "public virtual required int P { get; }"); } @@ -3171,7 +3173,7 @@ public void TestAddVirtualModifierToRequiredProperty() [InlineData("protected internal")] public void TestCompoundAccessibilityModifierKeywordsOrder(string modifier) { - var property = (PropertyDeclarationSyntax)SyntaxFactory.ParseMemberDeclaration($$"""{{modifier}} int P { get; }"""); + var property = (PropertyDeclarationSyntax)ParseMemberDeclaration($$"""{{modifier}} int P { get; }"""); var updatedProperty = Generator.WithModifiers(property, Generator.GetModifiers(property).WithIsRequired(true)); VerifySyntax(updatedProperty, $$"""{{modifier}} required int P { get; }"""); } @@ -3284,15 +3286,15 @@ public void TestGetExpression() // expression bodied methods var method = (MethodDeclarationSyntax)Generator.MethodDeclaration("p"); - method = method.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); - method = method.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); + method = method.WithBody(null).WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + method = method.WithExpressionBody(ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("x", Generator.GetExpression(method).ToString()); // expression bodied local functions - var local = SyntaxFactory.LocalFunctionStatement(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "p"); - local = local.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); - local = local.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); + var local = LocalFunctionStatement(PredefinedType(Token(SyntaxKind.VoidKeyword)), "p"); + local = local.WithBody(null).WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + local = local.WithExpressionBody(ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("x", Generator.GetExpression(local).ToString()); } @@ -3320,15 +3322,15 @@ public void TestWithExpression() // expression bodied methods var method = (MethodDeclarationSyntax)Generator.MethodDeclaration("p"); - method = method.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); - method = method.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); + method = method.WithBody(null).WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + method = method.WithExpressionBody(ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(method, Generator.IdentifierName("y"))).ToString()); // expression bodied local functions - var local = SyntaxFactory.LocalFunctionStatement(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "p"); - local = local.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); - local = local.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); + var local = LocalFunctionStatement(PredefinedType(Token(SyntaxKind.VoidKeyword)), "p"); + local = local.WithBody(null).WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); + local = local.WithExpressionBody(ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(local, Generator.IdentifierName("y"))).ToString()); } @@ -3428,7 +3430,7 @@ public void TestAccessorDeclarations2() [Fact] public void TestAccessorsOnSpecialProperties() { - var root = SyntaxFactory.ParseCompilationUnit( + var root = ParseCompilationUnit( @"class C { public int X { get; set; } = 100; @@ -3449,7 +3451,7 @@ public void TestAccessorsOnSpecialProperties() [Fact] public void TestAccessorsOnSpecialIndexers() { - var root = SyntaxFactory.ParseCompilationUnit( + var root = ParseCompilationUnit( @"class C { public int this[int p] { get { return p * 10; } set { } }; @@ -3471,7 +3473,7 @@ public void TestAccessorsOnSpecialIndexers() public void TestExpressionsOnSpecialProperties() { // you can get/set expression from both expression value property and initialized properties - var root = SyntaxFactory.ParseCompilationUnit( + var root = ParseCompilationUnit( @"class C { public int X { get; set; } = 100; @@ -3497,7 +3499,7 @@ public void TestExpressionsOnSpecialProperties() public void TestExpressionsOnSpecialIndexers() { // you can get/set expression from both expression value property and initialized properties - var root = SyntaxFactory.ParseCompilationUnit( + var root = ParseCompilationUnit( @"class C { public int this[int p] { get { return p * 10; } set { } }; @@ -3622,7 +3624,7 @@ public void TestWithAccessorStatements() [Fact] public void TestGetBaseAndInterfaceTypes() { - var classBI = SyntaxFactory.ParseCompilationUnit( + var classBI = ParseCompilationUnit( @"class C : B, I { }").Members[0]; @@ -3633,7 +3635,7 @@ public void TestGetBaseAndInterfaceTypes() Assert.Equal("B", baseListBI[0].ToString()); Assert.Equal("I", baseListBI[1].ToString()); - var classB = SyntaxFactory.ParseCompilationUnit( + var classB = ParseCompilationUnit( @"class C : B { }").Members[0]; @@ -3643,7 +3645,7 @@ public void TestGetBaseAndInterfaceTypes() Assert.Equal(1, baseListB.Count); Assert.Equal("B", baseListB[0].ToString()); - var classN = SyntaxFactory.ParseCompilationUnit( + var classN = ParseCompilationUnit( @"class C { }").Members[0]; @@ -3656,7 +3658,7 @@ public void TestGetBaseAndInterfaceTypes() [Fact] public void TestRemoveBaseAndInterfaceTypes() { - var classBI = SyntaxFactory.ParseCompilationUnit( + var classBI = ParseCompilationUnit( @"class C : B, I { }").Members[0]; @@ -3686,17 +3688,17 @@ public void TestRemoveBaseAndInterfaceTypes() [Fact] public void TestAddBaseType() { - var classC = SyntaxFactory.ParseCompilationUnit( + var classC = ParseCompilationUnit( @"class C { }").Members[0]; - var classCI = SyntaxFactory.ParseCompilationUnit( + var classCI = ParseCompilationUnit( @"class C : I { }").Members[0]; - var classCB = SyntaxFactory.ParseCompilationUnit( + var classCB = ParseCompilationUnit( @"class C : B { }").Members[0]; @@ -3724,17 +3726,17 @@ public void TestAddBaseType() [Fact] public void TestAddInterfaceTypes() { - var classC = SyntaxFactory.ParseCompilationUnit( + var classC = ParseCompilationUnit( @"class C { }").Members[0]; - var classCI = SyntaxFactory.ParseCompilationUnit( + var classCI = ParseCompilationUnit( @"class C : I { }").Members[0]; - var classCB = SyntaxFactory.ParseCompilationUnit( + var classCB = ParseCompilationUnit( @"class C : B { }").Members[0]; @@ -3925,7 +3927,7 @@ public void TestMultiFieldDeclarations() public static int Q, Y, Z; }"); VerifySyntax( - Generator.ReplaceNode(declC, declX.GetAncestorOrThis(), SyntaxFactory.VariableDeclarator("Q")), + Generator.ReplaceNode(declC, declX.GetAncestorOrThis(), VariableDeclarator("Q")), @"public class C { public static int Q, Y, Z; @@ -3985,7 +3987,7 @@ public void TestInsertMembersOnRecordStruct_SemiColon() "; var comp = CSharpCompilation.Create("test") .AddReferences(TestMetadata.Net451.mscorlib) - .AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(src, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview))); + .AddSyntaxTrees(ParseSyntaxTree(src, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview))); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); @@ -4565,7 +4567,7 @@ public class C : IDisposable } "; - var root = SyntaxFactory.ParseCompilationUnit(text); + var root = ParseCompilationUnit(text); var decl = root.DescendantNodes().OfType().First(); var newDecl = Generator.AddInterfaceType(decl, Generator.IdentifierName("IDisposable")); var newRoot = root.ReplaceNode(decl, newDecl); diff --git a/src/Workspaces/CSharpTest/Formatting/FormattingElasticTriviaTests.cs b/src/Workspaces/CSharpTest/Formatting/FormattingElasticTriviaTests.cs index 05071d233c0b9..e0a9edc341ea6 100644 --- a/src/Workspaces/CSharpTest/Formatting/FormattingElasticTriviaTests.cs +++ b/src/Workspaces/CSharpTest/Formatting/FormattingElasticTriviaTests.cs @@ -16,6 +16,8 @@ namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Formatting { + using static SyntaxFactory; + [Trait(Traits.Feature, Traits.Features.Formatting)] public class FormattingEngineElasticTriviaTests : CSharpFormattingTestBase { @@ -40,40 +42,40 @@ class A class B { }"; - var compilation = SyntaxFactory.CompilationUnit( - externs: [SyntaxFactory.ExternAliasDirective("A1")], + var compilation = CompilationUnit( + externs: [ExternAliasDirective("A1")], usings: default, - attributeLists: [SyntaxFactory.AttributeList( - SyntaxFactory.Token( - [SyntaxFactory.Trivia( - SyntaxFactory.LineDirectiveTrivia( - SyntaxFactory.Literal("99", 99), false))], + attributeLists: [AttributeList( + Token( + [Trivia( + LineDirectiveTrivia( + Literal("99", 99), false))], SyntaxKind.OpenBracketToken, - SyntaxFactory.TriviaList()), - SyntaxFactory.AttributeTargetSpecifier( - SyntaxFactory.Identifier("assembly")), - [SyntaxFactory.Attribute( - SyntaxFactory.ParseName("My"))], - SyntaxFactory.Token( + TriviaList()), + AttributeTargetSpecifier( + Identifier("assembly")), + [Attribute( + ParseName("My"))], + Token( SyntaxKind.CloseBracketToken))], members: [ - SyntaxFactory.ClassDeclaration( + ClassDeclaration( default, modifiers: [], - SyntaxFactory.Identifier("My"), + Identifier("My"), null, - SyntaxFactory.BaseList([SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName("System.Attribute"))]), + BaseList([SimpleBaseType(ParseTypeName("System.Attribute"))]), default, default), - SyntaxFactory.ClassDeclaration("A"), - SyntaxFactory.ClassDeclaration( + ClassDeclaration("A"), + ClassDeclaration( attributeLists: [ - SyntaxFactory.AttributeList([ - SyntaxFactory.Attribute( - SyntaxFactory.ParseName("My"))])], + AttributeList([ + Attribute( + ParseName("My"))])], modifiers: [], - identifier: SyntaxFactory.Identifier("B"), + identifier: Identifier("B"), typeParameterList: null, baseList: null, constraintClauses: default, @@ -104,7 +106,7 @@ public class SomeAttribute : System.Attribute { } var workspace = new AdhocWorkspace(); var generator = SyntaxGenerator.GetGenerator(workspace, LanguageNames.CSharp); - var root = SyntaxFactory.ParseCompilationUnit(text); + var root = ParseCompilationUnit(text); var decl = generator.GetDeclaration(root.DescendantNodes().OfType().First(vd => vd.Identifier.Text == "f2")); var newDecl = generator.AddAttributes(decl, generator.Attribute("Some")).WithAdditionalAnnotations(Formatter.Annotation); var newRoot = root.ReplaceNode(decl, newDecl); @@ -142,34 +144,34 @@ public void FormatElasticTriviaBetweenPropertiesWithoutAccessors() string MyProperty => ""42""; }"; - var property = SyntaxFactory.PropertyDeclaration( + var property = PropertyDeclaration( attributeLists: default, modifiers: [], - type: SyntaxFactory.PredefinedType( - SyntaxFactory.Token( + type: PredefinedType( + Token( SyntaxKind.StringKeyword)), explicitInterfaceSpecifier: null, - identifier: SyntaxFactory.Identifier("MyProperty"), + identifier: Identifier("MyProperty"), accessorList: null, expressionBody: - SyntaxFactory.ArrowExpressionClause( - SyntaxFactory.LiteralExpression( + ArrowExpressionClause( + LiteralExpression( SyntaxKind.StringLiteralExpression, - SyntaxFactory.Literal("42"))), + Literal("42"))), initializer: null, - semicolonToken: SyntaxFactory.Token(SyntaxKind.SemicolonToken)); + semicolonToken: Token(SyntaxKind.SemicolonToken)); - var compilation = SyntaxFactory.CompilationUnit( + var compilation = CompilationUnit( externs: default, usings: default, attributeLists: default, - members: SyntaxFactory.List( + members: List( new MemberDeclarationSyntax[] { - SyntaxFactory.ClassDeclaration( + ClassDeclaration( attributeLists: default, modifiers: [], - identifier: SyntaxFactory.Identifier("PropertyTest"), + identifier: Identifier("PropertyTest"), typeParameterList: null, baseList: null, constraintClauses: default, diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/AttributeGenerator.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/AttributeGenerator.cs index c99bd4fada087..24d4b62d7382f 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/AttributeGenerator.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/AttributeGenerator.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; -using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; @@ -15,6 +14,8 @@ namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration; +using static SyntaxFactory; + internal static class AttributeGenerator { public static SyntaxList GenerateAttributeLists( @@ -30,8 +31,8 @@ public static SyntaxList GenerateAttributeLists( .WhereNotNull().ToList(); return attributeNodes.Count == 0 ? default - : [SyntaxFactory.AttributeList( - target.HasValue ? SyntaxFactory.AttributeTargetSpecifier(target.Value) : null, + : [AttributeList( + target.HasValue ? AttributeTargetSpecifier(target.Value) : null, [.. attributeNodes])]; } else @@ -50,9 +51,9 @@ public static SyntaxList GenerateAttributeLists( var attributeSyntax = TryGenerateAttribute(attribute, info); return attributeSyntax == null ? null - : SyntaxFactory.AttributeList( + : AttributeList( target.HasValue - ? SyntaxFactory.AttributeTargetSpecifier(target.Value) + ? AttributeTargetSpecifier(target.Value) : null, [attributeSyntax]); } @@ -76,7 +77,7 @@ public static SyntaxList GenerateAttributeLists( var attributeArguments = GenerateAttributeArgumentList(info.Generator, attribute); return attribute.AttributeClass.GenerateTypeSyntax() is NameSyntax nameSyntax - ? SyntaxFactory.Attribute(nameSyntax, attributeArguments) + ? Attribute(nameSyntax, attributeArguments) : null; } @@ -87,13 +88,13 @@ public static SyntaxList GenerateAttributeLists( var arguments = new List(); arguments.AddRange(attribute.ConstructorArguments.Select(c => - SyntaxFactory.AttributeArgument(ExpressionGenerator.GenerateExpression(generator, c)))); + AttributeArgument(ExpressionGenerator.GenerateExpression(generator, c)))); arguments.AddRange(attribute.NamedArguments.Select(kvp => - SyntaxFactory.AttributeArgument( - SyntaxFactory.NameEquals(SyntaxFactory.IdentifierName(kvp.Key)), null, + AttributeArgument( + NameEquals(IdentifierName(kvp.Key)), null, ExpressionGenerator.GenerateExpression(generator, kvp.Value)))); - return SyntaxFactory.AttributeArgumentList([.. arguments]); + return AttributeArgumentList([.. arguments]); } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/CSharpCodeGenerationHelpers.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/CSharpCodeGenerationHelpers.cs index 37c86cd6a8d2d..00215dd9964dd 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/CSharpCodeGenerationHelpers.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/CSharpCodeGenerationHelpers.cs @@ -19,6 +19,8 @@ namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration; +using static SyntaxFactory; + internal static class CSharpCodeGenerationHelpers { public static TDeclarationSyntax ConditionallyAddFormattingAnnotationTo( @@ -44,24 +46,24 @@ internal static void AddAccessibilityModifiers( switch (accessibility) { case Accessibility.Public: - tokens.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)); + tokens.Add(Token(SyntaxKind.PublicKeyword)); break; case Accessibility.Protected: - tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); + tokens.Add(Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.Private: - tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); + tokens.Add(Token(SyntaxKind.PrivateKeyword)); break; case Accessibility.ProtectedAndInternal: - tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); - tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); + tokens.Add(Token(SyntaxKind.PrivateKeyword)); + tokens.Add(Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.Internal: - tokens.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); + tokens.Add(Token(SyntaxKind.InternalKeyword)); break; case Accessibility.ProtectedOrInternal: - tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); - tokens.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); + tokens.Add(Token(SyntaxKind.ProtectedKeyword)); + tokens.Add(Token(SyntaxKind.InternalKeyword)); break; } } @@ -94,7 +96,7 @@ private static TypeDeclarationSyntax ReplaceUnterminatedConstructs(TypeDeclarati var text = t1.ToString(); if (!text.EndsWith(MultiLineCommentTerminator, StringComparison.Ordinal)) { - return SyntaxFactory.SyntaxTrivia(SyntaxKind.MultiLineCommentTrivia, text + MultiLineCommentTerminator); + return SyntaxTrivia(SyntaxKind.MultiLineCommentTrivia, text + MultiLineCommentTerminator); } } else if (t1.Kind() == SyntaxKind.SkippedTokensTrivia) @@ -115,10 +117,10 @@ private static SyntaxTrivia ReplaceUnterminatedConstructs(SyntaxTrivia skippedTo var tokens = syntax.Tokens; - var updatedTokens = SyntaxFactory.TokenList(tokens.Select(ReplaceUnterminatedConstruct)); + var updatedTokens = TokenList(tokens.Select(ReplaceUnterminatedConstruct)); var updatedSyntax = syntax.WithTokens(updatedTokens); - return SyntaxFactory.Trivia(updatedSyntax); + return Trivia(updatedSyntax); } private static SyntaxToken ReplaceUnterminatedConstruct(SyntaxToken token) @@ -129,7 +131,7 @@ private static SyntaxToken ReplaceUnterminatedConstruct(SyntaxToken token) if (tokenText.Length <= 2 || tokenText.Last() != '"') { tokenText += '"'; - return SyntaxFactory.Literal(token.LeadingTrivia, tokenText, token.ValueText, token.TrailingTrivia); + return Literal(token.LeadingTrivia, tokenText, token.ValueText, token.TrailingTrivia); } } else if (token.IsRegularStringLiteral()) @@ -138,7 +140,7 @@ private static SyntaxToken ReplaceUnterminatedConstruct(SyntaxToken token) if (tokenText.Length <= 1 || tokenText.Last() != '"') { tokenText += '"'; - return SyntaxFactory.Literal(token.LeadingTrivia, tokenText, token.ValueText, token.TrailingTrivia); + return Literal(token.LeadingTrivia, tokenText, token.ValueText, token.TrailingTrivia); } } @@ -182,7 +184,7 @@ public static SyntaxList Insert( if (index != 0 && declarationList[index - 1].ContainsDiagnostics && AreBracesMissing(declarationList[index - 1])) { - return declarationList.Insert(index, declaration.WithLeadingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed)); + return declarationList.Insert(index, declaration.WithLeadingTrivia(ElasticCarriageReturnLineFeed)); } return declarationList.Insert(index, declaration); @@ -217,7 +219,7 @@ private static bool AreBracesMissing(TDeclaration declaration) whe return null; } - return SyntaxFactory.ExplicitInterfaceSpecifier(name); + return ExplicitInterfaceSpecifier(name); } public static CodeGenerationDestination GetDestination(SyntaxNode destination) @@ -253,8 +255,8 @@ public static TSyntaxNode ConditionallyAddDocumentationCommentTo( } var result = TryGetDocumentationComment(symbol, "///", out var comment, cancellationToken) - ? node.WithPrependedLeadingTrivia(SyntaxFactory.ParseLeadingTrivia(comment)) - .WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker) + ? node.WithPrependedLeadingTrivia(ParseLeadingTrivia(comment)) + .WithPrependedLeadingTrivia(ElasticMarker) : node; return result; } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/CSharpCodeGenerationService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/CSharpCodeGenerationService.cs index d3d2c3bfef690..f3d8d4242bb47 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/CSharpCodeGenerationService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/CSharpCodeGenerationService.cs @@ -15,7 +15,6 @@ using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host; -using Microsoft.CodeAnalysis.LanguageService; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; @@ -23,6 +22,8 @@ namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration; +using static SyntaxFactory; + internal partial class CSharpCodeGenerationService : AbstractCodeGenerationService { public CSharpCodeGenerationService(LanguageServices languageServices) @@ -461,7 +462,7 @@ private static SyntaxList RemoveAttributeFromAttributeLists { // Remove just the given attribute from the attribute list. ComputePositionAndTriviaForRemoveAttributeFromAttributeList(attributeToRemove, (SyntaxToken t) => t.IsKind(SyntaxKind.CommaToken), out positionOfRemovedNode, out trivia); - var newAttributes = SyntaxFactory.SeparatedList(attributes.Where(a => a != attributeToRemove)); + var newAttributes = SeparatedList(attributes.Where(a => a != attributeToRemove)); var newAttributeList = attributeList.WithAttributes(newAttributes); newAttributeLists = attributeLists.Select(attrList => attrList == attributeList ? newAttributeList : attrList); } @@ -509,7 +510,7 @@ public override TDeclarationNode AddStatements( // Insert the new global statement(s) at the end of any current global statements. // This code relies on 'LastIndexOf' returning -1 when no matching element is found. var insertionIndex = compilationUnit.Members.LastIndexOf(memberDeclaration => memberDeclaration.IsKind(SyntaxKind.GlobalStatement)) + 1; - var wrappedStatements = StatementGenerator.GenerateStatements(statements).Select(SyntaxFactory.GlobalStatement).ToArray(); + var wrappedStatements = StatementGenerator.GenerateStatements(statements).Select(GlobalStatement).ToArray(); return Cast(compilationUnit.WithMembers(compilationUnit.Members.InsertRange(insertionIndex, wrappedStatements))); } else if (destinationMember is StatementSyntax statement && statement.IsParentKind(SyntaxKind.GlobalStatement)) @@ -517,7 +518,7 @@ public override TDeclarationNode AddStatements( // We are adding a statement to a global statement in script, where the CompilationUnitSyntax is not a // statement container. If the global statement is not already a block, create a block which can hold // both the original statement and any new statements we are adding to it. - var block = statement as BlockSyntax ?? SyntaxFactory.Block(statement); + var block = statement as BlockSyntax ?? Block(statement); return Cast(block.AddStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else @@ -613,10 +614,10 @@ private static TDeclarationNode AddStatementsToAnonymousFunctions members) @@ -52,14 +53,14 @@ internal static ConstructorDeclarationSyntax GenerateConstructorDeclaration( var hasNoBody = !info.Context.GenerateMethodBodies; - var declaration = SyntaxFactory.ConstructorDeclaration( + var declaration = ConstructorDeclaration( attributeLists: AttributeGenerator.GenerateAttributeLists(constructor.GetAttributes(), info), modifiers: GenerateModifiers(constructor, info), identifier: CodeGenerationConstructorInfo.GetTypeName(constructor).ToIdentifierToken(), parameterList: ParameterGenerator.GenerateParameterList(constructor.Parameters, isExplicit: false, info: info), initializer: GenerateConstructorInitializer(constructor), body: hasNoBody ? null : GenerateBlock(constructor), - semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default); + semicolonToken: hasNoBody ? Token(SyntaxKind.SemicolonToken) : default); declaration = UseExpressionBodyIfDesired(info, declaration, cancellationToken); @@ -97,11 +98,11 @@ private static ConstructorDeclarationSyntax UseExpressionBodyIfDesired( return arguments == null ? null - : SyntaxFactory.ConstructorInitializer(kind).WithArgumentList(GenerateArgumentList(arguments)); + : ConstructorInitializer(kind).WithArgumentList(GenerateArgumentList(arguments)); } private static ArgumentListSyntax GenerateArgumentList(ImmutableArray arguments) - => SyntaxFactory.ArgumentList([.. arguments.Select(ArgumentGenerator.GenerateArgument)]); + => ArgumentList([.. arguments.Select(ArgumentGenerator.GenerateArgument)]); private static BlockSyntax GenerateBlock( IMethodSymbol constructor) @@ -110,7 +111,7 @@ private static BlockSyntax GenerateBlock( ? default : StatementGenerator.GenerateStatements(CodeGenerationConstructorInfo.GetStatements(constructor)); - return SyntaxFactory.Block(statements); + return Block(statements); } private static SyntaxTokenList GenerateModifiers(IMethodSymbol constructor, CSharpCodeGenerationContextInfo info) @@ -119,7 +120,7 @@ private static SyntaxTokenList GenerateModifiers(IMethodSymbol constructor, CSha if (constructor.IsStatic) { - tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); + tokens.Add(Token(SyntaxKind.StaticKeyword)); } else { @@ -128,7 +129,7 @@ private static SyntaxTokenList GenerateModifiers(IMethodSymbol constructor, CSha if (CodeGenerationConstructorInfo.GetIsUnsafe(constructor)) { - tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); + tokens.Add(Token(SyntaxKind.UnsafeKeyword)); } return tokens.ToSyntaxTokenListAndFree(); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/ConversionGenerator.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/ConversionGenerator.cs index 388277d92dcef..8a26db95c4eda 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/ConversionGenerator.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/ConversionGenerator.cs @@ -13,6 +13,8 @@ namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration; +using static SyntaxFactory; + internal static class ConversionGenerator { internal static TypeDeclarationSyntax AddConversionTo( @@ -54,25 +56,25 @@ private static ConversionOperatorDeclarationSyntax GenerateConversionDeclaration } var keyword = method.MetadataName == WellKnownMemberNames.ImplicitConversionName - ? SyntaxFactory.Token(SyntaxKind.ImplicitKeyword) - : SyntaxFactory.Token(SyntaxKind.ExplicitKeyword); + ? Token(SyntaxKind.ImplicitKeyword) + : Token(SyntaxKind.ExplicitKeyword); var checkedToken = SyntaxFacts.IsCheckedOperator(method.MetadataName) - ? SyntaxFactory.Token(SyntaxKind.CheckedKeyword) + ? Token(SyntaxKind.CheckedKeyword) : default; - var declaration = SyntaxFactory.ConversionOperatorDeclaration( + var declaration = ConversionOperatorDeclaration( attributeLists: AttributeGenerator.GenerateAttributeLists(method.GetAttributes(), info), modifiers: GenerateModifiers(destination), implicitOrExplicitKeyword: keyword, explicitInterfaceSpecifier: null, - operatorKeyword: SyntaxFactory.Token(SyntaxKind.OperatorKeyword), + operatorKeyword: Token(SyntaxKind.OperatorKeyword), checkedKeyword: checkedToken, type: method.ReturnType.GenerateTypeSyntax(), parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, isExplicit: false, info: info), body: hasNoBody ? null : StatementGenerator.GenerateBlock(method), expressionBody: null, - semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : new SyntaxToken()); + semicolonToken: hasNoBody ? Token(SyntaxKind.SemicolonToken) : new SyntaxToken()); declaration = UseExpressionBodyIfDesired(info, declaration, cancellationToken); @@ -103,12 +105,12 @@ private static SyntaxTokenList GenerateModifiers(CodeGenerationDestination desti if (destination is CodeGenerationDestination.InterfaceType) { return [ - SyntaxFactory.Token(SyntaxKind.StaticKeyword), - SyntaxFactory.Token(SyntaxKind.AbstractKeyword)]; + Token(SyntaxKind.StaticKeyword), + Token(SyntaxKind.AbstractKeyword)]; } return [ - SyntaxFactory.Token(SyntaxKind.PublicKeyword), - SyntaxFactory.Token(SyntaxKind.StaticKeyword)]; + Token(SyntaxKind.PublicKeyword), + Token(SyntaxKind.StaticKeyword)]; } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/DestructorGenerator.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/DestructorGenerator.cs index 159f03ea4248d..d020f2bb63e1f 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/DestructorGenerator.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/DestructorGenerator.cs @@ -13,6 +13,8 @@ namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration; +using static SyntaxFactory; + internal static class DestructorGenerator { private static MemberDeclarationSyntax? LastConstructorOrField(SyntaxList members) @@ -46,14 +48,14 @@ internal static DestructorDeclarationSyntax GenerateDestructorDeclaration( var hasNoBody = !info.Context.GenerateMethodBodies; - var declaration = SyntaxFactory.DestructorDeclaration( + var declaration = DestructorDeclaration( attributeLists: AttributeGenerator.GenerateAttributeLists(destructor.GetAttributes(), info), modifiers: default, - tildeToken: SyntaxFactory.Token(SyntaxKind.TildeToken), + tildeToken: Token(SyntaxKind.TildeToken), identifier: CodeGenerationDestructorInfo.GetTypeName(destructor).ToIdentifierToken(), - parameterList: SyntaxFactory.ParameterList(), + parameterList: ParameterList(), body: hasNoBody ? null : GenerateBlock(destructor), - semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default); + semicolonToken: hasNoBody ? Token(SyntaxKind.SemicolonToken) : default); return AddFormatterAndCodeGeneratorAnnotationsTo( ConditionallyAddDocumentationCommentTo(declaration, destructor, info, cancellationToken)); @@ -66,6 +68,6 @@ private static BlockSyntax GenerateBlock( ? default : StatementGenerator.GenerateStatements(CodeGenerationDestructorInfo.GetStatements(constructor)); - return SyntaxFactory.Block(statements); + return Block(statements); } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/EnumMemberGenerator.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/EnumMemberGenerator.cs index aa9928a932d1a..59e97d94131cf 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/EnumMemberGenerator.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/EnumMemberGenerator.cs @@ -12,11 +12,12 @@ using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Utilities; -using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; -using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; - namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration; +using static CodeGenerationHelpers; +using static CSharpCodeGenerationHelpers; +using static SyntaxFactory; + internal static class EnumMemberGenerator { internal static EnumDeclarationSyntax AddEnumMemberTo(EnumDeclarationSyntax destination, IFieldSymbol enumMember, CSharpCodeGenerationContextInfo info, CancellationToken cancellationToken) @@ -33,19 +34,19 @@ internal static EnumDeclarationSyntax AddEnumMemberTo(EnumDeclarationSyntax dest else if (members.LastOrDefault().Kind() == SyntaxKind.CommaToken) { members.Add(member); - members.Add(SyntaxFactory.Token(SyntaxKind.CommaToken)); + members.Add(Token(SyntaxKind.CommaToken)); } else { var lastMember = members.Last(); var trailingTrivia = lastMember.GetTrailingTrivia(); members[members.Count - 1] = lastMember.WithTrailingTrivia(); - members.Add(SyntaxFactory.Token(SyntaxKind.CommaToken).WithTrailingTrivia(trailingTrivia)); + members.Add(Token(SyntaxKind.CommaToken).WithTrailingTrivia(trailingTrivia)); members.Add(member); } return destination.EnsureOpenAndCloseBraceTokens() - .WithMembers(SyntaxFactory.SeparatedList(members)); + .WithMembers(SeparatedList(members)); } public static EnumMemberDeclarationSyntax GenerateEnumMemberDeclaration( @@ -61,8 +62,8 @@ public static EnumMemberDeclarationSyntax GenerateEnumMemberDeclaration( } var value = CreateEnumMemberValue(info.Generator, destination, enumMember); - var member = SyntaxFactory.EnumMemberDeclaration(enumMember.Name.ToIdentifierToken()) - .WithEqualsValue(value == null ? null : SyntaxFactory.EqualsValueClause(value: value)); + var member = EnumMemberDeclaration(enumMember.Name.ToIdentifierToken()) + .WithEqualsValue(value == null ? null : EqualsValueClause(value: value)); return AddFormatterAndCodeGeneratorAnnotationsTo( ConditionallyAddDocumentationCommentTo(member, enumMember, info, cancellationToken)); @@ -127,10 +128,10 @@ not long and var shiftValue = IntegerUtilities.LogBase2(value); // Re-use the numericLiteral text so type suffixes match too - return SyntaxFactory.BinaryExpression( + return BinaryExpression( SyntaxKind.LeftShiftExpression, - SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(numericLiteral.Token.Text, 1)), - SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(shiftValue.ToString(), shiftValue))); + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(numericLiteral.Token.Text, 1)), + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(shiftValue.ToString(), shiftValue))); } } } @@ -142,13 +143,13 @@ not long and if (numericText.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) { // Hex - return SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, - SyntaxFactory.Literal(numericText[..2] + value.ToString("X"), value)); + return LiteralExpression(SyntaxKind.NumericLiteralExpression, + Literal(numericText[..2] + value.ToString("X"), value)); } else if (numericText.StartsWith("0b", StringComparison.OrdinalIgnoreCase)) { - return SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, - SyntaxFactory.Literal(numericText[..2] + Convert.ToString(value, 2), value)); + return LiteralExpression(SyntaxKind.NumericLiteralExpression, + Literal(numericText[..2] + Convert.ToString(value, 2), value)); } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/EventGenerator.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/EventGenerator.cs index 1e5e90bd3c974..e63e6ef486e2c 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/EventGenerator.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/EventGenerator.cs @@ -12,11 +12,12 @@ using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; -using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; -using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; - namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration; +using static CodeGenerationHelpers; +using static CSharpCodeGenerationHelpers; +using static SyntaxFactory; + internal static class EventGenerator { private static MemberDeclarationSyntax? AfterMember( @@ -113,12 +114,12 @@ private static MemberDeclarationSyntax GenerateEventFieldDeclaration( { return AddFormatterAndCodeGeneratorAnnotationsTo( AddAnnotationsTo(@event, - SyntaxFactory.EventFieldDeclaration( + EventFieldDeclaration( AttributeGenerator.GenerateAttributeLists(@event.GetAttributes(), info), GenerateModifiers(@event, destination, info), - SyntaxFactory.VariableDeclaration( + VariableDeclaration( @event.Type.GenerateTypeSyntax(), - [SyntaxFactory.VariableDeclarator(@event.Name.ToIdentifierToken())])))); + [VariableDeclarator(@event.Name.ToIdentifierToken())])))); } private static MemberDeclarationSyntax GenerateEventDeclarationWorker( @@ -126,7 +127,7 @@ private static MemberDeclarationSyntax GenerateEventDeclarationWorker( { var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(@event.ExplicitInterfaceImplementations); - return AddFormatterAndCodeGeneratorAnnotationsTo(SyntaxFactory.EventDeclaration( + return AddFormatterAndCodeGeneratorAnnotationsTo(EventDeclaration( attributeLists: AttributeGenerator.GenerateAttributeLists(@event.GetAttributes(), info), modifiers: GenerateModifiers(@event, destination, info), type: @event.Type.GenerateTypeSyntax(), @@ -144,7 +145,7 @@ private static AccessorListSyntax GenerateAccessorList( GenerateAccessorDeclaration(@event, @event.RemoveMethod, SyntaxKind.RemoveAccessorDeclaration, destination, info), }; - return SyntaxFactory.AccessorList([.. accessors.WhereNotNull()]); + return AccessorList([.. accessors.WhereNotNull()]); } private static AccessorDeclarationSyntax? GenerateAccessorDeclaration( @@ -165,14 +166,14 @@ private static AccessorDeclarationSyntax GenerateAccessorDeclaration( SyntaxKind kind, bool hasBody) { - return AddAnnotationsTo(accessor, SyntaxFactory.AccessorDeclaration(kind) + return AddAnnotationsTo(accessor, AccessorDeclaration(kind) .WithBody(hasBody ? GenerateBlock(accessor) : null) - .WithSemicolonToken(hasBody ? default : SyntaxFactory.Token(SyntaxKind.SemicolonToken))); + .WithSemicolonToken(hasBody ? default : Token(SyntaxKind.SemicolonToken))); } private static BlockSyntax GenerateBlock(IMethodSymbol accessor) { - return SyntaxFactory.Block( + return Block( StatementGenerator.GenerateStatements(CodeGenerationMethodInfo.GetStatements(accessor))); } @@ -196,7 +197,7 @@ private static SyntaxTokenList GenerateModifiers( if (@event.ExplicitInterfaceImplementations.Any()) { if (@event.IsStatic) - tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); + tokens.Add(Token(SyntaxKind.StaticKeyword)); } else { @@ -205,11 +206,11 @@ private static SyntaxTokenList GenerateModifiers( { if (@event.IsStatic) { - tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); + tokens.Add(Token(SyntaxKind.StaticKeyword)); // We only generate the abstract keyword in interfaces for static abstract members if (@event.IsAbstract) - tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); + tokens.Add(Token(SyntaxKind.AbstractKeyword)); } } else @@ -217,7 +218,7 @@ private static SyntaxTokenList GenerateModifiers( CSharpCodeGenerationHelpers.AddAccessibilityModifiers(@event.DeclaredAccessibility, tokens, info, Accessibility.Private); if (@event.IsStatic) - tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); + tokens.Add(Token(SyntaxKind.StaticKeyword)); // An event is readonly if its accessors are readonly. // If one accessor is readonly and the other one is not, @@ -225,18 +226,18 @@ private static SyntaxTokenList GenerateModifiers( // See https://github.com/dotnet/roslyn/issues/34213 // Don't show the readonly modifier if the containing type is already readonly if (@event.AddMethod?.IsReadOnly == true && !@event.ContainingType.IsReadOnly) - tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); + tokens.Add(Token(SyntaxKind.ReadOnlyKeyword)); if (@event.IsAbstract) - tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); + tokens.Add(Token(SyntaxKind.AbstractKeyword)); if (@event.IsOverride) - tokens.Add(SyntaxFactory.Token(SyntaxKind.OverrideKeyword)); + tokens.Add(Token(SyntaxKind.OverrideKeyword)); } } if (CodeGenerationEventInfo.GetIsUnsafe(@event)) - tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); + tokens.Add(Token(SyntaxKind.UnsafeKeyword)); return tokens.ToSyntaxTokenListAndFree(); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/ExpressionGenerator.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/ExpressionGenerator.cs index 1105c4fbf6067..2362363916b81 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/ExpressionGenerator.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/ExpressionGenerator.cs @@ -8,17 +8,17 @@ using System.Linq; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; -using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; -using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; - namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration; +using static CodeGenerationHelpers; +using static SyntaxFactory; + internal static class ExpressionGenerator { public static ExpressionSyntax GenerateExpression( @@ -32,14 +32,14 @@ public static ExpressionSyntax GenerateExpression( case TypedConstantKind.Type: return typedConstant.Value is ITypeSymbol typeSymbol - ? SyntaxFactory.TypeOfExpression(typeSymbol.GenerateTypeSyntax()) + ? TypeOfExpression(typeSymbol.GenerateTypeSyntax()) : GenerateNullLiteral(); case TypedConstantKind.Array: return typedConstant.IsNull ? GenerateNullLiteral() - : SyntaxFactory.ImplicitArrayCreationExpression( - SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, + : ImplicitArrayCreationExpression( + InitializerExpression(SyntaxKind.ArrayInitializerExpression, [.. typedConstant.Values.Select(v => GenerateExpression(generator, v))])); default: @@ -48,7 +48,7 @@ public static ExpressionSyntax GenerateExpression( } private static ExpressionSyntax GenerateNullLiteral() - => SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression); + => LiteralExpression(SyntaxKind.NullLiteralExpression); internal static ExpressionSyntax GenerateExpression( SyntaxGenerator generator, @@ -79,17 +79,17 @@ internal static ExpressionSyntax GenerateNonEnumValueExpression(SyntaxGenerator bool val => GenerateBooleanLiteralExpression(val), string val => GenerateStringLiteralExpression(val), char val => GenerateCharLiteralExpression(val), - sbyte val => GenerateLiteralExpression(type, val, LiteralSpecialValues.SByteSpecialValues, formatString: null, canUseFieldReference, (s, v) => SyntaxFactory.Literal(s, v), x => x < 0, x => (sbyte)-x, "128"), - short val => GenerateLiteralExpression(type, val, LiteralSpecialValues.Int16SpecialValues, formatString: null, canUseFieldReference, (s, v) => SyntaxFactory.Literal(s, v), x => x < 0, x => (short)-x, "32768"), - int val => GenerateLiteralExpression(type, val, LiteralSpecialValues.Int32SpecialValues, formatString: null, canUseFieldReference, SyntaxFactory.Literal, x => x < 0, x => -x, "2147483648"), - long val => GenerateLiteralExpression(type, val, LiteralSpecialValues.Int64SpecialValues, formatString: null, canUseFieldReference, SyntaxFactory.Literal, x => x < 0, x => -x, "9223372036854775808"), - byte val => GenerateNonNegativeLiteralExpression(type, val, LiteralSpecialValues.ByteSpecialValues, formatString: null, canUseFieldReference, (s, v) => SyntaxFactory.Literal(s, v)), - ushort val => GenerateNonNegativeLiteralExpression(type, val, LiteralSpecialValues.UInt16SpecialValues, formatString: null, canUseFieldReference, (s, v) => SyntaxFactory.Literal(s, (uint)v)), - uint val => GenerateNonNegativeLiteralExpression(type, val, LiteralSpecialValues.UInt32SpecialValues, formatString: null, canUseFieldReference, SyntaxFactory.Literal), - ulong val => GenerateNonNegativeLiteralExpression(type, val, LiteralSpecialValues.UInt64SpecialValues, formatString: null, canUseFieldReference, SyntaxFactory.Literal), + sbyte val => GenerateLiteralExpression(type, val, LiteralSpecialValues.SByteSpecialValues, formatString: null, canUseFieldReference, (s, v) => Literal(s, v), x => x < 0, x => (sbyte)-x, "128"), + short val => GenerateLiteralExpression(type, val, LiteralSpecialValues.Int16SpecialValues, formatString: null, canUseFieldReference, (s, v) => Literal(s, v), x => x < 0, x => (short)-x, "32768"), + int val => GenerateLiteralExpression(type, val, LiteralSpecialValues.Int32SpecialValues, formatString: null, canUseFieldReference, Literal, x => x < 0, x => -x, "2147483648"), + long val => GenerateLiteralExpression(type, val, LiteralSpecialValues.Int64SpecialValues, formatString: null, canUseFieldReference, Literal, x => x < 0, x => -x, "9223372036854775808"), + byte val => GenerateNonNegativeLiteralExpression(type, val, LiteralSpecialValues.ByteSpecialValues, formatString: null, canUseFieldReference, (s, v) => Literal(s, v)), + ushort val => GenerateNonNegativeLiteralExpression(type, val, LiteralSpecialValues.UInt16SpecialValues, formatString: null, canUseFieldReference, (s, v) => Literal(s, (uint)v)), + uint val => GenerateNonNegativeLiteralExpression(type, val, LiteralSpecialValues.UInt32SpecialValues, formatString: null, canUseFieldReference, Literal), + ulong val => GenerateNonNegativeLiteralExpression(type, val, LiteralSpecialValues.UInt64SpecialValues, formatString: null, canUseFieldReference, Literal), float val => GenerateSingleLiteralExpression(type, val, canUseFieldReference), double val => GenerateDoubleLiteralExpression(type, val, canUseFieldReference), - decimal val => GenerateLiteralExpression(type, val, LiteralSpecialValues.DecimalSpecialValues, formatString: null, canUseFieldReference, SyntaxFactory.Literal, x => x < 0, x => -x, integerMinValueString: null), + decimal val => GenerateLiteralExpression(type, val, LiteralSpecialValues.DecimalSpecialValues, formatString: null, canUseFieldReference, Literal, x => x < 0, x => -x, integerMinValueString: null), _ => type == null || type.IsReferenceType || type is IPointerTypeSymbol || type.IsNullable() ? GenerateNullLiteral() : (ExpressionSyntax)generator.DefaultExpression(type), @@ -97,7 +97,7 @@ internal static ExpressionSyntax GenerateNonEnumValueExpression(SyntaxGenerator private static ExpressionSyntax GenerateBooleanLiteralExpression(bool val) { - return SyntaxFactory.LiteralExpression(val + return LiteralExpression(val ? SyntaxKind.TrueLiteralExpression : SyntaxKind.FalseLiteralExpression); } @@ -105,15 +105,15 @@ private static ExpressionSyntax GenerateBooleanLiteralExpression(bool val) private static ExpressionSyntax GenerateStringLiteralExpression(string val) { var valueString = SymbolDisplay.FormatLiteral(val, quote: true); - return SyntaxFactory.LiteralExpression( - SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(valueString, val)); + return LiteralExpression( + SyntaxKind.StringLiteralExpression, Literal(valueString, val)); } private static ExpressionSyntax GenerateCharLiteralExpression(char val) { var literal = SymbolDisplay.FormatLiteral(val, quote: true); - return SyntaxFactory.LiteralExpression( - SyntaxKind.CharacterLiteralExpression, SyntaxFactory.Literal(literal, val)); + return LiteralExpression( + SyntaxKind.CharacterLiteralExpression, Literal(literal, val)); } private static string DetermineSuffix(ITypeSymbol? type, object value) @@ -176,27 +176,27 @@ private static ExpressionSyntax GenerateDoubleLiteralExpression(ITypeSymbol? typ { if (double.IsNaN(value)) { - return SyntaxFactory.BinaryExpression(SyntaxKind.DivideExpression, + return BinaryExpression(SyntaxKind.DivideExpression, GenerateDoubleLiteralExpression(type: null, 0.0, canUseFieldReference: false), GenerateDoubleLiteralExpression(type: null, 0.0, canUseFieldReference: false)); } else if (double.IsPositiveInfinity(value)) { - return SyntaxFactory.BinaryExpression(SyntaxKind.DivideExpression, + return BinaryExpression(SyntaxKind.DivideExpression, GenerateDoubleLiteralExpression(type: null, 1.0, canUseFieldReference: false), GenerateDoubleLiteralExpression(type: null, 0.0, canUseFieldReference: false)); } else if (double.IsNegativeInfinity(value)) { - return SyntaxFactory.BinaryExpression(SyntaxKind.DivideExpression, - SyntaxFactory.PrefixUnaryExpression(SyntaxKind.UnaryMinusExpression, GenerateDoubleLiteralExpression(null, 1.0, false)), + return BinaryExpression(SyntaxKind.DivideExpression, + PrefixUnaryExpression(SyntaxKind.UnaryMinusExpression, GenerateDoubleLiteralExpression(null, 1.0, false)), GenerateDoubleLiteralExpression(type: null, 0.0, canUseFieldReference: false)); } } return GenerateLiteralExpression( type, value, LiteralSpecialValues.DoubleSpecialValues, formatString: "R", canUseFieldReference, - SyntaxFactory.Literal, x => x < 0, x => -x, integerMinValueString: null); + Literal, x => x < 0, x => -x, integerMinValueString: null); } private static ExpressionSyntax GenerateSingleLiteralExpression(ITypeSymbol? type, float value, bool canUseFieldReference) @@ -205,27 +205,27 @@ private static ExpressionSyntax GenerateSingleLiteralExpression(ITypeSymbol? typ { if (float.IsNaN(value)) { - return SyntaxFactory.BinaryExpression(SyntaxKind.DivideExpression, + return BinaryExpression(SyntaxKind.DivideExpression, GenerateSingleLiteralExpression(type: null, 0.0F, canUseFieldReference: false), GenerateSingleLiteralExpression(type: null, 0.0F, canUseFieldReference: false)); } else if (float.IsPositiveInfinity(value)) { - return SyntaxFactory.BinaryExpression(SyntaxKind.DivideExpression, + return BinaryExpression(SyntaxKind.DivideExpression, GenerateSingleLiteralExpression(type: null, 1.0F, canUseFieldReference: false), GenerateSingleLiteralExpression(type: null, 0.0F, canUseFieldReference: false)); } else if (float.IsNegativeInfinity(value)) { - return SyntaxFactory.BinaryExpression(SyntaxKind.DivideExpression, - SyntaxFactory.PrefixUnaryExpression(SyntaxKind.UnaryMinusExpression, GenerateSingleLiteralExpression(null, 1.0F, false)), + return BinaryExpression(SyntaxKind.DivideExpression, + PrefixUnaryExpression(SyntaxKind.UnaryMinusExpression, GenerateSingleLiteralExpression(null, 1.0F, false)), GenerateSingleLiteralExpression(null, 0.0F, false)); } } return GenerateLiteralExpression( type, value, LiteralSpecialValues.SingleSpecialValues, formatString: "R", canUseFieldReference, - SyntaxFactory.Literal, x => x < 0, x => -x, null); + Literal, x => x < 0, x => -x, null); } private static ExpressionSyntax GenerateNonNegativeLiteralExpression( @@ -268,11 +268,11 @@ private static ExpressionSyntax GenerateLiteralExpression( ? (integerMinValueString ?? throw ExceptionUtilities.Unreachable()) : ((IFormattable)nonNegativeValue).ToString(formatString, CultureInfo.InvariantCulture) + suffix; - var literal = SyntaxFactory.LiteralExpression( + var literal = LiteralExpression( SyntaxKind.NumericLiteralExpression, tokenFactory(stringValue, nonNegativeValue)); return negative - ? SyntaxFactory.PrefixUnaryExpression(SyntaxKind.UnaryMinusExpression, literal) + ? PrefixUnaryExpression(SyntaxKind.UnaryMinusExpression, literal) : literal; } @@ -289,7 +289,7 @@ private static ExpressionSyntax GenerateLiteralExpression( memberAccess = memberAccess.WithAdditionalAnnotations(SpecialTypeAnnotation.Create(type.SpecialType)); } - var result = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, memberAccess, SyntaxFactory.IdentifierName(constant.Value)); + var result = MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, memberAccess, IdentifierName(constant.Value)); return result.WithAdditionalAnnotations(Simplifier.Annotation); } } @@ -299,17 +299,17 @@ private static ExpressionSyntax GenerateLiteralExpression( private static ExpressionSyntax GenerateMemberAccess(params string[] names) { - ExpressionSyntax result = SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)); + ExpressionSyntax result = IdentifierName(Token(SyntaxKind.GlobalKeyword)); for (var i = 0; i < names.Length; i++) { - var name = SyntaxFactory.IdentifierName(names[i]); + var name = IdentifierName(names[i]); if (i == 0) { - result = SyntaxFactory.AliasQualifiedName((IdentifierNameSyntax)result, name); + result = AliasQualifiedName((IdentifierNameSyntax)result, name); } else { - result = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, result, name); + result = MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, result, name); } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/FieldGenerator.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/FieldGenerator.cs index 1afaf4e705926..c05e69f6a86df 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/FieldGenerator.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/FieldGenerator.cs @@ -16,6 +16,8 @@ namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration; +using static SyntaxFactory; + internal static class FieldGenerator { private static MemberDeclarationSyntax? LastField( @@ -91,15 +93,15 @@ public static FieldDeclarationSyntax GenerateFieldDeclaration( } var initializer = CodeGenerationFieldInfo.GetInitializer(field) is ExpressionSyntax initializerNode - ? SyntaxFactory.EqualsValueClause(initializerNode) + ? EqualsValueClause(initializerNode) : GenerateEqualsValue(info.Generator, field); - var fieldDeclaration = SyntaxFactory.FieldDeclaration( + var fieldDeclaration = FieldDeclaration( AttributeGenerator.GenerateAttributeLists(field.GetAttributes(), info), GenerateModifiers(field, info), - SyntaxFactory.VariableDeclaration( + VariableDeclaration( field.Type.GenerateTypeSyntax(), - [AddAnnotationsTo(field, SyntaxFactory.VariableDeclarator(field.Name.ToIdentifierToken(), null, initializer))])); + [AddAnnotationsTo(field, VariableDeclarator(field.Name.ToIdentifierToken(), null, initializer))])); return AddFormatterAndCodeGeneratorAnnotationsTo( ConditionallyAddDocumentationCommentTo(fieldDeclaration, field, info, cancellationToken)); @@ -110,7 +112,7 @@ public static FieldDeclarationSyntax GenerateFieldDeclaration( if (field.HasConstantValue) { var canUseFieldReference = field.Type != null && !field.Type.Equals(field.ContainingType); - return SyntaxFactory.EqualsValueClause(ExpressionGenerator.GenerateExpression(generator, field.Type, field.ConstantValue, canUseFieldReference)); + return EqualsValueClause(ExpressionGenerator.GenerateExpression(generator, field.Type, field.ConstantValue, canUseFieldReference)); } return null; @@ -123,29 +125,29 @@ private static SyntaxTokenList GenerateModifiers(IFieldSymbol field, CSharpCodeG CSharpCodeGenerationHelpers.AddAccessibilityModifiers(field.DeclaredAccessibility, tokens, info, Accessibility.Private); if (field.IsConst) { - tokens.Add(SyntaxFactory.Token(SyntaxKind.ConstKeyword)); + tokens.Add(Token(SyntaxKind.ConstKeyword)); } else { if (field.IsStatic) { - tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); + tokens.Add(Token(SyntaxKind.StaticKeyword)); } if (field.IsReadOnly) { - tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); + tokens.Add(Token(SyntaxKind.ReadOnlyKeyword)); } if (field.IsRequired) { - tokens.Add(SyntaxFactory.Token(SyntaxKind.RequiredKeyword)); + tokens.Add(Token(SyntaxKind.RequiredKeyword)); } } if (CodeGenerationFieldInfo.GetIsUnsafe(field)) { - tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); + tokens.Add(Token(SyntaxKind.UnsafeKeyword)); } return tokens.ToSyntaxTokenListAndFree(); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/MethodGenerator.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/MethodGenerator.cs index 3e450fc522bcc..ded147332b1ce 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/MethodGenerator.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/MethodGenerator.cs @@ -8,21 +8,22 @@ using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeGeneration; -using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; -using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; -using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration; +using static CodeGenerationHelpers; +using static CSharpCodeGenerationHelpers; +using static SyntaxFactory; + internal static class MethodGenerator { - private static readonly TypeParameterConstraintSyntax s_classConstraint = SyntaxFactory.ClassOrStructConstraint(SyntaxKind.ClassConstraint); - private static readonly TypeParameterConstraintSyntax s_structConstraint = SyntaxFactory.ClassOrStructConstraint(SyntaxKind.StructConstraint); - private static readonly TypeParameterConstraintSyntax s_defaultConstraint = SyntaxFactory.DefaultConstraint(); + private static readonly TypeParameterConstraintSyntax s_classConstraint = ClassOrStructConstraint(SyntaxKind.ClassConstraint); + private static readonly TypeParameterConstraintSyntax s_structConstraint = ClassOrStructConstraint(SyntaxKind.StructConstraint); + private static readonly TypeParameterConstraintSyntax s_defaultConstraint = DefaultConstraint(); internal static BaseNamespaceDeclarationSyntax AddMethodTo( BaseNamespaceDeclarationSyntax destination, @@ -117,7 +118,7 @@ private static MethodDeclarationSyntax GenerateMethodDeclarationWorker( var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(method.ExplicitInterfaceImplementations); - var methodDeclaration = SyntaxFactory.MethodDeclaration( + var methodDeclaration = MethodDeclaration( attributeLists: GenerateAttributes(method, info, explicitInterfaceSpecifier != null), modifiers: GenerateModifiers(method, destination, info), returnType: method.GenerateReturnTypeSyntax(), @@ -128,7 +129,7 @@ private static MethodDeclarationSyntax GenerateMethodDeclarationWorker( constraintClauses: GenerateConstraintClauses(method), body: hasNoBody ? null : StatementGenerator.GenerateBlock(method), expressionBody: null, - semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default); + semicolonToken: hasNoBody ? Token(SyntaxKind.SemicolonToken) : default); methodDeclaration = UseExpressionBodyIfDesired(info, methodDeclaration, cancellationToken); return AddFormatterAndCodeGeneratorAnnotationsTo(methodDeclaration); @@ -138,7 +139,7 @@ private static LocalFunctionStatementSyntax GenerateLocalFunctionDeclarationWork IMethodSymbol method, CodeGenerationDestination destination, CSharpCodeGenerationContextInfo info, CancellationToken cancellationToken) { - var localFunctionDeclaration = SyntaxFactory.LocalFunctionStatement( + var localFunctionDeclaration = LocalFunctionStatement( modifiers: GenerateModifiers(method, destination, info), returnType: method.GenerateReturnTypeSyntax(), identifier: method.Name.ToIdentifierToken(), @@ -197,7 +198,7 @@ private static SyntaxList GenerateAttributes( if (!isExplicit) { attributes.AddRange(AttributeGenerator.GenerateAttributeLists(method.GetAttributes(), info)); - attributes.AddRange(AttributeGenerator.GenerateAttributeLists(method.GetReturnTypeAttributes(), info, SyntaxFactory.Token(SyntaxKind.ReturnKeyword))); + attributes.AddRange(AttributeGenerator.GenerateAttributeLists(method.GetReturnTypeAttributes(), info, Token(SyntaxKind.ReturnKeyword))); } return [.. attributes]; @@ -235,7 +236,7 @@ private static SyntaxList GenerateDefaultCo _ => s_defaultConstraint }; - listOfClauses.Add(SyntaxFactory.TypeParameterConstraintClause( + listOfClauses.Add(TypeParameterConstraintClause( typeParameter.Name.ToIdentifierName(), [constraint])); } @@ -258,10 +259,10 @@ private static SyntaxTokenList GenerateModifiers( if (method.ExplicitInterfaceImplementations.Any()) { if (method.IsStatic) - tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); + tokens.Add(Token(SyntaxKind.StaticKeyword)); if (CodeGenerationMethodInfo.GetIsUnsafe(method)) - tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); + tokens.Add(Token(SyntaxKind.UnsafeKeyword)); } else { @@ -270,11 +271,11 @@ private static SyntaxTokenList GenerateModifiers( { if (method.IsStatic) { - tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); + tokens.Add(Token(SyntaxKind.StaticKeyword)); // We only generate the abstract keyword in interfaces for static abstract members if (method.IsAbstract) - tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); + tokens.Add(Token(SyntaxKind.AbstractKeyword)); } } else if (destination is not CodeGenerationDestination.CompilationUnit and @@ -283,52 +284,52 @@ private static SyntaxTokenList GenerateModifiers( CSharpCodeGenerationHelpers.AddAccessibilityModifiers(method.DeclaredAccessibility, tokens, info, Accessibility.Private); if (method.IsStatic) - tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); + tokens.Add(Token(SyntaxKind.StaticKeyword)); if (method.IsAbstract) - tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); + tokens.Add(Token(SyntaxKind.AbstractKeyword)); if (method.IsSealed) - tokens.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword)); + tokens.Add(Token(SyntaxKind.SealedKeyword)); // Don't show the readonly modifier if the containing type is already readonly // ContainingSymbol is used to guard against methods which are not members of their ContainingType (e.g. lambdas and local functions) if (method.IsReadOnly && (method.ContainingSymbol as INamedTypeSymbol)?.IsReadOnly != true) - tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); + tokens.Add(Token(SyntaxKind.ReadOnlyKeyword)); if (method.IsOverride) - tokens.Add(SyntaxFactory.Token(SyntaxKind.OverrideKeyword)); + tokens.Add(Token(SyntaxKind.OverrideKeyword)); if (method.IsVirtual) - tokens.Add(SyntaxFactory.Token(SyntaxKind.VirtualKeyword)); + tokens.Add(Token(SyntaxKind.VirtualKeyword)); if (CodeGenerationMethodInfo.GetIsPartial(method) && !method.IsAsync) - tokens.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)); + tokens.Add(Token(SyntaxKind.PartialKeyword)); } else if (destination is CodeGenerationDestination.CompilationUnit) { if (method.IsStatic) - tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); + tokens.Add(Token(SyntaxKind.StaticKeyword)); } if (CodeGenerationMethodInfo.GetIsUnsafe(method)) - tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); + tokens.Add(Token(SyntaxKind.UnsafeKeyword)); if (CodeGenerationMethodInfo.GetIsNew(method)) - tokens.Add(SyntaxFactory.Token(SyntaxKind.NewKeyword)); + tokens.Add(Token(SyntaxKind.NewKeyword)); } if (destination != CodeGenerationDestination.InterfaceType) { if (CodeGenerationMethodInfo.GetIsAsyncMethod(method)) { - tokens.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword)); + tokens.Add(Token(SyntaxKind.AsyncKeyword)); } } if (CodeGenerationMethodInfo.GetIsPartial(method) && method.IsAsync) { - tokens.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)); + tokens.Add(Token(SyntaxKind.PartialKeyword)); } return tokens.ToSyntaxTokenListAndFree(); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/NamedTypeGenerator.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/NamedTypeGenerator.cs index 67d3c77b2afd2..dbf4f605452a9 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/NamedTypeGenerator.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/NamedTypeGenerator.cs @@ -12,11 +12,13 @@ using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; -using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; -using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration; +using static CodeGenerationHelpers; +using static CSharpCodeGenerationHelpers; +using static SyntaxFactory; + internal static class NamedTypeGenerator { public static TypeDeclarationSyntax AddNamedTypeTo( @@ -124,11 +126,11 @@ private static RecordDeclarationSyntax GenerateRecordMembers( // If there are no members, just make a simple record with no body if (members.Length == 0) - return recordDeclaration.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); + return recordDeclaration.WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); // Otherwise, give the record a body and add the members to it. - recordDeclaration = recordDeclaration.WithOpenBraceToken(SyntaxFactory.Token(SyntaxKind.OpenBraceToken)) - .WithCloseBraceToken(SyntaxFactory.Token(SyntaxKind.CloseBraceToken)) + recordDeclaration = recordDeclaration.WithOpenBraceToken(Token(SyntaxKind.OpenBraceToken)) + .WithCloseBraceToken(Token(SyntaxKind.CloseBraceToken)) .WithSemicolonToken(default); return service.AddMembers(recordDeclaration, members, info, cancellationToken); } @@ -194,19 +196,19 @@ private static MemberDeclarationSyntax GetDeclarationSyntaxWithoutMembersWorker( { var isRecordClass = namedType.TypeKind is TypeKind.Class; var declarationKind = isRecordClass ? SyntaxKind.RecordDeclaration : SyntaxKind.RecordStructDeclaration; - var classOrStructKeyword = SyntaxFactory.Token(isRecordClass ? default : SyntaxKind.StructKeyword); + var classOrStructKeyword = Token(isRecordClass ? default : SyntaxKind.StructKeyword); - typeDeclaration = SyntaxFactory.RecordDeclaration(kind: declarationKind, attributeLists: default, modifiers: default, - SyntaxFactory.Token(SyntaxKind.RecordKeyword), classOrStructKeyword, namedType.Name.ToIdentifierToken(), + typeDeclaration = RecordDeclaration(kind: declarationKind, attributeLists: default, modifiers: default, + Token(SyntaxKind.RecordKeyword), classOrStructKeyword, namedType.Name.ToIdentifierToken(), typeParameterList: null, parameterList: null, baseList: null, constraintClauses: default, openBraceToken: default, members: default, closeBraceToken: default, - SyntaxFactory.Token(SyntaxKind.SemicolonToken)); + Token(SyntaxKind.SemicolonToken)); } else { var kind = namedType.TypeKind == TypeKind.Struct ? SyntaxKind.StructDeclaration : namedType.TypeKind == TypeKind.Interface ? SyntaxKind.InterfaceDeclaration : SyntaxKind.ClassDeclaration; - typeDeclaration = SyntaxFactory.TypeDeclaration(kind, namedType.Name.ToIdentifierToken()); + typeDeclaration = TypeDeclaration(kind, namedType.Name.ToIdentifierToken()); } var result = typeDeclaration @@ -227,7 +229,7 @@ private static DelegateDeclarationSyntax GenerateDelegateDeclaration( var invokeMethod = namedType.DelegateInvokeMethod; Contract.ThrowIfNull(invokeMethod); - return SyntaxFactory.DelegateDeclaration( + return DelegateDeclaration( GenerateAttributeDeclarations(namedType, info), GenerateModifiers(namedType, destination, info), invokeMethod.ReturnType.GenerateTypeSyntax(), @@ -243,10 +245,10 @@ private static EnumDeclarationSyntax GenerateEnumDeclaration( CSharpCodeGenerationContextInfo info) { var baseList = namedType.EnumUnderlyingType != null && namedType.EnumUnderlyingType.SpecialType != SpecialType.System_Int32 - ? SyntaxFactory.BaseList([SyntaxFactory.SimpleBaseType(namedType.EnumUnderlyingType.GenerateTypeSyntax())]) + ? BaseList([SimpleBaseType(namedType.EnumUnderlyingType.GenerateTypeSyntax())]) : null; - return SyntaxFactory.EnumDeclaration( + return EnumDeclaration( GenerateAttributeDeclarations(namedType, info), GenerateModifiers(namedType, destination, info), namedType.Name.ToIdentifierToken(), @@ -276,12 +278,12 @@ private static SyntaxTokenList GenerateModifiers( } else { - tokens.Add(SyntaxFactory.Token(SyntaxKind.FileKeyword)); + tokens.Add(Token(SyntaxKind.FileKeyword)); } if (namedType.IsStatic) { - tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); + tokens.Add(Token(SyntaxKind.StaticKeyword)); } else { @@ -289,24 +291,24 @@ private static SyntaxTokenList GenerateModifiers( { if (namedType.IsAbstract) { - tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); + tokens.Add(Token(SyntaxKind.AbstractKeyword)); } if (namedType.IsSealed) { - tokens.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword)); + tokens.Add(Token(SyntaxKind.SealedKeyword)); } } } if (namedType.IsReadOnly) { - tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); + tokens.Add(Token(SyntaxKind.ReadOnlyKeyword)); } if (namedType.IsRefLikeType) { - tokens.Add(SyntaxFactory.Token(SyntaxKind.RefKeyword)); + tokens.Add(Token(SyntaxKind.RefKeyword)); } return tokens.ToSyntaxTokenListAndFree(); @@ -322,15 +324,15 @@ private static SyntaxTokenList GenerateModifiers( { var types = new List(); if (namedType.TypeKind == TypeKind.Class && namedType.BaseType != null && namedType.BaseType.SpecialType != Microsoft.CodeAnalysis.SpecialType.System_Object) - types.Add(SyntaxFactory.SimpleBaseType(namedType.BaseType.GenerateTypeSyntax())); + types.Add(SimpleBaseType(namedType.BaseType.GenerateTypeSyntax())); foreach (var type in namedType.Interfaces) - types.Add(SyntaxFactory.SimpleBaseType(type.GenerateTypeSyntax())); + types.Add(SimpleBaseType(type.GenerateTypeSyntax())); if (types.Count == 0) return null; - return SyntaxFactory.BaseList([.. types]); + return BaseList([.. types]); } private static SyntaxList GenerateConstraintClauses(INamedTypeSymbol namedType) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/NamespaceGenerator.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/NamespaceGenerator.cs index 7a958cda09908..293a5e8e041a5 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/NamespaceGenerator.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/NamespaceGenerator.cs @@ -8,7 +8,6 @@ using System.Threading; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; @@ -18,6 +17,8 @@ namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration; +using static SyntaxFactory; + internal static class NamespaceGenerator { public static BaseNamespaceDeclarationSyntax AddNamespaceTo( @@ -102,16 +103,16 @@ private static SyntaxNode GenerateNamespaceDeclarationWorker( // If they're just generating the empty namespace then make that into compilation unit. if (name == string.Empty) - return SyntaxFactory.CompilationUnit().WithUsings(usings); + return CompilationUnit().WithUsings(usings); if (destination == CodeGenerationDestination.CompilationUnit && info.Options.NamespaceDeclarations.Value == NamespaceDeclarationPreference.FileScoped && info.LanguageVersion >= LanguageVersion.CSharp10) { - return SyntaxFactory.FileScopedNamespaceDeclaration(SyntaxFactory.ParseName(name)).WithUsings(usings); + return FileScopedNamespaceDeclaration(ParseName(name)).WithUsings(usings); } - return SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(name)).WithUsings(usings); + return NamespaceDeclaration(ParseName(name)).WithUsings(usings); } private static SyntaxNode GetDeclarationSyntaxWithoutMembers( @@ -153,8 +154,8 @@ private static SyntaxList GenerateUsingDirectives(INamespa var name = GenerateName(alias.Target); if (name != null) { - return SyntaxFactory.UsingDirective( - SyntaxFactory.NameEquals(alias.Name.ToIdentifierName()), + return UsingDirective( + NameEquals(alias.Name.ToIdentifierName()), name); } } @@ -163,7 +164,7 @@ private static SyntaxList GenerateUsingDirectives(INamespa var name = GenerateName(namespaceOrType); if (name != null) { - return SyntaxFactory.UsingDirective(name); + return UsingDirective(name); } } @@ -174,6 +175,6 @@ private static NameSyntax GenerateName(INamespaceOrTypeSymbol symbol) { return symbol is ITypeSymbol type ? type.GenerateNameSyntax() - : SyntaxFactory.ParseName(symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)); + : ParseName(symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)); } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/OperatorGenerator.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/OperatorGenerator.cs index 26c097c12b235..235047cbe6933 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/OperatorGenerator.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/OperatorGenerator.cs @@ -5,17 +5,18 @@ using System; using System.Collections.Generic; using System.Threading; -using System.Xml; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; -using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; -using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration; +using static CodeGenerationHelpers; +using static CSharpCodeGenerationHelpers; +using static SyntaxFactory; + internal static class OperatorGenerator { internal static TypeDeclarationSyntax AddOperatorTo( @@ -82,23 +83,23 @@ private static OperatorDeclarationSyntax GenerateOperatorDeclarationWorker( throw new ArgumentException(string.Format(WorkspaceExtensionsResources.Cannot_generate_code_for_unsupported_operator_0, method.Name), nameof(method)); } - var operatorToken = SyntaxFactory.Token(operatorSyntaxKind); + var operatorToken = Token(operatorSyntaxKind); var checkedToken = SyntaxFacts.IsCheckedOperator(method.MetadataName) - ? SyntaxFactory.Token(SyntaxKind.CheckedKeyword) + ? Token(SyntaxKind.CheckedKeyword) : default; - var operatorDecl = SyntaxFactory.OperatorDeclaration( + var operatorDecl = OperatorDeclaration( attributeLists: AttributeGenerator.GenerateAttributeLists(method.GetAttributes(), info), modifiers: GenerateModifiers(method, destination, hasNoBody), returnType: method.ReturnType.GenerateTypeSyntax(), explicitInterfaceSpecifier: GenerateExplicitInterfaceSpecifier(method.ExplicitInterfaceImplementations), - operatorKeyword: SyntaxFactory.Token(SyntaxKind.OperatorKeyword), + operatorKeyword: Token(SyntaxKind.OperatorKeyword), checkedKeyword: checkedToken, operatorToken: operatorToken, parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, isExplicit: false, info: info), body: hasNoBody ? null : StatementGenerator.GenerateBlock(method), expressionBody: null, - semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : new SyntaxToken()); + semicolonToken: hasNoBody ? Token(SyntaxKind.SemicolonToken) : new SyntaxToken()); operatorDecl = UseExpressionBodyIfDesired(info, operatorDecl, cancellationToken); return operatorDecl; @@ -111,14 +112,14 @@ private static SyntaxTokenList GenerateModifiers(IMethodSymbol method, CodeGener if (method.ExplicitInterfaceImplementations.Length == 0 && !(destination is CodeGenerationDestination.InterfaceType && hasNoBody)) { - tokens.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)); + tokens.Add(Token(SyntaxKind.PublicKeyword)); } - tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); + tokens.Add(Token(SyntaxKind.StaticKeyword)); if (method.IsAbstract) { - tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); + tokens.Add(Token(SyntaxKind.AbstractKeyword)); } return tokens.ToImmutableAndClear().ToSyntaxTokenList(); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/ParameterGenerator.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/ParameterGenerator.cs index 3b7c79d31be7f..253523c3f2e56 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/ParameterGenerator.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/ParameterGenerator.cs @@ -3,17 +3,18 @@ // See the LICENSE file in the project root for more information. using System; -using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; -using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration; +using static CSharpCodeGenerationHelpers; +using static SyntaxFactory; + internal static class ParameterGenerator { public static ParameterListSyntax GenerateParameterList( @@ -23,7 +24,7 @@ public static ParameterListSyntax GenerateParameterList( { var parameters = GetParameters(parameterDefinitions, isExplicit, info); - return SyntaxFactory.ParameterList([.. parameters]); + return ParameterList([.. parameters]); } public static BracketedParameterListSyntax GenerateBracketedParameterList( @@ -35,7 +36,7 @@ public static BracketedParameterListSyntax GenerateBracketedParameterList( // could never have a typeParameterMapping. var parameters = GetParameters(parameterDefinitions, isExplicit, info); - return SyntaxFactory.BracketedParameterList([.. parameters]); + return BracketedParameterList([.. parameters]); } internal static ImmutableArray GetParameters( @@ -64,7 +65,7 @@ internal static ParameterSyntax GetParameter(IParameterSymbol parameter, CSharpC if (reusableSyntax != null) return reusableSyntax; - return SyntaxFactory.Parameter(parameter.Name.ToIdentifierToken()) + return Parameter(parameter.Name.ToIdentifierToken()) .WithAttributeLists(GenerateAttributes(parameter, isExplicit, info)) .WithModifiers(GenerateModifiers(parameter, isFirstParam)) .WithType(parameter.Type.GenerateTypeSyntax()) @@ -80,12 +81,12 @@ private static SyntaxTokenList GenerateModifiers( parameter.ContainingSymbol is IMethodSymbol methodSymbol && methodSymbol.IsExtensionMethod) { - list = list.Add(SyntaxFactory.Token(SyntaxKind.ThisKeyword)); + list = list.Add(Token(SyntaxKind.ThisKeyword)); } if (parameter.IsParams) { - list = list.Add(SyntaxFactory.Token(SyntaxKind.ParamsKeyword)); + list = list.Add(Token(SyntaxKind.ParamsKeyword)); } return list; @@ -105,7 +106,7 @@ parameter.ContainingSymbol is IMethodSymbol methodSymbol && if (defaultValue is DateTime) return null; - return SyntaxFactory.EqualsValueClause( + return EqualsValueClause( GenerateEqualsValueClauseWorker(generator, parameter, defaultValue)); } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/PropertyGenerator.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/PropertyGenerator.cs index 0bc31a2c452be..a409ecfd60608 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/PropertyGenerator.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/PropertyGenerator.cs @@ -14,11 +14,12 @@ using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; -using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; -using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; - namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration; +using static CodeGenerationHelpers; +using static CSharpCodeGenerationHelpers; +using static SyntaxFactory; + internal static class PropertyGenerator { public static bool CanBeGenerated(IPropertySymbol property) @@ -92,7 +93,7 @@ private static MemberDeclarationSyntax GenerateIndexerDeclaration( { var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(property.ExplicitInterfaceImplementations); - var declaration = SyntaxFactory.IndexerDeclaration( + var declaration = IndexerDeclaration( attributeLists: AttributeGenerator.GenerateAttributeLists(property.GetAttributes(), info), modifiers: GenerateModifiers(property, destination, info), type: GenerateTypeSyntax(property), @@ -110,14 +111,14 @@ private static MemberDeclarationSyntax GeneratePropertyDeclaration( CSharpCodeGenerationContextInfo info, CancellationToken cancellationToken) { var initializer = CodeGenerationPropertyInfo.GetInitializer(property) is ExpressionSyntax initializerNode - ? SyntaxFactory.EqualsValueClause(initializerNode) + ? EqualsValueClause(initializerNode) : null; var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(property.ExplicitInterfaceImplementations); var accessorList = GenerateAccessorList(property, destination, info, cancellationToken); - var propertyDeclaration = SyntaxFactory.PropertyDeclaration( + var propertyDeclaration = PropertyDeclaration( attributeLists: AttributeGenerator.GenerateAttributeLists(property.GetAttributes(), info), modifiers: GenerateModifiers(property, destination, info), type: GenerateTypeSyntax(property), @@ -126,7 +127,7 @@ private static MemberDeclarationSyntax GeneratePropertyDeclaration( accessorList: accessorList, expressionBody: null, initializer: initializer, - semicolonToken: initializer is null ? default : SyntaxFactory.Token(SyntaxKind.SemicolonToken)); + semicolonToken: initializer is null ? default : Token(SyntaxKind.SemicolonToken)); propertyDeclaration = UseExpressionBodyIfDesired(info, propertyDeclaration, cancellationToken); @@ -268,7 +269,7 @@ private static bool TryGetArrowExpressionBody( return accessors[0] == null && accessors[1] == null ? null - : SyntaxFactory.AccessorList([.. accessors.WhereNotNull()]); + : AccessorList([.. accessors.WhereNotNull()]); } private static AccessorDeclarationSyntax? GenerateAccessorDeclaration( @@ -293,10 +294,10 @@ private static AccessorDeclarationSyntax GenerateAccessorDeclaration( CSharpCodeGenerationContextInfo info, CancellationToken cancellationToken) { - var declaration = SyntaxFactory.AccessorDeclaration(kind) + var declaration = AccessorDeclaration(kind) .WithModifiers(GenerateAccessorModifiers(property, accessor, info)) .WithBody(hasBody ? GenerateBlock(accessor) : null) - .WithSemicolonToken(hasBody ? default : SyntaxFactory.Token(SyntaxKind.SemicolonToken)); + .WithSemicolonToken(hasBody ? default : Token(SyntaxKind.SemicolonToken)); declaration = UseExpressionBodyIfDesired(info, declaration, cancellationToken); @@ -305,7 +306,7 @@ private static AccessorDeclarationSyntax GenerateAccessorDeclaration( private static BlockSyntax GenerateBlock(IMethodSymbol accessor) { - return SyntaxFactory.Block( + return Block( StatementGenerator.GenerateStatements(CodeGenerationMethodInfo.GetStatements(accessor))); } @@ -336,7 +337,7 @@ private static SyntaxTokenList GenerateAccessorModifiers( var hasNonReadOnlyAccessor = property.GetMethod?.IsReadOnly == false || property.SetMethod?.IsReadOnly == false; if (hasNonReadOnlyAccessor && accessor.IsReadOnly) { - modifiers.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); + modifiers.Add(Token(SyntaxKind.ReadOnlyKeyword)); } return modifiers.ToSyntaxTokenListAndFree(); @@ -351,7 +352,7 @@ private static SyntaxTokenList GenerateModifiers( if (property.ExplicitInterfaceImplementations.Any()) { if (property.IsStatic) - tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); + tokens.Add(Token(SyntaxKind.StaticKeyword)); } else { @@ -360,10 +361,10 @@ private static SyntaxTokenList GenerateModifiers( { if (property.IsStatic) { - tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); + tokens.Add(Token(SyntaxKind.StaticKeyword)); if (property.IsAbstract) - tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); + tokens.Add(Token(SyntaxKind.AbstractKeyword)); } } else if (destination is not CodeGenerationDestination.CompilationUnit) @@ -371,7 +372,7 @@ private static SyntaxTokenList GenerateModifiers( CSharpCodeGenerationHelpers.AddAccessibilityModifiers(property.DeclaredAccessibility, tokens, info, Accessibility.Private); if (property.IsStatic) - tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); + tokens.Add(Token(SyntaxKind.StaticKeyword)); // note: explicit interface impls are allowed to be 'readonly' but it never actually affects callers // because of the boxing requirement in order to call the method. @@ -380,27 +381,27 @@ private static SyntaxTokenList GenerateModifiers( // Don't show the readonly modifier if the containing type is already readonly if (hasAllReadOnlyAccessors && !property.ContainingType.IsReadOnly) - tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); + tokens.Add(Token(SyntaxKind.ReadOnlyKeyword)); if (property.IsSealed) - tokens.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword)); + tokens.Add(Token(SyntaxKind.SealedKeyword)); if (property.IsOverride) - tokens.Add(SyntaxFactory.Token(SyntaxKind.OverrideKeyword)); + tokens.Add(Token(SyntaxKind.OverrideKeyword)); if (property.IsVirtual) - tokens.Add(SyntaxFactory.Token(SyntaxKind.VirtualKeyword)); + tokens.Add(Token(SyntaxKind.VirtualKeyword)); if (property.IsAbstract) - tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); + tokens.Add(Token(SyntaxKind.AbstractKeyword)); if (property.IsRequired) - tokens.Add(SyntaxFactory.Token(SyntaxKind.RequiredKeyword)); + tokens.Add(Token(SyntaxKind.RequiredKeyword)); } } if (CodeGenerationPropertyInfo.GetIsUnsafe(property)) - tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); + tokens.Add(Token(SyntaxKind.UnsafeKeyword)); return tokens.ToSyntaxTokenList(); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/TypeParameterGenerator.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/TypeParameterGenerator.cs index a8c1df4a28190..4216133cb6d14 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/TypeParameterGenerator.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeGeneration/TypeParameterGenerator.cs @@ -5,12 +5,13 @@ using System.Collections.Immutable; using System.Linq; -using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration; +using static SyntaxFactory; + internal static class TypeParameterGenerator { public static TypeParameterListSyntax? GenerateTypeParameterList( @@ -18,17 +19,17 @@ internal static class TypeParameterGenerator { return typeParameters.Length == 0 ? null - : SyntaxFactory.TypeParameterList( + : TypeParameterList( [.. typeParameters.Select(t => GenerateTypeParameter(t, info))]); } private static TypeParameterSyntax GenerateTypeParameter(ITypeParameterSymbol symbol, CSharpCodeGenerationContextInfo info) { var varianceKeyword = - symbol.Variance == VarianceKind.In ? SyntaxFactory.Token(SyntaxKind.InKeyword) : - symbol.Variance == VarianceKind.Out ? SyntaxFactory.Token(SyntaxKind.OutKeyword) : default; + symbol.Variance == VarianceKind.In ? Token(SyntaxKind.InKeyword) : + symbol.Variance == VarianceKind.Out ? Token(SyntaxKind.OutKeyword) : default; - return SyntaxFactory.TypeParameter( + return TypeParameter( AttributeGenerator.GenerateAttributeLists(symbol.GetAttributes(), info), varianceKeyword, symbol.Name.ToIdentifierToken()); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ExpressionSyntaxExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ExpressionSyntaxExtensions.cs index 75dcffa498b64..d8edb44cd813f 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ExpressionSyntaxExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ExpressionSyntaxExtensions.cs @@ -11,6 +11,8 @@ namespace Microsoft.CodeAnalysis.CSharp.Extensions; +using static SyntaxFactory; + internal static partial class ExpressionSyntaxExtensions { public static ExpressionSyntax Parenthesize( @@ -55,11 +57,11 @@ private static ExpressionSyntax ParenthesizeWorker( { var withoutTrivia = expression.WithoutTrivia(); var parenthesized = includeElasticTrivia - ? SyntaxFactory.ParenthesizedExpression(withoutTrivia) - : SyntaxFactory.ParenthesizedExpression( - SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.OpenParenToken, SyntaxTriviaList.Empty), + ? ParenthesizedExpression(withoutTrivia) + : ParenthesizedExpression( + Token(SyntaxTriviaList.Empty, SyntaxKind.OpenParenToken, SyntaxTriviaList.Empty), withoutTrivia, - SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, SyntaxTriviaList.Empty)); + Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, SyntaxTriviaList.Empty)); return parenthesized.WithTriviaFrom(expression); } @@ -69,11 +71,11 @@ public static PatternSyntax Parenthesize( { var withoutTrivia = pattern.WithoutTrivia(); var parenthesized = includeElasticTrivia - ? SyntaxFactory.ParenthesizedPattern(withoutTrivia) - : SyntaxFactory.ParenthesizedPattern( - SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.OpenParenToken, SyntaxTriviaList.Empty), + ? ParenthesizedPattern(withoutTrivia) + : ParenthesizedPattern( + Token(SyntaxTriviaList.Empty, SyntaxKind.OpenParenToken, SyntaxTriviaList.Empty), withoutTrivia, - SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, SyntaxTriviaList.Empty)); + Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, SyntaxTriviaList.Empty)); var result = parenthesized.WithTriviaFrom(pattern); return addSimplifierAnnotation @@ -86,7 +88,7 @@ public static CastExpressionSyntax Cast( ITypeSymbol targetType) { var parenthesized = expression.Parenthesize(); - var castExpression = SyntaxFactory.CastExpression( + var castExpression = CastExpression( targetType.GenerateTypeSyntax(), parenthesized.WithoutTrivia()).WithTriviaFrom(parenthesized); return castExpression.WithAdditionalAnnotations(Simplifier.Annotation); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeParameterSymbolExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeParameterSymbolExtensions.cs index 37d8030e3dcda..27e8300214536 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeParameterSymbolExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeParameterSymbolExtensions.cs @@ -10,6 +10,8 @@ namespace Microsoft.CodeAnalysis.CSharp.Extensions; +using static SyntaxFactory; + internal static class ITypeParameterSymbolExtensions { public static SyntaxList GenerateConstraintClauses( @@ -39,19 +41,19 @@ private static void AddConstraintClauses( if (typeParameter.HasReferenceTypeConstraint) { - constraints.Add(SyntaxFactory.ClassOrStructConstraint(SyntaxKind.ClassConstraint)); + constraints.Add(ClassOrStructConstraint(SyntaxKind.ClassConstraint)); } else if (typeParameter.HasUnmanagedTypeConstraint) { - constraints.Add(SyntaxFactory.TypeConstraint(SyntaxFactory.IdentifierName("unmanaged"))); + constraints.Add(TypeConstraint(IdentifierName("unmanaged"))); } else if (typeParameter.HasValueTypeConstraint) { - constraints.Add(SyntaxFactory.ClassOrStructConstraint(SyntaxKind.StructConstraint)); + constraints.Add(ClassOrStructConstraint(SyntaxKind.StructConstraint)); } else if (typeParameter.HasNotNullConstraint) { - constraints.Add(SyntaxFactory.TypeConstraint(SyntaxFactory.IdentifierName("notnull"))); + constraints.Add(TypeConstraint(IdentifierName("notnull"))); } var constraintTypes = @@ -63,13 +65,13 @@ private static void AddConstraintClauses( { if (type.SpecialType != SpecialType.System_Object) { - constraints.Add(SyntaxFactory.TypeConstraint(type.GenerateTypeSyntax())); + constraints.Add(TypeConstraint(type.GenerateTypeSyntax())); } } if (typeParameter.HasConstructorConstraint) { - constraints.Add(SyntaxFactory.ConstructorConstraint()); + constraints.Add(ConstructorConstraint()); } if (constraints.Count == 0) @@ -77,7 +79,7 @@ private static void AddConstraintClauses( return; } - clauses.Add(SyntaxFactory.TypeParameterConstraintClause( + clauses.Add(TypeParameterConstraintClause( typeParameter.Name.ToIdentifierName(), [.. constraints])); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.ExpressionSyntaxGeneratorVisitor.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.ExpressionSyntaxGeneratorVisitor.cs index 7421eed99f672..c0e844d2cb548 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.ExpressionSyntaxGeneratorVisitor.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.ExpressionSyntaxGeneratorVisitor.cs @@ -8,6 +8,8 @@ namespace Microsoft.CodeAnalysis.CSharp.Extensions; +using static SyntaxFactory; + internal partial class ITypeSymbolExtensions { private class ExpressionSyntaxGeneratorVisitor : SymbolVisitor @@ -29,7 +31,7 @@ public override ExpressionSyntax DefaultVisit(ISymbol symbol) private static TExpressionSyntax AddInformationTo(TExpressionSyntax syntax, ISymbol symbol) where TExpressionSyntax : ExpressionSyntax { - syntax = syntax.WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker).WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker); + syntax = syntax.WithPrependedLeadingTrivia(ElasticMarker).WithAppendedTrailingTrivia(ElasticMarker); syntax = syntax.WithAdditionalAnnotations(SymbolAnnotation.Create(symbol)); return syntax; @@ -64,8 +66,8 @@ public override ExpressionSyntax VisitNamedType(INamedTypeSymbol symbol) if (symbol.TypeKind != TypeKind.Error) { return AddInformationTo( - SyntaxFactory.AliasQualifiedName( - SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)), + AliasQualifiedName( + IdentifierName(Token(SyntaxKind.GlobalKeyword)), simpleNameSyntax), symbol); } } @@ -90,8 +92,8 @@ public override ExpressionSyntax VisitNamespace(INamespaceSymbol symbol) if (symbol.ContainingNamespace.IsGlobalNamespace) { return AddInformationTo( - SyntaxFactory.AliasQualifiedName( - SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)), + AliasQualifiedName( + IdentifierName(Token(SyntaxKind.GlobalKeyword)), syntax), symbol); } else @@ -104,7 +106,7 @@ public override ExpressionSyntax VisitNamespace(INamespaceSymbol symbol) private static MemberAccessExpressionSyntax CreateMemberAccessExpression( ISymbol symbol, ExpressionSyntax container, SimpleNameSyntax syntax) { - return AddInformationTo(SyntaxFactory.MemberAccessExpression( + return AddInformationTo(MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, container, syntax), symbol); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.TypeSyntaxGeneratorVisitor.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.TypeSyntaxGeneratorVisitor.cs index 5629bbcf2e7d0..48be9de69ce9b 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.TypeSyntaxGeneratorVisitor.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.TypeSyntaxGeneratorVisitor.cs @@ -17,6 +17,8 @@ namespace Microsoft.CodeAnalysis.CSharp.Extensions; +using static SyntaxFactory; + internal partial class ITypeSymbolExtensions { private class TypeSyntaxGeneratorVisitor : SymbolVisitor @@ -38,7 +40,7 @@ public override TypeSyntax DefaultVisit(ISymbol node) private static TTypeSyntax AddInformationTo(TTypeSyntax syntax, ISymbol symbol) where TTypeSyntax : TypeSyntax { - syntax = syntax.WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker).WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker); + syntax = syntax.WithPrependedLeadingTrivia(ElasticMarker).WithAppendedTrailingTrivia(ElasticMarker); syntax = syntax.WithAdditionalAnnotations(SymbolAnnotation.Create(symbol)); return syntax; @@ -91,17 +93,17 @@ public override TypeSyntax VisitArrayType(IArrayTypeSymbol symbol) var arrayType = symbol; while (arrayType != null && !arrayType.Equals(underlyingType)) { - ranks.Add(SyntaxFactory.ArrayRankSpecifier( - [.. Enumerable.Repeat(SyntaxFactory.OmittedArraySizeExpression(), arrayType.Rank)])); + ranks.Add(ArrayRankSpecifier( + [.. Enumerable.Repeat(OmittedArraySizeExpression(), arrayType.Rank)])); arrayType = arrayType.ElementType as IArrayTypeSymbol; } - TypeSyntax arrayTypeSyntax = SyntaxFactory.ArrayType(elementTypeSyntax, [.. ranks]); + TypeSyntax arrayTypeSyntax = ArrayType(elementTypeSyntax, [.. ranks]); if (symbol.NullableAnnotation == NullableAnnotation.Annotated) { - arrayTypeSyntax = SyntaxFactory.NullableType(arrayTypeSyntax); + arrayTypeSyntax = NullableType(arrayTypeSyntax); } return AddInformationTo(arrayTypeSyntax, symbol); @@ -109,9 +111,9 @@ public override TypeSyntax VisitArrayType(IArrayTypeSymbol symbol) public override TypeSyntax VisitDynamicType(IDynamicTypeSymbol symbol) { - var typeSyntax = SyntaxFactory.IdentifierName("dynamic"); + var typeSyntax = IdentifierName("dynamic"); return symbol.NullableAnnotation is NullableAnnotation.Annotated - ? AddInformationTo(SyntaxFactory.NullableType(typeSyntax), symbol) + ? AddInformationTo(NullableType(typeSyntax), symbol) : AddInformationTo(typeSyntax, symbol); } @@ -119,7 +121,7 @@ public static bool TryCreateNativeIntegerType(INamedTypeSymbol symbol, [NotNullW { if (symbol.IsNativeIntegerType) { - syntax = SyntaxFactory.IdentifierName(symbol.SpecialType == SpecialType.System_IntPtr ? "nint" : "nuint"); + syntax = IdentifierName(symbol.SpecialType == SpecialType.System_IntPtr ? "nint" : "nuint"); return true; } @@ -151,24 +153,24 @@ public override TypeSyntax VisitFunctionPointerType(IFunctionPointerTypeSymbol s _ => throw ExceptionUtilities.UnexpectedValue(symbol.Signature.CallingConvention), }; - callingConventionSyntax = SyntaxFactory.FunctionPointerCallingConvention( - SyntaxFactory.Token(SyntaxKind.UnmanagedKeyword), + callingConventionSyntax = FunctionPointerCallingConvention( + Token(SyntaxKind.UnmanagedKeyword), conventionsList is object - ? SyntaxFactory.FunctionPointerUnmanagedCallingConventionList([.. conventionsList]) + ? FunctionPointerUnmanagedCallingConventionList([.. conventionsList]) : null); static FunctionPointerUnmanagedCallingConventionSyntax GetConventionForString(string identifier) - => SyntaxFactory.FunctionPointerUnmanagedCallingConvention(SyntaxFactory.Identifier(identifier)); + => FunctionPointerUnmanagedCallingConvention(Identifier(identifier)); } var parameters = symbol.Signature.Parameters.Select(p => (p.Type, RefKindModifiers: CSharpSyntaxGeneratorInternal.GetParameterModifiers(p.RefKind))) .Concat([( Type: symbol.Signature.ReturnType, RefKindModifiers: CSharpSyntaxGeneratorInternal.GetParameterModifiers(symbol.Signature.RefKind, forFunctionPointerReturnParameter: true))]) - .SelectAsArray(t => SyntaxFactory.FunctionPointerParameter(t.Type.GenerateTypeSyntax()).WithModifiers(t.RefKindModifiers)); + .SelectAsArray(t => FunctionPointerParameter(t.Type.GenerateTypeSyntax()).WithModifiers(t.RefKindModifiers)); return AddInformationTo( - SyntaxFactory.FunctionPointerType(callingConventionSyntax, SyntaxFactory.FunctionPointerParameterList([.. parameters])), symbol); + FunctionPointerType(callingConventionSyntax, FunctionPointerParameterList([.. parameters])), symbol); } public TypeSyntax CreateSimpleTypeSyntax(INamedTypeSymbol symbol) @@ -201,31 +203,31 @@ public TypeSyntax CreateSimpleTypeSyntax(INamedTypeSymbol symbol) } var typeArguments = symbol.IsUnboundGenericType - ? Enumerable.Repeat((TypeSyntax)SyntaxFactory.OmittedTypeArgument(), symbol.TypeArguments.Length) + ? Enumerable.Repeat((TypeSyntax)OmittedTypeArgument(), symbol.TypeArguments.Length) : symbol.TypeArguments.SelectAsArray(t => t.GenerateTypeSyntax()); - return SyntaxFactory.GenericName( + return GenericName( symbol.Name.ToIdentifierToken(), - SyntaxFactory.TypeArgumentList([.. typeArguments])); + TypeArgumentList([.. typeArguments])); } public static QualifiedNameSyntax CreateSystemObject() { - return SyntaxFactory.QualifiedName( - SyntaxFactory.AliasQualifiedName( + return QualifiedName( + AliasQualifiedName( CreateGlobalIdentifier(), - SyntaxFactory.IdentifierName("System")), - SyntaxFactory.IdentifierName("Object")); + IdentifierName("System")), + IdentifierName("Object")); } private static IdentifierNameSyntax CreateGlobalIdentifier() - => SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)); + => IdentifierName(Token(SyntaxKind.GlobalKeyword)); private static TypeSyntax? TryCreateSpecializedNamedTypeSyntax(INamedTypeSymbol symbol) { if (symbol.SpecialType == SpecialType.System_Void) { - return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)); + return PredefinedType(Token(SyntaxKind.VoidKeyword)); } if (symbol.IsTupleType && symbol.TupleElements.Length >= 2) @@ -240,7 +242,7 @@ private static IdentifierNameSyntax CreateGlobalIdentifier() if (innerType.TypeKind != TypeKind.Pointer) { return AddInformationTo( - SyntaxFactory.NullableType(innerType.GenerateTypeSyntax()), symbol); + NullableType(innerType.GenerateTypeSyntax()), symbol); } } @@ -253,11 +255,11 @@ private static TupleTypeSyntax CreateTupleTypeSyntax(INamedTypeSymbol symbol) foreach (var element in symbol.TupleElements) { - var name = element.IsImplicitlyDeclared ? default : SyntaxFactory.Identifier(element.Name); - list = list.Add(SyntaxFactory.TupleElement(element.Type.GenerateTypeSyntax(), name)); + var name = element.IsImplicitlyDeclared ? default : Identifier(element.Name); + list = list.Add(TupleElement(element.Type.GenerateTypeSyntax(), name)); } - return AddInformationTo(SyntaxFactory.TupleType(list), symbol); + return AddInformationTo(TupleType(list), symbol); } public override TypeSyntax VisitNamedType(INamedTypeSymbol symbol) @@ -278,7 +280,7 @@ public override TypeSyntax VisitNamedType(INamedTypeSymbol symbol) if (containingTypeSyntax is NameSyntax name) { typeSyntax = AddInformationTo( - SyntaxFactory.QualifiedName(name, simpleNameSyntax), + QualifiedName(name, simpleNameSyntax), symbol); } else @@ -299,7 +301,7 @@ public override TypeSyntax VisitNamedType(INamedTypeSymbol symbol) else { var container = symbol.ContainingNamespace.Accept(this)!; - typeSyntax = AddInformationTo(SyntaxFactory.QualifiedName( + typeSyntax = AddInformationTo(QualifiedName( (NameSyntax)container, simpleNameSyntax), symbol); } @@ -309,7 +311,7 @@ public override TypeSyntax VisitNamedType(INamedTypeSymbol symbol) { // value type with nullable annotation may be composed from unconstrained nullable generic // doesn't mean nullable value type in this case - typeSyntax = AddInformationTo(SyntaxFactory.NullableType(typeSyntax), symbol); + typeSyntax = AddInformationTo(NullableType(typeSyntax), symbol); } return typeSyntax; @@ -330,7 +332,7 @@ public override TypeSyntax VisitNamespace(INamespaceSymbol symbol) else { var container = symbol.ContainingNamespace.Accept(this)!; - return AddInformationTo(SyntaxFactory.QualifiedName( + return AddInformationTo(QualifiedName( (NameSyntax)container, syntax), symbol); } @@ -343,7 +345,7 @@ public override TypeSyntax VisitNamespace(INamespaceSymbol symbol) private static TypeSyntax AddGlobalAlias(INamespaceOrTypeSymbol symbol, SimpleNameSyntax syntax) { return AddInformationTo( - SyntaxFactory.AliasQualifiedName( + AliasQualifiedName( CreateGlobalIdentifier(), syntax), symbol); } @@ -353,7 +355,7 @@ public override TypeSyntax VisitPointerType(IPointerTypeSymbol symbol) ThrowIfNameOnly(); return AddInformationTo( - SyntaxFactory.PointerType(symbol.PointedAtType.GenerateTypeSyntax()), + PointerType(symbol.PointedAtType.GenerateTypeSyntax()), symbol); } @@ -364,7 +366,7 @@ public override TypeSyntax VisitTypeParameter(ITypeParameterSymbol symbol) { // value type with nullable annotation may be composed from unconstrained nullable generic // doesn't mean nullable value type in this case - typeSyntax = AddInformationTo(SyntaxFactory.NullableType(typeSyntax), symbol); + typeSyntax = AddInformationTo(NullableType(typeSyntax), symbol); } return typeSyntax; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.cs index cd4295a86059d..1ced3ad6bc222 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.cs @@ -4,8 +4,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -19,6 +17,8 @@ namespace Microsoft.CodeAnalysis.CSharp.Extensions; +using static SyntaxFactory; + internal static partial class ITypeSymbolExtensions { /// if only normal name-syntax nodes should be returned. @@ -42,7 +42,7 @@ private static TypeSyntax GenerateTypeSyntax( { // something with an anonymous type can only be represented with 'var', regardless // of what the user's preferences might be. - return SyntaxFactory.IdentifierName("var"); + return IdentifierName("var"); } var syntax = containsAnonymousType @@ -74,21 +74,21 @@ public static TypeSyntax GenerateRefTypeSyntax( this INamespaceOrTypeSymbol symbol) { var underlyingType = GenerateTypeSyntax(symbol) - .WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker) + .WithPrependedLeadingTrivia(ElasticMarker) .WithAdditionalAnnotations(Simplifier.Annotation); - var refKeyword = SyntaxFactory.Token(SyntaxKind.RefKeyword); - return SyntaxFactory.RefType(refKeyword, underlyingType); + var refKeyword = Token(SyntaxKind.RefKeyword); + return RefType(refKeyword, underlyingType); } public static TypeSyntax GenerateRefReadOnlyTypeSyntax( this INamespaceOrTypeSymbol symbol) { var underlyingType = GenerateTypeSyntax(symbol) - .WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker) + .WithPrependedLeadingTrivia(ElasticMarker) .WithAdditionalAnnotations(Simplifier.Annotation); - var refKeyword = SyntaxFactory.Token(SyntaxKind.RefKeyword); - var readOnlyKeyword = SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword); - return SyntaxFactory.RefType(refKeyword, readOnlyKeyword, underlyingType); + var refKeyword = Token(SyntaxKind.RefKeyword); + var readOnlyKeyword = Token(SyntaxKind.ReadOnlyKeyword); + return RefType(refKeyword, readOnlyKeyword, underlyingType); } public static bool ContainingTypesOrSelfHasUnsafeKeyword(this ITypeSymbol containingType) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpReplaceDiscardDeclarationsWithAssignmentsService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpReplaceDiscardDeclarationsWithAssignmentsService.cs index 556f6d97f2316..6de1859a1714d 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpReplaceDiscardDeclarationsWithAssignmentsService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpReplaceDiscardDeclarationsWithAssignmentsService.cs @@ -14,7 +14,6 @@ using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; -using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.ReplaceDiscardDeclarationsWithAssignments; @@ -23,6 +22,8 @@ namespace Microsoft.CodeAnalysis.CSharp.ReplaceDiscardDeclarationsWithAssignments; +using static SyntaxFactory; + [ExportLanguageService(typeof(IReplaceDiscardDeclarationsWithAssignmentsService), LanguageNames.CSharp), Shared] internal sealed class CSharpReplaceDiscardDeclarationsWithAssignmentsService : IReplaceDiscardDeclarationsWithAssignmentsService { @@ -68,13 +69,13 @@ public async Task ReplaceAsync( // "M(out var _)" => "M(out _)" // "M(out int _)" => "M(out _)" - var discardToken = SyntaxFactory.Identifier( + var discardToken = Identifier( leading: declarationExpression.GetLeadingTrivia(), contextualKind: SyntaxKind.UnderscoreToken, text: discardSyntax.UnderscoreToken.Text, valueText: discardSyntax.UnderscoreToken.ValueText, trailing: declarationExpression.GetTrailingTrivia()); - var replacementNode = SyntaxFactory.IdentifierName(discardToken); + var replacementNode = IdentifierName(discardToken); // Removing explicit type is possible only if there are no overloads of the method with same parameter. // For example, if method "M" had overloads with signature "void M(int x)" and "void M(char x)", @@ -95,7 +96,7 @@ public async Task ReplaceAsync( declarationPattern.Parent is IsPatternExpressionSyntax isPatternExpression) { // "x is int _" => "x is int" - var replacementNode = SyntaxFactory.BinaryExpression( + var replacementNode = BinaryExpression( kind: SyntaxKind.IsExpression, left: isPatternExpression.Expression, operatorToken: isPatternExpression.IsKeyword, @@ -211,7 +212,7 @@ private void ProcessDeclarationStatement() } else { - _editor.ReplaceNode(_localDeclarationStatement, SyntaxFactory.Block(_statementsBuilder)); + _editor.ReplaceNode(_localDeclarationStatement, Block(_statementsBuilder)); } } @@ -224,8 +225,8 @@ private void GenerateDeclarationStatementForCurrentNonDiscardVariables() // which are split by a single assignment statement "_ = M();" if (_currentNonDiscardVariables.Count > 0) { - var statement = SyntaxFactory.LocalDeclarationStatement( - SyntaxFactory.VariableDeclaration(_localDeclarationStatement.Declaration.Type, _currentNonDiscardVariables)) + var statement = LocalDeclarationStatement( + VariableDeclaration(_localDeclarationStatement.Declaration.Type, _currentNonDiscardVariables)) .WithAdditionalAnnotations(Formatter.Annotation); _statementsBuilder.Add(statement); _currentNonDiscardVariables = []; @@ -241,10 +242,10 @@ private void GenerateAssignmentForDiscardVariable(VariableDeclaratorSyntax varia if (variable.Initializer != null) { _statementsBuilder.Add( - SyntaxFactory.ExpressionStatement( - SyntaxFactory.AssignmentExpression( + ExpressionStatement( + AssignmentExpression( kind: SyntaxKind.SimpleAssignmentExpression, - left: SyntaxFactory.IdentifierName(variable.Identifier), + left: IdentifierName(variable.Identifier), operatorToken: variable.Initializer.EqualsToken, right: variable.Initializer.Value)) .WithAdditionalAnnotations(Formatter.Annotation));