PasteRack.org
Paste # 36865
2016-01-19 13:58:28

Fork as a new paste.

Paste viewed 129 times.


Embed:

  1. #lang racket/base
  2.  
  3. (provide compile-c-module
  4.          from-c)
  5.  
  6. (require racket/file
  7.          dynext/file
  8.          dynext/compile
  9.          dynext/link
  10.          (for-syntax racket/base
  11.                      racket/set
  12.                      syntax/parse
  13.                      racket/require-transform
  14.                      racket/file
  15.                      dynext/file
  16.                      dynext/compile
  17.                      dynext/link))
  18.  
  19. (define-syntax-rule (define-for-syntax-and-runtime f ...)
  20.   (begin (define f ...)
  21.          (define-for-syntax f ...)))
  22.  
  23. (define-for-syntax-and-runtime (compile-c-module c-source)
  24.   (define extensionless-source (path-replace-suffix c-source ""))
  25.   (define object-target-path
  26.     (build-path "compiled" "native" (system-library-subpath)))
  27.   (define object-target
  28.     (build-path object-target-path (append-object-suffix extensionless-source)))
  29.   (define shared-object-target
  30.     (build-path object-target-path (append-extension-suffix extensionless-source)))
  31.   (make-directory* object-target-path)
  32.   (compile-extension #t c-source object-target '())
  33.   (link-extension #t (list object-target) shared-object-target))
  34.  
  35. (define-for-syntax linked-files (mutable-set))
  36.  
  37. (define-syntax from-c
  38.   (make-require-transformer
  39.    (lambda (stx)
  40.      (syntax-parse stx
  41.        [(_ c-source:str)
  42.         (define f (syntax-e #'c-source))
  43.         (define complete-file (path->complete-path (string->path f)))
  44.         (when (set-member? linked-files complete-file)
  45.           (raise-user-error 'from-c
  46.                             "Cannot load ~a more then once, please restart Racket"
  47.                             f))
  48.         (set-add! linked-files complete-file)
  49.         (compile-c-module f)
  50.         (expand-import (datum->syntax stx (path->string (path-replace-suffix f ""))))]))))

=>