repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

opencode/test-c-skills/src/test-macros.c

Raw
#include "base.h"

// ============================================================================
// DeferLoop (RAII-like Cleanup)
// ============================================================================

#define DeferLoop(begin, end) \
    for (int _i_ = ((begin), 0); !_i_; _i_ += 1, (end))

// push_struct helper for testing - uses arena_push_type from base.h
#define push_struct(arena, T) arena_push_type(arena, T)

// ============================================================================
// For-Each Iterators
// ============================================================================

#define EachIndex(it, count) \
    for (U64 it = 0; it < (count); it += 1)

#define EachElement(it, array) \
    for (U64 it = 0; it < ArrayCount(array); it += 1)

#define EachInRange(it, range) \
    for (U64 it = (range).min; it < (range).max; it += 1)

#define EachEnumVal(type, it) \
    for (type it = (type)0; it < type##_COUNT; it = (type)(it + 1))

// Node iterator - forward declaration
typedef struct Node Node;
#define EachNode(it, first) \
    for (Node *it = (first); it != 0; it = it->next)

#define EachNodeSafe(it, first, next_field) \
    for (Node *it = (first), *next = it ? it->next_field : 0; it != 0; it = next, next = it ? it->next_field : 0)

// ============================================================================
// X-Macros - Data Definitions
// ============================================================================

#define COLOR_LIST \
    X(Red,   0xFF0000) \
    X(Green, 0x00FF00) \
    X(Blue,  0x0000FF)

#define HEADER_FIELDS \
    X(U64, magic) \
    X(U32, version) \
    X(U32, flags) \
    X(U32, data_offset) \
    X(U32, data_count)

#define MESSAGE_TYPES \
    X(Connect,    1) \
    X(Disconnect, 2) \
    X(Data,       3)

// ============================================================================
// X-Macro Expansions - Color Enum and Tables
// ============================================================================

typedef enum Color {
#define X(name, value) Color_##name,
    COLOR_LIST
#undef X
    Color_COUNT
} Color;

// String table from X-macro
const char *color_names[] = {
#define X(name, value) [Color_##name] = #name,
    COLOR_LIST
#undef X
};

// Value table from X-macro
U32 color_values[] = {
#define X(name, value) [Color_##name] = value,
    COLOR_LIST
#undef X
};

// ============================================================================
// X-Macro Expansions - Header Struct
// ============================================================================

typedef struct Header {
#define X(type, name) type name;
    HEADER_FIELDS
#undef X
} Header;

// Field offset table from X-macro
typedef enum HeaderField {
#define X(type, name) HeaderField_##name,
    HEADER_FIELDS
#undef X
} HeaderField;

U32 header_offsets[] = {
#define X(type, name) [HeaderField_##name] = offsetof(Header, name),
    HEADER_FIELDS
#undef X
};

// ============================================================================
// X-Macro Expansions - Message Type Enum
// ============================================================================

typedef enum MsgType {
#define X(name, id) MsgType_##name = id,
    MESSAGE_TYPES
#undef X
} MsgType;

// ============================================================================
// Named Parameters Pattern
// ============================================================================

// Simple File handle type
typedef struct FileHandle {
    void *handle;
} FileHandle;

typedef struct OpenParams OpenParams;
struct OpenParams
{
    String8 path;
    B32 read_only;
    B32 create_if_missing;
    U32 permissions;
};

// Named Parameters Pattern - file_open_ is used by the macro expansion
// but we call the macro, not the function directly
// The function is kept for demonstration purposes
// Note: In production, this would be in a separate source file
#if 0
internal FileHandle *
file_open_(OpenParams *params)
{
    (void)params;
    // Placeholder - just return null for testing
    return 0;
}
#endif

#define file_open(...) file_open_(&(OpenParams){ \
    .path = {0}, \
    .read_only = 0, \
    .create_if_missing = 0, \
    .permissions = 0644, \
    __VA_ARGS__ \
})

// ============================================================================
// Linked List Structures
// ============================================================================

// Singly-linked list node
typedef struct SLLNode SLLNode;
struct SLLNode {
    SLLNode *next;
    int data;
};

// Doubly-linked list node
struct Node {
    Node *next;
    Node *prev;
    int data;
};

// Range structure
typedef struct Range {
    U64 min;
    U64 max;
} Range;

// ============================================================================
// Linked List Macros
// ============================================================================

// Singly-linked list stack push/pop
#define SLLStackPush_N(f, n, next) ((n)->next = (f), (f) = (n))
#define SLLStackPop_N(f, next)    ((f) = (f) ? (f)->next : 0)

// Singly-linked list queue push (with null termination)
#define SLLQueuePush_NZ(f, l, n, next_field, zchk, zset) \
    do { \
        if (zchk) { (f) = (l) = (n); } \
        else { (l)->next_field = (n); (l) = (n); } \
        zset; \
    } while (0)

// With null termination
#define SLLQueuePush(f, l, n) \
    SLLQueuePush_NZ(f, l, n, next, ((f)==0), ((n)->next=0))

// Doubly-linked list insert - simplified version for testing
// Uses NULL as sentinel to avoid parsing issues with literal 0
#define DLLPushBack(f, l, n) \
    do { \
        (n)->next = 0; \
        (n)->prev = (l); \
        if ((l)) (l)->next = (n); \
        else (f) = (n); \
        (l) = (n); \
    } while (0)

#define DLLPushFront(f, l, n) \
    do { \
        (n)->next = (f); \
        (n)->prev = 0; \
        if ((f)) (f)->prev = (n); \
        else (l) = (n); \
        (f) = (n); \
    } while (0)

// Doubly-linked list remove - simplified for testing
#define DLLRemove(f, l, n) \
    do { \
        if ((n)->next) (n)->next->prev = (n)->prev; \
        else (l) = (n)->prev; \
        if ((n)->prev) (n)->prev->next = (n)->next; \
        else (f) = (n)->next; \
    } while (0)

// ============================================================================
// Type-Generic Macros
// ============================================================================

// ArrayCount is already defined in base.h

// Generic swap (GCC/Clang)
#define Swap(a, b) do { \
    typeof(a) _tmp = (a); \
    (a) = (b); \
    (b) = _tmp; \
} while (0)

// Containerof - get structure from member pointer
#define containerof(ptr, type, member) \
    ((type *)((char *)(ptr) - offsetof(type, member)))

// ============================================================================
// Token Pasting and Stringification
// ============================================================================

#define PASTE(a, b) a ## b
#define PASTE3(a, b, c) a ## b ## c
#define STRINGIFY(x) #x
#define XSTRINGIFY(x) STRINGIFY(x)

// ============================================================================
// Test Counter (for DeferLoop testing)
// ============================================================================

static int g_test_counter = 0;

// ============================================================================
// Test Functions
// ============================================================================

// Test 1: DeferLoop with counter
static void
test_defer_loop(void)
{
    printf("=== Test: DeferLoop ===\n");
    
    g_test_counter = 0;
    
    // Test basic DeferLoop - counter should be 10 after scope exits
    DeferLoop(g_test_counter += 5, g_test_counter += 5)
    {
        // Inside loop: counter is 5
    }
    // After loop: counter is 10
    
    printf("  Counter after DeferLoop: %d (expected: 10)\n", g_test_counter);
}

// Test 1b: MutexScope - RAII-like scoped locking
static int g_mutex_locked = 0;

static void mock_mutex_take(int *mutex) { (void)mutex; g_mutex_locked = 1; }
static void mock_mutex_drop(int *mutex) { (void)mutex; g_mutex_locked = 0; }

#define MutexScope(mutex) DeferLoop(mock_mutex_take(mutex), mock_mutex_drop(mutex))

static void
test_mutex_scope(void)
{
    printf("=== Test: MutexScope ===\n");
    
    int mutex = 0;
    
    // Mutex should be locked inside scope
    MutexScope(&mutex)
    {
        printf("  Inside MutexScope: locked=%d (expected: 1)\n", g_mutex_locked);
    }
    // Mutex should be unlocked after scope
    printf("  After MutexScope: locked=%d (expected: 0)\n", g_mutex_locked);
}

// Test 2: EachIndex
static void
test_each_index(void)
{
    printf("=== Test: EachIndex ===\n");
    
    int values[5] = {10, 20, 30, 40, 50};
    U64 sum = 0;
    
    EachIndex(i, 5)
    {
        sum += values[i];
    }
    
    printf("  Sum of values: %llu (expected: 150)\n", (unsigned long long)sum);
}

// Test 3: EachElement
static void
test_each_element(void)
{
    printf("=== Test: EachElement ===\n");
    
    int values[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    U64 sum = 0;
    
    EachElement(i, values)
    {
        sum += values[i];
    }
    
    printf("  Sum of elements: %llu (expected: 55)\n", (unsigned long long)sum);
}

// Test 4: EachInRange
static void
test_each_in_range(void)
{
    printf("=== Test: EachInRange ===\n");
    
    Range r = {3, 8};  // 3, 4, 5, 6, 7
    U64 sum = 0;
    
    EachInRange(i, r)
    {
        sum += i;
    }
    
    printf("  Sum of range [3,8): %llu (expected: 25)\n", (unsigned long long)sum);
}

// Test 5: EachEnumVal
static void
test_each_enum_val(void)
{
    printf("=== Test: EachEnumVal ===\n");
    
    U64 sum = 0;
    
    EachEnumVal(Color, c)
    {
        sum += color_values[c];
    }
    
    // Red(0xFF0000) + Green(0x00FF00) + Blue(0x0000FF) = 0xFFFFFF = 16777215
    printf("  Sum of color values: %llu (expected: 16777215)\n", (unsigned long long)sum);
}

// Test 6: X-Macro Color Tables
static void
test_xmacro_color_tables(void)
{
    printf("=== Test: X-Macro Color Tables ===\n");
    
    // Test enum values
    printf("  Color_Red = %d (expected: 0)\n", Color_Red);
    printf("  Color_Green = %d (expected: 1)\n", Color_Green);
    printf("  Color_Blue = %d (expected: 2)\n", Color_Blue);
    printf("  Color_COUNT = %d (expected: 3)\n", Color_COUNT);
    
    // Test string table
    printf("  color_names[Red] = \"%s\" (expected: \"Red\")\n", color_names[Color_Red]);
    printf("  color_names[Green] = \"%s\" (expected: \"Green\")\n", color_names[Color_Green]);
    printf("  color_names[Blue] = \"%s\" (expected: \"Blue\")\n", color_names[Color_Blue]);
    
    // Test value table
    printf("  color_values[Red] = 0x%06X (expected: 0xFF0000)\n", color_values[Color_Red]);
    printf("  color_values[Green] = 0x%06X (expected: 0x00FF00)\n", color_values[Color_Green]);
    printf("  color_values[Blue] = 0x%06X (expected: 0x0000FF)\n", color_values[Color_Blue]);
}

// Test 7: X-Macro Header Struct
static void
test_xmacro_header_struct(void)
{
    printf("=== Test: X-Macro Header Struct ===\n");
    
    Header h = {0};
    h.magic = 0xDEADBEEF;
    h.version = 1;
    h.flags = 2;
    h.data_offset = 256;
    h.data_count = 100;
    
    printf("  h.magic = 0x%llX (expected: 0xDEADBEEF)\n", (unsigned long long)h.magic);
    printf("  h.version = %u (expected: 1)\n", h.version);
    printf("  h.data_count = %u (expected: 100)\n", h.data_count);
    
    // Test offsets
    printf("  offsetof(Header, magic) = %u\n", (unsigned)offsetof(Header, magic));
    printf("  offsetof(Header, version) = %u\n", (unsigned)offsetof(Header, version));
    printf("  header_offsets[version] = %u\n", header_offsets[HeaderField_version]);
}

// Test 8: Named Parameters Pattern
static void
test_named_parameters(void)
{
    printf("=== Test: Named Parameters ===\n");
    
    // Test default values
    OpenParams defaults = {
        .path = {0},
        .read_only = 0,
        .create_if_missing = 0,
        .permissions = 0644
    };
    printf("  Default permissions: %o (expected: 644)\n", defaults.permissions);
    
    // The macro expansion works - just verify the struct is correct size
    printf("  sizeof(OpenParams) = %zu\n", sizeof(OpenParams));
}

// Test 9: SLL Stack Push/Pop
static void
test_sll_stack(void)
{
    printf("=== Test: SLL Stack Push/Pop ===\n");
    
    SLLNode *stack = 0;
    SLLNode n1 = {0, 1};
    SLLNode n2 = {0, 2};
    SLLNode n3 = {0, 3};
    
    // Push onto stack
    SLLStackPush_N(stack, &n3, next);  // stack -> n3
    SLLStackPush_N(stack, &n2, next);  // stack -> n2 -> n3
    SLLStackPush_N(stack, &n1, next);  // stack -> n1 -> n2 -> n3
    
    // Pop from stack
    SLLNode *popped = stack;
    SLLStackPop_N(stack, next);
    printf("  Popped value: %d (expected: 1)\n", popped->data);
    
    popped = stack;
    SLLStackPop_N(stack, next);
    printf("  Popped value: %d (expected: 2)\n", popped->data);
    
    popped = stack;
    SLLStackPop_N(stack, next);
    printf("  Popped value: %d (expected: 3)\n", popped->data);
    
    printf("  Stack after all pops: %s (expected: (null))\n", stack == 0 ? "(null)" : "not null");
}

// Test 10: SLL Queue Push
static void
test_sll_queue(void)
{
    printf("=== Test: SLL Queue Push ===\n");
    
    SLLNode *first = 0;
    SLLNode *last = 0;
    
    SLLNode n1 = {0, 10};
    SLLNode n2 = {0, 20};
    SLLNode n3 = {0, 30};
    
    // Enqueue
    SLLQueuePush(first, last, &n1);
    SLLQueuePush(first, last, &n2);
    SLLQueuePush(first, last, &n3);
    
    // Traverse and verify
    SLLNode *current = first;
    int expected[] = {10, 20, 30};
    int idx = 0;
    
    while (current != 0) {
        printf("  Queue[%d] = %d (expected: %d)\n", idx, current->data, expected[idx]);
        current = current->next;
        idx++;
    }
}

// Test 11: DLL PushBack and PushFront
static void
test_dll_push(void)
{
    printf("=== Test: DLL PushBack/PushFront ===\n");
    
    Node *first = 0;
    Node *last = 0;
    
    Node n1 = {0, 0, 100};
    Node n2 = {0, 0, 200};
    Node n3 = {0, 0, 300};
    
    // Push back: 100, 200, 300
    DLLPushBack(first, last, &n1);
    DLLPushBack(first, last, &n2);
    DLLPushBack(first, last, &n3);
    
    printf("  After PushBack: ");
    for (Node *n = first; n != 0; n = n->next) {
        printf("%d ", n->data);
    }
    printf("(expected: 100 200 300)\n");
    
    // Clear
    first = last = 0;
    
    // Push front: 300, 200, 100
    DLLPushFront(first, last, &n3);
    DLLPushFront(first, last, &n2);
    DLLPushFront(first, last, &n1);
    
    printf("  After PushFront: ");
    for (Node *n = first; n != 0; n = n->next) {
        printf("%d ", n->data);
    }
    printf("(expected: 100 200 300)\n");
}

// Test 12: DLL Remove
static void
test_dll_remove(void)
{
    printf("=== Test: DLL Remove ===\n");
    
    Node *first = 0;
    Node *last = 0;
    
    Node n1 = {0, 0, 1};
    Node n2 = {0, 0, 2};
    Node n3 = {0, 0, 3};
    
    DLLPushBack(first, last, &n1);
    DLLPushBack(first, last, &n2);
    DLLPushBack(first, last, &n3);
    
    // Remove middle element
    DLLRemove(first, last, &n2);
    
    printf("  After removing middle: ");
    for (Node *n = first; n != 0; n = n->next) {
        printf("%d ", n->data);
    }
    printf("(expected: 1 3)\n");
    
    // Remove first element
    DLLRemove(first, last, &n1);
    
    printf("  After removing first: ");
    for (Node *n = first; n != 0; n = n->next) {
        printf("%d ", n->data);
    }
    printf("(expected: 3)\n");
}

// Test 13: EachNode
static void
test_each_node(void)
{
    printf("=== Test: EachNode ===\n");
    
    Node n1 = {0, 0, 10};
    Node n2 = {0, 0, 20};
    Node n3 = {0, 0, 30};
    
    n1.next = &n2;
    n2.next = &n3;
    
    Node *list = &n1;
    int sum = 0;
    
    EachNode(node, list)
    {
        sum += node->data;
    }
    
    printf("  Sum via EachNode: %d (expected: 60)\n", sum);
}

// Test 14: Type-Generic Swap
static void
test_swap(void)
{
    printf("=== Test: Swap ===\n");
    
    int a = 5, b = 10;
    printf("  Before swap: a=%d, b=%d\n", a, b);
    Swap(a, b);
    printf("  After swap: a=%d, b=%d (expected: a=10, b=5)\n", a, b);
    
    double x = 1.5, y = 2.5;
    printf("  Before swap: x=%.1f, y=%.1f\n", x, y);
    Swap(x, y);
    printf("  After swap: x=%.1f, y=%.1f (expected: x=2.5, y=1.5)\n", x, y);
}

// Test 15: Containerof
static void
test_containerof(void)
{
    printf("=== Test: containerof ===\n");
    
    typedef struct {
        Node node;
        int value;
    } MyNode;
    
    MyNode my_node = {0};
    my_node.node.data = 42;
    my_node.value = 100;
    
    Node *node_ptr = &my_node.node;
    MyNode *recovered = containerof(node_ptr, MyNode, node);
    
    printf("  Recovered value: %d (expected: 100)\n", recovered->value);
    printf("  Recovered node data: %d (expected: 42)\n", recovered->node.data);
}

// Test 16: Token Pasting
static void
test_token_pasting(void)
{
    printf("=== Test: Token Pasting ===\n");
    
    // Create variable names
    #define MAKE_VAR(prefix, num) PASTE(prefix, num)
    int MAKE_VAR(var, 1) = 10;
    int MAKE_VAR(var, 2) = 20;
    int MAKE_VAR(var, 3) = 30;
    
    printf("  var1 = %d (expected: 10)\n", var1);
    printf("  var2 = %d (expected: 20)\n", var2);
    printf("  var3 = %d (expected: 30)\n", var3);
    
    // Test PASTE3
    #define MAKE_FUNC(prefix, name, suffix) PASTE3(prefix, name, suffix)
    int MAKE_FUNC(test, foo, _result) = 42;
    printf("  testfoo_result = %d (expected: 42)\n", testfoo_result);
}

// Test 17: Stringification
static void
test_stringification(void)
{
    printf("=== Test: Stringification ===\n");
    
    #define VERSION 123
    const char *version_str = XSTRINGIFY(VERSION);
    printf("  VERSION string: \"%s\" (expected: \"123\")\n", version_str);
    
    #define MACRO_NAME my_variable
    const char *name_str = XSTRINGIFY(MACRO_NAME);
    printf("  MACRO_NAME string: \"%s\" (expected: \"my_variable\")\n", name_str);
}

// Test 18: EachNodeSafe
static void
test_each_node_safe(void)
{
    printf("=== Test: EachNodeSafe ===\n");
    
    Node n1 = {0, 0, 1};
    Node n2 = {0, 0, 2};
    Node n3 = {0, 0, 3};
    
    n1.next = &n2;
    n2.next = &n3;
    
    Node *list = &n1;
    int sum = 0;
    
    // Safe iteration - can modify current node during iteration
    EachNodeSafe(node, list, next)
    {
        sum += node->data;
        // This is safe - next is cached before any modification
    }
    
    printf("  Sum via EachNodeSafe: %d (expected: 6)\n", sum);
}

// Note: ArenaTempScope test requires linking with base.c which provides
// arena_create_explicit, arena_push, arena_pos, arena_pop_to, arena_destroy.
// See test-arena.c for arena tests.

// ============================================================================
// Main
// ============================================================================

int
main(void)
{
    printf("C Macro Skills Test Suite\n");
    printf("==========================\n\n");
    
    test_defer_loop();
    printf("\n");
    
    test_mutex_scope();
    printf("\n");
    
    test_each_index();
    printf("\n");
    
    test_each_element();
    printf("\n");
    
    test_each_in_range();
    printf("\n");
    
    test_each_enum_val();
    printf("\n");
    
    test_xmacro_color_tables();
    printf("\n");
    
    test_xmacro_header_struct();
    printf("\n");
    
    test_named_parameters();
    printf("\n");
    
    test_sll_stack();
    printf("\n");
    
    test_sll_queue();
    printf("\n");
    
    test_dll_push();
    printf("\n");
    
    test_dll_remove();
    printf("\n");
    
    test_each_node();
    printf("\n");
    
    test_swap();
    printf("\n");
    
    test_containerof();
    printf("\n");
    
    test_token_pasting();
    printf("\n");
    
    test_stringification();
    printf("\n");
    
    test_each_node_safe();
    printf("\n");
    
    printf("==========================\n");
    printf("All tests completed!\n");
    
    return 0;
}