summaryrefslogtreecommitdiff
path: root/cmamut.lisp
blob: 41910852725c0316eef5d0073dd038d063255977 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
(in-package #:cmamut)

(defparameter +target-package+ (gensym))

; TODO: Create a C parser so I don't rely on c2ffi.
; TODO: Process the header files directly in memory.
(defun get-raw-spec (filename search-directories)
  (sb-ext:run-program "/usr/local/bin/c2ffi"
                      (list filename
                            "--macro-file" "defines.h"
                            "--with-macro-defs"
                            "--output" "spec.json"))
  (let ((tmp (make-string-output-stream)))
    (with-open-file (in "defines.h")
      (loop :for ln = (read-line in nil)
            :while ln :do
            (when (some (lambda (path) (search path ln)) search-directories)
              (format tmp "~a~&~a~&" (read-line in) (read-line in)))))
    (with-open-file (out "defines.h" :direction :output :if-exists :supersede)
      (format out "~a" (get-output-stream-string tmp))))
  (sb-ext:run-program "/usr/local/bin/c2ffi"
                      (list "defines.h"
                            "--output" "defines.json"))
  (let ((spec (json:from-file "spec.json"))
        (defines (json:from-file "defines.json")))
    (delete-file "spec.json")
    (delete-file "defines.json")
    (delete-file "defines.h")
    (concatenate 'vector defines spec)))

(defun raw-array-p (type)
  (and (listp type)
       (eq (car type)
           :array)))

(defun define-argument (type)
  (if (raw-array-p type)
    (cons :pointer (cadr type))
    type))

(defun define-field (name type)
  (if (raw-array-p type)
    (cons name (cdr type))
    (list name type)))

; TODO: Handle different sizes of enum.
(defun cook-type (raw-type type-associations name-transformer)
  (let ((tag (gethash "tag" raw-type)))
    (cond ((string= tag ":void")
           :void)
          ((string= tag ":function-pointer")
           :pointer)
          ((string= tag ":pointer")
           (let ((pointed-type (gethash "type" raw-type)))
             (cond ((string= (gethash "tag" pointed-type) ":char")
                    :string)
                   ((string= (gethash "tag" pointed-type) ":void")
                    :pointer)
                   (t (list :pointer (define-argument
                                       (cook-type pointed-type type-associations name-transformer)))))))
          ((string= tag ":float")
           :float)
          ((or (string= tag ":double") (string= tag ":long-double"))
           :double)
          ((string= tag ":_Bool")
           :bool)
          ((string= tag ":unsigned-char")
           :unsigned-char)
          ((string= tag ":unsigned-short")
           :unsigned-short)
          ((string= tag ":unsigned-int")
           :unsigned-int)
          ((string= tag ":unsigned-long")
           :unsigned-long)
          ((string= tag ":unsigned-long-long")
           :unsigned-long-long)
          ((or (string= tag ":char") (string= tag ":signed-char"))
           :char)
          ((or (string= tag ":short") (string= tag ":signed-short"))
           :short)
          ((or (string= tag ":int") (string= tag ":signed-int") (char= (char tag 0) #\<))
           :int)
          ((or (string= tag ":long") (string= tag ":signed-long"))
           :long)
          ((or (string= tag ":long-long") (string= tag ":signed-long-long"))
           :long-long)
          ((string= tag ":array")
           (list :array (cook-type (gethash "type" raw-type) type-associations name-transformer)
                 :count
                 (gethash "size" raw-type)))
          ((string= tag ":struct")
           (list :struct (intern (funcall name-transformer (gethash "name" raw-type) :composite)
                                 +target-package+)))
          ((string= tag ":union")
           (list :union (intern (funcall name-transformer (gethash "name" raw-type) :composite)
                                +target-package+)))
          ((string= tag ":enum")
           :int)
          ((or (string= tag "struct") (string= tag "union"))
           (cons :struct
                 (cdr (cook-composite raw-type type-associations name-transformer))))
          ((string= tag "__builtin_va_list")
           :pointer)
          (t (let ((new-type (gethash tag type-associations)))
               (if new-type
                 (cook-type new-type type-associations name-transformer)
                 (error "Unknown type: ~a" tag)))))))

(defun cook-function (raw-function type-associations name-transformer)
  (let ((raw-params (gethash "parameters" raw-function))
        (cooked-params (queue:new)))
    (dotimes (j (length raw-params))
      (queue:add cooked-params
                 (list (if (string= (gethash "name" (aref raw-params j)) "")
                         (gensym)
                         (make-symbol (funcall name-transformer
                                               (gethash "name" (aref raw-params j))
                                               :argument)))
                       (define-argument
                         (cook-type (gethash "type" (aref raw-params j)) type-associations name-transformer)))))
    `(defcfun
       ,(let ((function-name (gethash "name" raw-function)))
          (list function-name (intern (funcall name-transformer function-name :function) +target-package+)))
       ,(define-argument
          (cook-type (gethash "return-type" raw-function) type-associations name-transformer))
       ,@(queue:to-list cooked-params))))

(defun cook-composite (raw-composite type-associations name-transformer)
  (let ((raw-fields (gethash "fields" raw-composite))
        (cooked-fields (queue:new)))
    (dotimes (j (length raw-fields))
      (queue:add cooked-fields
                 (define-field
                   (intern (string-upcase (gethash "name" (aref raw-fields j)))
                           'keyword)
                   (cook-type (gethash "type" (aref raw-fields j)) type-associations name-transformer))))
    `(,(find-symbol (string-upcase
                      (concatenate 'string
                                   "defc"
                                   (gethash "tag" raw-composite)))
                    'cffi)
       ,(intern (funcall name-transformer (gethash "name" raw-composite) :composite)
                +target-package+)
       ,@(queue:to-list cooked-fields))))

(defun cook-const (raw-const name-transformer)
  `(defconstant
     ,(intern (funcall name-transformer (gethash "name" raw-const) :const) +target-package+)
     ,(gethash "value" raw-const)))

(defun cook-enum (raw-enum enum-references name-transformer)
  (let ((name (if (> (gethash "id" raw-enum) 0)
                (gethash (gethash "id" raw-enum) enum-references)
                (gethash "name" raw-enum)))
        (raw-fields (gethash "fields" raw-enum))
        (cooked-fields (queue:new)))
    (dotimes (j (length raw-fields))
      (queue:add cooked-fields
                 `(defconstant
                    ,(intern (funcall name-transformer (gethash "name" (aref raw-fields j)) :const)
                             +target-package+)
                    ,(gethash "value" (aref raw-fields j)))))
    `(progn
       ,name
       ,@(queue:to-list cooked-fields))))

(defun generate-enum-references (raw-typedefs)
  (let ((enum-references (make-hash-table :test #'equal :size 256)))
    (dolist (i raw-typedefs)
      (let ((inner-type (gethash "type" i)))
        (when (string= (gethash "tag" inner-type) ":enum")
          (setf (gethash "name" inner-type) (gethash "name" i))
          (setf (gethash (gethash "id" inner-type) enum-references)
                (gethash "name" i)))))
    enum-references))

; Typedefs get "flattened" so that resolving is just a lookup.
(defun generate-type-associations (raw-typedefs)
  (let ((type-associations (make-hash-table :test #'equal :size 256)))
    (dolist (i raw-typedefs)
      (setf (gethash (gethash "name" i) type-associations) (gethash "type" i)))
    (labels ((flatten-typedef (k v)
                              (let ((new-v (gethash (gethash "tag" v) type-associations)))
                                (when new-v
                                  (setf (gethash k type-associations) new-v)
                                  (flatten-typedef k new-v)))))
      (maphash #'flatten-typedef type-associations))
    type-associations))

(defstruct spec
  consts
  functions
  typedefs
  composite
  enums)

; TODO: Sort the entries alphabetically, to increase consistency of generated files.
; This is done so we can separate definition types into stages when generating code.
; When processing typedefs we need to identify nested composite types and put them into the right buckets.
; What's left on the typedefs are references to said composite types.
; This allows for a comfier type resolution stage by letting us flatten typedefs.
; Composite types cause problems because they can't be redefined.
(defun classify-definitions (raw-spec)
  (let ((spec (make-spec)))
    (dotimes (i (length raw-spec))
      (classify-definition (aref raw-spec i) spec))
    spec))

(defun classify-definition (def spec)
  (let ((tag (gethash "tag" def)))
    (cond ((string= tag "function")
           (push def (spec-functions spec)))

          ((and (string= tag "const") (gethash "value" def))
           (push def (spec-consts spec)))

          ((or (string= tag "typedef")
               (string= tag ":array")
               (string= tag ":pointer"))
           (let* ((internal-type (gethash "type" def))
                  (internal-tag (gethash "tag" internal-type)))
             (cond ((or (string= internal-tag "struct")
                        (string= internal-tag "union"))
                    (setf (gethash "name" internal-type) (gethash "name" def))
                    (push internal-type (spec-composite spec))
                    (setf (gethash "type" def)
                          (json:obj ("tag" (gethash "tag" internal-type))
                                    ("name" (gethash "name" internal-type)))))
                   ((or (string= internal-tag ":array")
                        (string= internal-tag ":pointer"))
                    (classify-definition internal-type spec)))
             (when (string= tag "typedef")
               (push def (spec-typedefs spec)))))

          ((string= tag "enum")
           (push def (spec-enums spec)))

          ((or (string= tag "struct") (string= tag "union"))
           (push def (spec-composite spec)))))
  spec)

(defun find-dependency (field-type type-associations)
  (let* ((type-assoc (gethash (gethash "tag" field-type)
                              type-associations))
         (inner-type (or type-assoc field-type))
         (type-tag (gethash "tag" inner-type)))
    (cond ((or (string= type-tag ":struct")
               (string= type-tag "struct")
               (string= type-tag ":union")
               (string= type-tag "union"))
           (gethash "name" inner-type))
          ((or (string= type-tag ":pointer")
               (string= type-tag ":array"))
           (find-dependency (gethash "type" inner-type)
                            type-associations))
          (t nil))))

(defun gather-dependencies (raw-composite type-associations)
  (let ((result nil)
        (fields (gethash "fields" raw-composite)))
    (dotimes (i (length fields))
      (let* ((field-type (gethash "type" (aref fields i)))
             (dependency (find-dependency field-type type-associations)))
        (if dependency
          (push dependency result))))
    (cons raw-composite result)))

; Composites need to be defined in a partial ordering so dependencies are satisfied.
(defun sort-composites (raw-composites type-associations)
  (labels ((partial-sort (leaves roots)
                         (if roots
                           (let ((new-leaves (mapcar
                                               (lambda (x) (car x))
                                               (remove-if
                                                 (lambda (x) (> (length x) 1))
                                                 roots)))
                                 (new-roots (remove-if
                                              (lambda (x) (= (length x) 1))
                                              roots)))
                             (dolist (i new-leaves)
                               (let ((leaf-name (gethash "name" i)))
                                 (dolist (j new-roots)
                                   (delete leaf-name j :test #'equal))))
                             (partial-sort (concatenate 'list
                                                        leaves
                                                        new-leaves)
                                           new-roots))
                           leaves)))
    (let ((result (partial-sort nil
                                (mapcar (lambda (x)
                                          (gather-dependencies x type-associations))
                                        raw-composites))))
      result)))

(defun codegen (spec name-transformer)
  (let ((enum-references (generate-enum-references (spec-typedefs spec)))
        (type-associations (generate-type-associations (spec-typedefs spec))))
    (let ((consts (mapcar (lambda (x) (cook-const x name-transformer))
                          (spec-consts spec)))
          (enums (mapcar (lambda (x) (cook-enum x enum-references name-transformer))
                         (spec-enums spec)))
          (composite (mapcar (lambda (x) (cook-composite x type-associations name-transformer))
                             (sort-composites (spec-composite spec)
                                              type-associations)))
          (functions (mapcar (lambda (x) (cook-function x type-associations name-transformer))
                             (spec-functions spec))))
      (remove-duplicates (concatenate 'list consts enums composite functions) :test #'equal))))

; TODO: Generate a lisp file for every header file.
; TODO: Generate a file for the shared objects.
; TODO: Create an asd file referencing the generated files.
(defun to-file (code filename pkg-name shared-object)
  (with-open-file (f "package.lisp"
                     :direction :output
                     :if-exists nil)
    (format f "(DEFPACKAGE #:~a~&  (:EXPORT" pkg-name)
    (let ((*package* (find-package +target-package+)))
      (do-symbols (s *package*) (format f "~&    #:~s" s)))
    (format f "))~&")
    (when shared-object
      (format f "~s~&"
              `(cffi:define-foreign-library ,pkg-name
                                            (:unix ,shared-object)))
      (format f "~s~&"
              `(cffi:use-foreign-library ,pkg-name))))
  (with-open-file (f filename
                     :direction :output
                     :if-exists nil)
    (let ((*print-length* nil)
          (*print-level* nil)
          (*package* (find-package +target-package+)))
      (format f "(COMMON-LISP:IN-PACKAGE #:~a)~&" pkg-name)
      (format f "~{~s~&~}" code))))

(defun filter-directories (search-directories raw-spec)
  (remove-if (lambda (x)
               (and (notany (lambda (dir)
                              (let ((location (gethash "location" x)))
                                (string= dir location :end2 (min (length location) (length dir)))))
                            search-directories)
                    (string/= (gethash "tag" x) "typedef")
                    (string/= (gethash "tag" x) "const")))
             raw-spec))

(defun default-name-transformer (name type)
  (cond ((eq type :const)
         (concatenate 'string "+" (string-upcase (str:underscore->hyphen name)) "+"))
        (t (string-upcase
             (str:pascal->kebab
               (str:upcase->pascal
                 (str:underscore->hyphen name)))))))

; TODO: Handle multiple header files and shared objects.
(defun generate-bindings (package-name &key header-file shared-object additional-directories name-transformer)
  (unless (probe-file header-file)
    (error (format t "The header file ~a doesn't exist!" header-file)))
  (when (not (find-package +target-package+))
    (make-package +target-package+))
  (setf header-file (parse-namestring header-file))
  (push (directory-namestring header-file) additional-directories)
  (let* ((raw-spec (get-raw-spec (namestring header-file) additional-directories))
         (spec (classify-definitions (filter-directories additional-directories raw-spec)))
         (code (codegen spec (or name-transformer #'default-name-transformer))))
    (to-file code (concatenate 'string (pathname-name header-file) ".lisp") package-name shared-object))
  (delete-package (find-package +target-package+)))