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


C# SyntaxNode.Ancestors方法代码示例

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


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

示例1: Check

 void Check(SyntaxNode n)
 {
     var info = nodeContext.SemanticModel.GetSymbolInfo(n);
     var symbol = info.Symbol;
     if ((symbol == null) || (symbol.ContainingType == null) || symbol.ContainingType.Locations.Where(loc => loc.IsInSource && loc.SourceTree.FilePath == type.SyntaxTree.FilePath).All(loc => !type.Span.Contains(loc.SourceSpan)))
         return;
     if (!symbol.IsSealed && (symbol.IsVirtual || symbol.IsAbstract || symbol.IsOverride))
     {
         if (symbol.Kind == SymbolKind.Property)
         {
             var propertySymbol = symbol as IPropertySymbol;
             if (propertySymbol != null)
             {
                 if (n.Ancestors().Any(a => a is AssignmentExpressionSyntax))
                 {
                     var setterMethodSymbol = propertySymbol.SetMethod;
                     if ((setterMethodSymbol != null) && (setterMethodSymbol.DeclaredAccessibility == Accessibility.Private))
                         return;
                 }
                 else
                 {
                     var getterMethodSymbol = propertySymbol.GetMethod;
                     if ((getterMethodSymbol != null) && (getterMethodSymbol.DeclaredAccessibility == Accessibility.Private))
                         return;
                 }
             }
             else
             {
                 return;
             }
         }
         Diagnostics.Add(Diagnostic.Create(descriptor, n.GetLocation()));
     }
 }
开发者ID:pgrefviau,项目名称:RefactoringEssentials,代码行数:34,代码来源:DoNotCallOverridableMethodsInConstructorAnalyzer.cs

示例2: GetRootNodeOfLine

 private static SyntaxNode GetRootNodeOfLine(SyntaxNode node) {
     int nodeLocationLine = node.GetLocation().GetLineSpan().StartLinePosition.Line;
     var ancestors = node.Ancestors();
     var nodeLocationCharacter = ancestors.Where(ancestor => GetSpanLocation(ancestor).Start.Line == nodeLocationLine)
         .Min(ancestor => GetSpanLocation(ancestor).Start.Character);
     return ancestors.Last(ancestor => GetSpanLocation(ancestor).Start == new LinePosition(nodeLocationLine, nodeLocationCharacter));
 }
开发者ID:vuder,项目名称:CodingStandardCodeAnalyzers,代码行数:7,代码来源:TimeMeasurementCodeAnalyzerCodeFixProvider.cs

示例3: GetTypeSymbols

 public static IEnumerable<NamedSymbol> GetTypeSymbols(this SemanticModel semanticModel, SyntaxNode node)
 {
     var typesymbols = semanticModel.LookupSymbols(node.SpanStart)
         .OfType<ILocalSymbol>()
         .Where(x => x.Locations.Any() && x.Locations.First().GetLineSpan().StartLinePosition < node.GetLocation().GetLineSpan().StartLinePosition)
         .Select(x => new NamedSymbol( x.Name,  x.Type))
         .Concat(
             semanticModel.LookupSymbols(node.SpanStart)
                 .OfType<IParameterSymbol>()
                 .Select(x => new NamedSymbol( x.Name,  x.Type))
         ).Concat(
             semanticModel.LookupSymbols(node.SpanStart)
                 .OfType<IPropertySymbol>()
                 .Select(x => new NamedSymbol( x.Name,  x.Type))
         ).Concat(
             semanticModel.LookupSymbols(node.SpanStart)
                 .OfType<IFieldSymbol>()
                 .Select(x => new NamedSymbol( x.Name,  x.Type))
         );
     if (!semanticModel.GetEnclosingSymbol(node.SpanStart).IsStatic)
     {
         var classDeclaration = node.Ancestors().OfType<ClassDeclarationSyntax>().FirstOrDefault();
         if(classDeclaration!=null)
         {
             typesymbols = typesymbols.Concat(new NamedSymbol[]
             {
                 new NamedSymbol( "this",(ITypeSymbol)semanticModel.GetDeclaredSymbol(classDeclaration))
             });
         }
     }
     return typesymbols;
 }
开发者ID:jarlrasm,项目名称:PhilTheCartographer,代码行数:32,代码来源:SemanticModelExtensions.cs

示例4: IsInStateScope

        /// <summary>
        /// True if the given syntax node is in the scope of a state.
        /// </summary>
        /// <param name="node">SyntaxNode</param>
        /// <returns>Boolean</returns>
        protected bool IsInStateScope(SyntaxNode node)
        {
            var result = false;

            var ancestors = node.Ancestors().OfType<ClassDeclarationSyntax>().ToList();
            foreach (var ancestor in ancestors)
            {
                result = this.Project.PSharpPrograms.
                    SelectMany(p => p.NamespaceDeclarations).
                    SelectMany(n => n.MachineDeclarations).
                    SelectMany(m => m.StateDeclarations).
                    Any(s => s.Identifier.TextUnit.Text.Equals(ancestor.Identifier.ValueText));

                if (result)
                {
                    break;
                }
            }

            return result;
        }
开发者ID:huangpf,项目名称:PSharp,代码行数:26,代码来源:CSharpRewriter.cs

示例5: FixMissingType

        private static void FixMissingType(SyntaxNode node, Scope scope)
        {
            var type = node
                .Ancestors()
                .OfType<TypeDeclarationSyntax>()
                .FirstOrDefault();

            if (type != null)
            {
                var typeScope = scope.GetScope<SyntaxToken, SyntaxNode, SemanticModel>(type);
                if (typeScope != null)
                {
                    SyntaxNode realType = typeScope.get<SyntaxNode>("__tdef" + node.ToString());
                    if (realType != null)
                    {
                        realType = RoslynCompiler.Mark(realType); //make sure not to duplicate nodes

                        var document = scope.GetDocument<SyntaxToken, SyntaxNode, SemanticModel>();
                        document.change(node, RoslynCompiler.ReplaceNode(realType));
                    }
                }
            }
        }
开发者ID:mpmedia,项目名称:Excess,代码行数:23,代码来源:TypeDef.cs

示例6: GenerateName

            public string GenerateName(SyntaxNode node)
            {
                Debug.Assert(IsNameableNode(node));

                var builder = new StringBuilder();

                var ancestors = node.Ancestors().ToArray();
                for (int i = ancestors.Length - 1; i >= 0; i--)
                {
                    var ancestor = ancestors[i];

                    // We skip "unnameable" nodes to ensure that we don't add empty names
                    // for nodes like the compilation unit or field declarations.
                    if (IsNameableNode(ancestor))
                    {
                        AppendNodeName(builder, ancestor);
                    }
                }

                AppendNodeName(builder, node);

                return builder.ToString();
            }
开发者ID:Rickinio,项目名称:roslyn,代码行数:23,代码来源:AbstractCodeModelService.AbstractNodeNameGenerator.cs

示例7: TryGetParentMachine

        /// <summary>
        /// Tries to return the parent machine identifier, if any.
        /// </summary>
        /// <param name="node">SyntaxNode</param>
        /// <param name="machine">MachineDeclaration</param>
        /// <returns>Boolean value</returns>
        protected bool TryGetParentMachine(SyntaxNode node, out MachineDeclaration machine)
        {
            var result = false;
            machine = null;

            var ancestors = node.Ancestors().OfType<ClassDeclarationSyntax>().ToList();
            foreach (var ancestor in ancestors)
            {
                machine = this.Project.PSharpPrograms.
                    SelectMany(p => p.NamespaceDeclarations).
                    SelectMany(n => n.MachineDeclarations).
                    FirstOrDefault(s => s.Identifier.TextUnit.Text.Equals(ancestor.Identifier.ValueText));

                if (machine != null)
                {
                    result = true;
                    break;
                }
            }

            return result;
        }
开发者ID:jerickmsft,项目名称:PSharp,代码行数:28,代码来源:PSharpRewriter.cs

示例8: CanAddImportForType

        protected override bool CanAddImportForType(Diagnostic diagnostic, ref SyntaxNode node)
        {
            switch (diagnostic.Id)
            {
                case CS0103:
                case CS0246:
                case CS0305:
                case CS0308:
                case CS0122:
                case CS0307:
                case CS0616:
                case CS1003:
                case CS1580:
                case CS1581:
                    break;

                case CS1002:
                    //// only lookup errors inside ParenthesizedLambdaExpression e.g., () => { ... }
                    if (node.Ancestors().OfType<ParenthesizedLambdaExpressionSyntax>().Any())
                    {
                        if (node is SimpleNameSyntax)
                        {
                            break;
                        }
                        else if (node is BlockSyntax || node is MemberAccessExpressionSyntax || node is BinaryExpressionSyntax)
                        {
                            var last = node.DescendantNodes().OfType<SimpleNameSyntax>().LastOrDefault();
                            if (!TryFindStandaloneType(ref node))
                            {
                                node = node.DescendantNodes().OfType<SimpleNameSyntax>().FirstOrDefault();
                            }
                            else
                            {
                                node = last;
                            }
                        }
                    }
                    else
                    {
                        return false;
                    }

                    break;

                case CS1574:
                case CS1584:
                    var cref = node as QualifiedCrefSyntax;
                    if (cref != null)
                    {
                        node = cref.Container;
                    }

                    break;

                default:
                    return false;
            }

            return TryFindStandaloneType(ref node);
        }
开发者ID:reidwooten99apps,项目名称:roslyn,代码行数:60,代码来源:CSharpAddImportCodeFixProvider.cs

示例9: GetContainingMember

		private static SyntaxNode GetContainingMember(SyntaxNode oldNode)
		{
			var parenthesizedLambda = oldNode
				.Ancestors()
				.FirstOrDefault(n =>
				                n.IsKind(SyntaxKind.ParenthesizedLambdaExpression));

			if (parenthesizedLambda != null)
			{
				return parenthesizedLambda;
			}

			var simpleLambda = oldNode
				.Ancestors()
				.FirstOrDefault(n =>
				                n.IsKind(SyntaxKind.SimpleLambdaExpression));

			if (simpleLambda != null)
			{
				return simpleLambda;
			}

			return oldNode
				.Ancestors()
				.FirstOrDefault(n =>
				                n.IsKind(SyntaxKind.MethodDeclaration));
		}
开发者ID:FreeBSD-DotNet,项目名称:monodevelop,代码行数:27,代码来源:CSharpAddAsyncCodeFixProvider.cs

示例10: GetIdentifiersInScope

        private static IEnumerable<string> GetIdentifiersInScope(SyntaxNode node)
        {
            var withinFirstClass = true;
            foreach (var ancestor in node.Ancestors())
            {
                switch (ancestor.Kind())
                {
                    case SyntaxKind.IndexerDeclaration:
                        var indexerDeclarationSyntax = (IndexerDeclarationSyntax)ancestor;
                        foreach (var parameter in indexerDeclarationSyntax.ParameterList.Parameters)
                        {
                            yield return parameter.Identifier.ValueText;
                        }
                        break;
                    case SyntaxKind.ConstructorDeclaration:
                        var constructorDeclarationSyntax = (ConstructorDeclarationSyntax)ancestor;
                        foreach (var parameter in constructorDeclarationSyntax.ParameterList.Parameters)
                        {
                            yield return parameter.Identifier.ValueText;
                        }
                        break;
                    case SyntaxKind.ParenthesizedLambdaExpression:
                        var parenthesizedLambdaExpressionSyntax = (ParenthesizedLambdaExpressionSyntax)ancestor;
                        foreach (var parameter in parenthesizedLambdaExpressionSyntax.ParameterList.Parameters)
                        {
                            yield return parameter.Identifier.ValueText;
                        }
                        break;
                    case SyntaxKind.SimpleLambdaExpression:
                        yield return ((SimpleLambdaExpressionSyntax)ancestor).Parameter.Identifier.ValueText;
                        break;
                    case SyntaxKind.MethodDeclaration:
                        var methodDeclarationSyntax = (MethodDeclarationSyntax)ancestor;
                        foreach (var parameter in methodDeclarationSyntax.ParameterList.Parameters)
                        {
                            yield return parameter.Identifier.ValueText;
                        }
                        yield return methodDeclarationSyntax.Identifier.ValueText;
                        if (methodDeclarationSyntax.TypeParameterList != null)
                        {
                            foreach (var typeParameter in methodDeclarationSyntax.TypeParameterList.Parameters)
                            {
                                yield return typeParameter.Identifier.ValueText;
                            }
                        }
                        break;
                    case SyntaxKind.StructDeclaration:
                    case SyntaxKind.ClassDeclaration:
                        var typeDeclarationSyntax = (TypeDeclarationSyntax)ancestor;
                        yield return typeDeclarationSyntax.Identifier.ValueText;
                        if (typeDeclarationSyntax.TypeParameterList != null)
                        {
                            foreach (var typeParameter in typeDeclarationSyntax.TypeParameterList.Parameters)
                            {
                                yield return typeParameter.Identifier.ValueText;
                            }
                        }
                        if (withinFirstClass)
                        {
                            var children = typeDeclarationSyntax.ChildNodes();
                            foreach (var property in children.OfType<PropertyDeclarationSyntax>())
                            {
                                yield return property.Identifier.ValueText;
                            }
                            foreach (var field in children.OfType<FieldDeclarationSyntax>())
                            {
                                foreach (var variable in field.Declaration.Variables)
                                {
                                    yield return variable.Identifier.ValueText;
                                }
                            }
                            withinFirstClass = false;
                        }
                        break;

                }
            }
        }
开发者ID:TylerBrinkley,项目名称:CSharpEssentials,代码行数:78,代码来源:UseNameOfAnalyzer.cs

示例11: WriteDetectedThreadingNamespaceUsage

        internal void WriteDetectedThreadingNamespaceUsage(Enums.ThreadingNamespaceDetected type, string documentPath, ISymbol symbol, SyntaxNode node)
        {
            if (Enums.ThreadingNamespaceDetected.None != type)
            {


                Logger usagelog=null;
                Logger typelog=null;

                switch (type)
                {
                    case Enums.ThreadingNamespaceDetected.ThreadClass:
                        usagelog = Logs.TempLog;
                        typelog = Logs.TempLog2;
                        break;
                    case Enums.ThreadingNamespaceDetected.ThreadpoolClass:
                        usagelog = Logs.TempLog3;
                        typelog = Logs.TempLog4;
                        break;
                    case Enums.ThreadingNamespaceDetected.OtherClass:
                        usagelog = Logs.TempLog5;
                        typelog = Logs.TempLog6;
                        break;
                }

                SyntaxNode block=null;
                var temp = node.Ancestors().OfType<BlockSyntax>();
                if (temp.Any())
                    block = temp.First();
                else
                    block = node.Ancestors().ElementAt(3);

                typelog.Info("{0};{1}", symbol.ContainingType, symbol.ToString());
                usagelog.Info("{0} {1}\r\n{2}\r\n--------------------------", symbol, documentPath,  block);


                //// Let's get rid of all specific information!
                //if (!symbol.ReturnsVoid)
                //    returntype = symbol.ReturnType.OriginalDefinition.ToString();

                //typelog.Info(@"{0};{1};{2};{3};{4};{5};{6};{7}", AppName, documentPath, type.ToString(), returntype, symbol.OriginalDefinition.ContainingNamespace, symbol.OriginalDefinition.ContainingType, symbol.OriginalDefinition.Name, ((MethodSymbol)symbol.OriginalDefinition).Parameters);
            }
        }
开发者ID:modulexcite,项目名称:concurrent-code-analyses,代码行数:43,代码来源:TaskifierAnalysisResult.cs

示例12: Visit

        public override void Visit(SyntaxNode node)
        {
            var padding = node.Ancestors().Count();
            var prepend = node.ChildNodes().Any() ? "[-]" : "[.]";
            var nodetype = node.GetType().FullName;
            if (nodetype.StartsWith(prefix)) nodetype = nodetype.Substring(prefix.Length);
            var line = new string(' ', padding) + prepend + " " + nodetype;
            Console.WriteLine(line);

            //var decl = node as ClassDeclarationSyntax;
            //if (decl != null && decl.BaseList != null)
            //{
            //    Console.Write(new string(' ', padding + 4) + decl.Identifier);
            //    foreach (var n in decl.BaseList.Types.OfType<IdentifierNameSyntax>())
            //    {
            //        Console.Write(" " + n.Identifier);
            //    }
            //    Console.WriteLine();
            //}

            var attr = node as AttributeSyntax;
            if (attr != null)
            {
                Console.WriteLine(new string(' ', padding + 4) + "> " + attr.Name);
                foreach (var arg in attr.ArgumentList.Arguments)
                {
                    var expr = arg.Expression as LiteralExpressionSyntax;
                    //Console.WriteLine(new string(' ', padding + 4) + "> " + arg.NameColon + " " + arg.NameEquals);
                    Console.WriteLine(new string(' ', padding + 4) + "> " + (expr == null ? null : expr.Token.Value));
                }
            }
            var attr2 = node as IdentifierNameSyntax;
            if (attr2 != null)
            {
                Console.WriteLine(new string(' ', padding + 4) + "T " + attr2.Identifier.GetType());
                Console.WriteLine(new string(' ', padding + 4) + "V " + attr2.Identifier);
            }

            var x = node as TypeSyntax;
            if (x != null)
            {
                var xtype = x.GetType().FullName;
                if (xtype.StartsWith(prefix)) xtype = nodetype.Substring(prefix.Length);
                Console.WriteLine(new string(' ', padding + 4) + "> " + xtype);
            }

            base.Visit(node);
        }
开发者ID:nul800sebastiaan,项目名称:Zbu.ModelsBuilder,代码行数:48,代码来源:RoslynTests.cs

示例13: Visit

        public override SyntaxNode Visit(SyntaxNode node)
        {
            Context.LastNode = node;
            try
            {

                if (node is NameEqualsSyntax)
                    return (node);

               

                //			SyntaxNode visit; //Needs update
                //                     if (FixPropertyUnaryExpressions(node, out visit))
                //                return visit;
                  if (node is IdentifierNameSyntax &&
                   //   (node.Parent is ExpressionSyntax || node.Parent is MethodDeclarationSyntax || node.Parent is PropertyDeclarationSyntax
                     // || node.Parent is BlockSyntax) &&
                      !(node.Parent.Parent is InitializerExpressionSyntax) &&
                      !(node.Parent is QualifiedNameSyntax) && !(node.Parent is MemberAccessExpressionSyntax) && !(node.Parent is ThisExpressionSyntax))
                  {
                      //Lets fully qualify these so that we can have property code working
                      var symbolInfo = _semanticModel.GetSymbolInfo(node);

                      if (symbolInfo.Symbol != null &&
                          (symbolInfo.Symbol.Kind == SymbolKind.Field || symbolInfo.Symbol.Kind == SymbolKind.Property))
                      {
                          if (symbolInfo.Symbol.ContainingType != null && symbolInfo.Symbol.IsStatic)
                          {
                              var newName = symbolInfo.Symbol.ContainingType.GetFullNameCSharp() + "." +
                                            symbolInfo.Symbol.Name;
                              return SyntaxFactory.ParseExpression(newName);
                          }
                          else
                          {

                              var firstParent =
                                  TypeProcessor.GetDeclaredSymbol(node.Ancestors().OfType<BaseTypeDeclarationSyntax>().First());
                              //_semanticModel.GetSymbolInfo(node.Ancestors().OfType<BaseTypeDeclarationSyntax>().First());
                              if (symbolInfo.Symbol.ContainingType != null && !symbolInfo.Symbol.IsStatic && symbolInfo.Symbol.ContainingType == firstParent)
                                  return SyntaxFactory.ParseExpression("this." + symbolInfo.Symbol.Name);
                          }
                          return base.Visit(node);
                      }
                  }

                if (node is MemberAccessExpressionSyntax &&
                //   (node.Parent is ExpressionSyntax || node.Parent is MethodDeclarationSyntax || node.Parent is PropertyDeclarationSyntax
                // || node.Parent is BlockSyntax) &&
                !(node.Parent.Parent is InitializerExpressionSyntax) &&
              !(node.Parent is QualifiedNameSyntax) && !(node.Parent is MemberAccessExpressionSyntax) && !(node.Parent is ThisExpressionSyntax))
            {
                var nodeasMember = node as MemberAccessExpressionSyntax;
                if (!(nodeasMember.Expression is ThisExpressionSyntax))
                { 
                //Lets fully qualify these so that we can have property code working
                var symbolInfo = _semanticModel.GetSymbolInfo(node);

                    if (symbolInfo.Symbol != null &&
                        (symbolInfo.Symbol.Kind == SymbolKind.Field || symbolInfo.Symbol.Kind == SymbolKind.Property))
                    {
                        if (symbolInfo.Symbol.ContainingType != null && symbolInfo.Symbol.IsStatic)
                        {
                            var newName = symbolInfo.Symbol.ContainingType.GetFullNameCSharp() + "." +
                                          symbolInfo.Symbol.Name;
                            return SyntaxFactory.ParseExpression(newName);
                        }
                        else
                        {
                            ISymbol symbol = TypeProcessor.GetSymbolInfo((node as MemberAccessExpressionSyntax).Expression).Symbol;
                            if (
                                symbol != null && (!(symbol
                                    is
                                    ILocalSymbol) && !(symbol is IParameterSymbol) && symbol.Name != ".ctor"))
                            {
                                var firstParent =
                                    TypeProcessor.GetDeclaredSymbol(
                                        node.Ancestors().OfType<BaseTypeDeclarationSyntax>().First());
                                //_semanticModel.GetSymbolInfo(node.Ancestors().OfType<BaseTypeDeclarationSyntax>().First());
                                if (symbolInfo.Symbol.ContainingType != null && !symbolInfo.Symbol.IsStatic &&
                                    symbolInfo.Symbol.ContainingType == firstParent)
                                    return SyntaxFactory.ParseExpression("this." + node.ToFullString());
                            }

                        }
                    }
                    return base.Visit(node);
                }
            }

            return base.Visit(node);
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
开发者ID:mortezabarzkar,项目名称:SharpNative,代码行数:97,代码来源:CSharpToDlangRewriter.cs


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