Reputation: 1494
For now, i can write in VS2017:
var какаяТоНепонятнаяПеременная = "some variable value here";
and VS2017 has compiled it successfully. I want to allow to write variable names only using letters from the English alphabet.
Upvotes: 1
Views: 212
Reputation: 2314
I do not know how to quickly inject my code into compiler process to force build failure, but that's theoretically feasible. What I can suggest is a workaround with unit tests based on Roslyn
. The starting point will be an installation of Microsoft.Build, Microsoft.CodeAnalysis.Analyzers, Microsoft.CodeAnalysis.Workspaces.MSBuild nuget packages. The idea is to load a solution and then a project you want to scan (using MSBuildWorkpace
api) and iterate through all Documents(files). You asked about validating variable names, so it means you need to detect IdentifierNameSyntax
items in the SyntaxTree
, however that's not the only thing you can detect - MethodDeclarationSyntax
, ClassDeclarationSyntax
etc. are detectable too. The sample code is below:
[Test]
public async Task Verify_ProjectDoesNotHaveNonASCIICharacters()
{
var project = workspace.CurrentSolution.Projects.Single(p => p.Name == "csproj_name");
foreach (var document in project.Documents)
{
var semanticModel = await document.GetSemanticModelAsync();
foreach (var item in semanticModel.SyntaxTree.GetRoot().DescendantNodes())
{
switch (item)
{
// you may catch other Syntax types for methods, class names for example
case IdentifierNameSyntax identifierName:
Assert.IsFalse(ContainsUnicodeCharacter(identifierName.Identifier.Text), $"Variable {identifierName.Identifier.Text} in {document.Name} contains non ASCII characters");
break;
}
}
}
}
ASCII character check can be improved, but I used the code from here for the sake of time:
private bool ContainsUnicodeCharacter(string input)
{
const int MaxAnsiCode = 255;
return input.Any(c => c > MaxAnsiCode);
}
Some sample code to setup MSBuildWorkspace:
var workspace = MSBuildWorkspace.Create();
await workspace.OpenSolutionAsync("...your_path/solution.sln");
Upvotes: 2