#!/bin/sh
# -*- scheme -*-
exec guile $0 $*
!#
;; Copyright (C) 2025 Matthew Wette
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public License
;; along with this library; if not, see <http://www.gnu.org/licenses/>


(use-modules (nyacc lang julia parser))
;;(use-modules (nyacc lang julia pprint))

(use-modules (ice-9 pretty-print))
(define pp pretty-print)


;; =================================

(use-modules (srfi srfi-37))

(define (fail fmt . args)
  (apply simple-format (current-error-port)
	 (string-append "nxjulia: " fmt "\n")
	 args)
  (exit 1))

(define (show-usage)
  (simple-format #t "Usage: mltoc [OPTION] FILE ...
Convert a julia dot-jl file to c.
  -h, --help           print this help message

Report bugs to https://savannah.nongnu.org/projects/nyacc.\n"))

(define options
  (list
   (option '(#\h "help") #f #f
	   (lambda (opt name arg opts files)
	     (values (acons 'help #t opts) files)))
   (option '(#\s "sxml") #f #f
           (lambda (opt name arg opts files)
             (values (acons 'sxml #t opts) files)))
   (option '(#\p "pprint") #f #f
           (lambda (opt name arg opts files)
             (values (acons 'pprint #t opts) files)))
   (option '(#\c "c99") #f #f
           (lambda (opt name arg opts files)
             (values (acons 'c99 #t opts) files)))
   ))

(define (parse-args args)
  (args-fold args options
	     (lambda (opt name arg files opts)
	       (fail "unrecognized option: ~S" name)
	       (exit 1))
	     (lambda (file opts files)
	       (unless (string-suffix? ".jl" file)
		 (fail "expecting .jl file"))
	       (values opts (cons file files)))
	     '() '()))

(define (main . args)
  (call-with-values
      (lambda () (parse-args args))
    (lambda (opts files)
      (when (or (assq-ref options 'help) (null? files)) (show-usage) (exit 0))
      (for-each 
       (lambda (srcfile)
         (let ((tree (call-with-input-file srcfile
                       (lambda (port)
                         (set-port-filename! port srcfile)
                         (read-julia-file port '())))))
           (when (assq-ref opts 'sxml) (pp tree))
           ;;(when (assq-ref opts 'pprint) (pretty-print-jl tree))
           ;;(when (assq-ref opts 'c99) (mlang->c99 tree opts))
           #f))
       files)))
  0)

(apply main (cdr (program-arguments)))

;; --- last line ---
