-
Notifications
You must be signed in to change notification settings - Fork 0
/
c.lisp
2113 lines (1933 loc) · 72.6 KB
/
c.lisp
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(declaim (optimize
(safety 3)
(speed 0)
(debug 3)))
#-nil
(progn (ql:quickload "alexandria")
(defpackage :cl-cpp-generator2
(:use :cl
:alexandria
:cl-ppcre)
(:export
#:write-source)))
;;(setf *features* (union *features* '(:generic-c)))
;;(setf *features* (set-difference *features* '(:generic-c)))
(in-package :cl-cpp-generator2)
(setf (readtable-case *readtable*) :invert)
(defparameter *file-hashes* (make-hash-table))
(defparameter *auto-keyword* "auto")
(defun write-notebook (&key nb-file nb-code (std 17))
"write xeus-cling C++ jupyter notebook"
(let ((tmp (format nil "~a.tmp" nb-file)))
(with-output-to-file (s tmp :if-exists :supersede
:if-does-not-exist :create)
(format
s "~a~%"
(jonathan:to-json
`(:|cells|
,(loop for e in nb-code
collect
(destructuring-bind (name &rest rest) e
(case name
(`markdown `(:cell_type "markdown"
:metadata :empty
:source
,(loop for p in rest
collect
(format nil "~a~c" p #\Newline))))
(`cpp `(:cell_type "code"
:metadata :empty
:execution_count :null
:outputs ()
:source
,(loop for p in rest
appending
(let ((tempfn #+sbcl "/dev/shm/cell.cpp"
#+ecl (format nil "~a_tmp_cell" nb-file)))
(write-source tempfn p)
(with-open-file (stream (format nil "~a" tempfn))
(loop for line = (read-line stream nil)
while line
collect
(format nil "~a~c" line #\Newline)))))))
)))
:|metadata| (:|kernelspec| (:|display_name| ,(format nil "C++~a" std)
:|language| ,(format nil "C++~a" std)
:|name| ,(format nil "xcpp~a" std)))
:|nbformat| 4
:|nbformat_minor| 2
#+nil
(:metadata (:kernelspec (:display_name "Python 3"
:language "python"
:name "python3"))
:nbformat 4
:nbformat_minor 2)))))
#+nil
(sb-ext:run-program "/usr/bin/python3" `("-mjson.tool" ,nb-file))
#-sbcl
(external-program:run
"/usr/bin/jq"
`("-M" "." ,tmp)
:output nb-file
:if-output-exists :supersede
)
#+sbcl
(sb-ext:run-program "/usr/bin/jq" `("-M" "." ,tmp)
:output nb-file
:if-output-exists :supersede)
(delete-file tmp)))
(defun write-source (name code &key
(dir (user-homedir-pathname))
ignore-hash
(format t)
(tidy t)
(omit-parens nil)
)
"This function writes the given code into a file specified by the name and directory.
It also provides options to control the behavior of the writing process.
Parameters:
name - the name of the file to be written
code - the code to be written into the file (s-expression)
dir - the directory where the file will be written (default is user's home directory)
ignore-hash - a flag indicating whether to ignore the hash value of the file, which means the code will be written into the file if the hash value is different from the previous one (default is nil)
format - a flag indicating whether to format the code using clang-format (default is t)
tidy - a flag indicating whether to tidy the code using clang-tidy (default is t)
omit-parens - a flag indicating whether to omit redundant parentheses in the code (default is nil)
Example usage:
(write-source \"myfile.cpp\" `(defun foo () (declare (values int)) (return 42)) :dir \"/path/to/directory\" :format nil)"
;(format t "<write-source code='~a'>~%" code)
(let* ((fn (merge-pathnames (format nil "~a" name)
dir))
(code-str (m-of (emit-c :code code :header-only nil
:omit-redundant-parentheses omit-parens)))
(fn-hash (sxhash fn))
(code-hash (sxhash code-str)))
(multiple-value-bind (old-code-hash exists) (gethash fn-hash *file-hashes*)
(when (or (not exists) ignore-hash (/= code-hash old-code-hash)
(not (probe-file fn)))
(format t "write code into file: '~a'~%" fn)
;; store the sxhash of the c source in the hash table
;; *file-hashes* with the key formed by the sxhash of the full
;; pathname
(setf (gethash fn-hash *file-hashes*) code-hash)
(with-open-file (s fn
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(write-sequence code-str s))
;; https://travisdowns.github.io/blog/2019/11/19/toupper.html
;; header reordering can affect compilation performance
;; https://stackoverflow.com/questions/60334299/clang-format-disable-ordering-includes
;; SortIncludes: false in .clang-format
(when format
(sb-ext:run-program "/usr/bin/clang-format"
(list "-i" (namestring fn)
"-style=llvm" ;; removes unneccessary parentheses (i hope)
;; "-style='{PenaltyReturnTypeOnItsOwnLine: 100000000}'"
)))
(when tidy
(sb-ext:run-program "/usr/bin/clang-tidy"
(list (namestring fn)
"--checks=readability-*"
"--fix"
))
)))))
;; http://clhs.lisp.se/Body/s_declar.htm
;; http://clhs.lisp.se/Body/d_type.htm
;; go through the body until no declare anymore
;; (declare (type int a b) (type float c)
;; (declare (values int &optional))
;; (declare (values int float &optional))
;; FIXME doesnt handle documentation strings
;; FIXME: misses const override
(defun consume-declare (body)
"Take a list of instructions from `body`, parse type declarations,
return the `body` without them and a hash table with an environment. The
entry `return-values` contains a list of return values. Currently supports
type, values, construct, and capture declarations. Construct is member
assignment in constructors. Capture is for lambda functions.
Parameters:
- `body` (list): The list of instructions to process.
Returns:
- `new-body` (list): The modified `body` without the type declarations.
- `env` (hash-table): The hash table containing the environment.
- `captures` (list): The list of captured variables.
- `constructs` (list): The list of constructed variables.
- `const-p` (boolean): Indicates if the `const` declaration is present.
- `explicit-p` (boolean): Indicates if the `explicit` declaration is present.
- `inline-p` (boolean): Indicates if the `inline` declaration is present.
- `static-p` (boolean): Indicates if the `static` declaration is present.
- `virtual-p` (boolean): Indicates if the `virtual` declaration is present.
- `noexcept-p` (boolean): Indicates if the `noexcept` declaration is present.
- `final-p` (boolean): Indicates if the `final` declaration is present.
- `override-p` (boolean): Indicates if the `override` declaration is present.
- `pure-p` (boolean): Indicates if the `pure` declaration is present.
- `template` (symbol): The template declaration.
- `template-instance` (symbol): The template instance declaration."
(let ((env (make-hash-table))
(captures nil)
(constructs nil)
(const-p nil)
(explicit-p nil)
(inline-p nil)
(static-p nil)
(virtual-p nil)
(noexcept-p nil)
(final-p nil)
(override-p nil)
(pure-p nil)
(template nil)
(template-instance nil)
(looking-p t)
(new-body nil))
(loop for e in body do
(if looking-p
(if (listp e)
(if (eq (car e) 'declare)
(loop for declaration in (cdr e) do
(when (eq (first declaration) 'type)
(destructuring-bind (symb type &rest vars) declaration
(declare (ignorable symb))
(loop for var in vars do
(setf (gethash var env) type))))
(when (eq (first declaration) 'capture)
(destructuring-bind (symb &rest vars) declaration
(declare (ignorable symb))
(loop for var in vars do
(push var captures))))
(when (eq (first declaration) 'construct)
(destructuring-bind (symb &rest vars) declaration
(declare (ignorable symb))
(loop for var in vars do
(push var constructs))))
(when (eq (first declaration) 'const)
(setf const-p t))
(when (eq (first declaration) 'explicit)
(setf explicit-p t))
(when (eq (first declaration) 'inline)
(setf inline-p t))
(when (eq (first declaration) 'virtual)
(setf virtual-p t))
(when (eq (first declaration) 'noexcept)
(setf noexcept-p t))
(when (eq (first declaration) 'final)
(setf final-p t))
(when (eq (first declaration) 'override)
(setf override-p t))
(when (eq (first declaration) 'pure)
(setf pure-p t))
(when (eq (first declaration) 'static)
(setf static-p t))
(when (eq (first declaration) 'template)
(setf template (second declaration)))
(when (eq (first declaration) 'template-instance)
(setf template-instance (second declaration)))
(when (eq (first declaration) 'values)
(destructuring-bind (symb &rest types-opt) declaration
(declare (ignorable symb))
;; if no values specified parse-defun will emit void
;; if (values :constructor) then nothing will be emitted
(let ((types nil))
;; only collect types until occurrence of &optional
(loop for type in types-opt do
(unless (eq #\& (aref (format nil "~a" type) 0))
(push type types)))
(setf (gethash 'return-values env) (reverse types))))))
(progn
(push e new-body)
(setf looking-p nil)))
(progn
(setf looking-p nil)
(push e new-body)))
(push e new-body)))
(values (reverse new-body) env (reverse captures) (reverse constructs)
const-p explicit-p inline-p static-p virtual-p noexcept-p final-p override-p pure-p template template-instance)))
(defun lookup-type (name &key env)
"Get the type of a variable from an environment.
This function takes a variable name and an environment and returns the type of the variable.
Parameters:
- name: The name of the variable.
- env: The environment containing the variable.
Returns:
The type of the variable, or nil if the variable is not found in the environment."
(gethash name env))
(defun variable-declaration (&key name env emit)
"Find the type of variable NAME in environment ENV and emit the type and name as a
concatenated string using EMIT. If the variable is not present in the environment,
emit 'auto'. If the type is an array, emit a string 'type name[dimension]'.
Parameters:
- NAME: The name of the variable.
- ENV: The environment in which to look up the variable.
- EMIT: A function used to emit the type and name as a string.
Returns:
A string representing the variable declaration."
(let* ((type (lookup-type name :env env)))
(cond ((null type)
(format nil "~a ~a"
*auto-keyword*
(funcall emit name)))
((and (listp type)
(eq 'array (first type)))
(progn
;; array
(destructuring-bind (array_ element-type &rest dims) type
(assert (eq array_ 'array))
(format nil "~a ~a~{[~a]~}"
(funcall emit element-type)
(funcall emit name)
(mapcar emit dims)))))
(t (format nil "~a ~a"
(if type
(funcall emit type)
*auto-keyword*)
(funcall emit name))))))
#+nil (if (listp type)
(if (null type)
(format nil "~a ~a"
#+generic-c "__auto_type"
#-generic-c "auto"
(funcall emit name))
(progn
;; array
(destructuring-bind (array_ element-type &rest dims) type
(assert (eq array_ 'array))
(format nil "~a ~a~{[~a]~}"
element-type
(funcall emit name)
(mapcar emit dims)))))
(format nil "~a ~a"
(if type
(funcall emit type)
#+generic-c "__auto_type"
#-generic-c "auto"
)
(funcall emit name)))
(defun parse-let (code emit &key const)
"Parse a Common Lisp LET form and emit similar C++ code.
This function takes a Common Lisp LET form and generates equivalent
C++ code. The LET form consists of variable declarations and an
optional DECLARE form. The DECLARE form can be used to declare types
for the variables. If types are not declared, the 'auto' keyword
will be used in C++.
Initial values for the variables are assigned using the C++ initializer list. For example, the input code '(let ((a (std--vector<int> (curly 1 2 3)))))' will generate the output 'auto a{std::vector<int>{1, 2, 3}};'.
The supported grammar for the LET form is as follows:
let ({var | (var [init-form])}*) declaration* form*
Parameters:
- code: The Common Lisp LET form to parse.
- emit: The function used to emit child forms below the LET form as C++ code.
- const: Write const in front of every definition (this is used in letc)
Returns:
The generated C++ code as a string."
(destructuring-bind (decls &rest body) (cdr code)
(multiple-value-bind (body env captures constructs const-p explicit-p inline-p static-p virtual-p noexcept-p final-p override-p pure-p template template-instance) (consume-declare body)
(with-output-to-string (s)
(format s "~a"
(funcall emit
`(do0
,@(loop for decl in decls collect
(if (listp decl) ;; split into name and initform
(destructuring-bind (name &optional value) decl
;; FIXME: introducing initializer lists is better for C++ but not working with GLSL (and possibly C)
(format nil ;"~a ~@[ = ~a~];"
"~a~a ~@[{~a}~];"
(if const "const " "")
(variable-declaration :name name :env env :emit emit)
(when value
(funcall emit value))))
(format nil "~a;"
(variable-declaration :name decl :env env :emit emit))))
,@body)))))))
(defun parse-defun (code emit &key header-only (class nil))
"Emit a C++ function definition or declaration from a Common Lisp DEFUN form.
Arguments:
- CODE: The DEFUN form to parse.
- EMIT: The function to emit the C++ code.
- HEADER-ONLY: If true, the function will be emitted as a declaration only.
- CLASS: The class name if the function is a member of a class.
Returns:
- The C++ function definition or declaration as a string.
Example:
(defun foo (a b)
(declare (values int) inline (type int a b))
(return (+ a b)))
will be emitted as 'inline int foo(int a, int b) { return a + b; }'
Supported grammar: defun function-name lambda-list [declaration*] form*"
(destructuring-bind (name lambda-list &rest body) (cdr code)
(multiple-value-bind (body env captures constructs const-p explicit-p inline-p static-p virtual-p noexcept-p final-p override-p pure-p template template-instance) (consume-declare body) ;; py
(multiple-value-bind (req-param opt-param res-param
key-param other-key-p
aux-param key-exist-p)
(parse-ordinary-lambda-list lambda-list)
(declare (ignorable req-param opt-param res-param
key-param other-key-p aux-param key-exist-p))
(with-output-to-string (s)
;; template static inline virtual ret params pure override header-only
;; explicit name const constructs
;; 1 2 3 4 5 6 7 8 9a 9b 9c 10 11
(format s "~%~@[template<~a> ~]~@[~a ~]~@[~a ~]~@[~a ~]~@[~a ~]~a ~a ~a ~@[~a~] ~:[~;=0~] ~:[~;noexcept~] ~:[~;final~] ~:[~;override~] ~:[~;;~] ~@[: ~a~]"
;; 1 template
(when template
template)
;; 2 static
(when (and static-p
header-only)
"static")
;; 3 explicit
(when (and explicit-p
header-only)
"explicit")
;; 4 inline
(when (and inline-p
header-only)
"inline")
;; 5 virtual
(when (and virtual-p
header-only
)
;(format t "virtual defun~%")
"virtual")
;; 6 return value
(let ((r (gethash 'return-values env)))
(if (< 1 (length r))
(break "multiple return values unsupported: ~a"
r)
(if (car r)
(case (car r)
(:constructor "") ;; (values :constructor) will not print anything
(t (car r)))
"void")))
;; 7 function-name, add class if not header
(if class
(if header-only
name
(format nil "~a::~a" class name))
name)
;; 8 positional parameters, followed by key parameters
(funcall emit `(paren
;; positional
,@(loop for p in req-param collect
(format nil "~a ~a"
(let ((type (gethash p env)))
(if type
(funcall emit type)
(break "can't find type for positional parameter ~a in defun"
p)))
p))
;; key parameters
;; http://www.crategus.com/books/alexandria/pages/alexandria.0.dev_fun_parse-ordinary-lambda-list.html
,@(loop for ((keyword-name name) init supplied-p) in key-param collect
(progn
#+nil (format t "~s~%" (list (loop for k being the hash-keys in env using (hash-value v) collect
(format nil "'~a'='~a'~%" k v)) :name name :keyword-name keyword-name :init init))
(format nil "~a ~a ~@[~a~]"
(let ((type (gethash name env)))
(if type
(funcall emit type)
(break "can't find type for keyword parameter ~a in defun"
name)))
name
(when header-only ;; only in class definition
(format nil "= ~a" (funcall emit init))))))
))
;; 9 const keyword / or '=0' for pure function
(when const-p #+nil
(and const-p
(not header-only))
"const")
nil ;; pure not applicable
noexcept-p
final-p
nil ;; override-p not applicable
;; 10 semicolon if header only
header-only
;; 11 constructor initializers
(when (and constructs
(not header-only))
(funcall emit `(comma ,@(mapcar emit constructs)))))
(unless header-only
(format s "~a~%" (funcall emit `(progn ,@body)))))))))
;; https://stackoverflow.com/questions/21577466/the-order-of-override-and-noexcept-in-the-standard
;; This states that override and final have to come after noexcept.
;; void f() final is the same as virtual f() final override
(defun parse-defmethod (code emit &key header-only (class nil) (in-class-p nil))
"Emit a C++ class member function definition or declaration from a
Common Lisp DEFMETHOD form.
This function takes a DEFMETHOD form in Common Lisp and
generates the corresponding C++ class member function
definition or declaration. The generated code can be emitted
using the provided EMIT function.
Arguments:
- CODE: The DEFMETHOD form to parse.
- EMIT: The function to emit the C++ code.
- HEADER-ONLY: If true, the function will be emitted as a declaration only.
- CLASS: The class name if the function is a member of a class.
- IN-CLASS-P: Selects if a declaration is emitted inside of a
class (e.g. in the header) or if a function definition is
written in an implementation .cpp file. In the latter case,
the class name is prepended to the function name.
Returns:
- The C++ function definition or declaration as a string.
Example:
(defclass+ A ()
\"public:\"
(defmethod foo (a b)
(declare (values int) (type int a b))
(return (+ a b))))
will be emitted as 'int A::foo(int a, int b) { return a + b; }'
Supported grammar: defmethod function-name lambda-list [declaration*] form*"
(destructuring-bind (name lambda-list &rest body) (cdr code)
(multiple-value-bind (body env captures constructs const-p explicit-p inline-p static-p virtual-p noexcept-p final-p override-p pure-p template template-instance) (consume-declare body) ;; py
(multiple-value-bind (req-param opt-param res-param
key-param other-key-p
aux-param key-exist-p)
(parse-ordinary-lambda-list lambda-list)
(declare (ignorable req-param opt-param res-param
key-param other-key-p aux-param key-exist-p))
(when (and (or inline-p
pure-p
)
(not header-only))
(return-from parse-defmethod ""))
#+nil
(when (and virtual-p
(not header-only))
(return-from parse-defmethod (format nil "// virtual method ~a" name)))
(with-output-to-string (s)
;; template static inline virtual ret params noexc,fina header-only
;; explicit name const pure override constructs
;; 1 2 3 4 5 6 7 8 9 9b 9c 10 11
; format s "~@[template<~a> ~]~@[~a ~]~@[~a ~]~@[~a ~]~@[~a ~]~a ~a ~a ~@[~a~] ~:[~;=0~] ~:[~;;~] ~@[: ~a~]"
(format s "~@[template<~a> ~]~@[~a ~]~@[~a ~]~@[~a ~]~@[~a ~]~a ~a ~a ~@[~a~] ~:[~;=0~] ~:[~;noexcept~] ~:[~;final~] ~:[~;override~] ~:[~;;~] ~@[: ~a~]"
;; 1 template
(when template
template)
;; 2 static
(when (and static-p
header-only)
"static")
;; 3 explicit
(when (and explicit-p
header-only)
"explicit")
;; 4 inline
(when (and inline-p
header-only)
"inline")
;; 5 virtual
(when (and virtual-p
(not (eq in-class-p 'defclass-cpp))
#+nil (or
;(eq in-class-p 'defclass+)
;(eq in-class-p 'defclass-hpp)
)
;(or in-class-p header-only)
)
;(format t "virtual defmethod~%")
"virtual")
;; 6 return value
(let ((r (gethash 'return-values env)))
(if (< 1 (length r))
(break "multiple return values unsupported: ~a"
r)
(if (car r)
(case (car r)
(:constructor "") ;; (values :constructor) will not print anything
(t (car r)))
"void")))
;; 7 function-name, add class if not header
(if class
(if header-only
name
(format nil "~a~@[< ~a >~]::~a" class template-instance name))
name)
;; positional parameters, followed by key parameters
(funcall emit `(paren
;; positional
,@(loop for p in req-param collect
(format nil "~a ~a"
(let ((type (gethash p env)))
(if type
(funcall emit type)
(break "can't find type for positional parameter ~a in defun"
p)))
p))
;; key parameters
;; http://www.crategus.com/books/alexandria/pages/alexandria.0.dev_fun_parse-ordinary-lambda-list.html
,@(loop for ((keyword-name name) init supplied-p) in key-param collect
(progn
#+nil (format t "~s~%" (list (loop for k being the hash-keys in env using (hash-value v) collect
(format nil "'~a'='~a'~%" k v)) :name name :keyword-name keyword-name :init init))
(format nil "~a ~a ~@[~a~]"
(let ((type (gethash name env)))
(if type
(funcall emit type)
(break "can't find type for keyword parameter ~a in defun"
name)))
name
(when header-only ;; only in class definition
(format nil "= ~a" (funcall emit init))))))
))
;; const keyword
(when const-p #+nil
(and const-p
(not header-only))
"const")
(when header-only pure-p)
noexcept-p
;(when header-only final-p)
(cond (header-only final-p)
((eq in-class-p 'defclass+)
final-p))
(cond (header-only override-p)
((eq in-class-p 'defclass+)
override-p))
;(when header-only override-p) ;; FIXME: not working in defclass+
;; semicolon if header only
(and (not inline-p) header-only)
;; constructor initializers
(when (and constructs
(not header-only))
(funcall emit `(comma ,@(mapcar emit (loop for (var init) in constructs
collect
`(space ,var (curly ,init))))))))
(when (or inline-p (not header-only))
(format s "~a" (funcall emit `(progn ,@body)))))))))
(defun parse-lambda (code emit)
"Parse a Common Lisp LAMBDA form and emit similar C++ code.
This function takes a Common Lisp LAMBDA form and generates
equivalent C++ code.
Arguments:
- code: The Common Lisp LAMBDA form to parse.
- emit: A function used to emit C++ code.
Returns:
A string containing the generated C++ code.
Supported Grammar:
lambda lambda-list [declaration*] form*
Example without return value:
[] (int a, float b) { body }
Example with return type declaration:
[] (int a, float b) -> float { body }
Support for captures:
Captures can be specified using the (declare (capture ...))
syntax. Captures are placed into the first set of brackets in the
generated C++ code.
Parameters:
- lambda-list: The lambda list of the Common Lisp LAMBDA form.
- body: The body of the Common Lisp LAMBDA form.
Returns:
A string containing the generated C++ code."
(destructuring-bind (lambda-list &rest body) (cdr code)
(multiple-value-bind (body env captures constructs const-p) (consume-declare body)
;; empty captures shall default to "&"
(when (null captures)
(setf captures `("&")))
(multiple-value-bind (req-param opt-param res-param
key-param other-key-p
aux-param key-exist-p)
(parse-ordinary-lambda-list lambda-list)
(declare (ignorable req-param opt-param res-param
key-param other-key-p aux-param key-exist-p))
(with-output-to-string (s)
(format s "[~{~a~^,~}] ~a~@[-> ~a ~]"
(mapcar emit captures)
(funcall emit `(paren
,@(loop for p in req-param collect
(format nil "~a ~a"
(let ((type (gethash p env)))
(if type
(funcall emit type)
(progn
;; (break "can't find type for ~a in defun" p)
"auto"
)))
p
))))
(let ((r (gethash 'return-values env)))
(if (< 1 (length r))
(funcall emit `(paren ,@r))
(car r))))
(format s "~a" (funcall emit `(progn ,@body))))))))
(defun print-sufficient-digits-f32 (f)
"Prints a single floating point number as a string with a given number
of digits. Parses it again and increases the number of digits until
the same bit pattern is obtained.
Args:
f: The floating point number to be printed.
Returns:
The string representation of the floating point number with sufficient digits."
(let* ((a f)
(digits 1)
(b (- a 1)))
(unless (= a 0)
(loop while (and (< 1e-6 (/ (abs (- a b))
(abs a)))
(< digits 30))
do
(setf b (read-from-string (format nil "~,v,,,,,'eG"
;"~,vG"
digits a
)))
(incf digits)))
;(format nil "~,vG" digits a)
;(format nil "~,v,,,,,'eGf" digits a)
(let ((str
(format nil "~,v,,,,,'eG" digits a)))
(format nil "~aF" (string-trim '(#\Space) str))
#+nil
(if (find #\e str)
str
(format nil "~af" (string-trim '(#\Space) str))))))
(defun print-sufficient-digits-f64 (f)
"Prints a double floating point number as a string with a given number
of digits.
Parses it again and increases the number of digits until the
same bit pattern of the 64-bit float is obtained.
Args:
- f: The double floating point number to be printed.
Returns:
- The string representation of the double floating point number with sufficient digits."
(let* ((a f)
(digits 1)
(b (- a 1)))
(unless (= a 0)
(loop while (and (< 1d-12
(/ (abs (- a b))
(abs a))
)
(< digits 30)) do
(setf b (read-from-string (format nil "~,vG" digits a)))
(incf digits)))
;(format t "~,v,,,,,'eG~%" digits a)
(format nil "~,v,,,,,'eG" digits a)
;(substitute #\e #\d (format nil "~,vG" digits a))
))
(defparameter *operators*
`(comma semicolon space space-n comments paren* paren angle bracket curly designated-initializer new indent split-header-and-code do0 pragma include include<> progn namespace do defclass+ defclass protected public defmethod defun defun* defun+ return co_return co_await co_yield throw cast let setf not bitwise-not deref ref + - * ^ xor & / or and logior logand = /= *= ^= <= < != == % << >> incf decf string string-r string-u8 char hex ? if when unless dot aref -> lambda case for for-range dotimes foreach while deftype struct defstruct0 handler-case)
"This variable stores a list of operators that are supported by the EMIT-C function.
It is used in the PAREN* form to determine whether parentheses are needed.")
;; https://en.cppreference.com/w/cpp/language/operator_precedence
;; FIXME: how to handle Associativity (right-to-left or
;; left-to-right). do i need a table or is this implicitly handled in
;; emit-c for each symbol itself?
#+nil
(defparameter *precedence* `(#+nil
("::")
(hex)
(char)
(string)
((paren) l) ;; ?? does that go here
(( ; incf decf (only with a++ a--)
;; unary+ unary-
aref ; call cast
-> dot
) l)
; ((prefix++ prefix--) r)
(-unary
not bitwise-not
cast ref
deref
sizeof
co_await
new
new[]
delete
delete[]
)
#+nil (.* ->*)
(* / %)
(+ -)
(<< >>)
(<=>)
(< <= > >=)
;; 10
(== !=)
;; 11
(and &)
(xor ^)
(or )
(logand &&)
;; 15
(logior )
;; 16
(? )
(throw )
(co_yield)
(setf =)
(incf decf)
(*= /= %=)
(<<= >>=)
(&= ^- ; |=
)
(comma )
))
(defparameter *precedence* `((:op (scope))
(:op (hex))
(:op (char))
(:op (string))
(:op (paren
paren*
curly
aref dot ->) :assoc l)
(:op (-unary
not bitwise-not
cast
deref
ref
sizeof
co_await
new
new[]
delete
delete[]
)
:assoc r)
#+nil (.* ->*) ;; pointer to member
(:op (* / %) :assoc l)
(:op (+ -) :assoc l)
(:op (<< >>) :assoc l)
(:op (<=>) :assoc l)
(:op (< <= > >=) :assoc l)
;; 10
(:op (== !=) :assoc l)
;; 11
(:op (and &) :assoc l)
(:op (xor ^) :assoc l)
(:op (or) :assoc l)
(:op (logand &&) :assoc l) ;; FIXME: I'm never sure if logand should be && or &. I think it currently is wrong. But I don't want to touch it because that would break existing code.
;; 15
(:op (logior) :assoc l)
;; 16
(:op (? throw co_yield setf =
incf decf
*= /= %=
<<= >>=
&= ^- ; |=
) :assoc r)
(:op (comma) :assoc l)
)
"This variable contains the C++ operator precedence table.
It is used in the PAREN* form to determine whether placing parentheses is necessary.")
(defun lookup-precedence (operator )
"This function looks up the precedence of an operator in the precedence table."
(loop for e in *precedence*
and e-i from 0
do
(destructuring-bind (&key op assoc) e
(when (member operator op)
(return e-i)))))
(defun lookup-associativity (operator )
"This function looks up the associativity of an operator in the precedence table."
(loop for e in *precedence*
do
(destructuring-bind (&key op (assoc 'l)) e
(when (member operator op)
(return assoc)))))
;; The `string-op` class is used in the `emit-c` function for the
;; implementation of the PAREN* form to expand branches of the
;; abstract syntax tree into strings. The `string-op` class
;; represents a string that also remembers the most recent operator
;; used. This operator can be used for lookup and precedence
;; comparison with the next operator.
(defclass string-op ()
((string :accessor string-of
:initarg :string
:initform (error "Must supply a string."))
(operator :accessor operator-of
:initarg :operator
:initform (error "Must supply an operator."))))
(defmethod print-object ((object string-op) stream)
"Prints the string representation of STRING-OP object to a stream."
(format stream "~a" (string-of object)))
(defun m (op str)
"Create a STRING-OP object.
This function creates an instance of the STRING-OP class with
the given operator and string values. The purpose of this
function is to conveniently create multiple instances of
STRING-OP objects with a concise function name.
Parameters:
- op: The operator value for the STRING-OP object.
- str: The string value for the STRING-OP object.
Returns:
A new instance of the STRING-OP class."
(make-instance 'string-op
:string str
:operator op))
(defun m-of (obj-or-string)
"This function is a shortcut to convert all types that can occur inside
emit-c into a string. Except lists: Those stay lists."
(typecase obj-or-string
(string-op
(string-of obj-or-string))
(string
obj-or-string)
(cons
obj-or-string)
(symbol
(format nil "~a" obj-or-string))
(t
(break "variable '~a' of unknown type '~a'" obj-or-string (type-of obj-or-string)))))
(progn
(defun emit-c (&key code (str nil) (level 0) (hook-defun nil) (hook-defclass)
(current-class nil) (header-only nil) (in-class nil) (diag nil)
(omit-redundant-parentheses nil))
"Evaluates s-expressions in CODE and emits a string or STRING-OP class.
If HOOK-DEFUN is not nil, it calls hook-defun with every function definition.
This functionality is intended to collect function declarations.
When omit-redundant-parentheses is not nil, the feature to avoid redundant parentheses is active.
Args:
- code: The code as s-expressions to emit as C++.
- str: A string to write the result into.
- level: The indentation level.
- hook-defun: The function to call with every function definition.
- hook-defclass: The function to call with every class definition.
- current-class: The current class.
- header-only: A flag indicating whether to emit only the header. This flag can is used to emit only function declarations.
- in-class: A flag indicating whether we are currently inside a class. This flag is used to emit method declarations or implementations.
- diag: If true, write diagnostic information as log output.
- omit-redundant-parentheses: A flag indicating whether to avoid redundant parentheses.
Returns: