-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.scm
1504 lines (1198 loc) · 40.2 KB
/
utils.scm
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
; Generic Utilities.
; Copyright (C) 2000, 2005, 2006, 2007, 2009, 2010 Red Hat, Inc.
; This file is part of CGEN.
; See file COPYING.CGEN for details.
; These utilities are neither object nor cgen centric.
; They're generic, non application-specific utilities.
; There are a few exceptions, keep them to a minimum.
;
; Conventions:
; - the prefix "gen-" comes from cgen's convention that procs that return C
; code, and only those procs, are prefixed with "gen-"
(define nil '())
; Hobbit support code; for when not using hobbit.
; FIXME: eliminate this stuff ASAP.
(defmacro /fastcall-make (proc) proc)
(defmacro fastcall4 (proc arg1 arg2 arg3 arg4)
(list proc arg1 arg2 arg3 arg4)
)
(defmacro fastcall5 (proc arg1 arg2 arg3 arg4 arg5)
(list proc arg1 arg2 arg3 arg4 arg5)
)
(defmacro fastcall6 (proc arg1 arg2 arg3 arg4 arg5 arg6)
(list proc arg1 arg2 arg3 arg4 arg5 arg6)
)
(defmacro fastcall7 (proc arg1 arg2 arg3 arg4 arg5 arg6 arg7)
(list proc arg1 arg2 arg3 arg4 arg5 arg6 arg7)
)
; Value doesn't matter too much here, just ensure it's portable.
(define *UNSPECIFIED* (if #f 1))
(define assert-fail-msg "assertion failure:")
(defmacro assert (expr)
`(if (not ,expr)
(error assert-fail-msg ',expr))
)
(define verbose-level 0)
(define (verbose-inc!)
(set! verbose-level (+ verbose-level 1))
)
(define (verbose? level) (>= verbose-level level))
; Print to stderr, takes an arbitrary number of objects, possibly nested.
; ??? Audit callers, can we maybe just use "display" here (except that
; we still might want some control over the output).
(define message
(lambda args
(for-each (lambda (str)
(if (pair? str)
(if (list? str)
;; ??? Incorrect for improper lists, later.
(begin
(message "(")
(for-each (lambda (s) (message s " ")) str)
(message ")"))
(message "(" (car str) " . " (cdr str) ")"))
(display str (current-error-port))))
args))
)
; Print a message if the verbosity level calls for it.
; This is a macro as a bit of cpu may be spent computing args,
; and we only want to spend it if the result will be printed.
(defmacro logit (level . args)
`(if (>= verbose-level ,level) (message ,@args))
)
; Return a string of N spaces.
(define (spaces n) (make-string n #\space))
; Write N spaces to PORT, or the current output port if elided.
(define (write-spaces n . port)
(let ((port (if (null? port) (current-output-port) (car port))))
(write (spaces n) port))
)
; Concatenate all the arguments and make a string. Symbols are
; converted to strings.
(define (string/symbol-append . sequences)
(define (sequence->string o) (if (symbol? o) (symbol->string o) o))
(apply string-append (map sequence->string sequences)))
; Often used idiom.
(define (string-map fn . args) (apply string-append (apply map (cons fn args))))
; Collect a flat list of returned sublists from the lambda fn applied over args.
(define (collect fn . args) (apply append (apply map (cons fn args))))
; Map over value entries in an alist.
; 'twould be nice if this were a primitive.
(define (amap fn args)
(map fn (map cdr args))
)
; Like map but accept a proper or improper list.
; An improper list is (a b c . d).
; FN must be a proc of one argument.
(define (map1-improper fn l)
(let ((result nil))
(let loop ((last #f) (l l))
(cond ((null? l)
result)
((pair? l)
(if last
(begin
(set-cdr! last (cons (fn (car l)) nil))
(loop (cdr last) (cdr l)))
(begin
(set! result (cons (fn (car l)) nil))
(loop result (cdr l)))))
(else
(if last
(begin
(set-cdr! last (fn l))
result)
(fn l))))))
)
; Turn string or symbol STR into a proper C symbol.
; The result is a string.
; We assume STR has no leading digits.
; All invalid characters are turned into '_'.
; FIXME: Turn trailing "?" into "_p".
(define (gen-c-symbol str)
(if (not (or (string? str) (symbol? str)))
(error "gen-c-symbol: not symbol or string:" str))
(map-over-string (lambda (c) (if (id-char? c) c #\_))
(->string str))
)
; Turn string or symbol STR into a proper file name, which is
; defined to be the same as gen-c-symbol except use -'s instead of _'s.
; The result is a string.
(define (gen-file-name str)
(if (not (or (string? str) (symbol? str)))
(error "gen-file-name: not symbol or string:" str))
(map-over-string (lambda (c) (if (id-char? c) c #\-))
(->string str))
)
; Turn STR into lowercase.
(define (string-downcase str)
(map-over-string (lambda (c) (char-downcase c)) str)
)
; Turn STR into uppercase.
(define (string-upcase str)
(map-over-string (lambda (c) (char-upcase c)) str)
)
; Turn SYM into lowercase.
(define (symbol-downcase sym)
(string->symbol (string-downcase (symbol->string sym)))
)
; Turn SYM into uppercase.
(define (symbol-upcase sym)
(string->symbol (string-upcase (symbol->string sym)))
)
; Symbol sorter.
(define (symbol<? a b)
(string<? (symbol->string a) (symbol->string b))
)
; Drop N chars from string S.
; If N is negative, drop chars from the end.
; It is ok to drop more characters than are in the string, the result is "".
(define (string-drop n s)
(cond ((>= n (string-length s)) "")
((< n 0) (substring s 0 (+ (string-length s) n)))
(else (substring s n (string-length s))))
)
; Drop the leading char from string S (assumed to have at least 1 char).
(define (string-drop1 s)
(string-drop 1 s)
)
; Return the leading N chars from string STR.
; This has APL semantics:
; N > length: FILLER chars are appended
; N < 0: take from the end of the string and prepend FILLER if necessary
(define (string-take-with-filler n str filler)
(let ((len (string-length str)))
(if (< n 0)
(let ((n (- n)))
(string-append (if (> n len)
(make-string (- n len) filler)
"")
(substring str (max 0 (- len n)) len)))
(string-append (substring str 0 (min len n))
(if (> n len)
(make-string (- n len) filler)
""))))
)
(define (string-take n str)
(string-take-with-filler n str #\space)
)
; Return the leading char from string S (assumed to have at least 1 char).
(define (string-take1 s)
(substring s 0 1)
)
; Return the index of char C in string S or #f if not found.
(define (string-index s c)
(let loop ((i 0))
(cond ((= i (string-length s)) #f)
((char=? c (string-ref s i)) i)
(else (loop (1+ i)))))
)
; Cut string S into a list of strings using delimiter DELIM (a character).
(define (string-cut s delim)
(let loop ((start 0)
(end 0)
(length (string-length s))
(result nil))
(cond ((= end length)
(if (> end start)
(reverse! (cons (substring s start end) result))
(reverse! result)))
((char=? (string-ref s end) delim)
(loop (1+ end) (1+ end) length (cons (substring s start end) result)))
(else (loop start (1+ end) length result))))
)
; Convert a list of elements to a string, inserting DELIM (a string)
; between elements.
; L can also be a string or a number.
(define (stringize l delim)
(cond ((string? l) l)
((number? l) (number->string l))
((symbol? l) (symbol->string l))
((list? l)
(string-drop
(string-length delim)
(string-map (lambda (elm)
(string-append delim
(stringize elm delim)))
l)))
(else (error "stringize: can't handle:" l)))
)
; Same as string-append, but accepts symbols too.
; PERF: This implementation may be unacceptably slow. Revisit.
(define stringsym-append
(lambda args
(apply string-append
(map (lambda (s)
(if (symbol? s)
(symbol->string s)
s))
args)))
)
; Same as symbol-append, but accepts strings too.
(define symbolstr-append
(lambda args
(string->symbol (apply stringsym-append args)))
)
; Given a symbol or a string, return the string form.
(define (->string s)
(if (symbol? s)
(symbol->string s)
s)
)
; Given a symbol or a string, return the symbol form.
(define (->symbol s)
(if (string? s)
(string->symbol s)
s)
)
; Output routines.
;; Given some state that has a setter function (SETTER NEW-VALUE) and
;; a getter function (GETTER), call THUNK with the state set to VALUE,
;; and restore the original value when THUNK returns. Ensure that the
;; original value is restored whether THUNK returns normally, throws
;; an exception, or invokes a continuation that leaves the call's
;; dynamic scope.
(define (setter-getter-fluid-let setter getter value thunk)
(let ((swap (lambda ()
(let ((temp (getter)))
(setter value)
(set! value temp)))))
(dynamic-wind swap thunk swap)))
;; Call THUNK with the current input and output ports set to PORT, and
;; then restore the current ports to their original values.
;;
;; This ensures the current ports get restored whether THUNK exits
;; normally, throws an exception, or leaves the call's dynamic scope
;; by applying a continuation.
(define (with-input-and-output-to port thunk)
(setter-getter-fluid-let
set-current-input-port current-input-port port
(lambda ()
(setter-getter-fluid-let
set-current-output-port current-output-port port
thunk))))
; Extension to the current-output-port.
; Only valid inside string-write.
(define /current-print-state #f)
; Create a print-state object.
; This is written in portable Scheme so we don't use COS objects, etc.
(define (make-print-state)
(vector 'print-state 0)
)
; print-state accessors.
(define (pstate-indent pstate) (vector-ref pstate 1))
(define (pstate-set-indent! pstate indent) (vector-set! pstate 1 indent))
; Special print commands (embedded in args).
(define (pstate-cmd? x) (and (vector? x) (eq? (vector-ref x 0) 'pstate)))
;(define /endl (vector 'pstate '/endl)) ; ??? needed?
(define /indent (vector 'pstate '/indent))
(define (/indent-set n) (vector 'pstate '/indent-set n))
(define (/indent-add n) (vector 'pstate '/indent-add n))
; Process a pstate command.
(define (pstate-cmd-do pstate cmd)
(assert (pstate-cmd? cmd))
(case (vector-ref cmd 1)
((/endl)
"\n")
((/indent)
(let ((indent (pstate-indent pstate)))
(string-append (make-string (quotient indent 8) #\tab)
(make-string (remainder indent 8) #\space))))
((/indent-set)
(pstate-set-indent! pstate (vector-ref cmd 2))
"")
((/indent-add)
(pstate-set-indent! pstate (+ (pstate-indent pstate)
(vector-ref cmd 2)))
"")
(else
(error "unknown pstate command" (vector-ref cmd 1))))
)
; Write STRINGS to current-output-port.
; STRINGS is a list of things to write. Supported types are strings, symbols,
; lists, procedures. Lists are printed by applying string-write recursively.
; Procedures are thunks that return the string to write.
;
; The result is the empty string. This is for debugging where this
; procedure is modified to return its args, rather than write them out.
(define string-write
(lambda strings
(let ((pstate (make-print-state)))
(set! /current-print-state pstate)
(for-each (lambda (elm) (/string-write pstate elm))
strings)
(set! /current-print-state #f)
""))
)
; Subroutine of string-write and string-write-map.
(define (/string-write pstate expr)
(cond ((string? expr) (display expr)) ; not write, we want raw text
((symbol? expr) (display expr))
((procedure? expr) (/string-write pstate (expr)))
((pstate-cmd? expr) (display (pstate-cmd-do pstate expr)))
((list? expr) (for-each (lambda (x) (/string-write pstate x)) expr))
(else (error "string-write: bad arg:" expr)))
*UNSPECIFIED*
)
; Combination of string-map and string-write.
(define (string-write-map proc arglist)
(let ((pstate /current-print-state))
(for-each (lambda (arg) (/string-write pstate (proc arg)))
arglist))
""
)
; Build up an argument for string-write.
(define string-list list)
(define string-list-map map)
; Subroutine of string-list->string. Does same thing /string-write does.
(define (/string-list-flatten pstate strlist)
(cond ((string? strlist) strlist)
((symbol? strlist) strlist)
((procedure? strlist) (/string-list-flatten pstate (strlist)))
((pstate-cmd? strlist) (pstate-cmd-do pstate strlist))
((list? strlist) (apply string-append
(map (lambda (str)
(/string-list-flatten pstate str))
strlist)))
(else (error "string-list->string: bad arg:" strlist)))
)
; Flatten out a string list.
(define (string-list->string strlist)
(/string-list-flatten (make-print-state) strlist)
)
; Prefix CHARS, a string of characters, with backslash in STR.
; STR is either a string or list of strings (to any depth).
; ??? Quick-n-dirty implementation.
(define (backslash chars str)
(if (string? str)
; quick check for any work to do
(if (any-true? (map (lambda (c)
(string-index str c))
(string->list chars)))
(let loop ((result "") (str str))
(if (= (string-length str) 0)
result
(loop (string-append result
(if (string-index chars (string-ref str 0))
"\\"
"")
(substring str 0 1))
(substring str 1 (string-length str)))))
str)
; must be a list
(if (null? str)
nil
(cons (backslash chars (car str))
(backslash chars (cdr str)))))
)
; Return a boolean indicating if S is bound to a value.
;(define old-symbol-bound? symbol-bound?)
;(define (symbol-bound? s) (old-symbol-bound? #f s))
; Return a boolean indicating if S is a symbol and is bound to a value.
(define (bound-symbol? s)
(and (symbol? s)
(or (symbol-bound? #f s)
;(module-bound? cgen-module s)
))
)
; Return X.
(define (identity x) x)
; Test whether X is a `form' (non-empty list).
; ??? Is `form' the right word to use here?
; One can argue we should also test for a valid car. If so, it's the
; name that's wrong not the code (because the code is what I want).
(define (form? x) (and (not (null? x)) (list? x)))
; Return the number of arguments to ARG-SPEC, a valid argument list
; of `lambda'.
; The result is a pair: number of fixed arguments, varargs indicator (#f/#t).
(define (num-args arg-spec)
(if (symbol? arg-spec)
'(0 . #t)
(let loop ((count 0) (arg-spec arg-spec))
(cond ((null? arg-spec) (cons count #f))
((null? (cdr arg-spec)) (cons (+ count 1) #f))
((pair? (cdr arg-spec)) (loop (+ count 1) (cdr arg-spec)))
(else (cons (+ count 1) #t)))))
)
; Return a boolean indicating if N args is ok to pass to a proc with
; an argument specification of ARG-SPEC (a valid argument list of `lambda').
(define (num-args-ok? n arg-spec)
(let ((processed-spec (num-args arg-spec)))
(and
; Ensure enough fixed arguments.
(>= n (car processed-spec))
; If more args than fixed args, ensure varargs.
(or (= n (car processed-spec))
(cdr processed-spec))))
)
; Take N elements from list L.
; If N is negative, take elements from the end.
; If N is larger than the length, the extra elements are NIL.
; FIXME: incomplete
; FIXME: list-tail has args reversed (we should conform)
(define (list-take n l)
(let ((len (length l)))
(if (< n 0)
(list-tail l (+ len n))
(let loop ((result nil) (l l) (i 0))
(if (= i n)
(reverse! result)
(loop (cons (car l) result) (cdr l) (+ i 1))))))
)
; Drop N elements from list L.
; FIXME: list-tail has args reversed (we should conform)
(define (list-drop n l)
(let loop ((n n) (l l))
(if (> n 0)
(loop (- n 1) (cdr l))
l))
)
; Drop N elements from the end of L.
; FIXME: list-tail has args reversed (we should conform)
(define (list-tail-drop n l)
(reverse! (list-drop n (reverse l)))
)
;; left fold
(define (foldl kons accum lis)
(if (null? lis) accum
(foldl kons (kons accum (car lis)) (cdr lis))))
;; right fold
(define (foldr kons knil lis)
(if (null? lis) knil
(kons (car lis) (foldr kons knil (cdr lis)))))
;; filter list on predicate
(define (filter p ls)
(foldr (lambda (x a) (if (p x) (cons x a) a))
'() ls))
; APL's +\ operation on a vector of numbers.
(define (plus-scan l)
(letrec ((-plus-scan (lambda (l result)
(if (null? l)
result
(-plus-scan (cdr l)
(cons (if (null? result)
(car l)
(+ (car l) (car result)))
result))))))
(reverse! (-plus-scan l nil)))
)
; Remove duplicate elements from sorted list L.
; Currently supported elements are symbols (a b c) and lists ((a) (b) (c)).
; NOTE: Uses equal? for comparisons.
(define (remove-duplicates l)
(let loop ((l l) (result nil))
(cond ((null? l) (reverse! result))
((null? result) (loop (cdr l) (cons (car l) result)))
((equal? (car l) (car result)) (loop (cdr l) result))
(else (loop (cdr l) (cons (car l) result)))
)
)
)
; Return a boolean indicating if each element of list satisfies its
; corresponding predicates. The length of L must be equal to the length
; of PREDS.
(define (list-elements-ok? l preds)
(and (list? l)
(= (length l) (length preds))
(all-true? (map (lambda (pred elm) (pred elm)) preds l)))
)
; Remove duplicates from unsorted list L.
; KEY-GENERATOR is a lambda that takes a list element as input and returns
; an equal? key to use to determine duplicates.
; The first instance in a set of duplicates is always used.
; This is not intended to be applied to large lists with an expected large
; result (where sorting the list first would be faster), though one could
; add such support later.
;
; ??? Rename to follow memq/memv/member naming convention.
(define (nub l key-generator)
(let loop ((l l) (keys (map key-generator l)) (result nil))
(if (null? l)
(reverse! (map cdr result))
(if (assv (car keys) result)
(loop (cdr l) (cdr keys) result)
(loop (cdr l) (cdr keys) (acons (car keys) (car l)
result)))))
)
; Return a boolean indicating if list L1 is a subset of L2.
; Uses memq.
(define (subset? l1 l2)
(let loop ((l1 l1))
(if (null? l1)
#t
(if (memq (car l1) l2)
(loop (cdr l1))
#f)))
)
; Return intersection of two lists.
(define (intersection a b)
(foldl (lambda (l e) (if (memq e a) (cons e l) l)) '() b))
; Return #t if the intersection of A and B is non-null.
(define (non-null-intersection? a b)
(let loop ((todo a))
(cond ((null? todo)
#f)
((memq (car todo) b)
#t)
(else
(loop (cdr todo)))))
)
; Return union of two lists.
(define (union a b)
(foldl (lambda (l e) (if (memq e l) l (cons e l))) a b))
; Return a count of the number of elements of list L1 that are in list L2.
; Uses memq.
(define (count-common l1 l2)
(let loop ((result 0) (l1 l1))
(if (null? l1)
result
(if (memq (car l1) l2)
(loop (+ result 1) (cdr l1))
(loop result (cdr l1)))))
)
; Remove duplicate elements from sorted alist L.
; L must be sorted by name.
(define (alist-nub l)
(let loop ((l l) (result nil))
(cond ((null? l) (reverse! result))
((null? result) (loop (cdr l) (cons (car l) result)))
((eq? (caar l) (caar result)) (loop (cdr l) result))
(else (loop (cdr l) (cons (car l) result)))
)
)
)
; Return a copy of alist L.
(define (alist-copy l)
; (map cons (map car l) (map cdr l)) ; simple way
; presumably more efficient way (less cons cells created)
(map (lambda (elm)
(cons (car elm) (cdr elm)))
l)
)
; Return the order in which to select elements of L sorted by SORT-FN.
; The result is origin 0.
(define (sort-grade l sort-fn)
(let ((sorted (sort (map cons (iota (length l)) l)
(lambda (a b) (sort-fn (cdr a) (cdr b))))))
(map car sorted))
)
; Return ALIST sorted on the name in ascending order.
(define (alist-sort alist)
(sort alist
(lambda (a b)
(string<? (symbol->string (car a))
(symbol->string (car b)))))
)
; Return a boolean indicating if C is a leading id char.
; '@' is treated as an id-char as it's used to delimit something that
; sed will alter.
(define (leading-id-char? c)
(or (char-alphabetic? c)
(char=? c #\_)
(char=? c #\@))
)
; Return a boolean indicating if C is an id char.
; '@' is treated as an id-char as it's used to delimit something that
; sed will alter.
(define (id-char? c)
(or (leading-id-char? c)
(char-numeric? c))
)
; Return the length of the identifier that begins S.
; Identifiers are any of letter, digit, _, @.
; The first character must not be a digit.
; ??? The convention is to use "-" between cgen symbols, not "_".
; Try to handle "-" here as well.
(define (id-len s)
(if (leading-id-char? (string-ref s 0))
(let ((len (string-length s)))
(let loop ((n 0))
(if (and (< n len)
(id-char? (string-ref s n)))
(loop (1+ n))
n)))
0)
)
; Return number of characters in STRING until DELIMITER.
; Returns #f if DELIMITER not present.
; FIXME: Doesn't yet support \-prefixed delimiter (doesn't terminate scan).
(define (chars-until-delimiter string delimiter)
(let loop ((str string) (result 0))
(cond ((= (string-length str) 0)
#f)
((char=? (string-ref str 0) delimiter)
result)
(else (loop (string-drop1 str) (1+ result)))))
)
; Apply FN to each char of STR.
(define (map-over-string fn str)
(do ((tmp (string-copy (if (symbol? str) (symbol->string str) str)))
(i (- (string-length str) 1) (- i 1)))
((< i 0) tmp)
(string-set! tmp i (fn (string-ref tmp i)))
)
)
; Return a range.
; It must be distinguishable from a list of numbers.
(define (minmax min max) (cons min max))
; Move VALUE of LENGTH bits to position START in a word of SIZE bits.
; LSB0? is non-#f if bit numbering goes LSB->MSB.
; Otherwise it goes MSB->LSB.
; START-LSB? is non-#f if START denotes the least significant bit.
; Otherwise START denotes the most significant bit.
; N is assumed to fit in the field.
(define (word-value start length size lsb0? start-lsb? value)
(if lsb0?
(if start-lsb?
(logsll value start)
(logsll value (+ (- start length) 1)))
(if start-lsb?
(logsll value (- size start 1))
(logsll value (- size (+ start length)))))
)
; Return a bit mask of LENGTH bits in a word of SIZE bits starting at START.
; LSB0? is non-#f if bit numbering goes LSB->MSB.
; Otherwise it goes MSB->LSB.
; START-LSB? is non-#f if START denotes the least significant bit.
; Otherwise START denotes the most significant bit.
(define (word-mask start length size lsb0? start-lsb?)
(if lsb0?
(if start-lsb?
(logsll (mask length) start)
(logsll (mask length) (+ (- start length) 1)))
(if start-lsb?
(logsll (mask length) (- size start 1))
(logsll (mask length) (- size (+ start length)))))
)
; Extract LENGTH bits at bit number START in a word of SIZE bits from VALUE.
; LSB0? is non-#f if bit numbering goes LSB->MSB.
; Otherwise it goes MSB->LSB.
; START-LSB? is non-#f if START denotes the least significant bit.
; Otherwise START denotes the most significant bit.
;
; ??? bit-extract takes a big-number argument but still uses logand
; which doesn't so we don't use it
(define (word-extract start length size lsb0? start-lsb? value)
(if lsb0?
(if start-lsb?
(remainder (logslr value start) (integer-expt 2 length))
(remainder (logslr value (+ (- start length) 1)) (integer-expt 2 length)))
(if start-lsb?
(remainder (logslr value (- size start 1)) (integer-expt 2 length))
(remainder (logslr value (- size (+ start length))) (integer-expt 2 length))))
)
; Return numeric value of bit N in a word of size WORD-BITSIZE.
(define (word-bit-value bitnum word-bitsize lsb0?)
(assert (< bitnum word-bitsize))
(if lsb0?
(ash 1 bitnum)
(ash 1 (- word-bitsize bitnum 1)))
)
; Return a bit mask of size SIZE beginning at the LSB.
(define (mask size)
(- (logsll 1 size) 1)
)
; Split VAL into pieces of bit size LENGTHS.
; e.g. (split-bits '(8 2) 997) -> (229 3)
; There are as many elements in the result as there are in LENGTHS.
; Note that this can result in a loss of information.
(define (split-bits lengths val)
(letrec ((split1
(lambda (lengths val result)
(if (null? lengths)
result
(split1 (cdr lengths)
(quotient val (integer-expt 2 (car lengths)))
(cons (remainder val (integer-expt 2 (car lengths)))
result))))))
(reverse! (split1 lengths val nil)))
)
; Generalized version of split-bits.
; e.g. (split-value '(10 10 10) 1234) -> (4 3 2 1) ; ??? -> (1 2 3 4) ?
; (split-value '(10 10) 1234) -> (4 3)
; There are as many elements in the result as there are in BASES.
; Note that this can result in a loss of information.
(define (split-value bases val)
(letrec ((split1
(lambda (bases val result)
(if (null? bases)
result
(split1 (cdr bases)
(quotient val (car bases))
(cons (remainder val (car bases))
result))))))
(reverse! (split1 bases val nil)))
)
; Convert bits to bytes.
(define (bits->bytes bits) (quotient (+ 7 bits) 8))
; Convert bytes to bits.
(define (bytes->bits bytes) (* bytes 8))
; Return a list of integers.
; Usage:
; (.iota count) ; start=0, incr=1
; (.iota count start) ; incr=1
; (.iota count start incr)
(define (iota count . start-incr)
(if (> (length start-incr) 2)
(error "iota: wrong number of arguments:" start-incr))
(if (< count 0)
(error "iota: count must be non-negative:" n))
(let ((start (if (pair? start-incr) (car start-incr) 0))
(incr (if (= (length start-incr) 2) (cadr start-incr) 1)))
(let loop ((i start) (count count) (result '()))
(if (= count 0)
(reverse! result)
(loop (+ i incr) (- count 1) (cons i result)))))
)
; Return a list of the first N powers of 2.
(define (powers-of-2 n)
(cond ((= n 0) nil)
(else (cons (integer-expt 2 (1- n)) (powers-of-2 (1- n))))
)
; Another way: (map (lambda (n) (ash 1 n)) (iota n))
)
; I'm tired of writing (not (= foo bar)).
(define (!= a b) (not (= a b)))
; Return #t if BIT-NUM (which is starting from LSB), is set in the binary
; representation of non-negative integer N.
(define (bit-set? n bit-num)
; ??? Quick hack to work around missing bignum support.
;(= 1 (cg-logand (logslr n bit-num) 1))
(if (>= n #x20000000)
(if (>= bit-num 16)
(logbit? (- bit-num 16) (logslr n 16))
(logbit? bit-num (remainder n 65536)))
(logbit? bit-num n))
)
; Return #t if each element of bools is #t. Since Scheme considers any
; non-#f value as #t we do too.
; (all-true? '()) is #t since that is the identity element.
(define (all-true? bools)
(cond ((null? bools) #t)
((car bools) (all-true? (cdr bools)))
(else #f))
)
; Return #t if any element of BOOLS is #t.
; If BOOLS is empty, return #f.
(define (any-true? bools)
(cond ((null? bools) #f)
((car bools) #t)
(else (any-true? (cdr bools))))
)
; Return count of true values.
(define (count-true flags)
(let loop ((result 0) (flags flags))
(if (null? flags)
result
(loop (+ result (if (car flags) 1 0))
(cdr flags))))
)
; Return count of all ones in BITS.
(define (count-bits bits)
(let loop ((result 0) (bits bits))
(if (= bits 0)
result
(loop (+ result (remainder bits 2)) (quotient bits 2))))
)
; Convert bits in N #f/#t.
; LENGTH is the length of N in bits.
(define (bits->bools n length)
(do ((result (make-list length #f))
(i 0 (+ i 1)))
((= i length) (reverse! result))
(list-set! result i (if (bit-set? n i) #t #f))