Beispiel #1
0
        public static LocalDeclarationStatementSyntax DeclareLocalVariable(Type variableType, string name,
                                                                           ExpressionSyntax initValue = null,
                                                                           VariableDeclarationType variableDeclarationType = VariableDeclarationType.ExplicitType)
        {
            VariableDeclaratorSyntax varDeclarator = SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(name));

            if (variableType.IsVsArrayType())
            {
                ObjectCreationExpressionSyntax exp = SyntaxFactory.ObjectCreationExpression(variableType.ToTypeSyntax())
                                                     .WithArgumentList(SyntaxFactory.ArgumentList());
                varDeclarator = varDeclarator.WithInitializer(SyntaxFactory.EqualsValueClause(exp));
            }
            else if (initValue != null)
            {
                varDeclarator = varDeclarator.WithInitializer(SyntaxFactory.EqualsValueClause(initValue));
            }

            VariableDeclarationSyntax varDeclaration = variableDeclarationType == VariableDeclarationType.InferredType
                ? SyntaxFactory.VariableDeclaration(SyntaxFactory.IdentifierName("var"))
                : SyntaxFactory.VariableDeclaration(variableType.ToTypeSyntax());

            varDeclaration = varDeclaration.WithVariables(SyntaxFactory.SingletonSeparatedList(varDeclarator));

            return(SyntaxFactory.LocalDeclarationStatement(varDeclaration));
        }
Beispiel #2
0
        public static VariableDeclaratorSyntax WithInitialValue(
            this VariableDeclaratorSyntax parentSyntax,
            ExpressionSyntax childSyntax)
        {
            if (childSyntax == null)
            {
                return(parentSyntax.WithInitializer(null));
            }

            EqualsValueClauseSyntax valueSyntax = parentSyntax.Initializer;

            return(valueSyntax == null?
                   parentSyntax.WithInitializer(SyntaxFactory.EqualsValueClause(childSyntax)) :
                       parentSyntax.WithInitializer(parentSyntax.Initializer.WithValue(childSyntax)));
        }
Beispiel #3
0
        private static VariableDeclaratorSyntax FieldConstDeclaration(ConstDeclaration constDeclaration,
                                                                      VariableDeclaratorSyntax varDeclarator)
        {
            var assignment =
                constDeclaration.Type.Type switch
            {
                BaseTypes.Int => SyntaxFactory.EqualsValueClause(
                    SyntaxFactory.LiteralExpression(
                        SyntaxKind.NumericLiteralExpression,
                        SyntaxFactory.Literal(constDeclaration.Value.ToInt32()))),
                BaseTypes.Bool => SyntaxFactory.EqualsValueClause(
                    SyntaxFactory.LiteralExpression(
                        constDeclaration.Value.ToBool()
                                ? SyntaxKind.TrueLiteralExpression
                                : SyntaxKind.FalseLiteralExpression)),
                BaseTypes.Real => SyntaxFactory.EqualsValueClause(
                    SyntaxFactory.LiteralExpression(
                        SyntaxKind.NumericLiteralExpression,
                        SyntaxFactory.Literal(constDeclaration.Value.ToDouble()))),
                _ => throw new ArgumentException(
                          "Cannot handle type " + Enum.GetName(typeof(BaseTypes), constDeclaration.Type.Type),
                          nameof(constDeclaration))
            };

            return(varDeclarator.WithInitializer(assignment));
        }
        /// <summary>
        /// System.Object paramName [= ...];
        /// </summary>
        protected internal virtual LocalDeclarationStatementSyntax DeclareLocal(ITypeInfo type, string name, ExpressionSyntax?initializer = null)
        {
            VariableDeclaratorSyntax declarator = VariableDeclarator
                                                  (
                identifier: Identifier(name)
                                                  );

            if (initializer != null)
            {
                declarator = declarator.WithInitializer
                             (
                    initializer: EqualsValueClause
                    (
                        initializer
                    )
                             );
            }

            return(LocalDeclarationStatement
                   (
                       declaration: VariableDeclaration
                       (
                           type: CreateType(type),
                           variables: SeparatedList(new List <VariableDeclaratorSyntax>
            {
                declarator
            })
                       )
                   ));
        }
Beispiel #5
0
        protected LocalDeclarationStatementSyntax ResolveLocal(ITypeInfo type, string name, ExpressionSyntax?initializer = null)
        {
            VariableDeclaratorSyntax declarator = VariableDeclarator
                                                  (
                identifier: Identifier(name)
                                                  );

            if (initializer is not null)
            {
                declarator = declarator.WithInitializer
                             (
                    initializer: EqualsValueClause
                    (
                        initializer
                    )
                             );
            }

            return(LocalDeclarationStatement
                   (
                       declaration: VariableDeclaration
                       (
                           type: ResolveType(type),
                           variables: SingletonSeparatedList(declarator)
                       )
                   ));
        }
Beispiel #6
0
            public override SyntaxNode VisitVariableDeclarator(VariableDeclaratorSyntax node)
            {
                if (node.Initializer == null)
                {
                    return(base.VisitVariableDeclarator(node));
                }
                if (node.Parent is VariableDeclarationSyntax == false)
                {
                    return(base.VisitVariableDeclarator(node));
                }
                if (node.Parent.Parent is FieldDeclarationSyntax == false)
                {
                    return(base.VisitVariableDeclarator(node));
                }
                if ((node.Parent.Parent as FieldDeclarationSyntax).Modifiers.Any(x => x.ValueText == "const"))
                {
                    return(base.VisitVariableDeclarator(node));
                }

                var value = node.Initializer.Value;

                if (value is LiteralExpressionSyntax)
                {
                    var variableTypeNode = GetSystemTypeOfTypeNode((node.Parent as VariableDeclarationSyntax));
                    var valueObj         = (value as LiteralExpressionSyntax).Token.Value;

                    if (TypesMapItem.GetAllPredefinedTypesDic().ContainsKey(variableTypeNode))
                    {
                        var typeItem = TypesMapItem.GetAllPredefinedTypesDic()[variableTypeNode];
                        if ((typeItem.DefaultValue == null && valueObj != null) || (typeItem.DefaultValue != null && !typeItem.DefaultValue.Equals(valueObj)))
                        {
                            return(base.VisitVariableDeclarator(node));
                        }
                    }
                    else
                    {
                        if (valueObj != null)
                        {
                            return(base.VisitVariableDeclarator(node));
                        }
                    }

                    node = node.WithInitializer(null).WithoutTrailingTrivia();
                }
                //else if (value is DefaultExpressionSyntax)
                //{
                //    node = node.WithInitializer(null).WithoutTrailingTrivia();
                //}
                //else if (value is ObjectCreationExpressionSyntax)
                //{
                //    if (variableTypeNode.IsKind(SyntaxKind.PredefinedType))
                //    {
                //        node = node.WithInitializer(null).WithoutTrailingTrivia();
                //    }
                //}

                return(base.VisitVariableDeclarator(node));
            }
        /// <summary>
        /// Declares the variables in the field along with their initializers.
        /// <para>In the example "private int testInt = 0", "testInt" would be the variable. </para>
        /// </summary>
        private static VariableDeclaratorSyntax CreateVariableDeclaratorSyntax(FieldGenerationData data)
        {
            VariableDeclaratorSyntax declaratorSyntax = SyntaxFactory.VariableDeclarator(data.m_VariableName);

            if (!data.m_UseInitializer)
            {
                return(declaratorSyntax);
            }

            if (VariableTypeCheckerUtility.IsVariableInitializableWithoutNewKeyword(data.m_VariableType))
            {
                return(declaratorSyntax.WithInitializer(CreateFieldInitializer(data)));
            }
            else
            {
                return(declaratorSyntax.WithInitializer(CreateNewFieldInitializer(data)));
            }
        }
Beispiel #8
0
        public static Task <Document> RemoveRedundantAssignmentAfterLocalDeclarationAsync(
            Document document,
            VariableDeclaratorSyntax declarator,
            CancellationToken cancellationToken = default)
        {
            var declaration = (VariableDeclarationSyntax)declarator.Parent;

            var localDeclaration = (LocalDeclarationStatementSyntax)declaration.Parent;

            StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(localDeclaration);

            SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

            int index = statements.IndexOf(localDeclaration);

            StatementSyntax nextStatement = statements[index + 1];

            var expressionStatement = (ExpressionStatementSyntax)nextStatement;

            var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression;

            ExpressionSyntax right = assignment.Right;

            EqualsValueClauseSyntax initializer = declarator.Initializer;

            ExpressionSyntax value = initializer?.Value;

            VariableDeclaratorSyntax newDeclarator = (value != null)
                ? declarator.ReplaceNode(value, right)
                : declarator.WithInitializer(EqualsValueClause(right));

            LocalDeclarationStatementSyntax newLocalDeclaration = localDeclaration.ReplaceNode(declarator, newDeclarator);

            SyntaxTriviaList trailingTrivia = localDeclaration.GetTrailingTrivia();

            if (!trailingTrivia.IsEmptyOrWhitespace())
            {
                newLocalDeclaration = newLocalDeclaration.WithTrailingTrivia(trailingTrivia.Concat(nextStatement.GetTrailingTrivia()));
            }
            else
            {
                newLocalDeclaration = newLocalDeclaration.WithTrailingTrivia(nextStatement.GetTrailingTrivia());
            }

            SyntaxTriviaList leadingTrivia = nextStatement.GetLeadingTrivia();

            if (!leadingTrivia.IsEmptyOrWhitespace())
            {
                newLocalDeclaration = newLocalDeclaration.WithLeadingTrivia(newLocalDeclaration.GetLeadingTrivia().Concat(leadingTrivia));
            }

            SyntaxList <StatementSyntax> newStatements = statements
                                                         .Replace(localDeclaration, newLocalDeclaration)
                                                         .RemoveAt(index + 1);

            return(document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken));
        }
Beispiel #9
0
        public static Task <Document> RefactorAsync(
            Document document,
            VariableDeclaratorSyntax declarator,
            CancellationToken cancellationToken)
        {
            var declaration = (VariableDeclarationSyntax)declarator.Parent;

            var localDeclaration = (LocalDeclarationStatementSyntax)declaration.Parent;

            StatementContainer container = StatementContainer.Create(localDeclaration);

            SyntaxList <StatementSyntax> statements = container.Statements;

            int index = statements.IndexOf(localDeclaration);

            StatementSyntax nextStatement = statements[index + 1];

            var expressionStatement = (ExpressionStatementSyntax)nextStatement;

            var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression;

            ExpressionSyntax right = assignment.Right;

            EqualsValueClauseSyntax initializer = declarator.Initializer;

            ExpressionSyntax value = initializer?.Value;

            VariableDeclaratorSyntax newDeclarator = (value != null)
                ? declarator.ReplaceNode(value, right)
                : declarator.WithInitializer(EqualsValueClause(right));

            LocalDeclarationStatementSyntax newLocalDeclaration = localDeclaration.ReplaceNode(declarator, newDeclarator);

            SyntaxTriviaList trailingTrivia = localDeclaration.GetTrailingTrivia();

            if (trailingTrivia.Any(f => !f.IsWhitespaceOrEndOfLineTrivia()))
            {
                newLocalDeclaration = newLocalDeclaration.WithTrailingTrivia(trailingTrivia.Concat(nextStatement.GetTrailingTrivia()));
            }
            else
            {
                newLocalDeclaration = newLocalDeclaration.WithTrailingTrivia(nextStatement.GetTrailingTrivia());
            }

            SyntaxTriviaList leadingTrivia = nextStatement.GetLeadingTrivia();

            if (leadingTrivia.Any(f => !f.IsWhitespaceOrEndOfLineTrivia()))
            {
                newLocalDeclaration = newLocalDeclaration.WithLeadingTrivia(newLocalDeclaration.GetLeadingTrivia().Concat(leadingTrivia));
            }

            SyntaxList <StatementSyntax> newStatements = statements
                                                         .Replace(localDeclaration, newLocalDeclaration)
                                                         .RemoveAt(index + 1);

            return(document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken));
        }
Beispiel #10
0
 public static VariableDeclaratorSyntax WithSuppressNullableWarningExpression(
     this VariableDeclaratorSyntax variable) =>
 variable
 .WithInitializer(
     EqualsValueClause(
         PostfixUnaryExpression(
             SyntaxKind.SuppressNullableWarningExpression,
             LiteralExpression(
                 SyntaxKind.DefaultLiteralExpression,
                 Token(SyntaxKind.DefaultKeyword)))));
        public CSharpSyntaxNode Convert(VariableDeclarationNode node)
        {
            //TODO: name is ArrayBindingPattern
            VariableDeclaratorSyntax csVariable = SyntaxFactory.VariableDeclarator(node.Name.Text);

            if (node.Initializer != null)
            {
                csVariable = csVariable.WithInitializer(SyntaxFactory.EqualsValueClause(node.Initializer.ToCsNode <ExpressionSyntax>()));
            }

            return(csVariable);
        }
Beispiel #12
0
            public override SyntaxNode VisitVariableDeclarator(VariableDeclaratorSyntax node)
            {
                if (node.Identifier.ValueText == _variableName)
                {
                    return(node.WithInitializer(
                               node.Initializer.WithValue(
                                   SyntaxFactory.LiteralExpression(_kind, _creator())
                                   )
                               ));
                }

                return(base.VisitVariableDeclarator(node));
            }
Beispiel #13
0
        public SyntaxNode Substitute()
        {
            var literal = TryCreateLiteral();

            if (literal != null)
            {
                return(node.WithInitializer(SyntaxFactory.EqualsValueClause(literal)));
            }

            Log.Trace(string.Format("Matched field {0} with substitution coming from cmd line but type conversion failed", symbol));

            return(node);
        }
Beispiel #14
0
        protected override LocalDeclarationStatementSyntax CreateNewStatement()
        {
            ConditionalExpressionSyntax conditionalExpression = IfRefactoringHelper.CreateConditionalExpression(IfStatement.Condition, WhenTrue, WhenFalse);

            VariableDeclaratorSyntax declarator = Statement.Declaration.Variables[0];

            EqualsValueClauseSyntax initializer = declarator.Initializer;

            EqualsValueClauseSyntax newInitializer = (initializer != null)
                ? initializer.WithValue(conditionalExpression)
                : EqualsValueClause(conditionalExpression);

            return(Statement.ReplaceNode(declarator, declarator.WithInitializer(newInitializer)));
        }
Beispiel #15
0
        /// <summary>
        ///   Normalizes the <paramref name="declaration" />.
        /// </summary>
        public override SyntaxNode VisitVariableDeclarator(VariableDeclaratorSyntax declaration)
        {
            var objectCreation = declaration?.Initializer?.Value as ObjectCreationExpressionSyntax;

            if (objectCreation == null)
            {
                return(declaration);
            }

            var symbol = SemanticModel.GetDeclaredSymbol(declaration);

            if (symbol == null)
            {
                return(declaration);
            }

            ITypeSymbol type;
            string      name;

            switch (symbol.Kind)
            {
            case SymbolKind.Field:
                var fieldSymbol = ((IFieldSymbol)symbol);
                type = fieldSymbol.Type;
                name = fieldSymbol.Name;
                break;

            case SymbolKind.Local:
                var localSymbol = ((ILocalSymbol)symbol);
                type = localSymbol.Type;
                name = localSymbol.Name;
                break;

            default:
                return(declaration);
            }

            var fault = SemanticModel.GetTypeSymbol <Fault>();

            if (!type.Equals(fault) && !type.IsDerivedFrom(fault))
            {
                return(declaration);
            }

            return(declaration.WithInitializer(declaration.Initializer.WithValue(AddNameInitializer(fault, objectCreation, name))));
        }
Beispiel #16
0
        private static StatementSyntax CreateStaticDefinitionId(DatasetDefinition datasetDefinition)
        {
            SyntaxToken token = SyntaxFactory.Literal(datasetDefinition.Id);
            VariableDeclaratorSyntax variable = SyntaxFactory.VariableDeclarator(
                SyntaxFactory.SingletonSeparatedList(SyntaxFactory.ModifiedIdentifier("DatasetDefinitionId")));

            variable = variable.WithAsClause(
                SyntaxFactory.SimpleAsClause(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword))));

            variable = variable.WithInitializer(
                SyntaxFactory.EqualsValue(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression,
                                                                          token)));

            return(SyntaxFactory.FieldDeclaration(
                       SyntaxFactory.List <AttributeListSyntax>(),
                       SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword),
                                               SyntaxFactory.Token(SyntaxKind.SharedKeyword)),
                       SyntaxFactory.SingletonSeparatedList(variable)));
        }
Beispiel #17
0
        public static FieldDeclarationSyntax DeclareField(Type fieldType, string name,
                                                          AccessibilityFlags accessibility = AccessibilityFlags.Default)
        {
            VariableDeclarationSyntax varDeclaration = SyntaxFactory.VariableDeclaration(fieldType.ToTypeSyntax());
            VariableDeclaratorSyntax  varDeclarator  = SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(name));

            if (fieldType.IsVsArrayType())
            {
                ObjectCreationExpressionSyntax exp = SyntaxFactory.ObjectCreationExpression(fieldType.ToTypeSyntax())
                                                     .WithArgumentList(SyntaxFactory.ArgumentList());
                varDeclarator = varDeclarator.WithInitializer(SyntaxFactory.EqualsValueClause(exp));
            }

            FieldDeclarationSyntax fieldDeclaration = SyntaxFactory.FieldDeclaration(
                varDeclaration.WithVariables(SyntaxFactory.SingletonSeparatedList(varDeclarator)))
                                                      .WithModifiers(SyntaxFactory.TokenList(AccessibilityToSyntaxToken(accessibility).ToArray()));

            return(fieldDeclaration);
        }
Beispiel #18
0
        public static LocalDeclarationStatementSyntax Declare(TypeSyntax typeSyntax, string identifier, bool initializeToDefault)
        {
            VariableDeclaratorSyntax decl = VariableDeclarator(identifier);

            if (initializeToDefault)
            {
                decl = decl.WithInitializer(
                    EqualsValueClause(
                        LiteralExpression(SyntaxKind.DefaultLiteralExpression)));
            }

            // <type> <identifier>;
            // or
            // <type> <identifier> = default;
            return(LocalDeclarationStatement(
                       VariableDeclaration(
                           typeSyntax,
                           SingletonSeparatedList(decl))));
        }
        public static LocalDeclarationStatementSyntax DeclareLocalVariable(string typeName, string variableName,
                                                                           ExpressionSyntax initValue = null,
                                                                           VariableDeclarationType variableDeclarationType = VariableDeclarationType.ExplicitType)
        {
            VariableDeclaratorSyntax varDeclarator = SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(variableName));

            if (initValue != null)
            {
                varDeclarator = varDeclarator.WithInitializer(SyntaxFactory.EqualsValueClause(initValue));
            }

            VariableDeclarationSyntax varDeclaration = variableDeclarationType == VariableDeclarationType.InferredType
                ? SyntaxFactory.VariableDeclaration(SyntaxFactory.IdentifierName("var"))
                : SyntaxFactory.VariableDeclaration(SyntaxFactory.IdentifierName(typeName));

            varDeclaration = varDeclaration.WithVariables(SyntaxFactory.SingletonSeparatedList(varDeclarator));

            return(SyntaxFactory.LocalDeclarationStatement(varDeclaration));
        }
Beispiel #20
0
        public static LocalDeclarationStatementSyntax Declare(TypeSyntax typeSyntax, string identifier, ExpressionSyntax?initializer)
        {
            VariableDeclaratorSyntax decl = VariableDeclarator(identifier);

            if (initializer is not null)
            {
                decl = decl.WithInitializer(
                    EqualsValueClause(
                        initializer));
            }

            // <type> <identifier>;
            // or
            // <type> <identifier> = <initializer>;
            return(LocalDeclarationStatement(
                       VariableDeclaration(
                           typeSyntax,
                           SingletonSeparatedList(decl))));
        }
        private static StatementSyntax GetRequestInitialization(SyntaxToken queryStringDictToken, SyntaxToken bodyDictToken,
                                                                VariableDeclaratorSyntax descriptorDeclaration, VariableDeclaratorSyntax requestDeclaration)
        {
            var remoteRequestArguments = ArgumentList(SeparatedList(
                                                          new[]
            {
                Argument(IdentifierName(descriptorDeclaration.Identifier)),
                Argument(GetCallingExpression(queryStringDictToken, nameof(ImmutableDictionary <string, object> .Builder.ToImmutable))),
                Argument(GetCallingExpression(bodyDictToken, nameof(ImmutableDictionary <string, object> .Builder.ToImmutable)))
            }
                                                          ));

            var requestInitializer =
                EqualsValueClause(InvocationExpression(ObjectCreationExpression(ParseTypeName(nameof(RemoteRequest))), remoteRequestArguments));

            var requestInitialization = LocalDeclarationStatement(VariableDeclaration(ParseTypeName("var"))
                                                                  .AddVariables(requestDeclaration.WithInitializer(requestInitializer)));

            return(requestInitialization);
        }
        private static VariableDeclaratorSyntax GetNewDeclarator(
            VariableDeclaratorSyntax declarator,
            TypeSyntax type,
            ITypeSymbol typeSymbol)
        {
            ExpressionSyntax value = SyntaxUtility.CreateDefaultValue(typeSymbol, type);

            EqualsValueClauseSyntax @default = EqualsValueClause(value);

            if (declarator.Initializer == null || declarator.Initializer.IsMissing)
            {
                return(declarator
                       .WithIdentifier(declarator.Identifier.WithoutTrailingTrivia())
                       .WithInitializer(@default.WithTrailingTrivia(declarator.Identifier.TrailingTrivia)));
            }
            else
            {
                return(declarator
                       .WithInitializer(@default.WithTriviaFrom(declarator.Initializer.EqualsToken)));
            }
        }
        private static StatementSyntax GetDescriptorInitialization(IReadOnlyDictionary <string, object> attributeData, VariableDeclaratorSyntax descriptorDeclaration)
        {
            if (!attributeData.ContainsKey(nameof(WebInvokeAttribute.Method)))
            {
                throw new InvalidOperationException("Cannot generate call without specifying HTTP method");
            }
            if (!attributeData.TryGetValue(nameof(WebInvokeAttribute.UriTemplate), out var uriTemplate))
            {
                uriTemplate = string.Empty;
            }
            if (!attributeData.TryGetValue(nameof(WebInvokeAttribute.RequestFormat), out var requestFormat))
            {
                requestFormat = default(OperationWebMessageFormat);
            }
            if (!attributeData.TryGetValue(nameof(WebInvokeAttribute.ResponseFormat), out var responseFormat))
            {
                responseFormat = default(OperationWebMessageFormat);
            }
            var remoteOperationDescriptorArguments = ArgumentList(SeparatedList(
                                                                      new[]
            {
                Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(attributeData[nameof(WebInvokeAttribute.Method)].ToString()))),
                Argument(LiteralExpression(SyntaxKind.StringLiteralExpression,
                                           Literal(uriTemplate.ToString()))),
                Argument(MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, ParseTypeName(nameof(OperationWebMessageFormat)),
                                                IdentifierName(Enum.GetName(typeof(OperationWebMessageFormat), requestFormat)))),
                Argument(MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, ParseTypeName(nameof(OperationWebMessageFormat)),
                                                IdentifierName(Enum.GetName(typeof(OperationWebMessageFormat), responseFormat)))),
            }
                                                                      ));

            var descriptorInitializer = EqualsValueClause(InvocationExpression(ObjectCreationExpression(ParseTypeName(nameof(RemoteOperationDescriptor))),
                                                                               remoteOperationDescriptorArguments));

            var descriptorInitialization = LocalDeclarationStatement(VariableDeclaration(ParseTypeName("var"))
                                                                     .AddVariables(descriptorDeclaration.WithInitializer(descriptorInitializer)));

            return(descriptorInitialization);
        }
Beispiel #24
0
        private static VariableDeclaratorSyntax GetNewDeclarator(
            VariableDeclaratorSyntax declarator,
            TypeSyntax type,
            ITypeSymbol typeSymbol)
        {
            ExpressionSyntax value = typeSymbol.GetDefaultValueSyntax(type);

            EqualsValueClauseSyntax initializer    = declarator.Initializer;
            EqualsValueClauseSyntax newInitializer = EqualsValueClause(value);

            if (initializer == null || initializer.IsMissing)
            {
                return(declarator
                       .WithIdentifier(declarator.Identifier.WithoutTrailingTrivia())
                       .WithInitializer(newInitializer.WithTrailingTrivia(declarator.Identifier.TrailingTrivia)));
            }
            else
            {
                return(declarator
                       .WithInitializer(newInitializer.WithTriviaFrom(initializer.EqualsToken)));
            }
        }
Beispiel #25
0
        protected FieldDeclarationSyntax ResolveStaticGlobal(ITypeInfo type, string name, ExpressionSyntax?initializer = null, bool @private = true)
        {
            VariableDeclaratorSyntax declarator = VariableDeclarator
                                                  (
                identifier: Identifier(name)
                                                  );

            if (initializer is not null)
            {
                declarator = declarator.WithInitializer
                             (
                    initializer: EqualsValueClause
                    (
                        initializer
                    )
                             );
            }

            return(FieldDeclaration
                   (
                       declaration: VariableDeclaration
                       (
                           type: ResolveType(type),
                           variables: SingletonSeparatedList(declarator)
                       )
                   )
                   .WithModifiers
                   (
                       TokenList
                       (
                           new SyntaxToken[]
            {
                Token(@private ? SyntaxKind.PrivateKeyword : SyntaxKind.PublicKeyword),
                Token(SyntaxKind.StaticKeyword),
                Token(SyntaxKind.ReadOnlyKeyword)
            }
                       )
                   ));
        }
Beispiel #26
0
        public static Task <Document> RefactorAsync(
            Document document,
            LocalDeclarationStatementSyntax localDeclaration,
            VariableDeclaratorSyntax declarator,
            ITypeSymbol typeSymbol,
            CancellationToken cancellationToken = default)
        {
            VariableDeclaratorSyntax newDeclarator = GetNewDeclarator(localDeclaration.Declaration.Type.WithoutTrivia());

            LocalDeclarationStatementSyntax newNode = localDeclaration.ReplaceNode(declarator, newDeclarator);

            if (localDeclaration.SemicolonToken.IsMissing &&
                localDeclaration.Declaration.Variables.Last().Equals(declarator))
            {
                newNode = newNode.WithSemicolonToken(SemicolonToken().WithTrailingTrivia(newDeclarator.GetTrailingTrivia()));
            }

            return(document.ReplaceNodeAsync(localDeclaration, newNode, cancellationToken));

            VariableDeclaratorSyntax GetNewDeclarator(TypeSyntax type)
            {
                ExpressionSyntax value = typeSymbol.GetDefaultValueSyntax(document.GetDefaultSyntaxOptions(), type);

                EqualsValueClauseSyntax initializer    = declarator.Initializer;
                EqualsValueClauseSyntax newInitializer = EqualsValueClause(value);

                if (initializer?.IsMissing != false)
                {
                    return(declarator
                           .WithIdentifier(declarator.Identifier.WithoutTrailingTrivia())
                           .WithInitializer(newInitializer.WithTrailingTrivia(declarator.Identifier.TrailingTrivia)));
                }
                else
                {
                    return(declarator
                           .WithInitializer(newInitializer.WithTriviaFrom(initializer.EqualsToken)));
                }
            }
        }
        private static Task <Document> RefactorAsync(
            Document document,
            SingleLocalDeclarationStatementInfo localInfo,
            TypeSyntax type,
            CancellationToken cancellationToken)
        {
            LocalDeclarationStatementSyntax localStatement = localInfo.Statement;

            StatementsInfo statementsInfo = SyntaxInfo.StatementsInfo(localStatement);

            int index = statementsInfo.IndexOf(localStatement);

            VariableDeclaratorSyntax declarator = localInfo.Declarator;

            VariableDeclaratorSyntax newDeclarator = declarator.WithInitializer(null);

            VariableDeclarationSyntax newDeclaration = localInfo.Declaration.ReplaceNode(declarator, newDeclarator);

            if (type != null)
            {
                newDeclaration = newDeclaration.WithType(type.WithTriviaFrom(newDeclaration.Type));
            }

            LocalDeclarationStatementSyntax newLocalStatement = localStatement
                                                                .WithDeclaration(newDeclaration)
                                                                .WithTrailingTrivia(NewLine())
                                                                .WithFormatterAnnotation();

            ExpressionStatementSyntax assignmentStatement = SimpleAssignmentStatement(IdentifierName(localInfo.Identifier), localInfo.Initializer.Value)
                                                            .WithTrailingTrivia(localStatement.GetTrailingTrivia())
                                                            .WithFormatterAnnotation();

            StatementsInfo newStatementsInfo = statementsInfo
                                               .Insert(index + 1, assignmentStatement)
                                               .ReplaceAt(index, newLocalStatement);

            return(document.ReplaceStatementsAsync(statementsInfo, newStatementsInfo, cancellationToken));
        }
		/// <summary>
		///   Normalizes the <paramref name="declaration" />.
		/// </summary>
		public override SyntaxNode VisitVariableDeclarator(VariableDeclaratorSyntax declaration)
		{
			var objectCreation = declaration?.Initializer?.Value as ObjectCreationExpressionSyntax;
			if (objectCreation == null)
				return declaration;

			var symbol = SemanticModel.GetDeclaredSymbol(declaration);
			if (symbol == null)
				return declaration;

			ITypeSymbol type;
			string name;

			switch (symbol.Kind)
			{
				case SymbolKind.Field:
					var fieldSymbol = ((IFieldSymbol)symbol);
					type = fieldSymbol.Type;
					name = fieldSymbol.Name;
					break;
				case SymbolKind.Local:
					var localSymbol = ((ILocalSymbol)symbol);
					type = localSymbol.Type;
					name = localSymbol.Name;
					break;
				default:
					return declaration;
			}

			var fault = SemanticModel.GetTypeSymbol<Fault>();
			if (!type.Equals(fault) && !type.IsDerivedFrom(fault))
				return declaration;

			return declaration.WithInitializer(declaration.Initializer.WithValue(AddNameInitializer(fault, objectCreation, name)));
		}
Beispiel #29
0
        public static Task <Document> RefactorAsync(Document document, IfAnalysis ifAnalysis, CancellationToken cancellationToken = default)
        {
            switch (ifAnalysis.Kind)
            {
            case IfAnalysisKind.IfElseToAssignmentWithCoalesceExpression:
            {
                return(IfElseToAssignmentWithCoalesceExpressionAsync(document, (IfElseToAssignmentWithCoalesceExpressionAnalysis)ifAnalysis, cancellationToken));
            }

            case IfAnalysisKind.IfElseToAssignmentWithConditionalExpression:
            {
                return(IfElseToAssignmentWithConditionalExpressionAsync(document, (IfElseToAssignmentWithConditionalExpressionAnalysis)ifAnalysis, cancellationToken));
            }

            case IfAnalysisKind.AssignmentAndIfToAssignmentWithConditionalExpression:
            {
                var analysis = (AssignmentAndIfToAssignmentWithConditionalExpressionAnalysis)ifAnalysis;

                ConditionalExpressionSyntax conditionalExpression = CreateConditionalExpression(analysis.IfStatement.Condition, analysis.WhenTrue, analysis.WhenFalse);

                ExpressionStatementSyntax newStatement = analysis.Statement.ReplaceNode(analysis.Right, conditionalExpression);

                return(ToAssignmentWithConditionalExpressionAsync(document, analysis, newStatement, cancellationToken));
            }

            case IfAnalysisKind.LocalDeclarationAndIfElseAssignmentWithConditionalExpression:
            {
                var analysis = (LocalDeclarationAndIfElseToAssignmentWithConditionalExpressionAnalysis)ifAnalysis;

                ConditionalExpressionSyntax conditionalExpression = CreateConditionalExpression(analysis.IfStatement.Condition, analysis.WhenTrue, analysis.WhenFalse);

                VariableDeclaratorSyntax declarator = analysis.Statement.Declaration.Variables[0];

                EqualsValueClauseSyntax initializer = declarator.Initializer;

                EqualsValueClauseSyntax newInitializer = (initializer != null)
                            ? initializer.WithValue(conditionalExpression)
                            : EqualsValueClause(conditionalExpression);

                LocalDeclarationStatementSyntax newStatement = analysis.Statement.ReplaceNode(declarator, declarator.WithInitializer(newInitializer));

                return(ToAssignmentWithConditionalExpressionAsync(document, analysis, newStatement, cancellationToken));
            }

            case IfAnalysisKind.IfElseToAssignmentWithExpression:
            {
                return(IfElseToAssignmentWithExpressionAsync(document, (IfElseToAssignmentWithExpressionAnalysis)ifAnalysis, cancellationToken));
            }

            case IfAnalysisKind.IfElseToAssignmentWithCondition:
            {
                return(IfElseToAssignmentWithConditionAsync(document, (IfElseToAssignmentWithConditionAnalysis)ifAnalysis, cancellationToken));
            }

            case IfAnalysisKind.IfElseToReturnWithCoalesceExpression:
            case IfAnalysisKind.IfElseToYieldReturnWithCoalesceExpression:
            case IfAnalysisKind.IfReturnToReturnWithCoalesceExpression:
            {
                return(IfToReturnWithCoalesceExpressionAsync(document, (IfToReturnWithCoalesceExpressionAnalysis)ifAnalysis, cancellationToken));
            }

            case IfAnalysisKind.IfElseToReturnWithConditionalExpression:
            {
                return(IfElseToReturnWithConditionalExpressionAsync(document, (IfElseToReturnWithConditionalExpressionAnalysis)ifAnalysis, cancellationToken));
            }

            case IfAnalysisKind.IfElseToReturnWithBooleanExpression:
            {
                return(IfElseToReturnWithBooleanExpressionAsync(document, (IfElseToReturnWithBooleanExpressionAnalysis)ifAnalysis, cancellationToken));
            }

            case IfAnalysisKind.IfElseToReturnWithExpression:
            case IfAnalysisKind.IfElseToYieldReturnWithExpression:
            case IfAnalysisKind.IfReturnToReturnWithExpression:
            {
                return(IfToReturnWithExpressionAsync(document, (IfToReturnWithExpressionAnalysis)ifAnalysis, cancellationToken));
            }

            case IfAnalysisKind.IfElseToYieldReturnWithConditionalExpression:
            {
                return(IfElseToYieldReturnWithConditionalExpressionAsync(document, (IfElseToYieldReturnWithConditionalExpressionAnalysis)ifAnalysis, cancellationToken));
            }

            case IfAnalysisKind.IfElseToYieldReturnWithBooleanExpression:
            {
                return(IfElseToYieldReturnWithBooleanExpressionAsync(document, (IfElseToYieldReturnWithBooleanExpressionAnalysis)ifAnalysis, cancellationToken));
            }

            case IfAnalysisKind.IfReturnToReturnWithConditionalExpression:
            {
                return(IfReturnToReturnWithConditionalExpressionAsync(document, (IfReturnToReturnWithConditionalExpressionAnalysis)ifAnalysis, cancellationToken));
            }

            case IfAnalysisKind.IfReturnToReturnWithBooleanExpression:
            {
                return(IfReturnToReturnWithBooleanExpressionAsync(document, (IfReturnToReturnWithBooleanExpressionAnalysis)ifAnalysis, cancellationToken));
            }

            default:
            {
                throw new InvalidOperationException();
            }
            }
        }
Beispiel #30
0
        public static void ReplaceMember(DocumentEditor editor, SemanticModel model, VariableDeclaratorSyntax original, InvocationExpressionSyntax avaloniaInvocation)
        {
            var parent = (VariableDeclarationSyntax)original.Parent;

            if (parent.Variables.Count > 1)
            {
                editor.ReplaceNode(original.Initializer.Value, avaloniaInvocation);
            }
            else
            {
                var replacedParent = parent
                                     .WithType((TypeSyntax)editor.Generator.TypeExpression(model.GetSpeculativeTypeInfo(original.SpanStart, avaloniaInvocation, SpeculativeBindingOption.BindAsExpression).Type))
                                     .WithVariables(parent.Variables.Replace(parent.Variables[0], original.WithInitializer(original.Initializer.WithValue(avaloniaInvocation))));
                var fieldDeclaration = parent.Parent as FieldDeclarationSyntax;
                editor.ReplaceNode(fieldDeclaration, fieldDeclaration.WithDeclaration(replacedParent));
            }
        }
Beispiel #31
0
        public static async Task <Document> RefactorAsync(
            Document document,
            VariableDeclaratorSyntax declarator,
            CancellationToken cancellationToken)
        {
            var declaration = (VariableDeclarationSyntax)declarator.Parent;

            var localDeclaration = (LocalDeclarationStatementSyntax)declaration.Parent;

            StatementContainer container;

            if (StatementContainer.TryCreate(localDeclaration, out container))
            {
                SyntaxList <StatementSyntax> statements = container.Statements;

                int index = statements.IndexOf(localDeclaration);

                StatementSyntax nextStatement = statements[index + 1];

                var expressionStatement = (ExpressionStatementSyntax)nextStatement;

                var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression;

                ExpressionSyntax right = assignment.Right;

                EqualsValueClauseSyntax initializer = declarator.Initializer;

                ExpressionSyntax value = initializer?.Value;

                VariableDeclaratorSyntax newDeclarator = (value != null)
                    ? declarator.ReplaceNode(value, right)
                    : declarator.WithInitializer(EqualsValueClause(right));

                LocalDeclarationStatementSyntax newLocalDeclaration = localDeclaration.ReplaceNode(declarator, newDeclarator);

                SyntaxTriviaList trailingTrivia = nextStatement.GetTrailingTrivia();

                IEnumerable <SyntaxTrivia> trivia = container
                                                    .Node
                                                    .DescendantTrivia(TextSpan.FromBounds(localDeclaration.Span.End, right.SpanStart));

                if (!trivia.All(f => f.IsWhitespaceOrEndOfLineTrivia()))
                {
                    newLocalDeclaration = newLocalDeclaration.WithTrailingTrivia(trivia.Concat(trailingTrivia));
                }
                else
                {
                    newLocalDeclaration = newLocalDeclaration.WithTrailingTrivia(trailingTrivia);
                }

                SyntaxList <StatementSyntax> newStatements = statements
                                                             .Replace(localDeclaration, newLocalDeclaration)
                                                             .RemoveAt(index + 1);

                return(await document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken).ConfigureAwait(false));
            }

            Debug.Assert(false, "");

            return(document);
        }