Commit 84f4d089
84f4d089668cMerged
Richard Ramsden <[email protected]> · 6 months ago · 2 files · ~2 modified
Description
feat(codegen): introduce FFI for direct C calls
Adds the Spinel-native FFI surface so Ruby modules can declare and call C functions without an extension compiler. Closes #214 (MVP scope per the resolution there: scalars + strings + opaque pointers + static buffers + struct-field reads; callbacks remain a follow-up).
DSL inside any module M:
ffi_lib "name" contributes -lname at link time ffi_cflags "..." contributes cc flags ffi_func :name, [args], ret declares an extern + dispatch ffi_const :NAME, integer constant (Module::NAME) ffi_buffer :name, static byte buffer (Module.name) ffi_read_u32/i32/ptr :n, read field from a buffer
Implementation:
- New
:ptrscalar type (void *). Intentionally NOT GC-tracked — foreign memory is the user's responsibility. scan_ffi_declrecognises the bareffi_*calls during the module-body walk incollect_module_with_prefixand populates parallel @ffi_* registries.infer_ffi_call_typeruns ahead of the operator/comparison branch ininfer_call_typeso an FFI function name (e.g. a Cpow) can shadow a Ruby operator.compile_ffi_call_expremits the direct call site, casting each arg to its declared C type. Void returns get wrapped in a comma expression so they have a value in Ruby expression position.emit_ffi_externswrites the prologue (extern prototypes, buffer storage, plus/* SPINEL_LINK: -lname */and/* SPINEL_CFLAGS: ... */marker comments).spinelwrapper greps the markers with sed and appends them to the cc invocation.
No parser or runtime-header changes — the DSL piggybacks on the existing CallNode shape; pointers don't need any runtime support.
Details
- Commit
- 84f4d089668c
- Parent
- 15f7e5f356d7
spinelmodifiedView file
EXTRA_FLAGS="$EXTRA_FLAGS $RE_LIB"fiINCLUDE_FLAGS="$INCLUDE_FLAGS -I$DIR/lib/regexp"# Scrape FFI link/cflag markers emitted by the codegen. Each line looks# like "/* SPINEL_LINK: -lraylib */" or "/* SPINEL_CFLAGS: -I/foo */"# and comes from an ffi_lib / ffi_cflags declaration.FFI_LINKS=$(sed -n 's|^/\* SPINEL_LINK: \(.*\) \*/$|\1|p' "$C_FILE" | tr '\n' ' ')FFI_CFLAGS=$(sed -n 's|^/\* SPINEL_CFLAGS: \(.*\) \*/$|\1|p' "$C_FILE" | tr '\n' ' ')if [ "$(uname -s)" = "Darwin" ]; then GC_FLAG="-Wl,-dead_strip"else MINGW*|MSYS*|CYGWIN*) EXTRA_FLAGS="$EXTRA_FLAGS -Wl,--stack,67108864" ;;esac$CC_CMD -O${OPT_LEVEL} -Wno-all -ffunction-sections -fdata-sections $INCLUDE_FLAGS "$C_FILE" -lm $EXTRA_FLAGS $GC_FLAG -o "$BIN_FILE"$CC_CMD -O${OPT_LEVEL} -Wno-all -ffunction-sections -fdata-sections $INCLUDE_FLAGS $FFI_CFLAGS "$C_FILE" -lm $EXTRA_FLAGS $FFI_LINKS $GC_FLAG -o "$BIN_FILE"if [ $? -ne 0 ]; then echo "spinel: C compilation failed" >&2 exit 1spinel_codegen.rbmodifiedView file
Loading diff…