|
| 1 | +## CDDL (RFC 8610) schema generator for the nim-ffi framework. |
| 2 | +## Mirrors the CBOR wire format produced by ffi/cbor_serial.nim: every |
| 3 | +## user-declared {.ffi.} type becomes a CDDL rule, every {.ffi.} / {.ffiCtor.} |
| 4 | +## proc gets a request envelope rule plus a response shape rule. |
| 5 | + |
| 6 | +import std/[os, strutils] |
| 7 | +import ./meta |
| 8 | + |
| 9 | +proc innerOf(typeName, prefix: string): string = |
| 10 | + if typeName.startsWith(prefix) and typeName.endsWith("]"): |
| 11 | + return typeName[prefix.len .. ^2] |
| 12 | + return "" |
| 13 | + |
| 14 | +proc capitalizeFirstLetter(s: string): string = |
| 15 | + if s.len == 0: return s |
| 16 | + result = s |
| 17 | + result[0] = s[0].toUpperAscii() |
| 18 | + |
| 19 | +proc toCamelCase(s: string): string = |
| 20 | + ## "testlib_create" → "TestlibCreate" |
| 21 | + var parts = s.split('_') |
| 22 | + result = "" |
| 23 | + for p in parts: |
| 24 | + result.add capitalizeFirstLetter(p) |
| 25 | + |
| 26 | +proc nimTypeToCddl*(typeName: string): string = |
| 27 | + ## Maps a Nim type name (as recorded in the compile-time registries) to its |
| 28 | + ## CDDL equivalent. Unknown PascalCase names are passed through as references |
| 29 | + ## to other CDDL rules in the same document. |
| 30 | + let t = typeName.strip() |
| 31 | + if t.startsWith("ptr "): |
| 32 | + return "uint" # in-process pointer; documented inline at the call site |
| 33 | + let seqI = innerOf(t, "seq[") |
| 34 | + if seqI.len > 0: |
| 35 | + return "[* " & nimTypeToCddl(seqI) & "]" |
| 36 | + let arrI = innerOf(t, "array[") |
| 37 | + if arrI.len > 0: |
| 38 | + # CDDL has no fixed-length array literal as ergonomic as Nim's array; emit |
| 39 | + # an unbounded array whose element type is the user-declared element type. |
| 40 | + let commaIdx = arrI.find(',') |
| 41 | + let elemT = if commaIdx >= 0: arrI[commaIdx + 1 .. ^1].strip() else: arrI |
| 42 | + return "[* " & nimTypeToCddl(elemT) & "]" |
| 43 | + let optI = innerOf(t, "Option[") |
| 44 | + if optI.len > 0: |
| 45 | + return nimTypeToCddl(optI) & " / nil" |
| 46 | + let mayI = innerOf(t, "Maybe[") |
| 47 | + if mayI.len > 0: |
| 48 | + return nimTypeToCddl(mayI) & " / nil" |
| 49 | + case t |
| 50 | + of "bool": "bool" |
| 51 | + of "int", "int64", "int32", "int16", "int8": "int" |
| 52 | + of "uint", "uint64", "uint32", "uint16", "uint8": "uint" |
| 53 | + of "string", "cstring": "tstr" |
| 54 | + of "float", "float64": "float64" |
| 55 | + of "float32": "float32" |
| 56 | + of "pointer": "uint" |
| 57 | + else: t # reference to another rule in this CDDL document |
| 58 | + |
| 59 | +proc reqStructName(p: FFIProcMeta): string = |
| 60 | + ## Mirrors the Nim macro: <CamelCase(procName)>{Ctor}Req. |
| 61 | + let camel = toCamelCase(p.procName) |
| 62 | + if p.kind == ffiCtorKind: camel & "CtorReq" else: camel & "Req" |
| 63 | + |
| 64 | +proc emitMap(fields: openArray[tuple[name: string, typeName: string, isPtr: bool]]): string = |
| 65 | + if fields.len == 0: |
| 66 | + return "{ }" |
| 67 | + var parts: seq[string] = @[] |
| 68 | + for f in fields: |
| 69 | + let cddlType = |
| 70 | + if f.isPtr: "uint" |
| 71 | + else: nimTypeToCddl(f.typeName) |
| 72 | + parts.add(f.name & ": " & cddlType) |
| 73 | + "{ " & parts.join(", ") & " }" |
| 74 | + |
| 75 | +proc emitObjectFields(t: FFITypeMeta): string = |
| 76 | + var fields: seq[tuple[name: string, typeName: string, isPtr: bool]] = @[] |
| 77 | + for f in t.fields: |
| 78 | + let isPtr = f.typeName.startsWith("ptr ") |
| 79 | + let tn = if isPtr: f.typeName[4 .. ^1] else: f.typeName |
| 80 | + fields.add((name: f.name, typeName: tn, isPtr: isPtr)) |
| 81 | + emitMap(fields) |
| 82 | + |
| 83 | +proc emitReqFields(p: FFIProcMeta): string = |
| 84 | + var fields: seq[tuple[name: string, typeName: string, isPtr: bool]] = @[] |
| 85 | + for ep in p.extraParams: |
| 86 | + fields.add((name: ep.name, typeName: ep.typeName, isPtr: ep.isPtr)) |
| 87 | + emitMap(fields) |
| 88 | + |
| 89 | +proc responseRule(p: FFIProcMeta): string = |
| 90 | + ## CDDL shape of the success payload returned by the FFI callback. |
| 91 | + ## Error payloads stay as raw UTF-8 and are intentionally absent from the schema. |
| 92 | + case p.kind |
| 93 | + of ffiCtorKind: |
| 94 | + # The ctor returns the FFI context address as a CBOR-encoded decimal string. |
| 95 | + "tstr" |
| 96 | + of ffiDtorKind: |
| 97 | + # The dtor has no meaningful payload — handleRes sends a CBOR null sentinel. |
| 98 | + "nil" |
| 99 | + of ffiFfiKind: |
| 100 | + if p.returnIsPtr: "uint" |
| 101 | + else: nimTypeToCddl(p.returnTypeName) |
| 102 | + |
| 103 | +proc generateCddlSchema*( |
| 104 | + procs: seq[FFIProcMeta], |
| 105 | + types: seq[FFITypeMeta], |
| 106 | + libName: string, |
| 107 | + nimSrcRelPath: string, |
| 108 | +): string = |
| 109 | + var L: seq[string] = @[] |
| 110 | + L.add("; CDDL schema for `" & libName & "` — auto-generated from " & nimSrcRelPath) |
| 111 | + L.add("; Wire format: CBOR (RFC 8949). Errors return raw UTF-8 (not CBOR) and") |
| 112 | + L.add("; are intentionally absent from this schema.") |
| 113 | + L.add("") |
| 114 | + |
| 115 | + if types.len > 0: |
| 116 | + L.add("; ─── User-declared FFI types ──────────────────────────────────────") |
| 117 | + for t in types: |
| 118 | + L.add(t.name & " = " & emitObjectFields(t)) |
| 119 | + L.add("") |
| 120 | + |
| 121 | + # Per-proc request envelopes (one CBOR blob per request). |
| 122 | + let nonDtor = block: |
| 123 | + var r: seq[FFIProcMeta] = @[] |
| 124 | + for p in procs: |
| 125 | + if p.kind != ffiDtorKind: r.add(p) |
| 126 | + r |
| 127 | + if nonDtor.len > 0: |
| 128 | + L.add("; ─── Request envelopes (one CBOR blob per request) ────────────────") |
| 129 | + for p in nonDtor: |
| 130 | + L.add(reqStructName(p) & " = " & emitReqFields(p)) |
| 131 | + L.add("") |
| 132 | + |
| 133 | + # Per-proc request/response rules. |
| 134 | + L.add("; ─── Procs ─────────────────────────────────────────────────────────") |
| 135 | + for p in procs: |
| 136 | + let kindTag = |
| 137 | + case p.kind |
| 138 | + of ffiCtorKind: "ctor" |
| 139 | + of ffiDtorKind: "dtor" |
| 140 | + of ffiFfiKind: |
| 141 | + if p.isAsync: "async" else: "sync" |
| 142 | + L.add("; " & p.procName & " (" & kindTag & ")") |
| 143 | + if p.kind != ffiDtorKind: |
| 144 | + L.add(p.procName & "-request = " & reqStructName(p)) |
| 145 | + L.add(p.procName & "-response = " & responseRule(p)) |
| 146 | + L.add("") |
| 147 | + |
| 148 | + result = L.join("\n") |
| 149 | + |
| 150 | +proc generateCddlBindings*( |
| 151 | + procs: seq[FFIProcMeta], |
| 152 | + types: seq[FFITypeMeta], |
| 153 | + libName: string, |
| 154 | + outputDir: string, |
| 155 | + nimSrcRelPath: string, |
| 156 | +) = |
| 157 | + createDir(outputDir) |
| 158 | + writeFile( |
| 159 | + outputDir / (libName & ".cddl"), |
| 160 | + generateCddlSchema(procs, types, libName, nimSrcRelPath), |
| 161 | + ) |
0 commit comments