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



;;; *** Constructors ***


(import (rnrs exceptions)
	(srfi srfi-1)
	(th-scheme-utilities stdutils)
	(th-scheme-utilities hrecord))


(define (get-field-arg-types fields)
  (assert (list? fields))
  (let ((result '()))
    (do ((cur-lst fields (cdr cur-lst)))
	((null? cur-lst) result)
      (let ((cur-field (car cur-lst)))
	(if (not (tno-field-ref cur-field 'has-init-value?))
	    (begin
	      (dvar1-set! cur-field)
	      (let ((type (tno-field-ref cur-field 'type)))
		(set! result
		      (append result (list type))))))))))


(define (get-constructor-type binder r-class)
  (assert (is-binder? binder))
  (assert (is-target-object? r-class))
  (assert (is-t-instance? binder r-class tc-class))
  (let* ((all-fields (tno-field-ref r-class 'l-all-fields))
	 (field-types (get-field-arg-types all-fields))
	 (result
	  ;; Constructors always return.
	  (translate-simple-proc-class-expression
	   binder
	   field-types r-class #t #t #f #f)))
    result))


(define (get-empty-constructor to-class)
  (make-hrecord <expr-constructor>
		(make-tpti-general-proc
		 #t
		 (make-tt-uniform-list tc-object)
		 to-class
		 #t #t #f #f)
		#t
		#f
		'()

		#t
		#t
		#f
		'()

		to-class))


(define (make-constructor! binder to-class)
  (assert (is-binder? binder))
  (assert (is-target-object? to-class))
  (let ((type-constructor (get-constructor-type binder to-class)))
    ;; The result value of make-constructor! is not used.
    (tno-field-set! to-class 'type-constructor type-constructor)))


(set! make-constructor-fwd! make-constructor!)


(define (get-constructor-expr tc type-constructor)
  (make-hrecord <expr-constructor>
		type-constructor
		#t
		#t
		'()
		#t
		#t
		#f
		'()
		tc))
