コード例 #1
0
        private static void AnalyzeStringLiteralExpression(SyntaxNodeAnalysisContext context)
        {
            var literalExpression = (LiteralExpressionSyntax)context.Node;

            if (literalExpression.Token.ValueText.Length > 0)
            {
                return;
            }

            if (CSharpUtility.IsPartOfExpressionThatMustBeConstant(literalExpression))
            {
                return;
            }

            DiagnosticHelpers.ReportDiagnostic(
                context,
                DiagnosticDescriptors.ReportOnly.UseStringEmptyInsteadOfEmptyStringLiteral,
                literalExpression);
        }
コード例 #2
0
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false);

            if (!TryFindFirstAncestorOrSelf(root, context.Span, out MemberDeclarationSyntax memberDeclaration))
            {
                return;
            }

            string name  = CSharpUtility.GetIdentifier(memberDeclaration).ValueText;
            string title = ExtractTypeDeclarationToNewDocumentRefactoring.GetTitle(name);

            CodeAction codeAction = CodeAction.Create(
                title,
                cancellationToken => ExtractTypeDeclarationToNewDocumentRefactoring.RefactorAsync(context.Document, memberDeclaration, cancellationToken),
                GetEquivalenceKey(DiagnosticIdentifiers.DeclareEachTypeInSeparateFile));

            context.RegisterCodeFix(codeAction, context.Diagnostics);
        }
コード例 #3
0
        private static void AnalyzeInterpolatedStringExpression(SyntaxNodeAnalysisContext context)
        {
            var interpolatedString = (InterpolatedStringExpressionSyntax)context.Node;

            if (interpolatedString.Contents.Any())
            {
                return;
            }

            if (CSharpUtility.IsPartOfExpressionThatMustBeConstant(interpolatedString))
            {
                return;
            }

            DiagnosticHelpers.ReportDiagnostic(
                context,
                DiagnosticDescriptors.ReportOnly.UseStringEmptyInsteadOfEmptyStringLiteral,
                interpolatedString);
        }
コード例 #4
0
            private SyntaxNode Rewrite(StatementsInfo statementsInfo, IfStatementSyntax ifStatement)
            {
                SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

                int index = statements.IndexOf(ifStatement);

                ExpressionSyntax newCondition = CSharpUtility.LogicallyNegate(ifStatement.Condition, _semanticModel, _cancellationToken);

                if (_recursive)
                {
                    ifStatement = (IfStatementSyntax)VisitIfStatement(ifStatement);
                }

                var block = (BlockSyntax)ifStatement.Statement;

                BlockSyntax newBlock = block.WithStatements(SingletonList(_jumpStatement));

                if (!block
                    .Statements
                    .First()
                    .GetLeadingTrivia()
                    .Any(f => f.IsEndOfLineTrivia()))
                {
                    newBlock = newBlock.WithCloseBraceToken(newBlock.CloseBraceToken.AppendToTrailingTrivia(NewLine()));
                }

                IfStatementSyntax newIfStatement = ifStatement
                                                   .WithCondition(newCondition)
                                                   .WithStatement(newBlock)
                                                   .WithFormatterAnnotation();

                if (statements.Last().Kind().IsJumpStatementOrYieldBreakStatement() &&
                    block.Statements.Last().Kind().IsJumpStatementOrYieldBreakStatement())
                {
                    statements = statements.RemoveAt(statements.Count - 1);
                }

                SyntaxList <StatementSyntax> newStatements = statements
                                                             .ReplaceAt(index, newIfStatement)
                                                             .InsertRange(index + 1, block.Statements.Select(f => f.WithFormatterAnnotation()));

                return(statementsInfo.WithStatements(newStatements).Node);
            }
コード例 #5
0
        public void CompileLambdaWithTraceTest()
        {
            dynamic value    = null;
            var     function = CSharpUtility.CompileLambda <dynamic, dynamic>("(source) => Trace(source) * 2", null, (v, m) => {
                value = v;
                return(v);
            });

            Assert.AreEqual(4, function(2));
            Assert.AreEqual(2, value);

            function = CSharpUtility.CompileLambda <dynamic, dynamic>("(source) => Trace(source, \"Message\") * 2", null, (v, m) => {
                value = m;
                return(v);
            });

            function(2);
            Assert.AreEqual("Message", value);
        }
コード例 #6
0
        public static async Task <Document> RefactorAsync(
            Document document,
            IfStatementSyntax ifStatement,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            StatementSyntax trueStatement = ifStatement.Statement;

            StatementSyntax falseStatement = ifStatement.Else.Statement;

            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            IfStatementSyntax newIfStatement = ifStatement
                                               .WithCondition(CSharpUtility.LogicallyNegate(ifStatement.Condition, semanticModel, cancellationToken))
                                               .WithStatement(falseStatement.WithTriviaFrom(trueStatement))
                                               .WithElse(ifStatement.Else.WithStatement(trueStatement.WithTriviaFrom(falseStatement)))
                                               .WithFormatterAnnotation();

            return(await document.ReplaceNodeAsync(ifStatement, newIfStatement, cancellationToken).ConfigureAwait(false));
        }
コード例 #7
0
        public static async Task <Document> RefactorAsync(
            Document document,
            InvocationExpressionSyntax invocationExpression,
            string memberName,
            ExpressionSyntax expression,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            var memberAccessExpression = (MemberAccessExpressionSyntax)invocationExpression.Expression;

            MemberAccessExpressionSyntax newMemberAccessExpression = memberAccessExpression
                                                                     .WithName(SyntaxFactory.IdentifierName(memberName).WithTriviaFrom(memberAccessExpression.Name));

            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            InvocationExpressionSyntax newNode = invocationExpression
                                                 .ReplaceNode(expression, CSharpUtility.LogicallyNegate(expression, semanticModel, cancellationToken))
                                                 .WithExpression(newMemberAccessExpression);

            return(await document.ReplaceNodeAsync(invocationExpression, newNode, cancellationToken).ConfigureAwait(false));
        }
コード例 #8
0
        private static void AnalyzeInterpolatedStringExpression(SyntaxNodeAnalysisContext context)
        {
            var interpolatedString = (InterpolatedStringExpressionSyntax)context.Node;

            if (interpolatedString.Contents.Any())
            {
                return;
            }

            if (CSharpUtility.IsPartOfExpressionThatMustBeConstant(interpolatedString))
            {
                return;
            }

            DiagnosticHelpers.ReportDiagnostic(
                context,
                DiagnosticRules.UseEmptyStringLiteralOrStringEmpty,
                interpolatedString,
                "'string.Empty'");
        }
コード例 #9
0
        private static void AnalyzeStringLiteralExpression(SyntaxNodeAnalysisContext context)
        {
            var literalExpression = (LiteralExpressionSyntax)context.Node;

            if (literalExpression.Token.ValueText.Length > 0)
            {
                return;
            }

            if (CSharpUtility.IsPartOfExpressionThatMustBeConstant(literalExpression))
            {
                return;
            }

            DiagnosticHelpers.ReportDiagnostic(
                context,
                DiagnosticRules.UseEmptyStringLiteralOrStringEmpty,
                literalExpression,
                "'string.Empty'");
        }
コード例 #10
0
ファイル: JsonMapper.cs プロジェクト: ANANC/CakePiece
        private static Type FindTypeByName(string classname)
        {
            Type type = null;

            if (namespaces != null)
            {
                foreach (var name in namespaces)
                {
                    type = CSharpUtility.FindType(string.Concat(name, classname), false);

                    if (type != null)
                    {
                        return(type);//////end
                    }
                }
            }


            return(null);//////end
        }
コード例 #11
0
        public override async Task <Document> RefactorAsync(Document document, CancellationToken cancellationToken = default(CancellationToken))
        {
            ExpressionSyntax expression = Expression;

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

                expression = CSharpUtility.LogicallyNegate(expression, semanticModel, cancellationToken);
            }

            StatementSyntax statement = CreateStatement(expression);

            if (IfStatement.IsSimpleIf())
            {
                StatementsInfo statementsInfo = SyntaxInfo.StatementsInfo(IfStatement);

                SyntaxList <StatementSyntax> statements = statementsInfo.Statements;

                int index = statements.IndexOf(IfStatement);

                StatementSyntax newNode = statement
                                          .WithLeadingTrivia(IfStatement.GetLeadingTrivia())
                                          .WithTrailingTrivia(statements[index + 1].GetTrailingTrivia())
                                          .WithFormatterAnnotation();

                SyntaxList <StatementSyntax> newStatements = statements
                                                             .RemoveAt(index)
                                                             .ReplaceAt(index, newNode);

                return(await document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken).ConfigureAwait(false));
            }
            else
            {
                StatementSyntax newNode = statement
                                          .WithTriviaFrom(IfStatement)
                                          .WithFormatterAnnotation();

                return(await document.ReplaceNodeAsync(IfStatement, newNode, cancellationToken).ConfigureAwait(false));
            }
        }
コード例 #12
0
        private static bool IsArgumentExpressionOfNameOfExpression(SyntaxNodeAnalysisContext context, SyntaxNode node)
        {
            SyntaxNode parent = node.Parent;

            if (parent?.IsKind(SyntaxKind.Argument) != true)
            {
                return(false);
            }

            parent = parent.Parent;

            if (parent?.IsKind(SyntaxKind.ArgumentList) != true)
            {
                return(false);
            }

            parent = parent.Parent;

            return(parent != null &&
                   CSharpUtility.IsNameOfExpression(parent, context.SemanticModel, context.CancellationToken));
        }
コード例 #13
0
        public static bool CanRefactor(MemberInvocationExpression memberInvocation, SemanticModel semanticModel, CancellationToken cancellationToken)
        {
            if (memberInvocation.Expression?.IsMissing != false)
            {
                return(false);
            }

            if (!semanticModel.TryGetExtensionMethodInfo(memberInvocation.InvocationExpression, out MethodInfo methodInfo, ExtensionMethodKind.Reduced, cancellationToken))
            {
                return(false);
            }

            if (!methodInfo.IsLinqExtensionOfIEnumerableOfTWithoutParameters("First", allowImmutableArrayExtension: true))
            {
                return(false);
            }

            ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(memberInvocation.Expression, cancellationToken);

            return(CSharpUtility.HasAccessibleIndexer(typeSymbol, semanticModel, memberInvocation.InvocationExpression.SpanStart));
        }
コード例 #14
0
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, IdentifierNameSyntax identifierName)
        {
            SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

            INamespaceSymbol namespaceSymbol = null;

            SyntaxNode node     = identifierName;
            SyntaxNode prevNode = null;

            while (node.IsParentKind(
                       SyntaxKind.QualifiedName,
                       SyntaxKind.AliasQualifiedName,
                       SyntaxKind.SimpleMemberAccessExpression))
            {
                ISymbol symbol = semanticModel.GetSymbol(node, context.CancellationToken);

                if (symbol?.Kind == SymbolKind.Namespace)
                {
                    namespaceSymbol = (INamespaceSymbol)symbol;
                    prevNode        = node;
                    node            = node.Parent;
                }
                else
                {
                    break;
                }
            }

            node = prevNode;

            if (node.IsParentKind(SyntaxKind.QualifiedName, SyntaxKind.AliasQualifiedName, SyntaxKind.SimpleMemberAccessExpression) &&
                !node.Ancestors(ascendOutOfTrivia: true).Any(f => f.IsKind(SyntaxKind.UsingDirective, SyntaxKind.FileScopedNamespaceDeclaration)) &&
                !CSharpUtility.IsNamespaceInScope(node, namespaceSymbol, semanticModel, context.CancellationToken))
            {
                context.RegisterRefactoring(
                    $"using {namespaceSymbol};",
                    ct => RefactorAsync(context.Document, node, namespaceSymbol, ct),
                    RefactoringDescriptors.AddUsingDirective);
            }
        }
コード例 #15
0
        public static async Task <Document> RefactorAsync(
            Document document,
            IfStatementSyntax ifStatement,
            CancellationToken cancellationToken)
        {
            ExpressionSyntax condition = ifStatement.Condition;

            AssignmentExpressionSyntax assignment = GetSimpleAssignmentExpression(ifStatement.GetSingleStatementOrDefault());

            if (assignment.Right.IsKind(SyntaxKind.FalseLiteralExpression))
            {
                SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

                condition = CSharpUtility.LogicallyNegate(condition, semanticModel, cancellationToken);
            }

            ExpressionStatementSyntax newNode = SimpleAssignmentStatement(assignment.Left, condition)
                                                .WithTriviaFrom(ifStatement)
                                                .WithFormatterAnnotation();

            return(await document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken).ConfigureAwait(false));
        }
コード例 #16
0
        private static bool IsFixable(
            ExpressionSyntax left,
            BinaryExpressionSyntax right,
            SemanticModel semanticModel,
            CancellationToken cancellationToken = default)
        {
            NullCheckExpressionInfo nullCheck = SyntaxInfo.NullCheckExpressionInfo(left);

            if (!nullCheck.Success)
            {
                return(false);
            }

            ExpressionSyntax expression = nullCheck.Expression;

            if (CSharpFactory.AreEquivalent(expression, right.Left))
            {
                return(right.IsKind(SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression) &&
                       SymbolEquals(expression, right.Left, semanticModel, cancellationToken) &&
                       CSharpUtility.IsEmptyStringExpression(right.Right, semanticModel, cancellationToken));
            }

            if (right.Left.IsKind(SyntaxKind.SimpleMemberAccessExpression))
            {
                var memberAccess = (MemberAccessExpressionSyntax)right.Left;

                return(string.Equals(memberAccess.Name.Identifier.ValueText, "Length", StringComparison.Ordinal) &&
                       right.Right.IsNumericLiteralExpression("0") &&
                       semanticModel.GetSymbol(memberAccess, cancellationToken) is IPropertySymbol propertySymbol &&
                       !propertySymbol.IsIndexer &&
                       SymbolUtility.IsPublicInstance(propertySymbol, "Length") &&
                       propertySymbol.Type.SpecialType == SpecialType.System_Int32 &&
                       propertySymbol.ContainingType?.SpecialType == SpecialType.System_String &&
                       CSharpFactory.AreEquivalent(expression, memberAccess.Expression) &&
                       SymbolEquals(expression, memberAccess.Expression, semanticModel, cancellationToken));
            }

            return(false);
        }
コード例 #17
0
        public static async Task ComputeRefactoringAsync(RefactoringContext context, ExpressionSyntax expression)
        {
            if (expression is LiteralExpressionSyntax)
            {
                return;
            }

            if (CSharpUtility.IsStringLiteralConcatenation(expression as BinaryExpressionSyntax))
            {
                return;
            }

            SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

            Optional <object> optional = semanticModel.GetConstantValue(expression, context.CancellationToken);

            if (!optional.HasValue)
            {
                return;
            }

            SyntaxNode oldNode = expression;

            if (oldNode.IsParentKind(SyntaxKind.SimpleMemberAccessExpression))
            {
                var memberAccessExpression = (MemberAccessExpressionSyntax)oldNode.Parent;

                if (memberAccessExpression.Name == expression)
                {
                    oldNode = memberAccessExpression;
                }
            }

            ExpressionSyntax newNode = LiteralExpression(optional.Value);

            context.RegisterRefactoring(
                $"Replace expression with '{newNode}'",
                cancellationToken => context.Document.ReplaceNodeAsync(oldNode, newNode.WithTriviaFrom(expression).Parenthesize(), cancellationToken));
        }
コード例 #18
0
        private static Location GetLocation(SyntaxNode node)
        {
            SyntaxKind kind = node.Kind();

            if (kind == SyntaxKind.OperatorDeclaration)
            {
                return(((OperatorDeclarationSyntax)node).OperatorToken.GetLocation());
            }

            if (kind == SyntaxKind.ConversionOperatorDeclaration)
            {
                return(((ConversionOperatorDeclarationSyntax)node).Type?.GetLocation());
            }

            SyntaxToken token = CSharpUtility.GetIdentifier(node);

            if (!token.IsKind(SyntaxKind.None))
            {
                return(token.GetLocation());
            }

            return(null);
        }
        private static void AnalyzeEqualsExpression(SyntaxNodeAnalysisContext context)
        {
            var equalsExpression = (BinaryExpressionSyntax)context.Node;

            if (equalsExpression.ContainsDirectives)
            {
                return;
            }

            BinaryExpressionInfo equalsExpressionInfo = SyntaxInfo.BinaryExpressionInfo(equalsExpression);

            if (!equalsExpressionInfo.Success)
            {
                return;
            }

            ExpressionSyntax left  = equalsExpressionInfo.Left;
            ExpressionSyntax right = equalsExpressionInfo.Right;

            SemanticModel     semanticModel     = context.SemanticModel;
            CancellationToken cancellationToken = context.CancellationToken;

            if (CSharpUtility.IsEmptyStringExpression(left, semanticModel, cancellationToken))
            {
                if (CSharpUtility.IsStringExpression(right, semanticModel, cancellationToken) &&
                    !equalsExpression.IsInExpressionTree(semanticModel, cancellationToken))
                {
                    DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseStringLengthInsteadOfComparisonWithEmptyString, equalsExpression);
                }
            }
            else if (CSharpUtility.IsEmptyStringExpression(right, semanticModel, cancellationToken) &&
                     CSharpUtility.IsStringExpression(left, semanticModel, cancellationToken) &&
                     !equalsExpression.IsInExpressionTree(semanticModel, cancellationToken))
            {
                DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseStringLengthInsteadOfComparisonWithEmptyString, equalsExpression);
            }
        }
        public static void Analyze(SyntaxNodeAnalysisContext context, SimpleMemberInvocationExpressionInfo invocationInfo)
        {
            InvocationExpressionSyntax invocationExpression = invocationInfo.InvocationExpression;

            if (invocationExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression))
            {
                return;
            }

            SemanticModel     semanticModel     = context.SemanticModel;
            CancellationToken cancellationToken = context.CancellationToken;

            IMethodSymbol methodSymbol = semanticModel.GetReducedExtensionMethodInfo(invocationExpression, cancellationToken).Symbol;

            if (methodSymbol == null)
            {
                return;
            }

            if (!SymbolUtility.IsLinqExtensionOfIEnumerableOfTWithoutParameters(methodSymbol, "Any", semanticModel))
            {
                return;
            }

            string propertyName = CSharpUtility.GetCountOrLengthPropertyName(invocationInfo.Expression, semanticModel, cancellationToken);

            if (propertyName == null)
            {
                return;
            }

            context.ReportDiagnostic(
                DiagnosticDescriptors.UseCountOrLengthPropertyInsteadOfAnyMethod,
                Location.Create(context.Node.SyntaxTree, TextSpan.FromBounds(invocationInfo.Name.SpanStart, invocationExpression.Span.End)),
                ImmutableDictionary.CreateRange(new KeyValuePair <string, string>[] { new KeyValuePair <string, string>("PropertyName", propertyName) }),
                propertyName);
        }
コード例 #21
0
        private static void AnalyzeNamedType(SymbolAnalysisContext context)
        {
            ISymbol symbol = context.Symbol;

            if (symbol.ContainingNamespace?.IsGlobalNamespace != true)
            {
                return;
            }

            if (symbol.ContainingType != null)
            {
                return;
            }

            SyntaxNode node = symbol
                              .DeclaringSyntaxReferences
                              .SingleOrDefault(shouldThrow: false)?
                              .GetSyntax(context.CancellationToken);

            if (node == null)
            {
                return;
            }

            SyntaxToken identifier = CSharpUtility.GetIdentifier(node);

            if (identifier == default)
            {
                return;
            }

            DiagnosticHelpers.ReportDiagnostic(
                context,
                DiagnosticRules.DeclareTypeInsideNamespace,
                identifier,
                identifier.ValueText);
        }
コード例 #22
0
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.SynchronizeAccessibility))
            {
                return;
            }

            SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false);

            if (!TryFindFirstAncestorOrSelf(root, context.Span, out MemberDeclarationSyntax memberDeclaration))
            {
                return;
            }

            SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

            var symbol = (INamedTypeSymbol)semanticModel.GetDeclaredSymbol(memberDeclaration, context.CancellationToken);

            ImmutableArray <MemberDeclarationSyntax> memberDeclarations = ImmutableArray.CreateRange(
                symbol.DeclaringSyntaxReferences,
                f => (MemberDeclarationSyntax)f.GetSyntax(context.CancellationToken));

            foreach (Accessibility accessibility in memberDeclarations
                     .Select(f => f.GetModifiers().GetAccessibility())
                     .Where(f => f != Accessibility.NotApplicable))
            {
                if (CSharpUtility.IsAllowedAccessibility(memberDeclaration, accessibility))
                {
                    CodeAction codeAction = CodeAction.Create(
                        $"Change accessibility to '{accessibility.GetName()}'",
                        cancellationToken => ChangeAccessibilityRefactoring.RefactorAsync(context.Solution(), memberDeclarations, accessibility, cancellationToken),
                        GetEquivalenceKey(CompilerDiagnosticIdentifiers.PartialDeclarationsHaveConfictingAccessibilityModifiers, accessibility.ToString()));

                    context.RegisterCodeFix(codeAction, context.Diagnostics);
                }
            }
        }
コード例 #23
0
        private static void ReportDiagnostic(SymbolAnalysisContext context, ISymbol member)
        {
            SyntaxNode node = member.GetSyntaxOrDefault(context.CancellationToken);

            Debug.Assert(node != null, member.ToString());

            if (node == null)
            {
                return;
            }

            SyntaxToken identifier = CSharpUtility.GetIdentifier(node);

            Debug.Assert(!identifier.IsKind(SyntaxKind.None), node.ToString());

            if (identifier.Kind() == SyntaxKind.None)
            {
                return;
            }

            DiagnosticHelpers.ReportDiagnostic(context,
                                               DiagnosticDescriptors.StaticMemberInGenericTypeShouldUseTypeParameter,
                                               identifier);
        }
コード例 #24
0
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, IdentifierNameSyntax identifierName)
        {
            SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

            INamespaceSymbol namespaceSymbol = null;

            SyntaxNode node     = identifierName;
            SyntaxNode prevNode = null;

            while (node?.IsParentKind(SyntaxKind.QualifiedName, SyntaxKind.AliasQualifiedName, SyntaxKind.SimpleMemberAccessExpression) == true)
            {
                ISymbol symbol = semanticModel.GetSymbol(node, context.CancellationToken);

                if (symbol?.IsNamespace() == true)
                {
                    namespaceSymbol = (INamespaceSymbol)symbol;
                    prevNode        = node;
                    node            = node.Parent;
                }
                else
                {
                    break;
                }
            }

            node = prevNode;

            if (node?.IsParentKind(SyntaxKind.QualifiedName, SyntaxKind.AliasQualifiedName, SyntaxKind.SimpleMemberAccessExpression) == true &&
                !node.IsDescendantOf(SyntaxKind.UsingDirective) &&
                !CSharpUtility.IsNamespaceInScope(node, namespaceSymbol, semanticModel, context.CancellationToken))
            {
                context.RegisterRefactoring(
                    $"using {namespaceSymbol};",
                    cancellationToken => RefactorAsync(context.Document, node, namespaceSymbol, cancellationToken));
            }
        }
コード例 #25
0
        public static void ChangeTypeOrReturnType(
            CodeFixContext context,
            Diagnostic diagnostic,
            SyntaxNode node,
            ITypeSymbol newTypeSymbol,
            SemanticModel semanticModel,
            string additionalKey = null)
        {
            if (newTypeSymbol.IsErrorType())
            {
                return;
            }

            TypeSyntax type = CSharpUtility.GetTypeOrReturnType(node);

            if (type == null)
            {
                return;
            }

            CodeAction codeAction = CodeActionFactory.ChangeType(context.Document, type, newTypeSymbol, semanticModel, equivalenceKey: EquivalenceKey.Create(diagnostic, additionalKey));

            context.RegisterCodeFix(codeAction, diagnostic);
        }
コード例 #26
0
        public static async Task <Document> RefactorAsync(
            Document document,
            ExpressionSyntax expression,
            IMethodSymbol methodSymbol,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            InvocationExpressionSyntax invocation = SimpleMemberInvocationExpression(
                expression
                .WithoutTrailingTrivia()
                .Parenthesize(moveTrivia: true)
                .WithSimplifierAnnotation(),
                IdentifierName(methodSymbol.Name));

            invocation = invocation.WithTrailingTrivia(expression.GetTrailingTrivia());

            SyntaxNode newRoot = root.ReplaceNode(expression, invocation);

            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            if (methodSymbol.IsExtensionMethod &&
                newRoot.IsKind(SyntaxKind.CompilationUnit))
            {
                INamespaceSymbol namespaceSymbol = methodSymbol.ContainingNamespace;

                if (namespaceSymbol != null &&
                    !CSharpUtility.IsNamespaceInScope(expression, namespaceSymbol, semanticModel, cancellationToken))
                {
                    newRoot = ((CompilationUnitSyntax)newRoot)
                              .AddUsings(UsingDirective(ParseName(namespaceSymbol.ToString())));
                }
            }

            return(document.WithSyntaxRoot(newRoot));
        }
コード例 #27
0
        public static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext context)
        {
            var invocation = (InvocationExpressionSyntax)context.Node;

            ExpressionSyntax expression = invocation.Expression;

            if (expression?.IsKind(SyntaxKind.SimpleMemberAccessExpression) == true)
            {
                var memberAccess = (MemberAccessExpressionSyntax)expression;

                ArgumentListSyntax argumentList = invocation.ArgumentList;

                if (argumentList != null)
                {
                    SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments;

                    if (arguments.Any())
                    {
                        SimpleNameSyntax name = memberAccess.Name;

                        if (name?.Identifier.ValueText == "Join")
                        {
                            SemanticModel     semanticModel     = context.SemanticModel;
                            CancellationToken cancellationToken = context.CancellationToken;

                            MethodInfo info;
                            if (semanticModel.TryGetMethodInfo(invocation, out info, cancellationToken) &&
                                info.IsName("Join") &&
                                info.IsContainingType(SpecialType.System_String) &&
                                info.IsPublic &&
                                info.IsStatic &&
                                info.IsReturnType(SpecialType.System_String) &&
                                !info.IsGenericMethod &&
                                !info.IsExtensionMethod)
                            {
                                ImmutableArray <IParameterSymbol> parameters = info.Parameters;

                                if (parameters.Length == 2 &&
                                    parameters[0].Type.IsString())
                                {
                                    IParameterSymbol parameter = parameters[1];

                                    if (parameter.IsParamsOf(SpecialType.System_String, SpecialType.System_Object) ||
                                        parameter.Type.IsConstructedFromIEnumerableOfT())
                                    {
                                        ArgumentSyntax   firstArgument      = arguments.First();
                                        ExpressionSyntax argumentExpression = firstArgument.Expression;

                                        if (argumentExpression != null &&
                                            CSharpUtility.IsEmptyString(argumentExpression, semanticModel, cancellationToken) &&
                                            !invocation.ContainsDirectives(TextSpan.FromBounds(invocation.SpanStart, firstArgument.Span.End)))
                                        {
                                            context.ReportDiagnostic(
                                                DiagnosticDescriptors.CallStringConcatInsteadOfStringJoin,
                                                name);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #28
0
        public static void ComputeCodeFix(
            CodeFixContext context,
            Diagnostic diagnostic,
            ExpressionSyntax expression,
            SemanticModel semanticModel)
        {
            TypeInfo typeInfo = semanticModel.GetTypeInfo(expression, context.CancellationToken);

            ITypeSymbol expressionTypeSymbol = typeInfo.Type;

            if (expressionTypeSymbol == null)
            {
                return;
            }

            if (!expressionTypeSymbol.SupportsExplicitDeclaration())
            {
                return;
            }

            (ISymbol symbol, ITypeSymbol typeSymbol) = GetContainingSymbolAndType(expression, semanticModel, context.CancellationToken);

            Debug.Assert(symbol != null, expression.ToString());

            if (symbol == null)
            {
                return;
            }

            if (symbol.IsOverride)
            {
                return;
            }

            if (symbol.ImplementsInterfaceMember())
            {
                return;
            }

            SyntaxNode node = symbol.GetSyntax(context.CancellationToken);

            if (node.Kind() == SyntaxKind.VariableDeclarator)
            {
                node = node.Parent.Parent;
            }

            TypeSyntax type = CSharpUtility.GetTypeOrReturnType(node);

            if (type == null)
            {
                return;
            }

            ITypeSymbol newTypeSymbol = expressionTypeSymbol;

            string additionalKey = null;

            bool isAsyncMethod = false;
            bool insertAwait   = false;
            bool isYield       = false;

            if (symbol.IsAsyncMethod())
            {
                isAsyncMethod = true;

                INamedTypeSymbol taskOfT = semanticModel.GetTypeByMetadataName("System.Threading.Tasks.Task`1");

                if (taskOfT == null)
                {
                    return;
                }

                if (expression.Kind() == SyntaxKind.AwaitExpression)
                {
                    newTypeSymbol = taskOfT.Construct(expressionTypeSymbol);
                }
                else if (expressionTypeSymbol.OriginalDefinition.Equals(taskOfT))
                {
                    insertAwait   = true;
                    additionalKey = "InsertAwait";
                }
                else if (expressionTypeSymbol.HasMetadataName(MetadataNames.System_Threading_Tasks_Task))
                {
                    return;
                }
            }
            else if (expression.IsParentKind(SyntaxKind.YieldReturnStatement))
            {
                isYield = true;

                newTypeSymbol = semanticModel
                                .Compilation
                                .GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T)
                                .Construct(expressionTypeSymbol);
            }

            if (!isYield &&
                !isAsyncMethod &&
                !typeSymbol.OriginalDefinition.IsIEnumerableOfT() &&
                newTypeSymbol.OriginalDefinition.HasMetadataName(MetadataNames.System_Linq_IOrderedEnumerable_T))
            {
                INamedTypeSymbol constructedEnumerableSymbol = semanticModel
                                                               .Compilation
                                                               .GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T)
                                                               .Construct(((INamedTypeSymbol)newTypeSymbol).TypeArguments.ToArray());

                RegisterCodeFix(context, diagnostic, node, type, expression, constructedEnumerableSymbol, semanticModel, insertAwait: false);
                additionalKey = "IOrderedEnumerable<T>";
            }

            RegisterCodeFix(context, diagnostic, node, type, expression, newTypeSymbol, semanticModel, insertAwait: insertAwait, additionalKey: additionalKey);
        }
コード例 #29
0
 private static void ReportDiagnostic(SyntaxNodeAnalysisContext context, SyntaxNode node, string declarationName)
 {
     DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.RemoveUnusedMemberDeclaration, CSharpUtility.GetIdentifier(node), declarationName);
 }
コード例 #30
0
        /// <summary>
        /// 随从的导入
        /// </summary>
        /// <param name="target"></param>
        /// <param name="workbook"></param>
        private void Minion(dynamic workbook)
        {
            if (Directory.Exists(ExportFolderPicker.SelectedPathOrFileName + "\\Minion\\"))
            {
                Directory.Delete(ExportFolderPicker.SelectedPathOrFileName + "\\Minion\\", true);
            }
            Directory.CreateDirectory(ExportFolderPicker.SelectedPathOrFileName + "\\Minion\\");
            //随从的导入
            dynamic worksheet = workbook.Sheets(1);
            int     rowCount  = 4;

            while (!string.IsNullOrEmpty(worksheet.Cells(rowCount, 2).Text))
            {
                MinionCard Minion = new MinionCard();
                Minion.序列号  = worksheet.Cells(rowCount, 2).Text;
                Minion.称    = worksheet.Cells(rowCount, 3).Text;
                Minion.描述   = worksheet.Cells(rowCount, 4).Text;
                Minion.职业   = CSharpUtility.GetEnum <CardUtility.职业枚举>(worksheet.Cells(rowCount, 5).Text, CardUtility.职业枚举.中立);
                Minion.种族   = CSharpUtility.GetEnum <CardUtility.种族枚举>(worksheet.Cells(rowCount, 6).Text, CardUtility.种族枚举.无);
                Minion.使用成本 = CSharpUtility.GetInt(worksheet.Cells(rowCount, 7).Text);

                Minion.攻击力   = CSharpUtility.GetInt(worksheet.Cells(rowCount, 8).Text);
                Minion.生命值上限 = CSharpUtility.GetInt(worksheet.Cells(rowCount, 9).Text);
                Minion.稀有程度  = CSharpUtility.GetEnum <CardBasicInfo.稀有程度枚举>(worksheet.Cells(rowCount, 12).Text, CardBasicInfo.稀有程度枚举.白色);
                Minion.是否启用  = !string.IsNullOrEmpty(worksheet.Cells(rowCount, 13).Text);

                Minion.嘲讽特性 = !string.IsNullOrEmpty(worksheet.Cells(rowCount, 14).Text);
                Minion.冲锋特性 = !string.IsNullOrEmpty(worksheet.Cells(rowCount, 15).Text);
                Minion.风怒特性 = !string.IsNullOrEmpty(worksheet.Cells(rowCount, 17).Text);
                Minion.潜行特性 = !string.IsNullOrEmpty(worksheet.Cells(rowCount, 18).Text);
                Minion.圣盾特性 = !string.IsNullOrEmpty(worksheet.Cells(rowCount, 19).Text);

                bool HasBuff = false;
                for (int i = 22; i < 25; i++)
                {
                    if (!string.IsNullOrEmpty(worksheet.Cells(rowCount, i).Text))
                    {
                        HasBuff = true;
                        break;
                    }
                }
                if (HasBuff)
                {
                    Minion.光环效果.来源 = Minion.称;
                    //Minion.光环效果.范围 = CSharpUtility.GetEnum<Buff.光环范围枚举>(worksheet.Cells(rowCount, 22).Text, Buff.光环范围枚举.随从全体);
                    Minion.光环效果.类型 = CSharpUtility.GetEnum <Buff.光环类型枚举>(worksheet.Cells(rowCount, 23).Text, Buff.光环类型枚举.增加攻防);
                    Minion.光环效果.信息 = worksheet.Cells(rowCount, 24).Text;
                }
                Minion.战吼效果   = worksheet.Cells(rowCount, 25).Text;
                Minion.亡语效果   = worksheet.Cells(rowCount, 27).Text;
                Minion.激怒效果   = worksheet.Cells(rowCount, 28).Text;
                Minion.连击效果   = worksheet.Cells(rowCount, 29).Text;
                Minion.回合开始效果 = worksheet.Cells(rowCount, 30).Text;
                Minion.回合结束效果 = worksheet.Cells(rowCount, 31).Text;
                Minion.过载     = CSharpUtility.GetInt(worksheet.Cells(rowCount, 32).Text);
                //Minion.自身事件效果.触发效果事件类型 = CSharpUtility.GetEnum<CardUtility.事件类型枚举>(worksheet.Cells(rowCount, 33).Text, CardUtility.事件类型枚举.无);
                Minion.自身事件效果.效果编号     = worksheet.Cells(rowCount, 34).Text;
                Minion.自身事件效果.触发效果事件方向 = CSharpUtility.GetEnum <CardUtility.目标选择方向枚举>(worksheet.Cells(rowCount, 35).Text, CardUtility.目标选择方向枚举.本方);
                Minion.自身事件效果.限制信息     = worksheet.Cells(rowCount, 36).Text;
                Minion.特殊效果            = CSharpUtility.GetEnum <MinionCard.特殊效果枚举>(worksheet.Cells(rowCount, 37).Text, MinionCard.特殊效果枚举.无效果);
                switch (exportType)
                {
                case SystemManager.ExportType.XML:
                    XmlSerializer xml         = new XmlSerializer(typeof(MinionCard));
                    string        XmlFilename = ExportFolderPicker.SelectedPathOrFileName + "\\Minion\\" + Minion.序列号 + ".xml";
                    xml.Serialize(new StreamWriter(XmlFilename), Minion);
                    break;

                case SystemManager.ExportType.JSON:
                    string       JSonFilename = ExportFolderPicker.SelectedPathOrFileName + "\\Minion\\" + Minion.序列号 + ".json";
                    StreamWriter json         = new StreamWriter(JSonFilename);
                    json.Write(Minion.ToJson());
                    json.Close();
                    break;

                default:
                    break;
                }
                rowCount++;
            }
        }