Skip to content

Instantly share code, notes, and snippets.

@amis92
Created May 29, 2019 15:16
Show Gist options
  • Save amis92/f4d56e202e831ed2a373fe8b146424ae to your computer and use it in GitHub Desktop.
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
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 }));
}
}
}
@amis92
Copy link
Author

amis92 commented May 29, 2019

To create attribute:

    [CodeGenerationAttribute("BuggedGenerator.ErrorGenerator, BuggedGenerator")]
    class ErrorGenAttribute : Attribute
    {
        public ErrorGenAttribute(string action = null)
        {
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment