Skip to content

Instantly share code, notes, and snippets.

@thomaslevesque
Created May 10, 2017 01:10
Show Gist options
  • Save thomaslevesque/0e530476ddbaadb22e827c7308fb3e45 to your computer and use it in GitHub Desktop.
Save thomaslevesque/0e530476ddbaadb22e827c7308fb3e45 to your computer and use it in GitHub Desktop.
Generate "warnings as errors" ruleset from error code definitions in Roslyn source code
void Main()
{
string errorCodesFileUrl = "https://raw.githubusercontent.com/dotnet/roslyn/master/src/Compilers/CSharp/Portable/Errors/ErrorCode.cs";
string errorCodesFileContent = new WebClient().DownloadString(errorCodesFileUrl);
var syntaxTree = CSharpSyntaxTree.ParseText(errorCodesFileContent);
var root = syntaxTree.GetRoot();
var enumDeclaration =
root.DescendantNodes()
.OfType<EnumDeclarationSyntax>()
.First(e => e.Identifier.ValueText == "ErrorCode");
var errorCodes =
enumDeclaration
.Members
.Select(m => new ErrorCode(m))
.ToList();
var doc =
new XDocument(
new XElement("RuleSet",
new XAttribute("Name", "C# Warnings as Errors"),
new XAttribute("ToolsVersion", "15.0"),
new XElement("Rules",
new XAttribute("AnalyzerId", "Microsoft.CodeAnalysis.CSharp"),
new XAttribute("RuleNamespace", "Microsoft.CodeAnalysis.CSharp"),
from e in errorCodes
where e.Level == "WRN"
select new XElement("Rule",
new XAttribute("Id", e.Code),
new XAttribute("Action", "Error")))));
doc.Save(Console.Out);
}
class ErrorCode
{
public ErrorCode(EnumMemberDeclarationSyntax member)
{
string name = member.Identifier.ValueText;
if (name == "Void" || name == "Unknown")
{
Name = name;
Value = 0;
Level = "UNK";
}
else
{
Name = name.Substring(4);
Value = int.Parse(member.EqualsValue?.Value?.GetText()?.ToString() ?? "0");
Level = name.Substring(0, 3);
}
}
public string Name { get; }
public int Value { get; }
public string Level { get; }
public string Code => $"CS{Value:D4}";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment