Created
May 29, 2019 15:16
-
-
Save amis92/f4d56e202e831ed2a373fe8b146424ae to your computer and use it in GitHub Desktop.
BuggedGenerator providing options to report warning, error or throw exception within CodeGeneration.Roslyn generator
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; | |
using System.Linq; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using CodeGeneration.Roslyn; | |
using Microsoft.CodeAnalysis; | |
using Microsoft.CodeAnalysis.CSharp; | |
using Microsoft.CodeAnalysis.CSharp.Syntax; | |
namespace BuggedGenerator | |
{ | |
public class ErrorGenerator : ICodeGenerator | |
{ | |
private readonly AttributeData attributeData; | |
private DiagnosticDescriptor WarnDescriptor { get; } | |
= new DiagnosticDescriptor( | |
"TEST001", | |
"Custom Warning Diagnostic Title", | |
"Message format for warning is here", | |
"TST", | |
DiagnosticSeverity.Warning, | |
isEnabledByDefault: true); | |
private DiagnosticDescriptor ErrorDescriptor { get; } | |
= new DiagnosticDescriptor( | |
"TEST002", | |
"Custom Error Diagnostic Title", | |
"Message format for error is here", | |
"TST", | |
DiagnosticSeverity.Error, | |
isEnabledByDefault: true); | |
public ErrorGenerator(AttributeData attributeData) | |
{ | |
this.attributeData = attributeData; | |
} | |
public Task<SyntaxList<MemberDeclarationSyntax>> GenerateAsync( | |
TransformationContext context, | |
IProgress<Diagnostic> progress, | |
CancellationToken cancellationToken) | |
{ | |
if (attributeData.ConstructorArguments.Any(arg => arg.Value.ToString() == "warn")) | |
{ | |
progress.Report(Diagnostic.Create(WarnDescriptor, context.ProcessingNode.GetLocation())); | |
} | |
if (attributeData.ConstructorArguments.Any(arg => arg.Value.ToString() == "error")) | |
{ | |
progress.Report(Diagnostic.Create(ErrorDescriptor, context.ProcessingNode.GetLocation())); | |
} | |
if (attributeData.ConstructorArguments.Any(arg => arg.Value.ToString() == "throw")) | |
{ | |
throw new InvalidOperationException("Custom exception message"); | |
} | |
var prop = SyntaxFactory.ParseMemberDeclaration("public int Bugger { get; }"); | |
return Task.FromResult(SyntaxFactory.List<MemberDeclarationSyntax>(new []{ prop })); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To create attribute: