#!/usr/bin/env mzscheme
#lang scheme/base
(require scheme/pretty
scheme/cmdline
(planet zwizwa/staapl/tools))
(define-syntax-rule (flags: name ...)
(begin (define name (make-parameter #f)) ...))
(flags: output-hex
output-dict
device
baud
filename
print-asm
)
(device "/dev/staapl0")
(baud #f)
(print-asm void)
(filename
(command-line
#:program "staaplc"
#:once-each
[("-o" "--output-hex") filename "Output Intel HEX file."
(output-hex filename)]
[("--print-code") "Print assembly and binary code output."
(print-asm (lambda () (eval '(code-print))))]
[("-d" "--device") filename "Console device. (default: /dev/staapl0)" (device filename)]
[("--baud") number "Console baud rate. (default from source file)" (baud (string->number number))]
[("-d" "--output-dict") filename "Output dictionary file."
(output-dict filename)]
#:args (filename)
filename))
(define (out param template suffix)
(let ((p (param)))
(unless p
(param
(let-values (((base name _) (split-path template)))
(path-replace-suffix name suffix))))))
(out output-hex (filename) ".hex")
(out output-dict (filename) ".dict")
(define (absolute param)
(let ((p (param)))
(param
(if (absolute-path? p)
(string->path p)
(path->complete-path p)))))
(define orig-filename (filename))
(absolute filename)
(absolute output-hex)
(absolute output-dict)
(define (dir-of path)
(let-values (((base name _) (split-path path)))
base))
(unless (file-exists? (filename))
(printf "input file not found: ~a\n" (filename))
(exit 1))
(define (init-code path)
`(require
(planet zwizwa/staapl/live) (planet zwizwa/staapl/code) (planet zwizwa/staapl/port/ihex) (planet zwizwa/staapl/pic18) (file ,(path->string path))))
(parameterize
((current-namespace
(make-base-namespace)))
(eval (init-code (filename)))
((print-asm))
(unless (baud) (baud (eval '(macro-constant 'baud))))
(with-output-to-file/safe
(output-hex)
(lambda ()
(eval '(write-ihex (code->binary)))))
(with-output-to-file/safe
(output-dict)
(lambda ()
(pretty-print
`(begin
,(init-code (filename))
(code-clear!)
,(eval '(dict-snapshot))
(console '(,(device) ,(baud))))))))