;; -*-theme-d-*-

;; Copyright (C) 2016 Tommi Höynälänmaa
;; Distributed under GNU Lesser General Public License version 3,
;; see file doc/LGPL-3.

(define-body (standard-library promise)

  (define-param-proc make-promise (%type)
		     (((proc (:procedure () %type pure)))
		      (:promise %type)
		      pure)
      (let-volatile ((result-ready? <boolean> #f)
		     (result (:maybe %type) null))
	(lambda (() %type pure)
	  (if result-ready?
	      (cast %type result)
	      (let ((x (proc)))
		(if result-ready?
		    (cast %type result)
		    (begin (set! result-ready? #t)
			   (set! result x)
			   x)))))))


  (define-param-proc force (%type)
		     (((promise (:promise %type)))
		      %type
		      pure)
    (promise))


  (define-param-proc make-nonpure-promise (%type)
		     (((proc (:procedure () %type nonpure)))
		      (:nonpure-promise %type)
		      pure)
      (let-mutable ((result-ready? <boolean> #f)
		    (result (:maybe %type) null))
	(lambda (() %type nonpure)
	  (if result-ready?
	      (cast %type result)
	      (let ((x (proc)))
		(if result-ready?
		    (cast %type result)
		    (begin (set! result-ready? #t)
			   (set! result x)
			   x)))))))

  (define-param-proc force-nonpure (%type)
		     (((promise (:nonpure-promise %type)))
		      %type
		      nonpure)
    (promise)))
