# Under the Hood: 6-Stage Rust Engine, Cargo Crate & EBNF Grammars

> **FrameAssembly v3.2.2** · Reference Guide R3 · Canonical URL: https://frameassembly-lang.dev/docs/compiler-and-rust-api

How the 6-stage Rust packet engine and `.pcap` reverse reader work in memory, plus embedding `frameassembly` in Rust tests and grammar schemas.

## Key Takeaways

- Pure safe Rust (`1.89+`, Edition `2024`) in memory: zero shelling out, zero `libpcap` C FFI, and zero raw sockets (`CAP_NET_RAW`).
- Embed directly into Rust integration or DPI regression tests via `cargo add frameassembly` (`parse_program`, `compile_program`, `serialize_classic_pcap`, `serialize_pcapng`, `reverse_pcap_bytes`).
- Ships root `grammar.ebnf`, `frameassembly.gbnf`, and `frameassembly.lark` schemas + `/llms-full.txt` tested against 2,600+ packet scenarios.

## 1. Six Stages: `.frasm` <-> Wire Bytes

Everything runs in safe Rust in memory — zero shelling out, zero libpcap C bindings, zero raw sockets:

| Stage | What It Actually Does |
| --- | --- |
| 1. Lexer (`lexer::lex`) | Tokenizes UTF-8 `.frasm`, `->` / `<-` arrows, time units, IPv4/IPv6, colon/hyphen/Cisco MACs, hex strings, and OIDs with source line/column spans. |
| 2. Parser (`parser::parse_program`) | Builds the AST (`host`, `flow`, `compile`), runs Levenshtein typo suggestions (`Did you mean ...?`), and invokes `validation::validate_semantics`. |
| 3. Semantic Validator (`parser::validation::validate_semantics`) | Enforces L2 MAC-only vs L3–L7 IP rules, `igmp`/`ndp`/`mld` families, the 9-protocol `transport` whitelist, and field bounds. |
| 4. Stateful Expander (`backend::compile_program`) | Inlines `flow(...)` calls, advances the nanosecond `wait` clock (`0ns` start, `+10ms` default), and tracks 4-tuple TCP `seq`/`acknum` + port memory. |
| 5. Wire Encoder | Serializes L7 payloads (including SNMPv3 USM key localization + AES-128-CFB and DNP3 CRC-16 chunks), wraps L4/L3/MPLS/QinQ/802.1Q/Ethernet II, and computes RFC checksums. |
| 6. `.pcap` / `.pcapng` <-> `reverse` | Emits classic `.pcap` (`pcap::serialize_classic_pcap`) or nanosecond `.pcapng` (`pcap::serialize_pcapng`), and reverses captures via `reverse::reverse_pcap_bytes`. |

## 2. Embedding in Rust Tests & Tools (`cargo add frameassembly`)

Writing automated network parser, firewall, or DPI regression tests in Rust? Call the verified `frameassembly 3.2.2` library entrypoints directly in RAM without touching disk:

```bash
# Add the FrameAssembly Rust crate from crates.io (MSRV Rust 1.89+, Edition 2024)
cargo add frameassembly
```

### In-Memory Rust Test (src/main.rs)

```rust
use frameassembly::backend::compile_program;
use frameassembly::parser::parse_program;
use frameassembly::pcap::{serialize_classic_pcap, serialize_pcapng};
use frameassembly::reverse::reverse_pcap_bytes;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let src = r#"
        host sensor { ip 10.0.0.10 }
        host target { ip 10.0.0.20 }
        compile {
            sensor -> target icmp echorequest id 1 seq 1 wait 2ms
            sensor <- target icmp echoreply   id 1 seq 1
        }
    "#;

    let program = parse_program(src)?;
    let frames = compile_program(&program)?;
    let pcap_bytes = serialize_classic_pcap(&frames)?;
    let pcapng_bytes = serialize_pcapng(&frames)?;
    let rev = reverse_pcap_bytes(&pcapng_bytes)?;
    assert!(pcap_bytes.len() > 24 && rev.packet_count == 2 && rev.host_count == 2 && rev.warnings.is_empty());
    Ok(())
}
```

| Rust Crate Entrypoint (`frameassembly 3.2.2`) | Signature & Behavior |
| --- | --- |
| `frameassembly::parser::parse_program(src)` | `Result<Program, CompilerError>` — executes `lexer::lex`, `winnow` AST parse, and `validation::validate_semantics`. |
| `frameassembly::backend::compile_program(&program)` | Returns `(frame_bytes, timestamp_ns)` Ethernet II byte buffers paired with relative `u64` nanosecond timestamps (`Result<..., String>`). |
| `frameassembly::pcap::serialize_classic_pcap(&frames)` | Returns classic libpcap `.pcap` file bytes (`0xa1b2c3d4`, `1 µs` timestamps, `Result<..., String>`). |
| `frameassembly::pcap::serialize_pcapng(&frames)` | Returns nanosecond `.pcapng` file bytes (`IfTsResol=9`, `LINKTYPE_ETHERNET`, `Result<..., String>`). |
| `frameassembly::backend::generate_pcap(&program, output_path)` | `Result<(), String>` — compiles and writes `.pcap` or `.pcapng` directly by file extension. |
| `frameassembly::reverse::{reverse_pcap_bytes, reverse_pcap_file, reverse_pcap_reader}` | `Result<ReverseOutput, CompilerError>` — auto-detects `.pcap` / `.pcapng`, normalizes link types, and returns reversed `.frasm` text + `packet_count`, `host_count`, and `warnings`. |

## 3. JavaScript / TypeScript WebAssembly SDK (`npm install frameassembly-wasm`)

Building browser-local packet tools, Web Worker inspectors, or Node.js `.pcap` regression harnesses? The official `frameassembly-wasm` (`v3.2.2`, MIT, `https://www.npmjs.com/package/frameassembly-wasm`) package ships the exact `wasm-pack` bindings running inside `/playground`:

```bash
# Install the official WebAssembly SDK for browsers, Web Workers, or Node.js
npm install frameassembly-wasm
```

### Browser / Web Worker / Node.js Usage (wasm-demo.ts)

```typescript
import initWasm, {
  validate_frasm,
  inspect_frasm,
  compile_frasm_to_pcap,
  compile_frasm_to_pcapng,
  reversePcap,
} from 'frameassembly-wasm';

await initWasm();

const src = `host client { ip 10.0.0.10 }
host server { ip 10.0.0.20 }
compile {
    client -> server dns query txid 0x1a2b qname "api.internal" qtype "A"
}`;

const diagnostics = validate_frasm(src);
const frames = inspect_frasm(src);
const pcapBytes = compile_frasm_to_pcap(src);
const pcapngBytes = compile_frasm_to_pcapng(src);
const reversed = reversePcap(pcapBytes);
```

| `frameassembly-wasm` (`3.2.2`) Export | TypeScript Signature & Behavior |
| --- | --- |
| `default` (`initWasm`) / `initSync` | Initializes `frameassembly_wasm_bg.wasm` asynchronously (`fetch` / `Response` / `BufferSource`) or synchronously (`initSync({ module })` in Node.js / Workers). |
| `validate_frasm(source: string)` | Returns structured `WasmDiagnostic[]` (`line`, `column`, `end_column`, `severity`, `message`, `suggestion`, `replacement`) with zero disk I/O. |
| `inspect_frasm(source: string)` | Compiles in memory and returns `InspectedFrame[]` (`index`, `timestamp_ms`, `length`, space-delimited `hex`). |
| `compile_frasm_to_pcap(source: string)` | Returns `Uint8Array` classic libpcap (`.pcap`, `0xa1b2c3d4`, `1 µs` resolution). |
| `compile_frasm_to_pcapng(source: string)` | Returns `Uint8Array` nanosecond PCAPNG (`.pcapng`, `IfTsResol=9`, `LINKTYPE_ETHERNET`). |
| `reversePcap(bytes: Uint8Array)` / `reverse_pcap` | Auto-detects `.pcap` or `.pcapng` bytes and returns `{ success, frasm, packetCount, hostCount, warnings, error }`. |

## 4. Constrained Decoding Schemas (`grammar.ebnf`, `frameassembly.gbnf`, `frameassembly.lark`)

Running local `llama.cpp` / `XGrammar` constrained decoding, `Outlines` / `vLLM`, or feeding an LLM? Fetch the root-level grammar schemas straight from `SteveWinschel/FrameAssembly` (or `/llms-full.txt` from this site):

- ISO/IEC 14977 EBNF (`grammar.ebnf`): `https://raw.githubusercontent.com/SteveWinschel/FrameAssembly/main/grammar.ebnf`
- llama.cpp / XGrammar GBNF (`frameassembly.gbnf`): `https://raw.githubusercontent.com/SteveWinschel/FrameAssembly/main/frameassembly.gbnf`
- Outlines / vLLM Lark (`frameassembly.lark`): `https://raw.githubusercontent.com/SteveWinschel/FrameAssembly/main/frameassembly.lark`

### `grammar_verified_sample.frasm`

```frameassembly
host verifier_a { ip 2001:db8:10::1  mac 00:1b:21:aa:00:01 }
host verifier_b { ip 2001:db8:10::2  mac 00:1c:73:bb:00:02 }

compile {
    verifier_a -> verifier_b ndp neighborsolicit target 2001:db8:10::2 slla 00:1b:21:aa:00:01 wait 1ms
    verifier_a <- verifier_b ndp neighboradvert target 2001:db8:10::2 tlla 00:1c:73:bb:00:02
}
```

### Excerpt from grammar.ebnf (v3.2.2)

```ebnf
program       = { host_block | flow_block } , compile_block , { host_block | flow_block } ;
host_block    = "host" , identifier , "{" , host_attr , { host_attr } , "}" ;
host_attr     = ( "ip" , ip_literal ) | ( "mac" , mac_literal ) ;
flow_block    = "flow" , identifier , "(" , param_list , ")" , "{" , { frame_stmt } , "}" ;
compile_block = "compile" , "{" , { frame_stmt | flow_call } , "}" ;
frame_stmt    = identifier , ( "->" | "<-" ) , identifier , protocol_kw , { modifier } ;
```

## 5. `frameassembly reverse` Fidelity & Boundary Matrix

The 5-stage reverse engine verifies every dissected frame against an internal self-check oracle so round-trip edits stay deterministic:

| Input Frame / Container Class | `frameassembly reverse` Output Behavior | Recompile Round-Trip Guarantee |
| --- | --- | --- |
| Container & Link-Layer Normalization | Reads classic/nanosecond `.pcap` and `.pcapng` (`SHB`/`IDB`/`EPB`/`SPB`); normalizes `ETHERNET`, `RAW`, `IPV4`, `IPV6`, `LINUX_SLL`, `LINUX_SLL2`, `NULL`, and `LOOP` into Ethernet II; strips trailing 60/64B zero-padding and 4B FCS. | Clean Ethernet II output (`LINKTYPE_ETHERNET`) with preserved nanosecond inter-packet `wait` deltas. |
| Cleartext & Structured L2–L7 Protocols (`80` builders) | Dissects into symbolic `host1`, `host2`, ... + lowercase `.frasm` protocol modifiers (`dns qname`, `tls clienthello sni`, `http`, `bgp`, `modbus`, `dnp3`, `snmp1`/`snmp2`, `snmp3` `noAuthNoPriv`), verified per-packet by the internal self-check oracle. | Editing variable-length strings or adding `vlan`/`qinq` recalculates L7 TLV lengths, IPv4/UDP lengths, downstream TCP `seq`/`acknum`, and all checksums. |
| IPsec ESP (`IP Protocol 50`) | Emits canonical `esp` (`spi`, `seq`, `iv`, `icv` / encrypted payload) rather than the `ipsec` authoring alias. | Preserves SPI, sequence number, and ciphertext while recalculating outer IP headers if `hostN` IPs are redacted. |
| Encrypted `snmp3` (`authPriv` / keyed `authNoPriv`) & Unknown Payloads | Steps down deterministically to `udp` / `tcp` with lossless `hexpayload "..."` because USM decryption requires out-of-band secrets. | Byte-exact payload preservation on recompile while still allowing outer MAC, VLAN, IP, and port redaction. |
