Skip to content

Instantly share code, notes, and snippets.

@nesteruk
Last active December 13, 2015 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nesteruk/4987154 to your computer and use it in GitHub Desktop.
Save nesteruk/4987154 to your computer and use it in GitHub Desktop.
R# plugin class creation sample
private static class ReadOnlyIntefaceBuilderWorkflow
{
public static WorkflowResult Start([CanBeNull] CSharpGeneratorContext context, CSharpElementFactory factory)
{
if (context.ClassDeclaration == null) return WorkflowResult.Inapplicable;
return CreateNewInterfaceDeclaration(context, factory);
}
private static WorkflowResult CreateNewInterfaceDeclaration(CSharpGeneratorContext context, CSharpElementFactory factory)
{
string interfaceName = "IReadOnly" + context.ClassDeclaration.DeclaredName;
var itfDecl = (IInterfaceDeclaration)factory.CreateTypeMemberDeclaration("interface " + interfaceName + " {}");
return AddInterfaceToContainingNamespace(context, itfDecl, factory);
}
private static WorkflowResult AddInterfaceToContainingNamespace(CSharpGeneratorContext context, IInterfaceDeclaration itfDecl, CSharpElementFactory factory)
{
var ns = context.ClassDeclaration.GetContainingNamespaceDeclaration();
if (ns == null) return WorkflowResult.Inapplicable;
else
{
var typeDecl = ns.AddTypeDeclarationBefore(itfDecl, context.ClassDeclaration);
return PopulateInterfaceDeclaration(context, factory, (IInterfaceDeclaration)typeDecl);
}
}
private static WorkflowResult PopulateInterfaceDeclaration(CSharpGeneratorContext context, CSharpElementFactory factory, IInterfaceDeclaration itfDecl)
{
var props = context.InputElements.OfType<GeneratorDeclaredElement<ITypeOwner>>().ToList();
foreach (var prop in props)
{
var propDecl = (IClassMemberDeclaration)factory.CreateTypeMemberDeclaration("public $0 $1 { get; }", prop.DeclaredElement.Type, prop.DeclaredElement.ShortName);
itfDecl.AddClassMemberDeclaration(propDecl);
}
return EnsureClassImplementsInterface(context, itfDecl);
}
private static WorkflowResult EnsureClassImplementsInterface(CSharpGeneratorContext context, IInterfaceDeclaration itfDecl)
{
var interfaceType = TypeFactory.CreateType(itfDecl.DeclaredElement);
context.ClassDeclaration.AddSuperInterface(interfaceType, false);
return WorkflowResult.Success;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment