Skip to content
pi-c Documentation
Login

Documentation

/* Unit tests for src/tui/highlight.c, including random-byte robustness. */
#include "tui/highlight.h"
#include "tui/width.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define E "\x1b["
#define R E "0m"

static int passes;

static void fail(const char *what, const char *got)
{
    fprintf(stderr, "FAIL: %s: got [%s]\n", what, got);
    exit(1);
}

static void pass(const char *what)
{
    printf("PASS: %s\n", what);
    passes++;
}

/* A theme whose SGR is "ESC[Nm" so expectations stay readable. */
static const tui_hl_theme T = {{
    [TUI_HL_COMMENT] = E "1m", [TUI_HL_KEYWORD] = E "2m", [TUI_HL_FUNCTION] = E "3m",
    [TUI_HL_VARIABLE] = E "4m", [TUI_HL_STRING] = E "5m", [TUI_HL_NUMBER] = E "6m",
    [TUI_HL_TYPE] = E "7m", [TUI_HL_OPERATOR] = E "8m", [TUI_HL_PUNCT] = E "9m",
    [TUI_HL_ADD] = E "10m", [TUI_HL_DEL] = E "11m", [TUI_HL_META] = E "12m",
}};

static char *hl(const char *lang, const char *code, const tui_hl_theme *th)
{
    char *out;
    size_t n;
    if (tui_highlight(lang, code, strlen(code), th, &out, &n) != 0 || strlen(out) != n)
        fail("tui_highlight", "rc/len");
    return out;
}

static void eq(const char *what, const char *lang, const char *code, const char *want)
{
    char *got = hl(lang, code, &T);
    if (strcmp(got, want) != 0) {
        char buf[512];
        size_t o = 0;
        for (const char *p = got; *p && o < sizeof buf - 6; p++) {
            if (*p == 0x1b)
                o += (size_t)snprintf(buf + o, sizeof buf - o, "\\e");
            else
                buf[o++] = *p;
        }
        buf[o] = 0;
        fail(what, buf);
    }
    free(got);
    pass(what);
}

/* Strips SGR escapes. */
static void strip_into(const char *s, char *dst)
{
    size_t o = 0;
    for (; *s; s++) {
        if (*s == 0x1b) {
            while (*s && *s != 'm')
                s++;
            if (!*s)
                break;
        } else {
            dst[o++] = *s;
        }
    }
    dst[o] = 0;
}

static void roundtrip(const char *lang, const char *code)
{
    char *got = hl(lang, code, &T), *plain = malloc(strlen(got) + 1);
    strip_into(got, plain);
    if (strcmp(plain, code) != 0)
        fail(lang ? lang : "generic", plain);
    free(plain);
    free(got);
}

static void test_random(void)
{
    static const char *const names[] = {"c", "sh", "py", "ts", "json", "go", "rust", "diff", "md", "yaml", "sql", NULL, "zzz"};
    unsigned seed = 12345;
    static const char alpha[] = "\"'`/*#$(){}[]<>-+=:;\\\n \t0aZ_.@e";
    for (int iter = 0; iter < 3000; iter++) {
        char buf[300];
        size_t n = (size_t)((unsigned)rand_r(&seed) % sizeof buf);
        for (size_t i = 0; i < n; i++) {
            unsigned r = (unsigned)rand_r(&seed);
            /* half raw bytes (never NUL or ESC: the check uses C strings), half syntax-heavy */
            buf[i] = (r & 1) ? alpha[(r >> 1) % (sizeof alpha - 1)] : (char)(1 + (r >> 1) % 255);
            if (buf[i] == 0x1b)
                buf[i] = 'x';
        }
        buf[n] = 0;
        const char *lang = names[(size_t)iter % (sizeof names / sizeof names[0])];
        roundtrip(lang, buf);
        /* raw ESC bytes must never reach the output */
        char *out;
        size_t on;
        if (n > 0)
            buf[0] = 0x1b;
        if (tui_highlight(lang, buf, n, NULL, &out, &on) != 0 || out[on] || memchr(out, 0x1b, on))
            fail("random", "esc leaked");
        free(out);
    }
    pass("random bytes, all languages: round-trip and ESC safe");
}

int main(void)
{
    eq("c keyword type function", "c", "int main(void) { return 0; }",
       E "7mint" R " " E "3mmain" R E "9m(" R E "7mvoid" R E "9m)" R " " E "9m{" R " " E "2mreturn" R " " E "6m0" R
       E "9m;" R " " E "9m}" R);
    eq("c preproc and comment", "c", "#include <x.h> // hi\n/* a\nb */",
       E "2m#include" R " " E "8m<" R "x" E "9m." R "h" E "8m>" R " " E "1m// hi" R "\n" E "1m/* a" R "\n" E "1mb */" R);
    eq("c string escape", "cpp", "\"a\\\"b\"", E "5m\"a\\\"b\"" R);
    eq("shell variable and comment", "bash", "echo $HOME # c", E "2mecho" R " " E "4m$HOME" R " " E "1m# c" R);
    eq("python triple string", "python", "\"\"\"a\nb\"\"\"", E "5m\"\"\"a" R "\n" E "5mb\"\"\"" R);
    eq("python keyword literal", "py", "def f(): pass\nNone",
       E "2mdef" R " " E "3mf" R E "9m(" R E "9m)" R E "8m:" R " " E "2mpass" R "\n" E "2mNone" R);
    eq("js template and number", "ts", "let x = `a` + 1.5e3",
       E "2mlet" R " x " E "8m=" R " " E "5m`a`" R " " E "8m+" R " " E "6m1.5e3" R);
    eq("json key vs value", "json", "{\"a\": \"b\", \"n\": 1, \"t\": true}",
       E "9m{" R E "4m\"a\"" R E "8m:" R " " E "5m\"b\"" R E "9m," R " " E "4m\"n\"" R E "8m:" R " " E "6m1" R E "9m," R " "
       E "4m\"t\"" R E "8m:" R " " E "2mtrue" R E "9m}" R);
    eq("go raw string and func", "go", "func f() { s := `x` }",
       E "2mfunc" R " " E "3mf" R E "9m(" R E "9m)" R " " E "9m{" R " s " E "8m:" R E "8m=" R " " E "5m`x`" R " " E "9m}" R);
    eq("rust lifetime and char", "rust", "fn a<'a>(c: 'x')",
       E "2mfn" R " a" E "8m<" R E "7m'a" R E "8m>" R E "9m(" R "c" E "8m:" R " " E "5m'x'" R E "9m)" R);
    eq("diff lines", "diff", "@@ -1 +1 @@\n-a\n+b\n c",
       E "12m@@ -1 +1 @@" R "\n" E "11m-a" R "\n" E "10m+b" R "\n c");
    eq("markdown heading code link", "md", "# T\nuse `x` [a](u)",
       E "2m# T" R "\nuse " E "5m`x`" R " " E "3m[a]" R E "1m(u)" R);
    eq("markdown fence", "markdown", "```c\nint\n```", E "9m```c" R "\n" E "5mint" R "\n" E "9m```" R);
    eq("yaml key comment", "yml", "a-b: \"v\" # c\nn: 3",
       E "4ma-b" R E "8m:" R " " E "5m\"v\"" R " " E "1m# c" R "\n" E "4mn" R E "8m:" R " " E "6m3" R);
    eq("sql case-insensitive", "sql", "SELECT a FROM t -- x", E "2mSELECT" R " a " E "2mFROM" R " t " E "1m-- x" R);
    eq("generic fallback", NULL, "x = \"s\" // c 12", "x " E "8m=" R " " E "5m\"s\"" R " " E "1m// c 12" R);
    eq("info string and case", "Python title=\"x\"", "None", E "2mNone" R);
    eq("unknown lang is generic", "brainfuck", "'a' #z", E "5m'a'" R " " E "1m#z" R);
    eq("unterminated string stops at newline", "c", "\"abc\nint", E "5m\"abc" R "\n" E "7mint" R);
    eq("unterminated block comment", "c", "/* x", E "1m/* x" R);
    eq("empty input", "c", "", "");
    {
        char *out = hl("c", "int x;", NULL);
        if (strcmp(out, "int x;") != 0)
            fail("null theme", out);
        free(out);
        pass("null theme is plain text");
    }
    {
        char *out = hl("c", "/* a\n b */ x", &T);
        tui_lines ls = {0};
        if (tui_wrap(out, strlen(out), 4, &ls) != 0)
            fail("wrap", "oom");
        for (size_t i = 0; i < ls.n; i++)
            if (tui_width(ls.lines[i], strlen(ls.lines[i])) > 4)
                fail("wrap width", ls.lines[i]);
        if (ls.n < 2)
            fail("wrap lines", out);
        tui_lines_clear(&ls);
        free(out);
        pass("output wraps with tui_wrap within width");
    }
    {
        size_t n = 4u << 20;
        char *big = malloc(n);
        char *out;
        size_t on;
        if (!big)
            fail("big", "oom");
        memset(big, '"', n);
        for (size_t i = 0; i < n; i += 7)
            big[i] = '\\';
        if (tui_highlight("c", big, n, &T, &out, &on) != 0)
            fail("big", "rc");
        free(out);
        memset(big, '/', n);
        if (tui_highlight("go", big, n, &T, &out, &on) != 0)
            fail("big", "rc");
        free(out);
        free(big);
        pass("large pathological inputs");
    }
    test_random();
    printf("test_highlight: %d PASS\n", passes);
    return 0;
}