;;; snow.lisp
;;;
;;; Copyright (C) 2008-2009 Alessio Stalla
;;;
;;; This program is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU General Public License
;;; as published by the Free Software Foundation; either version 2
;;; of the License, or (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
;;;
;;; As a special exception, the copyright holders of this library give you
;;; permission to link this library with independent modules to produce an
;;; executable, regardless of the license terms of these independent
;;; modules, and to copy and distribute the resulting executable under
;;; terms of your choice, provided that you also meet, for each linked
;;; independent module, the terms and conditions of the license of that
;;; module.  An independent module is a module which is not derived from
;;; or based on this library.  If you modify this library, you may extend
;;; this exception to your version of the library, but you are not
;;; obligated to do so.  If you do not wish to do so, delete this
;;; exception statement from your version.


(in-package :snow)

;;Some utilities...
#|(defmacro with-unique-names ((&rest bindings) &body body)
  `(let ,(mapcar #'(lambda (binding)
                     (destructuring-bind (var prefix)
			 (if (consp binding) binding (list binding binding))
                       `(,var (gensym ,(string prefix)))))
                 bindings)
    ,@body))|#

#|(defmacro with-captured-specials ((&rest specials) &body body)
  (with-unique-names (tmp)
    `(let* (,@(loop
		 :for var :in specials
		 :append `((,tmp ,var) (,var ,tmp))))
       ,@body)))|#

(defmacro bwhen ((var condition) &body body)
  `(let ((,var ,condition))
     (when ,var ,@body)))

(defmacro bif ((var condition) then else)
  `(let ((,var ,condition))
     (if ,var ,then ,else)))

(defun ensure-list (obj)
  (if (listp obj)
      obj
      (list obj)))

(defun splice-if (item predicate tree)
  (let ((list-item (reverse (ensure-list item))))
    (labels
	((aux (tree acc)
	   (if tree
	       (if (listp (car tree))
		   (aux (cdr tree)
			(cons (splice-if item predicate (car tree)) acc))
		   (if (funcall predicate (car tree))
		       (aux (cdr tree) (append list-item acc))
		       (aux (cdr tree) (cons (car tree) acc))))
	       (nreverse acc))))
      (aux tree nil))))

(defun splice-into (item olditem tree)
  (splice-if item #'(lambda (x) (eq x olditem)) tree))

;;Interface/implementation
(defstruct interface name lambda-list (implementations (list)))

(defun ensure-property (plist indicator &optional default)
  (let ((prop (getf plist indicator)))
    (if prop
      prop
      (setf (getf plist indicator) default))))

(defun get-interfaces (dispatch-var)
  (getf (symbol-plist dispatch-var) 'interfaces))

(defun get-interface (dispatch-var interface-name)
  (cdr (assoc interface-name (getf (symbol-plist dispatch-var) 'interfaces)
	      :test #'equal))) ;;to handle (setf x) function names

(defun (setf get-interface) (value dispatch-var interface-name)
  (bif (it (assoc interface-name
		  (getf (symbol-plist dispatch-var) 'interfaces)
		  :test #'equal)) ;;to handle (setf x) function names
       (setf (cdr it) value)
       (progn
	 (push (cons interface-name value)
	       (getf (symbol-plist dispatch-var) 'interfaces))
	 value)))

(defun interface-implementation (interface dispatch-value)
  (getf (interface-implementations interface) dispatch-value))

(defun (setf interface-implementation) (value interface dispatch-value)
  (setf (getf (interface-implementations interface) dispatch-value)
	value))
  
(defun get-implementation (dispatch-var interface-name dispatch-value)
  (interface-implementation (get-interface dispatch-var interface-name)
			    dispatch-value))

(defun (setf get-implementation) (value dispatch-var interface-name
				  dispatch-value)
  (let ((interface (get-interface dispatch-var interface-name)))
    (if interface
	(setf (interface-implementation interface dispatch-value) value)
	(error "Interface ~S not found in ~S" interface-name dispatch-var))))

(eval-when (:compile-toplevel :load-toplevel :execute)
  (defun extract-argument-names (arglist)
    (loop
       :for x :in arglist
       :unless (member x '(&optional &key &rest &allow-other-keys))
       :collect (if (consp x) (car x) x))))

(defmacro definterface (name dispatch-var arglist &optional documentation)
  (with-unique-names (args)
    `(progn
       (defun ,name (&rest ,args) ;;todo...
	 ,@(when documentation `(,documentation))
	 (destructuring-bind ,arglist ,args ;to check for arglist consistency
	   (declare (ignore ,@(extract-argument-names arglist))))
	 (let ((impl (get-implementation ',dispatch-var ',name ,dispatch-var)))
	   (if impl
	       (apply impl ,args)
	       (error "No implementation is defined for ~A when ~A = ~A"
		      ',name ',dispatch-var ,dispatch-var))))
       (setf (get-interface ',dispatch-var ',name)
	     (make-interface :name ',name :lambda-list ',arglist)))))

(defmacro defimplementation (name (dispatch-var dispatch-value) arglist
			     &body body)
  `(setf (get-implementation ',dispatch-var ',name ,dispatch-value)
	 (lambda ,arglist ,@body))) ;;todo check arglist is congruent with interface

(defun fix-implementation (dispatch-var)
  "Makes the current implementation of an interface permanent, avoiding a layer of indirection when calling the interface functions and thus improving performance, but losing the ability to change the implementation at runtime. Use only when your are absolutely sure you won't ever need to use a different implementation."
  (let ((dispatch-value (eval dispatch-var)))
    (loop
       :for entry :in (get-interfaces dispatch-var)
       :do (setf (symbol-function (car entry))
		 (interface-implementation (cdr entry) dispatch-value)))))

;;BROKEN
(defmacro with-implementation ((dispatch-var
				 &optional (dispatch-value (eval dispatch-var)))
				&body body)
  "Evaluates body in an environment where all implementations of interfaces dispatched by dispatch-var are selected at macro-expansion-time."
  `(let ((,dispatch-var ,dispatch-value))
     (flet (,@(loop
		 :for entry :in (get-interfaces dispatch-var)
		 :collect `(,(car entry) (&rest args)
			     (apply ,(interface-implementation
				       (cdr entry) dispatch-value)
				    args))))
       (declare (inline ,@(mapcar #'car (get-interfaces dispatch-var))))
       ,@body)))

#||
(setf (getf (symbol-plist '*aaa*) 'interfaces) nil)

(defvar *aaa* :aaa)

(definterface pippo *aaa* (a b c))

(defimplementation pippo (*aaa* :aaa) (a b c) (list a b c))

(defimplementation pippo (*aaa* :bbb) (a b c) (list c b a))

(pippo 1 2 3)

(let ((*aaa* :bbb))
  (pippo 1 2 3))

(get-interfaces '*aaa*)

(with-implementation (*aaa* :aaa) (pippo 1 2 3))
(with-implementation (*aaa* :bbb) (pippo 1 2 3))
(with-implementation (*aaa*) (pippo 1 2 3))
||#

;;Other stuff
(defmacro dbg (form &optional (stream '*standard-output*) &environment env)
  (with-unique-names (stream-var)
    `(let ((,stream-var ,stream))
       (format ,stream-var "~%;;; --debug--~%")
       (format ,stream-var "; Form:~%")
       (pprint (quote ,form) ,stream-var)
       ,@(when (and (consp form)
		    (symbolp (car form))
		    (macro-function (car form) env))
	      `((format ,stream-var "~%; Macroexpansion:~%")
	        (pprint ',(macroexpand form env) ,stream-var)))
       (format ,stream-var "~%;;; --end debug--~%")
       ,form)))
       
(defun str (&rest args)
  (with-output-to-string (str)
    (map nil (lambda (x) (princ x str)) args)))

(defmacro function* (form)
  (cond
    ((symbolp form) `(function ,form))
    ((listp form)
     (let ((f (car form))
	   (provided-args (cdr form)))
       `(let ((f (function ,f))) ;To provoke undefined-function error early
	  (lambda (&rest args)
	    (apply f ,@provided-args args)))))
    (t (error "function*: ~A should be a symbol or a list" form))))
