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


C# SyntaxNode.DescendantNodes方法代码示例

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


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

示例1: MakeMock

        private static async Task<Document> MakeMock(Document document, SyntaxNode invokationSyntax,
            CancellationToken cancellationToken)
        {
            var testSemanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            var testInitMethodDecl = TestSemanticHelper.GetTestInitializeMethod(testSemanticModel);

            var declaredFields = testInitMethodDecl.Parent.ChildNodes().OfType<FieldDeclarationSyntax>().ToArray();

            var suts = testInitMethodDecl.GetSuts(testSemanticModel, declaredFields);

            var memberAccessExpressions = invokationSyntax.DescendantNodes()
                .OfType<ExpressionSyntax>()
                .Where(x => x is InvocationExpressionSyntax || x is MemberAccessExpressionSyntax)
                .Select(expr =>
                {
                    var memberAccess = expr as MemberAccessExpressionSyntax;
                    var invokationExpression = expr as InvocationExpressionSyntax;
                    var expression = invokationExpression == null ? memberAccess : invokationExpression.Expression;
                    return expression;
                });

            var invokedMethodsOfMocks = memberAccessExpressions.SelectMany(expressionSyntax => MocksAnalyzingEngine.GetInvokedMethodsOfMock(expressionSyntax, testSemanticModel, suts))
                                                               .DistinctBy(x => string.Join(",", x.FieldsToSetup.SelectMany(y => y.Field.Select(z => z))) + "," + x.MethodOrPropertySymbol)
                                                               .ToArray();

            if (invokedMethodsOfMocks.Length == 0)
                return document;

            var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

            ChangesMaker.ApplyChanges(invokationSyntax, editor, invokedMethodsOfMocks);

            return editor.GetChangedDocument();
        }
开发者ID:ycherkes,项目名称:MockIt,代码行数:35,代码来源:TestMethodCodeFixProvider.cs

示例2: GetAllMutations

        private static IEnumerable<NameAndLocation> GetAllMutations(SyntaxNode syntax)
        {
            var assignments = syntax.DescendantNodes()
                                    .Where(NodeIsAssignmentExpression)
                                    .Cast<AssignmentExpressionSyntax>()
                                    .Select(expression => new NameAndLocation(
                                                GetIdentifierFromAssignmentExpression(expression),
                                                expression.GetLocation()));

            var prefixExpressions = syntax.DescendantNodes()
                                          .Where(NodeIsPrefixExpression)
                                          .Cast<PrefixUnaryExpressionSyntax>()
                                          .Select(expression => new NameAndLocation(
                                                      GetIdentifierFromPrefixOperand(expression),
                                                      expression.GetLocation()));

            var postfixExpressions = syntax.DescendantNodes()
                                           .Where(NodeIsPostfixExpression)
                                           .Cast<PostfixUnaryExpressionSyntax>()
                                           .Select(expression => new NameAndLocation(
                                                       GetIdentifierFromPostfixOperand(expression),
                                                       expression.GetLocation()));

            return assignments.Cons(prefixExpressions).Cons(postfixExpressions);
        }
开发者ID:DavidArno,项目名称:Arnolyzer,代码行数:25,代码来源:VariableMutations.cs

示例3: GetExerciseInsertIndex

		private int GetExerciseInsertIndex(SyntaxNode tree)
		{
			ClassDeclarationSyntax exerciseClass =
				tree.DescendantNodes()
					.OfType<ClassDeclarationSyntax>()
					.FirstOrDefault(n => n.Identifier.Text == ExerciseClassName);
			if (exerciseClass !=null)
				return exerciseClass.OpenBraceToken.Span.End;
			var ns = tree.DescendantNodes().OfType<NamespaceDeclarationSyntax>().FirstOrDefault();
			if (ns != null)
				return ns.OpenBraceToken.Span.End;
			return 0;
		}
开发者ID:kontur-edu,项目名称:uLearn,代码行数:13,代码来源:ExerciseBuilder.cs

示例4: Normalize

    private static SyntaxNode Normalize(SyntaxNode root, IEnumerable<SyntaxNode> members, Scope scope)
    {
        var appClass = root
                .DescendantNodes()
                .OfType<ClassDeclarationSyntax>()
                .Where(@class => @class.Identifier.ToString() == "testclass")
                .FirstOrDefault();

            if (appClass == null)
                appClass = CSharp.ClassDeclaration("testclass");

            return CSharp.CompilationUnit()
                .WithMembers(CSharp.List(new[] {(MemberDeclarationSyntax)
                appClass
                    .WithMembers(CSharp.List(
                     members.Select(
                         member => {
                             var method = member as MethodDeclarationSyntax;
                             if (method == null)
                                 return member;

                             return method.WithParameterList(
                                method
                                .ParameterList
                                .AddParameters(CSharp.Parameter(
                                    CSharp.ParseToken("result"))
                                    .WithType(CSharp.ParseTypeName("Dictionary<string, object>"))));})))}));
    }
开发者ID:mpmedia,项目名称:Excess,代码行数:28,代码来源:RuntimeHelper.cs

示例5: FindViolatingAssignments

        private static void FindViolatingAssignments(SyntaxNodeAnalysisContext context, SyntaxNode syntaxNode, SyntaxToken identifier)
        {
            IEnumerable<AssignmentExpressionSyntax> assignments = syntaxNode.DescendantNodes().OfType<AssignmentExpressionSyntax>();

            foreach (var violatingAssignment in assignments.Where(ass => ass.Left is IdentifierNameSyntax
                                             && ((IdentifierNameSyntax)ass.Left).Identifier.Value == identifier.Value))
                context.ReportDiagnostic(Diagnostic.Create(Rule, violatingAssignment.GetLocation()));
        }
开发者ID:mytinyfast,项目名称:CSharpCodingGuidelines,代码行数:8,代码来源:AV1530.cs

示例6: VariableExists

 public static bool VariableExists(SyntaxNode root, params string[] variableNames)
 {
     return root
         .DescendantNodes()
         .OfType<VariableDeclarationSyntax>()
         .SelectMany(ps => ps.DescendantTokens().Where(t => t.IsKind(SyntaxKind.IdentifierToken) && variableNames.Contains(t.ValueText)))
         .Any();
 }
开发者ID:hakenr,项目名称:RoslynCodeRefactoringPlayground,代码行数:8,代码来源:RoslynHelpers.cs

示例7: inheritsFromController

        public bool inheritsFromController(SyntaxNode root, String args)
        {

            bool isValid = false;

            try
            {
                 isValid = root.DescendantNodes().OfType<BaseTypeSyntax>().First().ToString().Equals("ApiController") ||
                   root.DescendantNodes().OfType<BaseTypeSyntax>().First().ToString().Equals("Controller");
            }
            catch (InvalidOperationException)
            {
                isValid = false;   
            }

            return isValid;
        }
开发者ID:hxp2k6,项目名称:DotNET-MVC-Enumerator,代码行数:17,代码来源:ControllerChecker.cs

示例8: IsMethodUsed

 private static bool IsMethodUsed(MethodDeclarationSyntax methodTarget, SyntaxNode typeDeclaration)
 {
     var descendents = typeDeclaration.DescendantNodes();
     var hasIdentifier = descendents.OfType<IdentifierNameSyntax>();
     if (hasIdentifier.Any(a => a != null && a.Identifier.ValueText.Equals(methodTarget.Identifier.ValueText)))
         return true;
     var genericNames = descendents.OfType<GenericNameSyntax>();
     return genericNames.Any(n => n != null && n.Identifier.ValueText.Equals(methodTarget.Identifier.ValueText));
 }
开发者ID:JeanLLopes,项目名称:code-cracker,代码行数:9,代码来源:RemovePrivateMethodNeverUsedAnalyzer.cs

示例9: ClassInitialize

 public static void ClassInitialize(TestContext context)
 {
     var tree = CSharpSyntaxTree.ParseText(source);
     var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
     var compilation = CSharpCompilation.Create(nameof(GetVariableString), new[] { tree }, new[] { mscorlib });
     semanticModel = compilation.GetSemanticModel(tree);
     syntaxRoot = tree.GetRoot();
     method1 = syntaxRoot.DescendantNodes().OfType<MethodDeclarationSyntax>().First();
     invocations = method1.Body.ChildNodes().OfType<ExpressionStatementSyntax>().Select(x => x.Expression as InvocationExpressionSyntax).ToArray();
 }
开发者ID:occar421,项目名称:OpenTKAnalyzer,代码行数:10,代码来源:IdentifierTests.GetVariableString.cs

示例10: MoveToMatchingFileAsync

 private async Task<Solution> MoveToMatchingFileAsync(Document document, SyntaxNode syntaxTree, TypeDeclarationSyntax declaration, CancellationToken cancellationToken)
 {
     var otherTypeDeclarationsInFile = syntaxTree.DescendantNodes().Where(originalNode => TypeDeclarationOtherThan(declaration, originalNode)).ToList();
     string newFilePath = GetNewFilePath(document, declaration);
     var newDocumentSyntaxTree = GetNewDocumentSyntaxTree(syntaxTree, otherTypeDeclarationsInFile);
     var newFile = document.Project.AddDocument(newFilePath, newDocumentSyntaxTree.GetText(), document.Folders);
     var solutionWithClassRemoved = GetDocumentWithClassDeclarationRemoved(newFile.Project, document, syntaxTree, declaration, otherTypeDeclarationsInFile);
     
     return document.Project.RemoveDocument(document.Id).Solution;
 }
开发者ID:GrahamTheCoder,项目名称:RoslynSpike,代码行数:10,代码来源:CodeFixProvider.cs

示例11: IsCreateTaskInLoop

 public void IsCreateTaskInLoop(SyntaxNode node)
 {
     if (node.DescendantNodes().OfType<IdentifierNameSyntax>().Any(a => "StartNew".Equals(a.ToString()))
         && !node.ToString().Contains("Stopwatch"))
     {
         if (Id.ToLower().Contains("test"))
             Helper.WriteInstance(LoopTaskTestFile, Id, node.Parent.ToString());
         else
             Helper.WriteInstance(LoopTaskFile, Id, node.Parent.ToString());
     }
 }
开发者ID:modulexcite,项目名称:concurrent-code-analyses,代码行数:11,代码来源:ThreadTaskAnalysisWalker.cs

示例12: CreateExtensionClass

        private static SyntaxNode CreateExtensionClass(SyntaxNode root, Scope scope)
        {
            if (!root
                .DescendantNodes()
                .OfType<ClassDeclarationSyntax>()
                .Where(@class => @class.Identifier.ToString() == "Extension")
                .Any())
                return ExtensionClass;

            return root;
        }
开发者ID:mpmedia,项目名称:Excess,代码行数:11,代码来源:ExtensionRuntime.cs

示例13: GetExpandableProperties

        internal static IEnumerable<ExpandablePropertyInfo> GetExpandableProperties(TextSpan span, SyntaxNode root, SemanticModel model)
        {
            var propertiesInTypes = root.DescendantNodes(span)
                       .OfType<PropertyDeclarationSyntax>()
                       .Select(p => GetExpandablePropertyInfo(p, model))
                       .Where(p => p != null)
                       .GroupBy(p => p.PropertyDeclaration.FirstAncestorOrSelf<TypeDeclarationSyntax>());

            return propertiesInTypes.Any()
                ? propertiesInTypes.First()
                : Enumerable.Empty<ExpandablePropertyInfo>();
        }
开发者ID:jerriclynsjohn,项目名称:roslyn,代码行数:12,代码来源:ExpansionChecker.cs

示例14: GetMissingEnumMembers

        //--- Class Methods ---
        public static IEnumerable<ISymbol> GetMissingEnumMembers(SyntaxNode switchNode, SemanticModel semanticModel, out IdentifierNameSyntax switchVariable)
        {
            switchVariable = switchNode.DescendantNodes().OfType<IdentifierNameSyntax>().First();
            var switchVariableTypeInfo = semanticModel.GetTypeInfo(switchVariable);

            // check if we are switching over an enum
            if(switchVariableTypeInfo.Type.TypeKind == TypeKind.Enum) {

                // get all the enum values
                var enumMembers = switchVariableTypeInfo.Type.GetMembers().Where(x => x.Kind == SymbolKind.Field).ToImmutableArray();

                // get all case statements
                var caseSwitchLabels = switchNode
                    .DescendantNodes().OfType<CaseSwitchLabelSyntax>()
                    .Select(x => x.DescendantNodes().OfType<MemberAccessExpressionSyntax>().FirstOrDefault())
                    .Where(x => x != null)
                    .Select(x => semanticModel.GetSymbolInfo(x).Symbol)
                    .ToImmutableHashSet();

                // make sure we have all cases covered
                return enumMembers.Where(x => !caseSwitchLabels.Contains(x)).ToImmutableArray();
            }
            return Enumerable.Empty<ISymbol>();
        }
开发者ID:manuel-sugawara,项目名称:RoslynAnalyzers,代码行数:25,代码来源:EnumSwitchAnalysis.cs

示例15: HasSameDocumentation

 /// <summary>
 /// checks if the documentation from the class member is the same as the one
 /// from the mixin member. 
 /// This only works if both have only one member
 /// </summary>
 /// <param name="classDeclaration"></param>
 /// <param name="mixin"></param>
 /// <returns>true if member documentation is identical, false otherwise</returns>
 public static bool HasSameDocumentation(SyntaxNode classDeclaration, MixinReference mixin)
 {
     var documentationFromChild = classDeclaration
        .DescendantNodes(descendIntoTrivia: true)
        .Last(x => x is DocumentationCommentTriviaSyntax)
        .GetText().ToString();
     // get generated documentation from mixin
     var documentationFromMixin = 
         mixin
         .Class
         .MembersFromThisAndBase
         .Single()
         .Documentation
         .ToString();
     return documentationFromChild == documentationFromMixin;
 }
开发者ID:pgenfer,项目名称:mixinSharp,代码行数:24,代码来源:ValidationHelpers.cs


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