aboutsummaryrefslogtreecommitdiff
path: root/module/vulgar/parse-cpp.scm
blob: 62d1e41a3752b69f2e197c203180771e9c51df94 (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
366
367
368
369
370
371
372
373
(define-module (vulgar parse-cpp)
  :use-module (util)
  :use-module (ice-9 popen)
  :use-module (ice-9 rdelim)
  :use-module (ice-9 peg)
  :use-module (ice-9 match)
  )


(define (read-lines port)
  (with-input-from-port port
    (lambda ()
      (let loop ((line (read-line)))
        (if (eof-object? line)
            '() (cons line (loop (read-line))))))))

(define (parse-header header-file)
  (map (lambda (line)
         (let* ((symbol (string-index line #\space))
                (value (string-index line #\space (1+ symbol))))
           (cons (substring line (1+ symbol) value)
                 (substring line (1+ value)))))
   (read-lines (open-input-pipe (string-append "cpp -dM " header-file))))

  #;
  (let* (((_ key . values) (string-split line #\space)))
    (if (char=? #\_ (string-ref key 0))
        (loop (read-line))
        (cons (cons key (string-join values " " 'infix))
              (loop (read-line)))))



  )



;;; Lexer


(define-peg-pattern base-8-digit body
  (range #\0 #\7))

(define-peg-pattern base-10-digit body
  (range #\0 #\9))

(define-peg-pattern base-16-digit body
  (or (range #\0 #\9)
      (range #\A #\F)
      (range #\a #\f)))

(define-peg-pattern base-10 all (+ base-10-digit))
(define-peg-pattern base-8 all (and "0" (+ base-8-digit)))
(define-peg-pattern base-16 all (and "0x" (+ base-16-digit)))

(define-peg-pattern number body
  (or base-8 base-16 base-10))

(define-peg-pattern group all
  (and (ignore "(") expr (ignore ")")))

(define-peg-pattern base-8-char all
  (and base-8-digit
       (? base-8-digit)
       (? base-8-digit)))

(define-peg-pattern base-16-char all
  (and (ignore "x") base-16-digit (? base-16-digit)))

(define-peg-pattern escaped-char all
  (and (ignore "\\") (or base-16-char
                         base-8-char
                         peg-any)))

(define-peg-pattern char all
  (and (ignore "'") (or escaped-char peg-any) (ignore "'")))

;; (define-peg-pattern string body
;;   (and "\"" (+ (or "\\\"" peg-any)) "\""))

;;; Simple operators are those which can be combined with '='
(define-peg-pattern simple-operator body
  (or "+" "-" "*" "/" "&" "|" "^" "<<" ">>" "%"
      "<" ">" "="))

(define-peg-pattern operator all
  (or (and simple-operator "=")
      "&&" "||"
      simple-operator
      "!=" ","
      "and" "bitand" "and_eq"
      "or" "bitor" "or_eq"
      "xor" "xor_eq"
      ;; "->" "." ; special cases since can only be used with variables
      ;; Todo Ternaries
      ))


;; whitespace
(define-peg-pattern ws none
  (or " " "	" "\n"))

;; space (for when whitespace is optional)
(define-peg-pattern sp none
  (* ws))

(define-peg-pattern safe-letter body
  (or "_"
      (range #\A #\Z)
      (range #\a #\z)))

(define-peg-pattern variable all
  (and safe-letter
       (* (or safe-letter
              base-10-digit))))

;; No further subparsing can be done.
;; NOTE that strings are generally also in this category.
(define-peg-pattern atom all
  (or base-8 base-10 base-16 number char variable))

;;; ++ and -- both pre and postfix

(define-peg-pattern prefix-operator all
  (or "!" "~" "*" "&" "++" "--" "+" "-"))

(define-peg-pattern prefix all
  (and prefix-operator sp expr))

(define-peg-pattern postfix-operator all
  (or "++" "--"))

(define-peg-pattern postfix all
  ;; literals can't be in-place incremented and decremented
  ;; Make sure we don't match postfix-operator here, since
  ;; that also gives us an infinite loop.
  (and (or prefix infix funcall group variable) sp postfix-operator))

;; 5 + 3 * 9
;; (5 + 3) * 9
;; 5 + (3 * 9)
(define-peg-pattern infix all
  ;; first case is "same" as expr, but in different order to prevent
  ;; infinite self reference.
  (and (or funcall group char prefix #; postfix number variable
           ) sp operator sp expr))

(define-peg-pattern funcall all
  (and variable sp group))

;;; main parser
(define-peg-pattern expr body
  (+ (and sp (or prefix #; postfix infix funcall group char number variable
                 ) sp)))


(define (lex string)
  (peg:tree (match-pattern expr string)))


;;; Parser


(define (parse-lexeme-tree tree)
  (match tree
    ['() '()]

    ;; Number constants
    [('base-10 n) (string->number n 10)]
    [('base-8  n) (string->number n  8)]
    [('base-16 n) (string->number n 16)]

    ;; Character literals
    [('char ('escaped-char ('base-8-char n)))
     (-> n (string->number 8) integer->char)]
    [('char ('escaped-char ('base-16-char n)))
     (-> n (string->number 16) integer->char)]
    [('char ('escaped-char c))
     (case (string-ref c 0)
       ((#\a) #\alarm)
       ((#\b) #\backspace)
       ((#\e) #\esc)
       ((#\f) #\page)
       ((#\n) #\newline)
       ((#\r) #\return)
       ((#\t) #\tab)
       ((#\v) #\vtab)
       ((#\\) #\\)
       ((#\') #\'))]
    [('char c) (string-ref c 0)]

    [('variable var) (string->symbol var)]
    [('operator op)  (string->symbol op)]
    [('prefix-operator op)
     (case (string->symbol op)
       ((*) 'dereference)
       ((&) 'pointer)
       ((++) 'pre-increment)
       ((--) 'pre-decrement)
       (else => identity))]
    [('postfix-operator op)
     (case (string->symbol op)
       [(++) 'post-increment]
       [(--) 'post-decrement]
       [else => identity])]

    ;; Parenthesis grouping
    [('group args)
     (parse-lexeme-tree args)]

    ;; Atomic item. Used by flatten-infix
    [('atom body)
     (parse-lexeme-tree body)]

    [('prefix op arg)
     `(,(parse-lexeme-tree op)
       ,(parse-lexeme-tree arg))]

    [('postfix arg op)
     `(,(parse-lexeme-tree op)
       ,(parse-lexeme-tree arg))]

    [('infix args ...)
     (resolve-order-of-operations
      (flatten-infix (cons 'infix args)))]

    [('funcall function ('group arguments))
     `(funcall ,(parse-lexeme-tree function)
               ,(parse-lexeme-tree arguments))]

    [bare (error "Naked literal in lex-tree. How did that get there?"
                 bare)]))

;;; TODO
;; (f "*C++")
;; $427 = (dereference (post-increment C))

(define (group-by list item)
  (let loop ((done '())
             (current '())
             (rem list))
    (cond [(null? rem)
           (reverse (cons (reverse current) done))]
          [(eqv? item (car rem))
           (loop (cons (reverse current) done)
                 '()
                 (cdr rem))]
          [else
           (loop done
                 (cons (car rem) current)
                 (cdr rem))])))

;; https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B

(define order-of-operations
  (reverse
   (apply append
          ;; This is only for binary operations
    `((* / %)
      (+ -)
      (<< >>)
      (< <= > >=)
      (== !=)
      (&)
      (^)
      (,(symbol #\|))
      (&&)
      (,(symbol #\| #\|))
      (= += -= *= /= %= <<= >>= &= ^= ,(symbol #\| #\=))
      (,(symbol #\,))
      ))))


;; (f "2 + (2*2)")
;; <unnamed port>:5967:23: In procedure resolve-order-of-operations:
;; In procedure car: Wrong type argument in position 1 (expecting pair): ()

;; Entering a new prompt.  Type `,bt' for a backtrace or `,q' to continue.

(define* (resolve-order-of-operations
          tree optional: (order order-of-operations))

  (cond [(null? order) (car tree)]
        [(not (list? tree)) tree]
        [(= 1 (length tree)) (resolve-order-of-operations
                              (car tree) order)]
        [else
         (let ((groups (group-by tree (car order))))
           (cond [(= 1 (length groups))
                  (resolve-order-of-operations
                   (car groups) (cdr order))]
                 [else
                  (cons (car order)
                        (append
                         (map (lambda (g) (resolve-order-of-operations
                                      g (cdr order)))
                              groups)))]))]))

;; Flatens a tree of infix triples. Stops when it should.
(define (flatten-infix form)
  (match form
    [('infix left op ('infix right ...))
     (cons* (parse-lexeme-tree left)
            (parse-lexeme-tree op)
            (flatten-infix (cons 'infix right)))]
    [('infix left op right)
     (map parse-lexeme-tree (list left op right))]
    [other (parse-lexeme-tree other)]))


;; scheme@(vulgar parse-cpp)> (match-pattern expr "a xorb")
;; $10 = #<peg start: 0 end: 6 string: a xorb tree: (infix (variable a) (operator xor) (variable b))>


(define (do-funcall function arguments)
  (if (list? arguments)
      (apply function arguments)
      (function arguments)))

(define-public (replace-symbols tree dict)
  (if (not (list? tree))
      (or (assoc-ref dict tree) tree)
      (map (lambda (node) (replace-symbols node dict))
           tree)))

(define f (compose parse-lexeme-tree lex))

;;; Right, when left simple binding
;; direct constant (int|char)
;; (op forms ...)
;; (do-funcall forms ...)
;; direct variable

(define (parse-cpp-define pair)
  (define left (f (car pair)))
  (define right (replace-symbols
                 (f (cdr pair))
                 `((,(symbol #\|) . logior)
                   (funcall . do-funcall)
                   (&& . and)
                   (& . logand)
                   (== . =)
                   (!= . (negate =))
                   )))

  (match left
    [('funcall name ('#{,}# args ...))
     `(define (,name ,@args)
        ,right)]

    [('funcall name arg)
     `(define (,name ,arg)
        ,right)]

    [name `(define ,name ,right)]))

;;; TODO order of these, to resolve dependencies
(define (parse-cpp-file file)
  ;; (map parse-cpp-define (parse-header file))
  (map (lambda (i line) (catch #t (lambda () (parse-cpp-define line))
                     (lambda (err caller fmt args . _) (format #t "~a ~?~%" i fmt args) #f)))
       (iota (length (parse-header file)) 1)
       (parse-header file)))

;; (parse-cpp-file "/usr/include/termios.h")

(begin
  (define file (open-output-file "/tmp/termios.scm"))
  (define lines (parse-cpp-file "/usr/include/termios.h"))

  (for-each (lambda (line) (format file "~y" line))
            lines)
  (close-port file))