Skip to main content

PCD Examples

These examples demonstrate PCD from simple circuits to production-grade programs. Each example includes:
  • Complete, runnable code
  • Which monomers it uses
  • Why Φ_c = 1 (how the TCE certifies it)

Hello World

The simplest circuit. One path, one output, Φ_c = 1 trivially.
PC hello {
    OUTPUT "Hello, World!\n";
}
Monomers used: None Φ_c = 1 because: Single unconditional path from entry to OUTPUT. No branches, no loops, no undefined flows.

Fibonacci (Iterative)

Computing Fibonacci with loop(N) — the canonical PCD loop pattern.
PC fibonacci {
    let n = 20;
    let a = 0;
    let b = 1;

    loop(n) as i {
        let temp = b;
        let b = a + b;
        let a = temp;
    }

    OUTPUT a;
}
Monomers used: None (pure arithmetic) Φ_c = 1 because: loop(N) always terminates after exactly n iterations. Loop-carried variables a, b, temp all use version-0 SSA rebinding. Single OUTPUT at the end. With stdlib output formatting:
import "stdlib/fmt.pcd";
import "stdlib/string.pcd";

PC fibonacci_verbose {
    let n = 10;
    let a = 0;
    let b = 1;

    loop(n) as i {
        let msg = format("fib({}) = {}", [i, a]);
        let _ = MC_58.WRITE(msg + "\n");
        let temp = b;
        let b = a + b;
        let a = temp;
    }

    OUTPUT a;
}

SHA-256 Hash

Calling the crypto monomer family to hash a string.
PC hash_example {
    let data = "BRIK-64 Digital Circuitality";
    let hash = MC_48.HASH(data);
    let result = "SHA256: " + hash;
    OUTPUT result;
}
Monomers used: MC_48.HASH Φ_c = 1 because: Linear path. MC_48.HASH is a pure function — same input always produces same output. No branches. HMAC example:
PC hmac_example {
    let key  = "secret-key";
    let data = "payload to authenticate";
    let mac  = MC_49.HMAC(key, data);
    OUTPUT "HMAC: " + mac;
}

Email Validator

String operations and boolean logic. Shows how loop(N) replaces while for character scanning.
import "stdlib/string.pcd";

PC validate_email {
    let email = MC_63.ENV("ARGV_1");

    // Must contain exactly one @
    let at_count = 0;
    let at_pos = -1;
    let elen = len(email);

    loop(elen) as i {
        let ch = char_at(email, i);
        if (ch == "@") {
            let at_count = at_count + 1;
            let at_pos = i;
        }
    }

    if (at_count != 1) {
        OUTPUT "INVALID: must have exactly one @";
    }

    // Must have local part (before @)
    if (at_pos == 0) {
        OUTPUT "INVALID: empty local part";
    }

    // Must have domain with a dot
    let domain = substr(email, at_pos + 1, elen - at_pos - 1);
    let dot_pos = find(domain, ".");

    if (dot_pos == -1) {
        OUTPUT "INVALID: domain has no dot";
    }

    if (dot_pos == 0) {
        OUTPUT "INVALID: domain starts with dot";
    }

    let dlen = len(domain);
    if (dot_pos == dlen - 1) {
        OUTPUT "INVALID: domain ends with dot";
    }

    OUTPUT "VALID: " + email;
}
Monomers used: MC_63.ENV, MC_43.LEN (via stdlib), MC_45.CHAR_AT (via stdlib), MC_42.SUBSTR, MC_40.CONCAT Φ_c = 1 because: Every branch terminates with an OUTPUT. The TCE verifies all control paths lead to an output value. No path can fall through without producing a result.
MC_63.ENV("ARGV_1") reads argv[1] from the process command line when compiled to native ELF. Run as: ./email_validator user@example.com

Policy Circuit for AI Safety

This is the most important example. It shows how PCD implements hardware-enforceable AI safety guardrails. A Policy Circuit intercepts an AI action and verifies it against a set of rules before returning ALLOW or BLOCK.
import "stdlib/string.pcd";
import "stdlib/json.pcd";
import "stdlib/array.pcd";

PC ai_policy_circuit {
    // Read the proposed AI action as JSON from stdin
    let action_json = MC_56.READ("/dev/stdin");
    let action = parse(action_json);

    let action_type = get(action, "type");
    let resource    = get(action, "resource");
    let agent_id    = get(action, "agent_id");

    // === RULE 1: No writes to /etc ===
    if (action_type == "write") {
        if (starts_with(resource, "/etc/")) {
            OUTPUT "BLOCK: writes to /etc are forbidden";
        }
    }

    // === RULE 2: No network access outside allowlist ===
    let allowed_domains = ["api.openai.com", "api.anthropic.com", "registry.brik64.dev"];
    if (action_type == "network") {
        let host = get(action, "host");
        let is_allowed = contains(allowed_domains, host);
        if (!is_allowed) {
            OUTPUT "BLOCK: host " + host + " not in allowlist";
        }
    }

    // === RULE 3: No shell execution ===
    if (action_type == "shell") {
        OUTPUT "BLOCK: shell execution is unconditionally forbidden";
    }

    // === RULE 4: Read access allowed for non-secret paths ===
    if (action_type == "read") {
        if (contains(resource, ".env")) {
            OUTPUT "BLOCK: reading .env files is forbidden";
        }
        if (starts_with(resource, "/proc/")) {
            OUTPUT "BLOCK: reading /proc is forbidden";
        }
    }

    // === RULE 5: Verify agent identity ===
    let known_agents = ["claude-code", "codex-cli", "gemini-cli"];
    let is_known = contains(known_agents, agent_id);
    if (!is_known) {
        OUTPUT "BLOCK: unknown agent_id: " + agent_id;
    }

    // All rules passed
    OUTPUT "ALLOW";
}
Monomers used: MC_56.READ, MC_40.CONCAT Φ_c = 1 because: Every possible input path terminates at an OUTPUT "BLOCK: ..." or the final OUTPUT "ALLOW". The TCE formally verifies there is no path through this circuit that produces an ambiguous result. This is what makes PCD Policy Circuits different from if/else chains in Python: the compiler proves completeness. Key insight on AI Safety:
RLHF teaches an AI to want to do the right thing. A Policy Circuit compiled to a BPU (BRIK Processing Unit) chip physically prevents the wrong thing. The difference is the difference between education and physics. Education can fail; physics cannot.When this circuit runs on a BPU, the BLOCK/ALLOW decision happens in silicon, before the action reaches the OS. The AI agent cannot bypass it — not because it’s trained not to, but because the hardware doesn’t route the request.

Reading Command-Line Arguments

Using MC_63.ENV("ARGV_1") in a native ELF to build a command-line tool:
import "stdlib/string.pcd";
import "stdlib/math.pcd";
import "stdlib/fmt.pcd";

PC word_counter {
    let filename = MC_63.ENV("ARGV_1");

    // Validate argument
    if (len(filename) == 0) {
        let _ = MC_58.WRITE("Usage: word_counter <filename>\n");
        OUTPUT 1;
    }

    // Read file
    let content = MC_56.READ(filename);
    let clen = len(content);

    if (clen == 0) {
        let _ = MC_58.WRITE("Error: could not read " + filename + "\n");
        OUTPUT 1;
    }

    // Count lines, words, characters
    let lines = 0;
    let words = 0;
    let chars = clen;
    let in_word = false;

    loop(clen) as i {
        let ch = char_at(content, i);
        if (ch == "\n") {
            let lines = lines + 1;
        }
        if (ch == " " || ch == "\n" || ch == "\t") {
            if (in_word) {
                let words = words + 1;
                let in_word = false;
            }
        } else {
            let in_word = true;
        }
    }

    // Count last word if file doesn't end with whitespace
    if (in_word) {
        let words = words + 1;
    }

    let result = format("{} {} {} {}", [lines, words, chars, filename]);
    OUTPUT result;
}
Compile and run:
brikc compile word_counter.pcd --target native -o word_counter
./word_counter README.md
# 42 287 1893 README.md

Mini HTTP Request Parser

Demonstrates struct usage and complex string parsing:
import "stdlib/string.pcd";
import "stdlib/array.pcd";

struct HttpRequest {
    method:  string,
    path:    string,
    version: string,
    headers: array,
    body:    string
}

fn parse_request_line(line) {
    let parts = split(line, " ");
    if (len(parts) < 3) {
        return HttpRequest {
            method: "INVALID",
            path: "/",
            version: "HTTP/1.1",
            headers: [],
            body: ""
        };
    }
    return HttpRequest {
        method:  parts[0],
        path:    parts[1],
        version: parts[2],
        headers: [],
        body:    ""
    };
}

fn parse_headers(lines, start) {
    let headers = [];
    let n = len(lines);
    loop(n) as i {
        let idx = start + i;
        if (idx >= n) {
            return headers;
        }
        let line = lines[idx];
        if (len(trim(line)) == 0) {
            return headers;
        }
        let headers = push(headers, line);
    }
    return headers;
}

PC http_parser {
    let raw = MC_56.READ("/dev/stdin");
    let lines = split(raw, "\n");
    let nlines = len(lines);

    if (nlines == 0) {
        OUTPUT "INVALID: empty request";
    }

    let req = parse_request_line(lines[0]);
    let headers = parse_headers(lines, 1);
    let req2 = HttpRequest {
        method:  req.method,
        path:    req.path,
        version: req.version,
        headers: headers,
        body:    ""
    };

    let summary = req2.method + " " + req2.path + " (" + req2.version + ")";
    OUTPUT summary;
}
Φ_c = 1 because: Both the early-exit path (OUTPUT "INVALID: ...") and the success path (OUTPUT summary) are reachable and terminate. The struct fields are fully initialized on all construction paths.

Self-Hosting: The Compiler Compiles Itself

This is the capstone example. brikc.pcd is the BRIK-64 compiler written in PCD. It compiles PCD source to BIR (BRIK Intermediate Representation):
// Excerpt from brikc.pcd — the self-hosting compiler
PC brikc {
    // Read source from argv[1] or stdin
    let source = MC_63.ENV("ARGV_1");
    if (len(source) == 0) {
        let source = MC_59.READ_LINE();
    }

    // === Stage 1: Lexer ===
    let tokens = tokenize(source, 0);
    let ntok = MC_43.LEN(tokens);

    // === Stage 2: Parser ===
    let ast = parse(tokens, 0, ntok);

    // === Stage 3: Planner (SSA + type check) ===
    let plan = plan_program(ast);

    // === Stage 4: Emitter (BIR) ===
    let bir_parts = emit(plan);
    let header = bir_parts[0];
    let code    = bir_parts[1];
    let nclines = MC_43.LEN(code);

    // Stream header
    let _ = MC_58.WRITE(header);
    let _ = MC_58.WRITE("\n");

    // Stream code lines
    loop(nclines) as i {
        let line = code[i];
        let _ = MC_58.WRITE(line);
        let _ = MC_58.WRITE("\n");
    }

    OUTPUT 0;
}
The self-compilation fixpoint:
# Gen0: Rust compiler compiles brikc.pcd → Gen1 BIR
brikc compile brikc.pcd --emit bir > gen1.bir

# Gen1: Gen1 BIR compiles brikc.pcd → Gen2 BIR
brikc run gen1.bir -- brikc.pcd > gen2.bir

# Gen2: Gen2 BIR compiles brikc.pcd → Gen3 BIR
brikc run gen2.bir -- brikc.pcd > gen3.bir

# Fixpoint: Gen1 == Gen2 == Gen3
sha256sum gen1.bir gen2.bir gen3.bir
# All three: 7229cfcde9613de42eda4dd207da3bac80d2bf2b5f778f3270c2321e8e489e95
The verified fixpoint hash is 7229cfcde9613de42eda4dd207da3bac80d2bf2b5f778f3270c2321e8e489e95. This was proven with 4 generations (Gen1==Gen2==Gen3==Gen4) on 2026-03-10. This hash is the “final seal” of BRIK-64 v2.0.0 — it proves the compiler is its own fixed point.
Why Φ_c = 1 for the self-hosting compiler: The most remarkable property of brikc.pcd is that it passes its own coherence verifier. The TCE verifies that:
  1. Tokenizer: All 1,052 string patterns have bounded scan loops
  2. Parser: MAX_DEPTH=256 enforces a finite parse tree
  3. Planner: SSA transformation is total (every variable has a defined version)
  4. Emitter: BIR output is streamed incrementally (no unbounded accumulation)
  5. All control paths from the entry to OUTPUT 0 are reachable and terminate
The fact that the compiler verifies itself is not a coincidence — it is the design goal. A language where the compiler cannot verify its own programs would be incoherent by definition.

Putting It All Together: A Complete PCD Program

This example uses stdlib, structs, closures, and monomers to implement a simple key-value store with persistence:
import "stdlib/string.pcd";
import "stdlib/array.pcd";
import "stdlib/json.pcd";
import "stdlib/fmt.pcd";
import "stdlib/io.pcd";

struct KVStore {
    data: array,
    path: string
}

fn kv_load(path) {
    if (exists(path)) {
        let raw = read_file(path);
        let data = parse(raw);
        return KVStore { data: data, path: path };
    }
    return KVStore { data: [], path: path };
}

fn kv_get(store, key) {
    let n = len(store.data);
    loop(n) as i {
        let pair = store.data[i];
        let k = pair[0];
        if (k == key) {
            return pair[1];
        }
    }
    return "";
}

fn kv_set(store, key, value) {
    let n = len(store.data);
    let found = false;
    let new_data = [];

    loop(n) as i {
        let pair = store.data[i];
        let k = pair[0];
        if (k == key) {
            let new_data = push(new_data, [key, value]);
            let found = true;
        } else {
            let new_data = push(new_data, pair);
        }
    }

    if (!found) {
        let new_data = push(new_data, [key, value]);
    }

    return KVStore { data: new_data, path: store.path };
}

fn kv_save(store) {
    let serialized = stringify(store.data);
    write_file(store.path, serialized);
}

PC kvstore_cli {
    let cmd      = MC_63.ENV("ARGV_1");
    let store_path = "store.json";
    let store    = kv_load(store_path);

    if (cmd == "get") {
        let key = MC_63.ENV("ARGV_2");
        let val = kv_get(store, key);
        if (len(val) == 0) {
            OUTPUT "NOT FOUND: " + key;
        }
        OUTPUT val;
    }

    if (cmd == "set") {
        let key = MC_63.ENV("ARGV_2");
        let val = MC_63.ENV("ARGV_3");
        let store2 = kv_set(store, key, val);
        kv_save(store2);
        OUTPUT "OK";
    }

    if (cmd == "list") {
        let n = len(store.data);
        let result = "";
        loop(n) as i {
            let pair = store.data[i];
            let result = result + pair[0] + " = " + pair[1] + "\n";
        }
        OUTPUT result;
    }

    OUTPUT "Usage: kvstore_cli [get|set|list] [key] [value]";
}
Monomers used: MC_63.ENV, MC_56.READ, MC_57.WRITE_FILE, MC_43.LEN, MC_40.CONCAT Φ_c = 1 because: Every if (cmd == "...") branch either terminates with OUTPUT or falls through to the final OUTPUT "Usage: ...". The TCE verifies that no execution path produces an undefined result.
This pattern — a series of if (cmd == "...") branches each ending in OUTPUT, with a final fallback OUTPUT — is the canonical PCD CLI dispatch pattern. It is used in brikc_cli_dispatch.pcd itself.