/// <summary> /// Get the syntax node's first ancestor of the specified kind. /// </summary> /// <param name="syntaxNode"> /// The target syntax node. /// </param> /// <param name="syntaxKind"> /// The kind of node to find. /// </param> /// <returns> /// The ancestor node, or <c>null</c> if no ancestor of the specified kind was found. /// </returns> public static SyntaxNode GetFirstParentOfKind(this SyntaxNode syntaxNode, SyntaxKind syntaxKind) { if (syntaxNode == null) { throw new ArgumentNullException(nameof(syntaxNode)); } if (syntaxNode.Kind == syntaxKind) { return(syntaxNode); } return(syntaxNode.AncestorNodes().FirstOrDefault(node => node.Kind == syntaxKind)); }
/// <summary> /// Get the syntax node's first ancestor of any of the specified kinds. /// </summary> /// <param name="syntaxNode"> /// The target syntax node. /// </param> /// <param name="syntaxKinds"> /// The kinds of node to find. /// </param> /// <returns> /// The ancestor node, or <c>null</c> if no ancestor of any of the specified kinds was found. /// </returns> public static SyntaxNode GetFirstParentOfKinds(this SyntaxNode syntaxNode, params SyntaxKind[] syntaxKinds) { if (syntaxNode == null) { throw new ArgumentNullException(nameof(syntaxNode)); } HashSet <SyntaxKind> kinds = new HashSet <SyntaxKind>(syntaxKinds); if (kinds.Contains(syntaxNode.Kind)) { return(syntaxNode); } return(syntaxNode.AncestorNodes().FirstOrDefault(node => kinds.Contains(node.Kind))); }
/// <summary> /// Get the syntax node's first ancestor of the specified type. /// </summary> /// <param name="syntaxNode"> /// The target syntax node. /// </param> /// <returns> /// The ancestor node, or <c>null</c> if no ancestor of the specified type was found. /// </returns> public static TSyntax GetFirstParentOfType <TSyntax>(this SyntaxNode syntaxNode) { return(syntaxNode.AncestorNodes().OfType <TSyntax>().FirstOrDefault()); }