ImplementMethodsVia.refscript

This page describes the ImplementMethodsVia RefactorScript shipped with VisualGDB.

Overview

This script generates implementations for the selected methods by forwarding the calls to a field, e.g.:
int method(int x) { return m_Field.method(x); }

In order to run this script, first select one or more methods in the Code Explorer -> Outline view.

Script


[Main, Description("Implement Methods via Field")]
generator ImplementMethodsViaField(Array methods,
                                   bool inline = true,
                                   string implementingClassName = "MyClass",
                                   string fieldExpression = "m_Impl.")
{
    foreach(method in methods)
    {
        if (inline)
        {
            GenerateMethodSignature(method, """");
            GenerateProxyMethodBody(method, implementingClassName, fieldExpression);
        }
        else
        {
            GenerateMethodSignature(method, """;");
        }
    }

    if (!inline)
    {
>
        foreach(method in methods)
        {
            set prefix = implementingClassName + "::";
            GenerateMethodSignature(method, prefix, "");
            GenerateProxyMethodBody(method, implementingClassName, fieldExpression);
        }
    }
}

generator GenerateMethodSignature(Function method, string prefix, string suffix)
{
>>$method.ReturnType.Literal $prefix$method.ShortName(
        foreach(arg in method.Arguments)
        {
>>$arg.Type.Literal $arg.ShortName
            if (arg.HasInitializer)
>> /* = $arg.Initializer */
            if (!arg.IsLast)
>>, 
        }
>)$suffix
}

generator GenerateProxyMethodBody(Function method,
                                  string implementingClassName,
                                  string fieldPrefix)
{
>{
        if (method.ReturnType.Resolved.Name != "void")
>>    return
else
>>    

>> $fieldPrefix$method.ShortName(
        foreach(arg in method.Arguments)
        {
>>$arg.ShortName
            if (!arg.IsLast)
>>, 
        }
>);
>}
>
}

Sample Input

class SimpleClass
{
public:
    void UnimplementedMethod(int x, void *p);
    double UnimplementedMethod2(double x);
};

Sample Output

void UnimplementedMethod(int x, void * p)
{
     m_Field.UnimplementedMethod(x, p);
}

double UnimplementedMethod2(double x)
{
    return m_Field.UnimplementedMethod2(x);
}

A detailed reference on RefactorScript syntax and data model is available here.
See this page for a full list of RefactorScripts shipped with VisualGDB.