/* =============================================================================
 * 03_contracts.c  --  design for fewer bugs: invariants, assertions, contracts
 * =============================================================================
 *
 * [Questions this demo answers]
 *   - How do assertions turn a silent wrong answer into a loud, located crash?
 *   - What is a function "contract" (preconditions, postconditions,
 *     invariants), and how does checking it catch a caller's mistake at the
 *     boundary instead of deep inside?
 *   - Why is modular, testable code easier to debug?
 *
 * [How to build & run]
 *   make && ./build/03_contracts
 *   Build without checks:   cc -DNDEBUG -O2 03_contracts.c -o nocheck
 *   (NDEBUG makes assert() compile to nothing -- zero run-time cost in release.)
 *
 * [How to read the output]
 *   PART A runs a correct binary search and a property test (a contract that
 *   holds for every input). PART B calls it with a broken PRECONDITION (an
 *   unsorted array) in a CHILD process, so the assertion fires there and this
 *   program survives to report it. PART C contrasts a defensive version.
 *
 * [Systems link / CS:APP "design and debugging"]
 *   Testing and contracts are acts of DESIGN and DOCUMENTATION as much as
 *   verification: writing down what must be true forces you to understand the
 *   code, and checking it makes a violation fail at the exact boundary where
 *   it happened -- the opposite of a bug that surfaces far away (Lecture 1).
 * -------------------------------------------------------------------------- */

#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

/* [Idea] Is the array sorted ascending? This is bsearch's PRECONDITION: the
 *   caller must guarantee it, and bsearch is allowed to misbehave otherwise. */
static bool is_sorted(const int *a, int n)
{
    for (int i = 1; i < n; i++)
        if (a[i - 1] > a[i])
            return false;
    return true;
}

/*
 * [Idea] Binary search for key in a sorted array.
 * [Parameters] a -- a SORTED array of n ints (the precondition); key -- the
 *   value to find.
 * [Returns] an index i with a[i] == key, or -1 if key is absent (the
 *   postcondition: the return is -1, or a valid index whose element equals key).
 * [Edge cases] n == 0 returns -1; duplicates return some matching index.
 */
static int bsearch_int(const int *a, int n, int key)
{
    assert(n >= 0);                       /* precondition: a real length */
    assert(is_sorted(a, n));              /* precondition: the array is sorted */

    int lo = 0, hi = n - 1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;     /* not (lo+hi)/2: avoids overflow */
        assert(lo <= mid && mid <= hi);   /* invariant: mid stays in range */
        if (a[mid] == key) {
            assert(a[mid] == key);        /* postcondition holds on this path */
            return mid;
        }
        if (a[mid] < key)
            lo = mid + 1;
        else
            hi = mid - 1;
    }
    return -1;                            /* postcondition: absent -> -1 */
}

static void part_a(void)
{
    printf("PART A: a correct binary search, plus a property test (a contract)\n");
    int a[] = {-9, -3, 0, 1, 4, 4, 8, 15, 16, 23, 42};
    int n = (int)(sizeof a / sizeof a[0]);
    printf("  sorted array of %d elements. spot checks:\n", n);
    int keys[] = {-9, 1, 42, 7};
    for (int k = 0; k < 4; k++) {
        int idx = bsearch_int(a, n, keys[k]);
        printf("    find %3d -> %s\n", keys[k],
               idx < 0 ? "absent" : (a[idx] == keys[k] ? "found (ok)" : "WRONG"));
    }
    /* A property/contract test: for EVERY element, search must find a matching
     * value; for a value known absent, it must return -1. This states the
     * postcondition and checks it exhaustively on this input. */
    int ok = 1;
    for (int i = 0; i < n; i++) {
        int idx = bsearch_int(a, n, a[i]);
        ok &= (idx >= 0 && a[idx] == a[i]);
    }
    ok &= (bsearch_int(a, n, 100) == -1);
    printf("  property test (every element found; a known-absent key -> -1): %s\n\n",
           ok ? "PASS" : "FAIL");
}

static void part_b(void)
{
    printf("PART B: a broken PRECONDITION caught at the boundary (in a child)\n");
    int bad[] = {5, 1, 4, 2, 3};          /* NOT sorted: violates the precondition */
    printf("  calling bsearch_int on an UNSORTED array {5,1,4,2,3} ...\n");
    fflush(stdout);
    pid_t pid = fork();                   /* run the failing call in a copy of us */
    if (pid == 0) {
        bsearch_int(bad, 5, 4);           /* the is_sorted assertion fires here */
        _exit(0);                         /* not reached if assert aborts */
    }
    int status;
    waitpid(pid, &status, 0);
    if (WIFSIGNALED(status))
        printf("  the child was killed by signal %d (%s): the assertion fired AT THE\n"
               "  CALL, naming the violated precondition, instead of returning a silent\n"
               "  wrong answer that would surface somewhere far away.\n\n",
               WTERMSIG(status), WTERMSIG(status) == SIGABRT ? "SIGABRT from assert" : "abort");
    else
        printf("  (child exited %d; assertions may be compiled out with -DNDEBUG)\n\n",
               WEXITSTATUS(status));
}

/* [Idea] A DEFENSIVE variant: instead of asserting the precondition (a
 *   programmer-error check), it validates input and reports failure in its
 *   return value -- appropriate when bad input is expected at run time
 *   (e.g. from a file or the network) rather than a bug. */
static int bsearch_checked(const int *a, int n, int key, bool *ok)
{
    if (n < 0 || !is_sorted(a, n)) { *ok = false; return -1; }   /* reject, don't crash */
    *ok = true;
    return bsearch_int(a, n, key);
}

static void part_c(void)
{
    printf("PART C: assertion vs defensive check -- two answers to bad input\n");
    int bad[] = {5, 1, 4, 2, 3};
    bool ok;
    int idx = bsearch_checked(bad, 5, 4, &ok);
    printf("  bsearch_checked on the unsorted array: ok=%s, idx=%d\n", ok ? "true" : "false", idx);
    printf("  Use an ASSERTION for a condition that should be impossible if the code\n");
    printf("  is correct (a caller's BUG). Use a DEFENSIVE check that returns an error\n");
    printf("  for input that can legitimately be bad at run time. Asserts document and\n");
    printf("  catch bugs during development; they vanish under -DNDEBUG in release.\n\n");
}

int main(void)
{
    printf("=== Demo 03: invariants, assertions and contracts ===\n\n");
    part_a();
    part_b();
    part_c();
    printf("Observations:\n");
    printf("  * An assertion states what MUST be true and, if it is not, fails loudly at\n"
           "    the exact spot -- turning a silent wrong answer into a located crash.\n");
    printf("  * A contract (preconditions / postconditions / invariants) is design and\n"
           "    documentation: writing it down clarifies the code and checks the caller.\n");
    printf("  * Assert programmer errors; defensively validate untrusted input. Asserts\n"
           "    compile away with -DNDEBUG, so they cost nothing in release builds.\n");
    printf("  * Modular, testable pieces (is_sorted, bsearch_int) can each be checked on\n"
           "    their own -- the design advice from the slides' cache-simulator example.\n");
    return 0;
}
