;; nyacc/lang/c99/fh-01.test		-*- scheme -*-
;;
;; Copyright (C) 2018 Matthew R. Wette
;; 
;; Copying and distribution of this file, with or without modification,
;; are permitted in any medium without royalty provided the copyright
;; notice and this notice are preserved.  This file is offered as-is,
;; without any warranty.


(define-module (fh-01)
  #:use-module (nyacc lang c99 ffi-help)
  #:use-module (nyacc lang c99 munge)
  #:use-module (nyacc lang c99 parser)
  #:use-module (system ffi-help-rt)
  #:use-module ((system foreign) #:prefix ffi:)
  #:use-module ((srfi srfi-1) #:select (last drop-right))
  #:use-module (test-suite lib))

(use-modules (ice-9 pretty-print))
(define (pp exp) (pretty-print exp #:per-line-prefix "  "))
(define (sf fmt . args) (apply simple-format #t fmt args))

(define incs '("exam.d"))

(define (parse-file file)
  (with-input-from-file file
    (lambda ()
      (parse-c99 #:inc-dirs incs #:mode 'code))))

(define (parse-string str)
  (with-input-from-string str
    (lambda ()
      (parse-c99 #:inc-dirs incs #:mode 'code))))

(define (parse-string-list . str-l)
  (parse-string (apply string-append str-l)))

(define (string->udecl str)
  (let* ((tree (parse-string str))
	 (udict (c99-trans-unit->udict tree)))
    (and=> udict cdar)))

;; Scheme string -> expression, remove export
;; TODO: change define-public to define
(define (fh-str->exp/nox str)
  (let ((exp (fh-scm-str->scm-exp str)))
    (if (not (eq? 'begin (car exp))) (error "expecting begin"))
    (if (eq? 'export (car (last exp))) (drop-right exp 1) exp)))

(define fh-llibs '())

(define (nearly-equal? f1 f2)
  (< (abs (- f1 f2)) 0.0001))

;; FFI Helper basic test
(with-test-prefix "nyacc/ffi-help"
  ;;(add-to-load-path (getcwd))

  (pass-if "C-fun->proc fmod"
    (let* ((expr (C-fun-decl->scm "double fmod(double x, double y);\n"))
	   (fmod (eval expr (current-module))))
      (nearly-equal? 0.3 (fmod 2.3 0.5))))

  (compile-ffi-file "ffi/hsearch-s.ffi")
  (use-modules (ffi hsearch-t))

  )

;; --- last line ---
