c-loader.ss
#lang scheme
(require scheme/foreign
         (for-syntax scheme/base
                     scheme/file
                     scheme/system
                     syntax/parse))

(unsafe!)

(define-syntax (c-loader stx)
  (syntax-parse 
   stx 
   [(_ c-source-string:str)
    (define gcc-path (find-executable-path "gcc"))
    (define source (syntax-source stx))
    (define scheme-path
      (if (path-string? source)
          source
          (make-temporary-file "superc-tmp~a.ss")))
    (define c-path (path-replace-suffix scheme-path #".c"))
    (define dylib-path (path-replace-suffix scheme-path #".dylib"))
    (define o-path (path-replace-suffix scheme-path #".o"))
    
    (with-output-to-file c-path
      (lambda ()
        (write-string (syntax->datum #'c-source-string)))
      #:exists 'replace)
    
    (system*/exit-code gcc-path "-m32" "-c" (path->string c-path)
                       "-o" (path->string o-path))
    (system*/exit-code gcc-path "-m32" "-dynamiclib"
                       "-o" (path->string dylib-path)
                       "-dylib" (path->string o-path))    
    
    (with-syntax ([this-lib (datum->syntax stx 'this-lib stx)])
      (quasisyntax/loc stx
        (define this-lib (ffi-lib #,dylib-path))))]))

(provide c-loader)