Last active
September 30, 2020 15:35
-
-
Save kolesnick/e05c0cdb62e7902d08bf98457c412577 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Linq; | |
using Microsoft.CodeAnalysis; | |
using Microsoft.CodeAnalysis.CSharp; | |
using Microsoft.CodeAnalysis.CSharp.Syntax; | |
using NUnit.Framework; | |
using static Microsoft.CodeAnalysis.CSharp.SyntaxKind; | |
namespace Tests | |
{ | |
public class RoslynAnalysisTests | |
{ | |
const string BadFile1 = "class A {}"; | |
const string BadFile2 = "class B { class C {} }"; | |
const string GoodFile1 = "namespace N { class A {} }"; | |
const string GoodFile2 = "namespace N { class X { class Y {} } }"; | |
[Test] | |
public void TestAllFiles() | |
{ | |
string[] files = { BadFile1, GoodFile1, BadFile2, GoodFile2 }; | |
var badFiles = | |
files | |
.Select(file => CSharpSyntaxTree.ParseText(file)) | |
.SelectMany(AllClasses) | |
.Where(OutsideOfNamespace); | |
CollectionAssert.IsEmpty(badFiles); | |
} | |
static bool OutsideOfNamespace(ClassDeclarationSyntax classNode) => classNode.Ancestors().All(NotANamespace); | |
static bool NotANamespace(SyntaxNode node) => node.Kind() != NamespaceDeclaration; | |
static IEnumerable<ClassDeclarationSyntax> AllClasses(SyntaxTree syntaxTree) => AllNodes(syntaxTree).OfType<ClassDeclarationSyntax>(); | |
static IEnumerable<SyntaxNode> AllNodes(SyntaxTree syntaxTree) => syntaxTree.GetRoot().DescendantNodesAndSelf(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment