GenerateComparisonOperators.refscript

This page describes the GenerateComparisonOperators RefactorScript shipped with VisualGDB.

Overview

This script generates the '<' , '>', '==' and '!=' operators for a selected class by iterating all fields in the order of declaration.
You can use it by selecting a class in Code Explorer -> Outline, or via Smart Tags in the code editor.

Script


[Main, Description("Generate comparison operators"), SuggestFor(Record)]
generator GenerateComparisonOperator(Record class,
                                     bool lessThan = true,
                                     bool greaterThan = false,
                                     bool equals = false,
                                     bool notEquals = false)
{
    if (lessThan)
        GenerateOrderingComparison(class, "<");
    if (greaterThan)
        GenerateOrderingComparison(class, ">");
    if (equals)
        GenerateEqualityComparison(class, "==""false""true");
    if (notEquals)
        GenerateEqualityComparison(class, "!=""true""false");
}

generator GenerateOrderingComparison(Record class, string operand)
{
>bool operator$operand(const $class.ShortName &right) const
>{
    foreach(field in class.NonStaticFields)
    {
>    if ($field.ShortName != right.$field.ShortName)
>        return $field.ShortName $operand right.$field.ShortName;
>
    }
>    return false;    
>}
>
}

generator GenerateEqualityComparison(Record class,
                                     string operand,
                                     string valueIfDifferent,
                                     string valueIfSame)
{
>bool operator$operand(const $class.ShortName &right) const
>{
    foreach(field in class.NonStaticFields)
    {
>    if ($field.ShortName != right.$field.ShortName)
>        return $valueIfDifferent
>
    }
>    return $valueIfSame;    
>}
>
}

Sample Input

class SimpleClass
{
public:
    int IntField;
    void *PointerField;
};

Sample Output

bool operator<(const SimpleClass &right) const
{
    if (IntField != right.IntField)
        return IntField < right.IntField;

    if (PointerField != right.PointerField)
        return PointerField < right.PointerField;

    return false;
}

bool operator>(const SimpleClass &right) const
{
    if (IntField != right.IntField)
        return IntField > right.IntField;

    if (PointerField != right.PointerField)
        return PointerField > right.PointerField;

    return false;
}

bool operator==(const SimpleClass &right) const
{
    if (IntField != right.IntField)
        return false

    if (PointerField != right.PointerField)
        return false

    return true;
}

bool operator!=(const SimpleClass &right) const
{
    if (IntField != right.IntField)
        return true

    if (PointerField != right.PointerField)
        return true

    return false;
}

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