private static async Task <Document> DeclareExplicitValueAsync( Document document, EnumDeclarationSyntax enumDeclaration, INamedTypeSymbol enumSymbol, ImmutableArray <ulong> values, SemanticModel semanticModel, CancellationToken cancellationToken) { bool isFlags = enumSymbol.HasAttribute(MetadataNames.System_FlagsAttribute); List <ulong> reservedValues = values.ToList(); SeparatedSyntaxList <EnumMemberDeclarationSyntax> members = enumDeclaration.Members; SeparatedSyntaxList <EnumMemberDeclarationSyntax> newMembers = members; for (int i = 0; i < members.Count; i++) { if (members[i].EqualsValue == null) { IFieldSymbol fieldSymbol = semanticModel.GetDeclaredSymbol(members[i], cancellationToken); ulong?value = null; if (isFlags) { Optional <ulong> optional = FlagsUtility <ulong> .Instance.GetUniquePowerOfTwo(reservedValues); if (optional.HasValue && ConvertHelpers.CanConvert(optional.Value, enumSymbol.EnumUnderlyingType.SpecialType)) { value = optional.Value; } } else { value = SymbolUtility.GetEnumValueAsUInt64(fieldSymbol.ConstantValue, enumSymbol); } if (value != null) { reservedValues.Add(value.Value); EqualsValueClauseSyntax equalsValue = EqualsValueClause(NumericLiteralExpression(value.Value, enumSymbol.EnumUnderlyingType.SpecialType)); EnumMemberDeclarationSyntax newMember = members[i].WithEqualsValue(equalsValue); newMembers = newMembers.ReplaceAt(i, newMember); } } } EnumDeclarationSyntax newEnumDeclaration = enumDeclaration.WithMembers(newMembers); return(await document.ReplaceNodeAsync(enumDeclaration, newEnumDeclaration, cancellationToken).ConfigureAwait(false)); }
public static Task <Document> RefactorAsync( Document document, InitializerExpressionSyntax initializer, CancellationToken cancellationToken) { SeparatedSyntaxList <ExpressionSyntax> expressions = initializer.Expressions; for (int i = 0; i < expressions.Count; i++) { expressions = expressions.ReplaceAt(i, CreateNewExpression((InitializerExpressionSyntax)expressions[i])); } InitializerExpressionSyntax newInitializer = initializer.WithExpressions(expressions); return(document.ReplaceNodeAsync(initializer, newInitializer, cancellationToken)); }
private static async Task <Document> SortEnumMembersAsync( Document document, EnumDeclarationSyntax enumDeclaration, CancellationToken cancellationToken) { SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); SpecialType enumSpecialType = semanticModel.GetDeclaredSymbol(enumDeclaration).EnumUnderlyingType.SpecialType; SeparatedSyntaxList <EnumMemberDeclarationSyntax> members = enumDeclaration.Members; SeparatedSyntaxList <EnumMemberDeclarationSyntax> newMembers = members .OrderBy(f => GetConstantValue(f, semanticModel, cancellationToken), EnumValueComparer.GetInstance(enumSpecialType)) .ToSeparatedSyntaxList(); if (AreSeparatedWithEmptyLine(members)) { for (int i = 0; i < newMembers.Count; i++) { newMembers = newMembers.ReplaceAt(i, newMembers[i].TrimLeadingTrivia()); } for (int i = 0; i < newMembers.Count - 1; i++) { SyntaxToken separator = newMembers.GetSeparator(i); newMembers = newMembers.ReplaceSeparator( separator, separator.TrimTrailingTrivia().AppendToTrailingTrivia(new SyntaxTrivia[] { NewLine(), NewLine() })); } } if (newMembers.SeparatorCount == members.SeparatorCount - 1) { SyntaxNodeOrTokenList newMembersWithSeparators = newMembers.GetWithSeparators(); newMembersWithSeparators = newMembersWithSeparators.Add(CommaToken()); newMembers = newMembersWithSeparators.ToSeparatedSyntaxList <EnumMemberDeclarationSyntax>(); } MemberDeclarationSyntax newNode = enumDeclaration .WithMembers(newMembers) .WithFormatterAnnotation(); return(await document.ReplaceNodeAsync(enumDeclaration, newNode, cancellationToken).ConfigureAwait(false)); }
private static InvocationExpressionSyntax GetNewInvocation(InvocationExpressionSyntax invocation) { ArgumentListSyntax argumentList = invocation.ArgumentList; SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments; if (arguments.Count == 1) { ArgumentSyntax argument = arguments[0]; arguments = arguments.ReplaceAt(0, argument.WithExpression(StringLiteralExpression("").WithTriviaFrom(argument.Expression))); } else { arguments = arguments.RemoveAt(0); } return(RefactoringHelper.ChangeInvokedMethodName(invocation, "Fail") .WithArgumentList(argumentList.WithArguments(arguments))); }
private static async Task <Document> RefactorAsync( Document document, EnumDeclarationSyntax enumDeclaration, INamedTypeSymbol enumSymbol, bool startFromHighestExistingValue, CancellationToken cancellationToken) { SeparatedSyntaxList <EnumMemberDeclarationSyntax> members = enumDeclaration.Members; SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); SpecialType specialType = enumSymbol.EnumUnderlyingType.SpecialType; List <object> values = GetExplicitValues(enumDeclaration, semanticModel, cancellationToken); for (int i = 0; i < members.Count; i++) { if (members[i].EqualsValue == null) { Optional <object> optional = FlagsUtility.GetUniquePowerOfTwo(specialType, values, startFromHighestExistingValue); if (optional.HasValue) { values.Add(optional.Value); EqualsValueClauseSyntax equalsValue = EqualsValueClause(CSharpFactory.LiteralExpression(optional.Value)); EnumMemberDeclarationSyntax newMember = members[i] .WithEqualsValue(equalsValue) .WithFormatterAnnotation(); members = members.ReplaceAt(i, newMember); } else { break; } } } EnumDeclarationSyntax newNode = enumDeclaration.WithMembers(members); return(await document.ReplaceNodeAsync(enumDeclaration, newNode, cancellationToken).ConfigureAwait(false)); }
private static async Task <Document> RefactorAsync( Document document, EnumDeclarationSyntax enumDeclaration, INamedTypeSymbol enumSymbol, ImmutableArray <ulong> values, bool startFromHighestExistingValue, CancellationToken cancellationToken) { SeparatedSyntaxList <EnumMemberDeclarationSyntax> members = enumDeclaration.Members; List <ulong> valuesList = values.ToList(); for (int i = 0; i < members.Count; i++) { if (members[i].EqualsValue == null) { Optional <ulong> optional = FlagsUtility <ulong> .Instance.GetUniquePowerOfTwo(valuesList, startFromHighestExistingValue); if (optional.HasValue && ConvertHelpers.CanConvertFromUInt64(optional.Value, enumSymbol.EnumUnderlyingType.SpecialType)) { valuesList.Add(optional.Value); EqualsValueClauseSyntax equalsValue = EqualsValueClause( Token(TriviaList(ElasticSpace), SyntaxKind.EqualsToken, TriviaList(ElasticSpace)), CSharpFactory.NumericLiteralExpression(optional.Value, enumSymbol.EnumUnderlyingType.SpecialType)); EnumMemberDeclarationSyntax newMember = members[i].WithEqualsValue(equalsValue); members = members.ReplaceAt(i, newMember); } else { break; } } } EnumDeclarationSyntax newNode = enumDeclaration.WithMembers(members); return(await document.ReplaceNodeAsync(enumDeclaration, newNode, cancellationToken).ConfigureAwait(false)); }
public static Task <Document> RefactorAsync( Document document, ParenthesizedLambdaExpressionSyntax parenthesizedLambda, MemberDeclarationSyntax memberDeclaration, TypeDeclarationSyntax typeDeclaration, string methodName, SemanticModel semanticModel, CancellationToken cancellationToken) { methodName = NameGenerator.Default.EnsureUniqueLocalName(methodName, semanticModel, parenthesizedLambda.SpanStart, cancellationToken: cancellationToken); MemberDeclarationSyntax newMemberDeclaration = memberDeclaration.ReplaceNode(parenthesizedLambda, IdentifierName(methodName).WithTriviaFrom(parenthesizedLambda)); IMethodSymbol lambdaSymbol = semanticModel.GetMethodSymbol(parenthesizedLambda, cancellationToken); ParameterListSyntax parameterList = parenthesizedLambda.ParameterList; SeparatedSyntaxList <ParameterSyntax> parameters = parameterList.Parameters; ImmutableArray <IParameterSymbol> parameterSymbols = lambdaSymbol.Parameters; parameters = parameters .ReplaceAt(0, AddTypeIfMissing(parameters[0], parameterSymbols[0])) .ReplaceAt(1, AddTypeIfMissing(parameters[1], parameterSymbols[1])); cancellationToken.ThrowIfCancellationRequested(); MethodDeclarationSyntax newMethodDeclaration = MethodDeclaration( (SyntaxInfo.ModifierListInfo(memberDeclaration).IsStatic) ? Modifiers.Private_Static() : Modifiers.Private(), VoidType(), Identifier(methodName).WithRenameAnnotation(), parameterList.WithParameters(parameters), CreateMethodBody(parenthesizedLambda.Body)) .WithFormatterAnnotation(); SyntaxList <MemberDeclarationSyntax> newMembers = typeDeclaration.Members.Replace(memberDeclaration, newMemberDeclaration); newMembers = MemberDeclarationInserter.Default.Insert(newMembers, newMethodDeclaration); return(document.ReplaceNodeAsync(typeDeclaration, typeDeclaration.WithMembers(newMembers), cancellationToken));
private static async Task <Document> OrderNamedArgumentsAsync( Document document, BaseArgumentListSyntax argumentList, CancellationToken cancellationToken) { SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); ImmutableArray <IParameterSymbol> parameters = semanticModel .GetSymbol(argumentList.Parent, cancellationToken) .ParametersOrDefault(); SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments; int firstIndex = OrderNamedArgumentsAnalyzer.IndexOfFirstFixableParameter(argumentList, arguments, semanticModel, cancellationToken); SeparatedSyntaxList <ArgumentSyntax> newArguments = arguments; for (int i = firstIndex; i < arguments.Count; i++) { IParameterSymbol parameter = parameters[i]; int index = arguments.IndexOf(f => f.NameColon?.Name.Identifier.ValueText == parameter.Name); Debug.Assert(index != -1, parameter.Name); if (index != -1 && index != i) { newArguments = newArguments.ReplaceAt(i, arguments[index]); } } BaseArgumentListSyntax newNode = argumentList .WithArguments(newArguments) .WithFormatterAnnotation(); return(await document.ReplaceNodeAsync(argumentList, newNode, cancellationToken).ConfigureAwait(false)); }
private static InitializerExpressionSyntax RemoveTrailingComma(InitializerExpressionSyntax initializer) { SeparatedSyntaxList <ExpressionSyntax> expressions = initializer.Expressions; SyntaxToken trailingComma = expressions.GetTrailingSeparator(); SeparatedSyntaxList <ExpressionSyntax> newExpressions = expressions.ReplaceSeparator( trailingComma, SyntaxFactory.MissingToken(SyntaxKind.CommaToken)); int lastIndex = expressions.Count - 1; SyntaxTriviaList newTrailingTrivia = expressions[lastIndex] .GetTrailingTrivia() .AddRange(trailingComma.LeadingTrivia) .AddRange(trailingComma.TrailingTrivia); ExpressionSyntax newExpression = newExpressions[lastIndex].WithTrailingTrivia(newTrailingTrivia); newExpressions = newExpressions.ReplaceAt(lastIndex, newExpression); return(initializer.WithExpressions(newExpressions)); }
private static Task <Document> RefactorAsync( Document document, EnumDeclarationSyntax enumDeclaration, SeparatedSyntaxListSelection <EnumMemberDeclarationSyntax> selection, CancellationToken cancellationToken) { SeparatedSyntaxList <EnumMemberDeclarationSyntax> members = enumDeclaration.Members; SeparatedSyntaxList <EnumMemberDeclarationSyntax> newMembers = members; for (int i = selection.StartIndex; i <= selection.EndIndex; i++) { EnumMemberDeclarationSyntax newMember = members[i] .WithEqualsValue(null) .WithTrailingTrivia(members[i].GetTrailingTrivia()) .WithFormatterAnnotation(); newMembers = newMembers.ReplaceAt(i, newMember); } EnumDeclarationSyntax newEnumDeclaration = enumDeclaration.WithMembers(newMembers); return(document.ReplaceNodeAsync(enumDeclaration, newEnumDeclaration, cancellationToken)); }
private static Task <Document> FormatInitializerOnSingleLineAsync( Document document, InitializerExpressionSyntax initializer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); SyntaxToken trailingComma = initializer.Expressions.GetTrailingSeparator(); if (trailingComma == default) { return(SyntaxFormatter.ToSingleLineAsync(document, initializer, cancellationToken)); } SyntaxNode parent = initializer.Parent; initializer = initializer .ReplaceWhitespace(SyntaxFactory.ElasticMarker, TextSpan.FromBounds(initializer.FullSpan.Start, initializer.Span.End)) .WithFormatterAnnotation(); SeparatedSyntaxList <ExpressionSyntax> expressions = initializer.Expressions; expressions = expressions.ReplaceAt(0, expressions.First().WithTrailingTrivia(SyntaxFactory.Space)); expressions = expressions.ReplaceSeparator(expressions.GetSeparator(0), SyntaxFactory.MissingToken(SyntaxKind.CommaToken)); initializer = initializer.WithExpressions(expressions); SyntaxNode newParent = GetNewParent(); return(document.ReplaceNodeAsync(parent, newParent, cancellationToken)); SyntaxNode GetNewParent() { switch (parent) { case ObjectCreationExpressionSyntax objectCreation: { objectCreation = objectCreation.WithInitializer(initializer); ArgumentListSyntax argumentList = objectCreation.ArgumentList; if (argumentList != null) { return(objectCreation.WithArgumentList(argumentList.WithoutTrailingTrivia())); } else { return(objectCreation.WithType(objectCreation.Type.WithoutTrailingTrivia())); } } case ArrayCreationExpressionSyntax arrayCreation: { return(arrayCreation .WithInitializer(initializer) .WithType(arrayCreation.Type.WithoutTrailingTrivia())); } case ImplicitArrayCreationExpressionSyntax implicitArrayCreation: { return(implicitArrayCreation .WithInitializer(initializer) .WithCloseBracketToken(implicitArrayCreation.CloseBracketToken.WithoutTrailingTrivia())); } } throw new InvalidOperationException(); } }
public static Task <Document> RefactorAsync( Document document, ParenthesizedLambdaExpressionSyntax parenthesizedLambda, MemberDeclarationSyntax memberDeclaration, TypeDeclarationSyntax typeDeclaration, string methodName, SemanticModel semanticModel, CancellationToken cancellationToken) { methodName = NameGenerator.Default.EnsureUniqueLocalName(methodName, semanticModel, parenthesizedLambda.SpanStart, cancellationToken: cancellationToken); MemberDeclarationSyntax newMemberDeclaration = memberDeclaration.ReplaceNode(parenthesizedLambda, IdentifierName(methodName).WithTriviaFrom(parenthesizedLambda)); IMethodSymbol lambdaSymbol = semanticModel.GetMethodSymbol(parenthesizedLambda, cancellationToken); ParameterListSyntax parameterList = parenthesizedLambda.ParameterList; SeparatedSyntaxList <ParameterSyntax> parameters = parameterList.Parameters; ImmutableArray <IParameterSymbol> parameterSymbols = lambdaSymbol.Parameters; parameters = parameters .ReplaceAt(0, AddTypeIfMissing(parameters[0], parameterSymbols[0])) .ReplaceAt(1, AddTypeIfMissing(parameters[1], parameterSymbols[1])); cancellationToken.ThrowIfCancellationRequested(); MethodDeclarationSyntax newMethodDeclaration = MethodDeclaration( (SyntaxInfo.ModifierListInfo(memberDeclaration).IsStatic) ? Modifiers.Private_Static() : Modifiers.Private(), VoidType(), Identifier(methodName).WithRenameAnnotation(), parameterList.WithParameters(parameters), CreateMethodBody(parenthesizedLambda.Body)).WithFormatterAnnotation(); SyntaxList <MemberDeclarationSyntax> newMembers = typeDeclaration.Members.Replace(memberDeclaration, newMemberDeclaration); newMembers = MemberDeclarationInserter.Default.Insert(newMembers, newMethodDeclaration); return(document.ReplaceNodeAsync(typeDeclaration, typeDeclaration.WithMembers(newMembers), cancellationToken)); BlockSyntax CreateMethodBody(CSharpSyntaxNode lambdaBody) { switch (lambdaBody) { case BlockSyntax block: return(block); case ExpressionSyntax expression: return(Block(ExpressionStatement(expression))); default: return(Block()); } } ParameterSyntax AddTypeIfMissing(ParameterSyntax parameter, IParameterSymbol parameterSymbol) { TypeSyntax type = parameter.Type; if (type?.IsMissing == false) { return(parameter); } type = parameterSymbol.Type.ToMinimalTypeSyntax(semanticModel, typeDeclaration.OpenBraceToken.Span.End); return(parameter.WithType(type)); } }
private static async Task <Document> DeclareExplicitValueAsync( Document document, EnumDeclarationSyntax enumDeclaration, INamedTypeSymbol enumSymbol, bool isFlags, bool useBitShift, ImmutableArray <ulong> values, SemanticModel semanticModel, CancellationToken cancellationToken) { List <ulong> reservedValues = values.ToList(); SeparatedSyntaxList <EnumMemberDeclarationSyntax> members = enumDeclaration.Members; SeparatedSyntaxList <EnumMemberDeclarationSyntax> newMembers = members; for (int i = 0; i < members.Count; i++) { if (members[i].EqualsValue == null) { IFieldSymbol fieldSymbol = semanticModel.GetDeclaredSymbol(members[i], cancellationToken); ulong?value = null; if (isFlags) { Optional <ulong> optional = FlagsUtility <ulong> .Instance.GetUniquePowerOfTwo(reservedValues); if (optional.HasValue && ConvertHelpers.CanConvertFromUInt64(optional.Value, enumSymbol.EnumUnderlyingType.SpecialType)) { value = optional.Value; } } else { value = SymbolUtility.GetEnumValueAsUInt64(fieldSymbol.ConstantValue, enumSymbol); } if (value != null) { reservedValues.Add(value.Value); ExpressionSyntax expression; if (useBitShift && value.Value > 1) { var power = (int)Math.Log(Convert.ToDouble(value.Value), 2); expression = LeftShiftExpression(NumericLiteralExpression(1), NumericLiteralExpression(power)); } else { expression = NumericLiteralExpression(value.Value, enumSymbol.EnumUnderlyingType.SpecialType); } EnumMemberDeclarationSyntax newMember = members[i].Update( members[i].AttributeLists, members[i].Modifiers, members[i].Identifier.WithoutTrailingTrivia(), EqualsValueClause(expression).WithTrailingTrivia(members[i].Identifier.TrailingTrivia)); newMembers = newMembers.ReplaceAt(i, newMember); } } } EnumDeclarationSyntax newEnumDeclaration = enumDeclaration.WithMembers(newMembers); return(await document.ReplaceNodeAsync(enumDeclaration, newEnumDeclaration, cancellationToken).ConfigureAwait(false)); }