call.scm 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. ;;; Test script to compile Scheme expressions to wasm, then apply via V8
  2. ;;; Copyright (C) 2023, 2024 Igalia, S.L.
  3. ;;;
  4. ;;; Licensed under the Apache License, Version 2.0 (the "License");
  5. ;;; you may not use this file except in compliance with the License.
  6. ;;; You may obtain a copy of the License at
  7. ;;;
  8. ;;; http://www.apache.org/licenses/LICENSE-2.0
  9. ;;;
  10. ;;; Unless required by applicable law or agreed to in writing, software
  11. ;;; distributed under the License is distributed on an "AS IS" BASIS,
  12. ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. ;;; See the License for the specific language governing permissions and
  14. ;;; limitations under the License.
  15. (use-modules (wasm assemble)
  16. (hoot compile)
  17. (hoot config)
  18. (ice-9 binary-ports)
  19. (ice-9 match)
  20. (ice-9 popen)
  21. (ice-9 textual-ports)
  22. (srfi srfi-64))
  23. (define (unwind-protect body unwind)
  24. (call-with-values
  25. (lambda ()
  26. (with-exception-handler
  27. (lambda (exn)
  28. (unwind)
  29. (raise-exception exn))
  30. body))
  31. (lambda vals
  32. (unwind)
  33. (apply values vals))))
  34. (define (call-with-compiled-wasm-file wasm f)
  35. (let* ((wasm-port (mkstemp "/tmp/tmp-wasm-XXXXXX"))
  36. (wasm-file-name (port-filename wasm-port)))
  37. (put-bytevector wasm-port (assemble-wasm wasm))
  38. (close-port wasm-port)
  39. (unwind-protect
  40. (lambda () (f wasm-file-name))
  41. (lambda () (delete-file wasm-file-name)))))
  42. (define (run-v8 . args)
  43. (let* ((v8 (or %node %d8))
  44. (pid (spawn v8 (cons v8 args))))
  45. (exit (status:exit-val (cdr (waitpid pid))))))
  46. (define (compile-call form)
  47. (let lp ((form form) (files '()) (first? #t))
  48. (match form
  49. (()
  50. (define runner (in-vicinity %js-runner-dir "call.js"))
  51. (apply run-v8 runner "--" %reflect-js-dir %reflect-wasm-dir
  52. (reverse files)))
  53. ((x . form)
  54. (call-with-compiled-wasm-file
  55. (compile x #:import-abi? (not first?) #:export-abi? first?)
  56. (lambda (file)
  57. (lp form (cons file files) #f)))))))
  58. (define (read1 str)
  59. (call-with-input-string
  60. str
  61. (lambda (port)
  62. (let ((expr (read port)))
  63. (when (eof-object? expr)
  64. (error "No expression to evaluate"))
  65. (let ((tail (read port)))
  66. (unless (eof-object? tail)
  67. (error "Unexpected trailing expression" tail)))
  68. expr))))
  69. (when (batch-mode?)
  70. (match (program-arguments)
  71. ((arg0 f . args)
  72. (compile-call (cons (read1 f) (map read1 args))))
  73. ((arg0 . _)
  74. (format (current-error-port) "usage: ~a FUNC ARG...\n" arg0)
  75. (exit 1))))