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 :ptr scalar type (void *). Intentionally NOT GC-tracked — foreign memory is the user's responsibility.
  • scan_ffi_decl recognises the bare ffi_* calls during the module-body walk in collect_module_with_prefix and populates parallel @ffi_* registries.
  • infer_ffi_call_type runs ahead of the operator/comparison branch in infer_call_type so an FFI function name (e.g. a C pow) can shadow a Ruby operator.
  • compile_ffi_call_expr emits 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_externs writes the prologue (extern prototypes, buffer storage, plus /* SPINEL_LINK: -lname */ and /* SPINEL_CFLAGS: ... */ marker comments).
  • spinel wrapper 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

@@ -166,6 +166,11 @@
166166 EXTRA_FLAGS="$EXTRA_FLAGS $RE_LIB"
167167 fi
168168 INCLUDE_FLAGS="$INCLUDE_FLAGS -I$DIR/lib/regexp"
169+# Scrape FFI link/cflag markers emitted by the codegen. Each line looks
170+# like "/* SPINEL_LINK: -lraylib */" or "/* SPINEL_CFLAGS: -I/foo */"
171+# and comes from an ffi_lib / ffi_cflags declaration.
172+FFI_LINKS=$(sed -n 's|^/\* SPINEL_LINK: \(.*\) \*/$|\1|p' "$C_FILE" | tr '\n' ' ')
173+FFI_CFLAGS=$(sed -n 's|^/\* SPINEL_CFLAGS: \(.*\) \*/$|\1|p' "$C_FILE" | tr '\n' ' ')
169174 if [ "$(uname -s)" = "Darwin" ]; then
170175 GC_FLAG="-Wl,-dead_strip"
171176 else
@@ -177,7 +182,7 @@
177182 MINGW*|MSYS*|CYGWIN*) EXTRA_FLAGS="$EXTRA_FLAGS -Wl,--stack,67108864" ;;
178183 esac
179184
180-$CC_CMD -O${OPT_LEVEL} -Wno-all -ffunction-sections -fdata-sections $INCLUDE_FLAGS "$C_FILE" -lm $EXTRA_FLAGS $GC_FLAG -o "$BIN_FILE"
185+$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"
181186 if [ $? -ne 0 ]; then
182187 echo "spinel: C compilation failed" >&2
183188 exit 1