; This file contains the lisp library code for the Munger interpreter.

; Copyright (c) 2001, 2002, 2003, James Bailie <jimmy@mammothcheese.ca>.
; All rights reserved.
;
; Redistribution and use in source form, with or without
; modification, are permitted provided that the following conditions are met:
;
;     * Redistributions of source code must retain the above copyright
; notice, this list of conditions and the following disclaimer.
;     * The name of James Bailie may not be used to endorse or promote
; products derived from this software without specific prior written permission.
;
; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
; ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
; POSSIBILITY OF SUCH DAMAGE.

(set 'caar (lambda (x) (car (car x))))
(set 'cdar (lambda (x) (cdr (car x))))
(set 'cadr (lambda (x) (car (cdr x))))
(set 'cddr (lambda (x) (cdr (cdr x))))
(set 'caddr (lambda (x) (car (cdr (cdr x)))))
(set 'cdddr (lambda (x) (cdr (cdr (cdr x)))))
(set 'cadddr (lambda (x) (car (cdr (cdr (cdr x))))))
(set 'cddddr (lambda (x) (cdr (cdr (cdr (cdr x))))))
(set 'caddddr (lambda (x) (car (cdr (cdr (cdr (cdr x)))))))

(set 'nullp (lambda (x) (eq x ())))
(set 'pairp (lambda (x) (and (not (atomp x)) (not (nullp x)))))

(set 'equal
   (lambda (x y)
       (if (eq x y)
           1
           (and (pairp x)
                (pairp y)
                (equal (car x) (car y))
                (equal (cdr x) (cdr y))))))

(set 'reverse
   (lambda (x)
      (if (stringp x)
         (join "" (reverse (split "" x)))

         (if (pairp x)
            (append (reverse (cdr x)) (list (car x)))
            ()))))

(set 'remove
   (lambda (y x)
      (if (not (pairp x))
         x
         (if (equal (car x) y)
            (remove y (cdr x))
            (cons (car x) (remove y (cdr x)))))))

(set 'alist_lookup
   (lambda (x y)
      (if (not (pairp y))
         ()
         (catch
            (while y
               (if (equal (caar y) x)
                  (throw (cdar y))
                  (set 'y (cdr y))))))))

(set 'alist_remove
   (lambda (x y)
      (let ((z y))
         (catch
            (while y
               (if (equal (caar y) x)
                  (throw (remove (car y) z)))
               (set 'y (cdr y)))
            z))))

(set 'alist_replace
   (lambda (x y z)

      (let ((w y))
         (catch
            (while y
               (if (equal (caar y) x)
                  (throw (cons (cons x z) (remove (car y) w))))
               (set 'y (cdr y)))

            (cons (cons x z) w)))))

(set 'upcase
   (lambda (s a)
      (when s
         (let ((x 1))

            (join ""
               (mapcar
                  (lambda (c)
                     (let ((d (code c)))
                        (if (not (and x (<= d 122) (>= d 97)))
                           c
                           (when (not a) (setq x 0))
                           (char (- d 32)))))

                  (split "" s)))))))

(set 'downcase
   (lambda (s a)
      (when s
         (let ((x 1))

            (join ""
               (mapcar
                  (lambda (c)
                     (let ((d (code c)))
                        (if (not (and x (<= d 90) (>= d 65)))
                           c
                           (when (not a) (setq x 0))
                           (char (+ d 32)))))

                  (split "" s)))))))

(setq mapcar
   (lambda (f l)
      (when l
         (let ((n ()))
            (while l
               (setq n (cons (f (car l)) n))
               (setq l (cdr l)))
            (reverse n)))))

(set 'map
   (lambda (f l (more))
      (if (not more)
         (mapcar f l)

         (letf map_more ((l l)
                         (more more))

            (when l
               (cons (eval (cons f (cons (car l) (map car more))))
                  (map_more (cdr l) (map cdr more))))))))

(set 'foreach
   (lambda (f l)
      (while l
         (f (car l))
         (setq l (cdr l)))))

(set 'member
   (lambda (x l)
      (if (not l)
         0
         (if (equal (car l) x)
            1
            (member x (cdr l))))))

(set 'apply
   (macro (a b)
      (list 'eval (list 'cons a b))))

(set 'quit (macro () '(exit 0)))

(set 'qquote
   (macro (args)
      (labels ((buildit
                  (lambda (args)
                     (and args
                        (cons (cond ((eq (car args) ',)
                                     (car (set 'args (cdr args))))

                                    ((pairp (car args))
                                     (cons 'list (buildit (car args))))

                                    (1 (list 'quote (car args))))

                              (buildit (cdr args)))))))

         (cons 'list (buildit args)))))

(set 'with_input_file
   (macro (file (code))
      (qquote
         (when (> (redirect 0 ,file) 0)
            (protect ,(cons 'progn code)
               (resume 0))))))

(set 'with_output_file
   (macro (file (code))
      (qquote
         (when (> (redirect 1 ,file) 0)
            (protect ,(cons 'progn code)
               (resume 1))))))

(set 'with_error_file
   (macro (file (code))
      (qquote
         (when (> (redirect 2 ,file) 0)
            (protect ,(cons 'progn code)
               (resume 2))))))

(let ((r (gensym)))

   (set 'with_error_file_appending
      (macro (file (code))
         (qquote
            (let ((,r 0))
               (if (> (setq ,r (redirect 2 ,file 1)) 0)
                  (protect ,(cons 'progn code)
                     (resume 2))
                  ,r))))))

(let ((r (gensym)))

   (set 'with_output_file_appending
      (macro (file (code))
         (qquote
            (let ((,r 0))
               (if (> (setq ,r (redirect 1 ,file 1)) 0)
                  (protect ,(cons 'progn code)
                     (resume 1))
                  ,r))))))

(set 'with_input_process
   (macro (cmd (code))
      (qquote
         (progn
            (pipe 0 ,cmd)
            (protect ,(cons 'progn code)
               (resume 0))))))

(set 'with_output_process
   (macro (cmd (code))
      (qquote
         (progn
            (pipe 1 ,cmd)
            (protect ,(cons 'progn code)
               (resume 1))))))

(let ((line (gensym)))

   (set 'foreach_line
      (macro (func)

         (qquote
            (if (not (next))
               (while (set (quote ,line) (getline))
                  (,func ,line))

               (do
                  (when (> (redirect 0 (current)) 0)
                     (while (set (quote ,line) (getline))
                        (,func ,line)))
                  (next))

               (resume 0))))))

(let ((line (gensym)))

   (set 'foreach_line_callback
      (macro (func callback (after))

         (qquote
            (if (not (next))
               (progn
                  (while (set (quote ,line) (getline))
                     (,func ,line))
                  (,callback))

               (do
                  (when (> (redirect 0 (current)) 0)
                     (while (set (quote ,line) (getline))
                        (,func ,line)))

                  ,(if (and after (car after))
                     (qquote
                        (prog1
                           (next)
                           (,callback)))

                     (qquote
                        (progn
                           (,callback)
                           (next)))))

               (resume 0))))))

(set 'assign
   (lambda (s l)

      (let ((n 0)
            (len (length l)))

         (progn
            (while (< (length s) len)
               (push s ()))

            (while l
               (store s n (car l))
               (inc n)
               (set 'l (cdr l)))

            s))))

(set 'flatten
   (lambda (s)

      (let ((r ())
            (i (length s)))

         (progn
            (while i
               (set 'r (cons (index s (dec i)) r)))

            r))))

(let ((buff (gensym)))

   (set 'with_buffer
      (macro (x (y))

         (qquote
            (let ((,buff (buffer)))
               (switch ,x)
               (protect ,(cons 'progn y)
                  (switch ,buff)))))))

(set 'defun
   (macro (name args (body))
      (qquote
         (set (quote ,name)
            ,(cons 'lambda (cons args body))))))

(set 'defmac
   (macro (name args (body))
      (qquote
         (set (quote ,name)
            ,(cons 'macro (cons args body))))))

(defmac letf (name args (body))
   (qquote
      (labels ((,name ,(append (list 'lambda (mapcar car args)) body)))
         ,(cons name (mapcar cadr args)))))

(let ((r (gensym)))

   (defmac prog1 ((args))
      (when args
         (qquote
            (let ((,r 0))
               (setq ,r ,(car args))
               ,(cons 'progn (cdr args))
               ,r)))))

(defmac concat ((args))
   (cons 'join (cons "" args)))

(defmac explode (arg)
   (list 'split "" arg))

(defun split_rx (rx arg (limit))

   (let ((m (match rx arg))
         (limit (if limit (- (abs (car limit)) 1) -1))
         (r ()))

      (if (not m)
         (list arg)

         (catch
            (while (and limit m)
               (when (car m)
                  (dec limit)
                  (setq r (cons (substring arg 0 (car m)) r)))

               (when (eq (length arg) (cadr m))
                  (throw (reverse r)))

               (setq arg (substring arg (cadr m) 0))
               (setq m (match rx arg)))

            (reverse (cons arg r))))))

(let ((rx (regcomp (concat "[\b\t" (char 10) (char 13) "]+"))))
   (defun tokenize (arg)
      (split_rx rx arg)))

(let ((m (gensym))
      (i (gensym))
      (l (gensym))
      (r (gensym))
      (c (gensym))
      (p (gensym)))

   (defmac replace (rx expr str (limit))
      (qquote

         (let ((,m (matches ,rx ,str))
               (,i -1)
               (,l "")
               (,r "")
               (,c 0)
               (,p ()))

            (if (not ,m)
               ,str

               (setq ,p ,m)
               (while ,p
                  (extend (intern (stringify "m" (inc ,i))) (car ,p))
                  (setq ,p (cdr ,p)))

               (setq ,l ,str)
               (setq ,c (if (quote ,limit) (+ 1 (car (quote ,limit))) -1))

               (catch
                  (while (and (dec ,c) ,m)
                     (setq ,p (match ,rx ,l))

                     (setq ,r
                        (concat ,r
                           (if (car ,p) (substring ,l 0 (car ,p)) "")
                           (substitute ,rx
                              ,expr
                              (if (cadr ,p) (substring ,l (car ,p) (- (cadr ,p) (car ,p))) "")
                              1)))

                     (when (eq (cadr ,p) (length ,l))
                        (throw ,r))

                     (setq ,l (substring ,l (cadr ,p) 0))
                     (setq ,m (matches ,rx ,l))

                     (setq ,i -1)
                     (foreach (lambda (x) (set (intern (stringify "m" (inc ,i))) x)) ,m))

                  (concat ,r ,l)))))))

(let ((root_rx (regcomp "^(.*)(\.[^.]*)$")))

   (defun rootname (str)
      (substitute root_rx "\1" str))

   (defun suffix (str)
      (substitute root_rx  "\2" str)))

(defmac case (expr (clauses))

   (let ((c (gensym)) (l ()))

      (while clauses
         (setq l (cons (cons (if (eq (caar clauses) '?) 1 (list 'eq (caar clauses) c))
                             (cdar clauses))
                       l))
         (setq clauses (cdr clauses)))

      (qquote
         (let ((,c ,expr))
            ,(cons 'cond (reverse l))))))

(defun getstring (cmd)
   (let ((line "") (str ""))
      (with_input_process cmd
         (while (setq line (getline))
            (setq str (concat str line)))
         str)))

(let ((g (gensym)))
   (defmac with_temporary_output_file ((exprs))
      (qquote 
         (let ((,g (temporary)))
            (protect
               ,(cons 'progn exprs)
               (resume 1))
            ,g))))
