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


C# SyntaxNode.Ancestors方法代码示例

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


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

示例1: GetContainingMember

        private static SyntaxNode GetContainingMember(SyntaxNode oldNode)
        {
            foreach (var node in oldNode.Ancestors())
            {
                switch (node.Kind())
                {
                    case SyntaxKind.ParenthesizedLambdaExpression:
                    case SyntaxKind.SimpleLambdaExpression:
                    case SyntaxKind.AnonymousMethodExpression:
                        if ((node as AnonymousFunctionExpressionSyntax)?.AsyncKeyword.Kind() != SyntaxKind.AsyncKeyword)
                        {
                            return node;
                        }
                        break;
                    case SyntaxKind.MethodDeclaration:
                        if ((node as MethodDeclarationSyntax)?.Modifiers.Any(SyntaxKind.AsyncKeyword) == false)
                        {
                            return node;
                        }
                        break;
                    default:
                        continue;
                }
            }

            return null;
        }
开发者ID:RoryVL,项目名称:roslyn,代码行数:27,代码来源:CSharpAddAsyncCodeFixProvider.cs

示例2: Visit

 public override void Visit(SyntaxNode node)
 {
     int padding = node.Ancestors().Count();
     //To identify leaf nodes vs nodes with children
     string prepend = node.ChildNodes().Any() ? "[-]"
     : "[.]";
     //Get the type of the node
     string line = new String(' ', padding) + prepend
     + " " + node.GetType().ToString();
     //Write the line
     System.Console.WriteLine(line);
     base.Visit(node);
 }
开发者ID:dotnetcurry,项目名称:roslyn-dncmag-03,代码行数:13,代码来源:Program.cs

示例3: MakeLocalSymbolWithEnclosingContext

 /// <summary>
 /// Make a local variable symbol whose type can be inferred (if necessary) by binding and enclosing construct.
 /// </summary>
 internal static LocalSymbol MakeLocalSymbolWithEnclosingContext(
     Symbol containingSymbol,
     Binder scopeBinder,
     Binder nodeBinder,
     TypeSyntax typeSyntax,
     SyntaxToken identifierToken,
     LocalDeclarationKind kind,
     SyntaxNode nodeToBind,
     SyntaxNode forbiddenZone)
 {
     Debug.Assert(
         nodeToBind.Kind() == SyntaxKind.CasePatternSwitchLabel ||
         nodeToBind.Kind() == SyntaxKind.ArgumentList && nodeToBind.Parent is ConstructorInitializerSyntax ||
         nodeToBind.Kind() == SyntaxKind.VariableDeclarator &&
             new[] { SyntaxKind.LocalDeclarationStatement, SyntaxKind.ForStatement, SyntaxKind.UsingStatement, SyntaxKind.FixedStatement }.
                 Contains(nodeToBind.Ancestors().OfType<StatementSyntax>().First().Kind()) ||
         nodeToBind is ExpressionSyntax);
     return typeSyntax.IsVar
         ? new LocalSymbolWithEnclosingContext(containingSymbol, scopeBinder, nodeBinder, typeSyntax, identifierToken, kind, nodeToBind, forbiddenZone)
         : new SourceLocalSymbol(containingSymbol, scopeBinder, false, typeSyntax, identifierToken, kind);
 }
开发者ID:GuilhermeSa,项目名称:roslyn,代码行数:24,代码来源:SourceLocalSymbol.cs

示例4: GetDefaultParameterValue

        /// <summary>
        /// Gets the default value for the <paramref name="parameter"/>.
        /// </summary>
        /// <param name="syntax">
        /// A syntax node corresponding to the invocation.
        /// </param>
        /// <param name="parameter">
        /// A parameter to get the default value for.
        /// </param>
        /// <param name="enableCallerInfo">
        /// Indicates if caller info is to be enabled when processing this optional parameter.
        /// The value <see cref="ThreeState.Unknown"/> means the decision is to be made based on the shape of the <paramref name="syntax"/> node.
        /// </param>
        /// <remarks>
        /// DELIBERATE SPEC VIOLATION: When processing an implicit invocation of an <c>Add</c> method generated
        /// for an element-initializer in a collection-initializer, the parameter <paramref name="enableCallerInfo"/> 
        /// is set to <see cref="ThreeState.True"/>. It means that if the optional parameter is annotated with <see cref="CallerLineNumberAttribute"/>,
        /// <see cref="CallerFilePathAttribute"/> or <see cref="CallerMemberNameAttribute"/>, and there is no explicit argument corresponding to it,
        /// we will provide caller information as a value of this parameter.
        /// This is done to match the native compiler behavior and user requests (see http://roslyn.codeplex.com/workitem/171). This behavior
        /// does not match the C# spec that currently requires to provide caller information only in explicit invocations and query expressions.
        /// </remarks>
        private BoundExpression GetDefaultParameterValue(SyntaxNode syntax, ParameterSymbol parameter, ThreeState enableCallerInfo)
        {
            // TODO: Ideally, the enableCallerInfo parameter would be of just bool type with only 'true' and 'false' values, and all callers
            // explicitly provided one of those values, so that we do not rely on shape of syntax nodes in the rewriter. There are not many immediate callers, 
            // but often the immediate caller does not have the required information, so all possible call chains should be analyzed and possibly updated
            // to pass this information, and this might be a big task. We should consider doing this when the time permits.

            TypeSymbol parameterType = parameter.Type;
            Debug.Assert(parameter.IsOptional);
            ConstantValue defaultConstantValue = parameter.ExplicitDefaultConstantValue;
            BoundExpression defaultValue;
            SourceLocation callerSourceLocation;

            // For compatibility with the native compiler we treat all bad imported constant
            // values as default(T).  
            if (defaultConstantValue != null && defaultConstantValue.IsBad)
            {
                defaultConstantValue = ConstantValue.Null;
            }

            if (parameter.IsCallerLineNumber && ((callerSourceLocation = GetCallerLocation(syntax, enableCallerInfo)) != null))
            {
                int line = callerSourceLocation.SourceTree.GetDisplayLineNumber(callerSourceLocation.SourceSpan);
                BoundExpression lineLiteral = MakeLiteral(syntax, ConstantValue.Create(line), _compilation.GetSpecialType(SpecialType.System_Int32));

                if (parameterType.IsNullableType())
                {
                    defaultValue = MakeConversionNode(lineLiteral, parameterType.GetNullableUnderlyingType(), false);

                    // wrap it in a nullable ctor.
                    defaultValue = new BoundObjectCreationExpression(
                        syntax,
                        GetNullableMethod(syntax, parameterType, SpecialMember.System_Nullable_T__ctor),
                        defaultValue);
                }
                else
                {
                    defaultValue = MakeConversionNode(lineLiteral, parameterType, false);
                }
            }
            else if (parameter.IsCallerFilePath && ((callerSourceLocation = GetCallerLocation(syntax, enableCallerInfo)) != null))
            {
                string path = callerSourceLocation.SourceTree.GetDisplayPath(callerSourceLocation.SourceSpan, _compilation.Options.SourceReferenceResolver);
                BoundExpression memberNameLiteral = MakeLiteral(syntax, ConstantValue.Create(path), _compilation.GetSpecialType(SpecialType.System_String));
                defaultValue = MakeConversionNode(memberNameLiteral, parameterType, false);
            }
            else if (parameter.IsCallerMemberName && ((callerSourceLocation = GetCallerLocation(syntax, enableCallerInfo)) != null))
            {
                string memberName;

                switch (_factory.TopLevelMethod.MethodKind)
                {
                    case MethodKind.Constructor:
                    case MethodKind.StaticConstructor:
                        // See if the code is actually part of a field, field-like event or property initializer and return the name of the corresponding member.
                        var memberDecl = syntax.Ancestors().OfType<MemberDeclarationSyntax>().FirstOrDefault();

                        if (memberDecl != null)
                        {
                            BaseFieldDeclarationSyntax fieldDecl;

                            if (memberDecl.Kind() == SyntaxKind.PropertyDeclaration)
                            {
                                var propDecl = (PropertyDeclarationSyntax)memberDecl;
                                EqualsValueClauseSyntax initializer = propDecl.Initializer;

                                if (initializer != null && initializer.Span.Contains(syntax.Span))
                                {
                                    memberName = propDecl.Identifier.ValueText;
                                    break;
                                }
                            }
                            else if ((fieldDecl = memberDecl as BaseFieldDeclarationSyntax) != null)
                            {
                                memberName = null;

                                foreach (VariableDeclaratorSyntax varDecl in fieldDecl.Declaration.Variables)
                                {
//.........这里部分代码省略.........
开发者ID:jkotas,项目名称:roslyn,代码行数:101,代码来源:LocalRewriter_Call.cs

示例5: GetFullQualifierNameOfSyntaxNode

        /// <summary>
        /// Returns the full qualifier name of the given syntax node.
        /// </summary>
        /// <param name="syntaxNode">SyntaxNode</param>
        /// <returns>string</returns>
        private string GetFullQualifierNameOfSyntaxNode(SyntaxNode syntaxNode)
        {
            string result = "";

            if (syntaxNode == null)
            {
                return result;
            }

            SyntaxNode ancestor = null;
            while ((ancestor = syntaxNode.Ancestors().Where(val
                => val is ClassDeclarationSyntax).FirstOrDefault()) != null)
            {
                result = (ancestor as ClassDeclarationSyntax).Identifier.ValueText + "." + result;
                syntaxNode = ancestor;
            }

            ancestor = null;
            while ((ancestor = syntaxNode.Ancestors().Where(val
                => val is NamespaceDeclarationSyntax).FirstOrDefault()) != null)
            {
                result = (ancestor as NamespaceDeclarationSyntax).Name + "." + result;
                syntaxNode = ancestor;
            }

            return result;
        }
开发者ID:yonglehou,项目名称:PSharp,代码行数:32,代码来源:AnalysisContext.cs

示例6: AddNode

        private static void AddNode(ItemCollection items, SyntaxNode node, string prefix)
        {
            var tooltip = string.Join(Environment.NewLine, node.GetDiagnostics().Select(x => x.ToString()));
            var treeViewItem = new TreeViewItem
            {
                Background = (node.ContainsDiagnostics) ? Brushes.Pink : Brushes.Transparent,
                Foreground = (node.IsToken) ? Brushes.DarkGreen : (node.Ancestors().Any(a => a.IsToken) ? Brushes.DarkRed : Brushes.Blue),
                Header = $"{prefix}{node.Kind} [{node.SourceRange.Start}..{node.SourceRange.End})",
                ToolTip = string.IsNullOrEmpty(tooltip) ? null : tooltip,
                Tag = node
            };

            foreach (var childNode in node.ChildNodes)
                AddNode(treeViewItem.Items, childNode, string.Empty);

            if (node.IsToken)
            {
                var token = (SyntaxToken) node;
                foreach (var childNode in token.LeadingTrivia)
                    AddNode(treeViewItem.Items, childNode, "Lead: ");
                foreach (var childNode in token.TrailingTrivia)
                    AddNode(treeViewItem.Items, childNode, "Trail: ");
            }

            items.Add(treeViewItem);
        }
开发者ID:davidlee80,项目名称:HlslTools,代码行数:26,代码来源:SyntaxVisualizerToolWindowControl.xaml.cs

示例7: TryGetOutsideMethod

 /// <summary>
 /// Try to get the method declaration that is outside of the given node.
 /// </summary>
 /// <param name="node"></param>
 /// <returns></returns>
 public static SyntaxNode TryGetOutsideMethod(SyntaxNode node)
 {
     var methods = node.Ancestors().OfType<MethodDeclarationSyntax>().ToList();
     if (methods.Any())
     {
         return methods.First();
     }
     return null;
 }
开发者ID:nkcsgexi,项目名称:GhostFactor2,代码行数:14,代码来源:ConditionCheckersUtils.cs


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