Пример #1
0
        public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
        {
            // e.g. int x, y = 0;
            if (node.Declaration.Variables.Count > 1)
            {
                return(node);
            }

            // e.g. int x;
            if (node.Declaration.Variables[0].Initializer == null)
            {
                return(node);
            }

            VariableDeclaratorSyntax declarator = node.Declaration.Variables.First();
            TypeSyntax variableTypeName         = node.Declaration.Type;
            TypeSymbol variableType             = (TypeSymbol)semanticModel.GetSymbolInfo(variableTypeName).Symbol;

            TypeInfo initializerInfo = semanticModel.GetTypeInfo(declarator.Initializer.Value);

            // only when type is the same, (e.g. no base class casting)
            if (variableType == initializerInfo.Type)
            {
                TypeSyntax varTypeName = Syntax.IdentifierName("var")
                                         .WithLeadingTrivia(variableTypeName.GetLeadingTrivia())
                                         .WithTrailingTrivia(variableTypeName.GetTrailingTrivia());

                return(node.ReplaceNode <LocalDeclarationStatementSyntax, TypeSyntax>(variableTypeName, varTypeName));
            }
            else
            {
                return(node);
            }
        }
        public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
        {
            if (node.Declaration.Variables.Count > 1)
            {
                return(node);
            }
            if (node.Declaration.Variables[0].Initializer == null)
            {
                return(node);
            }

            VariableDeclaratorSyntax declarator = node.Declaration.Variables.First();
            TypeSyntax variableTypeName         = node.Declaration.Type;

            ITypeSymbol variableType = (ITypeSymbol)SemanticModel.GetSymbolInfo(variableTypeName).Symbol;

            TypeInfo initializerInfo = SemanticModel.GetTypeInfo(declarator.Initializer.Value);


            if (variableType == initializerInfo.Type)
            {
                TypeSyntax varTypeName = IdentifierName("var").WithLeadingTrivia(variableTypeName.GetLeadingTrivia()).WithTrailingTrivia(variableTypeName.GetTrailingTrivia());

                return(node.ReplaceNode(variableTypeName, varTypeName));
            }
            else
            {
                return(node);
            }
        }
            private SyntaxNode ProcessTypeSyntax(TypeSyntax typeSyntax)
            {
                this.CancellationToken.ThrowIfCancellationRequested();

                // Only simplify if us, or a parent, was marked as needing simplification.
                if (!alwaysSimplify && !typeSyntax.HasAnnotation(Simplifier.Annotation))
                {
                    return(typeSyntax);
                }

                // Definitely do not simplify us if we were told to not simplify.
                if (typeSyntax.HasAnnotation(SimplificationHelpers.DontSimplifyAnnotation))
                {
                    return(typeSyntax);
                }

                var typeStyle = CSharpUseImplicitTypeHelper.Instance.AnalyzeTypeName(
                    typeSyntax, this.SemanticModel, this.OptionSet, this.CancellationToken);

                if (!typeStyle.IsStylePreferred || !typeStyle.CanConvert())
                {
                    return(typeSyntax);
                }

                return(SyntaxFactory.IdentifierName("var")
                       .WithLeadingTrivia(typeSyntax.GetLeadingTrivia())
                       .WithTrailingTrivia(typeSyntax.GetTrailingTrivia()));
            }
Пример #4
0
 public static Microsoft.CodeAnalysis.VisualBasic.Syntax.TypeSyntax ToVbSyntax(this ITypeSymbol type, SemanticModel model, TypeSyntax typeSyntax)
 {
     if (type == null)
     {
         throw new ArgumentNullException(nameof(type));
     }
     return(VBasic.SyntaxFactory.ParseTypeName(type.ToMinimalDisplayString(model, typeSyntax.SpanStart))
            .WithLeadingTrivia(typeSyntax.GetLeadingTrivia().ConvertTrivia())
            .WithTrailingTrivia(typeSyntax.GetTrailingTrivia().ConvertTrivia()));
 }
Пример #5
0
 public static TypeSyntax ToSyntax(this ITypeSymbol type, SemanticModel model, TypeSyntax typeSyntax)
 {
     if (type == null)
     {
         throw new ArgumentNullException(nameof(type));
     }
     return(SyntaxFactory.ParseTypeName(type.ToMinimalDisplayString(model, typeSyntax.SpanStart))
            .WithLeadingTrivia(typeSyntax.GetLeadingTrivia())
            .WithTrailingTrivia(typeSyntax.GetTrailingTrivia()));
 }
        static Document PerformAction(Document document, SemanticModel model, SyntaxNode root, ITypeSymbol type, TypeSyntax typeSyntax)
        {
            var newRoot = root.ReplaceNode((SyntaxNode)
                                           typeSyntax,
                                           SyntaxFactory.ParseTypeName(type.ToMinimalDisplayString(model, typeSyntax.SpanStart))
                                           .WithLeadingTrivia(typeSyntax.GetLeadingTrivia())
                                           .WithTrailingTrivia(typeSyntax.GetTrailingTrivia())
                                           );

            return(document.WithSyntaxRoot(newRoot));
        }
Пример #7
0
        internal static Document PerformAction(Document document, SyntaxNode root, TypeSyntax type)
        {
            var newRoot = root.ReplaceNode((SyntaxNode)
                                           type,
                                           SyntaxFactory.IdentifierName("var")
                                           .WithLeadingTrivia(type.GetLeadingTrivia())
                                           .WithTrailingTrivia(type.GetTrailingTrivia())
                                           );

            return(document.WithSyntaxRoot(newRoot));
        }
Пример #8
0
        public ICodeActionEdit GetEdit(CancellationToken cancellationToken)
        {
            var syntaxTree = (SyntaxTree)document.GetSyntaxTree();

            TypeSyntax newDeclarationType =
                Syntax.IdentifierName(typeName)
                .WithLeadingTrivia(
                    typeSyntax.GetLeadingTrivia())
                .WithTrailingTrivia(
                    typeSyntax.GetTrailingTrivia());

            return(editFactory.CreateTreeTransformEdit(document.Project.Solution, syntaxTree, syntaxTree.Root.ReplaceNode(typeSyntax, newDeclarationType)));
        }
Пример #9
0
        public override SyntaxNode VisitLocalDeclarationStatement(
            LocalDeclarationStatementSyntax node)
        {
            if (node.Declaration.Variables.Count > 1)
            {
                return(node);
            }
            if (node.Declaration.Variables[0].Initializer == null)
            {
                return(node);
            }
            if (node.Modifiers.Count() > 0)
            {
                foreach (SyntaxToken token in node.Modifiers)
                {
                    if (token.ValueText.Equals(kExclusionModifier))
                    {
                        return(node);
                    }
                }
            }

            VariableDeclaratorSyntax declarator = node.Declaration.Variables.First();
            TypeSyntax variableTypeName         = node.Declaration.Type;

            ITypeSymbol variableType =
                (ITypeSymbol)SemanticModel.GetSymbolInfo(variableTypeName)
                .Symbol;

            TypeInfo initializerInfo =
                SemanticModel.GetTypeInfo(declarator
                                          .Initializer
                                          .Value);

            if (variableType == initializerInfo.Type)
            {
                TypeSyntax varTypeName =
                    IdentifierName(kTypeInference)
                    .WithLeadingTrivia(
                        variableTypeName.GetLeadingTrivia())
                    .WithTrailingTrivia(
                        variableTypeName.GetTrailingTrivia());

                return(node.ReplaceNode(variableTypeName, varTypeName));
            }
            else
            {
                return(node);
            }
        }
Пример #10
0
        async Task <Document> MakeUseVar(
            Document document,
            TypeSyntax type,
            CancellationToken cancellationToken)
        {
            var newType = SyntaxFactory.IdentifierName(
                SyntaxFactory.Identifier(
                    type.GetLeadingTrivia(),
                    "var",
                    type.GetTrailingTrivia()));

            var oldRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var newRoot = oldRoot.ReplaceNode(type, newType);

            return(document.WithSyntaxRoot(newRoot));
        }
        public static Task <Document> RefactorAsync(
            Document document,
            CastExpressionSyntax castExpression,
            CancellationToken cancellationToken)
        {
            var parenthesizedExpression = (ParenthesizedExpressionSyntax)castExpression.Parent;

            TypeSyntax       type       = castExpression.Type;
            ExpressionSyntax expression = castExpression.Expression;

            ExpressionSyntax newExpression = expression.WithLeadingTrivia(type.GetLeadingTrivia());

            ParenthesizedExpressionSyntax newNode = parenthesizedExpression.WithExpression(newExpression)
                                                    .WithFormatterAnnotation()
                                                    .WithSimplifierAnnotation();

            return(document.ReplaceNodeAsync(parenthesizedExpression, expression, cancellationToken));
        }
Пример #12
0
        public static OperatorDeclarationSyntax InsertModifier(OperatorDeclarationSyntax operatorDeclaration, SyntaxToken modifier, IModifierComparer comparer)
        {
            if (operatorDeclaration == null)
            {
                throw new ArgumentNullException(nameof(operatorDeclaration));
            }

            SyntaxTokenList modifiers = operatorDeclaration.Modifiers;

            if (!modifiers.Any())
            {
                TypeSyntax returnType = operatorDeclaration.ReturnType;

                return(operatorDeclaration
                       .WithReturnType(returnType.WithoutLeadingTrivia())
                       .WithModifiers(TokenList(modifier.WithLeadingTrivia(returnType.GetLeadingTrivia()))));
            }

            return(operatorDeclaration.WithModifiers(modifiers.InsertModifier(modifier, comparer)));
        }
Пример #13
0
        public static PropertyDeclarationSyntax InsertModifier(PropertyDeclarationSyntax propertyDeclaration, SyntaxToken modifier, IModifierComparer comparer)
        {
            if (propertyDeclaration == null)
            {
                throw new ArgumentNullException(nameof(propertyDeclaration));
            }

            SyntaxTokenList modifiers = propertyDeclaration.Modifiers;

            if (!modifiers.Any())
            {
                TypeSyntax type = propertyDeclaration.Type;

                return(propertyDeclaration
                       .WithType(type.WithoutLeadingTrivia())
                       .WithModifiers(TokenList(modifier.WithLeadingTrivia(type.GetLeadingTrivia()))));
            }

            return(propertyDeclaration.WithModifiers(modifiers.InsertModifier(modifier, comparer)));
        }
Пример #14
0
        public static FieldDeclarationSyntax InsertModifier(FieldDeclarationSyntax fieldDeclaration, SyntaxToken modifier, IModifierComparer comparer)
        {
            if (fieldDeclaration == null)
            {
                throw new ArgumentNullException(nameof(fieldDeclaration));
            }

            SyntaxTokenList modifiers = fieldDeclaration.Modifiers;

            if (!modifiers.Any())
            {
                TypeSyntax type = fieldDeclaration.Declaration?.Type;

                return(fieldDeclaration
                       .ReplaceNode(type, type.WithoutLeadingTrivia())
                       .WithModifiers(TokenList(modifier.WithLeadingTrivia(type.GetLeadingTrivia()))));
            }

            return(fieldDeclaration.WithModifiers(modifiers.InsertModifier(modifier, comparer)));
        }
Пример #15
0
            private static SyntaxToken GetIdentifierTokenAndTrivia(SyntaxToken identifier, TypeSyntax typeSyntax)
            {
                if (typeSyntax != null)
                {
                    var identifierLeadingTrivia  = new SyntaxTriviaList();
                    var identifierTrailingTrivia = new SyntaxTriviaList();
                    if (typeSyntax.HasLeadingTrivia)
                    {
                        identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetLeadingTrivia());
                    }

                    if (typeSyntax.HasTrailingTrivia)
                    {
                        identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetTrailingTrivia());
                    }

                    identifierLeadingTrivia  = identifierLeadingTrivia.AddRange(identifier.LeadingTrivia);
                    identifierTrailingTrivia = identifierTrailingTrivia.AddRange(identifier.TrailingTrivia);
                    identifier = identifier.WithLeadingTrivia(identifierLeadingTrivia)
                                 .WithTrailingTrivia(identifierTrailingTrivia);
                }

                return(identifier);
            }
        private static SyntaxTokenList AddAsyncModifierWithCorrectedTrivia(SyntaxTokenList modifiers, ref TypeSyntax newReturnType)
        {
            if (modifiers.Any())
            {
                return(modifiers.Add(s_asyncToken));
            }

            // Move the leading trivia from the return type to the new modifiers list.
            SyntaxTokenList result = SyntaxFactory.TokenList(s_asyncToken.WithLeadingTrivia(newReturnType.GetLeadingTrivia()));

            newReturnType = newReturnType.WithoutLeadingTrivia();
            return(result);
        }
 private SyntaxNode ConvertType(IDeclarationConverter converter, SemanticModel semanticModel, TypeSyntax original)
 {
     return(SyntaxFactory.IdentifierName(converter.ConvertTypeName(original, semanticModel))
            .WithLeadingTrivia(original.GetLeadingTrivia())
            .WithTrailingTrivia(original.GetTrailingTrivia()));
 }
Пример #18
0
        public static TRoot ReplaceType <TRoot>(this TRoot node, TypeSyntax type) where TRoot : SyntaxNode
        {
            string value = HlslKnownTypes.GetMappedName(type.ToString());

            // If the HLSL mapped full type name equals the original type, just return the input node
            if (value == type.ToString())
            {
                return(node);
            }

            // Process and return the type name
            TypeSyntax newType = SyntaxFactory.ParseTypeName(value).WithLeadingTrivia(type.GetLeadingTrivia()).WithTrailingTrivia(type.GetTrailingTrivia());

            return(node.ReplaceNode(type, newType));
        }
Пример #19
0
        private static async Task <Document> MakeConstAsync(Document document, LocalDeclarationStatementSyntax localDeclaration, CancellationToken cancellationToken)
        {
            // Remove the leading trivia from the local declaration.
            SyntaxToken      firstToken    = localDeclaration.GetFirstToken();
            SyntaxTriviaList leadingTrivia = firstToken.LeadingTrivia;
            LocalDeclarationStatementSyntax trimmedLocal = localDeclaration.ReplaceToken(
                firstToken, firstToken.WithLeadingTrivia(SyntaxTriviaList.Empty));

            // Create a const token with the leading trivia.
            SyntaxToken constToken = SyntaxFactory.Token(leadingTrivia, SyntaxKind.ConstKeyword, SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker));

            // Insert the const token into the modifiers list, creating a new modifiers list.
            SyntaxTokenList newModifiers = trimmedLocal.Modifiers.Insert(0, constToken);

            // If the type of declaration is 'var', create a new type name for the
            // type inferred for 'var'.
            VariableDeclarationSyntax variableDeclaration = localDeclaration.Declaration;
            TypeSyntax variableTypeName = variableDeclaration.Type;

            if (variableTypeName.IsVar)
            {
                SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

                // Special case: Ensure that 'var' isn't actually an alias to another type
                // (e.g. using var = System.String).
                IAliasSymbol aliasInfo = semanticModel.GetAliasInfo(variableTypeName, cancellationToken);
                if (aliasInfo == null)
                {
                    // Retrieve the type inferred for var.
                    ITypeSymbol type = semanticModel.GetTypeInfo(variableTypeName, cancellationToken).ConvertedType;

                    // Special case: Ensure that 'var' isn't actually a type named 'var'.
                    if (type.Name != "var")
                    {
                        // Create a new TypeSyntax for the inferred type. Be careful
                        // to keep any leading and trailing trivia from the var keyword.
                        TypeSyntax typeName = SyntaxFactory.ParseTypeName(type.ToDisplayString())
                                              .WithLeadingTrivia(variableTypeName.GetLeadingTrivia())
                                              .WithTrailingTrivia(variableTypeName.GetTrailingTrivia());

                        // Add an annotation to simplify the type name.
                        TypeSyntax simplifiedTypeName = typeName.WithAdditionalAnnotations(Simplifier.Annotation);

                        // Replace the type in the variable declaration.
                        variableDeclaration = variableDeclaration.WithType(simplifiedTypeName);
                    }
                }
            }

            // Produce the new local declaration.
            LocalDeclarationStatementSyntax newLocal = trimmedLocal.WithModifiers(newModifiers)
                                                       .WithDeclaration(variableDeclaration);

            // Add an annotation to format the new local declaration.
            LocalDeclarationStatementSyntax formattedLocal = newLocal.WithAdditionalAnnotations(Formatter.Annotation);

            // Replace the old local declaration with the new local declaration.
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            SyntaxNode newRoot = root.ReplaceNode(localDeclaration, formattedLocal);

            // Return document with transformed tree.
            return(document.WithSyntaxRoot(newRoot));
        }