当前位置: 首页>>代码示例>>C#>>正文


C# SyntaxNode.AncestorsAndSelf方法代码示例

本文整理汇总了C#中Microsoft.CodeAnalysis.SyntaxNode.AncestorsAndSelf方法的典型用法代码示例。如果您正苦于以下问题:C# SyntaxNode.AncestorsAndSelf方法的具体用法?C# SyntaxNode.AncestorsAndSelf怎么用?C# SyntaxNode.AncestorsAndSelf使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Microsoft.CodeAnalysis.SyntaxNode的用法示例。


在下文中一共展示了SyntaxNode.AncestorsAndSelf方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: UseExpressionBodiedMemberAsync

        private Task<Solution> UseExpressionBodiedMemberAsync(Document document, SyntaxNode root, SyntaxNode statement)
        {
            var returnStatement = (ReturnStatementSyntax) statement;
            var expression = returnStatement.Expression;
            var arrowClause = SyntaxFactory.ArrowExpressionClause(expression);

            var property = statement.AncestorsAndSelf().OfType<PropertyDeclarationSyntax>().FirstOrDefault();
            if (property != null)
            {
                var newProperty = property.RemoveNode(property.AccessorList, SyntaxRemoveOptions.KeepNoTrivia)
                                          .WithExpressionBody(arrowClause)
                                          .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));


                root = root.ReplaceNode(property, newProperty);
            }

            var method = statement.AncestorsAndSelf().OfType<MethodDeclarationSyntax>().FirstOrDefault();
            if (method != null)
            {
                root = root.ReplaceNode(method, method.RemoveNode(method.Body, SyntaxRemoveOptions.KeepNoTrivia)
                                                      .WithExpressionBody(arrowClause)
                                                      .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
            }

            return Task.FromResult(document.WithSyntaxRoot(root).Project.Solution);
        }
开发者ID:nemec,项目名称:VSDiagnostics,代码行数:27,代码来源:SimplifyExpressionBodiedMemberCodeFix.cs

示例2: UsePropertyAsync

        private async Task<Solution> UsePropertyAsync(Document document, SyntaxNode statement)
        {
            // Create a new property
            // Using property naming conventions
            // Including possible initializers
            // And attributes

            var variableDeclarator = statement.AncestorsAndSelf().OfType<VariableDeclaratorSyntax>().First();
            var fieldStatement = variableDeclarator.AncestorsAndSelf().OfType<FieldDeclarationSyntax>().First();
            var variableDeclaration = variableDeclarator.AncestorsAndSelf().OfType<VariableDeclarationSyntax>().First();

            var newProperty = SyntaxFactory.PropertyDeclaration(variableDeclaration.Type, variableDeclarator.Identifier.WithConvention(NamingConvention.UpperCamelCase))
                                           .WithAttributeLists(fieldStatement.AttributeLists)
                                           .WithModifiers(fieldStatement.Modifiers)
                                           .WithAdditionalAnnotations(Formatter.Annotation)
                                           .WithAccessorList(
                                               SyntaxFactory.AccessorList(
                                                   SyntaxFactory.List(new[]
                                                   {
                                                       SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                                                       SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
                                                   })));

            if (variableDeclarator.Initializer != null)
            {
                newProperty = newProperty.WithInitializer(variableDeclarator.Initializer).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
            }

            var editor = await DocumentEditor.CreateAsync(document);
            editor.InsertAfter(statement, newProperty);
            editor.RemoveNode(variableDeclarator);
            return editor.GetChangedDocument().Project.Solution;
        }
开发者ID:nemec,项目名称:VSDiagnostics,代码行数:33,代码来源:NonEncapsulatedOrMutableFieldCodeFix.cs

示例3: UseAsAsync

        private async Task<Solution> UseAsAsync(Document document, SyntaxNode statement)
        {
            var isExpression = (BinaryExpressionSyntax) statement;
            var ifStatement = statement.AncestorsAndSelf().OfType<IfStatementSyntax>().First();

            var asExpressions = ifStatement.Statement.DescendantNodesAndSelf().OfType<BinaryExpressionSyntax>().Where(x => x.OperatorToken.IsKind(SyntaxKind.AsKeyword));
            var isIdentifier = ((IdentifierNameSyntax) isExpression.Left).Identifier.ValueText;

            foreach (var asExpression in asExpressions)
            {
                var isIdentifierInAsContext = ((IdentifierNameSyntax) asExpression.Left).Identifier.ValueText;
                if (string.Equals(isIdentifier, isIdentifierInAsContext))
                {
                    // Move the as statement before the if block
                    // Change the if-condition to "NewAsIdentifier != null"

                    var variableDeclarator = asExpression.AncestorsAndSelf().OfType<VariableDeclaratorSyntax>().First();
                    var asIdentifier = variableDeclarator.Identifier.ValueText;
                    var variableDeclaration = asExpression.AncestorsAndSelf().OfType<LocalDeclarationStatementSyntax>().First();

                    var editor = await DocumentEditor.CreateAsync(document);

                    var newCondition = SyntaxFactory.ParseExpression($"{asIdentifier} != null");
                    editor.ReplaceNode(ifStatement.Condition, newCondition);

                    if (variableDeclaration.Declaration.Variables.Count > 1) // Split variable declaration
                    {
                        // Extract the relevant variable and copy it outside the if-body
                        var extractedDeclarator = variableDeclaration.Declaration.Variables.First(x => x.Identifier.ValueText == asIdentifier);
                        var newDeclaration = SyntaxFactory.VariableDeclaration(
                            extractedDeclarator.AncestorsAndSelf().OfType<VariableDeclarationSyntax>().First().Type,
                            SyntaxFactory.SeparatedList(new[] { extractedDeclarator }));
                        var newStatement = SyntaxFactory.LocalDeclarationStatement(
                            SyntaxFactory.TokenList(),
                            newDeclaration,
                            SyntaxFactory.Token(SyntaxKind.SemicolonToken));
                        editor.InsertBefore(ifStatement, newStatement.WithAdditionalAnnotations(Formatter.Annotation));

                        // Rewrite the variable declaration inside the if-body to remove the one we just copied
                        var newVariables = variableDeclaration.Declaration.WithVariables(SyntaxFactory.SeparatedList(variableDeclaration.Declaration.Variables.Except(new[] { extractedDeclarator })));
                        var newBodyStatement = SyntaxFactory.LocalDeclarationStatement(
                            SyntaxFactory.TokenList(),
                            newVariables,
                            SyntaxFactory.Token(SyntaxKind.SemicolonToken));
                        editor.ReplaceNode(variableDeclaration, newBodyStatement);
                    }
                    else // Move declaration outside if-body
                    {
                        editor.RemoveNode(variableDeclaration);
                        editor.InsertBefore(ifStatement, variableDeclaration.WithAdditionalAnnotations(Formatter.Annotation));
                    }

                    var newDocument = editor.GetChangedDocument();
                    return newDocument.Project.Solution;
                }
            }

            return null;
        }
开发者ID:nemec,项目名称:VSDiagnostics,代码行数:59,代码来源:TryCastWithoutUsingAsNotNullCodeFix.cs

示例4: GetNewRoot

        static SyntaxNode GetNewRoot(SyntaxNode root, SyntaxNode node)
        {
            var decl = node.AncestorsAndSelf().OfType<LocalDeclarationStatementSyntax>().FirstOrDefault();
            if (decl != null)
                return root.RemoveNode(decl, SyntaxRemoveOptions.KeepNoTrivia);
            if (node.Parent.IsKind(SyntaxKind.ElseClause))
                return root.RemoveNode(node.Parent, SyntaxRemoveOptions.KeepNoTrivia);

            var statement = node as StatementSyntax;
            if (statement != null)
                return root.RemoveNode(statement, SyntaxRemoveOptions.KeepNoTrivia);

            return root.RemoveNode(node.Parent, SyntaxRemoveOptions.KeepNoTrivia);
        }
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:14,代码来源:CS0162UnreachableCodeDetectedCodeFixProvider.cs

示例5: Typedef

        private static SyntaxNode Typedef(SyntaxNode node, Scope scope)
        {
            var field = node
                .AncestorsAndSelf()
                .OfType<FieldDeclarationSyntax>()
                .FirstOrDefault();

            if (field == null)
            {
                scope.AddError("xs01", "malformed typedef", node);
                //td: error, malformed typedef
                return node;
            }

            if (field.Declaration.Variables.Count != 1)
            {
                scope.AddError("xs01", "malformed typedef", node);
                return node;
            }

            var variable = field
                .Declaration
                .Variables[0];

            Debug.Assert(variable.Initializer == null || variable.Initializer.IsMissing);

            var type = RoslynCompiler.UnMark(field.Declaration.Type);
            var identifier = variable.Identifier;

            var parentScope = scope.CreateScope<SyntaxToken, SyntaxNode, SemanticModel>(field.Parent);
            Debug.Assert(parentScope != null);

            parentScope.set("__tdef" + identifier.ToString(), type);

            //schedule deletion
            var document = scope.GetDocument<SyntaxToken, SyntaxNode, SemanticModel>();
            document.change(field.Parent, RoslynCompiler.RemoveMember(field));

            //return intact
            return node;
        }
开发者ID:mpmedia,项目名称:Excess,代码行数:41,代码来源:TypeDef.cs

示例6: GetParametersInScope

 private static IEnumerable<ParameterSyntax> GetParametersInScope(SyntaxNode node)
 {
     foreach (var ancestor in node.AncestorsAndSelf())
     {
         if (ancestor.IsKind(SyntaxKind.SimpleLambdaExpression))
         {
             yield return ((SimpleLambdaExpressionSyntax)ancestor).Parameter;
         }
         else
         {
             var parameterList = ancestor.GetParameterList();
             if (parameterList != null)
             {
                 foreach (var parameter in parameterList.Parameters)
                 {
                     yield return parameter;
                 }
             }
         }
     }
 }
开发者ID:jmarolf,项目名称:CSharpEssentials,代码行数:21,代码来源:UseNameOfAnalyzer.cs

示例7: GetNameProposal

        public static string GetNameProposal(string name, SemanticModel model, SyntaxNode node)
        {
            string baseName = char.ToLower(name[0]) + name.Substring(1);
            var enclosingClass = node.AncestorsAndSelf().OfType<TypeDeclarationSyntax>().FirstOrDefault();
            if (enclosingClass == null)
                return baseName;

            INamedTypeSymbol typeSymbol = model.GetDeclaredSymbol(enclosingClass);
            IEnumerable<string> members = typeSymbol.MemberNames;

            string proposedName = null;
            int number = 0;
            do
            {
                proposedName = baseName;
                if (number != 0)
                {
                    proposedName = baseName + number.ToString();
                }
                number++;
            } while (members.Contains(proposedName));
            return proposedName;
        }
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:23,代码来源:ConvertAutoPropertyToPropertyCodeRefactoringProvider.cs

示例8: GetVariableDeclaratorOfAFieldDeclarationNode

 public override SyntaxNode GetVariableDeclaratorOfAFieldDeclarationNode(SyntaxNode node)
 {
     if (IsObjectCreationExpressionUnderFieldDeclaration(node))
     {
         return node.AncestorsAndSelf().OfType<VariableDeclaratorSyntax>().FirstOrDefault();
     }
     else
     {
         return null;
     }
 }
开发者ID:Anniepoh,项目名称:roslyn-analyzers,代码行数:11,代码来源:SyntaxNodeHelper.cs

示例9: IsObjectCreationExpressionUnderFieldDeclaration

 public override bool IsObjectCreationExpressionUnderFieldDeclaration(SyntaxNode node)
 {
     return node != null &&
            node.Kind() == SyntaxKind.ObjectCreationExpression &&
            node.AncestorsAndSelf().OfType<FieldDeclarationSyntax>().FirstOrDefault() != null;
 }
开发者ID:Anniepoh,项目名称:roslyn-analyzers,代码行数:6,代码来源:SyntaxNodeHelper.cs

示例10: GetEnclosingTypeSymbol

        public override ITypeSymbol GetEnclosingTypeSymbol(SyntaxNode node, SemanticModel semanticModel)
        {
            if (node == null)
            {
                return null;
            }

            ClassDeclarationSyntax declaration = node.AncestorsAndSelf().OfType<ClassDeclarationSyntax>().FirstOrDefault();

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

            return semanticModel.GetDeclaredSymbol(declaration);
        }
开发者ID:Anniepoh,项目名称:roslyn-analyzers,代码行数:16,代码来源:SyntaxNodeHelper.cs

示例11: GetCallerMethodSymbol

        public override IMethodSymbol GetCallerMethodSymbol(SyntaxNode node, SemanticModel semanticModel)
        {
            if (node == null)
            {
                return null;
            }

            MethodDeclarationSyntax declaration = node.AncestorsAndSelf().OfType<MethodDeclarationSyntax>().FirstOrDefault();
            if (declaration != null)
            {
                return semanticModel.GetDeclaredSymbol(declaration);
            }

            ConstructorDeclarationSyntax contructor = node.AncestorsAndSelf().OfType<ConstructorDeclarationSyntax>().FirstOrDefault();
            if (contructor != null)
            {
                return semanticModel.GetDeclaredSymbol(contructor);
            }

            return null;
        }
开发者ID:Anniepoh,项目名称:roslyn-analyzers,代码行数:21,代码来源:SyntaxNodeHelper.cs

示例12: GetSemanticRootForSpeculation

 private static SyntaxNode GetSemanticRootForSpeculation(SyntaxNode expression)
 {
     var parentNodeToSpeculate = expression
         .AncestorsAndSelf(ascendOutOfTrivia: false)
         .LastOrDefault(node => CanSpeculateOnNode(node));
     return parentNodeToSpeculate ?? expression;
 }
开发者ID:haroldhues,项目名称:code-cracker,代码行数:7,代码来源:ConvertLambdaExpressionToMethodGroupAnalyzer.cs

示例13: GetQueryClauseInfo

        protected override ITypeSymbol GetQueryClauseInfo(
            SemanticModel semanticModel,
            SyntaxNode node,
            CancellationToken cancellationToken)
        {
            var query = node.AncestorsAndSelf().OfType<QueryExpressionSyntax>().First();

            if (InfoBoundSuccessfully(semanticModel.GetQueryClauseInfo(query.FromClause, cancellationToken)))
            {
                return null;
            }

            foreach (var clause in query.Body.Clauses)
            {
                if (InfoBoundSuccessfully(semanticModel.GetQueryClauseInfo(clause, cancellationToken)))
                {
                    return null;
                }
            }

            if (InfoBoundSuccessfully(semanticModel.GetSymbolInfo(query.Body.SelectOrGroup, cancellationToken)))
            {
                return null;
            }

            var fromClause = query.FromClause;
            return semanticModel.GetTypeInfo(fromClause.Expression, cancellationToken).Type;
        }
开发者ID:reidwooten99apps,项目名称:roslyn,代码行数:28,代码来源:CSharpAddImportCodeFixProvider.cs

示例14: CanAddImportForQuery

        protected override bool CanAddImportForQuery(Diagnostic diagnostic, ref SyntaxNode node)
        {
            if (diagnostic.Id != CS1935)
            {
                return false;
            }

            return node.AncestorsAndSelf().Any(n => n is QueryExpressionSyntax && !(n.Parent is QueryContinuationSyntax));
        }
开发者ID:reidwooten99apps,项目名称:roslyn,代码行数:9,代码来源:CSharpAddImportCodeFixProvider.cs

示例15: Property

        private static SyntaxNode Property(SyntaxNode node, Scope scope)
        {
            var field = node.AncestorsAndSelf()
                .OfType<MemberDeclarationSyntax>()
                .FirstOrDefault()
                as FieldDeclarationSyntax;

            if (field == null)
            {
                //td: error, malformed property
                return node;
            }

            if (field.Declaration.Variables.Count != 1)
            {
                //td: error, malformed property
                return node;
            }

            var variable = field
                .Declaration
                .Variables[0];

            var initializer = variable.Initializer;
            var type = field.Declaration.Type;
            if (type == null || type.IsMissing || type.ToString() == "property") //untyped
            {
                if (initializer != null)
                    type = RoslynCompiler.ConstantType(initializer.Value);
            }

            if (type == null)
                type = [email protected];

            var property = _property
                .WithIdentifier(variable.Identifier)
                .WithType(type);

            if (!RoslynCompiler.HasVisibilityModifier(field.Modifiers))
                property = property.AddModifiers(CSharp.Token(SyntaxKind.PublicKeyword));

            var document = scope.GetDocument<SyntaxToken, SyntaxNode, SemanticModel>();

            //schedule the field replacement
            //td: coud be done in this pass with the right info from lexical
            document.change(field, RoslynCompiler.ReplaceNode(property));

            //must be initialized
            if (initializer != null)
            {
                var expr = (AssignmentExpressionSyntax)_assignment.Expression;
                document.change(field.Parent, RoslynCompiler
                    .AddInitializers(_assignment.WithExpression(expr
                        .WithLeft(CSharp.IdentifierName(variable.Identifier))
                        .WithRight(initializer.Value))));
            }

            return node;
        }
开发者ID:mpmedia,项目名称:Excess,代码行数:59,代码来源:Members.cs


注:本文中的Microsoft.CodeAnalysis.SyntaxNode.AncestorsAndSelf方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。