eval.scm 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. ;;; Test script to compile a Scheme expression to wasm, then run 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 config)
  17. (hoot compile)
  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-expr expr)
  47. (call-with-compiled-wasm-file
  48. (compile expr)
  49. (lambda (wasm-file-name)
  50. (define runner (in-vicinity %js-runner-dir "load.js"))
  51. (run-v8 runner "--" %reflect-js-dir %reflect-wasm-dir wasm-file-name))))
  52. (define (read1 str)
  53. (call-with-input-string
  54. str
  55. (lambda (port)
  56. (let ((expr (read port)))
  57. (when (eof-object? expr)
  58. (error "No expression to evaluate"))
  59. (let ((tail (read port)))
  60. (unless (eof-object? tail)
  61. (error "Unexpected trailing expression" tail)))
  62. expr))))
  63. (when (batch-mode?)
  64. (match (program-arguments)
  65. ((arg0 str)
  66. (compile-expr (read1 str)))
  67. ((arg0 . _)
  68. (format (current-error-port) "usage: ~a EXPR\n" arg0)
  69. (exit 1))))