Move FFI code to src/ffi.lisp
[jscl.git] / src / ffi.lisp
1 ;;; ffi.lisp ---
2
3 ;; JSCL is free software: you can redistribute it and/or
4 ;; modify it under the terms of the GNU General Public License as
5 ;; published by the Free Software Foundation, either version 3 of the
6 ;; License, or (at your option) any later version.
7 ;;
8 ;; JSCL is distributed in the hope that it will be useful, but
9 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
10 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 ;; General Public License for more details.
12 ;;
13 ;; You should have received a copy of the GNU General Public License
14 ;; along with JSCL.  If not, see <http://www.gnu.org/licenses/>.
15
16 (defvar *js-package*
17   (make-package "JS"))
18
19 (defun ffi-intern-hook (symbol)
20   (when (eq (symbol-package symbol) *js-package*)
21     (let ((sym-name (symbol-name symbol))
22           (args (gensym)))
23       ;; Generate a trampoline to call the JS function
24       ;; properly. This trampoline is very inefficient,
25       ;; but it still works. Ideas to optimize this are
26       ;; provide a special lambda keyword
27       ;; cl::&rest-vector to avoid list argument
28       ;; consing, as well as allow inline declarations.
29       (fset symbol
30             (eval `(lambda (&rest ,args)
31                      (let ((,args (list-to-vector ,args)))
32                        (%js-call (%js-vref ,sym-name) ,args)))))
33       ;; Define it as a symbol macro to access to the
34       ;; Javascript variable literally.
35       (%define-symbol-macro symbol `(%js-vref ,(string symbol))))))
36
37 (setq *intern-hook* #'ffi-intern-hook)