blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
171
content_id
stringlengths
40
40
detected_licenses
listlengths
0
8
license_type
stringclasses
2 values
repo_name
stringlengths
6
82
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
13 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
1.59k
594M
star_events_count
int64
0
77.1k
fork_events_count
int64
0
33.7k
gha_license_id
stringclasses
12 values
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_language
stringclasses
46 values
src_encoding
stringclasses
14 values
language
stringclasses
2 values
is_vendor
bool
2 classes
is_generated
bool
1 class
length_bytes
int64
4
7.87M
extension
stringclasses
101 values
filename
stringlengths
2
149
content
stringlengths
4
7.87M
has_macro_def
bool
2 classes
578d776b00067f807d89f9be3cc19f5ed7a7e979
5355071004ad420028a218457c14cb8f7aa52fe4
/1.2/e-1.20.scm
046304aa23839deb0cec95bac2bd2d01cb918919
[]
no_license
ivanjovanovic/sicp
edc8f114f9269a13298a76a544219d0188e3ad43
2694f5666c6a47300dadece631a9a21e6bc57496
refs/heads/master
2022-02-13T22:38:38.595205
2022-02-11T22:11:18
2022-02-11T22:11:18
2,471,121
376
90
null
2022-02-11T22:11:19
2011-09-27T22:11:25
Scheme
UTF-8
Scheme
false
false
3,967
scm
e-1.20.scm
; TODO: Check if solution to this is correct. When printing from the ; remainder procedure it reports as it was called only 4 times in ; both ways of application. ; ; Exercise 1.20. ; ; The process that a procedure generates is of course dependent on the rules used by the interpreter. ; As an example, consider the iterative gcd procedure given below. ; Suppose we were to interpret this procedure using normal-order evaluation, ; as discussed in section 1.1.5. (The normal-order-evaluation rule for if is described in exercise 1.5.). ; Using the substitution method (for normal order), illustrate the process generated in evaluating (gcd 206 40) ; and indicate the remainder operations that are actually performed. ; How many remainder operations are actually performed in the normal-order evaluation of (gcd 206 40)? In the applicative-order evaluation? ; ; Iterative procedure for calculating GCD of two numbers ; ; moved to common for reuse by other parts ; ; (define (gcd a b) ; (if (= b 0) ; a ; (gcd b (remainder a b)))) (load "../common.scm") ;---------------------------------------------- ; ; Normal order evaluation: ; In this type of evaluation we do not evaluate params of the ; procedures, substitution is taken but evaluation is done only when ; is needed by some primitive operation (i.e (= b 0) will evaluate b) ; ; So execution would look like this ; ; (gcd 206 40) ; ; evaluate condition ; (if (= 40 0) 0) -> false ; ; next iteration ; (gcd 40 (remainder 206 40)) ; ; evaluate condition ; (if (= (remainder 206 40) 0) a) -> evaluates to 6 with 1 remainder call ; ; next iteration ; (gcd ; (remainder 206 40) ; (remainder 40 (remainder 206 40))) ; ; evaluate condition ; (if (= (remainder 40 (remainder 206 40)) 0) a) -> evaluates to 4 with 2 reminder calls ; ; next iteration ; (gcd ; (remainder ; 40 ; (remainder 206 40)) ; (remainder ; (remainder 206 40) ; (remainder 40 (remainder 206 40)))) ; ; evaluating condition ; (if (= ; (remainder ; (remainder 206 40) ; (remainder 40 (remainder 206 40))) ; 0) a) -> evaluating to 2 with 4 calls to remainder ; ; next iteration ; (gcd ; (remainder (remainder 206 40) (remainder 40 (remainder 206 40))) ; (remainder ; (remainder ; 40 ; (remainder 206 40)) ; (remainder ; (remainder 206 40) ; (remainder 40 (remainder 206 40))))) ; ; evaluating condition ; (if (= (remainder (remainder 40 (remainder 206 40)) (remainder (remainder 206 40) (remainder 40 (remainder 206 40)))) 0) -> evaluating to 0 ; (remainder ; (remainder 206 40) ; (remainder 40 (remainder 206 40)))) -> since it is true we have to evaluate as well result ; ; ; So we have here several places where execution needed to do the ; evaluation. 4 times to chech the condition and last time it had to ; evaluate result as well ; ; Number of executions 1 + 2 + 4 + 7 + 4 = 18 ; ; ------------------------------------------------ ; Applicative order of evaluation: ; In this case operands are evaluated previous to being passed to the ; procedure for evaluation. Therefore it looks like this for the given ; problem. ; ; (gc 206 40) ; ; checks condition ; (if (= 40 0) 206) ; ; next iteration ; (gcd 40 (remainder 206 40)) -> evaluates to (gcd 40 6) with 1 call to remainder ; (gcd 40 6) ; ; checks condition ; (if (= 6 0) 40) ; ; next iteration ; (gcd 6 (remainder 40 6)) -> evaluates to (gcd 6 4) with 1 call ; (gcd 6 4) ; ; checks condition ; (if (= 4 0) 6) ; ; next iteration ; (gcd 4 (remainder 6 4)) -> evaluates to (gcd 4 2) with 1 call ; (gcd 4 2) ; ; checks condition ; (if (= 2 0) 4) ; ; next iteration ; (gcd 2 (remainder 4 2)) -> evaluates to (gcd 2 0) with 1 call ; (gcd 2 0) ; ; checks condition ; (if (= 0 0) 2) ; ; prints 2 as GCD of numbers 206 and 40 ; ; Therefore we had 4 calls to remainder procedure.
false
f1bcfb9bbf005b389d428476c7d3b65292c0f5bc
f60baec01aa2c204a5ec583f95a55494bac0aeaa
/test/test_arithmetic.scm
c5938e00c7ce38ca01e6c6ea387bb8ddfa93e876
[]
no_license
medici/MameScheme
36aef454ea420426d87464cb8961bd1d232d56f4
a32817f2534233db59a3c156cc531d25256ad71d
refs/heads/master
2021-01-14T12:01:36.946604
2015-10-20T09:07:48
2015-10-20T09:07:48
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,068
scm
test_arithmetic.scm
(run-test "test_arithmetic.scm:arithmetic " (begin [assert (* 1) 1] [assert (* 3) 3] [assert (* 2 3) 6] [assert (* 2 3 4) 24] [assert (* 3 3/2) 9/2] [assert (* 2 1/2) 1] [assert (* 1.1 1.1) 1.2100000000000002] [assert (/ 1) 1] [assert (/ 6 3) 2] [assert (/ 24 3 2) 4] [assert (/ 7 3) 7/3] [assert (/ 67693145552775982373866185 2918354693076954957695495769285) 237519808957108710083741/10239841028340192834019283401] [assert (/ 4 2.0) 2] [assert (/ 4 1/2) 8] [assert (/ 9/7) 7/9] [assert (/ 7) 1/7] [assert (/ 9/7 1/2) 18/7] [assert (/ 9/5 1/2 5/4 6/7 123/17) 476/1025] ;; [assert (or (< 3.818181818 (/ 4.2 1.1)) ;; (> 3.818181819 (/ 4.2 1.1))) #t] [assert (quotient 7 3) 2] [assert (quotient -6 3) -2] [assert (+ 1) 1] [assert (+ 1 2) 3] [assert (+ 1 2 3) 6] [assert (+ 1/2 2/3) 7/6] [assert (+ 1 1/2) 3/2] [assert (+ 2 1/2 1/3) 17/6] [assert (= (+ 0.5 0.25) 0.75) #t] [assert (- 1) -1] [assert (- 9 4) 5] [assert (- 6 2 1 ) 3] [assert (= (- 1.1) -1.1) #t] [assert (= (- 1 0.5) 0.5) #t] [assert (= (- 0.5 1) -0.5) #t] [assert (- 10 4 3 2 1) 0] [assert (- 4294967296) -4294967296] [assert (- 4294967295) -4294967295] [assert (- 2147483648) -2147483648] [assert (- 2147483647) -2147483647] [assert (- 1073741824) -1073741824] [assert (- 1073741823) -1073741823] [assert (- 536870912) -536870912] [assert (- 536870911) -536870911] [assert (- -1) 1] [assert (- 0) 0] [assert (- 4312441/5451 123412/732) 206999000/332511] [assert (- 1/2 1/4 1/6) 1/12] [assert (- 1/2 1) -1/2] [assert (- 1/2 1 1/4) -3/4] [assert (- 1 1/2 1/4) 1/4] [assert (let ([n 999999999999999999999999])(- n) n) 999999999999999999999999] [assert (let ([n 999999999999999999999998/13])(- n) n) 999999999999999999999998/13] [assert (= (let ([n 0.5])(- n) n) 0.5) #t] [assert (let ((n 999999999999999999999999999999))(- 1 n) n) 999999999999999999999999999999] [assert (zero? 0) #t] [assert (zero? 2) #f] [assert (zero? -1) #f] [assert (gcd 4 6) 2] [assert (gcd 84 60) 12] [assert (gcd 4 5) 1] [assert (gcd 3) 3] [assert (gcd 4 8 6) 2] [assert (gcd) 0] [assert (lcm 4 6) 12] [assert (lcm 84 60) 420] [assert (lcm 45 42) 630] [assert (lcm 1 5) 5] [assert (lcm 3) 3] [assert (lcm 2 4 6) 12] [assert (lcm) 1] [assert (lcm 3366 14586 37026 38148) 16365492] [assert (even? 2) #t] [assert (odd? 3) #t] [assert (even? 3) #f] [assert (odd? 4) #f] [assert (even? -2) #t] [assert (odd? -3) #t] [assert (even? -3) #f] [assert (odd? -4) #f] [assert (even? 0) #t] [assert (odd? 0) #f] [assert (modulo 13 4) 1] [assert (modulo -13 4) 3] [assert (modulo 13 -4) -3] [assert (modulo -13 -4) -1] [assert (remainder 13 4) 1] [assert (remainder -13 4) -1] [assert (remainder 13 -4) 1] [assert (remainder -13 -4) -1] [assert (remainder 3 4) 3] [assert (remainder 3 3) 0] [assert (remainder 278498339886093762438332717358287437676301 9705932023587917550) 6176064781119719001] [assert (remainder -13 -4.0) -1.0] ))
false
db7de7a3d31f157699aafbb756572115d52ee8c1
1ed47579ca9136f3f2b25bda1610c834ab12a386
/sec3/q3.60.scm
ece19ed55532010b82298910418d91d6f4a0053a
[]
no_license
thash/sicp
7e89cf020e2bf5ca50543d10fa89eb1440f700fb
3fc7a87d06eccbe4dcd634406e3b400d9405e9c4
refs/heads/master
2021-05-28T16:29:26.617617
2014-09-15T21:19:23
2014-09-15T21:19:23
3,238,591
0
1
null
null
null
null
UTF-8
Scheme
false
false
1,108
scm
q3.60.scm
(load "./stream") ;; 3.59で見たようなべき級数の乗算手続きmul-series. ;; streamの要素同士を順々に掛け合わせて1つのstreamを作るのが3.54のmul-streams. ;; streamでできた級数同士を掛けるのがmul-series. ; (define (mul-series s1 s2) ; (cons-stream <??> (add-streams <??> <??>))) ;; q3.56.scm scale-streamを利用. (define (scale-stream stream factor) (stream-map (lambda (x) (* x factor)) stream)) ;; add-streamsは引数二つしか使えないことに留意. (define (mul-series s1 s2) (cons-stream (* (stream-car s1) (stream-car s2)) (add-streams (scale-stream (stream-cdr s2) (stream-car s1)) (add-streams (scale-stream (stream-cdr s1) (stream-car s2)) (cons-stream 0 (mul-series (stream-cdr s1) (stream-cdr s2))))))) ;; sin^2 + cos^2 = 1 を確認することでテストできる。 (load "./q3.59") (define s (add-streams (mul-series cosine-series cosine-series) (mul-series sine-series sine-series))) ; gosh> (display-stream-n s 10) ; 1, 0, 0, 0, 0, 0, 0, 0, 0, done ; => Ans: 1.000000000
false
9b2d27bc1fa0f36e451df8bd421eb0c9a08245f9
c63772c43d0cda82479d8feec60123ee673cc070
/ch1/35.scm
e195f55c1b0a328d6d0726d9e5b3534ba3517a46
[ "Apache-2.0" ]
permissive
liuyang1/sicp-ans
26150c9a9a9c2aaf23be00ced91add50b84c72ba
c3072fc65baa725d252201b603259efbccce990d
refs/heads/master
2021-01-21T05:02:54.508419
2017-09-04T02:48:46
2017-09-04T02:48:52
14,819,541
2
0
null
null
null
null
UTF-8
Scheme
false
false
92
scm
35.scm
#lang racket (require "fixed.scm") (fixed cos 1.0) (fixed (lambda (x) (+ 1 (/ 1 x))) 1.0)
false
1d8c4a8e849af508baebb0118f7fb2a2ab1fe21e
382706a62fae6f24855ab689b8b2d87c6a059fb6
/0.3/vm/load.scm
904f9863bd7ac75ea165c9d54447ca9ac3fee573
[ "Apache-2.0" ]
permissive
mstram/bard
ddb1e72a78059617403bea1842840bb9e979198e
340d6919603a30c7944fb66e04df0562180bc0bb
refs/heads/master
2021-01-21T00:12:27.174597
2014-07-10T13:20:39
2014-07-10T13:20:39
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,374
scm
load.scm
;;;; *********************************************************************** ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: load.scm ;;;; Project: Bard ;;;; Purpose: bard system loader ;;;; Author: mikel evins ;;;; Copyright: 2012 by mikel evins ;;;; ;;;; *********************************************************************** ;;; modify if the bard sources are at another pathname (define $bard-root "/Users/mikel/Workshop/bard/vm/") ; osx ;;;(define $bard-root "/home/mikel/Projects/bard/interpreter/") ; Linux ;;; ---------------------------------------------------------------------- ;;; Scheme files to load for interactive development ;;; ---------------------------------------------------------------------- (define (paths prefix . suffixes) (map (lambda (suffix)(string-append prefix suffix)) suffixes)) (define $bard-files (paths $bard-root "src/version.scm" "src/banner.scm" "lib/uuid.scm" "src/util.scm" "src/stack.scm" "src/env.scm" "src/instructions.scm" "src/program.scm" "src/bardo.scm" "src/bardvm.scm" )) ;;; load sources ;;; ---------------------------------------------------------------------- (define (loadvm) (gc-report-set! #t) (for-each (lambda (f)(load f)) $bard-files)) ;;; (loadvm)
false
6d03fc90eef2b7021e06b4798dbb3255b3bc1c7f
20aa11a2d7244e651882065ef5b21541dd9c9651
/scheme/anidb.scm
2bbedb9269fc574bab2c37f54db52f01db6f5211
[]
no_license
hitchiker42/my-code
355796707498775fe40bfedcdcb399b753d48cb2
571dd48bf6762e5d609ee5081f16a963a66151db
refs/heads/master
2022-12-15T20:44:31.990015
2021-10-31T18:22:25
2021-10-31T18:22:25
8,269,809
0
0
null
2022-12-14T02:00:12
2013-02-18T14:20:22
C
UTF-8
Scheme
false
false
30,031
scm
anidb.scm
(define-module (anidb udp)) ;;Guile scheme client for the anidb UDP api ;;API defination is located at http://wiki.anidb.net/w/UDP_API_Definition ;;receive is basically multiple-value-bind (use-modules (rnrs bytevectors) (ice-9 receive) (ice-9 readline) (ice-9 getopt-long) (sxml simple) (rnrs io ports) (ice-9 regex) (srfi srfi-1) (ice-9 format)) (load-extension "/home/tucker/anime_db/libguile-MD4" "init_MD4") ;;;;Global variables ;;I should read these from next 2 from a config file (define *anidb-config-file* (string-append (getenv "HOME") "/.anidb_scmrc")) (define *anidb-cache-dir* "/var/cache/anidb") (define *anidb-port* 9000) (define *anidb-server* (car (hostent:addr-list (gethostbyname "api.anidb.net")))) ;;the maximum size of a packet returned from the anidb server is 1400 bytes (define *output-buffer* (make-bytevector 1400)) (define *anidb-socket* #f) (define *client-name* "anidbscm") (define *client-version* 1) (define *api-version* 3) (define *session-key* #f) (define *default-anime-mask* #xb2f0e0fc000000) (define *anime-info-fields* #("aid" "dateflags" "year" "type" "related-aid-list" "related-aid-type" "category-list" "category-weight-list" "romaji-name" "kanji-name" "english-name" "other-name" "short-name-list" "synonym-list" "unused" "unused" "num-episodes" "max-episode-num" "num-special-episodes" "air-date" "end-date" "url" "picname" "cadegory-id-list" "rating" "vote-count" "temp-rating" "temp-vote-count" "avg-review" "review-count" "award-list" "is-18+" "anime-planet-id" "ann-id" "allcinema-id" "AnimeNfo-id" "unused" "unused" "unused" "date-record-updated" "character-id-list" "creator-id-list" "main-creator-id-list" "main-creator-name-list" "unused" "unused" "unused" "unused" "specials-count" "credits-count" "other-count" "trailer-count" "parody-count" "unused" "unused" "unused")) ;;;;Macros (eval-when (expand load eval) (define-inlinable (my-eval expr) (eval expr (interaction-environment)))) (define-macro (as-list x) `(if (list? ,x) ,x (list ,x))) ;; (define-macro (equal-any? val args) ;; ;;I can't get this to work any other way, so yeah ;; `(or ,@(map (lambda (x) `(equal? ,val ,x)) ;; (as-list (my-eval args))))) ;;This should be a macro but its too hard to make it work (define (equal-any? val args) (if (not (pair? args)) (equal? val args) (let ((retval #f)) (while (pair? args) (if (equal? val (pop args)) (set! retval #t) break)) retval))) ;;this works almast, it's horribly ugly and it doesn't work ;; (define-syntax equal-any? ;; (lambda (x) ;; (syntax-case x () ;; ((_ val args) ;; (let ((args-datum (syntax->datum #'args)) ;; (val-datum (syntax->datum #`val))) ;; (if (identifier? val-datum) ;; (set! val-datum (datum->syntax x val-datum))) ;; (if (list? args-datum) ;; (let ((or-body (map (lambda (x) `(equal? ,val-datum ,x)) ;; (my-eval args-datum)))) ;; (apply eval (list ;; (list 'syntax `(or ,@or-body)) ;; (interaction-environment)))) ;; #'(equal? val args))))))) (define-syntax progn (identifier-syntax begin)) (define-syntax prog1 (lambda (x) (syntax-case x () ((_ first rest ...) #'(let ((ret first)) rest ... first))))) (define-syntax pop (lambda (x) (syntax-case x () ((_ ls) #'(car (let ((ret ls)) (set! ls (cdr ls)) ret)))))) (define-syntax push (lambda (x) (syntax-case x () ((_ elt place) #'(set! place (cons elt place)))))) (define-syntax decf (lambda (x) (syntax-case x () ((_ y) #'(set! y (1- y)))))) (define-syntax incf (lambda (x) (syntax-case x () ((_ y) #'(set! y (1+ y)))))) ;;I actually need this and it works perfectly like this and I have ;;no clue how to make it work in the weird define-syntax form (define-macro (case-equal val . exprs) `(cond ,@(map (lambda (x) (cons (list 'equal? val (car x)) (cdr x))) exprs))) ;;Concatenate strings at macroexpansion time, allows writing long string ;;constants without looking ugly or suffering a performance penalty (define-macro (concat . strings) (string-join strings "")) ;;This implicitly introduces a few bindings, which is normally bad form, but in ;;this case I think it's fine, it's not as if this is a macro with wide applications (define-syntax define-anidb-command (lambda (x) (syntax-case x () ((_ define-clause command expected action ...) (with-syntax ((code (datum->syntax x 'code)) (msg (datum->syntax x 'msg)) (data (datum->syntax x 'data)) (cmd (datum->syntax x 'cmd))) #'(define* define-clause (let ((cmd command)) (send *anidb-socket* cmd) (receive (code msg data) (anidb-get-response cmd) (if (not (equal-any? code expected)) (anidb-handle-error code msg data) (begin action ...)))))))))) ;;;;Utility functions (define (string-split str delim) "Split string into substrings delimited by delim. Returns a list of substrings" (let acc ((index 0) (output '())) (let ((temp (string-index str delim (1+ index)))) (if temp (acc temp (cons (substring str index temp) output)) (reverse! (cons (substring str index) output)))))) (define (string-strip str) "returns a copy of str with leading and trailing whitespace removed" (let ((start (string-skip str char-set:whitespace)) (end (string-skip-right str char-set:whitespace))) (substring str start (1+ end)))) (define* (print obj #:optional (port (current-output-port))) "write obj to port, followed by a newline" (write obj port) (newline port)) (define* (pprint obj #:optional (port (current-output-port))) "display obj on port, followed by a newline" (display obj port) (newline port)) (define* (string-collect s char-pred #:optional (start 0) (end (string-length s))) "search string s for char-pred using string-index and if found return a substring begining at start and ending at the smaller of end and the index of char-pred, if char-pred is not found return #f" (let ((index (string-index s char-pred start end))) (if index (substring s start (min index end)) #f))) (define (integer->bitvector n) "Convert an integer to a bitvector such that the most significant bit in the integer is the first bit in the bitvector" (let* ((num-bits (integer-length n)) (bit (1- num-bits)) (vec (make-bitvector num-bits))) (while (> bit 0) (bitvector-set! vec (- num-bits 1 bit) (logbit? bit n)) (decf bit)) vec)) (define (logbit-reverse? index n) "test if bit number index is set in integer n, where index 0 corresponds to the most significant bit" (let ((num-bits (integer-length n))) (logbit? (- num-bits 1 index) n))) ;;add unwind-protect to close port (define (MD4-file filename) "Compute the MD4 sum of filename and return as a 16 byte integer" (let* ((io-port (open-file-input-port filename)) (file-size (stat:size (stat filename))) (file-contents (get-bytevector-n io-port file-size)) (MD4-sum (MD4 file-contents)) (retval (bytevector-uint-ref MD4-sum 0 (endianness big) 16))) (close-port io-port) retval)) (define-inlinable (MD4-bytevector bv) (bytevector-uint-ref (MD4 bv) 0 (endianness big) 16)) (define eD2k-chunk-size (* 9500 1024)) (define (eD2k-file filename) "Compute the eD2k sum of filename and return as a 16 byte integer" (let* ((port (open-file-input-port filename)) (size (stat:size (stat filename))) (result 0)) (if (<= size eD2k-chunk-size) (set! result (MD4-bytevector (get-bytevector-n port size))) (let ((chunk (make-bytevector eD2k-chunk-size)) (loops (modulo size eD2k-chunk-size)) (checksums '())) (while (>= loops 0) (reverse! checksums) (get-bytevector-n! port chunk 0 eD2k-chunk-size) (push (MD4-bytevector chunk) checksums) (decf loops)) ;;at this point there are < 9500k bytes left (push (MD4-bytevector (get-bytevector-all port)) checksums) (set! checksums (uint-list->bytevector (reverse! checksums) (endianness big) 16)) (set! result (MD4-bytevector checksums)))) (close-port port) result)) (define (set-socket-nonblocking! sock) (fcntl sock F_SETFL (logior O_NONBLOCK (fcntl sock F_GETFL)))) (define (wait-for-input fd timeout) (receive (secs usecs) (floor/ timeout 1) (set! usecs (round (* 1.9 usecs))) (select (list fd) '() '() secs usecs))) (define (print-checksum sum) (format #t "~32,'0x\n" sum)) (define (format-checksum sum) (format #f "~32,'0x\n" sum)) ;;;;anidb-commands (define (anidb-connect) "Connect to the anidb server" (set! *anidb-socket* (socket PF_INET SOCK_DGRAM IPPROTO_UDP)) (connect *anidb-socket* AF_INET *anidb-server* *anidb-port*) (set-port-encoding! *anidb-socket* "UTF-8")) (define* (anidb-keepalive #:optional (interval 6000)) "Initializes a timer which pings the server at specific intervals (default is every 10 minutes)" (let ((handler (lambda (signum) (anidb-ping) (alarm interval)))) (sigaction SIGALRM handler) (alarm interval))) (define (anidb-init) "Connects to the anidb sever and runs initialization code" (let ((port *anidb-port*)) (anidb-connect) (set! port (string-strip (anidb-ping 1))) (unless (eq? port *anidb-port*) (anidb-keepalive)))) (define (anidb-disconnect) "logout from anidb and cleanup resources" ;;attempt to logout, this prints a message if not logged in ;;but doesn't raise an error (anidb-logout) (alarm 0);;cancel any outstanding alarms (close *anidb-socket*));;close the socket (define (anidb-escape-string str) ;;perhaps not the most efficent way to do this but oh well ;;also I'm just ignoring newlines, since who puts a newline into a title (regexp-substitute/global #f "&" str 'pre "&amp;" 'post)) (define (anidb-recv cmd) "Attempts to receive a responce from the anidb server for cmd. Blocks for up to 1 second to see if there is output, then waits some ammount of time before resending the command. The command is resent upto 3 times and the delay between each is doubled every time" (let ((output-len #f)) (do ((wait 1 (* wait 2))) ((or output-len (> wait 4)) output-len) (if (select (list *anidb-socket*) '() '() 1) (set! output-len (recv! *anidb-socket* *output-buffer*)) (begin (sleep wait) (send *anidb-socket* cmd)))) output-len)) ;;Each responce has the form: ;;3-digit-return-code [data1] return-code-name(string) newline [data2] ;;the first data field is null for most responces except 200,201,271,272,504 ;;I believe that return-code-name shouldn't have any spaces in it ;;returns 4 values return-code return-string data2 data' ;;in this order since data1 is least used (define (anidb-get-response cmd) (let* ((output-len (anidb-recv cmd)) (output-string (make-bytevector output-len))) (bytevector-copy! *output-buffer* 0 output-string 0 output-len) (set! output-string (utf8->string output-string)) (let* ((index 4) (return-code (substring output-string 0 3)) (data1 (if (equal-any? return-code '("200" "201" "271" "272" "504")) (let ((data1-end (string-index output-string #\space 4))) (set! index data1-end) (substring output-string 4 index)) "")) (return-code-string (let ((str-end (string-index output-string #\newline index))) (prog1 (substring output-string index str-end) (set! index str-end)))) (data2 (substring output-string index))) (values return-code return-code-string data2 data1)))) ;;special command, to complicated to use define-anidb-command (define* (anidb-login #:optional username passwd) (if (not username) (set! username (readline "username: "))) (if (not passwd) (set! passwd (getpass "password: "))) (let ((command (format #f "AUTH user=~a&pass=~a&protover=~a&client=~a&clientver=~a" username passwd *api-version* *client-name* *client-version*))) (send *anidb-socket* command) (receive (code msg data2 data1) (anidb-get-response command) (if (not (or (equal? code "200") (equal? code "201"))) (anidb-handle-error code msg command) (begin (set! *session-key* data1) (print "Connection to anidb successful")))))) ;;special command, too simple to use define-anidb-command (define (anidb-logout) (if (not *session-key*) (print "Logout error, not logged in") (begin (send *anidb-socket* (format #f "LOGOUT s=~a" *session-key*)) (set! *session-key* #f)))) ;;Encryption, notification and buddy commands aren't supported ;;because I don't need them (define (anidb-encrypt) (error "Encrypted sessions not supported")) (define (anidb-push) (error "Notification commands unsupported")) (define (anidb-notify) (error "Notification commands unsupported")) (define (anidb-notifylist) (error "Notification commands unsupported")) (define (anidb-notifyget) (error "Notification commands unsupported")) (define (anidb-notifyack) (error "Notification commands unsupported")) (define (anidb-pushack) (error "Notification commands unsupported")) (define (anidb-buddyadd) (error "Buddy commands unimplemented")) (define (anidb-buddydel) (error "Buddy commands unimplemented")) (define (anidb-buddyaccept) (error "Buddy commands unimplemented")) (define (anidb-buddydeny) (error "Buddy commands unimplemented")) (define (anidb-buddylist) (error "Buddy commands unimplemented")) (define (anidb-buddystate) (error "Buddy commands unimplemented")) (define (amask->anime-info-fields amask) (let ((fields '())) (map (lambda (x) (when (logbit-reverse? x amask) (push (vector-ref *anime-info-fields* x) fields))) (iota (integer-length amask))) (reverse! fields))) (define (collect-fields str) (reverse! (fold-matches "([^|]*)|" str '() (lambda (match fields) (cons (match:substring match 1) fields))))) (define (get-anime-info-fields anime-info . fields) (reverse! (fold (lambda (x last) (let ((value (assoc-ref anime-info x))) (if value (cons value last) last))) '() fields))) ;;this returns an alist of (field-type . value) pairs (define-anidb-command (anidb-anime aid-or-name #:optional (amask *default-anime-mask*)) (cond ((integer? aid-or-name) (format #f "ANIME aid=~d&amask=~x&s=~a" aid-or-name amask *session-key*)) ((string? aid-or-name) (format #f "ANIME aname=~a&amask=~x&s=~a" aid-or-name amask *session-key*)) (else (error "anidb-anime reqires an integer or a string argument"))) "230" (map cons (amask->anime-info-fields amask) (collect-fields data))) ;;special command, has to recieve multiple responces ;;so can't ues define-anidb-command (define (andbd-animedesc aid) "Return a description of the anime specified by aid" (let acc ((output '()) (partno 0)) (let ((command (format #f "ANIMEDESC aid=~a&part=~a&s=~a" aid partno *session-key*))) (send *anidb-socket* command) (receive (code msg data) (anidb-get-response command) (if (not (equal? code "233")) (anidb-handle-error code msg command) (receive (cur-part max-part desc) (string-split data #\|) (if (equal? cur-part max-part) (string-join (append output desc)) (acc (append output desc) (1+ partno))))))))) (define-anidb-command (anidb-calendar) (format #f "CALENDAR s=~a" *session-key*) "297" (string-split data "\n")) (define-anidb-command (anidb-character id) (format #f "CHARACTER charid=~a&=~a" id *session-key*) "235" (let ((fields '("charid" "character name kanji" "character name transcription"- "pic" "blocks" "episode list" "last update date" "type" "gender"))) (map cons fields (collect-fields data)))) (define-anidb-command (anidb-creator id) (format #f "CREATOR creatorid=~a&s=~a" id *session-key*) "245" (let ((fields '("creatorid" "creator name kanji" "creator name transcription" "type" "pic_name" "url_english" "url_japanese" "wiki_url_english" "wiki_url_japanese" "last update date"))) (map cons fields (collect-fields (string-strip data))))) (define-anidb-command (anidb-episode id-name #:optional number) (if number (format #f "EPISODE ~a=~a&epno=~a&s=~a" (if (number? id-name) "aid" "aname");;error checking needed id-name number *session-key*) (format #f "EPISODE eid=~a&s=~a" id-name *session-key*)) "240" (let ((fields '("eid" "aid" "length" "rating" "votes" "epno" "eng" "romaji" "kanji" "aired" "type"))) (map cons fields (collect-fields (string-strip data))))) ;;need defaults for fmask and amosk (define-anidb-command (anidb-file filename #:optional fmask amask) (let ((size (stat:size (stat filename))) (ed2k (eD2k-file filename))) (format #f "FILE size=~d&ed2k=~32,'0x&fmask=~a&amask=~a&s=~a" size ed2k fmask amask *session-key*)) '("220" "322") (let ((file-fields '()) (anime-fields '())) (error "File command unimplemented"))) (define (anidb-group id-or-name) (format #f "GROUP ~a=~a&s=~a" (if (number? id-or-name) "gid" "gname") id-or-name *session-key*) "250" (let ((fields '("gid" "rating" "votes" "acount" "fcount" "name" "short" "irc channel" "irc server" "url" "picname" "foundeddate" "disbandeddate" "dateflags" "lastreleasedate" "lastactivitydate" "grouprelations"))) (map cons fields (collect-fields (string-strip data))))) (define (anidb-groupstats) (error "Groupstats command unimplemented")) ;;This is probably the most complicated command, then again, it is the only ;;command that let's you query your mylist so it needs to do a lot (define-anidb-command (anidb-mylist #:key lid fid filename anime) "Query mylist for a file, specified by a file id, mylist id or filename, or an anime specified by a name/anime id or a list of the form (name/anime-id group-name/group-id [episode-number])" (cond (lid (format #f "MYLIST lid=~a&s=~a" lid *session-key*)) (fid (format #f "MYLIST fid=~a&s=~a" fid *session-key*)) (filename (let ((size (stat:size (stat filename))) (ed2k (eD2k-file filename))) (format #f "MYLIST size=~d&ed2k=~32,'0x&s=~a" size ed2k *session-key*))) (anime (let ((aid-or-name (if (list? anime) (car anime) anime)) (gid-or-name (if (list? anime) (cadr anime) #f)) (epno (if (pair? (cddr anime)) (caddr anime) #f))) (format #f "MYLIST ~a=~a~a~a&s=~a" (if (number? aid-or-name) "aid" "aname") aid-or-name (if gid-or-name (format #f "&~a=~a" (if (number? gid-or-name) "gid" "gname") gid-or-name) "") (if epno (format #f "&epno=~a" epno) "") *session-key*))) (else (error (concat "One of lid, fid, filename, or anime must be" "supplied to the mylist command")))) (list "221" "321") (let ((fields (if (equal? code "221") ;;fields retured for a single episode '("lid" "fid" "eid" "aid" "gid" "date" "state" "viewdate" "storage" "source" "other" "filestate") ;;non-group fields returned for multiple episodes ;;several group fields are returned depending on the number ;;of groups that translated the anime '("anime title" "episodes" "eps with state unknown" "eps with state on hhd" "eps with state on cd" "eps with state deleted" "watched eps"))) (results (collect-fields (string-strip data)))) (if (equal? code "221") (map cons fields results) (append (map cons fields results) (cons "groups" (drop (length fields) results)))))) (define-anidb-command (anidb-mylistadd #:key fid lid filename anime;;one of these is required ;;all of these are optional state viewed viewdate source storage other edit) ;;a bit of complexity in format here, ~@[stuff] outputs stuff, ;;which should have one format clause, only if it's argument is not #f ;;if it is #f then nothing is output ;;TODO: Reformat other format strings like this, it's much cleaner (let ((options (format #f (concat "~@[&state=~a~]~@[&viewed=~a~]~@[&viewdate=~a~]~@[source=~a~]" "~@[&storage=~a~]~@[&other=~a~]~@[edit=~a~]&s=~a") state viewed viewdate source storage other edit *session-key*)) (anime-specifier (cond (lid (format #f "lid=~a" lid)) (fid (format #f "fid=~a" fid)) (filename (let ((size (stat:size (stat filename))) (ed2k (eD2k-file filename))) (format #f "size=~d&ed2k=~32,'0x&" size ed2k))) (anime (let ((aid-or-name (if (list? anime) (car anime) anime)) (gid-or-name (if (list? anime) (cadr anime) #f)) (epno (if (pair? (cddr anime)) (caddr anime) #f))) (format #f "~a=~a~a~a" (if (number? aid-or-name) "aid" "aname") aid-or-name (if gid-or-name (format #f "&~a=~a" (if (number? gid-or-name) "gid" "gname") gid-or-name) "") (if epno (format #f "&epno=~a" epno) "")))) (else (error (concat "One of lid, fid, filename, or anime must be" "supplied to the mylist command")))))) (format #f "MYLISTADD ~a~a" anime-specifier options)) (list "210" "310" "311" "322") (case-equal code ;;returns the lid if one episode was added, ;;or else the number of episodes added ("210" data) ("310") ;;file already exists return an alist of fields ("311" data);;entry/entries modified, return number modified ;;multiple files found for an anime ; ("322"))) (define (anidb-mylistdel) (error "Mylistdel command unimplemented")) (define-anidb-command (anidb-myliststats) (format #f "MYLISTSTATS s=~a" *session-key*) "222" (let ((fields '("animes" "eps" "files" "size of files" "added animes" "added eps" "added files" "added groups" "leech %" "glory %" "viewed % of db" "mylist % of db" "viewed % of mylist" "number of viewed eps" "votes" "reviews" "viewed length in minutes")) (results (collect-fields (string-strip data)))) ;;create an alist with fields as the keys ;;and the returned data as values, and return that (map cons fields results))) (define-anidb-command (anidb-vote id-or-name value #:key group epno) ;;vote paramater of anidb command is an integer 100-1000, argument to the ;;vote function is a floating point number (let ((vote (round (* 100 value)))) (format #f "VOTE type=~a&~a=~a&value=~a~@[&epno=~a~]" (if group 3 1) (if (string? id-or-name) "name" "id")) id-or-name vote epno) (list "260" "261" "262" "263") (error "Vote command unimplemented")) (define-anidb-command (anidb-random type) (format #f "RANDOM type=~a&s=~a" type *session-key*) "230" (map cons (amask->anime-info-fields *default-anime-mask*) (collect-fields data))) (define (anidb-mylistexport template) (error "Mylistexport command unimplemented")) (define (anidb-mylistexport-cancel) (error "Mylistexport command unimplemented")) (define-anidb-command (anidb-ping #:optional nat) ;;no need to be logged in for this one (if nat "PING nat=1" "PING") "300" (if nat;;if nat=1 data;;return the port #t)) (define-anidb-command (anidb-version) "VERSION" "998" data) (define-anidb-command (anidb-uptime) (format #f "UPTIME s=~a" *session-key*) "208" data) (define (anidb-encoding) (error "Encoding command unimplemented")) (define (anidb-sendmsg) (error "Sendmsg command unimplemented")) (define (anidb-user) (error "User command unimplemented")) ;;find the argument for the 'thing' field in an anidb command ;;matching is done case insensitively (define (find-thing thing str) (let* ((thing-start (string-contains-ci str thing)) ;;add 1 to account for the trailing = sign (thing-end (+ thing-start (string-length thing) 1)) (data-end (or (string-index str #\& thing-end) (string-length str)))) ;;currently this fails to account for the case where thing is found in ;;another part of str, which should be handled by checking that ;;thing is at the start of string or (eq (string-ref (1- thing-start) #\&)) ;;I don't know what to do if that's the case though (substring thing-end data-end))) (define* (anidb-handle-error err-code err-name cmd #:optional (err-msg "")) ;;err-code is a 3 character string giving the error number (let ((err-string (cond ((eqv? (string-ref err-code 0) #\6) (format #f "Anidb error ~a: ~a - ~a\n" err-code err-name err-msg )) ((equal-any? err-code '("330" "333" "334" "335" "336" "337" "338" "340" "343" "344" "345" "350" "351" "410" "411")) ;;these errors are all of the form NO_SUCH_THING (let* ((thing (substring err-name 8));;i.e anime, group, series,etc (thing-name (find-thing thing cmd)));;name of the above thing (format #f "Ainbd error ~a: No such ~a \"~a\"\n" err-code (string-capitalize thing) thing-name))) ((equal? err-code "598") (format #f "Internal error: Unknown Command ~a\n" cmd)) ((equal? err-code "500") (format #f "Login failed, please try again\n")) ((equal? err-code "501") (format #f "Error: Not logged in, please login to continue\n")) ((equal? err-code "505") (format #f "Error: Illegal input or Access denied\nCommand was ~a" cmd)) ((or (equal? err-code "502") (equal? err-code "506")) (format #f "Internal Error: Anidb access denied\n")) (else (format #f "Error ~a ~a ~a\nCommand was ~a" err-code err-name err-msg cmd))))) (write err-string (current-error-port)) (throw 'anidb-error err-string))) ;;Info about amask passed to anime command ;;Amask is a 7 byte bitmask indicating what information about the anime should ;;be returned, it is constructed as follows: ;;Byte1 (int aid) (int dateflags) (str year) (str type) (str related-aid-list) ;; (str related-aid-type) (str category-list) (str category-weight-list) ;;Byte2 (str romaji-name) (str kanji-name) (str english-name) (str other-name) ;; (str short-name-list) (str synonym-list) (unused) (unused) ;;Byet3 (int4 num-episodes) (int4 max-episode-num) (int4 num-special-episodes) ;; (int air-date) (int end-date) (str url) ;; (str picname) (str cadegory-id-list) ;;Byte4 (int4 rating) (int vote-count) (int4 temp-rating) (int temp-vote-count) ;; (int4 avg-review) (int review-count) (str award-list) (bool is-18+) ;;Byte5 (int anime-planet-id) (int ann-id) (int allcinema-id) ;; (int AnimeNfo-id) (int date-record-updated) ;;Byte6 (int character-id-list) (int creator-id-list) (int main-creator-id-list) ;; (str main-creator-name-list) (unused) (unused) ;;Byte7 (int4 specials-count) (int4 credits-count) (int4 other-count) ;; (int4 trailer-count) (int4 parody-count) ;;User interface (define *anidb-commands* '("AUTH" "LOGOUT" "ENCRYPT";;auth cmds "PUSH" "NOTIFY" "NOTIFYLIST" "NOTIFYGET" "NOTIFYACK" "PUSHACK";;notify cmds "ANIME" "ANIMEDESC" "CALENDAR" "CHARACTER" "CREATOR" ;;data cmds 1 "EPISODE" "FILE" "GROUP" "GROUPSTATS" ;;data cmds 2 "MYLIST" "MYLISTADD" "MYLISTDEL" "MYLISTSTATS" "VOTE" "RANDOM" ;;mylist cmds "MYLISTEXPORT" "PING" "VERSION" "UPTIME" "ENCODING" "SENDMSG" "USER")) ;;misc (define anidb-readline-completer (make-completion-function (append *anidb-commands* (map string-downcase *anidb-commands*) (map string-capitalize *anidb-commands*)))) ;;just for convience (define (anidb-readline) (with-readline-completion-function anidb-readline-completer readline)) ;;It'd be nice to have filename completion for some commands ;; (eval-when () (when running (set-readline-prompt "> ") (let ((line "")(cmd "")(args "")(results #f)) (while #t (set! line (anidb-readline)) (set! cmd (some-function line)) (set! args (some-other-function line)) (set! results (catch 'anidb-error (lambda () (apply (function-to-turn-cmd-into-a-function) args)) (lambda (key args) #f))) (when results (function-to-process-results cmd results))))))
true
d306339a765d27531f458cf84a96c8f95651f4e6
4b480cab3426c89e3e49554d05d1b36aad8aeef4
/chapter-02/ex2.68-Solidone.ss
30363a8728c0e567ce5bf290bcc5928e37fc8075
[]
no_license
tuestudy/study-sicp
a5dc423719ca30a30ae685e1686534a2c9183b31
a2d5d65e711ac5fee3914e45be7d5c2a62bfc20f
refs/heads/master
2021-01-12T13:37:56.874455
2016-10-04T12:26:45
2016-10-04T12:26:45
69,962,129
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,138
ss
ex2.68-Solidone.ss
(load "ex2.67-Solidone.ss") (define (entry tree) (car tree)) (define (element-of-set? x set) (cond ((null? set) false) ((equal? x (car set)) true) (else (element-of-set? x (cdr set))))) ; answer (define (encode-symbol character tree) (define (iter tree) (cond ((leaf? tree) null) ((element-of-set? character (symbols (left-branch tree))) (cons 0 (iter (left-branch tree)))) (else (cons 1 (iter (right-branch tree)))))) (if (memq character (symbols tree)) (iter tree) (display "No such character in tree\n"))) (define (encode message tree) (if (null? message) '() (append (encode-symbol (car message) tree) (encode (cdr message) tree)))) ;test-case (encode-symbol 'A sample-tree) (and (equal? (list 0) (encode-symbol 'A sample-tree)) (equal? (list 1 0) (encode-symbol 'B sample-tree)) (not (list? (encode-symbol 'K sample-tree))) (equal? (list 1 1 0) (encode-symbol 'D sample-tree)) (equal? (list 1 1 1) (encode-symbol 'C sample-tree)) (equal? '(A D A B B C A) (decode (encode '(A D A B B C A) sample-tree) sample-tree)))
false
e875df728bfdb76a235028d9a9c269e62a9d0728
3604661d960fac0f108f260525b90b0afc57ce55
/SICP-solutions/1/1.38.scm
d411b51b0a64e60bb710a5eed6c038bca8f604dc
[]
no_license
rythmE/SICP-solutions
b58a789f9cc90f10681183c8807fcc6a09837138
7386aa8188b51b3d28a663958b807dfaf4ee0c92
refs/heads/master
2021-01-13T08:09:23.217285
2016-09-27T11:33:11
2016-09-27T11:33:11
69,350,592
0
0
null
null
null
null
UTF-8
Scheme
false
false
155
scm
1.38.scm
(load "1.37.scm") (define (n i) 1.0) (define (d i) (if (= (remainder i 3) 2) (* 2 (+ (/ i 3) (/ 1 3))) 1)) (define (e k) (+ 2 (cont-frac-i n d k)))
false
c08fb4120924657691a36f6ad35272c64bb66098
736e7201d8133f7b5262bbe3f313441c70367a3d
/misc/internal/windows/TeXmacs/progs/ice-9/debug.scm
d99e7968257ab7a0d3f8b83863274c8098c61f84
[]
no_license
KarlHegbloom/texmacs
32eea6e344fd27ff02ff6a8027c065b32ff2b976
ddc05600d3d15a0fbc72a50cb657e6c8ebe7d638
refs/heads/master
2021-01-16T23:52:33.776123
2018-06-08T07:47:26
2018-06-08T07:47:26
57,338,153
24
4
null
2017-07-17T05:47:17
2016-04-28T22:37:14
Tcl
UTF-8
Scheme
false
false
3,463
scm
debug.scm
;;;; Copyright (C) 1996, 1997, 1998, 1999 Free Software Foundation ;;;; ;;;; This program is free software; you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation; either version 2, or (at your option) ;;;; any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this software; see the file COPYING. If not, write to ;;;; the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ;;;; Boston, MA 02111-1307 USA ;;;; ;;;; The author can be reached at [email protected] ;;;; Mikael Djurfeldt, SANS/NADA KTH, 10044 STOCKHOLM, SWEDEN ;;;; (define-module (ice-9 debug)) ;;; {Misc} ;;; (define-public (frame-number->index n . stack) (let ((stack (if (null? stack) (fluid-ref the-last-stack) (car stack)))) (if (memq 'backwards (debug-options)) n (- (stack-length stack) n 1)))) ;;; {Trace} ;;; ;;; This code is just an experimental prototype (e. g., it is not ;;; thread safe), but since it's at the same time useful, it's ;;; included anyway. ;;; (define traced-procedures '()) (define-public (trace . args) (if (null? args) (nameify traced-procedures) (begin (for-each (lambda (proc) (if (not (procedure? proc)) (error "trace: Wrong type argument:" proc)) (set-procedure-property! proc 'trace #t) (if (not (memq proc traced-procedures)) (set! traced-procedures (cons proc traced-procedures)))) args) (set! apply-frame-handler trace-entry) (set! exit-frame-handler trace-exit) (set! trace-level 0) (debug-enable 'trace) (nameify args)))) (define-public (untrace . args) (if (and (null? args) (not (null? traced-procedures))) (apply untrace traced-procedures) (begin (for-each (lambda (proc) (set-procedure-property! proc 'trace #f) (set! traced-procedures (delq! proc traced-procedures))) args) (if (null? traced-procedures) (debug-disable 'trace)) (nameify args)))) (define (nameify ls) (map (lambda (proc) (let ((name (procedure-name proc))) (or name proc))) ls)) (define trace-level 0) (add-hook! abort-hook (lambda () (set! trace-level 0))) (define (trace-entry key cont tail) (if (eq? (stack-id cont) 'repl-stack) (let ((cep (current-error-port)) (frame (last-stack-frame cont))) (if (not tail) (set! trace-level (+ trace-level 1))) (let indent ((n trace-level)) (cond ((> n 1) (display "| " cep) (indent (- n 1))))) (display-application frame cep) (newline cep))) ;; It's not necessary to call the continuation since ;; execution will continue if the handler returns ;(cont #f) ) (define (trace-exit key cont retval) (if (eq? (stack-id cont) 'repl-stack) (let ((cep (current-error-port))) (set! trace-level (- trace-level 1)) (let indent ((n trace-level)) (cond ((> n 0) (display "| " cep) (indent (- n 1))))) (write retval cep) (newline cep)))) ;;; A fix to get the error handling working together with the module system. ;;; (variable-set! (builtin-variable 'debug-options) debug-options) (debug-enable 'debug) (read-enable 'positions)
false
68c1e2507550534de68f34e22dd86c0edf3e3b22
ae76253c0b7fadf8065777111d3aa6b57383d01b
/chap4/exec-4.46.ss
463be817e1b6739eca6966519c5712b5370f7f07
[]
no_license
cacaegg/sicp-solution
176995237ad1feac39355f0684ee660f693b7989
5bc7df644c4634adc06355eefa1637c303cf6b9e
refs/heads/master
2021-01-23T12:25:25.380872
2014-04-06T09:35:15
2014-04-06T09:35:15
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
249
ss
exec-4.46.ss
;; If the amb evaluator evalute the argument from right to left order, ;; then the grammer can't match to input. ;; Since the input will always comes in with left to right order, ;; change the evaluation order will make a incorrect grammer result.
false
7feb24a19c4839cfc10b226da873a547d0abb1f4
23122d4bae8acdc0c719aa678c47cd346335c02a
/2022/10.scm
d50d2f4fc4b56d7f2d2b6f46bf13463c8b1c1eb3
[]
no_license
Arctice/advent-of-code
9076ea5d2e455d873da68726b047b64ffe11c34c
2a2721e081204d4fd622c2e6d8bf1778dcedab3e
refs/heads/master
2023-05-24T23:18:02.363340
2023-05-04T09:04:01
2023-05-04T09:06:24
225,228,308
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,209
scm
10.scm
#!chezscheme (import (scheme) (core)) (define input (map (λ (line) (let ([line (string-split " " line)]) (cons (string->symbol (car line)) (map string->number (cdr line))))) (readlines "10.input"))) (define (cpu) (let run ([register 1] [tape input] [cycle 1]) (cons (cons* cycle register) (if (null? tape) '() (let ([next (car tape)] [rest (cdr tape)] [cycle (+ 1 cycle)]) (record-case next [noop () (run register rest cycle)] [addx (n) (run register (cons `(addx* ,n) rest) cycle)] [addx* (n) (run (+ n register) rest cycle)])))))) (let* ([output (filter (λ (x) (= 20 (mod (car x) 40))) (cpu))] [signal-strengths (map (λ (x) (* (car x) (cdr x))) output)]) (printf "part 1: ~s\n" (fold-left + 0 signal-strengths))) (define (crt register-values) (for-each (λ (cycle sprite) (let* ([pixel (mod (- cycle 1) 40)] [activated (<= (abs (- pixel sprite)) 1)]) (printf "~c" (if activated #\| #\space)) (when (= pixel 39) (printf "\n")))) (map car register-values) (map cdr register-values))) (crt (cpu))
false
97f6b55a17aeaebec6884c8f858ac03c2389b0eb
45b0335564f2f65b8eea1196476f6545ec7ac376
/tests/tests-1.5-req.scm
7286a19de7ab901550839c0f9fae2907d5a63d7c
[ "MIT" ]
permissive
dannypsnl-fork/nanopass
cbc252bb36054550191f16c2353126464268de7c
80e0344a1f143832a75d798be903e05b5dbdd079
refs/heads/master
2021-12-12T16:14:13.733284
2017-02-02T05:17:05
2017-02-02T05:17:05
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,004
scm
tests-1.5-req.scm
(add-tests-with-string-output "fixnum?" [(fixnum? 0) => "#t\n"] [(fixnum? #t) => "#f\n"] [(fixnum? '()) => "#f\n"] [(fixnum? "s") => "#f\n"] [(fixnum? (fx+ 12 13)) => "#t\n"] ) (add-tests-with-string-output "fixnum" [(fixnum 0.0) => "0\n"] [(fixnum 1.5) => "1\n"] [(fixnum 11.9) => "11\n"] [(fixnum -2.45) => "-2\n"] [(fixnum? (fixnum 100.01)) => "#t\n"] ) (add-tests-with-string-output "fx+" [(fx+ 1 2) => "3\n"] [(fx+ 1 -2) => "-1\n"] [(fx+ -1 2) => "1\n"] [(fx+ -1 -2) => "-3\n"] [(fx+ 268435455 -1) => "268435454\n"] [(fx+ 268435454 1) => "268435455\n"] [(fx+ -268435456 1) => "-268435455\n"] [(fx+ -268435455 -1) => "-268435456\n"] [(fx+ 268435455 -268435456) => "-1\n"] [(fx+ 1 (fx+ 2 3)) => "6\n"] [(fx+ 1 (fx+ 2 -3)) => "0\n"] [(fx+ 1 (fx+ -2 3)) => "2\n"] [(fx+ 1 (fx+ -2 -3)) => "-4\n"] [(fx+ -1 (fx+ 2 3)) => "4\n"] [(fx+ -1 (fx+ 2 -3)) => "-2\n"] [(fx+ -1 (fx+ -2 3)) => "0\n"] [(fx+ -1 (fx+ -2 -3)) => "-6\n"] [(fx+ (fx+ 1 2) 3) => "6\n"] [(fx+ (fx+ 1 2) -3) => "0\n"] [(fx+ (fx+ 1 -2) 3) => "2\n"] [(fx+ (fx+ 1 -2) -3) => "-4\n"] [(fx+ (fx+ -1 2) 3) => "4\n"] [(fx+ (fx+ -1 2) -3) => "-2\n"] [(fx+ (fx+ -1 -2) 3) => "0\n"] [(fx+ (fx+ -1 -2) -3) => "-6\n"] [(fx+ (fx+ (fx+ (fx+ (fx+ (fx+ (fx+ (fx+ 1 2) 3) 4) 5) 6) 7) 8) 9) => "45\n"] [(fx+ 1 (fx+ 2 (fx+ 3 (fx+ 4 (fx+ 5 (fx+ 6 (fx+ 7 (fx+ 8 9)))))))) => "45\n"] ) (add-tests-with-string-output "fx-" [(fx- 1 2) => "-1\n"] [(fx- 1 -2) => "3\n"] [(fx- -1 2) => "-3\n"] [(fx- -1 -2) => "1\n"] [(fx- 268435454 -1) => "268435455\n"] [(fx- 268435455 1) => "268435454\n"] [(fx- -268435455 1) => "-268435456\n"] [(fx- -268435456 -1) => "-268435455\n"] [(fx- 1 268435455) => "-268435454\n"] [(fx- -1 268435455) => "-268435456\n"] [(fx- 1 -268435454) => "268435455\n"] [(fx- -1 -268435456) => "268435455\n"] [(fx- 268435455 268435455) => "0\n"] [(fx- -268435455 -268435456) => "1\n"] [(fx- 1 (fx- 2 3)) => "2\n"] [(fx- 1 (fx- 2 -3)) => "-4\n"] [(fx- 1 (fx- -2 3)) => "6\n"] [(fx- 1 (fx- -2 -3)) => "0\n"] [(fx- -1 (fx- 2 3)) => "0\n"] [(fx- -1 (fx- 2 -3)) => "-6\n"] [(fx- -1 (fx- -2 3)) => "4\n"] [(fx- -1 (fx- -2 -3)) => "-2\n"] [(fx- 0 (fx- -2 -3)) => "-1\n"] [(fx- (fx- 1 2) 3) => "-4\n"] [(fx- (fx- 1 2) -3) => "2\n"] [(fx- (fx- 1 -2) 3) => "0\n"] [(fx- (fx- 1 -2) -3) => "6\n"] [(fx- (fx- -1 2) 3) => "-6\n"] [(fx- (fx- -1 2) -3) => "0\n"] [(fx- (fx- -1 -2) 3) => "-2\n"] [(fx- (fx- -1 -2) -3) => "4\n"] [(fx- (fx- (fx- (fx- (fx- (fx- (fx- (fx- 1 2) 3) 4) 5) 6) 7) 8) 9) => "-43\n"] [(fx- 1 (fx- 2 (fx- 3 (fx- 4 (fx- 5 (fx- 6 (fx- 7 (fx- 8 9)))))))) => "5\n"] ) (add-tests-with-string-output "fx*" [(fx* 3 -3) => "-9\n"] [(fx* 0 -3) => "0\n"] [(fx* 30 -30) => "-900\n"] [(fx* 3 30) => "90\n"] [(fx* 234 1) => "234\n"] [(fx* 1 234) => "234\n"] [(fx* (fx* 1 -2) -3) => "6\n"] ) (add-tests-with-string-output "fx/" [(fx/ 3 -3) => "-1\n"] [(fx/ 0 -3) => "0\n"] [(fx/ 30 -30) => "-1\n"] [(fx/ 234 1) => "234\n"] [(fx/ 1 234) => "0\n"] [(fx/ 10 2) => "5\n"] [(fx/ 10 3) => "3\n"] ) (add-tests-with-string-output "modulo" [(modulo -3 5) => "-3\n"] [(modulo 3 -5) => "3\n"] [(modulo -3 -5) => "-3\n"] [(modulo 130 40) => "10\n"] [(modulo 50 100) => "50\n"] [(modulo 250 2) => "0\n"] [(modulo 250 123) => "4\n"] ) (add-tests-with-string-output "fx=" [(fx= 12 13) => "#f\n"] [(fx= 12 12) => "#t\n"] [(fx= 16 (fx+ 13 3)) => "#t\n"] [(fx= 16 (fx+ 13 13)) => "#f\n"] [(fx= (fx+ 13 3) 16) => "#t\n"] [(fx= (fx+ 13 13) 16) => "#f\n"] [(if (fx= 12 13) 12 13) => "13\n"] [(if (fx= 12 12) 13 14) => "13\n"] ) (add-tests-with-string-output "fx<" [(fx< 12 13) => "#t\n"] [(fx< 12 -13) => "#f\n"] [(fx< 1 1) => "#f\n"] ) (add-tests-with-string-output "fx<=" [(fx<= 12 13) => "#t\n"] [(fx<= 12 -13) => "#f\n"] [(fx<= 1 1) => "#t\n"] ) (add-tests-with-string-output "fxabs" [(fxabs -1) => "1\n"] [(fxabs 1) => "1\n"] [(fxabs -8) => "8\n"] )
false
9068b93d958658bd04a89559d38aa616899e0b24
be06d133af3757958ac6ca43321d0327e3e3d477
/99problems/66.scm
1eb0564536f12ad01249a425296d9886697164ef
[]
no_license
aoyama-val/scheme_practice
39ad90495c4122d27a5c67d032e4ab1501ef9c15
f133d9326699b80d56995cb4889ec2ee961ef564
refs/heads/master
2020-03-13T12:14:45.778707
2018-04-26T07:12:06
2018-04-26T07:12:06
131,115,150
0
0
null
null
null
null
UTF-8
Scheme
false
false
363
scm
66.scm
(define (comp x y) (- x y)) (define (min-vector cp vec start end) (let loop ((i start) (min (vector-ref vec start)) (min-index start)) (cond ((>= i end) min-index) ((negative? (cp (vector-ref vec i) min)) (loop (+ i 1) (vector-ref vec i) i)) (else (loop (+ i 1) min min-index))))) (print (min-vector comp #(5 4 6 3 7 8 2 9 1) 1 4)) ; 8
false
2b510a7c3ae793984232a97db8d88cc184cfe3f6
de21ee2b90a109c443485ed2e25f84daf4327af3
/exercise/section4/4.1.scm
54667645438d1d2bd8682bc555f6e3e79c294d98
[]
no_license
s-tajima/SICP
ab82518bdc0551bb4c99447ecd9551f8d3a2ea1d
9ceff8757269adab850d01f238225d871748d5dc
refs/heads/master
2020-12-18T08:56:31.032661
2016-11-10T11:37:52
2016-11-10T11:37:52
18,719,524
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,334
scm
4.1.scm
;= Question ============================================================================= ; ; 問題 4.1 ; ; 超循環評価器が被演算子を左から右へ評価するか, ; 右から左へ評価するかわれわれには分らない. 評価順は基盤のLispから引き継いでいる. ; list-of-valuesのconsの引数が左から右へ評価されるなら, ; list-of-valuesも被演算子を左から右へ評価する; consの引数が右から左へ評価されるなら, ; list-of-valuesも被演算子を右から左へ評価する. ; ; 基盤のLispの評価の順と無関係に被演算子を左から右へ評価するlist-of-valuesを書け. ; また被演算子を右から左へ評価するlist-of-valuesを書け. ; ;= Prepared ============================================================================= (define val 10) (define expression '((set! val (+ val 2)) (set! val (* val 2)))) (define val2 10) (define expression2 '((set! val2 (+ val2 2)) (set! val2 (* val2 2)))) (print expression) (define (list-of-values-right exps) (if (null? exps) '() (let ((first-eval (eval (car exps) (interaction-environment)))) (cons first-eval (list-of-values-right (cdr exps)))))) ;(print (list-of-values-right expression)) (define (list-of-values-left exps) (if (null? exps) '() (let ((first-eval (list-of-values-left (cdr exps)))) (cons (eval (car exps) (interaction-environment)) first-eval)))) ;(print (list-of-values-left expression2)) ;= Answer =============================================================================== (define no-operands? null?) (define first-operand car) (define rest-operands cdr) (define (list-of-values exps env) (if (no-operands? exps) '() (let ((first-eval (eval (first-operand exps) env))) (cons first-eval (list-of-values (rest-operands exps) env))))) ; (define (list-of-values exps env) ; (if (no-operands? exps) ; '() ; (let ((first-eval (list-of-values (rest-operands exps) env))) ; (cons (eval (first-operand exps) env) ; first-eval)))) (define val3 10) (define expression3 '((set! val3 (+ val3 2)) (set! val3 (* val3 2)))) (print (list-of-values expression3 (interaction-environment)))
false
edf5201504bd63145297ebf0218056548ce87997
4f30ba37cfe5ec9f5defe52a29e879cf92f183ee
/src/regex/regex.scm
1c3fc4060f50cf9aab565f2e257840943ada4f0d
[ "MIT" ]
permissive
rtrusso/scp
e31ecae62adb372b0886909c8108d109407bcd62
d647639ecb8e5a87c0a31a7c9d4b6a26208fbc53
refs/heads/master
2021-07-20T00:46:52.889648
2021-06-14T00:31:07
2021-06-14T00:31:07
167,993,024
8
1
MIT
2021-06-14T00:31:07
2019-01-28T16:17:18
Scheme
UTF-8
Scheme
false
false
6,569
scm
regex.scm
(need scheme/tag) (need regex/nfa) (need regex/dfa) (need regex/compile) (define (make-regex-syntax check compiler) (tag 'regex-syntax (list check compiler))) (define (regex-syntax.check syntax) (car (contents syntax))) (define (regex-syntax.compiler syntax) (cadr (contents syntax))) (define *regex-syntax-table* '()) (define (install-regex-syntax! syntax) (set! *regex-syntax-table* (cons syntax *regex-syntax-table*))) (define (lookup-regex-syntax rgx) (define (iter l) (cond ((null? l) #f) (((regex-syntax.check (car l)) rgx) (car l)) (else (iter (cdr l))))) (iter *regex-syntax-table*)) (define (lookup-regex-compiler rgx) (let ((syn (lookup-regex-syntax rgx))) (and syn (regex-syntax.compiler syn)))) (define (compile-subregex rgx) (let ((compiler (lookup-regex-compiler rgx))) (let ((res (and compiler (compiler rgx)))) (if (not (nfa? res)) (error "Result of compilation should be a NFA -- COMPILE-SUBREGEX" rgx res) res)))) (define (compile-regex rgx) (if (procedure? rgx) (begin (fast-dfa-reset! rgx) rgx) (let ((res (compile-subregex rgx))) (if (not (nfa? res)) (error "Reuslt of compilation should be a NFA -- COMPILE-REGEX" rgx res)) (compile-dfa-to-fast-dfa (nfa->dfa res))))) (define (define-regex-syntax check compiler) (install-regex-syntax! (make-regex-syntax check compiler))) (define (define-regex-keyword-syntax keyword compiler) (define-regex-syntax (lambda (rgx) (and (list? rgx) (eqv? keyword (car rgx)))) (lambda (rgx) (compiler (map compile-subregex (cdr rgx)))))) (define (true? x) (not (eqv? #f x))) (define (regex-whole-match rgx string) (let ((a-dfa (compile-regex rgx))) (for-each (lambda (char) (fast-dfa-input! a-dfa char)) (string->list string)) (fast-dfa-done? a-dfa))) (define (test-regex rgx string expected) (let ((res (true? (regex-whole-match rgx string)))) (if (not (equal? expected res)) (error (format "~ ~ => ~, expected ~" rgx string res expected))))) (define (regex-match-from regex string idx) (let ((a-dfa (compile-regex regex))) (define (return idx len) (list idx (+ idx len))) (define (try-match idx) (define (iter cur len) (if (>= cur (string-length string)) (and (fast-dfa-done? a-dfa) (return idx len)) (let ((pre-done? (fast-dfa-done? a-dfa))) (fast-dfa-input! a-dfa (string-ref string cur)) (cond ((and pre-done? (not (zero? len)) (fast-dfa-failed? a-dfa)) (return idx len)) ((fast-dfa-failed? a-dfa) (try-match (+ idx 1))) (else (iter (+ cur 1) (+ len 1))))))) (fast-dfa-reset! a-dfa) (iter idx 0)) (try-match 0))) (define (regex-match regex string) (regex-match-from regex string 0)) (define (regex-matching-string regex string) (let ((match (regex-match regex string))) (and match (substring string (car match) (cadr match))))) (define (regex-match-complete? regex string) (let ((match (regex-matching-string regex string))) (and match (string=? string match)))) (define (regex-match-port-line-column regex port line column) (let ((a-dfa (compile-regex regex))) (define (return res output line column) (list (list->string (reverse res)) output line column)) (define (return-error res char line column) (list '*lexer-error* (list->string (reverse (cons char res))) line column)) (define (next-line line char) (if (char=? char #\newline) (+ line 1) line)) (define (next-column col char) (if (char=? char #\newline) 0 (+ col 1))) (define (iter res line column) (let ((char (peek-char port))) (if (eof-object? char) (if (fast-dfa-done? a-dfa) (return res (fast-dfa-emit a-dfa) line column) (return-error res char line column)) (let ((pre-done (fast-dfa-done? a-dfa)) (pre-done-output (fast-dfa-emit a-dfa))) (fast-dfa-input! a-dfa char) (cond ((and pre-done (not (null? res)) (fast-dfa-failed? a-dfa)) (return res pre-done-output line column)) ((fast-dfa-failed? a-dfa) (return-error res char line column)) (else (let ((char (read-char port))) (iter (cons char res) (next-line line char) (next-column column char))))))))) (iter '() line column))) (define (regex-match-port regex port) (let ((res (regex-match-port-line-column regex port 0 0))) (and res (car res)))) (define-regex-syntax char? compile-char) (define-regex-syntax string? compile-string) (define-regex-syntax symbol? (lambda (rgx) (compile-string (symbol->string rgx)))) (define-regex-syntax number? (lambda (rgx) (compile-string (number->string rgx)))) (define-regex-syntax (lambda (x) (and (list? x) (= 2 (length x)) (eqv? '@ (list-ref x 0)) (string? (list-ref x 1)))) compile-optional-string) (define-regex-syntax (lambda (stmt) (and (list? stmt) (= 4 (length stmt)) (eqv? ':emit (list-ref stmt 0)))) (lambda (stmt) (compile-emit (compile-subregex (list-ref stmt 3)) ; <- nfa (list-ref stmt 1) ; <- value-to-emit (list-ref stmt 2)))) ; <- emit-priority (define-regex-keyword-syntax '& compile-append) (define-regex-keyword-syntax ': compile-or) ;(define-regex-keyword-syntax '@ compile-or) (define-regex-keyword-syntax '* (lambda (list-of-nfas) (compile-* (compile-append list-of-nfas)))) (define-regex-keyword-syntax '+ (lambda (list-of-nfas) (compile-+ (compile-append list-of-nfas)))) (define-regex-keyword-syntax '^ (lambda (list-of-nfas) (compile-append (map compile-optional list-of-nfas)))) (define-regex-keyword-syntax '^& (lambda (list-of-nfas) (compile-optional (compile-append list-of-nfas))))
false
c81a52e2dee25fd2181331ede25758af5d832cd7
8a0660bd8d588f94aa429050bb8d32c9cd4290d5
/test/r6rs-test-suite/tests/r6rs/base.sls
c52b0d4c64cd446eab45e69737b108cdc62c0e1c
[ "BSD-2-Clause" ]
permissive
david135/sagittarius-scheme
dbec76f6b227f79713169985fc16ce763c889472
2fbd9d153c82e2aa342bfddd59ed54d43c5a7506
refs/heads/master
2016-09-02T02:44:31.668025
2013-12-21T07:24:08
2013-12-21T07:24:08
32,497,456
0
0
null
null
null
null
UTF-8
Scheme
false
false
50,636
sls
base.sls
#!r6rs (library (tests r6rs base) (export run-base-tests) (import (rnrs) (tests r6rs test)) (define (try-reals f but-not) (if (not (member 0 but-not)) (f 0)) (f -1.0) (f 0.0) (f 1.0) (f 1/2) (f (expt 2 30)) (f (expt 2 60)) (f (expt 2 90)) (f (- (expt 2 90))) (if (not (member +inf.0 but-not)) (f +inf.0)) (if (not (member -inf.0 but-not)) (f -inf.0)) (if (not (exists nan? but-not)) (f +nan.0))) (define (try-complexes f but-not) (try-reals f but-not) (f 1+2i)) (define (zero-or-nan? v) (or (equal? v 0) (nan? v))) (define (one-two-or-two-one? v) (or (equal? v '(1 2)) (equal? v '(2 1)))) ;; Based on tests from Ikarus: (define-syntax divmod-test/? (syntax-rules () [(_ x1 x2) (begin (test/values (div-and-mod x1 x2) (div x1 x2) (mod x1 x2)) (test/values (div0-and-mod0 x1 x2) (div0 x1 x2) (mod0 x1 x2)))])) (define-syntax divmod-test (syntax-rules () [(_ x1 x2) (begin (divmod-test/? x1 x2) (test (<= 0 (mod x1 x2)) #t) (test (< (mod x1 x2) (abs x2)) #t) (test (+ (* (div x1 x2) x2) (mod x1 x2)) x1) (test (<= (- (abs (/ x2 2))) (mod0 x1 x2)) #t) (test (< (mod0 x1 x2) (abs (/ x2 2))) #t) (test (+ (* (div0 x1 x2) x2) (mod0 x1 x2)) x1))])) (define-syntax try-bad-divs (syntax-rules () [(_ op) (begin (test/unspec-flonum-or-exn (op 1 0) &assertion) (test/unspec-flonum-or-exn (op 1 0.0) &assertion) (test/unspec-flonum-or-exn (op +inf.0 1) &assertion) (test/unspec-flonum-or-exn (op -inf.0 1) &assertion) (test/unspec-flonum-or-exn (op +nan.0 1) &assertion))])) (define-syntax test-string-to-number (syntax-rules () [(_ [str num] ...) (begin (test (string->number str) num) ...)])) (define-syntax test/approx-string-to-number (syntax-rules () [(_ [str num] ...) (begin (test/approx (string->number str) num) ...)])) ;; Definitions ---------------------------------------- (define add3 (lambda (x) (+ x 3))) (define first car) (define reverse-subtract (lambda (x y) (- y x))) (define add4 (let ((x 4)) (lambda (y) (+ x y)))) (define x 0) (define gen-counter (lambda () (let ((n 0)) (lambda () (set! n (+ n 1)) n)))) (define gen-loser (lambda () (let ((n 0)) (lambda () (set! n (+ n 1)) 27)))) (define (fac n) (if (not (integer-valued? n)) (assertion-violation 'fac "non-integral argument" n)) (if (negative? n) (assertion-violation 'fac "negative argument" n)) (letrec ((loop (lambda (n r) (if (zero? n) r (loop (- n 1) (* r n)))))) (loop n 1))) (define compose (lambda (f g) (lambda args (f (apply g args))))) (define list-length (lambda (obj) (call-with-current-continuation (lambda (return) (letrec ((r (lambda (obj) (cond ((null? obj) 0) ((pair? obj) (+ (r (cdr obj)) 1)) (else (return #f)))))) (r obj)))))) (define-syntax be-like-begin (syntax-rules () ((be-like-begin name) (define-syntax name (syntax-rules () ((name expr (... ...)) (begin expr (... ...)))))))) (be-like-begin sequence) (define p (cons 4 5)) (define-syntax p.car (identifier-syntax (car p))) (define-syntax kons (identifier-syntax cons)) ;; Not the same as in the report, because we avoid `set-car!': (define-syntax p2.car (identifier-syntax (_ (car p)) ((set! _ e) (set! p (cons e (cdr p)))))) ;; Expressions ---------------------------------------- (define (run-base-tests) ;; 11.2.1 (test (add3 3) 6) (test (first '(1 2)) 1) ;; 11.2.2 (test (let () (define even? (lambda (x) (or (= x 0) (odd? (- x 1))))) (define-syntax odd? (syntax-rules () ((odd? x) (not (even? x))))) (even? 10)) #t) (test (let () (define-syntax bind-to-zero (syntax-rules () ((bind-to-zero id) (define id 0)))) (bind-to-zero x) x) 0) ;; 11.3 (test (let ((x 5)) (define foo (lambda (y) (bar x y))) (define bar (lambda (a b) (+ (* a b) a))) (foo (+ x 3))) 45) (test (let ((x 5)) (letrec* ((foo (lambda (y) (bar x y))) (bar (lambda (a b) (+ (* a b) a)))) (foo (+ x 3)))) 45) ;; Sagittarius this will never succeesed bacause this type of check may ;; happen in compile time. so guard handler is not ready yet. #;(test/exn (letrec ([x y] [y x]) 'should-not-get-here) &assertion) (test (letrec ([x (if (eq? (cons 1 2) (cons 1 2)) x 1)]) x) 1) ;; 11.4.1 ;; (These tests are especially silly, since they really ;; have to work to get this far.) (test (quote a) 'a) (test (quote #(a b c)) (vector 'a 'b 'c)) (test (quote (+ 1 2)) '(+ 1 2)) (test '"abc" "abc") (test '145932 145932) (test 'a 'a) (test '#(a b c) (vector 'a 'b 'c)) (test '() (list)) (test '(+ 1 2) '(+ 1 2)) (test '(quote a) '(quote a)) (test ''a '(quote a)) ;; 11.4.2 ;; (test (lambda (x) (+ x x)) {a procedure}) (test ((lambda (x) (+ x x)) 4) 8) (test ((lambda (x) (define (p y) (+ y 1)) (+ (p x) x)) 5) 11) (test (reverse-subtract 7 10) 3) (test (add4 6) 10) (test ((lambda x x) 3 4 5 6) '(3 4 5 6)) (test ((lambda (x y . z) z) 3 4 5 6) '(5 6)) ;; 11.4.3 (test (if (> 3 2) 'yes 'no) 'yes) (test (if (> 2 3) 'yes 'no) 'no) (test (if (> 3 2) (- 3 2) (+ 3 2)) 1) (test/unspec (if #f #f)) ;; 11.4.4 (test (let ((x 2)) (+ x 1) (set! x 4) (+ x 1)) 5) ;; 11.4.5 (test (cond ((> 3 2) 'greater) ((< 3 2) 'less)) 'greater) (test (cond ((> 3 3) 'greater) ((< 3 3) 'less) (else 'equal)) 'equal) (test (cond ('(1 2 3) => cadr) (else #t)) 2) (test (case (* 2 3) ((2 3 5 7) 'prime) ((1 4 6 8 9) 'composite)) 'composite) (test/unspec (case (car '(c d)) ((a) 'a) ((b) 'b))) (test (case (car '(c d)) ((a e i o u) 'vowel) ((w y) 'semivowel) (else 'consonant)) 'consonant) (test (and (= 2 2) (> 2 1)) #t) (test (and (= 2 2) (< 2 1)) #f) (test (and 1 2 'c '(f g)) '(f g)) (test (and) #t) (test (or (= 2 2) (> 2 1)) #t) (test (or (= 2 2) (< 2 1)) #t) (test (or #f #f #f) #f) (test (or '(b c) (/ 3 0)) '(b c)) ;; 11.4.6 (test (let ((x 2) (y 3)) (* x y)) 6) (test (let ((x 2) (y 3)) (let ((x 7) (z (+ x y))) (* z x))) 35) (test (let ((x 2) (y 3)) (let* ((x 7) (z (+ x y))) (* z x))) 70) (test (letrec ((even? (lambda (n) (if (zero? n) #t (odd? (- n 1))))) (odd? (lambda (n) (if (zero? n) #f (even? (- n 1)))))) (even? 88)) #t) (test (letrec* ((p (lambda (x) (+ 1 (q (- x 1))))) (q (lambda (y) (if (zero? y) 0 (+ 1 (p (- y 1)))))) (x (p 5)) (y x)) y) 5) (test (let-values (((a b) (values 1 2)) ((c d) (values 3 4))) (list a b c d)) '(1 2 3 4)) (test (let-values (((a b . c) (values 1 2 3 4))) (list a b c)) '(1 2 (3 4))) (test (let ((a 'a) (b 'b) (x 'x) (y 'y)) (let-values (((a b) (values x y)) ((x y) (values a b))) (list a b x y))) '(x y a b)) (test (let ((a 'a) (b 'b) (x 'x) (y 'y)) (let*-values (((a b) (values x y)) ((x y) (values a b))) (list a b x y))) '(x y x y)) ;; 11.4.7 (test (begin (set! x 5) (+ x 1)) 6) (test/output/unspec (begin (display "4 plus 1 equals ") (display (+ 4 1))) "4 plus 1 equals 5") ;; 11.5 (test (eqv? 'a 'a) #t) (test (eqv? 'a 'b) #f) (test (eqv? 2 2) #t) (test (eqv? '() '()) #t) (test (eqv? 100000000 100000000) #t) (test (eqv? (cons 1 2) (cons 1 2)) #f) (test (eqv? (lambda () 1) (lambda () 2)) #f) (test (eqv? #f 'nil) #f) (test/unspec (let ((p (lambda (x) x))) (eqv? p p))) (test/unspec (eqv? "" "")) (test/unspec (eqv? '#() '#())) (test/unspec (eqv? (lambda (x) x) (lambda (x) x))) (test/unspec (eqv? (lambda (x) x) (lambda (y) y))) (test/unspec (eqv? +nan.0 +nan.0)) (test/unspec (let ((g (gen-counter))) (eqv? g g))) (test (eqv? (gen-counter) (gen-counter)) #f) (test/unspec (let ((g (gen-loser))) (eqv? g g))) (test/unspec (eqv? (gen-loser) (gen-loser))) (test/unspec (letrec ((f (lambda () (if (eqv? f g) 'both 'f))) (g (lambda () (if (eqv? f g) 'both 'g)))) (eqv? f g))) (test (letrec ((f (lambda () (if (eqv? f g) 'f 'both))) (g (lambda () (if (eqv? f g) 'g 'both)))) (eqv? f g)) #f) (test/unspec (eqv? '(a) '(a))) (test/unspec (eqv? "a" "a")) (test/unspec (eqv? '(b) (cdr '(a b)))) (test (let ((x '(a))) (eqv? x x)) #t) (test (eq? 'a 'a) #t) (test/unspec (eq? '(a) '(a))) (test (eq? (list 'a) (list 'a)) #f) (test/unspec (eq? "a" "a")) (test/unspec (eq? "" "")) (test (eq? '() '()) #t) (test/unspec (eq? 2 2)) (test/unspec (eq? #\A #\A)) (test (eq? car car) #t) (test/unspec (let ((n (+ 2 3))) (eq? n n))) (test (let ((x '(a))) (eq? x x)) #t) (test/unspec (let ((x '#())) (eq? x x))) (test/unspec (let ((p (lambda (x) x))) (eq? p p))) (test (equal? 'a 'a) #t) (test (equal? '(a) '(a)) #t) (test (equal? '(a (b) c) '(a (b) c)) #t) (test (equal? "abc" "abc") #t) (test (equal? 2 2) #t) (test (equal? (make-vector 5 'a) (make-vector 5 'a)) #t) (test (equal? '#vu8(1 2 3 4 5) (u8-list->bytevector '(1 2 3 4 5))) #t) (test/unspec (equal? (lambda (x) x) (lambda (y) y))) (test (let* ((x (list 'a)) (y (list 'a)) (z (list x y))) (list (equal? z (list y x)) (equal? z (list x x)))) '(#t #t)) ;; 11.6 (test (procedure? car) #t) (test (procedure? 'car) #f) (test (procedure? (lambda (x) (* x x))) #t) (test (procedure? '(lambda (x) (* x x))) #f) ;; 11.7.4 (test (complex? 3+4i) #t) (test (complex? 3) #t) (test (real? 3) #t) (test (real? -2.5+0.0i) #f) (test (real? -2.5+0i) #t) (test (real? -2.5) #t) (test (real? #e1e10) #t) (test (rational? 6/10) #t) (test (rational? 6/3) #t) (test (rational? 2) #t) (test (integer? 3+0i) #t) (test (integer? 3.0) #t) (test (integer? 8/4) #t) (test (number? +nan.0) #t) (test (complex? +nan.0) #t) (test (real? +nan.0) #t) (test (rational? +nan.0) #f) (test (complex? +inf.0) #t) (test (real? -inf.0) #t) (test (rational? -inf.0) #f) (test (integer? -inf.0) #f) (test (real-valued? +nan.0) #t) (test (real-valued? +nan.0+0i) #t) (test (real-valued? -inf.0) #t) (test (real-valued? 3) #t) (test (real-valued? -2.5+0.0i) #t) (test (real-valued? -2.5+0i) #t) (test (real-valued? -2.5) #t) (test (real-valued? #e1e10) #t) (test (rational-valued? +nan.0) #f) (test (rational-valued? -inf.0) #f) (test (rational-valued? 6/10) #t) (test (rational-valued? 6/10+0.0i) #t) (test (rational-valued? 6/10+0i) #t) (test (rational-valued? 6/3) #t) (test (integer-valued? 3+0i) #t) (test (integer-valued? 3+0.0i) #t) (test (integer-valued? 3.0) #t) (test (integer-valued? 3.0+0.0i) #t) (test (integer-valued? 8/4) #t) (test (exact? 5) #t) (test (inexact? +inf.0) #t) (test (inexact 2) 2.0) (test (inexact 2.0) 2.0) (test (exact 2) 2) (test (exact 2.0) 2) (for-each (lambda (x y) (let ([try-one (lambda (x y) (let ([try-x (lambda (x x2) (test (= x x2) #t) (test (< x x2) #f) (test (> x x2) #f) (test (<= x x2) #t) (test (>= x x2) #t))]) (try-x x x) (when (exact? x) (try-x x (inexact x)) (try-x (inexact x) x))) (test (< x y) #t) (test (<= x y) #t) (test (> x y) #f) (test (>= x y) #f) (test (< y x) #f) (test (<= y x) #f) (test (> y x) #t) (test (>= y x) #t))]) (try-one x y) (try-one (inexact x) y) (try-one x (inexact y)) (try-one (inexact x) (inexact y)))) (list 1/2 1 3/2 (expt 2 100) (expt 2 100)) (list 1 2 51/20 (expt 2 102) (/ (* 4 (expt 2 100)) 3))) (test (= +inf.0 +inf.0) #t) (test (= -inf.0 +inf.0) #f) (test (= -inf.0 -inf.0) #t) (test (= +nan.0 +nan.0) #f) (try-reals (lambda (x) (test (< -inf.0 x +inf.0) #t) (test (> +inf.0 x -inf.0) #t)) '(+inf.0 -inf.0 +nan.0)) (try-complexes (lambda (z) (test (= +nan.0 x) #f)) '()) (try-reals (lambda (x) (test (< +nan.0 x) #f) (test (> +nan.0 x) #f)) '()) (test (zero? +0.0) #t) (test (zero? -0.0) #t) (test (zero? 2.0) #f) (test (zero? -2.0) #f) (test (zero? +nan.0) #f) (test (positive? 10) #t) (test (positive? -10) #f) (test (positive? +inf.0) #t) (test (negative? -inf.0) #t) (test (positive? +nan.0) #f) (test (negative? 10) #f) (test (negative? -10) #t) (test (negative? +nan.0) #f) (test (finite? +inf.0) #f) (test (finite? 5) #t) (test (finite? 5.0) #t) (test (infinite? 5.0) #f) (test (infinite? +inf.0) #t) (test (nan? +nan.0) #t) (test (nan? +inf.0) #f) (test (nan? 1020.0) #f) (test (nan? 1020/3) #f) (test (odd? 5) #t) (test (odd? 50) #f) (test (odd? 5.0) #t) (test (odd? 50.0) #f) (test (even? 5) #f) (test (even? 50) #t) (test (even? 5.0) #f) (test (even? 50.0) #t) (test (max 3 4) 4) (test (max 3.9 4) 4.0) (try-reals (lambda (x) (test (max +inf.0 x) +inf.0) (test (min -inf.0 x) -inf.0)) '(+nan.0)) (test (+ 3 4) 7) (test (+ 3) 3) (test (+) 0) (test (+ 3.0 4) 7.0) (test (+ +inf.0 +inf.0) +inf.0) (test (+ +inf.0 -inf.0) +nan.0) (test (* 4) 4) (test (* 4 3) 12) (test (* 4 3.0) 12.0) (test (*) 1) (test (* 5 +inf.0) +inf.0) (test (* -5 +inf.0) -inf.0) (test (* +inf.0 +inf.0) +inf.0) (test (* +inf.0 -inf.0) -inf.0) (test (zero-or-nan? (* 0 +inf.0)) #t) (test (zero-or-nan? (* 0 +nan.0)) #t) (test (zero? (* 1.0 0)) #t) (try-reals (lambda (x) (test (+ +inf.0 x) +inf.0) (test (+ -inf.0 x) -inf.0)) '(+inf.0 -inf.0 +nan.0)) (try-reals (lambda (x) (test (+ +nan.0 x) +nan.0)) '()) (try-reals (lambda (x) (test (* +nan.0 x) +nan.0)) '(0)) (test (+ 0.0 -0.0) 0.0) (test (+ -0.0 0.0) 0.0) (test (+ 0.0 0.0) 0.0) (test (+ -0.0 -0.0) -0.0) (test (- 3 4) -1) (test (- 3 4 5) -6) (test (- 3) -3) (test (- +inf.0 +inf.0) +nan.0) (test (- 0.0) -0.0) (test (- -0.0) 0.0) (test (- 0.0 -0.0) 0.0) (test (- -0.0 0.0) -0.0) (test (- 0.0 0.0) 0.0) (test (- -0.0 -0.0) 0.0) (test (/ 3 4 5) 3/20) (test (/ 2 3) 2/3) (test (/ 3 2.0) 1.5) (test (/ 3) 1/3) (test (/ 0.0) +inf.0) (test (/ 1.0 0) +inf.0) (test (/ -1 0.0) -inf.0) (test (/ +inf.0) 0.0) (test/exn (/ 0 0) &assertion) (test/exn (/ 3 0) &assertion) (test (/ 0 3.5) 0.0) (test (/ 0 0.0) +nan.0) (test (/ 0.0 0) +nan.0) (test (/ 0.0 0.0) +nan.0) (test (abs 7) 7) (test (abs -7) 7) (test (abs (- (expt 2 100))) (expt 2 100)) (test (abs -inf.0) +inf.0) (test (div 123 10) 12) (test (mod 123 10) 3) (test (div 123 -10) -12) (test (mod 123 -10) 3) (test (div -123 10) -13) (test (mod -123 10) 7) (test (div -123 -10) 13) (test (mod -123 -10) 7) (test (div0 123 10) 12) (test (mod0 123 10) 3) (test (div0 123 -10) -12) (test (mod0 123 -10) 3) (test (div0 -123 10) -12) (test (mod0 -123 10) -3) (test (div0 -123 -10) 12) (test (mod0 -123 -10) -3) ;; `divmod-test' cases originally from Ikarus: (divmod-test +17 +3) (divmod-test +17 -3) (divmod-test -17 +3) (divmod-test -17 -3) (divmod-test +16 +3) (divmod-test +16 -3) (divmod-test -16 +3) (divmod-test -16 -3) (divmod-test +15 +3) (divmod-test +15 -3) (divmod-test -15 +3) (divmod-test -15 -3) (divmod-test +10 +4) (divmod-test +10 -4) (divmod-test -10 +4) (divmod-test -10 -4) (divmod-test +3 +5/6) (divmod-test -3 +5/6) (divmod-test +3 -5/6) (divmod-test -3 -5/6) (divmod-test +3 +7/11) (divmod-test -3 +7/11) (divmod-test +3 -7/11) (divmod-test -3 -7/11) (divmod-test (least-fixnum) +1) (divmod-test (least-fixnum) -1) (divmod-test (greatest-fixnum) +1) (divmod-test (greatest-fixnum) -1) (divmod-test (least-fixnum) +2) (divmod-test (least-fixnum) -2) (divmod-test (greatest-fixnum) +2) (divmod-test (greatest-fixnum) -2) (divmod-test 0 (least-fixnum)) (divmod-test 0 (greatest-fixnum)) (divmod-test +1 (least-fixnum)) (divmod-test +1 (greatest-fixnum)) (divmod-test -1 (least-fixnum)) (divmod-test -1 (greatest-fixnum)) (divmod-test +2 (least-fixnum)) (divmod-test +2 (greatest-fixnum)) (divmod-test -2 (least-fixnum)) (divmod-test -2 (greatest-fixnum)) (divmod-test (least-fixnum) (least-fixnum)) (divmod-test (greatest-fixnum) (least-fixnum)) (divmod-test (least-fixnum) (greatest-fixnum)) (divmod-test (greatest-fixnum) (greatest-fixnum)) (divmod-test +17.0 +3.0) (divmod-test +17.0 -3.0) (divmod-test -17.0 +3.0) (divmod-test -17.0 -3.0) (divmod-test +16.0 +3.0) (divmod-test +16.0 -3.0) (divmod-test -16.0 +3.0) (divmod-test -16.0 -3.0) (divmod-test +15.0 +3.0) (divmod-test +15.0 -3.0) (divmod-test -15.0 +3.0) (divmod-test -15.0 -3.0) (divmod-test +17.0 +3.5) (divmod-test +17.0 -3.5) (divmod-test -17.0 +3.5) (divmod-test -17.0 -3.5) (divmod-test +16.0 +3.5) (divmod-test +16.0 -3.5) (divmod-test -16.0 +3.5) (divmod-test -16.0 -3.5) (divmod-test +15.0 +3.5) (divmod-test +15.0 -3.5) (divmod-test -15.0 +3.5) (divmod-test -15.0 -3.5) (divmod-test/? +17.0 +nan.0) (divmod-test/? -17.0 +nan.0) (divmod-test/? +17.0 +inf.0) (divmod-test/? +17.0 -inf.0) (divmod-test/? -17.0 +inf.0) (divmod-test/? -17.0 -inf.0) (divmod-test +17.0 +3.0) (divmod-test +17.0 -3.0) (divmod-test -17.0 +3.0) (divmod-test -17.0 -3.0) (divmod-test +16.0 +3.0) (divmod-test +16.0 -3.0) (divmod-test -16.0 +3.0) (divmod-test -16.0 -3.0) (divmod-test +15.0 +3.0) (divmod-test +15.0 -3.0) (divmod-test -15.0 +3.0) (divmod-test -15.0 -3.0) (divmod-test +17.0 +3.5) (divmod-test +17.0 -3.5) (divmod-test -17.0 +3.5) (divmod-test -17.0 -3.5) (divmod-test +16.0 +3.5) (divmod-test +16.0 -3.5) (divmod-test -16.0 +3.5) (divmod-test -16.0 -3.5) (divmod-test +15.0 +3.5) (divmod-test +15.0 -3.5) (divmod-test -15.0 +3.5) (divmod-test -15.0 -3.5) (divmod-test +10.0 +4.0) (divmod-test +10.0 -4.0) (divmod-test -10.0 +4.0) (divmod-test -10.0 -4.0) (divmod-test/? +17.0 +nan.0) (divmod-test/? -17.0 +nan.0) (divmod-test/? +17.0 +inf.0) (divmod-test/? +17.0 -inf.0) (divmod-test/? -17.0 +inf.0) (divmod-test/? -17.0 -inf.0) (try-bad-divs div) (try-bad-divs mod) (try-bad-divs div-and-mod) (try-bad-divs div0) (try-bad-divs mod0) (try-bad-divs div0-and-mod0) (test (gcd 32 -36) 4) (test (gcd) 0) (test (lcm 32 -36) 288) (test (lcm 32.0 -36) 288.0) (test (lcm) 1) (test (numerator 6) 6) (test (numerator (/ 6 4)) 3) (test (denominator (/ 6 4)) 2) (test (denominator 6) 1) (test (denominator (inexact (/ 6 4))) 2.0) (test (floor -4.3) -5.0) (test (ceiling -4.3) -4.0) (test (truncate -4.3) -4.0) (test (round -4.3) -4.0) (test (floor 3.5) 3.0) (test (ceiling 3.5) 4.0) (test (truncate 3.5) 3.0) (test (round 3.5) 4.0) (test (round 7/2) 4) (test (round 7) 7) (test (floor +inf.0) +inf.0) (test (ceiling -inf.0) -inf.0) (test (round +nan.0) +nan.0) (test (rationalize (exact .3) 1/10) 1/3) (test/approx (rationalize .3 1/10) #i1/3) (test (rationalize +inf.0 3) +inf.0) (test (rationalize +inf.0 +inf.0) +nan.0) (test (rationalize 3 +inf.0) 0.0) (test/approx (exp 1) 2.718281828459045) (test (exp +inf.0) +inf.0) (test (exp -inf.0) 0.0) (test/approx (log 2.718281828459045) 1.0) (test (log +inf.0) +inf.0) (test (log 0.0) -inf.0) (test/approx (log 100 10) 2.0) (test/approx (log 1125899906842624 2) 50.0) (test/exn (log 0) &assertion) (test/approx (log -inf.0) +inf.0+3.141592653589793i) (test/approx (atan -inf.0) -1.5707963267948965) (test/approx (atan +inf.0) 1.5707963267948965) (test/approx (log -1.0+0.0i) 0.0+3.141592653589793i) (unless (eqv? 0.0 -0.0) (test/approx (log -1.0-0.0i) 0.0-3.141592653589793i)) (test/approx (sqrt 5) 2.23606797749979) (test/approx (sqrt -5) 0.0+2.23606797749979i) (test (sqrt +inf.0) +inf.0) (test (sqrt -inf.0) +inf.0i) (test/values (exact-integer-sqrt 0) 0 0) (test/values (exact-integer-sqrt 4) 2 0) (test/values (exact-integer-sqrt 5) 2 1) (test (expt 5 3) 125) (test (expt 5 -3) 1/125) (test (expt 5 0) 1) (test (expt 0 5) 0) (test/approx (expt 0 5+.0000312i) 0.0) ; R6RS (Sept 2007) appears to be wrong; also, test that result is inexact? (test/approx (expt 0.0 5+.0000312i) 0.0) (test/approx (expt 0 0.0) 1.0) (test/approx (expt 0.0 0.0) 1.0) (test/unspec-or-exn (expt 0 -5) &implementation-restriction) (test/unspec-or-exn (expt 0 -5+.0000312i) &implementation-restriction) (test (expt 0 0) 1) (test (expt 0.0 0.0) 1.0) (test/approx (make-rectangular 1.1 0.0) 1.1+0.0i) (test/approx (make-rectangular 1.1 2.2) 1.1+2.2i) (test/approx (make-polar 1.1 0.0) 1.1+0.0i) (test/approx (make-polar 1.1 2.2) [email protected]) (test/approx (real-part 1.1+2.2i) 1.1) (test/approx (imag-part 1.1+2.2i) 2.2) (test/approx (magnitude [email protected]) 1.1) (test (exact? (imag-part 0.0)) #t) (test (exact? (imag-part 1.0)) #t) (test (exact? (imag-part 1.1)) #t) (test (exact? (imag-part +nan.0)) #t) (test (exact? (imag-part +inf.0)) #t) (test (exact? (imag-part -inf.0)) #t) (test (zero? (imag-part 0.0)) #t) (test (zero? (imag-part 1.0)) #t) (test (zero? (imag-part 1.1)) #t) (test (zero? (imag-part +nan.0)) #t) (test (zero? (imag-part +inf.0)) #t) (test (zero? (imag-part -inf.0)) #t) (test/approx (angle [email protected]) 2.2) (test/approx (angle -1.0) 3.141592653589793) (test/approx (angle -1.0+0.0i) 3.141592653589793) (unless (eqv? 0.0 -0.0) (test/approx (angle -1.0-0.0i) -3.141592653589793)) (test (angle +inf.0) 0.0) (test/approx (angle -inf.0) 3.141592653589793) (test (magnitude (make-rectangular +inf.0 1)) +inf.0) (test (magnitude (make-rectangular -inf.0 1)) +inf.0) (test (magnitude (make-rectangular 1 +inf.0)) +inf.0) (test (magnitude (make-rectangular 1 -inf.0)) +inf.0) (test/approx (angle -1) 3.141592653589793) (for-each (lambda (n) (test (string->number (number->string n)) n) (test (string->number (number->string (inexact n) 10 5)) (inexact n)) (when (exact? n) (test (string->number (number->string n 16) 16) n) (test (string->number (string-append "#x" (number->string n 16))) n) (test (string->number (number->string n 8) 8) n) (test (string->number (string-append "#o" (number->string n 8))) n) (test (string->number (number->string n 2) 2) n) (test (string->number (string-append "#b" (number->string n 2))) n) (test (string->number (number->string n 10) 10) n) (test (string->number (string-append "#d" (number->string n 10))) n))) '(1 15 1023 -5 2.0 1/2 2e200 1+2i)) (test (string->number "nope") #f) (test (string->number "100") 100) (test (string->number "100" 16) 256) (test (string->number "1e2") 100.0) (test (string->number "0/0") #f) (test (string->number "+inf.0") +inf.0) (test (string->number "-inf.0") -inf.0) (test (string->number "+nan.0") +nan.0) ;; Originally from Ikarus: (test-string-to-number ("10" 10) ("1" 1) ("-17" -17) ("+13476238746782364786237846872346782364876238477" 13476238746782364786237846872346782364876238477) ("1/2" (/ 1 2)) ("-1/2" (/ 1 -2)) ("#x24" 36) ("#x-24" -36) ("#b+00000110110" 54) ("#b-00000110110/10" -27) ("#e10" 10) ("#e1" 1) ("#e-17" -17) ("#e#x24" 36) ("#e#x-24" -36) ("#e#b+00000110110" 54) ("#e#b-00000110110/10" -27) ("#x#e24" 36) ("#x#e-24" -36) ("#b#e+00000110110" 54) ("#b#e-00000110110/10" -27) ("#e1e1000" (expt 10 1000)) ("#e-1e1000" (- (expt 10 1000))) ("#e1e-1000" (expt 10 -1000)) ("#e-1e-1000" (- (expt 10 -1000)))) (test/approx-string-to-number ("#i1e100" (inexact (expt 10 100))) ("#i1e1000" (inexact (expt 10 1000))) ("#i-1e1000" (inexact (- (expt 10 1000)))) ("1e100" (inexact (expt 10 100))) ("1.0e100" (inexact (expt 10 100))) ("1.e100" (inexact (expt 10 100))) ("0.1e100" (inexact (expt 10 99))) (".1e100" (inexact (expt 10 99))) ("+1e100" (inexact (expt 10 100))) ("+1.0e100" (inexact (expt 10 100))) ("+1.e100" (inexact (expt 10 100))) ("+0.1e100" (inexact (expt 10 99))) ("+.1e100" (inexact (expt 10 99))) ("-1e100" (inexact (- (expt 10 100)))) ("-1.0e100" (inexact (- (expt 10 100)))) ("-1.e100" (inexact (- (expt 10 100)))) ("-0.1e100" (inexact (- (expt 10 99)))) ("-.1e100" (inexact (- (expt 10 99))))) ;; 11.8 (test (not #t) #f) (test (not 3) #f) (test (not (list 3)) #f) (test (not #f) #t) (test (not '()) #f) (test (not (list)) #f) (test (not 'nil) #f) (test (boolean? #f) #t) (test (boolean? 0) #f) (test (boolean? '()) #f) (test (boolean=? #f #f) #t) (test (boolean=? #t #t) #t) (test (boolean=? #t #f) #f) (test (boolean=? #f #t) #f) (test (boolean=? #t #t #f) #f) (test (boolean=? #t #t #t #t) #t) ;; 11.9 (test (pair? '(a . b)) #t) (test (pair? '(a b c)) #t) (test (pair? '()) #f) (test (pair? '#(a b)) #f) (test (cons 'a '()) '(a)) (test (cons '(a) '(b c d)) '((a) b c d)) (test (cons "a" '(b c)) '("a" b c)) (test (cons 'a 3) '(a . 3)) (test (cons '(a b) 'c) '((a b) . c)) (test (car '(a b c)) 'a) (test (car '((a) b c d)) '(a)) (test (car '(1 . 2)) 1) (test/exn (car '()) &assertion) (test (cdr '((a) b c d)) '(b c d)) (test (cdr '(1 . 2)) 2) (test/exn (cdr '()) &assertion) (test (cadr '(1 2)) 2) (test (cddr '(1 2)) '()) (test (cdar '((1) 2)) '()) (test (caar '((1) 2)) 1) (test (cadar '((1 2))) 2) (test (cddar '((1 2))) '()) (test (cdaar '(((1) 2))) '()) (test (caaar '(((1) 2))) 1) (test (caddr '(0 1 2)) 2) (test (cdddr '(0 1 2)) '()) (test (cdadr '(0 (1) 2)) '()) (test (caadr '(0 (1) 2)) 1) (test (cadaar '(((1 2)))) 2) (test (cddaar '(((1 2)))) '()) (test (cdaaar '((((1) 2)))) '()) (test (caaaar '((((1) 2)))) 1) (test (caddar '((0 1 2))) 2) (test (cdddar '((0 1 2))) '()) (test (cdadar '((0 (1) 2))) '()) (test (caadar '((0 (1) 2))) 1) (test (cadadr '(- (1 2))) 2) (test (cddadr '(- (1 2))) '()) (test (cdaadr '(- ((1) 2))) '()) (test (caaadr '(- ((1) 2))) 1) (test (cadddr '(- 0 1 2)) 2) (test (cddddr '(- 0 1 2)) '()) (test (cdaddr '(- 0 (1) 2)) '()) (test (caaddr '(- 0 (1) 2)) 1) (test (null? '()) #t) (test (null? '(1)) #f) (test (null? #f) #f) (test (list? '(a b c)) #t) (test (list? '()) #t) (test (list? '(a . b)) #f) (test (list 'a (+ 3 4) 'c) '(a 7 c)) (test (list) '()) (test (length '(a b c)) 3) (test (length '(a (b) (c d e))) 3) (test (length '()) 0) (test (append '(x) '(y)) '(x y)) (test (append '(a) '(b c d)) '(a b c d)) (test (append '(a (b)) '((c))) '(a (b) (c))) (test (append '(a b) '(c . d)) '(a b c . d)) (test (append '() 'a) 'a) (test (reverse '(a b c)) '(c b a)) (test (reverse '(a (b c) d (e (f)))) '((e (f)) d (b c) a)) (test (list-tail '(a b c d) 2) '(c d)) (test (list-tail '(a b . c) 2) 'c) (test (list-ref '(a b c d) 2) 'c) (test (list-ref '(a b c . d) 2) 'c) (test (map cadr '((a b) (d e) (g h))) '(b e h)) (test (map (lambda (n) (expt n n)) '(1 2 3 4 5)) '(1 4 27 256 3125)) (test (map + '(1 2 3) '(4 5 6)) '(5 7 9)) (test (one-two-or-two-one? (let ((count 0)) (map (lambda (ignored) (set! count (+ count 1)) count) '(a b)))) #t) (test (let ((v (make-vector 5))) (for-each (lambda (i) (vector-set! v i (* i i))) '(0 1 2 3 4)) v) '#(0 1 4 9 16)) (test/unspec (for-each (lambda (x) x) '(1 2 3 4))) (test/unspec (for-each even? '())) ;; 11.10 (test (symbol? 'foo) #t) (test (symbol? (car '(a b))) #t) (test (symbol? "bar") #f) (test (symbol? 'nil) #t) (test (symbol? '()) #f) (test (symbol? #f) #f) (test (symbol=? 'a 'a) #t) (test (symbol=? 'a 'A) #f) (test (symbol=? 'a 'b) #f) (test (symbol=? 'a 'a 'b) #f) (test (symbol=? 'a 'a 'a 'a) #t) (test (symbol->string 'flying-fish) "flying-fish") (test (symbol->string 'Martin) "Martin") (test (symbol->string (string->symbol "Malvina")) "Malvina") (test (eq? 'mISSISSIppi 'mississippi) #f) (test (string->symbol "mISSISSIppi") 'mISSISSIppi) (test (eq? 'bitBlt (string->symbol "bitBlt")) #t) (test (eq? 'JollyWog (string->symbol (symbol->string 'JollyWog))) #t) (test (string=? "K. Harper, M.D." (symbol->string (string->symbol "K. Harper, M.D."))) #t) ;; 11.11 (test (char? #\a) #t) (test (char? 'a) #f) (test (char? 65) #f) (test (integer->char 32) #\space) (test (integer->char #xDF) #\xDF) (test (integer->char #x10AAAA) #\x10AAAA) (test (char->integer (integer->char 5000)) 5000) (test/exn (integer->char #xD800) &assertion) (test (char=? #\z #\xDF) #f) (test (char=? #\z #\z) #t) (test (char<? #\z #\z) #f) (test (char<? #\z #\xDF) #t) (test (char<? #\xDF #\z) #f) (test (char<? #\z #\Z) #f) (test (char<=? #\z #\z) #t) (test (char<=? #\z #\xDF) #t) (test (char<=? #\xDF #\z) #f) (test (char<=? #\z #\Z) #f) (test (char>? #\z #\z) #f) (test (char>? #\z #\xDF) #f) (test (char>? #\xDF #\z) #t) (test (char>? #\z #\Z) #t) (test (char>=? #\z #\z) #t) (test (char>=? #\z #\xDF) #f) (test (char>=? #\xDF #\z) #t) (test (char>=? #\z #\Z) #t) ;; 11.12 (test (string? "apple") #t) (test (string? #vu8(1 2)) #f) (test (string? #\a) #f) (test (string? 77) #f) (test (string-length (make-string 10)) 10) (test (string-length (make-string 10 #\a)) 10) (test (string-ref (make-string 10 #\a) 0) #\a) (test (string-ref (make-string 10 #\a) 5) #\a) (test (string-ref (make-string 10 #\a) 9) #\a) (test (string=? "Strasse" "Strasse") #t) (test (string=? "Stra\xDF;e" "Strasse") #f) (test (string=? "Strasse" "Strasse" "Stra\xDF;e") #f) (test (string=? "Strasse" "Stra\xDF;e" "Strasse") #f) (test (string=? "Stra\xDF;e" "Strasse" "Strasse") #f) (test (string=? "Strasse" "Strasse" "Strasse") #t) (test (string<? "z" "z") #f) (test (string<? "z" "\xDF;") #t) (test (string<? "\xDF;" "z") #f) (test (string<? "z" "zz") #t) (test (string<? "z" "Z") #f) (test (string<=? "z" "\xDF;") #t) (test (string<=? "\xDF;" "z") #f) (test (string<=? "z" "zz") #t) (test (string<=? "z" "Z") #f) (test (string<=? "z" "z") #t) (test (string<? "z" "z") #f) (test (string>? "z" "\xDF;") #f) (test (string>? "\xDF;" "z") #t) (test (string>? "z" "zz") #f) (test (string>? "z" "Z") #t) (test (string>=? "z" "\xDF;") #f) (test (string>=? "\xDF;" "z") #t) (test (string>=? "z" "zz") #f) (test (string>=? "z" "Z") #t) (test (string>=? "z" "z") #t) (test (substring "apple" 0 3) "app") (test (substring "apple" 1 3) "pp") (test (substring "apple" 3 5) "le") (test (string-append "apple") "apple") (test (string-append "apple" "banana") "applebanana") (test (string-append "apple" "banana" "cherry") "applebananacherry") (test (string->list "apple") (list #\a #\p #\p #\l #\e)) (test (list->string (list #\a #\p #\p #\l #\e)) "apple") (let ([accum '()]) (test/unspec (string-for-each (lambda (a) (set! accum (cons a accum))) "elppa")) (test accum '(#\a #\p #\p #\l #\e)) (test/unspec (string-for-each (lambda (a b) (set! accum (cons (list a b) accum))) "elppa" "ananb")) (test accum '((#\a #\b) (#\p #\n) (#\p #\a) (#\l #\n) (#\e #\a) #\a #\p #\p #\l #\e)) (test/unspec (string-for-each (lambda (a b c) (set! accum c)) "elppa" "ananb" "chery")) (test accum #\y)) (test "apple" (string-copy "apple")) (let ([s "apple"]) (test (eq? s (string-copy s)) #f)) ;; 11.13 (test (vector? '#(1 2 3)) #t) (test (vector? "apple") #f) (test (vector-length (make-vector 10)) 10) (test (vector-length (make-vector 10 'x)) 10) (test (vector-ref (make-vector 10 'x) 0) 'x) (test (vector-ref (make-vector 10 'x) 5) 'x) (test (vector-ref (make-vector 10 'x) 9) 'x) (test '#(0 (2 2 2 2) "Anna") (vector 0 '(2 2 2 2) "Anna")) (test (vector 'a 'b 'c) '#(a b c)) (test (vector-ref '#(1 1 2 3 5 8 13 21) 5) 8) (test (let ((vec (vector 0 '(2 2 2 2) "Anna"))) (vector-set! vec 1 '("Sue" "Sue")) vec) '#(0 ("Sue" "Sue") "Anna")) (test/unspec-or-exn (vector-set! '#(0 1 2) 1 "doe") &assertion) (test (vector->list '#(dah dah didah)) '(dah dah didah)) (test (list->vector '(dididit dah)) '#(dididit dah)) (let ([vec (vector 'x 'y 'z)]) (vector-fill! vec 10.1) (test vec '#(10.1 10.1 10.1))) (test (vector-map (lambda (x) (+ 1 x)) '#(1 2 3)) '#(2 3 4)) (test (vector-map (lambda (x y) (- x y)) '#(3 4 5) '#(0 -1 2)) '#(3 5 3)) (test (vector-map (lambda (x y f) (f (- x y))) '#(3 4 5) '#(0 -1 2) (vector - * /)) '#(-3 5 1/3)) (let ([accum '()]) (test/unspec (vector-for-each (lambda (a) (set! accum (cons a accum))) '#(e l p p a))) (test accum '(a p p l e)) (test/unspec (vector-for-each (lambda (a b) (set! accum (cons (list a b) accum))) '#(e l p p a) '#(a n a n b))) (test accum '((a b) (p n) (p a) (l n) (e a) a p p l e)) (test/unspec (vector-for-each (lambda (a b c) (set! accum c)) '#(e l p p a) '#(a n a n b) '#(c h e r y))) (test accum 'y)) ;; 11.14 (for-each (lambda (error) (test/exn (error 'apple "bad" 'worm) &who) (test/exn (error #f "bad" 'worm) &message) (test/exn (error 'apple "bad" 'worm) &irritants) (test/exn (error 'apple "bad") &irritants)) (list error assertion-violation)) (test/exn (error 'apple "bad" 'worm) &error) (test/exn (assertion-violation 'apple "bad" 'worm) &assertion) (test (condition-message (guard (v [#t v]) (assertion-violation 'apple "bad" 'worm))) "bad") (test (condition-who (guard (v [#t v]) (assertion-violation 'apple "bad" 'worm))) 'apple) (test (condition-irritants (guard (v [#t v]) (assertion-violation 'apple "bad" 'worm))) '(worm)) (test (who-condition? (guard (v [#t v]) (assertion-violation #f "bad" 'worm))) #f) (test (error? (guard (v [#t v]) (assertion-violation #f "bad" 'worm))) #f) (test (error? (guard (v [#t v]) (error #f "bad" 'worm))) #t) (test (fac 5) 120) (test/exn (fac 4.5) &assertion) (test/exn (fac -3) &assertion) (test/exn (fac -3) &message) ;; 11.15 (test (apply + (list 3 4)) 7) (test/approx ((compose sqrt *) 12 75) 30) (test (call-with-current-continuation (lambda (exit) (for-each (lambda (x) (if (negative? x) (exit x))) '(54 0 37 -3 245 19)) #t)) -3) (test (call/cc (lambda (exit) (for-each (lambda (x) (if (negative? x) (exit x))) '(54 0 37 -3 245 19)) #t)) -3) (test (list-length '(1 2 3 4)) 4) (test (list-length '(a b . c)) #f) (test/values (values)) (test (values 1) 1) (test/values (values 1 2 3) 1 2 3) (test (call-with-current-continuation procedure?) #t) (test (call-with-values (lambda () (values 4 5)) (lambda (a b) b)) 5) (test (call-with-values * -) -1) (test (let ((path '()) (c #f)) (let ((add (lambda (s) (set! path (cons s path))))) (dynamic-wind (lambda () (add 'connect)) (lambda () (add (call-with-current-continuation (lambda (c0) (set! c c0) 'talk1)))) (lambda () (add 'disconnect))) (if (< (length path) 4) (c 'talk2) (reverse path)))) '(connect talk1 disconnect connect talk2 disconnect)) (test (let ((n 0)) (call-with-current-continuation (lambda (k) (dynamic-wind (lambda () (set! n (+ n 1)) (k)) (lambda () (set! n (+ n 2))) (lambda () (set! n (+ n 4)))))) n) 1) (test (let ((n 0)) (call-with-current-continuation (lambda (k) (dynamic-wind values (lambda () (dynamic-wind values (lambda () (set! n (+ n 1)) (k)) (lambda () (set! n (+ n 2)) (k)))) (lambda () (set! n (+ n 4)))))) n) 7) ;; 11.16 (test (let loop ((numbers '(3 -2 1 6 -5)) (nonneg '()) (neg '())) (cond ((null? numbers) (list nonneg neg)) ((>= (car numbers) 0) (loop (cdr numbers) (cons (car numbers) nonneg) neg)) ((< (car numbers) 0) (loop (cdr numbers) nonneg (cons (car numbers) neg))))) '((6 1 3) (-5 -2))) ;; 11.17 (test `(list ,(+ 1 2) 4) '(list 3 4)) (test (let ((name 'a)) `(list ,name ',name)) '(list a (quote a))) (test `(a ,(+ 1 2) ,@(map abs '(4 -5 6)) b) '(a 3 4 5 6 b)) (test `((foo ,(- 10 3)) ,@(cdr '(c)) . ,(car '(cons))) '((foo 7) . cons)) (test `#(10 5 ,(- 4) ,@(map - '(16 9)) 8) '#(10 5 -4 -16 -9 8)) (test (let ((name 'foo)) `((unquote name name name))) '(foo foo foo)) (test (let ((name '(foo))) `((unquote-splicing name name name))) '(foo foo foo)) (test (let ((q '((append x y) (sqrt 9)))) ``(foo ,,@q)) '`(foo (unquote (append x y) (sqrt 9)))) (test (let ((x '(2 3)) (y '(4 5))) `(foo (unquote (append x y) (- 9)))) '(foo (2 3 4 5) -9)) (test `(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f) '(a `(b ,(+ 1 2) ,(foo 4 d) e) f)) (test (let ((name1 'x) (name2 'y)) `(a `(b ,,name1 ,',name2 d) e)) '(a `(b ,x ,'y d) e)) (test (let ((a 3)) `((1 2) ,a ,4 ,'five 6)) '((1 2) 3 4 five 6)) (test (let ((a 3)) `((1 2) ,a ,4 ,'five 6)) (let ((a 3)) (cons '(1 2) (cons a (cons 4 (cons 'five '(6))))))) ;; 11.18 (test (let-syntax ((when (syntax-rules () ((when test stmt1 stmt2 ...) (if test (begin stmt1 stmt2 ...)))))) (let ((if #t)) (when if (set! if 'now)) if)) 'now) (test (let ((x 'outer)) (let-syntax ((m (syntax-rules () ((m) x)))) (let ((x 'inner)) (m)))) 'outer) (test (let () (let-syntax ((def (syntax-rules () ((def stuff ...) (define stuff ...))))) (def foo 42)) foo) 42) (test (let () (let-syntax ()) 5) 5) (test (letrec-syntax ((my-or (syntax-rules () ((my-or) #f) ((my-or e) e) ((my-or e1 e2 ...) (let ((temp e1)) (if temp temp (my-or e2 ...))))))) (let ((x #f) (y 7) (temp 8) (let odd?) (if even?)) (my-or x (let temp) (if y) y))) 7) (test (let ((f (lambda (x) (+ x 1)))) (let-syntax ((f (syntax-rules () ((f x) x))) (g (syntax-rules () ((g x) (f x))))) (list (f 1) (g 1)))) '(1 2)) (test (let ((f (lambda (x) (+ x 1)))) (letrec-syntax ((f (syntax-rules () ((f x) x))) (g (syntax-rules () ((g x) (f x))))) (list (f 1) (g 1)))) '(1 1)) (test (sequence 1 2 3 4) 4) (test (let ((=> #f)) (cond (#t => 'ok))) 'ok) (test p.car 4) ; (test/exn (set! p.car 15) &syntax) - not a runtime test (test/unspec (set! p2.car 15)) (test p2.car 15) (test p '(15 . 5)) (test (kons 1 2) '(1 . 2)) ;;; ))
true
e61d1327f78b055dd35cffd20d7b9fa68d39683b
3132831399eacc4bd1ae519aac18a1342dec7282
/Exams/1st/04.scm
12c1a3f8d013dc2a2e59844bdd4342c367b65b98
[]
no_license
TsHristov/Functional-Programming-FMI-2017
ba3f1d46ed276f0fa4da7e6c396e4f50c1291e0d
58176d53d507c6df70465e1fcfbcd2c67f8af0aa
refs/heads/master
2021-09-05T18:49:14.471004
2018-01-30T11:08:00
2018-01-30T11:08:00
105,808,452
6
0
null
null
null
null
UTF-8
Scheme
false
false
635
scm
04.scm
(define (root tree) (car tree)) (define (left tree) (cadr tree)) (define (right tree) (caddr tree)) (define empty-tree '()) (define empty-tree? null?) (define (isomorphic? tree) (define (isomorphic-subtrees? left-tree right-tree) (or (empty-tree? tree) (or (and (empty-tree? left-tree) (empty-tree? right-tree)) (and (not (empty-tree? left-tree)) (not (empty-tree? right-tree)) (equal? (root left-tree) (root right-tree)) (and (isomorphic-subtrees? (left left-tree) (left right-tree)) (isomorphic-subtrees? (right left-tree) (right right-tree))))))) (isomorphic-subtrees? (left tree) (right tree)))
false
eadaa1dba08dacc3ffef066cc3451824e6d5f0f7
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
/ext/crypto/tests/testvectors/hmac/hmac_sha256_test.scm
ac41912c8661caae45d7f4792158f1037dfb1bca
[ "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "MIT", "BSD-2-Clause" ]
permissive
ktakashi/sagittarius-scheme
0a6d23a9004e8775792ebe27a395366457daba81
285e84f7c48b65d6594ff4fbbe47a1b499c9fec0
refs/heads/master
2023-09-01T23:45:52.702741
2023-08-31T10:36:08
2023-08-31T10:36:08
41,153,733
48
7
NOASSERTION
2022-07-13T18:04:42
2015-08-21T12:07:54
Scheme
UTF-8
Scheme
false
false
58,326
scm
hmac_sha256_test.scm
(test-hmac "hmac_sha256_test" :algorithm "HMACSHA256" :key-size 256 :tag-size 256 :tests '(#(1 "empty message" #vu8(30 34 92 175 185 3 57 187 161 178 64 118 212 32 108 62 121 195 85 128 93 133 22 130 188 129 139 170 79 90 119 121) #vu8() #vu8(177 117 181 125 137 234 108 182 6 251 51 99 242 83 138 189 115 164 192 11 74 19 134 144 91 172 128 144 4 207 25 51) #t ()) #(2 "short message" #vu8(129 89 253 21 19 60 217 100 201 166 150 76 148 240 234 38 154 128 111 217 244 63 13 165 139 108 209 179 61 24 155 42) #vu8(119) #vu8(223 197 16 93 94 236 247 174 123 139 141 227 147 14 118 89 232 76 65 114 242 85 81 66 241 229 104 252 24 114 173 147) #t ()) #(3 "short message" #vu8(133 167 203 170 232 37 187 130 201 182 246 197 194 175 90 192 61 31 109 170 99 210 169 60 24 153 72 236 65 185 222 217) #vu8(165 155) #vu8(15 226 241 59 186 33 152 246 221 161 160 132 190 146 142 48 78 156 177 106 86 188 11 123 147 154 7 50 128 36 67 115) #t ()) #(4 "short message" #vu8(72 243 2 147 52 229 92 251 213 116 204 199 101 251 44 54 133 170 177 244 131 125 35 55 8 116 163 230 52 195 167 109) #vu8(199 184 178) #vu8(108 19 247 155 178 213 182 249 163 21 254 143 214 203 181 203 129 122 102 6 135 0 157 236 205 136 195 119 66 158 89 109) #t ()) #(5 "short message" #vu8(222 139 91 91 47 9 100 91 228 126 203 100 7 164 225 217 198 179 58 227 194 210 37 23 211 53 125 160 53 122 49 57) #vu8(204 2 29 101) #vu8(232 117 56 235 22 126 98 215 203 35 102 144 255 63 3 74 156 18 212 23 170 141 250 105 77 116 5 249 225 248 95 232) #t ()) #(6 "short message" #vu8(183 147 137 16 245 24 241 50 5 202 20 146 198 105 0 26 20 255 145 60 138 180 160 220 53 100 231 65 142 145 41 124) #vu8(164 166 239 110 189) #vu8(1 169 63 78 210 22 208 178 128 137 99 1 227 102 170 103 178 94 107 106 90 110 132 242 145 161 51 145 198 228 150 197) #t ()) #(7 "short message" #vu8(27 185 151 255 77 232 165 163 145 222 92 8 163 59 194 199 194 137 30 71 173 91 156 99 17 1 146 247 139 152 254 120) #vu8(102 126 1 93 247 252) #vu8(6 181 216 197 57 35 35 168 2 188 92 221 11 60 82 116 84 168 115 217 101 28 54 136 54 234 164 173 152 43 165 70) #t ()) #(8 "short message" #vu8(50 253 237 163 159 152 180 244 66 108 45 42 192 10 181 221 75 250 187 104 243 17 68 114 86 237 109 61 58 81 177 84) #vu8(65 99 169 247 126 65 245) #vu8(27 1 3 114 159 72 194 119 43 177 50 174 249 235 214 221 106 175 201 20 93 246 213 197 20 178 51 238 146 239 74 0) #t ()) #(9 "short message" #vu8(35 62 79 222 231 11 204 32 35 91 105 119 221 252 5 176 223 102 245 99 93 130 124 102 229 166 60 219 22 162 73 56) #vu8(253 178 238 75 109 26 10 194) #vu8(18 11 38 238 19 85 193 52 194 98 81 60 121 34 222 182 196 253 144 48 61 228 205 97 185 249 205 8 242 45 110 24) #t ()) #(10 "short message" #vu8(185 132 198 115 78 11 209 43 23 55 178 252 122 27 56 3 180 223 236 64 33 64 165 123 158 204 195 84 20 174 102 27) #vu8(222 165 132 208 226 161 74 213 253) #vu8(136 188 34 130 229 252 228 126 198 217 137 83 149 205 71 255 249 26 12 220 88 154 143 213 109 141 52 70 22 83 58 61) #t ()) #(11 "short message" #vu8(208 202 241 69 106 197 226 85 250 106 253 97 167 157 200 199 22 245 53 138 41 138 80 130 113 54 63 225 255 152 53 97) #vu8(24 38 29 200 6 145 60 83 70 102) #vu8(246 120 240 129 216 60 241 38 173 107 213 44 45 255 215 134 33 79 81 156 71 69 43 133 169 116 88 208 193 12 62 229) #t ()) #(12 "short message" #vu8(131 91 200 36 30 216 23 115 94 201 211 208 226 223 76 23 62 228 221 237 74 142 240 192 74 150 196 143 17 130 4 99) #vu8(38 248 8 62 148 75 172 240 78 154 77) #vu8(224 228 108 215 209 167 91 61 16 40 147 218 100 222 244 110 69 83 8 118 31 29 144 135 134 98 140 167 238 34 160 235) #t ()) #(13 "short message" #vu8(5 95 149 201 70 27 8 9 87 94 204 223 165 205 208 98 117 242 93 48 145 92 78 184 219 64 225 172 211 171 117 145) #vu8(191 183 214 160 141 186 165 34 95 50 8 135) #vu8(231 109 92 140 7 10 107 60 72 36 233 243 66 220 48 86 230 56 25 80 158 29 239 152 181 133 174 186 13 99 138 0) #t ()) #(14 "short message" #vu8(228 15 122 62 184 141 222 196 198 52 126 164 214 118 16 117 108 130 200 235 204 35 118 41 191 135 60 202 188 50 152 74) #vu8(127 228 63 235 199 132 116 100 158 69 191 153 178) #vu8(170 87 208 32 170 36 173 130 52 114 194 184 15 242 208 207 71 95 125 224 6 143 154 89 232 17 47 237 229 58 53 129) #t ()) #(15 "short message" #vu8(176 32 173 29 225 193 65 247 236 97 94 229 112 21 33 119 63 155 35 46 77 6 55 108 56 40 148 206 81 166 31 72) #vu8(129 199 88 26 25 75 94 113 180 17 70 165 130 193) #vu8(244 92 114 96 60 193 96 192 118 47 112 52 7 132 74 119 129 223 224 241 221 240 170 244 204 216 32 94 148 70 154 237) #t ()) #(16 "short message" #vu8(159 63 214 26 16 82 2 100 142 207 246 7 76 149 229 2 193 197 26 205 50 236 83 138 92 206 137 239 132 31 121 137) #vu8(42 118 242 172 218 206 66 227 183 121 114 73 70 145 44) #vu8(2 38 238 19 204 5 226 52 1 53 179 244 178 122 157 161 161 96 246 23 15 232 5 218 221 152 163 113 30 201 196 33) #t ()) #(17 "" #vu8(111 163 83 134 140 130 229 222 238 218 199 240 148 113 166 27 247 73 171 84 152 35 158 148 126 1 46 238 60 130 215 196) #vu8(174 237 62 77 76 185 187 182 13 72 46 152 193 38 192 245) #vu8(158 215 240 231 56 18 162 122 135 163 128 142 224 200 154 100 86 73 158 131 89 116 186 87 197 170 178 160 216 198 158 147) #t ()) #(18 "" #vu8(83 0 72 148 148 202 134 34 28 145 214 217 83 149 42 225 165 224 151 19 157 201 207 17 121 194 245 100 51 117 56 36) #vu8(144 254 166 207 43 216 17 180 73 243 51 238 146 51 229 118 151) #vu8(91 105 44 186 19 181 79 255 195 173 203 176 224 21 204 1 31 191 214 18 53 48 63 240 173 42 73 119 80 131 191 34) #t ()) #(19 "" #vu8(56 62 124 92 19 71 106 98 38 132 35 239 5 0 71 159 158 134 226 54 197 160 129 198 68 145 137 230 175 223 42 245) #vu8(50 2 112 90 248 159 149 85 197 64 176 225 39 105 17 208 25 113 171 178 195 92 120 178) #vu8(78 73 1 89 43 164 100 118 64 141 117 132 53 199 209 180 137 210 104 154 253 132 206 170 238 120 191 185 31 217 57 29) #t ()) #(20 "" #vu8(24 110 36 138 216 36 225 235 147 50 154 127 220 213 101 182 203 78 175 63 133 185 11 145 7 119 18 141 140 83 141 39) #vu8(146 239 159 245 47 70 236 204 126 56 185 238 25 253 45 227 179 119 38 200 230 206 158 27 150 219 93 218 76 49 121 2) #vu8(63 193 215 61 212 168 133 140 31 195 216 196 163 243 62 213 173 12 112 33 0 56 57 74 89 2 203 38 254 40 115 72) #t ()) #(21 "long message" #vu8(40 133 92 126 252 133 50 217 37 103 48 9 51 204 28 162 208 88 111 85 220 201 240 84 252 202 47 5 37 79 191 127) #vu8(156 9 32 127 240 230 229 130 203 55 71 220 169 84 201 77 69 192 94 147 241 230 242 17 121 207 14 37 180 206 222 116 181 71 157 50 245 22 105 53 200 111 4 65 144 88 101) #vu8(120 140 5 137 0 15 183 240 181 213 31 21 150 71 43 201 236 65 52 33 164 61 249 110 227 43 2 181 210 117 255 227) #t ()) #(22 "long message" #vu8(142 84 12 179 12 148 131 106 226 165 149 15 53 93 72 42 112 2 226 85 32 126 148 253 163 247 239 26 9 144 19 160) #vu8(214 80 15 149 225 18 98 227 8 191 61 244 223 75 133 95 51 232 87 86 61 69 67 241 149 99 154 10 23 180 66 235 159 220 193 54 125 46 238 117 200 248 5 115 11 137 41 15) #vu8(57 105 126 112 206 116 31 235 51 222 220 6 159 0 181 98 127 217 184 55 209 12 189 213 182 209 156 251 213 17 221 44) #t ()) #(23 "long message" #vu8(105 197 13 82 116 53 129 136 207 244 192 250 231 66 36 61 78 138 94 91 165 93 148 255 64 237 217 15 106 67 221 16) #vu8(26 197 37 90 255 5 40 40 216 234 33 179 118 241 235 221 75 184 121 148 153 19 144 4 5 174 188 232 62 72 254 182 129 59 94 156 137 249 69 1 168 173 228 27 38 184 21 197 33) #vu8(75 11 77 4 22 250 46 17 88 111 191 167 251 17 38 30 105 153 29 250 52 1 155 152 147 214 154 43 232 193 252 128) #t ()) #(24 "long message" #vu8(35 32 155 124 90 173 203 209 63 114 121 175 26 134 211 199 174 143 23 157 27 202 170 208 223 249 161 83 2 231 141 191) #vu8(132 189 172 55 225 175 53 217 53 100 4 226 120 125 71 236 229 131 72 222 167 106 74 70 232 170 222 52 99 212 219 140 148 160 81 190 55 51 179 141 117 105 132 134 93 86 198 14 128 37 241 94 63 150 143 9 62 127 183 235 199 227 17 137 197 105 45 21 237 66 86 115 123 155 24 148 229 128 149 3 170 161 201 152 63 176 150 170 33 145 99 97 238 182 239 69 91 18 151 35 161 161 221 249 222 221 234 32 133 41 166 72) #vu8(74 133 196 121 209 101 13 189 115 188 82 72 7 74 85 255 80 33 139 221 170 141 31 221 170 244 73 70 220 25 174 251) #t ()) #(25 "long message" #vu8(124 156 198 103 202 225 117 244 72 250 169 102 71 49 150 51 178 212 133 49 55 58 231 211 22 196 77 221 139 159 105 207) #vu8(146 51 193 215 59 73 140 81 6 255 136 149 30 7 185 101 44 176 221 174 116 7 55 236 32 92 152 118 208 148 151 139 252 148 127 125 201 55 17 159 214 169 57 21 177 155 98 89 88 167 162 35 99 170 42 195 63 184 105 237 22 179 3 51 106 183 64 160 73 138 45 246 106 101 153 218 113 0 148 72 26 123 84 75 217 85 182 249 113 53 186 70 115 64 29 178 219 20 74 110 40 112 65 228 122 81 237 155 107 169 86 193 53 8 193 192 194 83 16 16 82 57 171 115 98 158 48) #vu8(202 27 128 68 29 51 57 9 194 187 48 118 150 80 5 80 81 237 32 241 125 232 238 149 60 185 7 10 245 108 112 79) #t ()) #(26 "long message" #vu8(130 49 69 64 86 78 163 206 48 89 30 151 246 139 38 2 222 64 250 41 247 115 194 80 131 39 71 27 131 72 232 196) #vu8(106 109 47 69 206 191 39 87 174 22 234 51 198 134 23 103 29 119 248 253 248 11 237 143 197 205 197 200 183 8 107 210 142 126 179 238 204 113 99 73 17 4 229 48 148 85 230 127 131 101 121 184 42 29 163 191 89 145 168 226 178 241 137 164 158 5 112 14 70 196 9 237 93 231 119 128 165 243 137 227 241 61 173 64 108 157 85 103 83 41 197 201 33 240 112 52 24 9 55 192 246 239 52 162 48 139 111 243 225 160 233 220 30 166 95 86 50 115 14 135 68 209 219 44 64 166 89 91) #vu8(9 0 179 230 83 93 52 249 14 44 51 87 117 232 107 243 142 231 227 210 111 182 12 217 205 246 57 235 52 150 185 76) #t ()) #(27 "long message" #vu8(209 21 172 201 166 54 145 82 65 121 95 72 133 32 82 224 123 81 39 58 226 68 130 81 236 29 13 15 152 7 243 219) #vu8(105 109 36 86 222 133 63 160 40 244 134 254 244 55 182 182 209 181 48 168 71 94 41 157 179 169 0 90 233 206 248 64 25 133 183 211 30 23 46 143 67 156 205 26 209 236 68 201 184 107 120 243 242 67 193 48 91 83 188 33 171 173 122 143 197 37 99 17 191 211 76 152 227 125 253 198 73 231 174 75 218 8 207 41 148 176 99 192 199 16 110 208 176 42 31 72 175 145 145 203 251 13 106 149 59 126 4 50 125 254 140 147 119 156 181 116 186 156 186 87 93 1 103 78 131 98 26 160 197 244 0 214 230 205 36 179 1 227 60 159 51 3 231 59 243 87 64 140 27 232 108 36 137 192 157 233 152 255 46 243 45 245 84 241 36 125 147 19 206 26 113 96 17 93 6 244 193 141 101 86 255 121 134 239 138 85 226 173 207 162 126 76 105 199 28 194 255 1 99 158 157 73 189 158 208 104 127 83 15 254 176 137 1 50 69 125 242 8 128 129 188 74 47 127 10 159 77 206 162 200 13 153 29 183 243 116 122 24 3 215 97 154 175 61 211 130 198 149 54 160 188 219 147 28 190) #vu8(130 249 41 119 240 182 5 234 173 165 16 255 206 181 58 215 95 222 22 168 2 159 27 117 180 6 168 66 112 219 184 183) #t ()) #(28 "Flipped bit 0 in tag" #vu8(0 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) #vu8() #vu8(210 139 66 9 109 128 244 95 130 107 68 169 213 96 125 231 36 150 164 21 211 244 161 168 200 142 59 185 218 141 193 203) #f ()) #(29 "Flipped bit 0 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(217 185 159 39 9 163 202 116 23 44 190 147 130 76 31 41 178 58 12 30 156 33 189 133 31 242 210 195 157 190 241 78) #f ()) #(30 "Flipped bit 1 in tag" #vu8(0 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) #vu8() #vu8(209 139 66 9 109 128 244 95 130 107 68 169 213 96 125 231 36 150 164 21 211 244 161 168 200 142 59 185 218 141 193 203) #f ()) #(31 "Flipped bit 1 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(218 185 159 39 9 163 202 116 23 44 190 147 130 76 31 41 178 58 12 30 156 33 189 133 31 242 210 195 157 190 241 78) #f ()) #(32 "Flipped bit 7 in tag" #vu8(0 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) #vu8() #vu8(83 139 66 9 109 128 244 95 130 107 68 169 213 96 125 231 36 150 164 21 211 244 161 168 200 142 59 185 218 141 193 203) #f ()) #(33 "Flipped bit 7 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(88 185 159 39 9 163 202 116 23 44 190 147 130 76 31 41 178 58 12 30 156 33 189 133 31 242 210 195 157 190 241 78) #f ()) #(34 "Flipped bit 8 in tag" #vu8(0 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) #vu8() #vu8(211 138 66 9 109 128 244 95 130 107 68 169 213 96 125 231 36 150 164 21 211 244 161 168 200 142 59 185 218 141 193 203) #f ()) #(35 "Flipped bit 8 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 184 159 39 9 163 202 116 23 44 190 147 130 76 31 41 178 58 12 30 156 33 189 133 31 242 210 195 157 190 241 78) #f ()) #(36 "Flipped bit 31 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 137 109 128 244 95 130 107 68 169 213 96 125 231 36 150 164 21 211 244 161 168 200 142 59 185 218 141 193 203) #f ()) #(37 "Flipped bit 31 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 167 9 163 202 116 23 44 190 147 130 76 31 41 178 58 12 30 156 33 189 133 31 242 210 195 157 190 241 78) #f ()) #(38 "Flipped bit 32 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 108 128 244 95 130 107 68 169 213 96 125 231 36 150 164 21 211 244 161 168 200 142 59 185 218 141 193 203) #f ()) #(39 "Flipped bit 32 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 8 163 202 116 23 44 190 147 130 76 31 41 178 58 12 30 156 33 189 133 31 242 210 195 157 190 241 78) #f ()) #(40 "Flipped bit 33 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 111 128 244 95 130 107 68 169 213 96 125 231 36 150 164 21 211 244 161 168 200 142 59 185 218 141 193 203) #f ()) #(41 "Flipped bit 33 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 11 163 202 116 23 44 190 147 130 76 31 41 178 58 12 30 156 33 189 133 31 242 210 195 157 190 241 78) #f ()) #(42 "Flipped bit 63 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 223 130 107 68 169 213 96 125 231 36 150 164 21 211 244 161 168 200 142 59 185 218 141 193 203) #f ()) #(43 "Flipped bit 63 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 244 23 44 190 147 130 76 31 41 178 58 12 30 156 33 189 133 31 242 210 195 157 190 241 78) #f ()) #(44 "Flipped bit 64 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 95 131 107 68 169 213 96 125 231 36 150 164 21 211 244 161 168 200 142 59 185 218 141 193 203) #f ()) #(45 "Flipped bit 64 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 116 22 44 190 147 130 76 31 41 178 58 12 30 156 33 189 133 31 242 210 195 157 190 241 78) #f ()) #(46 "Flipped bit 71 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 95 2 107 68 169 213 96 125 231 36 150 164 21 211 244 161 168 200 142 59 185 218 141 193 203) #f ()) #(47 "Flipped bit 71 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 116 151 44 190 147 130 76 31 41 178 58 12 30 156 33 189 133 31 242 210 195 157 190 241 78) #f ()) #(48 "Flipped bit 77 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 95 130 75 68 169 213 96 125 231 36 150 164 21 211 244 161 168 200 142 59 185 218 141 193 203) #f ()) #(49 "Flipped bit 77 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 116 23 12 190 147 130 76 31 41 178 58 12 30 156 33 189 133 31 242 210 195 157 190 241 78) #f ()) #(50 "Flipped bit 80 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 95 130 107 69 169 213 96 125 231 36 150 164 21 211 244 161 168 200 142 59 185 218 141 193 203) #f ()) #(51 "Flipped bit 80 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 116 23 44 191 147 130 76 31 41 178 58 12 30 156 33 189 133 31 242 210 195 157 190 241 78) #f ()) #(52 "Flipped bit 96 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 95 130 107 68 169 212 96 125 231 36 150 164 21 211 244 161 168 200 142 59 185 218 141 193 203) #f ()) #(53 "Flipped bit 96 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 116 23 44 190 147 131 76 31 41 178 58 12 30 156 33 189 133 31 242 210 195 157 190 241 78) #f ()) #(54 "Flipped bit 97 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 95 130 107 68 169 215 96 125 231 36 150 164 21 211 244 161 168 200 142 59 185 218 141 193 203) #f ()) #(55 "Flipped bit 97 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 116 23 44 190 147 128 76 31 41 178 58 12 30 156 33 189 133 31 242 210 195 157 190 241 78) #f ()) #(56 "Flipped bit 103 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 95 130 107 68 169 85 96 125 231 36 150 164 21 211 244 161 168 200 142 59 185 218 141 193 203) #f ()) #(57 "Flipped bit 103 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 116 23 44 190 147 2 76 31 41 178 58 12 30 156 33 189 133 31 242 210 195 157 190 241 78) #f ()) #(58 "Flipped bit 248 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 95 130 107 68 169 213 96 125 231 36 150 164 21 211 244 161 168 200 142 59 185 218 141 193 202) #f ()) #(59 "Flipped bit 248 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 116 23 44 190 147 130 76 31 41 178 58 12 30 156 33 189 133 31 242 210 195 157 190 241 79) #f ()) #(60 "Flipped bit 249 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 95 130 107 68 169 213 96 125 231 36 150 164 21 211 244 161 168 200 142 59 185 218 141 193 201) #f ()) #(61 "Flipped bit 249 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 116 23 44 190 147 130 76 31 41 178 58 12 30 156 33 189 133 31 242 210 195 157 190 241 76) #f ()) #(62 "Flipped bit 254 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 95 130 107 68 169 213 96 125 231 36 150 164 21 211 244 161 168 200 142 59 185 218 141 193 139) #f ()) #(63 "Flipped bit 254 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 116 23 44 190 147 130 76 31 41 178 58 12 30 156 33 189 133 31 242 210 195 157 190 241 14) #f ()) #(64 "Flipped bit 255 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 95 130 107 68 169 213 96 125 231 36 150 164 21 211 244 161 168 200 142 59 185 218 141 193 75) #f ()) #(65 "Flipped bit 255 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 116 23 44 190 147 130 76 31 41 178 58 12 30 156 33 189 133 31 242 210 195 157 190 241 206) #f ()) #(66 "Flipped bits 0 and 64 in tag" #vu8(0 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) #vu8() #vu8(210 139 66 9 109 128 244 95 131 107 68 169 213 96 125 231 36 150 164 21 211 244 161 168 200 142 59 185 218 141 193 203) #f ()) #(67 "Flipped bits 0 and 64 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(217 185 159 39 9 163 202 116 22 44 190 147 130 76 31 41 178 58 12 30 156 33 189 133 31 242 210 195 157 190 241 78) #f ()) #(68 "Flipped bits 31 and 63 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 137 109 128 244 223 130 107 68 169 213 96 125 231 36 150 164 21 211 244 161 168 200 142 59 185 218 141 193 203) #f ()) #(69 "Flipped bits 31 and 63 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 167 9 163 202 244 23 44 190 147 130 76 31 41 178 58 12 30 156 33 189 133 31 242 210 195 157 190 241 78) #f ()) #(70 "Flipped bits 63 and 127 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 223 130 107 68 169 213 96 125 103 36 150 164 21 211 244 161 168 200 142 59 185 218 141 193 203) #f ()) #(71 "Flipped bits 63 and 127 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 244 23 44 190 147 130 76 31 169 178 58 12 30 156 33 189 133 31 242 210 195 157 190 241 78) #f ()) #(72 "all bits of tag flipped" #vu8(0 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) #vu8() #vu8(44 116 189 246 146 127 11 160 125 148 187 86 42 159 130 24 219 105 91 234 44 11 94 87 55 113 196 70 37 114 62 52) #f ()) #(73 "all bits of tag flipped" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(39 70 96 216 246 92 53 139 232 211 65 108 125 179 224 214 77 197 243 225 99 222 66 122 224 13 45 60 98 65 14 177) #f ()) #(74 "Tag changed to all zero" #vu8(0 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) #vu8() #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) #f ()) #(75 "Tag changed to all zero" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) #f ()) #(76 "tag changed to all 1" #vu8(0 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) #vu8() #vu8(255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255) #f ()) #(77 "tag changed to all 1" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255) #f ()) #(78 "msbs changed in tag" #vu8(0 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) #vu8() #vu8(83 11 194 137 237 0 116 223 2 235 196 41 85 224 253 103 164 22 36 149 83 116 33 40 72 14 187 57 90 13 65 75) #f ()) #(79 "msbs changed in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(88 57 31 167 137 35 74 244 151 172 62 19 2 204 159 169 50 186 140 158 28 161 61 5 159 114 82 67 29 62 113 206) #f ()) #(80 "lsbs changed in tag" #vu8(0 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) #vu8() #vu8(210 138 67 8 108 129 245 94 131 106 69 168 212 97 124 230 37 151 165 20 210 245 160 169 201 143 58 184 219 140 192 202) #f ()) #(81 "lsbs changed in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(217 184 158 38 8 162 203 117 22 45 191 146 131 77 30 40 179 59 13 31 157 32 188 132 30 243 211 194 156 191 240 79) #f ()))) (test-hmac "hmac_sha256_test" :algorithm "HMACSHA256" :key-size 256 :tag-size 128 :tests '(#(82 "empty message" #vu8(123 249 229 54 182 106 33 92 34 35 63 226 218 170 116 58 137 139 154 203 159 120 2 222 112 180 14 61 110 67 239 151) #vu8() #vu8(244 96 85 133 148 151 71 222 38 243 238 152 167 56 177 114) #t ()) #(83 "short message" #vu8(231 84 7 108 234 179 253 175 79 155 202 183 212 240 223 12 187 175 188 135 115 27 143 155 124 210 22 100 114 232 238 188) #vu8(64) #vu8(13 192 13 114 23 187 175 232 215 139 249 97 24 155 143 210) #t ()) #(84 "short message" #vu8(234 59 1 107 221 56 125 214 77 131 124 113 104 56 8 243 53 219 220 83 89 138 78 168 197 249 82 71 63 175 175 95) #vu8(102 1) #vu8(255 41 107 54 141 59 240 89 204 72 104 47 105 73 204 170) #t ()) #(85 "short message" #vu8(115 212 112 150 55 133 125 175 171 106 216 178 176 165 27 6 82 71 23 254 223 16 2 150 100 79 124 253 170 225 128 91) #vu8(241 211 0) #vu8(45 2 189 28 37 177 254 82 177 234 208 115 116 214 232 131) #t ()) #(86 "short message" #vu8(213 200 27 57 157 76 13 21 131 161 61 165 109 230 210 220 69 166 110 123 71 194 74 177 25 46 36 109 201 97 221 119) #vu8(42 230 60 191) #vu8(77 158 139 221 249 183 161 33 131 9 213 152 138 161 176 217) #t ()) #(87 "short message" #vu8(37 33 32 63 160 221 223 89 216 55 178 131 15 135 177 170 97 249 88 21 93 243 202 77 29 242 69 124 180 40 77 200) #vu8(175 58 1 94 161) #vu8(203 138 75 65 51 80 180 47 74 195 83 60 199 244 120 100) #t ()) #(88 "short message" #vu8(102 90 2 188 38 90 102 208 23 117 9 29 165 103 38 182 102 139 253 144 60 183 175 102 251 27 120 168 160 98 228 60) #vu8(63 86 147 93 239 63) #vu8(28 252 231 69 219 28 167 222 154 29 68 32 230 18 202 85) #t ()) #(89 "short message" #vu8(250 205 117 178 34 33 56 0 71 48 91 201 129 245 112 226 161 175 56 146 142 167 226 5 158 58 245 252 107 130 180 147) #vu8(87 187 134 190 237 21 111) #vu8(11 222 13 12 117 109 240 157 79 109 168 27 41 154 58 223) #t ()) #(90 "short message" #vu8(80 90 169 136 25 128 158 246 59 154 54 138 30 139 194 233 34 218 69 176 60 224 45 154 121 102 177 80 6 219 162 213) #vu8(46 78 126 247 40 254 17 175) #vu8(64 106 92 43 211 230 169 89 95 155 125 255 96 141 89 167) #t ()) #(91 "short message" #vu8(249 66 9 56 66 128 139 164 127 100 228 39 247 53 29 222 107 149 70 230 109 228 231 214 10 166 243 40 24 39 18 207) #vu8(133 42 33 217 40 72 230 39 199) #vu8(11 27 249 233 141 10 121 79 165 92 9 182 62 37 121 159) #t ()) #(92 "short message" #vu8(100 190 22 43 57 198 229 241 254 217 195 45 159 103 77 154 140 222 110 170 36 67 33 77 134 189 74 31 181 59 129 180) #vu8(25 90 59 41 47 147 186 255 10 44) #vu8(113 243 63 96 33 217 8 88 202 219 19 83 215 251 232 215) #t ()) #(93 "short message" #vu8(178 89 165 85 212 75 138 32 197 72 158 47 56 57 45 218 166 190 158 53 185 131 59 103 225 181 253 246 203 62 76 108) #vu8(175 215 49 23 51 12 110 133 40 166 228) #vu8(75 141 118 55 46 190 94 92 170 86 202 78 92 89 205 211) #t ()) #(94 "short message" #vu8(44 111 198 45 170 119 186 140 104 129 179 221 105 137 137 143 239 100 102 99 204 123 10 61 184 34 138 112 123 133 242 220) #vu8(15 245 77 107 103 89 18 12 46 138 81 227) #vu8(197 128 197 66 132 106 150 232 78 167 119 1 119 132 85 191) #t ()) #(95 "short message" #vu8(171 171 129 93 81 223 41 247 64 228 226 7 159 183 152 224 21 40 54 230 171 87 209 83 106 232 146 158 82 192 110 184) #vu8(240 5 141 65 42 16 78 83 216 32 185 90 127) #vu8(19 205 176 5 5 147 56 240 242 142 45 140 225 175 93 10) #t ()) #(96 "short message" #vu8(61 93 161 175 131 247 40 116 88 191 247 167 101 30 165 216 219 114 37 148 1 51 63 107 130 9 105 150 221 126 175 25) #vu8(170 204 54 151 47 24 48 87 145 159 245 123 73 225) #vu8(189 153 62 68 40 203 192 226 117 228 216 11 111 82 3 99) #t ()) #(97 "short message" #vu8(193 155 223 49 76 108 246 67 129 66 84 103 244 42 239 161 124 28 201 53 139 225 108 227 27 29 33 72 89 206 134 170) #vu8(93 6 106 146 195 0 233 182 221 214 58 124 19 174 51) #vu8(134 201 244 221 224 178 87 167 5 58 123 3 199 80 68 9) #t ()) #(98 "" #vu8(97 46 131 120 67 206 174 127 97 212 150 37 250 167 231 73 79 146 83 226 12 179 173 206 166 134 81 43 4 57 54 205) #vu8(204 55 250 225 95 116 90 47 64 226 200 177 146 242 179 141) #vu8(185 107 202 202 250 195 0 148 241 138 197 3 158 123 54 86) #t ()) #(99 "" #vu8(115 33 111 175 208 2 45 13 110 226 113 152 178 39 37 120 250 143 4 221 159 68 70 127 187 100 55 170 69 100 27 247) #vu8(213 36 123 143 108 62 220 191 177 213 145 209 62 206 35 210 245) #vu8(110 89 124 76 56 97 163 128 192 104 84 180 70 252 42 135) #t ()) #(100 "" #vu8(4 39 167 14 37 117 40 243 171 112 100 11 186 26 93 225 44 243 136 93 212 200 226 132 251 187 85 254 179 82 148 165) #vu8(19 147 127 133 68 244 66 112 208 17 117 160 17 247 103 14 147 250 107 167 239 2 51 110) #vu8(247 49 170 242 240 64 35 214 33 241 4 149 52 70 121 160) #t ()) #(101 "" #vu8(150 225 228 137 111 178 205 5 241 51 166 161 0 188 86 9 167 172 60 166 216 23 33 233 34 218 221 105 173 7 168 146) #vu8(145 161 126 77 252 195 22 106 26 221 38 255 14 124 18 5 110 138 101 79 40 166 222 36 244 186 115 156 235 91 91 24) #vu8(149 36 62 177 169 212 72 23 74 228 252 207 74 83 235 254) #t ()) #(102 "long message" #vu8(65 32 21 103 190 78 110 160 109 226 41 95 208 230 232 167 216 98 187 87 49 24 148 245 37 216 173 234 187 164 163 228) #vu8(88 200 199 59 221 63 53 12 151 71 120 22 234 228 208 120 156 147 105 192 233 156 36 137 2 199 0 188 41 237 152 100 37 152 94 179 250 85 112 155 115 191 98 12 217 177 203) #vu8(52 51 103 32 127 113 66 93 143 129 243 17 11 4 5 246) #t ()) #(103 "long message" #vu8(100 158 55 62 104 30 245 46 60 16 172 38 84 132 117 9 50 169 145 143 40 251 130 79 124 181 10 218 179 151 129 254) #vu8(57 180 71 189 58 1 152 60 28 183 97 180 86 214 144 0 148 140 235 135 5 98 165 54 18 106 13 24 168 231 228 155 22 222 143 230 114 241 61 8 8 216 183 217 87 137 153 23) #vu8(21 22 24 238 196 245 3 243 182 59 83 157 224 165 137 102) #t ()) #(104 "long message" #vu8(123 13 35 127 123 83 110 44 105 80 153 14 97 179 97 179 132 51 61 218 105 0 69 197 145 50 26 78 63 121 116 127) #vu8(61 98 131 209 28 2 25 181 37 98 14 155 245 185 253 136 125 63 15 112 122 203 31 189 255 171 13 151 165 198 208 127 197 71 118 46 14 125 215 196 58 211 95 171 28 121 15 128 71) #vu8(206 32 28 13 207 220 63 43 239 54 6 9 163 31 177 158) #t ()) #(105 "long message" #vu8(23 201 38 99 116 31 1 46 91 182 113 78 97 76 45 21 89 72 97 127 16 147 98 105 217 84 197 138 186 42 230 45) #vu8(127 221 106 21 200 97 208 49 63 102 53 215 125 197 94 17 95 241 140 138 176 99 181 208 62 171 71 46 236 168 122 55 129 136 242 88 19 81 92 249 11 108 255 169 74 143 243 107 41 214 86 3 234 179 251 210 170 149 0 178 97 225 132 4 152 147 220 108 162 1 11 236 172 22 48 83 242 17 7 11 221 166 33 184 189 138 247 126 69 2 104 96 59 82 219 52 201 11 232 54 223 235 221 239 66 48 63 114 78 99 191 15) #vu8(118 232 223 217 77 180 175 157 121 217 113 142 236 70 203 45) #t ()) #(106 "long message" #vu8(66 76 107 34 96 111 204 9 74 232 47 197 211 203 228 132 23 76 34 17 179 236 119 128 145 202 195 74 142 56 161 82) #vu8(217 111 240 98 226 73 14 142 12 84 197 168 184 158 133 178 90 102 217 61 124 43 147 189 254 248 70 183 13 56 103 39 70 164 185 136 208 143 21 165 197 39 202 79 44 128 229 63 124 106 192 82 27 197 126 190 56 32 145 128 203 249 52 224 187 235 88 207 182 61 117 218 100 175 65 208 156 225 116 175 24 150 244 37 34 145 15 206 211 94 160 0 64 46 149 253 58 199 170 109 94 10 107 83 59 8 121 188 70 96 25 179 165 230 177 110 75 209 234 108 223 201 204 193 214 240 240) #vu8(237 167 9 199 0 151 20 195 114 208 214 166 61 253 228 105) #t ()) #(107 "long message" #vu8(21 213 83 200 218 67 61 83 205 199 241 80 135 167 3 73 202 171 87 179 121 164 7 137 40 206 155 153 48 46 49 166) #vu8(214 192 197 59 115 247 79 180 38 173 253 193 67 215 13 183 247 168 248 237 50 162 250 239 38 60 249 171 17 117 55 182 185 209 114 139 209 0 12 31 40 144 108 108 230 173 33 134 43 250 77 104 156 26 142 190 56 104 185 146 9 139 127 152 27 42 245 24 154 106 222 223 245 58 108 112 200 54 147 245 200 214 56 90 154 138 77 202 1 124 87 22 172 77 91 151 101 197 202 42 181 249 134 126 2 121 81 152 192 185 82 126 7 208 138 245 45 188 185 28 235 61 139 65 42 43 36 2) #vu8(140 161 64 43 248 252 35 68 42 194 6 123 233 37 184 40) #t ()) #(108 "long message" #vu8(255 229 89 70 138 16 49 223 179 206 210 227 129 231 75 88 33 163 109 154 191 95 46 89 137 90 127 220 160 250 86 160) #vu8(35 136 153 168 74 60 241 82 2 161 251 239 71 65 225 51 251 36 192 9 160 205 131 133 76 109 29 124 146 102 212 195 234 254 109 29 252 24 241 56 69 204 218 215 254 39 118 39 181 253 95 242 85 92 230 223 222 30 224 120 84 10 10 53 144 198 217 191 47 182 59 169 175 190 147 128 231 151 190 124 208 23 100 92 90 54 19 238 243 142 248 158 59 116 97 230 231 0 255 43 77 238 245 99 108 157 33 152 177 67 247 151 202 24 32 163 220 197 212 98 235 244 168 196 192 158 178 2 162 53 146 235 149 36 8 44 121 173 218 143 205 86 210 86 4 26 38 191 143 82 57 98 186 145 28 229 165 120 101 112 214 91 227 196 223 114 46 216 131 3 2 6 95 235 223 148 71 21 41 138 31 187 125 16 182 141 125 162 191 136 147 36 49 76 229 30 129 92 127 191 3 170 10 131 88 175 243 168 110 183 163 63 154 73 35 102 13 179 4 126 121 59 235 176 198 145 143 67 149 212 0 56 23 35 253 174 40 50 195 110 252 142 54 138 104 243 15 99 81 195 188 148 44 213 96) #vu8(168 48 179 19 244 147 109 234 86 163 174 253 106 62 190 125) #t ()) #(109 "Flipped bit 0 in tag" #vu8(0 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) #vu8() #vu8(210 139 66 9 109 128 244 95 130 107 68 169 213 96 125 231) #f ()) #(110 "Flipped bit 0 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(217 185 159 39 9 163 202 116 23 44 190 147 130 76 31 41) #f ()) #(111 "Flipped bit 1 in tag" #vu8(0 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) #vu8() #vu8(209 139 66 9 109 128 244 95 130 107 68 169 213 96 125 231) #f ()) #(112 "Flipped bit 1 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(218 185 159 39 9 163 202 116 23 44 190 147 130 76 31 41) #f ()) #(113 "Flipped bit 7 in tag" #vu8(0 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) #vu8() #vu8(83 139 66 9 109 128 244 95 130 107 68 169 213 96 125 231) #f ()) #(114 "Flipped bit 7 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(88 185 159 39 9 163 202 116 23 44 190 147 130 76 31 41) #f ()) #(115 "Flipped bit 8 in tag" #vu8(0 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) #vu8() #vu8(211 138 66 9 109 128 244 95 130 107 68 169 213 96 125 231) #f ()) #(116 "Flipped bit 8 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 184 159 39 9 163 202 116 23 44 190 147 130 76 31 41) #f ()) #(117 "Flipped bit 31 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 137 109 128 244 95 130 107 68 169 213 96 125 231) #f ()) #(118 "Flipped bit 31 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 167 9 163 202 116 23 44 190 147 130 76 31 41) #f ()) #(119 "Flipped bit 32 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 108 128 244 95 130 107 68 169 213 96 125 231) #f ()) #(120 "Flipped bit 32 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 8 163 202 116 23 44 190 147 130 76 31 41) #f ()) #(121 "Flipped bit 33 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 111 128 244 95 130 107 68 169 213 96 125 231) #f ()) #(122 "Flipped bit 33 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 11 163 202 116 23 44 190 147 130 76 31 41) #f ()) #(123 "Flipped bit 63 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 223 130 107 68 169 213 96 125 231) #f ()) #(124 "Flipped bit 63 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 244 23 44 190 147 130 76 31 41) #f ()) #(125 "Flipped bit 64 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 95 131 107 68 169 213 96 125 231) #f ()) #(126 "Flipped bit 64 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 116 22 44 190 147 130 76 31 41) #f ()) #(127 "Flipped bit 71 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 95 2 107 68 169 213 96 125 231) #f ()) #(128 "Flipped bit 71 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 116 151 44 190 147 130 76 31 41) #f ()) #(129 "Flipped bit 77 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 95 130 75 68 169 213 96 125 231) #f ()) #(130 "Flipped bit 77 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 116 23 12 190 147 130 76 31 41) #f ()) #(131 "Flipped bit 80 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 95 130 107 69 169 213 96 125 231) #f ()) #(132 "Flipped bit 80 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 116 23 44 191 147 130 76 31 41) #f ()) #(133 "Flipped bit 96 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 95 130 107 68 169 212 96 125 231) #f ()) #(134 "Flipped bit 96 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 116 23 44 190 147 131 76 31 41) #f ()) #(135 "Flipped bit 97 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 95 130 107 68 169 215 96 125 231) #f ()) #(136 "Flipped bit 97 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 116 23 44 190 147 128 76 31 41) #f ()) #(137 "Flipped bit 103 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 95 130 107 68 169 85 96 125 231) #f ()) #(138 "Flipped bit 103 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 116 23 44 190 147 2 76 31 41) #f ()) #(139 "Flipped bit 120 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 95 130 107 68 169 213 96 125 230) #f ()) #(140 "Flipped bit 120 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 116 23 44 190 147 130 76 31 40) #f ()) #(141 "Flipped bit 121 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 95 130 107 68 169 213 96 125 229) #f ()) #(142 "Flipped bit 121 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 116 23 44 190 147 130 76 31 43) #f ()) #(143 "Flipped bit 126 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 95 130 107 68 169 213 96 125 167) #f ()) #(144 "Flipped bit 126 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 116 23 44 190 147 130 76 31 105) #f ()) #(145 "Flipped bit 127 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 95 130 107 68 169 213 96 125 103) #f ()) #(146 "Flipped bit 127 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 116 23 44 190 147 130 76 31 169) #f ()) #(147 "Flipped bits 0 and 64 in tag" #vu8(0 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) #vu8() #vu8(210 139 66 9 109 128 244 95 131 107 68 169 213 96 125 231) #f ()) #(148 "Flipped bits 0 and 64 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(217 185 159 39 9 163 202 116 22 44 190 147 130 76 31 41) #f ()) #(149 "Flipped bits 31 and 63 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 137 109 128 244 223 130 107 68 169 213 96 125 231) #f ()) #(150 "Flipped bits 31 and 63 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 167 9 163 202 244 23 44 190 147 130 76 31 41) #f ()) #(151 "Flipped bits 63 and 127 in tag" #vu8(0 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) #vu8() #vu8(211 139 66 9 109 128 244 223 130 107 68 169 213 96 125 103) #f ()) #(152 "Flipped bits 63 and 127 in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(216 185 159 39 9 163 202 244 23 44 190 147 130 76 31 169) #f ()) #(153 "all bits of tag flipped" #vu8(0 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) #vu8() #vu8(44 116 189 246 146 127 11 160 125 148 187 86 42 159 130 24) #f ()) #(154 "all bits of tag flipped" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(39 70 96 216 246 92 53 139 232 211 65 108 125 179 224 214) #f ()) #(155 "Tag changed to all zero" #vu8(0 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) #vu8() #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) #f ()) #(156 "Tag changed to all zero" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) #f ()) #(157 "tag changed to all 1" #vu8(0 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) #vu8() #vu8(255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255) #f ()) #(158 "tag changed to all 1" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255) #f ()) #(159 "msbs changed in tag" #vu8(0 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) #vu8() #vu8(83 11 194 137 237 0 116 223 2 235 196 41 85 224 253 103) #f ()) #(160 "msbs changed in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(88 57 31 167 137 35 74 244 151 172 62 19 2 204 159 169) #f ()) #(161 "lsbs changed in tag" #vu8(0 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) #vu8() #vu8(210 138 67 8 108 129 245 94 131 106 69 168 212 97 124 230) #f ()) #(162 "lsbs changed in tag" #vu8(0 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) #vu8(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) #vu8(217 184 158 38 8 162 203 117 22 45 191 146 131 77 30 40) #f ()))) (test-hmac "hmac_sha256_test" :algorithm "HMACSHA256" :key-size 128 :tag-size 256 :tests '(#(163 "short key" #vu8(163 73 172 10 159 159 116 228 142 9 156 195 219 249 169 201) #vu8() #vu8(58 132 55 184 119 183 92 192 138 77 141 117 89 168 252 104 105 165 140 113 61 166 61 29 75 53 13 89 181 151 227 12) #t ()) #(164 "short key" #vu8(172 104 107 160 241 165 27 78 196 240 179 4 146 183 245 86) #vu8(47 164 58 20 174 80 5 7 222 185 90 181 189 50 176 254) #vu8(0 133 50 165 61 12 10 178 32 39 174 36 144 35 55 83 116 226 35 155 149 150 9 232 51 155 5 161 87 66 166 117) #t ()) #(165 "short key" #vu8(115 239 158 241 164 34 94 81 227 193 219 58 206 31 162 79) #vu8(255 173 56 13 154 171 176 172 237 229 193 191 17 41 37 205 252 61 55 159 194 55 106 79 226 100 68 144 208 67 10 195) #vu8(156 124 185 247 194 7 236 70 209 227 197 87 100 115 28 74 181 221 186 228 225 64 30 82 168 149 223 12 255 71 135 201) #t ()))) (test-hmac "hmac_sha256_test" :algorithm "HMACSHA256" :key-size 128 :tag-size 128 :tests '(#(166 "short key" #vu8(227 79 21 199 189 129 153 48 254 157 102 224 193 102 230 28) #vu8() #vu8(29 118 90 185 226 152 146 247 191 236 41 117 173 75 194 220) #t ()) #(167 "short key" #vu8(224 158 170 90 63 94 86 210 121 213 231 160 51 115 246 234) #vu8(239 78 171 55 24 31 152 66 62 83 233 71 231 5 15 208) #vu8(207 193 158 192 121 2 236 139 228 137 96 109 143 64 209 114) #t ()) #(168 "short key" #vu8(155 211 144 46 208 153 108 134 155 87 34 114 231 111 56 137) #vu8(167 186 25 212 158 225 234 2 240 152 170 142 48 199 64 216 147 164 69 108 204 41 64 64 72 78 216 160 10 85 249 62) #vu8(172 80 173 173 151 133 168 156 114 130 216 171 136 29 198 21) #t ()))) (test-hmac "hmac_sha256_test" :algorithm "HMACSHA256" :key-size 520 :tag-size 256 :tests '(#(169 "long key" #vu8(138 12 70 235 138 41 89 227 152 101 51 0 121 118 51 65 231 67 157 171 20 150 148 238 87 224 214 30 199 61 148 126 29 83 1 205 151 78 24 165 224 209 207 13 44 55 232 170 221 159 213 137 213 126 243 46 71 2 74 153 188 63 112 192 119) #vu8() #vu8(245 191 185 64 86 31 180 219 115 235 186 73 191 46 72 147 187 12 202 97 138 113 183 236 246 172 163 130 49 225 103 234) #t ()) #(170 "long key" #vu8(40 119 235 184 31 128 51 79 208 5 22 51 116 70 197 207 90 212 163 162 225 151 38 158 91 10 209 136 157 254 43 75 10 170 103 111 172 85 179 108 227 175 252 127 16 146 171 137 197 50 115 168 55 189 91 201 77 26 157 158 91 2 233 133 111) #vu8(186 68 141 184 143 21 79 119 80 40 253 236 249 230 117 45) #vu8(22 144 237 65 128 100 40 153 224 222 185 236 34 112 55 78 139 10 72 66 23 245 166 130 197 36 49 110 202 33 155 100) #t ()) #(171 "long key" #vu8(33 23 142 38 188 40 255 194 124 6 247 98 186 25 10 98 112 117 133 109 124 166 254 171 121 172 99 20 155 23 18 110 52 253 158 85 144 224 233 10 172 128 29 240 149 5 216 175 45 208 162 112 59 53 44 87 58 201 210 203 6 57 39 242 175) #vu8(125 95 29 107 153 52 82 177 181 58 67 117 118 13 16 162 13 70 160 171 158 195 148 63 196 176 122 44 231 53 231 49) #vu8(229 66 172 138 200 243 100 186 228 183 218 139 122 7 119 223 53 15 0 29 228 232 207 162 217 239 11 21 1 148 150 236) #t ()))) (test-hmac "hmac_sha256_test" :algorithm "HMACSHA256" :key-size 520 :tag-size 128 :tests '(#(172 "long key" #vu8(129 62 12 7 140 34 19 117 232 5 144 172 230 119 78 175 210 210 194 66 53 9 136 208 46 250 85 14 5 174 203 225 0 193 184 191 21 76 147 44 249 229 113 119 1 92 129 108 66 188 127 188 113 206 170 83 40 199 49 107 127 15 48 51 15) #vu8() #vu8(187 106 182 111 81 229 63 160 134 201 198 26 38 202 39 224) #t ()) #(173 "long key" #vu8(87 19 52 48 150 176 170 240 86 42 107 146 193 161 85 53 146 65 96 71 90 78 66 51 88 145 89 114 140 86 46 59 42 217 111 116 12 106 77 162 188 63 118 140 233 140 155 214 107 172 40 209 100 111 245 146 2 140 148 13 69 95 53 238 180) #vu8(113 113 45 226 250 193 251 133 86 115 191 247 42 246 66 87) #vu8(193 129 101 184 185 125 177 202 94 36 134 163 43 57 115 30) #t ()) #(174 "long key" #vu8(114 8 175 190 207 95 31 52 130 143 152 183 25 65 78 40 7 22 222 100 245 237 209 174 28 119 65 83 205 32 34 51 123 178 15 173 225 183 133 111 29 191 212 14 43 67 7 241 41 60 239 241 105 46 233 13 140 144 181 253 249 83 171 1 165) #vu8(67 181 51 2 182 4 214 19 230 45 176 2 4 74 71 130 213 114 172 143 189 60 208 236 233 27 67 188 82 225 142 152) #vu8(47 236 254 69 215 147 57 197 125 221 186 104 171 52 245 241) #t ())))
false
c552ab7909b728e65c7facd16b973f8cb71a33ac
7b49e5e3aec855d322c1179d4fb288b76307fa4a
/awful-picman.meta
f4b536fd614539b9c1280ef596c0558a565f9172
[]
no_license
mario-goulart/awful-picman
db7fb456e551a0796d67187d8bea90692056c48a
3a38e1265ff770e1292c45aa44df8edadaa22028
refs/heads/master
2022-12-22T10:13:21.786573
2022-12-11T19:41:17
2022-12-11T19:41:23
11,710,823
0
0
null
null
null
null
UTF-8
Scheme
false
false
371
meta
awful-picman.meta
;; -*- scheme -*- ((synopsis "An awful picture manager") (author "Mario Domenech Goulart") (category web) (license "BSD") (depends (awful "0.41.0") awful-sql-de-lite exif free-gettext hostinfo imlib2 make matchable slice (spock 0.098)) (test-depends test) (foreign-depends))
false
c635c6f8c99ad4850a94ab7607cc2a184825cd70
f634a79c9ea3bff7c9c4e0ecd8816d277a2ec282
/tests/test-huffman.scm
8a0491fd3360e2c35dfcf301c33de416d35aa33e
[ "MIT" ]
permissive
guenchi/compression
5b68dfcd557d53535db4e14a83047775dcc4e7ee
019ed92d92b71d737f3d5beba4464da5184f7833
refs/heads/master
2020-11-24T03:34:20.871259
2019-03-24T17:16:53
2019-03-24T17:16:53
227,948,379
1
0
NOASSERTION
2019-12-14T01:17:57
2019-12-14T01:17:56
null
UTF-8
Scheme
false
false
2,349
scm
test-huffman.scm
#!/usr/bin/env scheme-script ;; -*- mode: scheme; coding: utf-8 -*- !# ;; Copyright © 2009, 2010, 2011, 2012, 2017 Göran Weinholt <[email protected]> ;; SPDX-License-Identifier: MIT ;; Permission is hereby granted, free of charge, to any person obtaining a ;; copy of this software and associated documentation files (the "Software"), ;; to deal in the Software without restriction, including without limitation ;; the rights to use, copy, modify, merge, publish, distribute, sublicense, ;; and/or sell copies of the Software, and to permit persons to whom the ;; Software is furnished to do so, subject to the following conditions: ;; The above copyright notice and this permission notice shall be included in ;; all copies or substantial portions of the Software. ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ;; THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;; DEALINGS IN THE SOFTWARE. #!r6rs (import (rnrs (6)) (srfi :78 lightweight-testing) (compression bitstream) (compression huffman)) ;; ____ 12 in reverse (let ((br (make-bit-reader (open-bytevector-input-port #vu8(#b00111101 #b11000011 #b10100000)))) ;; ^^^^ this is 11, in reverse (table (canonical-codes->simple-lookup-table ;; ((symbol bit-length code) ...) '((0 4 10) (3 5 28) (4 5 29) (5 6 60) (6 4 11) (7 4 12) (8 2 0) (9 3 4) (10 6 61) (12 7 126) (13 6 62) (14 4 13) (16 2 1) (17 7 127))))) ;; Check that the following are properly decoded. The library has to ;; get from the bits in the bytevector to these symbols, via the ;; lookup table. (check (get-next-code br table) => 6) ;corresponds to 11 (check (get-next-code br table) => 7) ; --""-- 12 (check (get-next-code br table) => 7) (check (get-next-code br table) => 8) (check (get-next-code br table) => 7) #f) (check-report) (assert (check-passed? 5))
false
e685f40d91bbeb654056f6808146811ccd4d99c1
d51c8c57288cacf9be97d41079acc7c9381ed95a
/scsh/scheme/rw.scm
039a9c2aae17862c667912e7f9f1ce8d2025e1aa
[]
no_license
yarec/svm
f926315fa5906bd7670ef77f60b7ef8083b87860
d99fa4d3d8ecee1353b1a6e9245d40b60f98db2d
refs/heads/master
2020-12-13T08:48:13.540156
2020-05-04T06:42:04
2020-05-04T06:42:04
19,306,837
2
0
null
null
null
null
UTF-8
Scheme
false
false
4,457
scm
rw.scm
;;; Basic read and write ;;; Copyright (c) 1993 by Olin Shivers. ;;; Note: read ops should check to see if their string args are mutable. ;;; Best-effort/forward-progress reading ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (read-string!/partial s . args) (let-optionals args ((fd/port (current-input-port)) (start 0) (end (string-length s))) (if (bogus-substring-spec? s start end) (error "Bad substring indices" s start end)) (cond ((integer? fd/port) (let ((port (fdes->inport fd/port))) (read-string!/partial s port start end))) ((open-input-port? fd/port) (if (= start end) 0 (let* ((needed (if (file-options-on? (i/o-flags fd/port) (file-options nonblocking)) 'any 'immediate)) (nread (if (= end (string-length s)) (read-block s start needed fd/port) ;;; READ-BLOCK doesn't allow us to specify a ;;; maximum number of characters to read/partial ;;; but fills the buffer at most to the end. ;;; Therefore we allocate a new buffer here: (let* ((buf (make-string (- end start))) (nread-any (read-block buf 0 needed fd/port))) (if (not (eof-object? nread-any)) (copy-bytes! buf 0 s start nread-any)) nread-any)))) (if (eof-object? nread) #f nread)))) (else (apply error "Not a fd/port in read-string!/partial" s args))))) (define (read-string/partial len . maybe-fd/port) (let* ((fd/port (:optional maybe-fd/port (current-input-port)))) (cond ((integer? fd/port) (let ((port (fdes->inport fd/port))) (read-string/partial len port))) ((open-input-port? fd/port) (if (= len 0) "" (let* ((buffer (make-string len)) (nread (read-string!/partial buffer fd/port))) (cond ((not nread) #f) ((= nread len) buffer) (else (substring buffer 0 nread)))))) (else (error "Not a fd/port in read-string/partial" len fd/port))))) ;;; Persistent reading ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Operation on ports is easy, since we can use read-block (define (read-string! s . args) (let-optionals args ((fd/port (current-input-port)) (start 0) (end (string-length s))) (if (bogus-substring-spec? s start end) (error "Bad substring indices" s start end)) (cond ((integer? fd/port) (let ((port (fdes->inport fd/port))) (read-string! port start end))) (else ; no differnce between fd/port and s48 ports (let ((nbytes/eof (read-block s start (- end start) fd/port))) (if (eof-object? nbytes/eof) #f nbytes/eof)))))) (define (read-string len . maybe-fd/port) (let* ((s (make-string len)) (fd/port (:optional maybe-fd/port (current-input-port))) (nread (read-string! s fd/port 0 len))) (cond ((not nread) #f) ; EOF ((= nread len) s) (else (substring s 0 nread))))) ;;; Best-effort/forward-progress writing ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Non-blocking output to a buffered port is not defined. (define (write-string/partial s . args) (let-optionals args ((fd/port (current-output-port)) (start 0) (end (string-length s))) (if (bogus-substring-spec? s start end) (error "Bad substring indices" s start end)) (cond ((integer? fd/port) (let ((port (fdes->outport fd/port))) (write-string/partial s port start end))) (else ;; the only way to implement this, would be to use ;; channel-maybe-write. But this is an VM-instruction which is not ;; exported. Since we now have threads this shouldn;t matter. (error "write-string/parital is currently dereleased. See the RELEASE file for details"))))) ;;; Persistent writing ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (write-string s . args) (let-optionals args ((fd/port (current-output-port)) (start 0) (end (string-length s))) (if (bogus-substring-spec? s start end) (error "Bad substring indices" s start end)) (cond ((integer? fd/port) (let ((port (fdes->outport fd/port))) (write-string s port start end))) (else (write-block (string->os-byte-vector s) start (- end start) fd/port)))))
false
db22b2d959a9504e9dab3aeb59c39787d7dd18d0
1bbeeb35c45005ab263d88431e8ee0a2fc1fcae7
/lib/sdl-value.sls
5810722e418baeadd0279d13fa58e1c39300b458
[ "MIT" ]
permissive
steven741/chez-sdl
dbe744b76e7232f961cce1d40a4da1ee144358ba
a09bb0c13d633af075e5fc6ff60606361ace6ee5
refs/heads/master
2021-03-30T18:05:59.328516
2020-01-03T22:10:16
2020-01-03T22:10:16
123,814,071
29
15
BSD-2-Clause
2018-08-16T20:11:20
2018-03-04T17:57:25
Scheme
UTF-8
Scheme
false
false
47,434
sls
sdl-value.sls
;;;; -*- mode: Scheme; -*- (define SDL-PIXELFORMAT-UNKNOWN SDL_PIXELFORMAT_UNKNOWN) (define SDL-PIXELFORMAT-INDEX1LSB SDL_PIXELFORMAT_INDEX1LSB) (define SDL-PIXELFORMAT-INDEX1MSB SDL_PIXELFORMAT_INDEX1MSB) (define SDL-PIXELFORMAT-INDEX4LSB SDL_PIXELFORMAT_INDEX4LSB) (define SDL-PIXELFORMAT-INDEX4MSB SDL_PIXELFORMAT_INDEX4MSB) (define SDL-PIXELFORMAT-INDEX8 SDL_PIXELFORMAT_INDEX8) (define SDL-PIXELFORMAT-RGB332 SDL_PIXELFORMAT_RGB332) (define SDL-PIXELFORMAT-RGB444 SDL_PIXELFORMAT_RGB444) (define SDL-PIXELFORMAT-RGB555 SDL_PIXELFORMAT_RGB555) (define SDL-PIXELFORMAT-BGR555 SDL_PIXELFORMAT_BGR555) (define SDL-PIXELFORMAT-ARGB4444 SDL_PIXELFORMAT_ARGB4444) (define SDL-PIXELFORMAT-RGBA4444 SDL_PIXELFORMAT_RGBA4444) (define SDL-PIXELFORMAT-ABGR4444 SDL_PIXELFORMAT_ABGR4444) (define SDL-PIXELFORMAT-BGRA4444 SDL_PIXELFORMAT_BGRA4444) (define SDL-PIXELFORMAT-ARGB1555 SDL_PIXELFORMAT_ARGB1555) (define SDL-PIXELFORMAT-RGBA5551 SDL_PIXELFORMAT_RGBA5551) (define SDL-PIXELFORMAT-ABGR1555 SDL_PIXELFORMAT_ABGR1555) (define SDL-PIXELFORMAT-BGRA5551 SDL_PIXELFORMAT_BGRA5551) (define SDL-PIXELFORMAT-RGB565 SDL_PIXELFORMAT_RGB565) (define SDL-PIXELFORMAT-BGR565 SDL_PIXELFORMAT_BGR565) (define SDL-PIXELFORMAT-RGB24 SDL_PIXELFORMAT_RGB24) (define SDL-PIXELFORMAT-BGR24 SDL_PIXELFORMAT_BGR24) (define SDL-PIXELFORMAT-RGB888 SDL_PIXELFORMAT_RGB888) (define SDL-PIXELFORMAT-RGBX8888 SDL_PIXELFORMAT_RGBX8888) (define SDL-PIXELFORMAT-BGR888 SDL_PIXELFORMAT_BGR888) (define SDL-PIXELFORMAT-BGRX8888 SDL_PIXELFORMAT_BGRX8888) (define SDL-PIXELFORMAT-ARGB8888 SDL_PIXELFORMAT_ARGB8888) (define SDL-PIXELFORMAT-RGBA8888 SDL_PIXELFORMAT_RGBA8888) (define SDL-PIXELFORMAT-ABGR8888 SDL_PIXELFORMAT_ABGR8888) (define SDL-PIXELFORMAT-BGRA8888 SDL_PIXELFORMAT_BGRA8888) (define SDL-PIXELFORMAT-ARGB2101010 SDL_PIXELFORMAT_ARGB2101010) (define SDL-PIXELFORMAT-RGBA32 SDL_PIXELFORMAT_RGBA32) (define SDL-PIXELFORMAT-ARGB32 SDL_PIXELFORMAT_ARGB32) (define SDL-PIXELFORMAT-BGRA32 SDL_PIXELFORMAT_BGRA32) (define SDL-PIXELFORMAT-ABGR32 SDL_PIXELFORMAT_ABGR32) (define SDL-PIXELFORMAT-YV12 SDL_PIXELFORMAT_YV12) (define SDL-PIXELFORMAT-IYUV SDL_PIXELFORMAT_IYUV) (define SDL-PIXELFORMAT-YUY2 SDL_PIXELFORMAT_YUY2) (define SDL-PIXELFORMAT-UYVY SDL_PIXELFORMAT_UYVY) (define SDL-PIXELFORMAT-YVYU SDL_PIXELFORMAT_YVYU) (define SDL-PIXELFORMAT-NV12 SDL_PIXELFORMAT_NV12) (define SDL-PIXELFORMAT-NV21 SDL_PIXELFORMAT_NV21) (define SDL-RENDERER-SOFTWARE SDL_RENDERER_SOFTWARE) (define SDL-RENDERER-ACCELERATED SDL_RENDERER_ACCELERATED) (define SDL-RENDERER-PRESENT-VSYNC SDL_RENDERER_PRESENTVSYNC) (define SDL-RENDERER-TARGET-TEXTURE SDL_RENDERER_TARGETTEXTURE) (define SDL-TEXTUREACCESS-STATIC SDL_TEXTUREACCESS_STATIC) (define SDL-TEXTUREACCESS-STREAMING SDL_TEXTUREACCESS_STREAMING) (define SDL-TEXTUREACCESS-TARGET SDL_TEXTUREACCESS_TARGET) (define SDL-FLIP-NONE SDL_FLIP_NONE) (define SDL-FLIP-HORIZONTAL SDL_FLIP_HORIZONTAL) (define SDL-FLIP-VERTICAL SDL_FLIP_VERTICAL) (define SDL-BLENDMODE-NONE SDL_BLENDMODE_NONE) (define SDL-BLENDMODE-BLEND SDL_BLENDMODE_BLEND) (define SDL-BLENDMODE-ADD SDL_BLENDMODE_ADD) (define SDL-BLENDMODE-MOD SDL_BLENDMODE_MOD) (define SDL-BLENDMODE-INVALID SDL_BLENDMODE_INVALID) (define SDL-BLENDOPERATION-ADD SDL_BLENDOPERATION_ADD) (define SDL-BLENDOPERATION-SUBTRACT SDL_BLENDOPERATION_SUBTRACT) (define SDL-BLENDOPERATION-REV-SUBTRACT SDL_BLENDOPERATION_REV_SUBTRACT) (define SDL-BLENDOPERATION-MINIMUM SDL_BLENDOPERATION_MINIMUM) (define SDL-BLENDOPERATION-MAXIMUM SDL_BLENDOPERATION_MAXIMUM) (define SDL-BLENDFACTOR-ZERO SDL_BLENDFACTOR_ZERO) (define SDL-BLENDFACTOR-ONE SDL_BLENDFACTOR_ONE) (define SDL-BLENDFACTOR-SRC-COLOR SDL_BLENDFACTOR_SRC_COLOR) (define SDL-BLENDFACTOR-ONE-MINUS-SRC-COLOR SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR) (define SDL-BLENDFACTOR-SRC-ALPHA SDL_BLENDFACTOR_SRC_ALPHA) (define SDL-BLENDFACTOR-ONE-MINUS-SRC-ALPHA SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA) (define SDL-BLENDFACTOR-DST-COLOR SDL_BLENDFACTOR_DST_COLOR) (define SDL-BLENDFACTOR-ONE-MINUS-DST-COLOR SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR) (define SDL-BLENDFACTOR-DST-ALPHA SDL_BLENDFACTOR_DST_ALPHA) (define SDL-BLENDFACTOR-ONE-MINUS-DST-ALPHA SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA) (define SDL-SYSTEM-CURSOR-ARROW 0) (define SDL-SYSTEM-CURSOR-IBEAM 1) (define SDL-SYSTEM-CURSOR-WAIT 2) (define SDL-SYSTEM-CURSOR-CROSSHAIR 3) (define SDL-SYSTEM-CURSOR-WAIT-ARROW 4) (define SDL-SYSTEM-CURSOR-SIZE-NWSE 5) (define SDL-SYSTEM-CURSOR-SIZE-NESW 6) (define SDL-SYSTEM-CURSOR-SIZE-WE 7) (define SDL-SYSTEM-CURSOR-SIZE-NS 8) (define SDL-SYSTEM-CURSOR-SIZE-ALL 9) (define SDL-SYSTEM-CURSOR-NO 10) (define SDL-SYSTEM-CURSOR-HAND 11) (define SDL-HAPTIC-CONSTANT (bitwise-arithmetic-shift-left 1 0)) (define SDL-HAPTIC-SINE (bitwise-arithmetic-shift-left 1 1)) (define SDL-HAPTIC-LEFTRIGHT (bitwise-arithmetic-shift-left 1 2)) (define SDL-HAPTIC-TRIANGLE (bitwise-arithmetic-shift-left 1 3)) (define SDL-HAPTIC-SAWTOOTHUP (bitwise-arithmetic-shift-left 1 4)) (define SDL-HAPTIC-SAWTOOTHDOWN (bitwise-arithmetic-shift-left 1 5)) (define SDL-HAPTIC-RAMP (bitwise-arithmetic-shift-left 1 6)) (define SDL-HAPTIC-SPRING (bitwise-arithmetic-shift-left 1 7)) (define SDL-HAPTIC-DAMPER (bitwise-arithmetic-shift-left 1 8)) (define SDL-HAPTIC-INERTIA (bitwise-arithmetic-shift-left 1 9)) (define SDL-HAPTIC-FRICTION (bitwise-arithmetic-shift-left 1 10)) (define SDL-HAPTIC-CUSTOM (bitwise-arithmetic-shift-left 1 11)) (define SDL-HAPTIC-GAIN (bitwise-arithmetic-shift-left 1 12)) (define SDL-HAPTIC-AUTOCENTER (bitwise-arithmetic-shift-left 1 13)) (define SDL-HAPTIC-STATUS (bitwise-arithmetic-shift-left 1 14)) (define SDL-HAPTIC-PAUSE (bitwise-arithmetic-shift-left 1 15)) (define SDL-HAPTIC-POLAR 0) (define SDL-HAPTIC-CARTESIAN 1) (define SDL-HAPTIC-SPHERICAL 2) (define SDL-HAPTIC-INFINITY 4294967295) (define SDL-CONTROLLER-BINDTYPE-NONE 0) (define SDL-CONTROLLER-BINDTYPE-BUTTON 1) (define SDL-CONTROLLER-BINDTYPE-AXIS 2) (define SDL-CONTROLLER-BINDTYPE-HAT 3) (define SDL-TRUE 1) (define SDL-FALSE 0) (define SDL-QUERY -1) (define SDL-IGNORE 0) (define SDL-DISABLE 0) (define SDL-ENABLE 1) (define SDL-INIT-TIMER #x00000001) (define SDL-INIT-AUDIO #x00000010) (define SDL-INIT-VIDEO #x00000020) (define SDL-INIT-JOYSTICK #x00000200) (define SDL-INIT-HAPTIC #x00001000) (define SDL-INIT-GAMECONTROLLER #x00002000) (define SDL-INIT-EVENTS #x00004000) (define SDL-INIT-EVERYTHING (bitwise-ior SDL-INIT-TIMER SDL-INIT-AUDIO SDL-INIT-VIDEO SDL-INIT-EVENTS SDL-INIT-JOYSTICK SDL-INIT-HAPTIC SDL-INIT-GAMECONTROLLER)) (define SDL-HINT-DEFAULT 0) (define SDL-HINT-NORMAL 1) (define SDL-HINT-OVERRIDE 2) (define SDL-HINT-FRAMEBUFFER-ACCELERATION "SDL_FRAMEBUFFER_ACCELERATION") (define SDL-HINT-RENDER-DRIVER "SDL_RENDER_DRIVER") (define SDL-HINT-RENDER-OPENGL-SHADERS "SDL_RENDER_OPENGL_SHADERS") (define SDL-HINT-RENDER-DIRECT3D-THREADSAFE "SDL_RENDER_DIRECT3D_THREADSAFE") (define SDL-HINT-RENDER-DIRECT3D11-DEBUG "SDL_RENDER_DIRECT3D11_DEBUG") (define SDL-HINT-RENDER-LOGICAL-SIZE-MODE "SDL_RENDER_LOGICAL_SIZE_MODE") (define SDL-HINT-RENDER-SCALE-QUALITY "SDL_RENDER_SCALE_QUALITY") (define SDL-HINT-RENDER-VSYNC "SDL_RENDER_VSYNC") (define SDL-HINT-VIDEO-ALLOW-SCREENSAVER "SDL_VIDEO_ALLOW_SCREENSAVER") (define SDL-HINT-VIDEO-X11-XVIDMODE "SDL_VIDEO_X11_XVIDMODE") (define SDL-HINT-VIDEO-X11-XINERAMA "SDL_VIDEO_X11_XINERAMA") (define SDL-HINT-VIDEO-X11-XRANDR "SDL_VIDEO_X11_XRANDR") (define SDL-HINT-VIDEO-X11-NET-WM-PING "SDL_VIDEO_X11_NET_WM_PING") (define SDL-HINT-VIDEO-X11-NET-WM-BYPASS-COMPOSITOR "SDL_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR") (define SDL-HINT-WINDOW-FRAME-USABLE-WHILE-CURSOR-HIDDEN "SDL_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN") (define SDL-HINT-WINDOWS-INTRESOURCE-ICON "SDL_WINDOWS_INTRESOURCE_ICON") (define SDL-HINT-WINDOWS-INTRESOURCE-ICON-SMALL "SDL_WINDOWS_INTRESOURCE_ICON_SMALL") (define SDL-HINT-WINDOWS-ENABLE-MESSAGELOOP "SDL_WINDOWS_ENABLE_MESSAGELOOP") (define SDL-HINT-GRAB-KEYBOARD "SDL_GRAB_KEYBOARD") (define SDL-HINT-MOUSE-NORMAL-SPEED-SCALE "SDL_MOUSE_NORMAL_SPEED_SCALE") (define SDL-HINT-MOUSE-RELATIVE-SPEED-SCALE "SDL_MOUSE_RELATIVE_SPEED_SCALE") (define SDL-HINT-MOUSE-RELATIVE-MODE-WARP "SDL_MOUSE_RELATIVE_MODE_WARP") (define SDL-HINT-MOUSE-FOCUS-CLICKTHROUGH "SDL_MOUSE_FOCUS_CLICKTHROUGH") (define SDL-HINT-TOUCH-MOUSE-EVENTS "SDL_TOUCH_MOUSE_EVENTS") (define SDL-HINT-VIDEO-MINIMIZE-ON-FOCUS-LOSS "SDL_VIDEO_MINIMIZE_ON_FOCUS_LOSS") (define SDL-HINT-IDLE-TIMER-DISABLED "SDL_IOS_IDLE_TIMER_DISABLED") (define SDL-HINT-ORIENTATIONS "SDL_IOS_ORIENTATIONS") (define SDL-HINT-APPLE-TV-CONTROLLER-UI-EVENTS "SDL_APPLE_TV_CONTROLLER_UI_EVENTS") (define SDL-HINT-APPLE-TV-REMOTE-ALLOW-ROTATION "SDL_APPLE_TV_REMOTE_ALLOW_ROTATION") (define SDL-HINT-IOS-HIDE-HOME-INDICATOR "SDL_IOS_HIDE_HOME_INDICATOR") (define SDL-HINT-ACCELEROMETER-AS-JOYSTICK "SDL_ACCELEROMETER_AS_JOYSTICK") (define SDL-HINT-TV-REMOTE-AS-JOYSTICK "SDL_TV_REMOTE_AS_JOYSTICK") (define SDL-HINT-XINPUT-ENABLED "SDL_XINPUT_ENABLED") (define SDL-HINT-XINPUT-USE-OLD-JOYSTICK-MAPPING "SDL_XINPUT_USE_OLD_JOYSTICK_MAPPING") (define SDL-HINT-GAMECONTROLLERCONFIG "SDL_GAMECONTROLLERCONFIG") (define SDL-HINT-GAMECONTROLLER-IGNORE-DEVICES "SDL_GAMECONTROLLER_IGNORE_DEVICES") (define SDL-HINT-GAMECONTROLLER-IGNORE-DEVICES-EXCEPT "SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT") (define SDL-HINT-JOYSTICK-ALLOW-BACKGROUND-EVENTS "SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS") (define SDL-HINT-ALLOW-TOPMOST "SDL_ALLOW_TOPMOST") (define SDL-HINT-TIMER-RESOLUTION "SDL_TIMER_RESOLUTION") (define SDL-HINT-QTWAYLAND-CONTENT-ORIENTATION "SDL_QTWAYLAND_CONTENT_ORIENTATION") (define SDL-HINT-QTWAYLAND-WINDOW-FLAGS "SDL_QTWAYLAND_WINDOW_FLAGS") (define SDL-HINT-THREAD-STACK-SIZE "SDL_THREAD_STACK_SIZE") (define SDL-HINT-VIDEO-HIGHDPI-DISABLED "SDL_VIDEO_HIGHDPI_DISABLED") (define SDL-HINT-MAC-CTRL-CLICK-EMULATE-RIGHT-CLICK "SDL_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK") (define SDL-HINT-VIDEO-WIN-D3DCOMPILER "SDL_VIDEO_WIN_D3DCOMPILER") (define SDL-HINT-VIDEO-WINDOW-SHARE-PIXEL-FORMAT "SDL_VIDEO_WINDOW_SHARE_PIXEL_FORMAT") (define SDL-HINT-WINRT-PRIVACY-POLICY-URL "SDL_WINRT_PRIVACY_POLICY_URL") (define SDL-HINT-WINRT-PRIVACY-POLICY-LABEL "SDL_WINRT_PRIVACY_POLICY_LABEL") (define SDL-HINT-WINRT-HANDLE-BACK-BUTTON "SDL_WINRT_HANDLE_BACK_BUTTON") (define SDL-HINT-VIDEO-MAC-FULLSCREEN-SPACES "SDL_VIDEO_MAC_FULLSCREEN_SPACES") (define SDL-HINT-MAC-BACKGROUND-APP "SDL_MAC_BACKGROUND_APP") (define SDL-HINT-ANDROID-APK-EXPANSION-MAIN-FILE-VERSION "SDL_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION") (define SDL-HINT-ANDROID-APK-EXPANSION-PATCH-FILE-VERSION "SDL_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION") (define SDL-HINT-IME-INTERNAL-EDITING "SDL_IME_INTERNAL_EDITING") (define SDL-HINT-ANDROID-SEPARATE-MOUSE-AND-TOUCH "SDL_ANDROID_SEPARATE_MOUSE_AND_TOUCH") (define SDL-HINT-ANDROID-TRAP-BACK-BUTTON "SDL_ANDROID_TRAP_BACK_BUTTON") (define SDL-HINT-RETURN-KEY-HIDES-IME "SDL_RETURN_KEY_HIDES_IME") (define SDL-HINT-EMSCRIPTEN-KEYBOARD-ELEMENT "SDL_EMSCRIPTEN_KEYBOARD_ELEMENT") (define SDL-HINT-NO-SIGNAL-HANDLERS "SDL_NO_SIGNAL_HANDLERS") (define SDL-HINT-WINDOWS-NO-CLOSE-ON-ALT-F4 "SDL_WINDOWS_NO_CLOSE_ON_ALT_F4") (define SDL-HINT-BMP-SAVE-LEGACY-FORMAT "SDL_BMP_SAVE_LEGACY_FORMAT") (define SDL-HINT-WINDOWS-DISABLE-THREAD-NAMING "SDL_WINDOWS_DISABLE_THREAD_NAMING") (define SDL-HINT-RPI-VIDEO-LAYER "SDL_RPI_VIDEO_LAYER") (define SDL-HINT-VIDEO-DOUBLE-BUFFER "SDL_VIDEO_DOUBLE_BUFFER") (define SDL-HINT-OPENGL-ES-DRIVER "SDL_OPENGL_ES_DRIVER") (define SDL-HINT-AUDIO-RESAMPLING-MODE "SDL_AUDIO_RESAMPLING_MODE") (define SDL-HINT-AUDIO-CATEGORY "SDL_AUDIO_CATEGORY") (define SDL-WINDOW-FULLSCREEN #x00000001) (define SDL-WINDOW-OPENGL #x00000002) (define SDL-WINDOW-SHOWN #x00000004) (define SDL-WINDOW-HIDDEN #x00000008) (define SDL-WINDOW-BORDERLESS #x00000010) (define SDL-WINDOW-RESIZABLE #x00000020) (define SDL-WINDOW-MINIMIZED #x00000040) (define SDL-WINDOW-MAXIMIZED #x00000080) (define SDL-WINDOW-INPUT-GRABBED #x00000100) (define SDL-WINDOW-INPUT-FOCUS #x00000200) (define SDL-WINDOW-MOUSE-FOCUS #x00000400) (define SDL-WINDOW-FULLSCREEN-DESKTOP (bitwise-ior SDL-WINDOW-FULLSCREEN #x00001000)) (define SDL-WINDOW-FOREIGN #x00000800) (define SDL-WINDOW-ALLOW-HIGHDPI #x00002000) (define SDL-WINDOW-MOUSE-CAPTURE #x00004000) (define SDL-WINDOW-ALWAYS-ON-TOP #x00008000) (define SDL-WINDOW-SKIP-TASKBAR #x00010000) (define SDL-WINDOW-UTILITY #x00020000) (define SDL-WINDOW-TOOLTIP #x00040000) (define SDL-WINDOW-POPUP-MENU #x00080000) (define SDL-WINDOW-VULKAN #x10000000) (define SDL-WINDOWPOS-UNDEFINED-MASK #x1FFF0000) (define (SDL-WINDOWPOS-UNDEFINED-DISPLAY X) (bitwise-ior SDL-WINDOWPOS-UNDEFINED-MASK X)) (define SDL-WINDOWPOS-UNDEFINED (SDL-WINDOWPOS-UNDEFINED-DISPLAY 0)) (define (SDL-WINDOWPOS-IS-UNDEFINED? X) (= (bitwise-and X #xFFFF0000) SDL-WINDOWPOS-UNDEFINED-MASK)) (define SDL-WINDOWPOS-CENTERED-MASK #x2FFF0000) (define (SDL-WINDOWPOS-CENTERED-DISPLAY X) (bitwise-ior SDL-WINDOWPOS-CENTERED-MASK X)) (define SDL-WINDOWPOS-CENTERED (SDL-WINDOWPOS-CENTERED-DISPLAY 0)) (define (SDL-WINDOWPOS-IS-CENTERED? X) (= (bitwise-and X #xFFFF0000) SDL-WINDOWPOS-CENTERED-MASK)) (define SDL-SWSURFACE #x00000000) (define SDL-PREALLOC #x00000001) (define SDL-RLEACCEL #x00000002) (define SDL-DONTFREE #x00000004) (define SDL-GL-RED-SIZE 0) (define SDL-GL-GREEN-SIZE 1) (define SDL-GL-BLUE-SIZE 2) (define SDL-GL-ALPHA-SIZE 3) (define SDL-GL-BUFFER-SIZE 4) (define SDL-GL-DOUBLEBUFFER 5) (define SDL-GL-DEPTH-SIZE 6) (define SDL-GL-STENCIL-SIZE 7) (define SDL-GL-ACCUM-RED-SIZE 8) (define SDL-GL-ACCUM-GREEN-SIZE 9) (define SDL-GL-ACCUM-BLUE-SIZE 10) (define SDL-GL-ACCUM-ALPHA-SIZE 11) (define SDL-GL-STEREO 12) (define SDL-GL-MULTISAMPLEBUFFERS 13) (define SDL-GL-MULTISAMPLESAMPLES 14) (define SDL-GL-ACCELERATED-VISUAL 15) (define SDL-GL-RETAINED-BACKING 16) (define SDL-GL-CONTEXT-MAJOR-VERSION 17) (define SDL-GL-CONTEXT-MINOR-VERSION 18) (define SDL-GL-CONTEXT-EGL 19) (define SDL-GL-CONTEXT-FLAGS 20) (define SDL-GL-CONTEXT-PROFILE-MASK 21) (define SDL-GL-SHARE-WITH-CURRENT-CONTEXT 22) (define SDL-GL-FRAMEBUFFER-SRGB-CAPABLE 23) (define SDL-GL-CONTEXT-RELEASE-BEHAVIOR 24) (define SDL-GL-CONTEXT-RESET-NOTIFICATION 25) (define SDL-GL-CONTEXT-NO-ERROR 26) (define SDL-GL-CONTEXT-PROFILE-CORE #x0001) (define SDL-GL-CONTEXT-PROFILE-COMPATIBILITY #x0002) (define SDL-GL-CONTEXT-PROFILE-ES #x0004) (define SDL-GL-CONTEXT-DEBUG-FLAG #x0001) (define SDL-GL-CONTEXT-FORWARD-COMPATIBLE-FLAG #x0002) (define SDL-GL-CONTEXT-ROBUST-ACCESS-FLAG #x0004) (define SDL-GL-CONTEXT-RESET-ISOLATION-FLAG #x0008) (define SDL-AUDIO-MASK-BITSIZE #xFF) (define SDL-AUDIO-MASK-DATATYPE (bitwise-arithmetic-shift-left 1 8)) (define SDL-AUDIO-MASK-ENDIAN (bitwise-arithmetic-shift-left 1 12)) (define SDL-AUDIO-MASK-SIGNED (bitwise-arithmetic-shift-left 1 15)) (define (SDL-AUDIO-BITSIZE x) (bitwise-and x SDL-AUDIO-MASK-BITSIZE)) (define (SDL-AUDIO-ISFLOAT x) (> (bitwise-and x SDL-AUDIO-MASK-DATATYPE) 0)) (define (SDL-AUDIO-ISBIGENDIAN x) (> (bitwise-and x SDL-AUDIO-MASK-ENDIAN) 0)) (define (SDL-AUDIO-ISSIGNED x) (> (bitwise-and x SDL-AUDIO-MASK-SIGNED) 0)) (define (SDL-AUDIO-ISINT x) (not (SDL-AUDIO-ISFLOAT x))) (define (SDL-AUDIO-ISLITTLEENDIAN x) (not (SDL-AUDIO-ISBIGENDIAN x))) (define (SDL-AUDIO-ISUNSIGNED x) (not (SDL-AUDIO-ISSIGNED x))) (define AUDIO-U8 #x0008) (define AUDIO-S8 #x8008) (define AUDIO-U16LSB #x0010) (define AUDIO-S16LSB #x8010) (define AUDIO-U16MSB #x1010) (define AUDIO-S16MSB #x9010) (define AUDIO-U16 AUDIO-U16LSB) (define AUDIO-S16 AUDIO-S16LSB) (define AUDIO-S32LSB #x8020) (define AUDIO-S32MSB #x9020) (define AUDIO-S32 AUDIO-S32LSB) (define AUDIO-F32LSB #x8120) (define AUDIO-F32MSB #x9120) (define AUDIO-F32 AUDIO-F32LSB) (define AUDIO-U16SYS (if (eq? (native-endianness) 'little) AUDIO-U16LSB AUDIO-U16MSB)) (define AUDIO-S16SYS (if (eq? (native-endianness) 'little) AUDIO-S16LSB AUDIO-S16MSB)) (define AUDIO-S32SYS (if (eq? (native-endianness) 'little) AUDIO-S32LSB AUDIO-S32MSB)) (define AUDIO-F32SYS (if (eq? (native-endianness) 'little) AUDIO-F32LSB AUDIO-F32MSB)) (define SDL-AUDIO-ALLOW-FREQUENCY-CHANGE #x00000001) (define SDL-AUDIO-ALLOW-FORMAT-CHANGE #x00000002) (define SDL-AUDIO-ALLOW-CHANNELS-CHANGE #x00000004) (define SDL-AUDIO-ALLOW-SAMPLES-CHANGE #x00000008) (define SDL-AUDIO-ALLOW-ANY-CHANGE (bitwise-ior SDL-AUDIO-ALLOW-FREQUENCY-CHANGE SDL-AUDIO-ALLOW-FORMAT-CHANGE SDL-AUDIO-ALLOW-CHANNELS-CHANGE SDL-AUDIO-ALLOW-SAMPLES-CHANGE)) (define SDL-SCANCODE-UNKNOWN 0) (define SDL-SCANCODE-A 4) (define SDL-SCANCODE-B 5) (define SDL-SCANCODE-C 6) (define SDL-SCANCODE-D 7) (define SDL-SCANCODE-E 8) (define SDL-SCANCODE-F 9) (define SDL-SCANCODE-G 10) (define SDL-SCANCODE-H 11) (define SDL-SCANCODE-I 12) (define SDL-SCANCODE-J 13) (define SDL-SCANCODE-K 14) (define SDL-SCANCODE-L 15) (define SDL-SCANCODE-M 16) (define SDL-SCANCODE-N 17) (define SDL-SCANCODE-O 18) (define SDL-SCANCODE-P 19) (define SDL-SCANCODE-Q 20) (define SDL-SCANCODE-R 21) (define SDL-SCANCODE-S 22) (define SDL-SCANCODE-T 23) (define SDL-SCANCODE-U 24) (define SDL-SCANCODE-V 25) (define SDL-SCANCODE-W 26) (define SDL-SCANCODE-X 27) (define SDL-SCANCODE-Y 28) (define SDL-SCANCODE-Z 29) (define SDL-SCANCODE-1 30) (define SDL-SCANCODE-2 31) (define SDL-SCANCODE-3 32) (define SDL-SCANCODE-4 33) (define SDL-SCANCODE-5 34) (define SDL-SCANCODE-6 35) (define SDL-SCANCODE-7 36) (define SDL-SCANCODE-8 37) (define SDL-SCANCODE-9 38) (define SDL-SCANCODE-0 39) (define SDL-SCANCODE-RETURN 40) (define SDL-SCANCODE-ESCAPE 41) (define SDL-SCANCODE-BACKSPACE 42) (define SDL-SCANCODE-TAB 43) (define SDL-SCANCODE-SPACE 44) (define SDL-SCANCODE-MINUS 45) (define SDL-SCANCODE-EQUALS 46) (define SDL-SCANCODE-LEFTBRACKET 47) (define SDL-SCANCODE-RIGHTBRACKET 48) (define SDL-SCANCODE-BACKSLASH 49) (define SDL-SCANCODE-NONUSHASH 50) (define SDL-SCANCODE-SEMICOLON 51) (define SDL-SCANCODE-APOSTROPHE 52) (define SDL-SCANCODE-GRAVE 53) (define SDL-SCANCODE-COMMA 54) (define SDL-SCANCODE-PERIOD 55) (define SDL-SCANCODE-SLASH 56) (define SDL-SCANCODE-CAPSLOCK 57) (define SDL-SCANCODE-F1 58) (define SDL-SCANCODE-F2 59) (define SDL-SCANCODE-F3 60) (define SDL-SCANCODE-F4 61) (define SDL-SCANCODE-F5 62) (define SDL-SCANCODE-F6 63) (define SDL-SCANCODE-F7 64) (define SDL-SCANCODE-F8 65) (define SDL-SCANCODE-F9 66) (define SDL-SCANCODE-F10 67) (define SDL-SCANCODE-F11 68) (define SDL-SCANCODE-F12 69) (define SDL-SCANCODE-PRINTSCREEN 70) (define SDL-SCANCODE-SCROLLLOCK 71) (define SDL-SCANCODE-PAUSE 72) (define SDL-SCANCODE-INSERT 73) (define SDL-SCANCODE-HOME 74) (define SDL-SCANCODE-PAGEUP 75) (define SDL-SCANCODE-DELETE 76) (define SDL-SCANCODE-END 77) (define SDL-SCANCODE-PAGEDOWN 78) (define SDL-SCANCODE-RIGHT 79) (define SDL-SCANCODE-LEFT 80) (define SDL-SCANCODE-DOWN 81) (define SDL-SCANCODE-UP 82) (define SDL-SCANCODE-NUMLOCKCLEAR 83) (define SDL-SCANCODE-KP-DIVIDE 84) (define SDL-SCANCODE-KP-MULTIPLY 85) (define SDL-SCANCODE-KP-MINUS 86) (define SDL-SCANCODE-KP-PLUS 87) (define SDL-SCANCODE-KP-ENTER 88) (define SDL-SCANCODE-KP-1 89) (define SDL-SCANCODE-KP-2 90) (define SDL-SCANCODE-KP-3 91) (define SDL-SCANCODE-KP-4 92) (define SDL-SCANCODE-KP-5 93) (define SDL-SCANCODE-KP-6 94) (define SDL-SCANCODE-KP-7 95) (define SDL-SCANCODE-KP-8 96) (define SDL-SCANCODE-KP-9 97) (define SDL-SCANCODE-KP-0 98) (define SDL-SCANCODE-KP-PERIOD 99) (define SDL-SCANCODE-NONUSBACKSLASH 100) (define SDL-SCANCODE-APPLICATION 101) (define SDL-SCANCODE-POWER 102) (define SDL-SCANCODE-KP-EQUALS 103) (define SDL-SCANCODE-F13 104) (define SDL-SCANCODE-F14 105) (define SDL-SCANCODE-F15 106) (define SDL-SCANCODE-F16 107) (define SDL-SCANCODE-F17 108) (define SDL-SCANCODE-F18 109) (define SDL-SCANCODE-F19 110) (define SDL-SCANCODE-F20 111) (define SDL-SCANCODE-F21 112) (define SDL-SCANCODE-F22 113) (define SDL-SCANCODE-F23 114) (define SDL-SCANCODE-F24 115) (define SDL-SCANCODE-EXECUTE 116) (define SDL-SCANCODE-HELP 117) (define SDL-SCANCODE-MENU 118) (define SDL-SCANCODE-SELECT 119) (define SDL-SCANCODE-STOP 120) (define SDL-SCANCODE-AGAIN 121) (define SDL-SCANCODE-UNDO 122) (define SDL-SCANCODE-CUT 123) (define SDL-SCANCODE-COPY 124) (define SDL-SCANCODE-PASTE 125) (define SDL-SCANCODE-FIND 126) (define SDL-SCANCODE-MUTE 127) (define SDL-SCANCODE-VOLUMEUP 128) (define SDL-SCANCODE-VOLUMEDOWN 129) (define SDL-SCANCODE-KP-COMMA 133) (define SDL-SCANCODE-KP-EQUALSAS400 134) (define SDL-SCANCODE-INTERNATIONAL1 135) (define SDL-SCANCODE-INTERNATIONAL2 136) (define SDL-SCANCODE-INTERNATIONAL3 137) (define SDL-SCANCODE-INTERNATIONAL4 138) (define SDL-SCANCODE-INTERNATIONAL5 139) (define SDL-SCANCODE-INTERNATIONAL6 140) (define SDL-SCANCODE-INTERNATIONAL7 141) (define SDL-SCANCODE-INTERNATIONAL8 142) (define SDL-SCANCODE-INTERNATIONAL9 143) (define SDL-SCANCODE-LANG1 144) (define SDL-SCANCODE-LANG2 145) (define SDL-SCANCODE-LANG3 146) (define SDL-SCANCODE-LANG4 147) (define SDL-SCANCODE-LANG5 148) (define SDL-SCANCODE-LANG6 149) (define SDL-SCANCODE-LANG7 150) (define SDL-SCANCODE-LANG8 151) (define SDL-SCANCODE-LANG9 152) (define SDL-SCANCODE-ALTERASE 153) (define SDL-SCANCODE-SYSREQ 154) (define SDL-SCANCODE-CANCEL 155) (define SDL-SCANCODE-CLEAR 156) (define SDL-SCANCODE-PRIOR 157) (define SDL-SCANCODE-RETURN2 158) (define SDL-SCANCODE-SEPARATOR 159) (define SDL-SCANCODE-OUT 160) (define SDL-SCANCODE-OPER 161) (define SDL-SCANCODE-CLEARAGAIN 162) (define SDL-SCANCODE-CRSEL 163) (define SDL-SCANCODE-EXSEL 164) (define SDL-SCANCODE-KP-00 176) (define SDL-SCANCODE-KP-000 177) (define SDL-SCANCODE-THOUSANDSSEPARATOR 178) (define SDL-SCANCODE-DECIMALSEPARATOR 179) (define SDL-SCANCODE-CURRENCYUNIT 180) (define SDL-SCANCODE-CURRENCYSUBUNIT 181) (define SDL-SCANCODE-KP-LEFTPAREN 182) (define SDL-SCANCODE-KP-RIGHTPAREN 183) (define SDL-SCANCODE-KP-LEFTBRACE 184) (define SDL-SCANCODE-KP-RIGHTBRACE 185) (define SDL-SCANCODE-KP-TAB 186) (define SDL-SCANCODE-KP-BACKSPACE 187) (define SDL-SCANCODE-KP-A 188) (define SDL-SCANCODE-KP-B 189) (define SDL-SCANCODE-KP-C 190) (define SDL-SCANCODE-KP-D 191) (define SDL-SCANCODE-KP-E 192) (define SDL-SCANCODE-KP-F 193) (define SDL-SCANCODE-KP-XOR 194) (define SDL-SCANCODE-KP-POWER 195) (define SDL-SCANCODE-KP-PERCENT 196) (define SDL-SCANCODE-KP-LESS 197) (define SDL-SCANCODE-KP-GREATER 198) (define SDL-SCANCODE-KP-AMPERSAND 199) (define SDL-SCANCODE-KP-DBLAMPERSAND 200) (define SDL-SCANCODE-KP-VERTICALBAR 201) (define SDL-SCANCODE-KP-DBLVERTICALBAR 202) (define SDL-SCANCODE-KP-COLON 203) (define SDL-SCANCODE-KP-HASH 204) (define SDL-SCANCODE-KP-SPACE 205) (define SDL-SCANCODE-KP-AT 206) (define SDL-SCANCODE-KP-EXCLAM 207) (define SDL-SCANCODE-KP-MEMSTORE 208) (define SDL-SCANCODE-KP-MEMRECALL 209) (define SDL-SCANCODE-KP-MEMCLEAR 210) (define SDL-SCANCODE-KP-MEMADD 211) (define SDL-SCANCODE-KP-MEMSUBTRACT 212) (define SDL-SCANCODE-KP-MEMMULTIPLY 213) (define SDL-SCANCODE-KP-MEMDIVIDE 214) (define SDL-SCANCODE-KP-PLUSMINUS 215) (define SDL-SCANCODE-KP-CLEAR 216) (define SDL-SCANCODE-KP-CLEARENTRY 217) (define SDL-SCANCODE-KP-BINARY 218) (define SDL-SCANCODE-KP-OCTAL 219) (define SDL-SCANCODE-KP-DECIMAL 220) (define SDL-SCANCODE-KP-HEXADECIMAL 221) (define SDL-SCANCODE-LCTRL 224) (define SDL-SCANCODE-LSHIFT 225) (define SDL-SCANCODE-LALT 226) (define SDL-SCANCODE-LGUI 227) (define SDL-SCANCODE-RCTRL 228) (define SDL-SCANCODE-RSHIFT 229) (define SDL-SCANCODE-RALT 230) (define SDL-SCANCODE-RGUI 231) (define SDL-SCANCODE-MODE 257) (define SDL-SCANCODE-AUDIONEXT 258) (define SDL-SCANCODE-AUDIOPREV 259) (define SDL-SCANCODE-AUDIOSTOP 260) (define SDL-SCANCODE-AUDIOPLAY 261) (define SDL-SCANCODE-AUDIOMUTE 262) (define SDL-SCANCODE-MEDIASELECT 263) (define SDL-SCANCODE-WWW 264) (define SDL-SCANCODE-MAIL 265) (define SDL-SCANCODE-CALCULATOR 266) (define SDL-SCANCODE-COMPUTER 267) (define SDL-SCANCODE-AC-SEARCH 268) (define SDL-SCANCODE-AC-HOME 269) (define SDL-SCANCODE-AC-BACK 270) (define SDL-SCANCODE-AC-FORWARD 271) (define SDL-SCANCODE-AC-STOP 272) (define SDL-SCANCODE-AC-REFRESH 273) (define SDL-SCANCODE-AC-BOOKMARKS 274) (define SDL-SCANCODE-BRIGHTNESSDOWN 275) (define SDL-SCANCODE-BRIGHTNESSUP 276) (define SDL-SCANCODE-DISPLAYSWITCH 277) (define SDL-SCANCODE-KBDILLUMTOGGLE 278) (define SDL-SCANCODE-KBDILLUMDOWN 279) (define SDL-SCANCODE-KBDILLUMUP 280) (define SDL-SCANCODE-EJECT 281) (define SDL-SCANCODE-SLEEP 282) (define SDL-SCANCODE-APP1 283) (define SDL-SCANCODE-APP2 284) (define SDL-SCANCODE-AUDIOREWIND 285) (define SDL-SCANCODE-AUDIOFASTFORWARD 286) (define SDLK-SCANCODE-MASK (bitwise-arithmetic-shift 1 30)) (define (SDL-SCANCODE-TO-KEYCODE X) (bitwise-ior X SDLK-SCANCODE-MASK)) (define SDLK-UNKNOWN 0) (define SDLK-RETURN (char->integer #\r)) (define SDLK-ESCAPE (char->integer #\esc)) (define SDLK-BACKSPACE (char->integer #\b)) (define SDLK-TAB (char->integer #\t)) (define SDLK-SPACE (char->integer #\space)) (define SDLK-EXCLAIM (char->integer #\!)) (define SDLK-QUOTEDBL (char->integer #\")) (define SDLK-HASH (char->integer #\#)) (define SDLK-PERCENT (char->integer #\%)) (define SDLK-DOLLAR (char->integer #\$)) (define SDLK-AMPERSAND (char->integer #\&)) (define SDLK-QUOTE (char->integer #\')) (define SDLK-LEFTPAREN (char->integer #\()) (define SDLK-RIGHTPAREN (char->integer #\))) (define SDLK-ASTERISK (char->integer #\*)) (define SDLK-PLUS (char->integer #\+)) (define SDLK-COMMA (char->integer #\,)) (define SDLK-MINUS (char->integer #\-)) (define SDLK-PERIOD (char->integer #\.)) (define SDLK-SLASH (char->integer #\/)) (define SDLK-0 (char->integer #\0)) (define SDLK-1 (char->integer #\1)) (define SDLK-2 (char->integer #\2)) (define SDLK-3 (char->integer #\3)) (define SDLK-4 (char->integer #\4)) (define SDLK-5 (char->integer #\5)) (define SDLK-6 (char->integer #\6)) (define SDLK-7 (char->integer #\7)) (define SDLK-8 (char->integer #\8)) (define SDLK-9 (char->integer #\9)) (define SDLK-COLON (char->integer #\:)) (define SDLK-SEMICOLON (char->integer #\;)) (define SDLK-LESS (char->integer #\<)) (define SDLK-EQUALS (char->integer #\=)) (define SDLK-GREATER (char->integer #\>)) (define SDLK-QUESTION (char->integer #\?)) (define SDLK-AT (char->integer #\@)) (define SDLK-LEFTBRACKET (char->integer #\[)) (define SDLK-BACKSLASH (char->integer #\\)) (define SDLK-RIGHTBRACKET (char->integer #\])) (define SDLK-CARET (char->integer #\^)) (define SDLK-UNDERSCORE (char->integer #\_)) (define SDLK-BACKQUOTE (char->integer #\`)) (define SDLK-A (char->integer #\a)) (define SDLK-B (char->integer #\b)) (define SDLK-C (char->integer #\c)) (define SDLK-D (char->integer #\d)) (define SDLK-E (char->integer #\e)) (define SDLK-F (char->integer #\f)) (define SDLK-G (char->integer #\g)) (define SDLK-H (char->integer #\h)) (define SDLK-I (char->integer #\i)) (define SDLK-J (char->integer #\j)) (define SDLK-K (char->integer #\k)) (define SDLK-L (char->integer #\l)) (define SDLK-M (char->integer #\m)) (define SDLK-N (char->integer #\n)) (define SDLK-O (char->integer #\o)) (define SDLK-P (char->integer #\p)) (define SDLK-Q (char->integer #\q)) (define SDLK-R (char->integer #\r)) (define SDLK-S (char->integer #\s)) (define SDLK-T (char->integer #\t)) (define SDLK-U (char->integer #\u)) (define SDLK-V (char->integer #\v)) (define SDLK-W (char->integer #\w)) (define SDLK-X (char->integer #\x)) (define SDLK-Y (char->integer #\y)) (define SDLK-Z (char->integer #\z)) (define SDLK-CAPSLOCK (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-CAPSLOCK)) (define SDLK-F1 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F1)) (define SDLK-F2 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F2)) (define SDLK-F3 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F3)) (define SDLK-F4 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F4)) (define SDLK-F5 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F5)) (define SDLK-F6 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F6)) (define SDLK-F7 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F7)) (define SDLK-F8 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F8)) (define SDLK-F9 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F9)) (define SDLK-F10 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F10)) (define SDLK-F11 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F11)) (define SDLK-F12 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F12)) (define SDLK-PRINTSCREEN (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-PRINTSCREEN)) (define SDLK-SCROLLLOCK (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-SCROLLLOCK)) (define SDLK-PAUSE (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-PAUSE)) (define SDLK-INSERT (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-INSERT)) (define SDLK-HOME (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-HOME)) (define SDLK-PAGEUP (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-PAGEUP)) (define SDLK-DELETE (char->integer #\delete)) (define SDLK-END (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-END)) (define SDLK-PAGEDOWN (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-PAGEDOWN)) (define SDLK-RIGHT (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-RIGHT)) (define SDLK-LEFT (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-LEFT)) (define SDLK-DOWN (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-DOWN)) (define SDLK-UP (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-UP)) (define SDLK-NUMLOCKCLEAR (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-NUMLOCKCLEAR)) (define SDLK-KP-DIVIDE (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-DIVIDE)) (define SDLK-KP-MULTIPLY (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-MULTIPLY)) (define SDLK-KP-MINUS (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-MINUS)) (define SDLK-KP-PLUS (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-PLUS)) (define SDLK-KP-ENTER (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-ENTER)) (define SDLK-KP-1 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-1)) (define SDLK-KP-2 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-2)) (define SDLK-KP-3 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-3)) (define SDLK-KP-4 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-4)) (define SDLK-KP-5 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-5)) (define SDLK-KP-6 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-6)) (define SDLK-KP-7 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-7)) (define SDLK-KP-8 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-8)) (define SDLK-KP-9 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-9)) (define SDLK-KP-0 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-0)) (define SDLK-KP-PERIOD (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-PERIOD)) (define SDLK-APPLICATION (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-APPLICATION)) (define SDLK-POWER (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-POWER)) (define SDLK-KP-EQUALS (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-EQUALS)) (define SDLK-F13 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F13)) (define SDLK-F14 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F14)) (define SDLK-F15 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F15)) (define SDLK-F16 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F16)) (define SDLK-F17 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F17)) (define SDLK-F18 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F18)) (define SDLK-F19 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F19)) (define SDLK-F20 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F20)) (define SDLK-F21 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F21)) (define SDLK-F22 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F22)) (define SDLK-F23 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F23)) (define SDLK-F24 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-F24)) (define SDLK-EXECUTE (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-EXECUTE)) (define SDLK-HELP (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-HELP)) (define SDLK-MENU (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-MENU)) (define SDLK-SELECT (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-SELECT)) (define SDLK-STOP (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-STOP)) (define SDLK-AGAIN (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-AGAIN)) (define SDLK-UNDO (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-UNDO)) (define SDLK-CUT (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-CUT)) (define SDLK-COPY (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-COPY)) (define SDLK-PASTE (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-PASTE)) (define SDLK-FIND (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-FIND)) (define SDLK-MUTE (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-MUTE)) (define SDLK-VOLUMEUP (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-VOLUMEUP)) (define SDLK-VOLUMEDOWN (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-VOLUMEDOWN)) (define SDLK-KP-COMMA (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-COMMA)) (define SDLK-KP-EQUALSAS400 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-EQUALSAS400)) (define SDLK-ALTERASE (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-ALTERASE)) (define SDLK-SYSREQ (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-SYSREQ)) (define SDLK-CANCEL (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-CANCEL)) (define SDLK-CLEAR (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-CLEAR)) (define SDLK-PRIOR (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-PRIOR)) (define SDLK-RETURN2 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-RETURN2)) (define SDLK-SEPARATOR (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-SEPARATOR)) (define SDLK-OUT (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-OUT)) (define SDLK-OPER (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-OPER)) (define SDLK-CLEARAGAIN (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-CLEARAGAIN)) (define SDLK-CRSEL (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-CRSEL)) (define SDLK-EXSEL (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-EXSEL)) (define SDLK-KP-00 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-00)) (define SDLK-KP-000 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-000)) (define SDLK-THOUSANDSSEPARATOR (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-THOUSANDSSEPARATOR)) (define SDLK-DECIMALSEPARATOR (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-DECIMALSEPARATOR)) (define SDLK-CURRENCYUNIT (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-CURRENCYUNIT)) (define SDLK-CURRENCYSUBUNIT (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-CURRENCYSUBUNIT)) (define SDLK-KP-LEFTPAREN (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-LEFTPAREN)) (define SDLK-KP-RIGHTPAREN (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-RIGHTPAREN)) (define SDLK-KP-LEFTBRACE (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-LEFTBRACE)) (define SDLK-KP-RIGHTBRACE (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-RIGHTBRACE)) (define SDLK-KP-TAB (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-TAB)) (define SDLK-KP-BACKSPACE (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-BACKSPACE)) (define SDLK-KP-A (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-A)) (define SDLK-KP-B (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-B)) (define SDLK-KP-C (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-C)) (define SDLK-KP-D (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-D)) (define SDLK-KP-E (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-E)) (define SDLK-KP-F (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-F)) (define SDLK-KP-XOR (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-XOR)) (define SDLK-KP-POWER (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-POWER)) (define SDLK-KP-PERCENT (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-PERCENT)) (define SDLK-KP-LESS (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-LESS)) (define SDLK-KP-GREATER (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-GREATER)) (define SDLK-KP-AMPERSAND (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-AMPERSAND)) (define SDLK-KP-DBLAMPERSAND (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-DBLAMPERSAND)) (define SDLK-KP-VERTICALBAR (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-VERTICALBAR)) (define SDLK-KP-DBLVERTICALBAR (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-DBLVERTICALBAR)) (define SDLK-KP-COLON (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-COLON)) (define SDLK-KP-HASH (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-HASH)) (define SDLK-KP-SPACE (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-SPACE)) (define SDLK-KP-AT (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-AT)) (define SDLK-KP-EXCLAM (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-EXCLAM)) (define SDLK-KP-MEMSTORE (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-MEMSTORE)) (define SDLK-KP-MEMRECALL (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-MEMRECALL)) (define SDLK-KP-MEMCLEAR (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-MEMCLEAR)) (define SDLK-KP-MEMADD (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-MEMADD)) (define SDLK-KP-MEMSUBTRACT (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-MEMSUBTRACT)) (define SDLK-KP-MEMMULTIPLY (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-MEMMULTIPLY)) (define SDLK-KP-MEMDIVIDE (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-MEMDIVIDE)) (define SDLK-KP-PLUSMINUS (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-PLUSMINUS)) (define SDLK-KP-CLEAR (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-CLEAR)) (define SDLK-KP-CLEARENTRY (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-CLEARENTRY)) (define SDLK-KP-BINARY (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-BINARY)) (define SDLK-KP-OCTAL (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-OCTAL)) (define SDLK-KP-DECIMAL (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-DECIMAL)) (define SDLK-KP-HEXADECIMAL (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KP-HEXADECIMAL)) (define SDLK-LCTRL (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-LCTRL)) (define SDLK-LSHIFT (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-LSHIFT)) (define SDLK-LALT (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-LALT)) (define SDLK-LGUI (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-LGUI)) (define SDLK-RCTRL (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-RCTRL)) (define SDLK-RSHIFT (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-RSHIFT)) (define SDLK-RALT (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-RALT)) (define SDLK-RGUI (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-RGUI)) (define SDLK-MODE (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-MODE)) (define SDLK-AUDIONEXT (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-AUDIONEXT)) (define SDLK-AUDIOPREV (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-AUDIOPREV)) (define SDLK-AUDIOSTOP (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-AUDIOSTOP)) (define SDLK-AUDIOPLAY (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-AUDIOPLAY)) (define SDLK-AUDIOMUTE (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-AUDIOMUTE)) (define SDLK-MEDIASELECT (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-MEDIASELECT)) (define SDLK-WWW (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-WWW)) (define SDLK-MAIL (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-MAIL)) (define SDLK-CALCULATOR (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-CALCULATOR)) (define SDLK-COMPUTER (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-COMPUTER)) (define SDLK-AC-SEARCH (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-AC-SEARCH)) (define SDLK-AC-HOME (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-AC-HOME)) (define SDLK-AC-BACK (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-AC-BACK)) (define SDLK-AC-FORWARD (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-AC-FORWARD)) (define SDLK-AC-STOP (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-AC-STOP)) (define SDLK-AC-REFRESH (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-AC-REFRESH)) (define SDLK-AC-BOOKMARKS (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-AC-BOOKMARKS)) (define SDLK-BRIGHTNESSDOWN (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-BRIGHTNESSDOWN)) (define SDLK-BRIGHTNESSUP (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-BRIGHTNESSUP)) (define SDLK-DISPLAYSWITCH (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-DISPLAYSWITCH)) (define SDLK-KBDILLUMTOGGLE (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KBDILLUMTOGGLE)) (define SDLK-KBDILLUMDOWN (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KBDILLUMDOWN)) (define SDLK-KBDILLUMUP (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-KBDILLUMUP)) (define SDLK-EJECT (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-EJECT)) (define SDLK-SLEEP (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-SLEEP)) (define SDLK-APP1 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-APP1)) (define SDLK-APP2 (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-APP2)) (define SDLK-AUDIOREWIND (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-AUDIOREWIND)) (define SDLK-AUDIOFASTFORWARD (SDL-SCANCODE-TO-KEYCODE SDL-SCANCODE-AUDIOFASTFORWARD)) (define KMOD-NONE #x0000) (define KMOD-LSHIFT #x0001) (define KMOD-RSHIFT #x0002) (define KMOD-LCTRL #x0040) (define KMOD-RCTRL #x0080) (define KMOD-LALT #x0100) (define KMOD-RALT #x0200) (define KMOD-LGUI #x0400) (define KMOD-RGUI #x0800) (define KMOD-NUM #x1000) (define KMOD-CAPS #x2000) (define KMOD-MODE #x4000) (define KMOD-RESERVED #x8000) (define KMOD-CTRL (bitwise-ior KMOD-LCTRL KMOD-RCTRL)) (define KMOD-SHIFT (bitwise-ior KMOD-LSHIFT KMOD-RSHIFT)) (define KMOD-ALT (bitwise-ior KMOD-LALT KMOD-RALT)) (define KMOD-GUI (bitwise-ior KMOD-LGUI KMOD-RGUI)) ;;; ; ; ; ; ; ; ; ; ; ; ; ; ; ;;; ;;; Internal Data Definitions ;;; ;;; ; ; ; ; ; ; ; ; ; ; ; ; ; ;;; (define SDL-FIRSTEVENT-E 0) (define SDL-QUIT-E #x100) (define SDL-APP-TERMINATING-E #x101) (define SDL-APP-LOWMEMORY-E #x102) (define SDL-APP-WILLENTERBACKGROUND-E #x103) (define SDL-APP-DIDENTERBACKGROUND-E #x104) (define SDL-APP-WILLENTERFOREGROUND-E #x105) (define SDL-APP-DIDENTERFOREGROUND-E #x106) (define SDL-WINDOWEVENT-E #x200) (define SDL-SYSWMEVENT-E #x201) (define SDL-KEYDOWN-E #x300) (define SDL-KEYUP-E #x301) (define SDL-TEXTEDITING-E #x302) (define SDL-TEXTINPUT-E #x303) (define SDL-KEYMAPCHANGED-E #x304) (define SDL-MOUSEMOTION-E #x400) (define SDL-MOUSEBUTTONDOWN-E #x401) (define SDL-MOUSEBUTTONUP-E #x402) (define SDL-MOUSEWHEEL-E #x403) (define SDL-JOYAXISMOTION-E #x600) (define SDL-JOYBALLMOTION-E #x601) (define SDL-JOYHATMOTION-E #x602) (define SDL-JOYBUTTONDOWN-E #x603) (define SDL-JOYBUTTONUP-E #x604) (define SDL-JOYDEVICEADDED-E #x605) (define SDL-JOYDEVICEREMOVED-E #x606) (define SDL-CONTROLLERAXISMOTION-E #x650) (define SDL-CONTROLLERBUTTONDOWN-E #x651) (define SDL-CONTROLLERBUTTONUP-E #x652) (define SDL-CONTROLLERDEVICEADDED-E #x653) (define SDL-CONTROLLERDEVICEREMOVED-E #x654) (define SDL-CONTROLLERDEVICEREMAPPED-E #x655) (define SDL-FINGERDOWN-E #x700) (define SDL-FINGERUP-E #x701) (define SDL-FINGERMOTION-E #x702) (define SDL-DOLLARGESTURE-E #x800) (define SDL-DOLLARRECORD-E #x801) (define SDL-MULTIGESTURE-E #x802) (define SDL-CLIPBOARDUPDATE-E #x900) (define SDL-DROPFILE-E #x1000) (define SDL-DROPTEXT-E #x1001) (define SDL-DROPBEGIN-E #x1002) (define SDL-DROPCOMPLETE-E #x1003) (define SDL-AUDIODEVICEADDED-E #x1100) (define SDL-AUDIODEVICEREMOVED-E #x1101) (define SDL-RENDER-TARGETS-RESET-E #x2000) (define SDL-RENDER-DEVICE-RESET-E #x2001) (define SDL-USEREVENT-E #x8000) (define SDL-LASTEVENT-E #xFFFF) (define SDL-WINDOW-EVENT-SHOWN 1) (define SDL-WINDOW-EVENT-HIDDEN 2) (define SDL-WINDOW-EVENT-EXPOSED 3) (define SDL-WINDOW-EVENT-MOVED 4) (define SDL-WINDOW-EVENT-RESIZED 5) (define SDL-WINDOW-EVENT-SIZE-CHANGED 6) (define SDL-WINDOW-EVENT-MINIMIZED 7) (define SDL-WINDOW-EVENT-MAXIMIZED 8) (define SDL-WINDOW-EVENT-RESTORED 9) (define SDL-WINDOW-EVENT-ENTER 10) (define SDL-WINDOW-EVENT-LEAVE 11) (define SDL-WINDOW-EVENT-FOCUS-GAINED 12) (define SDL-WINDOW-EVENT-FOCUS-LOST 13) (define SDL-WINDOW-EVENT-CLOSE 14) (define SDL-WINDOW-EVENT-TAKE-FOCUS 15) (define SDL-WINDOW-EVENT-HIT-TEST 16)
false
a87126901e7d6c223bb2d8ac903b440b0b0af07f
bb65446a9debece8580bf0a20a229055038a5f6b
/guile/dds/base-impl/color.scm
a2a411dbbeebff9e665b27870a1788e803d88af2
[]
no_license
arvyy/DataDrivenScreenshots
f4ee1171c03a4a51cd96a3dd26b7205335445080
bd96d5bf22fdd449d681eaa509807108f72be442
refs/heads/master
2020-11-24T13:47:33.153065
2019-12-15T12:10:37
2019-12-15T12:10:37
228,175,925
0
0
null
null
null
null
UTF-8
Scheme
false
false
523
scm
color.scm
(define-module (dds base-impl color)) (use-modules (ice-9 match) (srfi srfi-9)) (define-record-type <color> (make-color r g b a) color? (r color-r) (g color-g) (b color-b) (a color-a)) (define (color->vec c) (match c (($ <color> r g b a) (vector r g b a)) (_ #f))) (define (vec->color v) (apply color (vector->list v))) (define* (color r g b #:optional (a 255)) (make-color r g b a)) (export <color> color? color->vec color vec->color color-r color-g color-b color-a)
false
fff7f2dcec47b4912e1e3c24a0b11dfbc22c5208
defeada37d39bca09ef76f66f38683754c0a6aa0
/UnityEngine/unity-engine/cursor.sls
e7f789026c1f0140009844439b9e8961cc354e6b
[]
no_license
futsuki/ironscheme-port
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
4e7a81b0fbeac9a47440464988e53fb118286c54
refs/heads/master
2016-09-06T17:13:11.462593
2015-09-26T18:20:40
2015-09-26T18:20:40
42,757,369
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,032
sls
cursor.sls
(library (unity-engine cursor) (export new is? cursor? set-cursor visible?-get visible?-set! visible?-update! lock-state-get lock-state-set! lock-state-update!) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new UnityEngine.Cursor a ...))))) (define (is? a) (clr-is UnityEngine.Cursor a)) (define (cursor? a) (clr-is UnityEngine.Cursor a)) (define-method-port set-cursor UnityEngine.Cursor SetCursor (static: System.Void UnityEngine.Texture2D UnityEngine.Vector2 UnityEngine.CursorMode)) (define-field-port visible?-get visible?-set! visible?-update! (static: property:) UnityEngine.Cursor visible System.Boolean) (define-field-port lock-state-get lock-state-set! lock-state-update! (static: property:) UnityEngine.Cursor lockState UnityEngine.CursorLockMode))
true
6862e8dac370da27446ae775299f81ab6a1a727f
cb8cccd92c0832e056be608063bbec8fff4e4265
/chapter2/Examples/2.2.2_HierarchicalStructures.scm
0ae3d0eaf8800cd775555f653131ecacc6909857
[]
no_license
JoseLGF/SICP
6814999c5fb15256401acb9a53bd8aac75054a14
43f7a8e6130095e732c6fc883501164a48ab2229
refs/heads/main
2023-07-21T03:56:35.984943
2021-09-08T05:19:38
2021-09-08T05:19:38
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
674
scm
2.2.2_HierarchicalStructures.scm
#lang scheme ; Recursion is a natural tool for dealing with tree structures ; , since we can ofter reduce operations on trees to oper- ; ations on their branches, which reduce to operations on lea- ; ves. ; Compare the length procedure of section 2.2.1: (define (length items) (if (null? items) 0 (+ 1 (length (cdr items))))) ; with the count-leaves procedure, which returns the total ; number of leaves of a tree: (define x (cons (list 1 2) (list 3 4))) (length x) (define (count-leaves tree) (cond ((null? tree) 0) ((not (pair? tree)) 1) (else (+ (count-leaves (car tree)) (count-leaves (cdr tree)))))) (count-leaves x)
false
451c1c99d60a3fd67b7728dd98ff1bb652d4e23e
4190d7db137e0e2c792c29df012bb9aa36f6fcad
/gi/c/regtype.sls
1114afb9518383d0425a6311a63a03bcfcf569d1
[ "Unlicense" ]
permissive
akce/chez-gi
e10e975ceecbb0f97652c70b5ac336ab2572bd2b
d7b78e2991a7120b92478e652d18be7a0a056223
refs/heads/master
2020-09-12T19:27:00.943653
2019-11-21T10:17:35
2019-11-21T10:17:35
222,526,577
2
0
null
null
null
null
UTF-8
Scheme
false
false
621
sls
regtype.sls
;; https://developer.gnome.org/gi/stable/gi-GIRegisteredTypeInfo.html ;; Written by Akce 2019. ;; SPDX-License-Identifier: Unlicense (library (gi c regtype) (export giregtype g-registered-type-info-get-type-name g-registered-type-info-get-type-init g-registered-type-info-get-g-type) (import (rnrs) (gi c glib) (gi c ftypes-util)) (define load-library (lso)) (define-ftype giregtype void*) (c-function (g-registered-type-info-get-type-name (giregtype) string) (g-registered-type-info-get-type-init (giregtype) string) (g-registered-type-info-get-g-type (giregtype) gtype)))
false
1aa069b957b67e63bca14285ea1258af40a10e47
ece1c4300b543df96cd22f63f55c09143989549c
/Chapter2/Exercise 2.26.scm
2681003a305708012ada7d637602ec81ff9f8dba
[]
no_license
candlc/SICP
e23a38359bdb9f43d30715345fca4cb83a545267
1c6cbf5ecf6397eaeb990738a938d48c193af1bb
refs/heads/master
2022-03-04T02:55:33.594888
2019-11-04T09:11:34
2019-11-04T09:11:34
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
760
scm
Exercise 2.26.scm
; Exercise 2.26: Suppose we define x and y to be two lists: (define x (list 1 2 3)) (define y (list 4 5 6)) ; What result is printed by the interpreter in response to evaluating each of the following expressions: (append x y) (cons x y) (list x y) ;(list x y) = (cons x (cons y nil)) (cons x (cons y nil)) ```````````````````````````````````` Welcome to DrRacket, version 6.7 [3m]. Language: SICP (PLaneT 1.18); memory limit: 128 MB. {mcons 1 {mcons 2 {mcons 3 {mcons 4 {mcons 5 {mcons 6 '()}}}}}} {mcons {mcons 1 {mcons 2 {mcons 3 '()}}} {mcons 4 {mcons 5 {mcons 6 '()}}}} {mcons {mcons 1 {mcons 2 {mcons 3 '()}}} {mcons {mcons 4 {mcons 5 {mcons 6 '()}}} '()}} {mcons {mcons 1 {mcons 2 {mcons 3 '()}}} {mcons {mcons 4 {mcons 5 {mcons 6 '()}}} '()}} >
false
aa0c640fc027aa1329f50edfe5a91d9b86268be9
ac2a3544b88444eabf12b68a9bce08941cd62581
/lib/termite/utils#.scm
6d1e23a37ee888e996190227da34726603896722
[ "Apache-2.0", "LGPL-2.1-only" ]
permissive
tomelam/gambit
2fd664cf6ea68859d4549fdda62d31a25b2d6c6f
d60fdeb136b2ed89b75da5bfa8011aa334b29020
refs/heads/master
2020-11-27T06:39:26.718179
2019-12-15T16:56:31
2019-12-15T16:56:31
229,341,552
1
0
Apache-2.0
2019-12-20T21:52:26
2019-12-20T21:52:26
null
UTF-8
Scheme
false
false
275
scm
utils#.scm
;; utils ;; ---------------------------------------------------------------------------- ;; Some basic utilities (##namespace ("termite/utils#" filter remove quoted-symbol? unquoted-symbol? make-uuid))
false
cc129fbba7245efbf2c884c3c512b3f61a27ff76
910c7561d77364436e75caacd9140b62ad606c00
/pkg/nftables.scm
2fc1fa54ae82b8de1af0afae66b7ea5ec12fe0e0
[]
no_license
SnellerInc/distill
567039bd436d1d1f78f01bf2e86064d33224c1fc
cec7234f46eede218d3c4d04e9e0c8dc53785a5a
refs/heads/master
2023-08-30T10:24:54.839538
2021-10-31T01:04:29
2021-10-31T01:05:45
416,853,839
0
0
null
null
null
null
UTF-8
Scheme
false
false
661
scm
nftables.scm
(import scheme (distill plan) (distill package) (distill base) (pkg libreadline) (pkg ncurses) (pkg jansson)) (define nftables (cmmi-package "nftables" "0.9.9" "http://netfilter.org/projects/nftables/files/$name-$version.tar.bz2" "xZDlbMRtT82r3nwMOtjtQDza-aqvfPd8vvDN3zDzmP8=" env: '((LIBMNL_LIBS . -lmnl) (LIBMNL_CFLAGS . -lmnl) (LIBNFTNL_LIBS . -lnftnl) (LIBNFTNL_CFLAGS . -lnftnl)) libs: (list ncurses jansson libgmp libmnl libnftnl linux-headers) tools: (list reflex byacc (interned-symlink "/usr/bin/byacc" "/usr/bin/yacc")) extra-configure: '(--disable-man-doc --without-cli --with-json)))
false
b47fc37291cef59b82974c246a4b9447213f458e
923209816d56305004079b706d042d2fe5636b5a
/sitelib/http/header-field/location.scm
918415600938b90dc546ea6eaccf51573e8bf30f
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
tabe/http
4144cb13451dc4d8b5790c42f285d5451c82f97a
ab01c6e9b4e17db9356161415263c5a8791444cf
refs/heads/master
2021-01-23T21:33:47.859949
2010-06-10T03:36:44
2010-06-10T03:36:44
674,308
1
0
null
null
null
null
UTF-8
Scheme
false
false
235
scm
location.scm
(library (http header-field location) (export Location) (import (rnrs (6)) (http abnf) (http uri)) ;;; 14.22 Location (define Location (seq (string->rule "Location") (char->rule #\:) *LWS absoluteURI)) )
false
d1cf4bc49e441b1097b6a40ab1f6f52070510f6e
d8bdd07d7fff442a028ca9edbb4d66660621442d
/scam/tests/00-syntax/other/when.scm
133cdb54300246a30d2cc045fea369c894069648
[]
no_license
xprime480/scam
0257dc2eae4aede8594b3a3adf0a109e230aae7d
a567d7a3a981979d929be53fce0a5fb5669ab294
refs/heads/master
2020-03-31T23:03:19.143250
2020-02-10T20:58:59
2020-02-10T20:58:59
152,641,151
0
0
null
null
null
null
UTF-8
Scheme
false
false
334
scm
when.scm
(import (only (scheme base) < >) (scheme write) (test narc)) (narc-label "When") (narc-expect (2 (when #t (display 1) 2)) (2 (when (> 3 2) (display 1) 1 2)) ('() (when (< 3 2) (display 1) 2))) (narc-catch (:syntax (when)) (:syntax (when #t))) (narc-report)
false
1f38c68be18fae59a9d463f76ca9c07d4735fdf2
0fb87930229b3bec24d7d6ad3dae79c715fd4c58
/src/scheme/tutorial/src/struct.scm
4edeefa3759efae809c3d70d09a9bc2d37a8c255
[ "BSD-2-Clause" ]
permissive
klose911/klose911.github.io
76beb22570b8e483532e8f2521b2b6334b4f856e
7d2407ff201af38d6c6178f93793b7d6cf59fbd8
refs/heads/main
2023-09-01T18:04:45.858325
2023-08-29T09:35:25
2023-08-29T09:35:25
73,625,857
3
2
Apache-2.0
2020-09-17T08:27:56
2016-11-13T15:52:32
HTML
UTF-8
Scheme
false
false
660
scm
struct.scm
(define-structure book title authors publisher year isbn) (define bazaar (make-book "The Cathedral and the Bazaar" "Eric S. Raymond" "O'Reilly" 1999 0596001088)) ; bazaar (define-structure (book keyword-constructor copier) title authors publisher year isbn) (define bazaar (make-book 'title "The Cathedral and the Bazaar" 'authors "Eric S. Raymond" 'publisher "O'Reilly" 'year 1999 'isbn 0596001088)) (book? bazaar) ; #t (define cathedral (copy-book bazaar)) ; cathedral (book-title bazaar) ; "The Cathedral and the Bazaar" (book-year bazaar) ; 1999 (set-book-year! bazaar 2001) (book-year bazaar) ; 2001
false
ed1aa6cd7983985b8607969fa3ea57e812b5a360
75efeba493b8ddf9b3d084962d7d9edf492a26cd
/test/helloworld.scm
b03a2bdac927eb99b23dd7799951c290c97ca3f8
[]
no_license
wehu/nao
63566553ce01fd7668b85cb04fbff2d01d894a99
ca6b0c76719e533e5a2a9561ee77e54fd7dc662a
refs/heads/master
2021-04-26T07:29:01.015941
2012-11-07T02:39:24
2012-11-07T02:39:24
6,457,247
0
1
null
null
null
null
UTF-8
Scheme
false
false
370
scm
helloworld.scm
(import nao) (define ch0 (make-chan "chan0")) (define ch1 (make-chan "chan1")) (always@ (ch0 ch1) (info (<- ch0)) (info (<- ch1)) (stop-server)) (start-server addr: "0.0.0.0" port: 1234) (define rch0 (make-remote-chan "chan0" addr: "0.0.0.0" port: 1234)) (define rch1 (make-remote-chan "chan1" addr: "0.0.0.0" port: 1234)) (-> rch0 "Hello") (-> rch1 "World")
false
171cbd2efe54bb651f6b7e6ba160e1da702e00df
de82217869618b0a975e86918184ecfddf701172
/srfi/arithmetic/reference/nary.scm
9f7a439e42a75295c3ff12ccf4dac3f7c9d285e9
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ]
permissive
schemedoc/r6rs
6b4ef7fd87d8883d6c4bcc422b38b37f588e20f7
0009085469e47df44068873f834a0d0282648750
refs/heads/master
2021-06-18T17:44:50.149253
2020-01-04T10:50:50
2020-01-04T10:50:50
178,081,881
5
0
null
null
null
null
UTF-8
Scheme
false
false
933
scm
nary.scm
; This file is part of the reference implementation of the R6RS Arithmetic SRFI. ; See file COPYING. ; Utilities for implementing n-ary procedures out of binary ones. (define (make-transitive-pred pred) (lambda (arg1 arg2 . args) (cond ((pred arg1 arg2) (let loop ((last arg2) (args args)) (cond ((null? args) #t) ((pred last (car args)) (loop (car args) (cdr args))) (else #f)))) (else #f)))) (define (reduce unit combine args) (cond ((null? args) unit) ((null? (cdr args)) (combine unit (car args))) (else (let loop ((acc (combine (car args) (cadr args))) (args (cddr args))) (if (null? args) acc (loop (combine acc (car args)) (cdr args))))))) (define (make-min/max comp) (lambda (arg0 . args) (let loop ((m arg0) (args args)) (cond ((null? args) m) ((comp (car args) m) (loop (car args) (cdr args))) (else (loop m (cdr args)))))))
false
0e8cd53ce4d12f67b162591999666739d5cc23a7
42e51abfeca55d4e37bcc598c3707b16840f3f8f
/sush.scm
e5aab6ec3292defbb478df74089a344d77e259d9
[ "MIT" ]
permissive
grafi-tt/sush
49693527854855c747dc9e09723d5445d79634d6
12750949de26e4ceb957e42df64a1e3ca7bc7768
refs/heads/master
2016-09-06T00:15:42.217500
2013-03-13T12:22:23
2013-03-13T12:22:23
8,690,470
1
0
null
null
null
null
UTF-8
Scheme
false
false
1,123
scm
sush.scm
(load "./structure.scm") (load "./eval.scm") (load "./macro.scm") (load "./builtin.scm") (define (repl) (let ((stack (make-top-stack))) (define (loop) (display "sush> ") (flush) (let ((expr (read))) (if (eof-object? expr) (begin (display "Oaiso!\n") #t) (let ((val (eval-expr stack expr))) (newline) (loop))))) (loop))) (define (top-eval-write exprs) (let ((stack (make-top-stack))) (let loop ((exprs exprs)) (if (null? exprs) #t (let ((val (eval-expr stack (car exprs)))) (print-data val) (newline) (loop (cdr exprs))))))) (define (make-top-stack) (let ((stack (make-empty-stack (make-builtin-env)))) (for-each (lambda (expr) (eval-expr stack expr)) base-library-exprs) stack)) (define (show val) (cond ((obj-error? val) (list 'error (cddr val) (show-stack (cadr val)))) ((obj-pair? val) (cons (show (cadr val)) (show (cddr val)))) ((obj-nil? val) '()) (else val))) (define (show-stack stack) (car stack) '())
false
6caacf529d0ec58a7bc8cc2eb3014621401279de
b13ba2793dbf455e2a6b5b50de6a1c253dd6b794
/spec/self-running.scm
53629bdb4b954db7de0a2921bedf4962ccc98bdb
[]
no_license
jmax315/missbehave
ca924a7e9272948e54b73385a9d2206d39324cdc
5ceee8e0ef1b96362b4a28400b227cc1406a7fbb
refs/heads/master
2021-01-07T19:47:53.572758
2020-02-20T05:31:53
2020-02-20T05:31:53
241,802,990
0
0
null
2020-07-28T08:21:28
2020-02-20T05:40:07
Scheme
UTF-8
Scheme
false
false
138
scm
self-running.scm
(use missbehave) (run-specification (call-with-specification (make-empty-specification) (lambda () (include "test.scm"))))
false
0975f4fd79730965af00ce774db142ff33d96672
a70301d352dcc9987daf2bf12919aecd66defbd8
/mredtalk3/talk.ss
c95bdf7aabe5ce83896a75d291fd18471ba6b155
[]
no_license
mflatt/talks
45fbd97b1ca72addecf8f4b92053b85001ed540b
7abfdf9a9397d3d3d5d1b4c107ab6a62d0ac1265
refs/heads/master
2021-01-19T05:18:38.094408
2020-06-04T16:29:25
2020-06-04T16:29:25
87,425,078
2
2
null
null
null
null
UTF-8
Scheme
false
false
36,924
ss
talk.ss
#lang slideshow (require (lib "mred.ss" "mred") (lib "class.ss") (lib "math.ss") (lib "list.ss") (lib "etc.ss") (lib "step.ss" "slideshow") slideshow/code racket/runtime-path "../mredtalk2/modified.ss" "../mredtalk2/angel-sequence.ss" "../mredtalk2/demo-eval.ss" "accounting.ss" "ks.ss") (provide mred-slides) (define-runtime-path people "people") (define-runtime-path mag.png "magnify.png") (define-runtime-path mag2.png "magnify2.png") (define-runtime-path web-break-png "browser.png" #;"web-break.png") (define-runtime-path demo-rkt "../mredtalk2/demo.rkt") (define (mred-slides) (define title-slide? #f) (define gnosys? #f) (define gnosys-title? gnosys?) (define os-title? #t) (define chinese-name? #f) (define edited-for-content? #f) (define angel-slides? #t) (use-pl-labels #t) (define use-angel-wings? #f) (define short-angel-sequence? #t) (define process-facet-list-early? #f) (define process-facet-list-late? #t) (define non-drscheme-examples? #t) (define compare-termination-languages? #f) (define limit-memory-slide? #f) (define accounting-section? #f) (define kill-safe-section? #f) (define fine-print? #f) (define long-conclusion? #f) (define no-conclusion? #t) (define skip-icfp99-cite? #t) (bitmap-draft-mode #f) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (author who where) (vc-append (current-line-sep) (colorize (bt who) "blue") (blank (/ (current-font-size) 3)) (scale/improve-new-text (t where) 0.8))) (define PERSON-H (* 4 gap-size)) (define (add-picture who p) (let ([img (bitmap (build-path people (format "~a.jpg" (car (regexp-match #rx"^[A-Z][a-z]+" who)))))]) (vc-append (scale img (/ PERSON-H (pict-height img))) p))) (define (authors whos where) (vc-append (current-line-sep) (scale (apply hc-append (* 2 gap-size) (for/list ([who (in-list whos)]) (if (pict? who) who (add-picture who (bt who))))) 0.8) (scale (t where) 0.8))) (when title-slide? (slide (vc-append (current-line-sep) (cond [gnosys-title? (vc-append (current-line-sep) (titlet "GnoSys: Raising the Level of Discourse") (titlet "in Programming Systems"))] [os-title? (titlet "Programming Languages as Operating Systems")] [else (titlet "Processes without Partitions")])) (blank) (if gnosys-title? (blank) (bitmap (build-path (collection-path "icons") "PLT-206.png"))) (blank) (if gnosys-title? (vc-append (* 2 gap-size) (authors '("Olin Shivers" "Matthias Felleisen" "Pete Manolios" "Mitch Wand") "Northeastern University") (authors (list "Matt Might" (add-picture "Matthew" (colorize (bt "Matthew Flatt") "blue"))) "University of Utah")) (vc-append (current-line-sep) (author (string-append "Matthew Flatt" (if chinese-name? " 马晓" "")) "University of Utah") (blank) (blank) (scale/improve-new-text (let ([a (author "Adam Wick" "University of Utah")] [r (author "Robert Bruce Findler" "Northwestern University")]) (hc-append (* 3 gap-size) (cc-superimpose (ghost r) a) (cc-superimpose (ghost a) r))) 0.80))))) (when edited-for-content? (modified-slide)) (use-angel-wings use-angel-wings?) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (mgt s) (colorize (bt s) "forestgreen")) (define (spin p theta) (let ([d (make-pict-drawer p)] [w (pict-width p)] [h (pict-height p)]) (let ([w2 (+ (abs (* w (cos theta))) (abs (* h (sin theta))))] [h2 (+ (abs (* h (cos theta))) (abs (* w (sin theta))))]) (dc (lambda (dc x y) (let ([t (send dc get-transformation)]) (send dc translate (+ x (/ w 2) (/ (- w2 w) 2)) (+ y (/ h 2) (/ (- h2 h) 2))) (send dc rotate theta) (d dc (/ w -2) (/ h -2)) (send dc set-transformation t))) w2 h2)))) (define servlet (scale (vc-append (scheme-angel-file) (tt "servlet.rkt")) 0.75)) (when gnosys? (with-steps (server analyze servlets contracts) (slide #:title "A GnoSys Application" (blank) (let ([contract-dircomm (scale (if (after? contracts) (refocus (vc-append (mgt "contracts") short-dircomm (mgt "processes")) short-dircomm) short-dircomm) 0.75)]) (vc-append (let ([ws (vc-append (scheme-angel-file) (tt "web-server.rkt"))] [lglass (bitmap mag2.png)] [rglass (bitmap mag.png)]) (let ([l (inset (vr-append (inset (mgt "static analysis") 0 0 (* 2 gap-size) 0) (scale lglass 1/2)) 0 -50 -40 0)] [r (inset (vl-append (inset (mgt "theorem proving") (* 2 gap-size) 0 0 0) (scale rglass 1/2)) -40 -50 0 0)]) (inset (hc-append ((vafter analyze) l) (inset ws -10 30 -10 0) ((vafter analyze) r)) (- (pict-width l)) 0 (- (pict-width r)) 0))) ((vafter servlets) (hc-append (* 4 gap-size) (vc-append (inset (spin contract-dircomm (* pi 3/8)) 60 0 0 0) servlet) (vc-append (inset (spin contract-dircomm (* pi -3/8)) 0 0 60 0) servlet)))))))) (define gnosys-slide (most-recent-slide)) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define dim-color "dark gray") (define hilite-color "black") (define bright-color "blue") ; was "purple" (define (half-page-item . s) (apply item #:width (* client-w 3/4) s)) (define (make-link s) (let ([p (t s)]) (refocus (colorize (vc-append p (linewidth 2 (hline (pict-width p) 1))) "blue") p))) (define outline (apply make-outline 'motivation "Motivation and Approach" #f 'plt-scheme "Processes in Racket" (lambda (sym) (vl-append (* 3 (current-line-sep)) (half-page-item "Threads") (half-page-item "Parameters") (half-page-item "Eventspaces") (half-page-item "Custodians"))) 'accounting "Memory Accounting" (lambda (sym) (half-page-item "Without partitions" (blank (current-font-size)) (colorize (t "[ISMM 04]") dim-color))) (if kill-safe-section? (list 'kill-safe "Synchronization Abstractions" (lambda (sym) (half-page-item "From thread-safe to kill-safe" (blank (current-font-size)) (colorize (t "[PLDI 04]") dim-color)))) null))) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (when angel-slides? (if short-angel-sequence? (if use-angel-wings? (simpler-angel-slides) (simplest-angel-slides)) (angel-slides))) (define (process-facet-list-slide) (slide #:title (if (use-pl-labels) "Process Concepts" "Languages as Operating Systems") (item "Threads") (item "Process-specific state (e.g., current directory)") (item "Graphical event loops") (item "Debugging capabilities") (item "Resource accounting") (item "Terminate a process and reclaim resources"))) (when process-facet-list-early? (process-facet-list-slide)) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (mrt2-bitmap file) (bitmap (build-path (this-expression-source-directory) 'up "mredtalk2" file))) (define (file-label p s) (vc-append (current-line-sep) p (bt s))) (define prog-process-title "Process Examples") #; (when non-drscheme-examples? (slide #:title prog-process-title (rb-superimpose (inset (bitmap "firefox.png") 0 0 (* gap-size 3) (* gap-size 4)) (bitmap "terminal.png")))) #; (slide/title/center prog-process-title (mrt2-bitmap "installer.bmp")) (when non-drscheme-examples? (slide #:title prog-process-title (bitmap web-break-png))) (when non-drscheme-examples? (slide #:title prog-process-title (let ([ws (mrt2-bitmap "web-server.png")] [ie (mrt2-bitmap "ie.bmp")] [chrome (mrt2-bitmap "chrome.png")] [firefox (mrt2-bitmap "firefox.png")] [safari (mrt2-bitmap "safari.png")]) (let ([ies (map launder (list ie chrome firefox safari))]) (let ([p (vc-append (* 2 (pict-height ws)) ws (apply hc-append (* 2 (pict-width ie)) ies))]) (foldl (lambda (ie p) (pin-line p ws cb-find ie ct-find #:line-width 1 #:color dim-color)) p ies)))))) (when #f (when non-drscheme-examples? (slide #:title prog-process-title (mrt2-bitmap "sirmail.bmp")))) (define (mk-drs-layout s) (let* ([user-file (ghost (scheme-angel-file))] [main (vc-append (/ (current-font-size) 2) (hc-append (file-label (scheme-angel-file) "DrRacket") (ghost dircomm) (file-label user-file "user’s program")) (blank) together-arrows mred-logo)]) (let-values ([(x y) (lt-find main user-file)]) (pin-over main x y (let* ([u (scheme-angel-file)] [big (scale u s s)]) (inset big (/ (- (pict-width u) (pict-width big)) 2) (/ (- (pict-height u) (pict-height big)) 2))))))) (slide #:title prog-process-title (blank) (blank) (mk-drs-layout 1) (blank) (blank) (blank) (para (clickback (make-link "Run DrRacket") (lambda () (end-subtalk) (begin-subtalk) (subtalk-eval `(begin (current-command-line-arguments (vector ,(path->string demo-rkt))) (exit-handler (lambda (x) (,end-subtalk))) (dynamic-require 'drracket #f))))))) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (when process-facet-list-late? (process-facet-list-slide)) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define object-color "forest green") (define (mk-object size) (cloud (* size 1.5 (current-font-size)) (* size (current-font-size)) object-color)) (define (mk-partition-icon objs) (frame (inset (hc-append (current-font-size) (scheme-angel-file) objs) (/ (current-font-size) 2)))) (define (connect-all p o . tos) (let loop ([p p][tos tos]) (if (null? tos) p (loop (pin-line p o cb-find (car tos) ct-find #:line-width 1 #:color object-color) (cdr tos))))) (define memory-icon (let* ([a1 (launder (scheme-angel-file))] [a2 (launder (scheme-angel-file))] [o1 (mk-object 1)] [o2 (mk-object 1.2)] [o3 (mk-object 1.3)] [o4 (mk-object 1)] [o5 (mk-object 1.4)] [o6 (mk-object 1.25)] [p (vc-append (current-font-size) (hc-append (* 0.5 (pict-width a1)) a1 a2) (blank) (hc-append (current-font-size) (ghost (launder o3)) o1 (blank) o2) (blank) (hc-append (current-font-size) o5 (ghost (launder o1)) o3 (ghost (launder o2)) o4 o6))]) (connect-all (connect-all (connect-all (connect-all p a1 o1 o5) a2 o1 o2) o2 o6 o4) o1 o3))) (define unix-memory-icon (hc-append (current-font-size) (mk-partition-icon (vc-append (mk-object 2) (hc-append (mk-object 1) (mk-object 1.2)))) (mk-partition-icon (vc-append (hc-append (vc-append (mk-object 1) (mk-object 1.2)) (mk-object 2)) (mk-object 1.3))))) (define (citation who) (colorize (t (format "[~a]" who)) dim-color)) (define (cite what who) (if who (hbl-append (bt what) (t " ") (citation who)) (bt what))) (define term-title "Languages with Termination") (define summary-figure (vc-append (current-font-size) (hc-append (scheme-angel-file) dircomm (scheme-angel-file)) together-arrows mred-logo)) (when compare-termination-languages? (slide #:title term-title (table 2 (list (cite "Pilot" "Redell80") (cite "SPIN" "Bershad95") (cite "JKernel" "Hawblitzel98") (cite "Alta" "Tullman99") (cite "KaffeOS" "Back00") (cite "JSR-121" "Soper03") (cite ".NET application domains" #f) (cite "Singularity" "Hunt07")) lbl-superimpose lbl-superimpose (* 4 gap-size) (* 2 gap-size)) 'next (blank) (blank) unix-memory-icon) (slide #:title term-title (cite "Racket" #f) (blank) (blank) memory-icon) (slide #:title "Processes" summary-figure (blank) (let ([w (* client-w 1/3)]) (hc-append (* 2 gap-size) (para #:width w #:fill? #f #:align 'center "Processes without partitions") (scale (t "⇒") 2) (para #:width w #:fill? #f #:align 'center "Break ``process'' into multiple facets"))))) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (current-demo-directory (build-path (this-expression-source-directory) 'up "mredtalk2")) (define eval-link (scale (make-link "eval") 0.75)) (define aspect-layout #;'tall 'center) (define aspectual (case-lambda [(s) (colorize (btitlet s) bright-color)] [(s a) (hbl-append (aspectual s) (titlet " – ") (titlet a))])) (define (btitlet s) (text s (current-main-font) 40)) (define (aspect s) 'nothing #; (colorize (para #:fill? #f ;; capitalize s: (it (string-append (string (char-upcase (string-ref s 0))) (substring s 1 (string-length s))))) "blue")) (define (mk-code-eval code) (lambda () (begin-subtalk) (subtalk-eval (read (open-input-string (format "(begin . ~s)" code)))))) (define-syntax-rule (eval-code-slide title . body) (demo-slide/title title (mk-code-eval (strip-unquote 'body)) (scale (code . body) code-scale))) (define-syntax (with-hilite stx) (syntax-case stx () [(_ [id ...] expr) (let ([ids (map syntax-e (syntax->list #'(id ...)))]) #`(code #,(let loop ([expr #'expr]) (cond [(identifier? expr) (if (memq (syntax-e expr) ids) (datum->syntax expr `(unsyntax (hilite (code ,expr))) expr) expr)] [(syntax? expr) (datum->syntax expr (loop (syntax-e expr)) expr expr)] [(pair? expr) (cons (loop (car expr)) (loop (cdr expr)))] [else expr]))))])) (define (strip-unquote v) (cond [(not (pair? v)) v] [(eq? 'code:blank (car v)) (strip-unquote (cdr v))] [(eq? 'unsyntax (car v)) (let loop ([v (last v)]) (cond [(eq? (car v) 'code) (strip-unquote (cadr v))] [(eq? 'with-hilite (car v)) (strip-unquote (caddr v))] [else (loop (last v))]))] [else (cons (strip-unquote (car v)) (strip-unquote (cdr v)))])) (define code-scale 0.8) (define-syntax-rule (eval-code-block/sep sep . body) (hbl-append sep (scale (code . body) code-scale) (clickback eval-link (mk-code-eval (strip-unquote 'body))))) (define-syntax-rule (eval-code-block . body) (eval-code-block/sep (current-font-size) . body)) (define-syntax-rule (normal c) (parameterize ([code-colorize-enabled #t]) c)) (define-syntax-rule (hilite c) (parameterize ([code-colorize-enabled #f]) (colorize c bright-color))) (define-syntax-rule (unhilite c) (parameterize ([code-colorize-enabled #f]) (colorize c dim-color))) (slide #:title (aspectual "Threads") #:layout aspect-layout #:inset demo-inset (aspect "concurrent execution") (blank) (vl-append (hbl-append (current-font-size) (scale (code (require "spin-display.rkt")) code-scale) (clickback eval-link (lambda () (end-subtalk) (begin-subtalk) (subtalk-eval '(require "spin-display.scm"))))) (eval-code-block code:blank (define (spin) (rotate-a-little) (sleep 0.1) (spin)) code:blank (define spinner (#,(hilite (code thread)) spin))) (eval-code-block code:blank (#,(hilite (code kill-thread)) spinner)))) (slide #:title (aspectual "Parameters" "Thread-local State") #:layout aspect-layout #:inset demo-inset (aspect "thread-local state") (vl-append (current-line-sep) (eval-code-block (printf "Hello\n") (fprintf (#,(hilite (code current-output-port))) "Hola\n") (fprintf (#,(hilite (code current-error-port))) "Goodbye\n") (error "Ciao")) (eval-code-block/sep 0 code:blank #,(with-hilite [parameterize] (parameterize ([current-error-port (current-output-port)]) (error "Au Revoir")))) (eval-code-block/sep 0 code:blank #,(with-hilite [parameterize thread] (parameterize ([current-error-port (current-output-port)]) (thread (lambda () (error "\u518D\u89C1")))))))) (slide #:title (aspectual "Eventspaces" "Concurrent GUIs") #:layout aspect-layout #:inset demo-inset (aspect "concurrent GUIs") (blank) (vl-append (current-line-sep) (eval-code-block (thread (lambda () (message-box "One" "Hi"))) (thread (lambda () (message-box "Two" "Bye")))) (eval-code-block code:blank code:blank (thread (lambda () (message-box "One" "Hi"))) #,(with-hilite [current-eventspace make-eventspace] (parameterize ([current-eventspace (make-eventspace)]) (thread (lambda () (message-box "Two" "Bye")))))))) (slide #:title (aspectual "Custodians" "Termination and Clean-up") #:layout aspect-layout #:inset demo-inset (aspect "termination and clean-up") (blank) (vl-append (current-line-sep) (hbl-append (current-font-size) (scale (code (define c (#,(hilite (code make-custodian)))) (parameterize ([#,(hilite (code current-custodian)) c]) ....)) code-scale) (clickback eval-link (lambda () (end-subtalk) (begin-subtalk) (subtalk-eval '(define c (make-custodian))) (subtalk-eval '(parameterize ((current-custodian c)) (parameterize ((current-eventspace (make-eventspace))) (dynamic-require "start-a-lot.scm" #f))))))) (eval-code-block code:blank (#,(hilite (code custodian-shutdown-all)) c)))) (when limit-memory-slide? (slide #:title (aspectual "Custodians" "Resource Limits") #:layout aspect-layout #:inset demo-inset (aspect "resource limits") (blank) (vl-append (current-line-sep) (hbl-append (current-font-size) (scale (code (define (run-away) (cons 1 (run-away))) code:blank (#,(hilite (code custodian-limit-memory)) c 2000000) code:blank (parameterize ([current-custodian c]) .... (thread run-away))) code-scale) (clickback eval-link (lambda () (end-subtalk) (begin-subtalk) (subtalk-eval '(define c (make-custodian))) (subtalk-eval '(begin (custodian-limit-memory c 2000000) (parameterize ([current-custodian c]) (parameterize ([current-eventspace (make-eventspace)]) (dynamic-require "start-a-lot.scm" #f) (thread (lambda () (let loop () (cons (loop))))))))))))))) (define (demo-slide/title s thunk . x) (slide #:title s #:inset demo-inset (lbl-superimpose (cc-superimpose (apply-slide-inset demo-inset titleless-page) (apply vl-append (current-font-size) x)) (clickback eval-link thunk)))) (slide #:title "Building a Programming Environment" (para #:fill? #f (clickback (make-link "RacketEsq") (lambda () (end-subtalk) (begin-subtalk) (subtalk-eval '(require "racket-esq.rkt")))) ", a mini DrRacket" (blank (current-font-size)) (if skip-icfp99-cite? "" (colorize (t "[ICFP 99]") dim-color)))) (demo-slide/title "GUI – Frame" (lambda () (end-subtalk) (begin-subtalk) (subtalk-eval '(begin (define frame (new frame% [label "RacketEsq"] [width 400] [height 185])) (send frame show #t)))) (scale (code (define frame (new #,(hilite (code frame%)) [label "RacketEsq"] [width 400] [height 175])) code:blank (send frame show #t)) code-scale)) (eval-code-slide "GUI – Reset Button" (new #,(hilite (code button%)) [label "Reset"] [parent frame] [callback (lambda (b e) (reset-program))])) (eval-code-slide "GUI – Interaction Area" (define repl-display-canvas (new #,(hilite (code editor-canvas%)) [parent frame]))) (demo-slide/title "GUI – Interaction Buffer" (lambda () (subtalk-eval '(begin (load "text.ss") (define repl-editor (make-object esq-text%)) (send repl-display-canvas set-editor repl-editor)))) (scale (code (define esq-text% (class #,(hilite (code text%)) .... (evaluate str) ....)) code:blank (define repl-editor (new esq-text%)) (send repl-display-canvas set-editor repl-editor)) code-scale)) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (eval-code-slide "Evaluator" #,(with-hilite [thread read eval print] (define (evaluate expr-str) (thread (lambda () (print (eval (read (open-input-string expr-str)))) (newline) (send repl-editor new-prompt)))))) (demo-slide/title "Evaluator Output" (lambda () (subtalk-eval '(begin (define user-output-port (make-output-port 'stdout always-evt (lambda (s start end nonblock? w/break?) (send repl-editor output (bytes->string/utf-8 (subbytes s start end))) (- end start)) void)) (define (evaluate expr-str) (thread (lambda () (current-output-port user-output-port) (with-handlers ((exn? (lambda (exn) (display (exn-message exn))))) (print (eval (read (open-input-string expr-str))))) (newline) (send repl-editor new-prompt))))))) (scale (code (define user-output-port (make-output-port .... repl-editor ....)) code:blank #,(unhilite (code (define (evaluate expr-str) #,(normal (code (parameterize ([current-output-port user-output-port]) #,(unhilite (code (thread (lambda () ....))))))))))) code-scale)) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (demo-slide/title "Evaluating GUIs" (lambda () (subtalk-eval '(begin (define user-eventspace (make-eventspace)) (define (evaluate expr-str) (thread (lambda () (current-output-port user-output-port) (current-eventspace user-eventspace) (with-handlers ((exn? (lambda (exn) (display (exn-message exn))))) (print (eval (read (open-input-string expr-str))))) (newline) (send repl-editor new-prompt))))))) (scale (code (define user-eventspace (make-eventspace)) code:blank #,(unhilite (code (define (evaluate expr-str) (parameterize ([current-output-port user-output-port] #,(normal (code [current-eventspace user-eventspace]))) (thread (lambda () ....))))))) code-scale)) (demo-slide/title "Custodian for Evaluation" (lambda () (subtalk-eval '(begin (define user-custodian (make-custodian)) (define user-eventspace (parameterize ((current-custodian user-custodian)) (make-eventspace))) (define (evaluate expr-str) (parameterize ((current-custodian user-custodian) (current-eventspace user-eventspace)) (queue-callback (lambda () (current-output-port user-output-port) (with-handlers ((exn? (lambda (exn) (display (exn-message exn))))) (print (eval (read (open-input-string expr-str))))) (newline) (send repl-editor new-prompt)))))))) (scale (code (define user-custodian (make-custodian)) code:blank (define user-eventspace (parameterize ([current-custodian user-custodian]) (make-eventspace))) code:blank #,(unhilite (code (define (evaluate expr-str) (parameterize ([current-output-port user-output-port] [current-eventspace user-eventspace] #,(normal (code [current-custodian user-custodian]))) (thread (lambda () ....))))))) code-scale)) (eval-code-slide "Reset Evaluation" (define (reset-program) (custodian-shutdown-all user-custodian) code:blank (set! user-custodian (make-custodian)) (parameterize ((current-custodian user-custodian)) (set! user-eventspace (make-eventspace)) (send repl-editor reset)))) #; (eval-code-slide "Limit Memory Use" #,(unhilite (code (define (reset-program) (custodian-shutdown-all user-custodian) code:blank (set! user-custodian (make-custodian)) #,(normal (code (custodian-limit-memory user-custodian 1000000))) (parameterize ((current-custodian user-custodian)) (set! user-eventspace (make-eventspace)) (send repl-editor reset)))))) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (when fine-print? (parameterize ([current-para-width (* 0.9 client-w)]) (slide #:title "Fine Print" (item "Kill-safe synchronization requires programmer effort" (citation "PLDI 04")) (item "Reachability-based memory accounting needs hierarchy" (citation "ISMM 04")) (item "Continuations need to be delimited" (citation "ICFP 07")) (item "Contracts need specific runtime support" (citation "in submission")) #;(item "A safe-for-space runtime implementation matters" (citation "ongoing")) (item "Safe language extension needs permissions on syntax" (citation "ongoing"))))) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; #| (require "../killsafetalk/squiggle.ss") (define (scale-process p) (scale p 4)) (slide/title/center "Recap: Unix" (scale-process unix)) (slide/title/center "Recap: Lisp Machine" (scale-process jvm)) (slide/title/center "Recap: Racket" (scale-process mz)) |# ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (when accounting-section? (outline 'accounting) (for-each (lambda (s) (slide #:title "Resource Consumption" (mk-drs-layout s))) '(1 1.25 1.5 2 3 4)) (void (parameterize ([current-para-width (* client-w 0.9)]) (with-steps (unix mz gc) (slide #:title "Resource Accounting" (cc-superimpose ((vonly unix) (item (colorize (bt "Conventional OS") "red") ": process memory use = size of partition")) ((vonly mz) (item (colorize (bt "Language as OS") "blue") ": process memory use = size of owned data")) ((vonly gc) (para "Our strategy: compute accounting charges during GC"))) (blank) (cc-superimpose ((vonly unix) unix-memory-icon) ((vafter mz) memory-icon)) (blank) (cc-superimpose ((vonly unix) (vc-append gap-size (subitem "Accounting is easy") (subitem "Trading data is difficult"))) ((vonly mz) (vc-append gap-size (subitem "Trading data is easy") (subitem "Accounting" (it "appears") "difficult: sharing, real-time tracking"))) ((vonly gc) (vc-append gap-size (para "See also [Price03]") #; (colorize (para* "Exact accounting is" (hbl-append (t "O(N") (text "2" `(superscript . , main-font) font-size) (t ")")) "in the worst case...") "red"))))))))) (define ((owner +a?) s) (if (memq s '(z s)) `(,(if +a? "B, A" "B") ,(symbol->string s) #f) `("A" ,(symbol->string s) #t))) (when accounting-section? (void (with-steps (unknown known link) (slide #:title "Basic Accounting" (make-basic-picture '(A B) '(1 2 3) `(,(map (before known values (owner (after? link))) '(x y z)) ,(map (before known values (owner (after? link))) '(q r s))) `((A 1) (A 2) (B 3) ,@(after link '((B A)) null) (1 x) (2 y) (3 z) (x q) (y r) (z s))))))) (define (mk-sharing-picture known? child?) (make-basic-picture '(A B) '(1 2) (if known? `((["A" "x" #t] ["B" "y" #f]) ([,(if child? "A" "A or B") "z" #t])) '((x y) (z))) `((A 1) (B 2) (1 x) (2 y) (x z) (y z) ,@(if child? '((B A)) '())))) (when accounting-section? (void (with-steps (unknown both child) (slide #:title (after child "Sharing: Charge the Parent" "Sharing") (mk-sharing-picture (after? both) (after? child))))) (void (with-steps (unknown known cust weak) (slide #:title "Threads, Custodians, and Weak References" (make-basic-picture '(A B) '(1 2) (before known '((x)) '((("B" "x" #t)))) `((A 1) (B 2) ,(after weak `(1 x !) `(1 ,(after cust 'B 2))) (2 x)))))) (slide #:title "Why Charge the Parent?" (blank) (blank) (mk-sharing-picture #t #t) (blank) (blank) (blank) (blank) 'next (item "Parent is responsible for children") 'next (item "Children refer to parent, so if the parent refers to children data directly," " any child is charged for all children"))) (define (full-strikeout image) (let ([w (pict-width image)] [h (pict-height image)]) (dc (lambda (dc dx dy) (let ([pen (send dc get-pen)] [pictdraw (make-pict-drawer image)]) (pictdraw dc dx dy) (send dc set-pen (make-object pen% (make-object color% "Red") 10 'solid)) (send dc draw-line dx dy (+ w dx) (+ h dy)) (send dc draw-line (+ dx w) dy dx (+ dy h)) (send dc set-pen pen))) w h 0 0))) (define (strikeout image) (let ([w (pict-width image)] [h (pict-height image)]) (cb-superimpose image (inset (full-strikeout (blank w (* 2/5 h))) 0 0 0 (* 1/10 h))))) (define dscheme (scale (bitmap "loop.png") 0.45)) (define dscheme-busy (scale (bitmap "deep.png") 0.45)) (define running-lbl (colorize (bt "Bad Loop") "Red")) (define normal-lbl (colorize (bt "Normal") "Blue")) (define killed-lbl (colorize (bt "Shut Down") "Red")) (define (drs-slide init? so1 so2 l1 l3) (slide #:title (string-append (if init? "Initial " "Current ") "Experience: DrRacket") (hc-append 40 (vc-append 20 (so1 dscheme-busy) l1) (vc-append 20 dscheme normal-lbl) (vc-append 20 (so2 dscheme) l3)))) (when accounting-section? (drs-slide #t values values running-lbl normal-lbl) (drs-slide #t values strikeout running-lbl killed-lbl)) (define (inset-i p) (inset p 20 0 0 0)) (when accounting-section? (void (with-steps (strong weak explain) (slide #:title (before weak "DrRacket Bug" "DrRacket Repair") (blank) (make-basic-picture '(DrRacket User1 User2) '(0 1 2) '((x _ _) (_ y z)) `((DrRacket 0) (User1 1) (User2 2) (0 x) (1 x) (2 x) (1 y) (2 z) (x y ,@(after weak '(!) '())) (x z ,@(after weak '(!) '())))) (blank) ((vafter explain) (vl-append (* 2 (current-line-sep)) (para #:fill? #f "Changed 5 references:") (inset-i (item #:fill? #f "Weakened 2")) (inset-i (item #:fill? #f "Removed 2")) (inset-i (item #:fill? #f "Moved 1 into child"))))))) (drs-slide #f values values running-lbl normal-lbl) (drs-slide #f strikeout values killed-lbl normal-lbl) (slide #:title "Accounting without Partitions" (vl-append gap-size (para #:fill? #f "Useful accounting") (item #:fill? #f "Doesn't need partitions") (item #:fill? #f "Does need hierarchy")))) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (when kill-safe-section? (outline 'kill-safe)) (when kill-safe-section? (kill-safe-slides)) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (when gnosys? (re-slide gnosys-slide) (slide #:title "Wireless Router" (hc-append (bitmap "netgear.png") (bt " + ") (t "DD-WRT") (bt " + ") (t "Racket")) (vl-append gap-size (item #:fill? #f "Racket-based web server for configuration") (item #:fill? #f "Racket-based DNS server")))) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (unless no-conclusion? (slide #:title "Conclusion" ((if long-conclusion? (lambda (p) (scale p 0.6)) values) summary-figure) (if long-conclusion? (vc-append gap-size (item "Programmers need OS-like constructs in languages") (vc-append (* 4 (current-line-sep)) (subitem "concurrency") (subitem "adjust run-time environment") (subitem "easy termination")) (blank) (item "Multiple language constructs for \u201Cprocess\u201D") (subitem "programmer can mix and match to" "balance isolation and cooperation")) (vc-append (* 2 (current-line-sep)) (para "But don\u2019t partition data:") (subitem "closures") (subitem "objects") (subitem "continuations") (subitem "..."))))) ) (module+ main (mred-slides))
true
caf78f646e9a59e6dab38ce850446690c97445b8
c157305e3b08b76c2f4b0ac4f9c04b435097d0dc
/eopl2e/code/interps/4-4.scm
3e7ee9955811366d3342e414d3c1e443a6e79bad
[]
no_license
rstewart2702/scheme_programs
a5e91bd0e1587eac3859058da18dd9271a497721
767d019d84896569f2fc02de95925b05a38cac4d
refs/heads/master
2021-05-02T02:01:01.964797
2014-03-31T19:02:36
2014-03-31T19:02:36
13,077,035
0
1
null
null
null
null
UTF-8
Scheme
false
false
23,353
scm
4-4.scm
(let ((time-stamp "Time-stamp: <2001-01-03 13:46:27 dfried>")) (eopl:printf "4-4.scm: language with type inference ~a~%" (substring time-stamp 13 29))) ;;;;;;;;;;;;;;;; top level interface ;;;;;;;;;;;;;;;; (define type-check (lambda (string) (type-to-external-form (type-of-program (scan&parse string))))) (define run (lambda (string) (eval-program (scan&parse string)))) (define all-groups '(lang4-2 lang4-3 lang4-4)) (define run-all (lambda () (run-experiment run use-execution-outcome all-groups all-tests))) (define run-one (lambda (test-name) (run-test run test-name))) (define check-all (lambda () (run-experiment type-check use-checker-outcome all-groups all-tests))) (define check-one (lambda (test-name) (run-test type-check test-name))) (define equal-external-reps? equal-up-to-gensyms?) ;;;;;;;;;;;;;;;; grammatical specification ;;;;;;;;;;;;;;;; (define the-lexical-spec '((whitespace (whitespace) skip) (comment ("%" (arbno (not #\newline))) skip) (identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol) (number (digit (arbno digit)) number))) (define the-grammar '((program (expression) a-program) (expression (number) lit-exp) (expression ("true") true-exp) (expression ("false") false-exp) (expression (identifier) var-exp) (expression (primitive "(" (separated-list expression ",") ")") primapp-exp) (expression ("if" expression "then" expression "else" expression) if-exp) (expression ("let" (arbno identifier "=" expression) "in" expression) let-exp) (expression ("proc" "(" (separated-list optional-type-exp identifier ",") ")" expression) proc-exp) (expression ("(" expression (arbno expression) ")") app-exp) (expression ("letrec" (arbno optional-type-exp identifier "(" (separated-list optional-type-exp identifier ",") ")" "=" expression) "in" expression) letrec-exp) (expression ("lettype" identifier "=" type-exp (arbno type-exp identifier "(" (separated-list type-exp identifier ",") ")" "=" expression) "in" expression) lettype-exp) (primitive ("+") add-prim) (primitive ("-") subtract-prim) (primitive ("*") mult-prim) (primitive ("add1") incr-prim) (primitive ("sub1") decr-prim) (primitive ("zero?") zero-test-prim) (type-exp ("int") int-type-exp) (type-exp ("bool") bool-type-exp) (type-exp ("(" (separated-list type-exp "*") "->" type-exp ")") proc-type-exp) (type-exp (identifier) tid-type-exp) (optional-type-exp ; new for 4-4 ("?") no-type-exp) (optional-type-exp (type-exp) a-type-exp) )) (sllgen:make-define-datatypes the-lexical-spec the-grammar) (define show-the-datatype (lambda () (sllgen:list-define-datatypes the-lexical-spec the-grammar))) (define scan&parse (sllgen:make-string-parser the-lexical-spec the-grammar)) (define just-scan (sllgen:make-string-scanner the-lexical-spec the-grammar)) ;;;;;;;;;;;;;;;; The Type Checker ;;;;;;;;;;;;;;;; (define type-of-program (lambda (pgm) (cases program pgm (a-program (exp) (type-of-expression exp (empty-tenv)))))) (define type-of-expression (lambda (exp tenv) (cases expression exp (lit-exp (number) int-type) (true-exp () bool-type) (false-exp () bool-type) (var-exp (id) (apply-tenv tenv id)) (if-exp (test-exp true-exp false-exp) (let ((test-type (type-of-expression test-exp tenv)) (false-type (type-of-expression false-exp tenv)) (true-type (type-of-expression true-exp tenv))) ;; these tests either succeed or raise an error (check-equal-type! test-type bool-type test-exp) (check-equal-type! true-type false-type exp) true-type)) (proc-exp (texps ids body) (type-of-proc-exp texps ids body tenv)) (primapp-exp (prim rands) (type-of-application (type-of-primitive prim) (types-of-expressions rands tenv) prim rands exp)) (app-exp (rator rands) (type-of-application (type-of-expression rator tenv) (types-of-expressions rands tenv) rator rands exp)) (let-exp (ids rands body) (type-of-let-exp ids rands body tenv)) (letrec-exp (result-texps proc-names texpss idss bodies letrec-body) (type-of-letrec-exp result-texps proc-names texpss idss bodies letrec-body tenv)) (lettype-exp (type-name texp result-texps proc-names texpss idss bodies lettype-body) (type-of-lettype-exp type-name texp result-texps proc-names texpss idss bodies lettype-body tenv)) ))) (define type-of-proc-exp (lambda (texps ids body tenv) (let ((arg-types (expand-optional-type-expressions texps tenv))) (let ((result-type (type-of-expression body (extend-tenv ids arg-types tenv)))) (proc-type arg-types result-type))))) (define type-of-application (lambda (rator-type actual-types rator rands exp) (let ((result-type (fresh-tvar))) (check-equal-type! rator-type (proc-type actual-types result-type) exp) result-type))) (define types-of-expressions (lambda (rands tenv) (map (lambda (exp) (type-of-expression exp tenv)) rands))) (define type-of-let-exp (lambda (ids rands body tenv) (let ((tenv-for-body (extend-tenv ids (types-of-expressions rands tenv) tenv))) (type-of-expression body tenv-for-body)))) (define type-of-letrec-exp (lambda (result-texps proc-names arg-optional-texpss idss bodies letrec-body tenv) (let ((arg-typess (map (lambda (optional-texps) (expand-optional-type-expressions optional-texps tenv)) arg-optional-texpss)) (result-types (expand-optional-type-expressions result-texps tenv))) (let ((the-proc-types (map proc-type arg-typess result-types))) (let ((tenv-for-body ;^ type env for all proc-bodies (extend-tenv proc-names the-proc-types tenv))) (for-each (lambda (ids arg-types body result-type) (check-equal-type! (type-of-expression body (extend-tenv ids arg-types tenv-for-body)) result-type body)) idss arg-typess bodies result-types) (type-of-expression letrec-body tenv-for-body)))))) (define extend-tenv-with-typedef-exp (lambda (typename texp tenv) (extend-tenv-with-typedef typename (expand-type-expression texp tenv) tenv))) (define extend-tenv-with-type-exps (lambda (ids texps tenv) (extend-tenv ids (expand-type-expressions texps tenv) tenv))) (define fresh-type (let ((serial-number 0)) (lambda (s) (set! serial-number (+ serial-number 1)) (atomic-type (string->symbol (string-append (symbol->string s) (number->string serial-number))))))) (define type-of-lettype-exp (lambda (type-name texp result-texps proc-names arg-texpss idss bodies lettype-body tenv) (let ((the-new-type (fresh-type type-name)) (rhs-texps (map proc-type-exp arg-texpss result-texps))) (let ((tenv-for-implementation ;; here type definition is known-- bind it to its definition (extend-tenv-with-typedef-exp type-name texp tenv)) (tenv-for-client ;; here the defined type is opaque-- bind it to a new atomic type (extend-tenv-with-typedef type-name the-new-type tenv))) (let ((tenv-for-proc ; type env for all proc-bodies (extend-tenv-with-type-exps proc-names rhs-texps tenv-for-implementation)) (tenv-for-body ; type env for body (extend-tenv-with-type-exps proc-names rhs-texps tenv-for-client))) (for-each (lambda (ids arg-texps body result-texp) (check-equal-type! (type-of-expression body (extend-tenv-with-type-exps ids arg-texps tenv-for-proc)) (expand-type-expression result-texp tenv-for-proc) body)) idss arg-texpss bodies result-texps) (type-of-expression lettype-body tenv-for-body)))))) ;;;;;;;;;;;;;;;; types ;;;;;;;;;;;;;;;; (define-datatype type type? (atomic-type (name symbol?)) (proc-type (arg-types (list-of type?)) (result-type type?)) (tvar-type ;\new3 (serial-number integer?) (container vector?))) ;;; selectors and extractors for types (define atomic-type? (lambda (ty) (cases type ty (atomic-type (name) #t) (else #f)))) (define proc-type? (lambda (ty) (cases type ty (proc-type (arg-types result-type) #t) (else #f)))) (define tvar-type? (lambda (ty) (cases type ty (tvar-type (sn cont) #t) (else #f)))) (define atomic-type->name (lambda (ty) (cases type ty (atomic-type (name) name) (else (eopl:error 'atomic-type->name "Not an atomic type: ~s" ty))))) (define proc-type->arg-types (lambda (ty) (cases type ty (proc-type (arg-types result-type) arg-types) (else (eopl:error 'proc-type->arg-types "Not a proc type: ~s" ty))))) (define proc-type->result-type (lambda (ty) (cases type ty (proc-type (arg-types result-type) result-type) (else (eopl:error 'proc-type->arg-types "Not a proc type: ~s" ty))))) (define tvar-type->serial-number (lambda (ty) (cases type ty (tvar-type (sn c) sn) (else (eopl:error 'tvar-type->serial-number "Not a tvar-type: ~s" ty))))) (define tvar-type->container (lambda (ty) (cases type ty (tvar-type (sn vec) vec) (else (eopl:error 'tvar-type->container "Not a tvar-type: ~s" ty))))) ;;; type variables ;; in a tvar-type, the container is a vector of length 1. It can ;; contain either: ;; 1. nil, meaning that nothing is known about this tvar ;; 2. a (pointer to) a type ;; also: type structures may never be cyclic. (define fresh-tvar (let ((serial-number 0)) (lambda () (set! serial-number (+ 1 serial-number)) (tvar-type serial-number (vector '()))))) (define tvar->contents (lambda (ty) (vector-ref (tvar-type->container ty) 0))) (define tvar-set-contents! (lambda (ty val) (vector-set! (tvar-type->container ty) 0 val))) (define tvar-non-empty? (lambda (ty) (not (null? (vector-ref (tvar-type->container ty) 0))))) (define expand-optional-type-expressions (lambda (otexps tenv) (map (lambda (otexp) (expand-optional-type-expression otexp tenv)) otexps))) (define expand-optional-type-expression (lambda (otexp tenv) (cases optional-type-exp otexp (no-type-exp () (fresh-tvar)) (a-type-exp (texp) (expand-type-expression texp tenv))))) (define expand-type-expressions (lambda (texps tenv) (map (lambda (texp) (expand-type-expression texp tenv)) texps))) (define expand-type-expression (lambda (texp tenv) (letrec ((loop (lambda (texp) (cases type-exp texp (tid-type-exp (id) (apply-tenv-typedef tenv id)) (int-type-exp () (atomic-type 'int)) (bool-type-exp () (atomic-type 'bool)) (proc-type-exp (arg-texps result-texp) (proc-type (map loop arg-texps) (loop result-texp))))))) (loop texp)))) ;;;;;;;;;;;;;;;; the unifier ;;;;;;;;;;;;;;;; ;;; cases is very cumbersome in this application, so don't use it! (define check-equal-type! (lambda (t1 t2 exp) (cond ((eqv? t1 t2)) ;^ succeed with void result ((tvar-type? t1) (check-tvar-equal-type! t1 t2 exp)) ((tvar-type? t2) (check-tvar-equal-type! t2 t1 exp)) ((and (atomic-type? t1) (atomic-type? t2)) (if (not (eqv? (atomic-type->name t1) (atomic-type->name t2))) (raise-type-error t1 t2 exp))) ((and (proc-type? t1) (proc-type? t2)) (let ((arg-types1 (proc-type->arg-types t1)) (arg-types2 (proc-type->arg-types t2)) (result-type1 (proc-type->result-type t1)) (result-type2 (proc-type->result-type t2))) (if (not (= (length arg-types1) (length arg-types2))) (raise-wrong-number-of-arguments t1 t2 exp) (begin (for-each (lambda (t1 t2) (check-equal-type! t1 t2 exp)) arg-types1 arg-types2) (check-equal-type! result-type1 result-type2 exp))))) (else (raise-type-error t1 t2 exp))))) (define check-tvar-equal-type! (lambda (tvar ty exp) (if (tvar-non-empty? tvar) (check-equal-type! (tvar->contents tvar) ty exp) (begin (check-no-occurrence! tvar ty exp) (tvar-set-contents! tvar ty))))) (define check-no-occurrence! (lambda (tvar ty exp) (letrec ((loop (lambda (ty1) (cases type ty1 (atomic-type (name) #t) ;^ <void> not permitted here (proc-type (arg-types result-type) (begin (for-each loop arg-types) (loop result-type))) (tvar-type (num vec) (if (tvar-non-empty? ty1) (loop (tvar->contents ty1)) (if (eqv? tvar ty1) (raise-occurrence-check tvar ty exp)))))))) (loop ty)))) (define raise-type-error (lambda (t1 t2 exp) (eopl:error 'check-equal-type! "Type mismatch: ~s doesn't match ~s in ~s~%" (type-to-external-form t1) (type-to-external-form t2) exp))) (define raise-wrong-number-of-arguments (lambda (t1 t2 exp) (eopl:error 'check-equal-type! "Different numbers of arguments ~s and ~s in ~s~%" (type-to-external-form t1) (type-to-external-form t2) exp))) (define raise-occurrence-check (lambda (tvnum t2 exp) (eopl:error 'check-equal-type! "Can't unify: ~s occurs in type ~s in expression ~s~%" tvnum (type-to-external-form t2) exp))) ;;; types of primitives (define int-type (atomic-type 'int)) (define bool-type (atomic-type 'bool)) (define binop-type (proc-type (list int-type int-type) int-type)) (define unop-type (proc-type (list int-type) int-type)) (define int->bool-type (proc-type (list int-type) bool-type)) (define type-of-primitive (lambda (prim) (cases primitive prim (add-prim () binop-type) (subtract-prim () binop-type) (mult-prim () binop-type) (incr-prim () unop-type) (decr-prim () unop-type) (zero-test-prim () int->bool-type)))) ;;;;;;;;;;;;;;;; type environments ;;;;;;;;;;;;;;;; (define-datatype type-environment type-environment? (empty-tenv-record) (extended-tenv-record (syms (list-of symbol?)) (vals (list-of type?)) (tenv type-environment?)) (typedef-record ;\new4 (name symbol?) (definition type?) (tenv type-environment?))) (define empty-tenv empty-tenv-record) (define extend-tenv extended-tenv-record) (define extend-tenv-with-typedef typedef-record) (define apply-tenv (lambda (tenv sym) (cases type-environment tenv (empty-tenv-record () (eopl:error 'apply-tenv "Variable ~s unbound in type environment" sym)) (extended-tenv-record (syms vals tenv) (let ((pos (list-find-position sym syms))) (if (number? pos) (list-ref vals pos) (apply-tenv tenv sym)))) (typedef-record (name type tenv) (apply-tenv tenv sym))))) (define apply-tenv-typedef (lambda (tenv0 sym) (let loop ((tenv tenv0)) (cases type-environment tenv (empty-tenv-record () (eopl:error 'apply-tenv "Type variable ~s unbound in type environment ~s" sym tenv0)) (extended-tenv-record (syms vals tenv) (loop tenv)) (typedef-record (name type tenv) (if (eqv? name sym) type (loop tenv))))))) ;;;;;;;;;;;;;;;; external form of types ;;;;;;;;;;;;;;;; (define type-to-external-form (lambda (ty) (cases type ty (atomic-type (name) name) (proc-type (arg-types result-type) (append (arg-types-to-external-form arg-types) '(->) (list (type-to-external-form result-type)))) (tvar-type (serial-number container) ;\new7 (if (tvar-non-empty? ty) (type-to-external-form (tvar->contents ty)) (string->symbol (string-append "tvar" (number->string serial-number)))))))) (define arg-types-to-external-form (lambda (types) (if (null? types) '() (if (null? (cdr types)) (list (type-to-external-form (car types))) (cons (type-to-external-form (car types)) (cons '* (arg-types-to-external-form (cdr types)))))))) ;;;;;;;;;;;;;;;; the interpreter ;;;;;;;;;;;;;;;; (define eval-program (lambda (pgm) (cases program pgm (a-program (exp) (eval-expression exp (empty-env)))))) (define eval-expression (lambda (exp env) (cases expression exp (lit-exp (datum) datum) (true-exp () 1) (false-exp () 0) (var-exp (id) (apply-env env id)) (primapp-exp (prim rands) (let ((args (eval-rands rands env))) (apply-primitive prim args))) (if-exp (test-exp true-exp false-exp) (if (true-value? (eval-expression test-exp env)) (eval-expression true-exp env) (eval-expression false-exp env))) (let-exp (ids rands body) (let ((args (eval-rands rands env))) (eval-expression body (extend-env ids args env)))) (proc-exp (texps ids body) (closure ids body env)) (app-exp (rator rands) (let ((proc (eval-expression rator env)) (args (eval-rands rands env))) (if (procval? proc) ; should always be true in ; typechecked code (apply-procval proc args) (eopl:error 'eval-expression "Attempt to apply non-procedure ~s" proc)))) (letrec-exp (result-texps proc-names texpss idss bodies letrec-body) (eval-expression letrec-body (extend-env-recursively proc-names idss bodies env))) (lettype-exp (type-name texp result-texps proc-names texpss idss bodies lettype-body) (eval-expression lettype-body (extend-env-recursively proc-names idss bodies env))) ))) (define eval-rands (lambda (exps env) (map (lambda (exp) (eval-expression exp env)) exps))) (define apply-primitive (lambda (prim args) (cases primitive prim (add-prim () (+ (car args) (cadr args))) (subtract-prim () (- (car args) (cadr args))) (mult-prim () (* (car args) (cadr args))) (incr-prim () (+ (car args) 1)) (decr-prim () (- (car args) 1)) (zero-test-prim () (if (zero? (car args)) 1 0)) ))) ;;;;;;;;;;;;;;;; booleans ;;;;;;;;;;;;;;;; (define true-value? (lambda (x) (not (zero? x)))) ;;;;;;;;;;;;;;;; procedures ;;;;;;;;;;;;;;;; (define-datatype procval procval? (closure (ids (list-of symbol?)) (body expression?) (env environment?))) (define apply-procval (lambda (proc args) (cases procval proc (closure (ids body env) (eval-expression body (extend-env ids args env)))))) ;;;;;;;;;;;;;;;; environments ;;;;;;;;;;;;;;;; (define-datatype environment environment? (empty-env-record) (extended-env-record (syms (list-of symbol?)) (vals vector?) (env environment?))) (define apply-env (lambda (env sym) (cases environment env (empty-env-record () (eopl:error 'apply-env "No binding for ~s" sym)) (extended-env-record (syms vals old-env) (let ((pos (rib-find-position sym syms))) (if (number? pos) (vector-ref vals pos) (apply-env old-env sym))))))) (define empty-env (lambda () (empty-env-record))) (define extend-env (lambda (syms vals env) (extended-env-record syms (list->vector vals) env))) (define extend-env-recursively (lambda (proc-names idss exps old-env) (let ((len (length proc-names))) (let ((vec (make-vector len))) (let ((env (extended-env-record proc-names vec old-env))) (for-each (lambda (pos ids exp) (vector-set! vec pos (closure ids exp env))) (iota len) idss exps) env))))) (define rib-find-position (lambda (sym los) (list-find-position sym los))) (define list-find-position (lambda (sym los) (list-index (lambda (sym1) (eqv? sym1 sym)) los))) (define list-index (lambda (pred ls) (cond ((null? ls) #f) ((pred (car ls)) 0) (else (let ((list-index-r (list-index pred (cdr ls)))) (if (number? list-index-r) (+ list-index-r 1) #f)))))) (define iota (lambda (end) (let loop ((next 0)) (if (>= next end) '() (cons next (loop (+ 1 next))))))) ; ;;;;;;;;;;;;;;;; hooks for test harness ;;;;;;;;;;;;;;;; ; (define equal-external-reps? ; (lambda (rep1 rep2) ; (cond ; ((eqv? rep1 rep2) #t) ; ((and (symbol? rep1) (symbol? rep2)) ; ;; should really check to see that the mapping is consistent ; (same-symbol-up-to-gensym? rep1 rep2)) ; ((and (pair? rep1) (pair? rep2)) ; (and ; (equal-external-reps? (car rep1) (car rep2)) ; (equal-external-reps? (cdr rep1) (cdr rep2)))) ; (else #f)))) ; (define same-symbol-up-to-gensym? ; (lambda (sym1 sym2) ; (let loop ((lst1 (symbol->list sym1)) ; (lst2 (symbol->list sym2))) ; (cond ; ((and (list-of-digits? lst1) (list-of-digits? lst2)) #t) ; ((eqv? (car lst1) (car lst2)) ; (loop (cdr lst1) (cdr lst2))) ; (else #f))))) ; (define symbol->list ; (lambda (x) (string->list (symbol->string x)))) ; (define list-of-digits? ; (lambda (lst) ; (cond ; ((null? lst) #t) ; ((char-numeric? (car lst)) ; (list-of-digits? (cdr lst))) ; (else #f))))
false
49e506db3c6cd7478f7a2d080719d961bda9a1f9
486d827459ba1114134654055e2ac11d3c5ab817
/libkawadroid/src/com/zeroxab/libkawadroid/misc.scm
6e013ee54f23d0b7d65b5369a8375ef79856a48e
[]
no_license
devehe/android-kawa
2a38e1e4a64f07a86072e4cf9815e00820c8c269
3e7b5dc46bdda436e64f70e71f37a0a7e74e7e5f
refs/heads/master
2020-12-28T17:31:55.745193
2013-09-10T21:21:41
2013-09-10T21:21:41
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
9,943
scm
misc.scm
(require 'android-defs) (require 'srfi-1) (import (except (srfi :13 strings) string-hash)) (require 'regex) (require 'syntax-utils) (require 'srfi-69) (provide 'libkawadroid) (define-alias Arrays java.util.Arrays) (define-alias Math java.lang.Math) (define-alias InterruptedException java.lang.InterruptedException) (define-alias Thread java.lang.Thread) (define-alias Timer java.util.Timer) (define-alias TimerTask java.util.TimerTask) (define-alias Runnable java.lang.Runnable) (define-alias BufferedReader java.io.BufferedReader) (define-alias StringBuilder java.lang.StringBuilder) (define-alias ScheduledThreadPoolExecutor java.util.concurrent.ScheduledThreadPoolExecutor) (define-alias Application android.app.Application) (define-alias Activity android.app.Activity) (define-alias Service android.app.Service) (define-alias Bitmap android.graphics.Bitmap) (define-alias Canvas android.graphics.Canvas) (define-alias Color android.graphics.Color) (define-alias Drawable android.graphics.drawable.Drawable) (define-alias Context android.content.Context) (define-alias Intent android.content.Intent) (define-alias Resources android.content.res.Resources) (define-alias SharedPreferences android.content.SharedPreferences) (define-alias ContentValues android.content.ContentValues) (define-alias Handler android.os.Handler) (define-alias Bundle android.os.Bundle) (define-alias IBinder android.os.IBinder) (define-alias PowerManager android.os.PowerManager) (define-alias WakeLock android.os.PowerManager$WakeLock) (define-alias Parcelable android.os.Parcelable) (define-alias KeyEvent android.view.KeyEvent) (define-alias OnClickListener android.view.View$OnClickListener) (define-alias SurfaceHolder android.view.SurfaceHolder) (define-alias Menu android.view.Menu) (define-alias MenuItem android.view.MenuItem) (define-alias MotionEvent android.view.MotionEvent) (define-alias OnGestureListener android.view.GestureDetector$OnGestureListener) (define-alias GestureDetector android.view.GestureDetector) (define-alias ListView android.widget.ListView) (define-alias SimpleCursorAdapter android.widget.SimpleCursorAdapter) (define-alias Toast android.widget.Toast) (define-alias ViewBinder android.widget.SimpleCursorAdapter$ViewBinder) (define-alias ArrayAdapter android.widget.ArrayAdapter) (define-alias SimpleAdapter android.widget.SimpleAdapter) (define-alias OnItemClickListener android.widget.AdapterView$OnItemClickListener) (define-alias ProgressBar android.widget.ProgressBar) (define-alias SeekBar android.widget.SeekBar) (define-alias OnSeekBarChangeListener android.widget.SeekBar$OnSeekBarChangeListener) (define-alias DateUtils android.text.format.DateUtils) (define-alias Editable android.text.Editable) (define-alias TextWatcher android.text.TextWatcher) (define-alias Spannable android.text.Spannable) (define-alias SpannableString android.text.SpannableString) (define-alias BackgroundColorSpan android.text.style.BackgroundColorSpan) (define-alias StyleSpan android.text.style.StyleSpan) (define-alias PreferenceActivity android.preference.PreferenceActivity) (define-alias PreferenceManager android.preference.PreferenceManager) (define-alias BaseColumns android.provider.BaseColumns) (define-alias HttpGet org.apache.http.client.methods.HttpGet) (define-alias BasicResponseHandler org.apache.http.impl.client.BasicResponseHandler) (define-alias DefaultHttpClient org.apache.http.impl.client.DefaultHttpClient) (define-alias HttpClient org.apache.http.client.HttpClient) (define-alias Uri android.net.Uri) (define-alias TypedValue android.util.TypedValue) (define-alias FVector gnu.lists.FVector) (define-namespace Log "class:android.util.Log") ;;; Manage tasks (define-syntax (async-task stx) ;; TODO should add in the ability to bind (this) at the callsite to ;; (this-parent) so that I don't need an ugly let (syntax-case stx () ((_ paramsT progressT resultT . r) (letrec ((process (lambda (form) (syntax-case form (background cancel post pre progress publish-progress) (((background name stmt ...) . rest) ;; FIXME using object here instead of object1 seems to ;; change the object macro at the toplevel in the ;; interpreter, this looks like a bug (cons #`((doInBackground (object1 ::Object[])) (@java.lang.Override) ::Object (as resultT (let ((name (gnu.lists.FVector[paramsT] object1))) stmt ...))) (process #`rest))) (((cancel name stmt ...) . rest) (cons #`((onCancelled (object1 ::Object)) (@java.lang.Override) ::void (let ((name (as resultT object1))) stmt ...)) (process #`rest))) (((post name stmt ...) . rest) (cons #`((onPostExecute (object1 ::Object)) (@java.lang.Override) ::void (let ((name (as resultT object1))) stmt ...)) (process #`rest))) (((pre stmt ...) . rest) (cons #`(onPreExecute (@java.lang.Override) ::void stmt ...) (process #`rest))) (((progress stmt ...) . rest) (cons #`((onProgressUpdate (object1 ::Object[])) (@java.lang.Override) ::void (let ((name (gnu.lists.FVector[progressT] object1))) stmt ...)) (process #`rest))) (((publish-progress stmt ...) . rest) (cons #`((publishProgress (object1 ::Object[])) (@java.lang.Override) ::void (let ((name (gnu.lists.FVector[progressT] object1))) stmt ...)) (process #`rest))) (() '()))))) #`(object (android.os.AsyncTask) #,@(process #`r)))))) (define-syntax (with-that stx) (syntax-case stx () ((_ stmts ...) (with-syntax ((that (datum->syntax stx 'that))) #'(let ((that (this))) stmts ...))))) (define-syntax (thread x) (syntax-case x () ((_ stmts ...) #`(with-that (as Thread (object (Thread) ((run) ::void stmts ...))))))) (define-syntax (runnable x) (syntax-case x () ((_ stmts ...) #`(with-that (as Runnable (object (Runnable) ((run) ::void stmts ...))))))) (define-syntax (timer-task x) (syntax-case x () ((_ stmts ...) #`(with-that (as TimerTask (object (TimerTask) ((run) ::void stmts ...))))))) ;;; Listeners (define-syntax (on-item-click stx) (syntax-case stx () ((_ obj stmts ...) (with-syntax ((adapter (datum->syntax stx 'adapter)) (view (datum->syntax stx 'view)) (position (datum->syntax stx 'position)) (id (datum->syntax stx 'id))) #`(obj:setOnItemClickListener (with-that (as OnItemClickListener (object (OnItemClickListener) ((onItemClick adapter view position id) ::void stmts ...))))))))) (define-syntax (on-user-seek-bar-change stx) (syntax-case stx () ((_ obj stmts ...) (with-syntax ((bar (datum->syntax stx 'bar)) (position (datum->syntax stx 'position)) (from-user (datum->syntax stx 'from-user))) #`(obj:setOnSeekBarChangeListener (with-that (as OnSeekBarChangeListener (object (OnSeekBarChangeListener) ((onProgressChanged seek-bar position from-user) ::void (when from-user stmts ...)) ((onStartTrackingTouch seek-bar) ::void #f) ((onStopTrackingTouch seek-bar) ::void #f))))))))) ;;; Start activities (define-syntax (simple-start-activity stx) (syntax-case stx () ((_ obj activity arguments) #`(let ((intent ::android.content.Intent (make <android.content.Intent> obj activity))) ;; this may cause runtime errors if you're trying to put an ;; object that isn't supported by putExtra (with-compile-options warn-invoke-unknown-method: #f (for-each (lambda (a) (intent:putExtra (car a) (cdr a))) arguments)) (obj:startActivity intent))))) ;;; Basic file chooser using an external file manager ;; FIXME This doesn't work for some reason, so we need to initialize it manually ;; FIXME (string-hash "*file-chooser-request*") ends up not delivering requests (define *file-chooser-request* 33) (define (file-chooser (obj ::Activity)) ;; TODO, why doesn't Intent work? (let ((intent <android.content.Intent> (make <android.content.Intent> (as String android.content.Intent:ACTION_GET_CONTENT)))) (intent:setType "*/*") (intent:addCategory android.content.Intent:CATEGORY_OPENABLE) (try-catch (obj:startActivityForResult (intent:createChooser intent "Select a book to read") *file-chooser-request*) (ex <android.content.ActivityNotFoundException> ((Toast:makeText obj "No file manager, install one from the play store" Toast:LENGTH_SHORT):show))))) (define (file-chooser-result f) (lambda ((obj ::Activity) (request ::int) (result ::int) (data ::Intent)) (if (and (= request *file-chooser-request*) (= result obj:RESULT_OK)) (begin (let ((uri ::Uri (data:getData))) (Log:i "speedread" (format #f "got back URI ~a ~a" (uri:toString) (uri:getPath))) (f uri)) #t) #f))) ;;; Manage activity results (define (multiple-activity-results (obj ::Activity) . fs) (lambda ((request ::int) (result ::int) (data ::Intent)) (Log:d "multiple-activity-results" (format #f "~a ~a ~a" request result data)) (let loop ((fs fs)) (if (null? fs) #f (let ((r ((car fs) obj request result data))) (if r #t (loop (cdr fs))))))))
true
7257938119d61feeb9ea53b786903ee4d1362544
958488bc7f3c2044206e0358e56d7690b6ae696c
/scheme/guile/char-sets.scm
4e5a97456170cbd7a6f956c5dd46397d154f5f80
[]
no_license
possientis/Prog
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
d4b3debc37610a88e0dac3ac5914903604fd1d1f
refs/heads/master
2023-08-17T09:15:17.723600
2023-08-11T12:32:59
2023-08-11T12:32:59
40,361,602
3
0
null
2023-03-27T05:53:58
2015-08-07T13:24:19
Coq
UTF-8
Scheme
false
false
912
scm
char-sets.scm
(define set (char-set #\a #\b #\c #\d #\e)) (define other (char-set #\a)) (display (char-set? set))(newline) ; #t (display (char-set= set set))(newline) ; #t (display (char-set= set other))(newline) ; #f (display (char-set<= set other))(newline) ; #f (display (char-set<= other set))(newline) ; #t (display (char-set-hash set))(newline) ; 420 (display (char-set-hash other))(newline) ; 97 (define iter (char-set-cursor set)) (define (char-set-for-each proc cs) (display "for-each is running ...\n") (if (not (char-set? cs)) (error "char-set-for-each: set argument should be a character set")) (let loop ((cursor (char-set-cursor cs))) (if (end-of-char-set? cursor) 'done (begin (proc (char-set-ref cs cursor)) (loop (char-set-cursor-next cs cursor)))))) (define new char-set:symbol) (display (string-append "abc" "def" "hij"))(newline) (exit 0)
false
f23776bd358ce893ccae4a725fe135a36b436fd0
575efd9d408a79f5681454b3a07c7bc3f294b05f
/src/memoize.scm
f24841211acfe6f6bb4f64b1cafa2b1e526c2ae4
[]
no_license
DeathKing/miniMaxima
2d12c47ff64430b96211308598c2c00378eccd8e
7ed73abc2e55c4a8556bbeed6cb9f275d3b5c3d5
refs/heads/master
2020-04-14T12:54:43.754996
2016-11-10T01:33:49
2016-11-10T01:33:49
32,081,631
3
0
null
null
null
null
UTF-8
Scheme
false
false
2,423
scm
memoize.scm
;;; MEMOIZE -- General memorization through table looking (load-option 'format) (define (memoize func) (let ((table (make-equal-hash-table)) (id (lambda (x) x))) (lambda args (hash-table/lookup table args id (lambda () (let ((res (apply func args))) (hash-table/put! table args res) res)))))) (define (memoize-cps fn) (let ((table (list))) (let* ((entry-continuations car) (entry-results cdr) (push-continuation! (lambda (entry cont) (set-car! entry (cons cont (entry-continuations entry))))) (push-result! (lambda (entry result) (set-cdr! entry (cons result (entry-results entry))))) (result-subsumed? (lambda (entry result) (member result (entry-results entry)))) (make-entry (lambda () (cons (list) (list)))) (table-ref (lambda (str) (pmatch (assoc str table) (`(,str . ,entry) entry) (`,__ (let ((entry (make-entry))) (set! table (cons (cons str entry) table)) entry)))))) (lambda (str cont) (let ((entry (table-ref str))) (pmatch entry (`(() . ()) (push-continuation! entry cont) (fn str (lambda (result) (format #t "result is ~A.\n" result) (format #t "Results is ~A.\n" (entry-results entry)) (if (result-subsumed? entry result) (for-each (lambda (cont) (cont result)) (entry-continuations entry)) (begin (format #t "result pushed!~%")(push-result! entry result)))))) (`,__ (push-continuation! entry cont) (for-each (lambda (result) (cont result)) (entry-results entry))))))))) (define-syntax %:memoize! (syntax-rules () ((_ func) (set! func (memoize func)))))
true
e9d6bfa2001cc3ac508406b9891e056ffc020c8b
03de0e9f261e97d98f70145045116d7d1a664345
/parscheme.sls
645fec5dcef02fa0d79dc7452ec2976800bbe4ba
[]
no_license
arcfide/riastradh
4929cf4428307b926e4c16e85bc39e5897c14447
9714b5c8b642f2d6fdd94d655ec5d92aa9b59750
refs/heads/master
2020-05-26T06:38:54.107723
2010-10-18T16:52:23
2010-10-18T16:52:23
3,235,881
2
1
null
null
null
null
UTF-8
Scheme
false
false
4,428
sls
parscheme.sls
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; R6RS Full Parser Combinators Wrapper ;;; ;;; Copyright (c) 2009 Aaron W. Hsu <[email protected]> ;;; ;;; Permission to use, copy, modify, and distribute this software for ;;; any purpose with or without fee is hereby granted, provided that the ;;; above copyright notice and this permission notice appear in all ;;; copies. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL ;;; WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE ;;; AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL ;;; DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA ;;; OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER ;;; TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR ;;; PERFORMANCE OF THIS SOFTWARE. (library (riastradh parscheme) (export parse-stream define-parser *parser parser:at-least parser:at-least-until parser:at-most parser:at-most-until parser:backtrackable parser:between parser:between-until parser:bracketed parser:bracketed* parser:bracketed-noise parser:bracketed-list parser:call-with-context parser:choice parser:complete parser:context parser:deep-choice parser:delayed parser:end parser:epsilon parser:error parser:eqv-token parser:exactly parser:extend parser:label parser:list:at-least parser:list:at-least-until parser:list:at-most parser:list:at-most-until parser:list:between parser:list:between-until parser:list:exactly parser:list:repeated parser:list:repeated-until parser:map parser:match parser:match->list parser:match->ignore parser:modify-context parser:noise:at-least parser:noise:at-least-until parser:noise:at-most parser:noise:at-most-until parser:noise:between parser:noise:between-until parser:noise:exactly parser:noise:repeated parser:noise:repeated-until parser:on-failure parser:optional parser:optional-noise parser:peek parser:refuse parser:repeated parser:repeated-until parser:return parser:sequence parser:set-context parser:token parser:token* parser:token-if match define-matcher matcher:at-least matcher:at-least-until matcher:at-most matcher:at-most-until matcher:between matcher:between-until matcher:bracketed matcher:bracketed* matcher:choice matcher:comparison matcher:deep-choice matcher:end matcher:epsilon matcher:error matcher:exactly matcher:if matcher:left-comparison matcher:optional matcher:peek matcher:repeated matcher:repeated-until matcher:right-comparison matcher:sequence matcher:token matcher:token-if comparator-matcher left-comparator-matcher right-comparator-matcher guarded-matcher parse-error? parse-error/position parse-error/messages merge-parse-errors parse-error-with-position make-parse-error make-parse-error:trailing-garbage make-parse-error:unknown make-parse-error:unexpected-end-of-input make-parse-error:unexpected-token match-string match-string? matcher:char matcher:char= matcher:char/= matcher:char-ci= matcher:char-ci/= matcher:char-in-set matcher:char-not-in-set parse-file parse-input-chars parse-string parser:bracketed-string parser:char parser:char= parser:char/= parser:char-ci= parser:char-ci/= parser:char-in-set parser:char-not-in-set parser:list->string parser:match->string parser:reverse-list->string parser:string= parser:string-ci= parser:string:at-least parser:string:at-least-until parser:string:at-most parser:string:at-most-until parser:string:between parser:string:between-until parser:string:exactly parser:string:repeated parser:string:repeated-until enable-match-trace disable-match-trace enable-parse-trace disable-parse-trace) (import (riastradh parscheme perror) (riastradh parscheme matcomb) (riastradh parscheme mattext) (riastradh parscheme parcomb) (riastradh parscheme partext)))
false
6cedaebcf20b91c7e79c1389594f619bd76ce956
4f97d3c6dfa30d6a4212165a320c301597a48d6d
/interpreter_experiments/in-progress-kanren-style-type-infer.scm
317a0b48e35e42f1f620bb234b296812848dccc1
[ "MIT", "LicenseRef-scancode-free-unknown" ]
permissive
michaelballantyne/Barliman
8c0b1ccbe5141347a304fe57dc9f85085aae9228
7a58671a85b82c05b364b60aa3a372313d71f8ca
refs/heads/master
2022-09-24T05:59:45.760663
2019-11-25T10:32:26
2019-11-25T10:32:26
268,399,942
0
0
MIT
2020-06-01T01:48:21
2020-06-01T01:48:20
null
UTF-8
Scheme
false
false
12,135
scm
in-progress-kanren-style-type-infer.scm
;;; WEB -- 18 June 2016 ;; Type inferencer in miniKanren, adapted from Oleg's Kanren polymorphic type inferencer ;; ;; http://kanren.cvs.sourceforge.net/viewvc/kanren/kanren/examples/type-inference.scm?view=markup ;; ;; Unlike the Kanren inferencer, this definition of !- is a pure ;; relation, with no cuts and no uses of project. This inferencer ;; also does not require a parser/unparser, and allows shadowing. ;;; TODO FIXME -- use initial environment to hold primitive functions, ;;; just like in evaluator and parser ;;; TODO -- add 'letrec', 'begin', multi-argument application, ;;; variadic and multi-argument lambda, lists, quote, match, and the ;;; primitives from the evaluator (define membero (lambda (x ls) (fresh (y rest) (== `(,y . ,rest) ls) (conde ((== y x)) ((=/= y x) (membero x rest)))))) (define type-lookupo (lambda (g x t) (fresh (tq) (membero `(,x . ,tq) g) (conde ((== `(non-generic ,t) tq)) ((fresh (g^ rand^) (== `(generic ,g^ ,rand^) tq) (!-auxo g^ rand^ t))))))) (define int 'int) (define bool 'bool) (define !- (lambda (expr t) (!-auxo initial-type-env expr t))) (define !-aux (lambda (g expr t) (conde ((symbolo expr) (type-lookupo g expr t)) ((numbero expr) (== int t)) ;;; from Oleg's inferencer -- ;;; not needed for miniScheme ((fresh (e) (== `(zero? ,e) expr) (== bool t) (not-in-envo 'zero? g) (!-auxo g e int))) ((fresh (e) (== `(sub1 ,e) expr) (== int t) (not-in-envo 'sub1 g) (!-auxo g e int))) ((fresh (e1 e2) (== `(+ ,e1 ,e2) expr) (== int t) (not-in-envo '+ g) (!-auxo g e1 int) (!-auxo g e2 int))) #| ;; TODO implement! ;; ;; I think I need to add lists to be able to handle variadic. ((fresh (x body) (== `(lambda ,x ,body) expr) (conde ;; Variadic ((symbolo x)) ;; Multi-argument ((list-of-symbolso x))) (not-in-envo 'lambda env))) |# ((fresh (x body t-x t-body) (== `(lambda (,x) ,body) expr) (symbolo x) (== `(-> ,t-x ,t-body) t) (not-in-envo 'lambda g) (!-auxo `((,x non-generic ,t-x) . ,g) body t-body))) ;; TODO -- multi-arg application and prim app ((fresh (rator rand t-rand) (== `(,rator ,rand) expr) (!-auxo g rator `(-> ,t-rand ,t)) (!-auxo g rand t-rand))) ;; TODO -- replace with 'letrec' ((fresh (rand) (== `(fix ,rand) expr) (not-in-envo 'fix g) (!-auxo g rand `(-> ,t ,t)))) ((fresh (x rand body) ;; polylet (== `(let ((,x ,rand)) ,body) expr) (not-in-envo 'let g) (fresh (some-type) (!-auxo g rand some-type)) (!-auxo `((,x generic ,g ,rand) . ,g) body t))) ((!-primo g expr t))))) ;; TODO -- update this to be prim-!o or whatever (define (eval-primo prim-id a* val) (conde [(== prim-id 'cons) (fresh (a d) (== `(,a ,d) a*) (== `(,a . ,d) val))] [(== prim-id 'car) (fresh (d) (== `((,val . ,d)) a*) (=/= 'closure val))] [(== prim-id 'cdr) (fresh (a) (== `((,a . ,val)) a*) (=/= 'closure a))] [(== prim-id 'not) (fresh (b) (== `(,b) a*) (conde ((=/= #f b) (== #f val)) ((== #f b) (== #t val))))] [(== prim-id 'equal?) (fresh (v1 v2) (== `(,v1 ,v2) a*) (conde ((== v1 v2) (== #t val)) ((=/= v1 v2) (== #f val))))] [(== prim-id 'symbol?) (fresh (v) (== `(,v) a*) (conde ((symbolo v) (== #t val)) ((numbero v) (== #f val)) ((fresh (a d) (== `(,a . ,d) v) (== #f val)))))] [(== prim-id 'null?) (fresh (v) (== `(,v) a*) (conde ((== '() v) (== #t val)) ((=/= '() v) (== #f val))))])) (define (!-primo g expr t) (conde ((!-booleano g expr t)) ((!-ando g expr t)) ((!-oro g expr t)) ((!-ifo g expr t)))) (define (!-booleano g expr t) (fresh () (== bool t) (conde ((== #t expr)) ((== #f expr))))) (define (!-ando g expr t) (fresh (e*) (== `(and . ,e*) expr) (== bool t) (not-in-envo 'and env) (!-and-auxo g e*))) (define (!-and-auxo g e*) (conde ((== '() e*)) ((fresh (e e-rest) (== `(,e . ,e-rest) e*) (!-auxo g e bool) (!-and-auxo g e-rest))))) (define (!-oro g expr t) (fresh (e*) (== `(or . ,e*) expr) (== bool t) (not-in-envo 'or env) (!-or-auxo g e*))) (define (!-or-auxo g e*) (conde ((== '() e*)) ((fresh (e e-rest) (== `(,e . ,e-rest) e*) (!-auxo g e bool) (!-or-auxo g e-rest))))) (define (!-ifo g expr t) (fresh (e1 e2 e3) (== `(if ,e1 ,e2 ,e3) expr) (not-in-envo 'if env) (!-auxo g e1 bool) (!-auxo g e2 t) (!-auxo g e3 t))) ;; TODO -- update to include types (define initial-type-env `((list . (val . (closure (lambda x x) ,empty-env))) (not . (val . (prim . not))) (equal? . (val . (prim . equal?))) (symbol? . (val . (prim . symbol?))) (cons . (val . (prim . cons))) (null? . (val . (prim . null?))) (car . (val . (prim . car))) (cdr . (val . (prim . cdr))) . ,empty-env)) ;;; reused definitions from interpreter: (define empty-env '()) (define (not-in-envo x env) (conde ((== empty-env env)) ((fresh (y b rest) (== `((,y . ,b) . ,rest) env) (=/= y x) (not-in-envo x rest))))) ;;; tests (test 'test-!-aux1 (and (equal? (run* (q) (!-auxo '() '17 int)) '(_.0)) (equal? (run* (q) (!-auxo '() '17 q)) '(int))) #t) (test 'arithmetic-primitives (run* (q) (!-auxo '() '(zero? 24) q)) '(bool)) (test 'test-!-auxsub1 (run* (q) (!-auxo '() '(zero? (sub1 24)) q)) '(bool)) (test 'test-!-aux+ (run* (q) (!-auxo '() '(zero? (sub1 (+ 18 (+ 24 50)))) q)) '(bool)) (test 'test-!-aux2 (and (equal? (run* (q) (!-auxo '() '(zero? 24) q)) '(bool)) (equal? (run* (q) (!-auxo '() '(zero? (+ 24 50)) q)) '(bool)) (equal? (run* (q) (!-auxo '() '(zero? (sub1 (+ 18 (+ 24 50)))) q)) '(bool))) #t) (test 'test-!-aux3 (run* (q) (!-auxo '() '(if (zero? 24) 3 4) q)) '(int)) (test 'if-expressions (run* (q) (!-auxo '() '(if (zero? 24) (zero? 3) (zero? 4)) q)) '(bool)) (test 'variables (and (equal? (run* (q) (type-lookupo '((b non-generic int) (a non-generic bool)) 'a q)) '(bool)) (equal? (run* (q) (!-auxo '((a non-generic int)) '(zero? a) q)) '(bool)) (equal? (run* (q) (!-auxo '((b non-generic bool) (a non-generic int)) '(zero? a) q)) '(bool))) #t) (test 'variables-4a (run* (q) (!-auxo '((b non-generic bool) (a non-generic int)) '(lambda (x) (+ x 5)) q)) '((-> int int))) (test 'variables-4b (run* (q) (!-auxo '((b non-generic bool) (a non-generic int)) '(lambda (x) (+ x a)) q)) '((-> int int))) (test 'variables-4c (run* (q) (!-auxo '() '(lambda (a) (lambda (x) (+ x a))) q)) '((-> int (-> int int)))) (test 'everything-but-polymorphic-let (run* (q) (!-auxo '() '(lambda (f) (lambda (x) ((f x) x))) q)) '((-> (-> _.0 (-> _.0 _.1)) (-> _.0 _.1)))) (test 'everything-but-polymorphic-let (run* (q) (!-auxo '() '((fix (lambda (sum) (lambda (n) (if (zero? n) 0 (+ n (sum (sub1 n))))))) 10) q)) '(int)) (test 'everything-but-polymorphic-let (run* (q) (!-auxo '() '((fix (lambda (sum) (lambda (n) (+ n (sum (sub1 n)))))) 10) q)) '(int)) (test 'everything-but-polymorphic-let (run* (q) (!-auxo '() '((lambda (f) (if (f (zero? 5)) (+ (f 4) 8) (+ (f 3) 7))) (lambda (x) x)) q)) '()) (test 'polymorphic-let (run* (q) (!-auxo '() '(let ((f (lambda (x) x))) (if (f (zero? 5)) (+ (f 4) 8) (+ (f 3) 7))) q)) '(int)) (test 'with-robust-syntax (run* (q) (!-auxo '() '((fix (lambda (sum) (lambda (n) (if (if (zero? n) #t #f) 0 (+ n (sum (sub1 n))))))) 10) q)) '(int)) (test 'with-robust-syntax-but-long-jumps/poly-let (run* (q) (!-auxo '() '(let ((f (lambda (x) x))) (if (f (zero? 5)) (+ (f 4) 8) (+ (f 3) 7))) q)) '(int)) (test 'type-habitation-1 (run 1 (g e) (!-auxo g e '(-> int int))) '(((((_.0 non-generic (-> int int)) . _.1) _.0) (sym _.0)))) (test 'type-habitation-2 (run 1 (g h r q z y t) (!-auxo g `(,h ,r (,q ,z ,y)) t)) '(((() + _.0 + _.1 _.2 int) (num _.0 _.1 _.2))) ) (test 'type-habitation-2b (run 1 (g h r q z y t) (symbolo r) (!-auxo g `(,h ,r (,q ,z ,y)) t)) '(((((_.0 non-generic int)) + _.0 + _.1 _.2 int) (=/= ((_.0 +))) (num _.1 _.2) (sym _.0))) ) (test 'type-habitation-3 (and (equal? (run 1 (la f b) (!-auxo '() `(,la (,f) ,b) '(-> int int))) '(((lambda _.0 _.1) (num _.1) (sym _.0)))) (equal? (run 1 (expr type) (fresh (h r q z y t u v) (== `(,h ,r (,q ,z ,y)) expr) (== `(,t ,u ,v) type) (!-auxo '() expr type))) '((((lambda (_.0) (+ _.1 _.2)) (-> _.3 int)) (=/= ((_.0 +))) (num _.1 _.2) (sym _.0))))) #t) ;;; Will's tests ;;; adapted from: ;;; ;;; Polymorphic Types ;;; and Type Inference Programming Languages CS442 ;;; David Toman ;;; School of Computer Science University of Waterloo ;;; ;;; https://cs.uwaterloo.ca/~david/cs442/lect-TYPEINFERENCE.pdf (test 'w-let-poly-1 (run* (q) (!-auxo '() '(let ((d (lambda (f) (lambda (x) (f (f x)))))) (let ((a1 ((d (lambda (x) (sub1 x))) 2))) (let ((a2 ((d (lambda (x) (if x #t #f))) #t))) d))) q)) '((-> (-> _.0 _.0) (-> _.0 _.0)))) (test 'w-let-poly-2 (run* (q) (!-auxo '() '(let ((d (lambda (f) (lambda (x) (f (f x)))))) (let ((a1 ((d (lambda (x) (sub1 x))) 2))) (let ((a2 (d (lambda (x) (if x #t #f))))) a1))) q)) '(int)) (test 'w-let-poly-3 (run* (q) (!-auxo '() '(let ((d (lambda (f) (lambda (x) (f (f x)))))) (let ((a1 ((d (lambda (x) (sub1 x))) 2))) (let ((a2 (d (lambda (x) (if x #t #f))))) a2))) q)) '((-> bool bool))) (test 'w-let-poly-4 (run* (q) (!-auxo '() '(let ((d (lambda (f) (lambda (x) (f (f x)))))) (let ((a1 ((d (lambda (x) (sub1 x))) 2))) (let ((a2 ((d (lambda (x) (if x #t #f))) #t))) a2))) q)) '(bool)) #| ;; need to add lists (test 'w-length-1 (run* (q) (!-auxo '() '((fix (lambda (length) (lambda (l) (if (if (null? l) #t #f) 0 (+ 1 (length (cdr l))))))) (cons 1 (cons 2 (cons 3)))) q)) '(int)) |# (test 'polymorphic-let-monomorphic (run* (q) (!-auxo '() '((lambda (g) (let ((f (lambda (x) (g x)))) (if (f (zero? 5)) (+ (f 4) 8) (+ (f 3) 7)))) (lambda (y) y)) q)) '(???))
false
7c7a1b55e4b1ea4c2ffb2510062827600c63e691
b9eb119317d72a6742dce6db5be8c1f78c7275ad
/racket/web/flickr/lazy/get-one-batch.ss
4c46b2a768cd99c4b3cd873a3afa091c85112ec1
[]
no_license
offby1/doodles
be811b1004b262f69365d645a9ae837d87d7f707
316c4a0dedb8e4fde2da351a8de98a5725367901
refs/heads/master
2023-02-21T05:07:52.295903
2022-05-15T18:08:58
2022-05-15T18:08:58
512,608
2
1
null
2023-02-14T22:19:40
2010-02-11T04:24:52
Scheme
UTF-8
Scheme
false
false
1,412
ss
get-one-batch.ss
#! /bin/sh #| Hey Emacs, this is -*-scheme-*- code! #$Id$ exec mzscheme --no-init-file --mute-banner --version --require "$0" |# (module get-one-batch mzscheme (require (lib "trace.ss") (only (planet "sxml.ss" ("lizorkin" "sxml.plt")) sxpath) "../flickr.ss") (define *my-NSID* (if #t "20825469@N00" (car ((sxpath '(user @ nsid *text*)) (flickr.people.findByUsername 'username "offby1"))))) ;; returns a simple list of photos, not an actual page. (define (get-one-batch page per_page auth_token) (fprintf (current-error-port) "Getting at most ~a photos from page ~a~%" per_page page) (let ((from-one-call ((sxpath '(photos (photo))) (apply flickr.photos.search (append (if auth_token (list 'auth_token auth_token) '()) (list 'user_id *my-NSID* 'page page 'per_page per_page 'sort "date-taken-desc")))))) (fprintf (current-error-port) "got ~a~%" (length from-one-call)) from-one-call)) ;;(trace get-one-batch) (provide get-one-batch) )
false
f94d8ecf47da2f7e9fa6f22225fd74f7373e7f0d
4bd59493b25febc53ac9e62c259383fba410ec0e
/Scripts/Task/set/scheme/set.ss
6735f13c9ce962f7bfb858cb7cad4586f7d0c380
[]
no_license
stefanos1316/Rosetta-Code-Research
160a64ea4be0b5dcce79b961793acb60c3e9696b
de36e40041021ba47eabd84ecd1796cf01607514
refs/heads/master
2021-03-24T10:18:49.444120
2017-08-28T11:21:42
2017-08-28T11:21:42
88,520,573
5
1
null
null
null
null
UTF-8
Scheme
false
false
890
ss
set.ss
(define (element? a lst) (and (not (null? lst)) (or (eq? a (car lst)) (element? a (cdr lst))))) ; util, not strictly needed (define (uniq lst) (if (null? lst) lst (let ((a (car lst)) (b (cdr lst))) (if (element? a b) (uniq b) (cons a (uniq b)))))) (define (intersection a b) (cond ((null? a) '()) ((null? b) '()) (else (append (intersection (cdr a) b) (if (element? (car a) b) (list (car a)) '()))))) (define (union a b) (if (null? a) b (union (cdr a) (if (element? (car a) b) b (cons (car a) b))))) (define (diff a b) ; a - b (if (null? a) '() (if (element? (car a) b) (diff (cdr a) b) (cons (car a) (diff (cdr a) b))))) (define (subset? a b) ; A ⊆ B (if (null? a) #t (and (element? (car a) b) (subset? (cdr a) b)))) (define (set-eq? a b) (and (subset? a b) (subset? b a)))
false
75c6b4133182520b63ae4ba6f8469148547b17e7
6f7df1f0361204fb0ca039ccbff8f26335a45cd2
/scheme/tests/background-predicate-tests.scm
12cd25408e670656708d8b870733675ac25cda0c
[]
no_license
LFY/bpm
f63c050d8a2080793cf270b03e6cf5661bf3599e
a3bce19d6258ad42dce6ffd4746570f0644a51b9
refs/heads/master
2021-01-18T13:04:03.191094
2012-09-25T10:31:25
2012-09-25T10:31:25
2,099,550
2
0
null
null
null
null
UTF-8
Scheme
false
false
2,140
scm
background-predicate-tests.scm
(import (background-predicates) (printing)) ; (print "soft predicate tests") ; (print "soft-eq tests") ; (print (soft-eq? 1 2)) ; (print (soft-eq? 1 1.5)) ; (print (soft-eq? 1 1.2)) ; (print (soft-eq? 1 1.1)) ; (print (soft-eq? 1 1.05)) ; ; (print "soft-greater tests") ; (print (soft-greater? 2 1)) ; (print (soft-greater? 1 2)) ; (print (soft-greater? 3 5)) ; (print (soft-greater? 2 1)) ; ; (print "soft-offby1 tests") ; (print (soft-offby1? 1 2)) ; (print (soft-offby1? 1 2.1)) ; (print (soft-offby1? 2 2)) ; (print (soft-offby1? 2 1)) ; (print (soft-offby1? 3 1)) ; ; (print "soft-neg tests") ; ; (print (soft-neg? 1 -1)) ; ; (print (soft-neg? 0.5 -0.5)) ; (print (soft-neg? 0.4 -0.4)) ; (print (soft-neg? 0.3 -0.3)) ; (print (soft-neg? 0.2 -0.2)) ; (print (soft-neg? 0.1 -0.1)) ; ; (print (soft-neg? 0.0 -0.5)) ; (print (soft-neg? 0.0 -0.4)) ; (print (soft-neg? 0.0 -0.3)) ; (print (soft-neg? 0.0 -0.2)) ; (print (soft-neg? 0.0 -0.1)) ; ; (print "range predicate tests") ; (print "range-eq tests") ; (print (range-eq? 1 2)) ; (print (range-eq? 1 1.5)) ; (print (range-eq? 1 1.2)) ; (print (range-eq? 1 1.1)) ; (print (range-eq? 1 1.05)) ; ; (print "range-greater tests") ; (print (range-greater? 2 1)) ; (print (range-greater? 1 2)) ; (print (range-greater? 3 5)) ; (print (range-greater? 2 1)) ; ; (print "range-offby1 tests") ; (print (range-offby1? 1 2)) ; (print (range-offby1? 1 2.1)) ; (print (range-offby1? 2 2)) ; (print (range-offby1? 2 1)) ; (print (range-offby1? 3 1)) ; ; (print "range-neg tests") ; ; (print (range-neg? 1 -1)) ; ; (print (range-neg? 0.5 -0.5)) ; (print (range-neg? 0.4 -0.4)) ; (print (range-neg? 0.3 -0.3)) ; (print (range-neg? 0.2 -0.2)) ; (print (range-neg? 0.1 -0.1)) ; ; (print (range-neg? 0.0 -0.5)) ; (print (range-neg? 0.0 -0.4)) ; (print (range-neg? 0.0 -0.3)) ; (print (range-neg? 0.0 -0.2)) ; (print (range-neg? 0.0 -0.1)) (define pa1 (list soft-eq? (list 1 'H))) (define pa2 (list soft-offby1? (list 'H 2))) (define pa3 (list soft-neg? (list -1 'H))) (print (unify (list pa1))) (print (unify (list pa2))) (print (unify (list pa3))) (print (unify (list pa1 pa2 pa3)))
false
013faa15effd86e73d1a27c94959342fbd1e3953
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
/sitelib/rfc/http2/client.scm
6d8255db4fb4559ea2ebfd563a229d000979b698
[ "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "MIT", "BSD-2-Clause" ]
permissive
ktakashi/sagittarius-scheme
0a6d23a9004e8775792ebe27a395366457daba81
285e84f7c48b65d6594ff4fbbe47a1b499c9fec0
refs/heads/master
2023-09-01T23:45:52.702741
2023-08-31T10:36:08
2023-08-31T10:36:08
41,153,733
48
7
NOASSERTION
2022-07-13T18:04:42
2015-08-21T12:07:54
Scheme
UTF-8
Scheme
false
false
26,944
scm
client.scm
;;; -*- mode:scheme; coding:utf-8; -*- ;;; ;;; rfc/http2/client.scm - HTTP2 client ;;; ;;; Copyright (c) 2010-2015 Takashi Kato <[email protected]> ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; #!read-macro=sagittarius/bv-string #!nounbound (library (rfc http2 client) (export http2-client-connection? make-http2-client-connection close-http2-client-connection! http2-construct-header ;; expose them as well http2-add-request! http2-invoke-requests! ;; convenient macro http2-request http2-multi-requests ;; common methods http2-get ;; TODO the rest http2-head http2-post ;; primitive senders&receivers http2-headers-sender http2-data-sender http2-multipart-sender http2-composite-sender http2-data-receiver http2-binary-receiver http2-null-receiver http2-gzip-receiver make-gzip-receiver http2-redirect-handler ;; TODO redirect handler using HTTP1.1 ) (import (rnrs) (rnrs mutable-pairs) (sagittarius) (sagittarius control) (binary io) (match) (net socket) (rfc uri) (rfc http2 frame) (rfc http2 conditions) (rfc http2 hpack) (rfc gzip) (rfc mime) (srfi :1) (srfi :18)) ;; (define-constant +client-window-size+ 1024) ;; (define-constant +client-window-size+ +http2-default-window-size+) ;; we use max value since we don't have to consider buffer or other factors. (define-constant +client-window-size+ (- (expt 2 31) 1)) ;; HTTP2 client connection (define-record-type (http2-client-connection %make-http2-client-connection http2-client-connection?) ;; HPACK buffers must be separated for request and response. (fields request-hpack-context ; request HPACK context response-hpack-context ; response HPACK context source ; input/output port buffer ; frame buffer (mutable next-id) ; next stream-id streams ; streams (hashtable) (mutable window-size) ; window size. do we need this? ; above is only for server one mutex ; lock for id user-agent ; for user-agent header ;; belows are for reconnection/debugging server ; request server port ; request port options ; TLS or not ) (protocol (lambda (n) (lambda (server port option user-agent) (let ((socket (socket-options->client-socket option server port))) ;; TODO check TLS socket extension. ;; (though, we can't do anything here since this only does HTTP2...) (n (make-hpack-context 4096) (make-hpack-context 4096) (socket-port socket) (make-frame-buffer) 1 (make-eqv-hashtable) 65535 ; initial value (make-mutex) user-agent server port option)))))) (define (stream-not-opened-error-raiser stream-id) (lambda (stream converter) (http2-stream-closed 'http2-sender "The stream is not opened. Maybe forgot to call http2-headers-sender?" `(stream-identifier, stream-id)))) ;; A stream is created when either HEADERS is sent or PUSH_PROMISE ;; is received. Either case, the state should be open. ;; For now we don't preserve streams so there is no idel state. ;; TODO we might want to reuse this (define-record-type http2-stream (fields identifier method ;; needed for redirect uri ;; ditto sender (mutable receiver) ;; this can be later (mutable state) ;; not really used though (mutable window-size) ;; again do we need this? connection ;; connection of this stream redirect-handler ;; for redirect, must be per stream? (mutable header-sender) ;; will be set by http2-headers-sender ) (protocol (lambda (p) (lambda (identifier method uri sender receiver connection :key (redirect-handler http2-redirect-handler)) (p identifier method uri sender receiver 'open (http2-client-connection-window-size connection) connection redirect-handler (stream-not-opened-error-raiser identifier)))))) (define (http2-stream-send-header stream conv) ((http2-stream-header-sender stream) stream conv)) (define (http2-stream-need-header? stream) (http2-stream-header-sender stream)) ;; open stream ;; associate sender and receiver to the created stream ;; associate stream to identifier (define (http2-open-stream conn method uri sender receiver . opts) (define stream-id (http2-next-stream-identifier conn)) (let ((stream (apply make-http2-stream stream-id method uri sender receiver conn opts))) (hashtable-set! (http2-client-connection-streams conn) stream-id stream) stream)) (define (http2-lookup-stream conn id) (let ((lookup (http2-client-connection-streams conn))) (hashtable-ref lookup id #f))) (define (http2-remove-stream! conn id) (define streams (http2-client-connection-streams conn)) (hashtable-delete! streams id)) ;; send or received END_STREAM (define (http2-half-close-stream! stream remote?) (http2-stream-state-set! stream (list 'half-closed remote?))) (define (http2-read-stream stream) (define in (%h2-source (http2-stream-connection stream))) ;; TODO read ) (define (http2-write-stream stream frame end?) (define conn (http2-stream-connection stream)) (define out (%h2-source conn)) (write-http2-frame out (%h2-buffer conn) frame end? (%h2-req-hpack conn))) ;; make things shorter... (define-syntax %h2-source (identifier-syntax http2-client-connection-source)) (define-syntax %h2-buffer (identifier-syntax http2-client-connection-buffer)) (define-syntax %h2-req-hpack (identifier-syntax http2-client-connection-request-hpack-context)) (define-syntax %h2-res-hpack (identifier-syntax http2-client-connection-response-hpack-context)) (define-syntax %h2-options (identifier-syntax http2-client-connection-options)) (define-syntax %h2-agent (identifier-syntax http2-client-connection-user-agent)) (define-syntax %h2-redirect (identifier-syntax http2-stream-redirect-handler)) (define-constant +http2-default-user-agent+ (string-append "Sagittarius-" (sagittarius-version))) ;; TODO add option to configure SETTINGS frame (define (make-http2-client-connection server port :key (secure? #f) (negotiate? #t) (user-agent +http2-default-user-agent+)) (rlet1 conn (%make-http2-client-connection server port (if secure? (tls-socket-options (alpn* '("h2")) (sni* (list server))) (socket-options)) user-agent) (when negotiate? (http2-send-preface conn) (http2-send-settings conn `(;; for now disable push (,+http2-settings-enable-push+ 0) (,+http2-settings-initial-window-size+ ,+client-window-size+) ;; no less than 100 huh? (,+http2-settings-max-concurrent-streams+ 100))) ;; ACK might be handled on request invocation (http2-handle-server-settings conn)))) (define (close-http2-client-connection! conn) ;; Closing port would also close socket ;; see creation of the port (close-port (%h2-source conn))) (define-constant +http2-preface+ #*"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n") (define (http2-send-preface conn) (let1 in/out (%h2-source conn) (put-bytevector in/out +http2-preface+))) (define (http2-send-settings conn settings) (let1 in/out (%h2-source conn) (write-http2-frame in/out (%h2-buffer conn) (make-http2-frame-settings 0 0 settings) ;; we know context is not needed and ;; this won't be the end of stream #f #f))) ;; return #t if the frame is not ACK otherwise #f (define (http2-apply-server-settings conn frame) (define in/out (%h2-source conn)) (define settings (http2-frame-settings-settings frame)) ;; Ignore ACK SETTINGS (and (not (bitwise-bit-set? (http2-frame-flags frame) 0)) ;; TODO handle it properly (let loop ((settings settings)) (cond ((null? settings) ;; send SETTING with ACK (write-http2-frame in/out (%h2-buffer conn) (make-http2-frame-settings 1 0 '()) ;; we know context is not needed and ;; this won't be the end of stream #f #f)) (else (cond ((= (caar settings) +http2-settings-header-table-size+) ;; initial request HPACK table size. (update-hpack-table-size! (%h2-req-hpack conn) (cadar settings))) ((= (caar settings) +http2-settings-initial-window-size+) (http2-client-connection-window-size-set! conn (cdar settings)))) (loop (cdr settings))))))) ;; should only be called when the next frame is SETTINGS. ;; (e.g. during negotiation) (define (http2-handle-server-settings conn) (let1 in/out (%h2-source conn) (http2-apply-server-settings conn (read-http2-frame in/out (%h2-buffer conn) #f)))) (define (http2-next-stream-identifier conn) (mutex-lock! (http2-client-connection-mutex conn)) (let ((next-id (http2-client-connection-next-id conn))) (http2-client-connection-next-id-set! conn (+ next-id 2)) (mutex-unlock! (http2-client-connection-mutex conn)) next-id)) ;; TODO do we need this? (define (http2-add-request! conn method uri sender receiver . opts) (apply http2-open-stream conn method uri sender receiver opts) conn) (define (http2-has-pending-streams? conn) (not (zero? (hashtable-size (http2-client-connection-streams conn))))) ;; This is an interface of generic HTTP2 request. ;; TODO we need to handle push/promise, window update and others. (define (http2-invoke-requests! conn) (define streams (http2-client-connection-streams conn)) (define (terminate-stream id) (http2-remove-stream! conn id)) (let ((in/out (%h2-source conn)) (req-hpack (%h2-req-hpack conn)) (res-hpack (%h2-res-hpack conn))) (define (send-frame frame :optional (end? #t)) (write-http2-frame in/out (%h2-buffer conn) frame end? (%h2-req-hpack conn))) (define (send-goaway e ec stream-id) (send-frame (make-http2-frame-goaway 0 stream-id stream-id ec (if (message-condition? e) (string->utf8 (condition-message e)) #vu8()))) (close-port in/out) (raise e)) (define (send-rst-stream code stream-id) (send-frame (make-http2-frame-rst-stream 0 stream-id code)) (terminate-stream stream-id)) (define (read-frame) (guard (e ((http2-error? e) ;; treat as connection error. (send-goaway e (http2-error-code e) 0)) (else ;; internal error. just close the session (send-goaway e +http2-error-code-internal-error+ 0) #f)) (read-http2-frame in/out (%h2-buffer conn) res-hpack))) (define (get-header sid alist) (cond ((assv sid alist) => cadr) ;; TODO should we allow this? (else '()))) (define (call-receiver sid stream alist frame) (let ((receiver (http2-stream-receiver stream))) (receiver stream (get-header sid alist) frame ;; TODO how should we expose this? (http2-frame-end-stream? frame)))) (define used-window-sizes (make-eqv-hashtable)) (vector-for-each (lambda (sid) (let* ((stream (hashtable-ref streams sid #f)) (sender (http2-stream-sender stream))) ;; we always pass end-stream? #t ;; because we only call sender once. (sender stream #t))) (let ((keys (hashtable-keys streams))) (vector-sort! < keys) keys)) ;; loop until connection has no open stream ;; the results is alist of sid, headers and receiver results. ;; the receiver results are only collected when the stream is ;; ended. (let loop ((results '()) (redirected-sids '()) (redirected-results '())) (define (continue/quit results sid? redirect?) (cond ((http2-has-pending-streams? conn) (loop results (if sid? (cons sid? redirected-sids) redirected-sids) (if redirect? (append redirect? redirected-results) redirected-results))) (else ;; drop stream identifier (apply append (filter-map (lambda (slot) (and (not (memv (car slot) redirected-sids)) (list (cadr slot) (cddr slot)))) results) redirected-results)))) (let* ((frame (read-frame)) (sid (http2-frame-stream-identifier frame)) (stream (hashtable-ref streams sid #f))) (cond ((not frame) #f) ;; these 2 must be first ((http2-frame-settings? frame) (http2-apply-server-settings conn frame) (continue/quit results #f #f)) ((http2-frame-goaway? frame) (close-port in/out) (let ((msg? (http2-frame-goaway-data frame))) (error 'http2-request (if (zero? (bytevector-length msg?)) "Got GOAWAY frame" (utf8->string msg?)) (http2-frame-goaway-last-stream-id frame) (http2-frame-goaway-error-code frame) msg?))) ((http2-frame-rst-stream? frame) (terminate-stream sid) ;; TODO should we remove the stored result of this ;; stream identifier? ;; TODO might be better to raise an error when ;; this is the last stream. (continue/quit results #f #f) #; (error 'http2-request "protocol error" (http2-frame-rst-stream-error-code frame))) ;; window update ((http2-frame-window-update? frame) (let ((size (http2-frame-window-update-window-size-increment frame))) (cond ((zero? size) (terminate-stream sid) (send-rst-stream +http2-error-code-protocol-error+ sid)) ((zero? sid) (http2-client-connection-window-size-set! conn size)) (else (http2-stream-window-size-set! stream size)))) (continue/quit results #f #f)) ((http2-frame-headers? frame) (let ((headers (http2-frame-headers-headers frame))) (when (http2-frame-end-stream? frame) (terminate-stream sid)) ;; TODO can HTTP2 send HEADERS more than once? ;; if so, do we want to update the stored one? (let ((status (utf8->string (http2-header-ref #*":status" headers)))) (if (and status (char=? (string-ref status 0) #\3) ;; 304 and 305 are not redirect (not (memv (string-ref status 2) '(#\4 #\5)))) ;; redirect (let ((r ((%h2-redirect stream) stream headers))) (if r ;; handled externally (continue/quit results sid r) ;; redirect handler should push ;; new stream (continue/quit results sid #f))) (continue/quit (acons sid (cons headers #f) results) #f #f))))) ((http2-frame-data? frame) (let ((r (call-receiver sid stream results frame))) (when (http2-frame-end-stream? frame) (terminate-stream sid) ;; TODO should we raise an error ;; if there is no slot created? (cond ((assv sid results) => (lambda (slot) (set-cdr! (cdr slot) r))))) (hashtable-update! used-window-sizes sid (lambda (v) (let* ((size (bytevector-length (http2-frame-data-data frame))) (new-size (+ v size))) (if (>= new-size +client-window-size+) (begin ;; Even though this should be the specified ;; way to do flow control, however, twitter.com ;; doesn't do anything with this at this moment ;; (2018-06-05). (send-frame (make-http2-frame-window-update 0 sid +client-window-size+)) 0) new-size))) 0) (continue/quit results #f #f))) (else (error 'http2-request "frame not supported" frame))))))) ;; convenient macro (define-syntax http2-request (syntax-rules () ((_ conn method uri sender receiver opts ...) (let ((c conn) (s sender) (r receiver)) (http2-add-request! c method uri s r opts ...) (http2-invoke-requests! c))))) ;; TODO (define-syntax http2-multi-requests (syntax-rules (GET POST HEAD) ((_ conn "clause" (GET uri headers ...) rest ...) ;; TODO how should we handle other receivers? (begin (http2-add-request! conn 'GET uri (http2-headers-sender headers ...) (http2-binary-receiver)) (http2-multi-requests conn "clause" rest ...))) ;; finish ((_ conn "clause") (http2-invoke-requests! conn)) ;; entry point ((_ conn (clause ...) rest ...) (http2-multi-requests conn "clause" (clause ...) rest ...)))) ;; helper (define (http2-construct-header stream . extras) (define conn (http2-stream-connection stream)) (define ->bv string->utf8) (let1 options (%h2-options conn) `((#*":method" ,(->bv (symbol->string (http2-stream-method stream)))) (#*":scheme" ,(if (tls-socket-options? options) #*"https" #*"http")) (#*":path" ,(->bv (http2-stream-uri stream))) (#*":authority" ,(->bv (http2-client-connection-server conn))) (#*"user-agent" ,(->bv (%h2-agent conn))) ,@(let loop ((h extras) (r '())) (match h ;; compatible format (:key "value") ;; may be we should accept all expressions and ;; convert them using format and string->utf8? (((? keyword? name) value rest ...) (loop rest (cons (list (->bv (keyword->string name)) (->bv value)) r))) (((? bytevector? name) (? bytevector? value) rest ...) (loop rest (cons (list name value) r))) (() (reverse! r)) (else (error 'http2-construct-header "invalid header" extras))))))) ;;; senders ;; TODO should senders look like this? ;; it might be better to wrap frames a bit for cutome senders ;; so that users don't have to import (rfc http2 frame). but ;; for now. (define (http2-headers-sender . headers) (lambda (stream end-stream?) (define (sender stream conv) (let* ((headers (apply http2-construct-header stream (conv headers))) (id (http2-stream-identifier stream)) (frame (make-http2-frame-headers 0 id #f #f headers))) (http2-write-stream stream frame end-stream?)) ;; ok it's ugly but we can check now :) (http2-stream-header-sender-set! stream #f)) (if end-stream? ;; if it's end of stream, then just send it (sender stream values) ;; otherwise let the next sender handle it (http2-stream-header-sender-set! stream sender)))) (define (http2-data-sender data) (lambda (stream end-stream?) (when (http2-stream-need-header? stream) (http2-stream-send-header stream values)) (let ((frame (make-http2-frame-data 0 (http2-stream-identifier stream) data))) (http2-write-stream stream frame end-stream?)))) (define (make-stream-write-port stream end-stream? buffer-size) (define buffer (make-bytevector buffer-size)) (define sid (http2-stream-identifier stream)) (define pos 0) (define (flush-buffer! end-stream? buffer) (let ((frame (make-http2-frame-data 0 sid buffer))) (http2-write-stream stream frame end-stream?))) (define (write! bv start count) (let loop ((i start) (c count)) (if (zero? c) count (let ((size (min c (- buffer-size pos)))) (bytevector-copy! bv i buffer pos size) (set! pos (+ pos size)) (when (= pos buffer-size) (flush-buffer! #f buffer) (set! pos 0)) (loop (+ i size) (- c size)))))) (define (close!) (define (copy-buffer buffer) (if (zero? pos) #vu8() (bytevector-copy buffer 0 pos))) (flush-buffer! end-stream? (copy-buffer buffer))) (make-custom-binary-output-port "stream-write-port" write! #f #f close!)) (define multipart-transcoder (make-transcoder (latin-1-codec) 'none)) (define (adjust-for-multipart boundary) (lambda (headers) (define ->bv string->utf8) (define (reconstruct headers boundary) (define (content-type? v) (or (eq? v :content-type) (and (bytevector? v) (bytevector=? #*"content-type" v)))) (let loop ((r '()) (h headers) (ct? #f)) (match h (() (cons* #*"mime-version" #*"1.0" (if ct? r (cons* #*"content-type" boundary r)))) (((? content-type? ct) value rest ...) (loop (if ct? r (cons* #*"content-type" boundary r)) rest #t)) ((name value rest ...) (loop (cons* name value r) rest ct?))))) (let1 b (string-append "multipart/form-data; boundary=\"" boundary "\"") (reconstruct headers (->bv b))))) (define (http2-multipart-sender parts :key (buffer-size 4096) (boundary (mime-make-boundary))) (lambda (stream end-stream?) ;; ok hope user sent it properly then (when (http2-stream-need-header? stream) (http2-stream-send-header stream (adjust-for-multipart boundary))) (let ((out (transcoded-port (make-stream-write-port stream end-stream? buffer-size) multipart-transcoder))) (mime-compose-message parts out :boundary boundary) (close-output-port out)))) (define (http2-composite-sender . senders) (lambda (stream end-stream?) (let loop ((senders senders)) (unless (null? senders) (cond ((null? (cdr senders)) ((car senders) stream end-stream?)) (else ((car senders) stream #f) (loop (cdr senders)))))))) ;;; receivers ;; TODO better handling... (define (http2-data-receiver sink flusher) (lambda (stream headers frame end-stream?) (when (http2-frame-data? frame) (put-bytevector sink (http2-frame-data-data frame))) (and end-stream? (flusher sink)))) (define (http2-binary-receiver) (let ((out (open-output-bytevector))) (http2-data-receiver out get-output-bytevector))) ;; do nothing :) (define (http2-null-receiver) (lambda (stream header frame end-stream?) #vu8())) (define (http2-gzip-receiver receiver) (let ((in/out (open-chunked-binary-input/output-port))) (lambda (stream headers frame end-stream?) (define (handle-compressed-stream) (define (call-next) (set-port-position! in/out 0) (let* ((gin (open-gzip-input-port in/out :owner? #t)) (frame (make-http2-frame-data 0 stream (get-bytevector-all gin)))) (receiver stream headers frame #t))) (when (http2-frame-data? frame) (put-bytevector in/out (http2-frame-data-data frame))) (and end-stream? (call-next))) (if (equal? (http2-header-ref #*"content-encoding" headers) #*"gzip") (handle-compressed-stream) (receiver stream headers frame end-stream?))))) ;; TODO more receivers ;;; common APIs (define (make-gzip-receiver) (http2-gzip-receiver (http2-binary-receiver))) ;; GET (define (http2-get conn uri :key (receiver (make-gzip-receiver)) (redirect-handler http2-redirect-handler) :allow-other-keys headers) ;; discards the stored streams first (when (http2-has-pending-streams? conn) (http2-invoke-requests! conn)) (http2-add-request! conn 'GET uri (apply http2-headers-sender headers) receiver :redirect-handler redirect-handler) (apply values (car (http2-invoke-requests! conn)))) ;; HEAD (define (http2-head conn uri :key (receiver (make-gzip-receiver)) (redirect-handler http2-redirect-handler) :allow-other-keys headers) ;; discards the stored streams first (when (http2-has-pending-streams? conn) (http2-invoke-requests! conn)) (http2-add-request! conn 'HEAD uri (apply http2-headers-sender headers) receiver :redirect-handler redirect-handler) (apply values (car (http2-invoke-requests! conn)))) ;; POST (not properly tested) (define (http2-post conn uri data :key (receiver (make-gzip-receiver)) (redirect-handler http2-redirect-handler) :allow-other-keys headers) ;; discards the stored streams first (when (http2-has-pending-streams? conn) (http2-invoke-requests! conn)) (let ((size (number->string (bytevector-length data)))) (http2-add-request! conn 'POST uri (http2-composite-sender (apply http2-headers-sender :content-length size headers) (http2-data-sender data)) receiver :redirect-handler redirect-handler) (apply values (car (http2-invoke-requests! conn))))) ;;; handlers ;; redirect ;; TODO redirect history (define (http2-redirect-handler stream headers) ;; get location (define (get-location headers) ;; for now only header (cond ((http2-header-ref #*"location" headers) => utf8->string) (else #f))) (let ((loc (get-location headers)) (receiver (http2-stream-receiver stream))) (let-values (((s ui host port path q f) (uri-parse loc))) ;; update stream receiver to null receiver (http2-stream-receiver-set! stream (http2-null-receiver)) (if (and host (not (string=? host (http2-client-connection-server (http2-stream-connection stream))))) (let ((conn (make-http2-client-connection host (if port (number->string port) "80") :secure? (and s (string=? s "https"))))) ;; we use the same http2 redirect handler (http2-request conn (http2-stream-method stream) path (http2-stream-sender stream) receiver)) ;; make new stream (let ((s (http2-open-stream (http2-stream-connection stream) (http2-stream-method stream) path (http2-stream-sender stream) receiver))) ;; invoke sender ;; TODO shouls we handle this in `http2-invoke-requests!`? ((http2-stream-sender stream) s #t) #f))))) ;;; helpers (define (http2-header-ref bv headers) (cond ((assoc bv headers bytevector=?) => cadr) (else #f))) )
true
79dca46b531bfdb457a3af2388310c364b499d07
ac2a3544b88444eabf12b68a9bce08941cd62581
/tests/unit-tests/02-flonum/flnumerator.scm
6102c8468a672adb4b07860b92162b7c470bb320
[ "Apache-2.0", "LGPL-2.1-only" ]
permissive
tomelam/gambit
2fd664cf6ea68859d4549fdda62d31a25b2d6c6f
d60fdeb136b2ed89b75da5bfa8011aa334b29020
refs/heads/master
2020-11-27T06:39:26.718179
2019-12-15T16:56:31
2019-12-15T16:56:31
229,341,552
1
0
Apache-2.0
2019-12-20T21:52:26
2019-12-20T21:52:26
null
UTF-8
Scheme
false
false
697
scm
flnumerator.scm
(include "#.scm") (check-eqv? (flnumerator 0.0) 0.) (check-eqv? (flnumerator -0.0) -0.) (check-eqv? (flnumerator 0.5) 1.) (check-eqv? (flnumerator 1.0) 1.) (check-eqv? (flnumerator 1.5) 3.) (check-eqv? (flnumerator 3.5) 7.) (check-eqv? (flnumerator 5.0) 5.) (check-tail-exn wrong-number-of-arguments-exception? (lambda () (flnumerator))) (check-tail-exn wrong-number-of-arguments-exception? (lambda () (flnumerator 1.0 2.0))) (check-tail-exn type-exception? (lambda () (flnumerator 1))) (check-tail-exn type-exception? (lambda () (flnumerator 1/2))) (check-tail-exn type-exception? (lambda () (flnumerator -inf.0))) (check-tail-exn type-exception? (lambda () (flnumerator +inf.0)))
false
3d39670457cd7a7d862ef517379ec50f66c15092
5fa722a5991bfeacffb1d13458efe15082c1ee78
/src/c3_35.scm
debcf1e4432347a609f8f1ff3e0b980315cebbf7
[]
no_license
seckcoder/sicp
f1d9ccb032a4a12c7c51049d773c808c28851c28
ad804cfb828356256221180d15b59bcb2760900a
refs/heads/master
2023-07-10T06:29:59.310553
2013-10-14T08:06:01
2013-10-14T08:06:01
11,309,733
3
0
null
null
null
null
UTF-8
Scheme
false
false
192
scm
c3_35.scm
; in lib/constraint.scm (import (constraint)) (print-connector (csquare (cv 3))) (let ((a (make-connector))) (define c (csquare a)) (set-new-value! c 4 'user) (print-connector a))
false
1cd446f19a95b71fc3417de824fbc357deabda1c
917429e3eb6bcf2db8c71197f88b979d998b1b7e
/progs/general/integ.scm
cd32b5276358d1c8e34474aa800eddacc7457ee5
[]
no_license
mario-goulart/chicken-benchmarks
554ca8421631211a891cc497f84dfe62b8f9c8e5
ea00fe51ec33496de7c9b07fa0ec481fe59989fa
refs/heads/master
2021-11-20T21:40:55.198252
2021-10-09T18:52:48
2021-10-09T18:52:48
4,427,587
1
5
null
2019-01-27T07:59:38
2012-05-24T01:59:23
Scheme
UTF-8
Scheme
false
false
902
scm
integ.scm
;; Copied from stalin-0.11 (benchmarks/integ.sc) -- mario (define (integrate-1D L U F) (let ((D (/ (- U L) 8.0))) (* (+ (* (F L) 0.5) (F (+ L D)) (F (+ L (* 2.0 D))) (F (+ L (* 3.0 D))) (F (+ L (* 4.0 D))) (F (- U (* 3.0 D))) (F (- U (* 2.0 D))) (F (- U D)) (* (F U) 0.5)) D))) (define (integrate-2D L1 U1 L2 U2 F) (integrate-1D L2 U2 (lambda (y) (integrate-1D L1 U1 (lambda (x) (F x y))) ))) (define (zark U V) (integrate-2D 0.0 U 0.0 V (lambda (X Y) (* X Y)) )) (define (r-total N) (do ((I 1 (+ I 1)) (Sum 0.0 (+ Sum (zark (* I 1.0) (* I 2.0))))) ((> I N) Sum))) (define (i-total N) (do ((I 1 (+ I 1)) (Sum 0.0 (+ Sum (let ((I2 (* (* I I) 1.0))) (* I2 I2))))) ((> I N) Sum))) (define (error-sum-of-squares N) (do ((I 1 (+ I 1)) (Sum 0.0 (+ Sum (let ((E (- (r-total I) (i-total I)))) (* E E))))) ((> I N) Sum))) (time (error-sum-of-squares 700))
false
0e5e4a6c35c1f99bdadbaa106fb837a52ac98b8f
3132831399eacc4bd1ae519aac18a1342dec7282
/Homeworks/1st/03.scm
17fc560b6c752902cb7cf30692a040f555737018
[]
no_license
TsHristov/Functional-Programming-FMI-2017
ba3f1d46ed276f0fa4da7e6c396e4f50c1291e0d
58176d53d507c6df70465e1fcfbcd2c67f8af0aa
refs/heads/master
2021-09-05T18:49:14.471004
2018-01-30T11:08:00
2018-01-30T11:08:00
105,808,452
6
0
null
null
null
null
UTF-8
Scheme
false
false
1,790
scm
03.scm
;; Compare three root-finding algorithms: ;; - Newton`s Method ;; - Bisection Method ;; - Secant Method ;; --------------------------------------------------------------------------- (define (bisection-method f a b eps) (define (search a b iterations) (let ((c (/ (+ a b) 2.0))) (if (or (= (f c) 0) (< (- c a) eps)) (list (list 'iterations: iterations) (list 'root: c)) (cond ((< (* (f a) (f c)) 0) (search a c (+ 1 iterations))) ((< (* (f b) (f c)) 0) (search c b (+ 1 iterations))))))) (search a b 0)) ;; --------------------------------------------------------------------------- (define (secant-method f a b eps) (define xi-1 a) (define xi b) (define (xi+1 xi-1 xi) (- xi (/ (* (f xi) (- xi xi-1)) (- (f xi) (f xi-1))))) (define (search xi-1 xi iterations) (if (or (= (f xi) 0) (< (- xi xi-1) eps)) (list (list 'iterations: iterations) (list 'root: xi)) (search xi (xi+1 xi-1 xi) (+ 1 iterations)))) (search xi-1 xi 0)) ;; --------------------------------------------------------------------------- (define (newton-method f a b eps) (define dx 0.001) (define (derive f) (lambda (x) (/ (- (f (+ x dx)) (f x)) dx))) (define x0 a) (define (xi+1 xi) (- xi (/ (f xi) ((derive f) xi)))) (define (search xi-1 xi iterations) (if (or (= (f xi) 0) (< (- xi xi-1) eps)) (list (list 'iterations: iterations) (list 'root: xi)) (search xi (xi+1 xi) (+ 1 iterations)))) (search x0 (xi+1 x0) 0)) ;; --------------------------------------------------------------------------- (define (compare-methods f a b eps) (list (cons 'Newton-Method: (newton-method f a b eps)) (cons 'Bisection-Method: (bisection-method f a b eps)) (cons 'Secant-Method: (secant-method f a b eps))))
false
bdbe3d5560593ceedebd9ff08982d4e882cf37bd
8a0660bd8d588f94aa429050bb8d32c9cd4290d5
/sitelib/rfc/%3a5322.scm
72bb8ab2174b73280ac6ec8938e829c0e7eb5b41
[ "BSD-2-Clause" ]
permissive
david135/sagittarius-scheme
dbec76f6b227f79713169985fc16ce763c889472
2fbd9d153c82e2aa342bfddd59ed54d43c5a7506
refs/heads/master
2016-09-02T02:44:31.668025
2013-12-21T07:24:08
2013-12-21T07:24:08
32,497,456
0
0
null
null
null
null
UTF-8
Scheme
false
false
11,249
scm
%3a5322.scm
;;; -*- Scheme -*- ;;; ;;; 5322.scm - RFC5322 Internet Message Format ;;; ;;; Copyright (c) 2009-2011 Takashi Kato <[email protected]> ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; ;; Main reference: ;; RFC5322 URI Generic Syntax ;; <http://www.ietf.org/rfc/rfc5322.txt> #!read-macro=sagittarius/regex (library (rfc :5322) (export &rfc5322-parse-error rfc5322-parse-error? rfc5322-read-headers rfc5322-next-token rfc5322-header-ref rfc5322-field->tokens rfc5322-quoted-string rfc5322-write-headers rfc5322-parse-date rfc5322-invalid-header-field ;; misc rfc5322-line-reader rfc5322-dot-atom ;; charsets *rfc5322-atext-chars* date->rfc5322-date ) (import (rnrs) (rnrs r5rs) (sagittarius) (sagittarius io) (sagittarius regex) (sagittarius control) (text parse) (shorten) (match) (srfi :1 lists) (srfi :2 and-let*) (srfi :13 strings) (srfi :14 char-sets) (srfi :19 time) (srfi :26 cut)) (define-condition-type &rfc5322-parse-error &assertion make-rfc5322-parse-error rfc5322-parse-error? (name header-field-name) (body header-field-body)) (define (rfc5322-parse-error who msg name body . irritants) (raise (apply condition (filter values (list (make-rfc5322-parse-error name body) (and who (make-who-condition who)) (make-message-condition msg) (make-irritants-condition irritants)))))) (define wsp '(#\space #\tab)) (define rfc5322-char-set (char-set-difference char-set:printing (string->char-set ":"))) (define (rfc5322-line-reader port) (let1 r (get-line port) (if (eof-object? r) r (let1 len (string-length r) (cond ((zero? len) r) ((char=? #\x0d (string-ref r (- len 1))) ;; check CR ;; TODO memory waste (substring r 0 (- len 1))) (else r)))))) (define (rfc5322-read-headers in :optional (strict? #f) (reader (cut rfc5322-line-reader <>))) (define (accum name bodies r) (cons (list name (string-concatenate-reverse bodies)) r)) (define drop-leading-fws string-trim) (let loop ((r '()) (line (reader in))) (cond ((eof-object? line) (reverse! r)) ((string-null? line) (reverse! r)) (else (receive (n body) (string-scan line ":" 'both) (let ((name (and-let* (( (string? n) ) (name (string-trim-both n)) ( (string-every rfc5322-char-set name) )) (string-downcase name)))) (cond (name (let loop2 ((nline (reader in)) (bodies (list (drop-leading-fws body)))) (cond ((eof-object? nline) ;; maybe premature end of the message (if strict? (rfc5322-parse-error 'rfc5322-read-headers "premature end of message header" #f #f) (reverse! (accum name bodies r)))) ((string-null? nline) (reverse! (accum name bodies r))) ;; treats folding. ((memv (string-ref nline 0) wsp) (loop2 (reader in) (cons nline bodies))) (else (loop (accum name bodies r) nline))))) (strict? (rfc5322-parse-error 'rfc5322-read-headers (format "bad header line: ~s" line) #f #f)) (else (loop r (reader in)))))))))) (define (rfc5322-header-ref header field-name . maybe-default) (cond ((assoc field-name header) => cadr) (else (get-optional maybe-default #f)))) (define (rfc5322-field->tokens field . opts) (call-with-input-string field (lambda (port) (let ((proc (cut apply rfc5322-next-token <> opts))) (let loop ((l (proc port)) (r '())) (if (eof-object? l) (reverse! r) (loop (proc port) (cons l r)))))))) (define *rfc5322-atext-chars* (string->char-set "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#$%&'*+/=?^_`{|}~-0123456789")) (define (rfc5322-dot-atom input) (next-token-of `(,*rfc5322-atext-chars* #\.) input)) (define *quote-set* (string->char-set "\"")) (define (rfc5322-quoted-string input) (call-with-string-output-port (lambda (port) (let loop ((c (peek-next-char input))) (cond ((eof-object? c) #t);; tolerate missing closing DQUOTE ((char=? c #\") (get-char input) #t) ;; discard DQUOTE ((char=? c #\\) (let ((c (peek-next-char input))) (cond ((eof-object? c) #t) ;; tolerate stray backslash (else (put-char port c) (loop (peek-next-char input)))))) (else (put-char port c) (loop (peek-next-char input)))))))) (define *rfc5322-standard-tokenizers* `((,*quote-set* . ,rfc5322-quoted-string) (,*rfc5322-atext-chars* . ,rfc5322-dot-atom))) (define (rfc5322-next-token input . opts) (let ((tokenab (map (lambda (e) (cond ((char-set? e) (cons e (cut next-token-of e <>))) (else e))) (get-optional opts *rfc5322-standard-tokenizers*))) (c (rfc5322-skip-cfws input))) (cond ((eof-object? c) c) ((find (lambda (e) (char-set-contains? (car e) c)) tokenab) => (lambda (e) ((cdr e) input))) (else (get-char input))))) (define (rfc5322-skip-cfws input) (define (scan c) (cond ((eof-object? c) c) ((char=? c #\( ) (in-comment (peek-next-char input))) ((char-whitespace? c) (scan (peek-next-char input))) (else c))) (define (in-comment c) (cond ((eof-object? c) c) ((char=? c #\) ) (scan (peek-next-char input))) ((char=? c #\\ ) (read-char input) (in-comment (peek-next-char input))) ((char=? c #\( ) (in-comment (in-comment (peek-next-char input)))) (else (in-comment (peek-next-char input))))) (scan (peek-char input))) ;; write (define (rfc5322-write-headers headers :key (output (current-output-port)) (check :error) (continue #f)) (define (process headers) (dolist (field headers) (display (car field) output) (display ": " output) (display (cadr field) output) (unless (string-suffix? "\r\n" (cadr field)) (display "\r\n" output))) (unless continue (display "\r\n" output))) (define (bad name body reason) (assertion-violation 'rfc5322-write-headers (format "Illegal RFC5322 header field data (~a)" reason) (format " ~a: ~,,,,80:a" reason name body))) (if (memv check '(#f :ignore)) (process headers) (let loop ((hs headers) (hs2 '())) (match hs (() (process (reverse hs2))) (((name body) . rest) (cond ((rfc5322-invalid-header-field (string-append name ": " body)) => (lambda (reason) (if (eq? check :error) (bad name body reason) (receive (name2 body2) (check name body reason) (if (and (equal? name name2) (equal? body body2)) (bad name body reason) (loop `((,name2 ,body2) . ,rest) hs2)))))) (else (loop rest `((,name ,body) . ,hs2))))) (else (assertion-violation 'rfc5322-write-headers "Invalid header data" headers)))))) (define *crlf* (string->char-set "\r\n")) (define *invalid-char* (char-set-union (char-set-difference char-set:full char-set:ascii) (string->char-set "\x0;"))) (define (rfc5322-invalid-header-field body) (if (string-index body *invalid-char*) 'bad-character (let1 lines (string-split body "\r\n ") (cond ((exists (lambda (s) (> (string-length s) 998)) lines) 'line-too-long) ((exists (lambda (s) (string-index s *crlf*)) lines) 'stray-crlf) (else #f))))) ;; date section 3.3 (define (rfc5322-parse-date s) (define (dow->number dow) (list-index (cut string=? <> dow) '("Sun" "Mon" "Tue" "Wed" "Thu" "Fri" "Sat"))) (define (month->number mon) (+ 1 (list-index (cut string=? <> mon) '("Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec")))) (define (year->number year) (let1 y (string->number year) (and y (cond ((< y 50) (+ y 2000)) ((< y 100) (+ y 1900)) (else y))))) (define (tz->number tz) (cond ((equal? tz "-0000") #f) ((string->number tz)) ((assoc tz '(("UT" . 0) ("GMT" . 0) ("EDT" . -400) ("EST" . -500) ("CDT" . -500) ("CST" . -600) ("MDT" . -600) ("MST" . -700) ("PDT" . -700) ("PST" . -800))) => cdr) (else #f))) (cond ((#/ # [day-of-week ","] (?:(Sun|Mon|Tue|Wed|Thu|Fri|Sat)\s*,)?\s* # date = day month year # day = {[FWS] 1*2DIGIT FWS} \/ obs-day (\d+)\s* # month (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s* # for emacs|) # year = {FWS 4*DIGIT FWS} \/ obs-year (\d{2}(?:\d{2})?)\s+ # time = time-of-day zone (?# time-of-day = hour ":" minute [":" second]) (\d{2})\s*:\s*(\d{2})(?:\s*:\s*(\d{2}))? # zone = {FWS ["+" \/ "-"] 4DIGIT} \/ obs-zone (?:\s+([+-]\d{4}|[A-Z][A-Z][A-Z]?))? # we ignore military zone|)) /x s) => (^m (values (year->number (m 4)) ; year (month->number (m 3)) ; month (string->number (m 2)) ; dom (string->number (m 5)) ; hour (string->number (m 6)) ; min (cond ((m 7) => string->number) (else #f)) ; sec (cond ((m 8) => tz->number) (else #f)) ; tz (cond ((m 1) => dow->number) (else #f)) ; dow ))) (else (values #f #f #f #f #f #f #f #f)))) (define (date->rfc5322-date date) ;; we can not use this because of ~z formatter... ;;(date->string date "~a, ~e ~b ~Y ~3 ~z") (let1 tz (date-zone-offset date) (format "~a, ~2d ~a ~4d ~2,'0d:~2,'0d:~2,'0d ~a~2,'0d~2,'0d" (vector-ref '#("Sun" "Mon" "Tue" "Wed" "Thu" "Fri" "Sat") (date-week-day date)) (date-day date) (vector-ref '#("" "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec") (date-month date)) (date-year date) (date-hour date) (date-minute date) (date-second date) (if (>= tz 0) "+" "-") (quotient (abs tz) 3600) (modulo (quotient (abs tz) 60) 60))) ) )
false
f9638d3a50269da693324aea2dcca327d335bb4d
2bcf33718a53f5a938fd82bd0d484a423ff308d3
/programming/sicp/ch3/ex-3.71.scm
dac7b218aa5f6885b89846ab0bd24807df372265
[]
no_license
prurph/teach-yourself-cs
50e598a0c781d79ff294434db0430f7f2c12ff53
4ce98ebab5a905ea1808b8785949ecb52eee0736
refs/heads/main
2023-08-30T06:28:22.247659
2021-10-17T18:27:26
2021-10-17T18:27:26
345,412,092
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,062
scm
ex-3.71.scm
#lang sicp (#%require "stream.scm") (#%require "ex-3.70.scm") ; weighted-pairs ;; https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-24.html#%_thm_3.71 ;; Ramanujan numbers are those that can be expressed as the sum of two cubes in ;; more than one way. Construct them by ordering pairs based on a weighting of ;; i³ + j³, then searching those pairs for two consecutive ones with the same ;; weight. (define (ramanujan-numbers) (define (sum-of-cubes pair) (let ((i (car pair)) (j (cadr pair))) (+ (* i i i) (* j j j)))) (define (go s) (let ((i (stream-car s)) (j (stream-car (stream-cdr s)))) (if (= (sum-of-cubes i) (sum-of-cubes j)) (cons-stream (list (sum-of-cubes i) i j) (go (stream-cdr s))) (go (stream-cdr s))))) (go (weighted-pairs integers integers sum-of-cubes))) (display-stream-next (ramanujan-numbers) 5) ;; (1729 (1 12) (9 10)) ;; (1729 (9 10) (1 12)) ;; (4104 (2 16) (9 15)) ;; (4104 (9 15) (2 16)) ;; (13832 (2 24) (18 20))
false
8dfef5e010413ff33da091dac76fe30e92e8c3f2
fba55a7038615b7967256306ee800f2a055df92f
/soulawaker/2.1/ex-2.5.scm
9c137c9181c84e9dd1469fb93ed9557c4a56402f
[]
no_license
lisp-korea/sicp2014
7e8ccc17fc85b64a1c66154b440acd133544c0dc
9e60f70cb84ad2ad5987a71aebe1069db288b680
refs/heads/master
2016-09-07T19:09:28.818346
2015-10-17T01:41:13
2015-10-17T01:41:13
26,661,049
2
3
null
null
null
null
UTF-8
Scheme
false
false
429
scm
ex-2.5.scm
(define (cons x y) (define (very-square x y) (cond ((= y 0) 1) (else (* x (very-square x (- y 1)))))) (define (dispatch m) (cond ((= m 0) x) ((= m 1) y) (else (* (very-square 2 x) (very-square 3 y))))) (cond ((< x 0) (display "error: x is not a positive integer")) ((< y 0) (display "error: y is not a positive integer")) (else (dispatch)))) (define (car z) (z 0)) (define (cdr z) (z 1))
false
7cdf93ec545918d2c837810e1379731421eed8d9
140a499a12332fa8b77fb738463ef58de56f6cb9
/worlds/core/verbcode/12/fit-4.scm
ea28c793467e64dcc2bdbd60c72db5acff6364b9
[ "MIT" ]
permissive
sid-code/nmoo
2a5546621ee8c247d4f2610f9aa04d115aa41c5b
cf504f28ab473fd70f2c60cda4d109c33b600727
refs/heads/master
2023-08-19T09:16:37.488546
2023-08-15T16:57:39
2023-08-15T16:57:39
31,146,820
10
0
null
null
null
null
UTF-8
Scheme
false
false
515
scm
fit-4.scm
(let ((str (get args 0)) (strlen (len str)) (size (get args 1)) (fill (get args 2 " ")) (toolong (get args 3 "..."))) (cond ((= size strlen) str) ((> size strlen) (let ((difference (- size strlen)) (numfills (+ 1 (/ difference (len fill))))) (substr (cat str (repeat fill numfills)) 0 (- size 1)))) ((< size strlen) (let ((pos (- size (+ 1 (len toolong))))) (if (> 1 pos) (substr str 0 size) (cat (substr str 0 pos) toolong)))) ("empty else clause")))
false
549291c6ac8cb47a91001439cf643bdeeb69a589
85a93dc2bd260c64bbf572f577c0f9a585551684
/samples/sample.scm
8e0b9a691ca3ce3ed8814d448cff4ea4d9b49edc
[]
no_license
kristianlm/acorn
8293d38e900e0c33d00b8d43a49a7b901d368b37
a6930bcd40164d962c0eefce0d1a32dbb49548da
refs/heads/master
2021-01-19T01:10:13.286925
2016-06-02T11:42:22
2016-06-02T11:42:22
3,646,213
3
0
null
null
null
null
UTF-8
Scheme
false
false
468
scm
sample.scm
(use acorn) (define space (nodes->space `(space () (body () (circle (radius 1)))))) ;; give our world a little gravity (space-set-gravity space (v 0 -1)) ;; run our simulation for a while, ;; letting our ball fall (do ((i 0 (add1 i))) ((> i 100)) (space-step space (/ 1 120))) ;; y-coordinate of pos and vel should be altered by gravity (pp (space->nodes space)) (space-free space)
false
2965631900dc5f8fd293ab8fe6d54a90d4df7408
e1c580145992634f089af18940508f5c26d2e264
/umcu/packages/contra.scm
bdc5e370e8dc8f0746be9f54631b44fa3ffd4e98
[]
no_license
inijman/guix-additions
8542592972e644a4ccd7b36ad4dd9b5631008fb5
b8e0e3f3b9598aade3103e9f491307fa06ece03d
refs/heads/master
2021-07-13T21:35:25.731179
2020-05-28T14:01:04
2020-05-28T14:01:04
142,980,977
0
0
null
2018-07-31T07:49:53
2018-07-31T07:49:53
null
UTF-8
Scheme
false
false
3,452
scm
contra.scm
;;; GNU Guix --- Functional package management for GNU ;;; Copyright © 2016 Roel Janssen <[email protected]> ;;; ;;; This file is not officially part of GNU Guix. ;;; ;;; GNU Guix is free software; you can redistribute it and/or modify it ;;; under the terms of the GNU General Public License as published by ;;; the Free Software Foundation; either version 3 of the License, or (at ;;; your option) any later version. ;;; ;;; GNU Guix is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>. (define-module (umcu packages contra) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix packages) #:use-module (guix download) #:use-module (guix build utils) #:use-module (guix build-system gnu) #:use-module (umcu packages samtools) #:use-module (gnu packages) #:use-module (gnu packages compression) #:use-module (gnu packages python) #:use-module (gnu packages statistics) #:use-module (gnu packages bioinformatics)) (define-public contra-2.0.6 (package (name "contra") (version "2.0.6") (source (origin (method url-fetch) (uri (string-append "mirror://sourceforge/contra-cnv/CONTRA.V2.0/CONTRA.v" version ".tar.gz")) (sha256 (base32 "0agpcm2xh5f0i9n9sx1kvln6mzdksddmh11bvzj6bh76yw5pnw91")))) (build-system gnu-build-system) (propagated-inputs `(("python" ,python-2) ("r" ,r) ;; ("r-dnacopy" ,r-dnacopy) <-- missing in Pjotr's tree ("bedtools" ,bedtools) ("samtools" ,samtools-1.2))) (arguments `(#:tests? #f ; There are no tests. #:phases (modify-phases %standard-phases (delete 'configure) (delete 'build) ; We can use Guix's BEDtools instead. (replace 'install (lambda _ (let* ((out (assoc-ref %outputs "out")) (bin (string-append out "/bin")) (doc (string-append out "/share/doc/contra"))) (mkdir-p bin) (mkdir-p doc) (and (zero? (system* "cp" "--recursive" "scripts" bin)) (zero? (system* "cp" "contra.py" bin)) (zero? (system* "cp" "baseline.py" bin)) ;; There's only a pre-built PDF available. (zero? (system* "cp" "CONTRA_User_Guide.2.0.pdf" doc))))))))) (home-page "http://contra-cnv.sourceforge.net/") (synopsis "Tool for copy number variation (CNV) detection for targeted resequencing data") (description "CONTRA is a tool for copy number variation (CNV) detection for targeted resequencing data such as those from whole-exome capture data. CONTRA calls copy number gains and losses for each target region with key strategies including the use of base-level log-ratios to remove GC-content bias, correction for an imbalanced library size effect on log-ratios, and the estimation of log-ratio variations via binning and interpolation. It takes standard alignment formats (BAM/SAM) and outputs in variant call format (VCF 4.0) for easy integration with other next generation sequencing analysis package.") (license license:gpl3+)))
false
44a46f075a1142d5647190eed77593656271a202
bdfa935097ef39f66c7f18856accef422ef39128
/parts/qa0/tree/scheme/be-ckind.ss
d2188456962c404a5fff4a6d147ef24fbafdf834
[ "MIT" ]
permissive
djm2131/qlua
213f5ed4b692b1b03d2ff1a78d09ea9d2d9fe244
737bfe85228dac5e9ae9eaab2b5331630703ae73
refs/heads/master
2020-04-18T15:01:06.117689
2019-02-06T15:23:27
2019-02-06T15:23:27
162,349,914
0
0
null
null
null
null
UTF-8
Scheme
false
false
10,920
ss
be-ckind.ss
;; Backend prototype for C-like targets #fload "sfc.sf" #fload "common.sf" #fload "error.ss" #fload "print.ss" #fload "format.ss" #fload "ast.ss" #fload "parser.ss" #fload "attr.ss" #fload "backend.ss" #fload "cenv.ss" #fload "cheader.ss" #fload "verbose.ss" ;; ;; (provide empty-postparam*) ;; (provide ck-new-var) ;; (provide do-emit) ;; (provide preemit-addr*) ;; (provide preemit-input) ;; (provide preemit-output) ;; (provide preemit-param) ;; (provide build-ckind-back-end) ;; (define (empty-postparam* arg-name* type* arg-c-name* c-type* env) #t) (define ck-new-var (let ([*var-count* 0]) (lambda () (let ([x (gen-reg 'g *var-count*)]) (set! *var-count* (+ *var-count* 1)) x)))) (define (do-emit* level fmt arg*) (define p (current-output-port)) (let loop ([n level]) (cond [(zero? n)] [else (q-print " ") (loop (- n 1))])) (q-fprint* p fmt arg*) (newline)) (define-syntax do-emit (syntax-rules () [(_ level fmt arg ...) (do-emit* level fmt (list arg ...))])) (define (preemit-output output env) (variant-case output [reg (name) (car (ce-lookup-x env 'back-end name "be-ckind: name of ~a not found" name))])) (define (preemit-input input env) (variant-case input [reg (name) (car (ce-lookup-x env 'back-end name "be-ckind: name of ~a not found" name))] [c-expr-number (number) number])) (define (preemit-addr* addr* env) (let loop ([r (preemit-input (car addr*) env)] [addr* (cdr addr*)]) (cond [(null? addr*) r] [else (loop (q-fmt "~a + (~a)" r (preemit-input (car addr*) env)) (cdr addr*))]))) (define (preemit-param p) (q-fmt "a_~a" p)) (define (build-ckind-back-end target-name int-size int-align pointer-size pointer-align op-emit-table op-type-table ld-type-table emit-load emit-store collect-outputs the-back-end extra-env extra-decl* extra-def* extra-postparam* extra-undef*) (define (ckind-emit qa0 env) (variant-case qa0 [qa0-top (decl*) (let loop ([decl* decl*]) (cond [(null? decl*)] [else (emit-decl (car decl*) env) (loop (cdr decl*))]))])) (define (emit-decl decl env) (variant-case decl [qa0-proc (attr* name arg-name* arg-type* arg-c-name* arg-c-type* code*) (emit-proc attr* name arg-name* arg-type* arg-c-name* arg-c-type* code* env)] [qa0-verbose (target* data*) (emit-verbose target-name target* data*)] [else #t])) (define (check-inputs! code* env) (define (chk-input*! input* env) (cond [(null? input*) env] [else (chk-input! (car input*) env) (chk-input*! (cdr input*) env)])) (define (chk-input! input env) (variant-case input [reg (name) (ce-lookup-x env 'back-end name "~a: register ~a is not defined" target-name name) env] [else env])) (walk-code* code* (lambda (env name attr* output* input*) (chk-input*! input* env)) ;; load (lambda (env type attr* output addr*) (chk-input*! addr* env)) ;; store (lambda (env type attr* addr* value) (chk-input*! addr* env) (chk-input! value env)) ;; loop (lambda (env attr* var low high) (chk-input! var env) (chk-input! low env) (chk-input! high env)) ;; if (lambda (env var) (chk-input! var env)) env)) (define (emit-proc-decl cl? rt attr* name arg-c-name* arg-c-type* env) (q-print "~a~%" (build-proc-type name attr* env)) (let* ([v (build-proc-name name attr* env)] [x (make-string (+ 1 (string-length v)) #\space)]) (q-print "~a" v) (if (null? arg-c-name*) (q-print "(void)~%") (begin (q-print "(") (let loop ([name* arg-c-name*] [type* arg-c-type*] [p ""]) (cond [(null? name*)] [else (q-print "~a~a ~a~a" p (car type*) (preemit-param (car name*)) (if (null? (cdr name*)) "" ",\n")) (loop (cdr name*) (cdr type*) x)])) (q-print ")~%"))))) (define (emit-variables env) (ce-for-each env (lambda (k v) (and (list? k) (eq? (car k) 'back-end))) (lambda (k v) (do-emit 1 "~a ~a;" (ce-lookup-x env 'name-of (cadr v) "~a type for ~a" target-name v) (car v))))) (define (emit-param* arg-name* arg-c-name* env) (do-emit 0 "") (let loop ([n* arg-name*] [c* arg-c-name*]) (cond [(null? n*)] [else (let* ([rn (ce-lookup-x env 'back-end (car n*) "~a name for ~a" target-name (car n*))] [rt (ce-lookup-x env 'name-of (cadr rn) "~a type for ~a" target-name (car n*))]) (do-emit 1 "~a = (~a)~a;" (car rn) rt (preemit-param (car c*))) (loop (cdr n*) (cdr c*)))]))) (define (emit-count level cf? counter f) (if (and cf? (not (zero? f))) (do-emit level "~a += ~a; /* count flops */" counter f))) (define (get-element r* f) (if (char-numeric? f) (q-fmt "~a" (list-ref r* (- (char->integer f) (char->integer #\0)))) (string f))) (define (do-emit-op level name out* in* outx* inx* in-count fmt flops more) (let loop ([r ""] [f* (string->list fmt)]) (cond [(null? f*) (do-emit level "~a; /* ~a */" r name) (+ flops more)] [(and (eq? (car f*) #\$) (not (null? (cdr f*)))) (loop (string-append r (get-element outx* (cadr f*))) (cddr f*))] [(and (eq? (car f*) #\%) (not (null? (cdr f*)))) (loop (string-append r (get-element inx* (cadr f*))) (cddr f*))] [else (loop (string-append r (string (car f*))) (cdr f*))]))) (define (emit-op level name attr* output* input* env f) (let ([in* (map (lambda (in) (preemit-input in env)) input*)] [out* (map (lambda (out) (preemit-output out env)) output*)]) (cond [(eq? name 'nop) (do-emit level "/* NOP: ~a */" (map qa0-attr->name attr*)) f] [(assq name op-emit-table) => (lambda (op) (let ([i-count (cadr op)] [fmt (caddr op)] [f-count (cadddr op)]) (do-emit-op level name output* input* out* in* i-count fmt f f-count)))] [else (ic-error 'qa0-ckind "UNKNOWN op ~a, out* ~a, in* ~a, attr* ~a" name output* input* attr*)]))) (define (emit-if level var true-code* false-code* env cf? counter f) (emit-count level cf? counter f) (do-emit level "if (~a) {" (preemit-input var env)) (emit-code* (+ level 1) true-code* env cf? counter 0) (if (not (null? false-code*)) (begin (do-emit level "} else {") (emit-code* (+ level 1) false-code* env cf? counter 0))) (do-emit level "}") 0) (define (emit-loop level var low high code* env cf? counter f) (let ([v (preemit-output var env)] [lo (preemit-input low env)] [hi (preemit-input high env)]) (cond [(null? code*) (do-emit level "~a = ~a; /* empty loop */" v hi) f] [else (emit-count level cf? counter f) (do-emit level "for (~a = ~a; ~a < ~a; ~a++) {" v lo v hi v) (emit-code* (+ level 1) code* env cf? counter 0) (do-emit level "}") 0]))) (define (emit-code level code env cf? counter f) (variant-case code [qa0-operation (name attr* output* input*) (emit-op level name attr* output* input* env f)] [qa0-load (type output addr*) (emit-load level type output addr* env f)] [qa0-store (type addr* value) (emit-store level type addr* value env f)] [qa0-if (var true-code* false-code*) (emit-if level var true-code* false-code* env cf? counter f)] [qa0-loop (var low high code*) (emit-loop level var low high code* env cf? counter f)])) (define (emit-code* level code* env cf? counter f) (cond [(null? code*) (emit-count level cf? counter f)] [else (let ([f (emit-code level (car code*) env cf? counter f)]) (emit-code* level (cdr code*) env cf? counter f))])) (define (emit-proc attr* name arg-name* arg-type* arg-c-name* arg-c-type* code* env) (let* ([env (C-collect-args arg-name* arg-type* ck-new-var env)] [env (collect-outputs code* env)] [cf? (attr-search attr* 'count-flops (lambda (v) #t) (lambda () #f))] [rv (attr-search attr* 'return (lambda (v*) v*) (lambda () #f))] [counter (ck-new-var)]) (check-inputs! code* env) (if (and cf? rv) (s-error "Both count-flops and return attributes in procedure ~a" name)) (emit-proc-decl cf? rv attr* name arg-c-name* arg-c-type* env) (do-emit 0 "{") (if cf? (do-emit 1 "size_t ~a = 0; /* flop counter */" counter)) (emit-variables env) (extra-decl* arg-name* arg-type* arg-c-name* arg-c-type* env) (emit-param* arg-name* arg-c-name* env) (extra-def* env) (extra-postparam* arg-name* arg-type* arg-c-name* arg-c-type* env) (emit-code* 1 code* env cf? counter 0) (extra-undef* env) (if cf? (do-emit 1 "return ~a;" counter)) (if rv (if (< (length rv) 1) (s-error "return without a name in ~a" name) (do-emit 1 "return ~a;" (preemit-output (make-reg (user-reg (car rv))) env)))) (do-emit 0 "}~%"))) (lambda (env) (let* ([env (machine-*-* int-size int-align pointer-size pointer-align env op-type-table ld-type-table)] [env (extra-env env)] [env (ce-bind env 'back-end the-back-end)] [env (ce-bind env 'be-emit ckind-emit)]) env)))
true
eb8027b8b0b3e742f76ce222c3a7499bb1c2cd63
c3523080a63c7e131d8b6e0994f82a3b9ed901ce
/algorithms.scm
2513f7088ec26af856a75aef1aefedb0e86719c4
[]
no_license
johnlawrenceaspden/hobby-code
2c77ffdc796e9fe863ae66e84d1e14851bf33d37
d411d21aa19fa889add9f32454915d9b68a61c03
refs/heads/master
2023-08-25T08:41:18.130545
2023-08-06T12:27:29
2023-08-06T12:27:29
377,510
6
4
null
2023-02-22T00:57:49
2009-11-18T19:57:01
Clojure
UTF-8
Scheme
false
false
5,166
scm
algorithms.scm
;; So today I want to talk about algorithms. ;; An algorithm is pretty much 'anything you can do with a computer', and so the study of algorithms is very important to computer science, and to the wider world. ;; I want to talk about the shape of computations in time and space ;; One of the simplest things we can compute is 'the number of ways of arranging some things' ;; How many ways can we arrange 3 things? ;; {a} ;; a ;; now add b, we can put it before a, or after a ;; ba ;; ab ;; now add c, we can put it before, in the middle, or at the end, and we can do that for each way of arranging two things ;; cba ;; bca ;; bac ;; cab ;; acb ;; abc ;; Does everyone know the factorial function? ;; n! = n * (n-1)! ;; 5! = 5 * 4! = 5 * 4 * 3! ... ;; Imagine we had a program for this: ;; (fact 0) ;-> 1 ;; (fact n) ;-> (* n (fact (- n 1)) ;; Can we write a program for this? (define fact (lambda (n) (if (= n 0) 1 (* n (fact (- n 1)))))) (fact 3) ;; Now the question is, what does the algorithm represented by our program look like as it executes? (fact 3) ((lambda (n) (if (= n 0) 1 (* n (fact (- n 1))))) 3) ; get function (if (= 3 0) 1 (* 3 (fact (- 3 1)))) ; argument substitution (if #f 1 (* 3 (fact (- 3 1)))) ; evaluate conditional (* 3 (fact (- 3 1))) ; choose branch (* 3 (fact 2)) ; subtract (* 3 ((lambda (n) (if (= n 0) 1 (* n (fact (- n 1))))) 2)) (* 3 (if (= 2 0) 1 (* 2 (fact (- 2 1))))) (* 3 (if #f 1 (* 2 (fact (- 2 1))))) (* 3 (* 2 (fact (- 2 1)))) (* 3 (* 2 (fact 1))) (* 3 (* 2 ((lambda (n) (if (= n 0) 1 (* n (fact (- n 1))))) 1))) (* 3 (* 2 (if (= 1 0) 1 (* 1 (fact (- 1 1)))))) (* 3 (* 2 (if #f 1 (* 1 (fact (- 1 1)))))) (* 3 (* 2 (* 1 (fact (- 1 1))))) (* 3 (* 2 (* 1 (fact 0)))) (* 3 (* 2 (* 1 ((lambda (n) (if (= n 0) 1 (* n (fact (- n 1))))) 0)))) (* 3 (* 2 (* 1 (if (= 0 0) 1 (* 0 (fact (- 0 1))))))) (* 3 (* 2 (* 1 (if #t 1 (* 0 (fact (- 0 1))))))) (* 3 (* 2 (* 1 1 ))) (* 3 (* 2 1)) (* 3 2) 6 ;; Now let's cut out some of the function call machinery, so that we can see a bit more clearly what's going on here: (fact 3) (* 3 (fact 2)) (* 3 (* 2 (fact 1))) (* 3 (* 2 (* 1 (fact 0)))) (* 3 (* 2 (* 1 1 ))) (* 3 (* 2 1)) (* 3 2) 6 ;; We have a process that grows, and then collapses. ;; How long is it from top to bottom? ;; How long is the longest line? ;; This is called a 'linear recursion' ;; Suppose instead we wanted to know the factorial of 30. How many ways are there of arranging 30 things? (fact 30) ;; We'd expect the execution to be 10 times as long, and the long list in the middle to be 10 times as long too. ;; (* 30 (* 29 (* 28 (* 27 (* 26 (* ......)))))) ;; Can anyone think of a different way to compute this number? ;; What would we do if we were trying to compute the factorial of 6 ourselves? ;; I'm not sure that I'd write down: (* 6 (* 5 (* 4 (* 3 (* 2 (* 1)))))) (* 6 (* 5 (* 4 (* 3 (* 2 1))))) (* 6 (* 5 (* 4 (* 3 2)))) (* 6 (* 5 (* 4 6))) (* 6 (* 5 24)) (* 6 120) (* 720) ;; I'd go ;; 1: 1 ;; 2: 2 ;; 3: 6 ;; 4: 24 ;; 5: 120 ;; 6: 720 ;; Can we make a computation that works like that? (define fact-iter (lambda (n count total) (if (= count n) total (fact-iter n (+ 1 count) (* count total))))) (fact-iter 6 1 1) ((lambda (n count total) (if (= count n) total (fact-iter n (+ 1 count) (* count total)))) 6 1 1) (if (= 1 6) 1 (fact-iter 6 (+ 1 1) (* 1 1))) (if #f 1 (fact-iter 6 (+ 1 1) (* 1 1))) (fact-iter 6 (+ 1 1) (* 1 1)) (fact-iter 6 2 1) ((lambda (n count total) (if (= count n) total (fact-iter n (+ 1 count) (* count total)))) 6 2 1) (if (= 2 6) 1 (fact-iter 6 (+ 1 2) (* 2 1))) (if #f 1 (fact-iter 6 (+ 1 2) (* 2 1))) (fact-iter 6 (+ 1 2) (* 2 1)) (fact-iter 6 3 2) ;; and so on (fact-iter 6 1 1) (fact-iter 6 2 1) (fact-iter 6 3 2) (fact-iter 6 4 6) (fact-iter 6 5 24) (fact-iter 6 6 120) 720 ;; In this version, the computation doesn't grow. There are always three numbers every time we get to the function call. ;; This pattern is called an iteration ;; Or maybe ;; 6 1 ;; 5 6 ;; 4 30 ;; 3 120 ;; 2 360 ;; 1 720 ;; 720 (define (fact-iter n total) (if (= n 1) total (fact-iter (- n 1) (* n total)))) (define (factorial n) (fact-iter n 1)) FUNCTION factorial(n) total = 1 count = 1 WHILE (count <= n) total = total*count count = count + 1 END RETURN total END int factorial (int n) { int count; int total; for (count=1, total=1; count <=n ; count ++) { total = count*total; } return total; } (define (fact-iter n count total) (if (= count n) total (fact-iter n (+ 1 count) (* count total)))) (define (factorial n) (fact-iter n 1 1)) FUNCTION factorial (n) total = 1 FOR count = 1 to n total = count * total NEXT count RETURN total END (reduce * (range 1 (inc n))) int factorial-iter (int n, int count, int total) { if (count < n) { return factorial-iter (n, count + 1, total * count); } else { return total; } } int factorial (int n) { return factorial-iter (n, 1, 1); }
false
5babbd255455a0c12dc7aa27028e4f2b022685a0
4a1ff5a0f674ff41bd384301ab82b3197f5ca0c8
/problems/0026/main.scm
9abe1267bef90498d68a1535951d76b78d596724
[]
no_license
MiyamonY/yukicoder
e0a323d68c4d3b41bdb42fb3ed6ab105619ca7e9
1bb8882ac76cc302428ab0417f90cfa94f7380c8
refs/heads/master
2020-05-09T12:13:31.627382
2019-10-06T17:01:45
2019-10-06T17:01:45
181,105,911
0
0
null
null
null
null
UTF-8
Scheme
false
false
392
scm
main.scm
(define (read-number) (string->number (read-line))) (let ((n (read-number)) (_ (read-number))) (let loop ((line (read-line))) (cond ((eof-object? line) (print n)) (else (let ((tokens (map string->number (string-split line #\space)))) (cond ((= n (car tokens)) (set! n (cadr tokens))) ((= n (cadr tokens)) (set! n (car tokens)))) (loop (read-line)))))))
false
a767b1ba11439a72c9a93ceb2b4618cfaf4ea3ff
958488bc7f3c2044206e0358e56d7690b6ae696c
/scheme/evaluator/tagged-list.scm
24bce50ff04edab6f5f1b8e97cb65fe7a3a41d55
[]
no_license
possientis/Prog
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
d4b3debc37610a88e0dac3ac5914903604fd1d1f
refs/heads/master
2023-08-17T09:15:17.723600
2023-08-11T12:32:59
2023-08-11T12:32:59
40,361,602
3
0
null
2023-03-27T05:53:58
2015-08-07T13:24:19
Coq
UTF-8
Scheme
false
false
393
scm
tagged-list.scm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; include guard ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (if (not (defined? included-tagged-list)) (begin (define included-tagged-list #f) (display "loading tagged-list")(newline) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (tagged-list? exp tag) (if (pair? exp) (eq? (car exp) tag) #f)) )) ; include guard
false
1116b4151b7ca44e97b1f4db2806f4a136593f81
4bba82967988e9a4d87994a65742e2c59bc414f8
/test2.scm
156150178ce29fb47d1f62ba8c564dcb1ac44598
[]
no_license
haramako/cslisp
e1cd4c52a8e6c87fd585d795e8ad01ab48a8c0ec
e5a94884d45c1b9d7c397df247a93003c66a9ee3
refs/heads/master
2021-06-24T05:28:02.531342
2021-04-17T01:39:36
2021-04-17T01:39:36
219,874,404
0
0
null
null
null
null
UTF-8
Scheme
false
false
178
scm
test2.scm
(%load "macrotest.scm") (%load "lib/prelude.scm") (define-syntax test-syntax (syntax-rules () ((_ x) (puts x)) ((_ x y) (puts x y)))) (test-syntax 1) (test-syntax 1 2)
true
dba8e005918db2e53c091162543c08ff84e79edb
74d2f4ec77852839450ab8563971a5e0f615c019
/chapter_02/chapter_2_5/test.scm
4d4efbe6cf9083a7ffab91adfd6ab70311c26a1c
[]
no_license
wangoasis/sicp
b56960a0c3202ce987f176507b1043ed632ed6b3
07eaf8d46f7b8eae5a46d338a4608d8e993d4568
refs/heads/master
2021-01-21T13:03:11.520829
2016-04-22T13:52:15
2016-04-22T13:52:15
53,835,426
0
0
null
null
null
null
UTF-8
Scheme
false
false
581
scm
test.scm
( load "table-get-put.scm" ) ( load "scheme-number-package.scm" ) ( load "rational-package.scm" ) ( load "generic-rec-polar.scm" ) ( load "complex-package.scm" ) ( load "generic-op.scm" ) ( install-rectangular-package ) ( install-polar-package ) ( install-complex-package ) ( install-scheme-number-package ) ( install-rational-package ) ( define x ( make-complex-from-real-imag 4 3 ) ) ( define y ( make-scheme-number 5 ) ) ( define z ( make-rational 4 7 ) ) ( define x2 ( make-complex-from-real-imag 4 6 ) ) ( define z2 ( make-rational 3 7 ) ) ( define main ( magnitude-1 x ) )
false
f2d54301a949fab867e303c163768c504084d8cf
53cb8287b8b44063adcfbd02f9736b109e54f001
/top/phases.scm
706c54114b92cc9748d58639feb9ab6a6d63825c
[]
no_license
fiddlerwoaroof/yale-haskell-reboot
72aa8fcd2ab7346a4990795621b258651c6d6c39
339b7d85e940db0b8cb81759e44abbb254c54aad
refs/heads/master
2021-06-22T10:32:25.076594
2020-10-30T00:00:31
2020-10-30T00:00:31
92,361,235
3
0
null
null
null
null
UTF-8
Scheme
false
false
6,080
scm
phases.scm
;;; This is the top-level phase structure of the compiler. ;;; Compilation phase support (define *phase* '#f) (define *abort-phase* '#f) ; abort when this phase completes (define *abort-compilation* (lambda () (error "No error continuation defined here!"))) (define *module-asts* '()) ; a global only for debugging purposes ;;; Later add the printing and timing stuff here (define-local-syntax (phase-body phase-name body printer) `(dynamic-let ((*phase* ',phase-name)) (when (memq ',phase-name (dynamic *printers*)) (format '#t "~%Phase ~a:~%" ',phase-name) (force-output)) (let* ((phase-start-time (get-run-time)) (result ,body) (current-time (get-run-time))) (when (eq? (dynamic *abort-phase*) ',phase-name) (abort-compilation)) ,@(if (eq? printer '#f) '() `((when (memq ',phase-name (dynamic *printers*)) (funcall ,printer result) (force-output)))) (when (memq 'phase-time *printers*) (let ((elapsed-time (- current-time phase-start-time))) (format '#t "~&~A complete: ~A seconds~%" ',phase-name elapsed-time) (force-output))) result))) ;;; Returns 2 values: module ast's and lisp code. (define (compile-haskell-files files) (dynamic-let ((*abort-phase* '#f)) (let ((all-mods (haskell-parse-files files)) (interface-mods '()) (regular-mods '())) (dolist (m all-mods) (if (eq? (module-type m) 'interface) (push m interface-mods) (push m regular-mods))) (dynamic-let ((*unit* (module-name (car all-mods)))) (values all-mods `(begin ,(if interface-mods (compile-interface-modules (nreverse interface-mods)) '#f) ,(if regular-mods (compile-modules (nreverse regular-mods)) '#f)) ))))) (define (compile-modules mods) (dynamic-let ((*context* '#f) (*recoverable-error-handler* '#f) (*abort-phase* '#f) (*unique-name-counter* 1) (*suffix-table* (make-table))) (haskell-import-export mods '#f) (haskell-process-type-declarations mods) (haskell-scope mods) (let ((big-let (haskell-dependency-analysis mods))) (cond ((not (void? big-let)) (haskell-type-check big-let mods) (setf big-let (haskell-cfn big-let)) (setf big-let (haskell-dependency-reanalysis big-let)) (setf big-let (haskell-ast-to-flic big-let)) (setf big-let (haskell-optimize big-let)) (setf big-let (haskell-strictness big-let)) (haskell-codegen big-let mods)) (else ''#f) )))) (define (modules->lisp-code modules) (dynamic-let ((*unit* (module-name (car modules)))) (compile-modules modules))) (predefine (notify-error)) ; in command-interface/command-utils.scm (define (abort-compilation) (notify-error) (funcall (dynamic *abort-compilation*))) (define (halt-compilation) (setf (dynamic *abort-phase*) (dynamic *phase*))) ;;; Here are the actual phase bodies (predefine (parse-files files)) (define (haskell-parse-files filenames) (phase-body parse (let ((mods (parse-files filenames))) mods) #f)) (predefine (import-export modules)) ; in import-export/import-export.scm (predefine (import-export/interface modules)) (define (haskell-import-export modules interface?) (phase-body import (if interface? (import-export/interface modules) (import-export modules)) #f)) (predefine (process-type-declarations modules)) ; in tdecl/type-declaration-analysis.scm (define (haskell-process-type-declarations modules) (phase-body type-decl (begin (process-type-declarations modules)) #f)) (predefine (scope-modules x)) ; in prec/scope.scm (predefine (print-full-module x . maybe-stream)) ; in the printers (define (haskell-scope modules) (phase-body scope (scope-modules modules) (lambda (result) (declare (ignore result)) (dolist (m modules) (print-full-module m))) )) (predefine (do-dependency-analysis x)) ; in depend/dependency-analysis.scm (define (haskell-dependency-analysis modules) (phase-body depend (do-dependency-analysis modules) (function pprint*))) (predefine (do-haskell-type-check big-let mods)) (define (haskell-type-check big-let modules) (phase-body type (do-haskell-type-check big-let modules) #f)) (predefine (cfn-ast x)) ; in cfn/main.scm (define (haskell-cfn big-let) (phase-body cfn (cfn-ast big-let) (function pprint*))) (predefine (analyze-dependency-top x)) ; in depend/dependency-analysis.scm (define (haskell-dependency-reanalysis big-let) (phase-body depend2 (begin (analyze-dependency-top big-let) big-let) (function pprint*))) (predefine (ast-to-flic x)) ; in flic/ast-to-flic.scm (define (haskell-ast-to-flic big-let) (phase-body flic (ast-to-flic big-let) (function pprint*))) (predefine (optimize-top x)) ; in backend/optimize.scm (define (haskell-optimize big-let) (phase-body optimize (optimize-top big-let) (function pprint*))) (predefine (strictness-analysis-top x)) ; in backend/strictness.scm (predefine (strictness-analysis-printer x)) (define (haskell-strictness big-let) (phase-body strictness (strictness-analysis-top big-let) (function strictness-analysis-printer))) (predefine (codegen-top x)) ; in backend/codegen.scm (predefine (codegen-exported-types x)) ; " (predefine (codegen-prim-entries x)) ; ditto (define (haskell-codegen big-let mods) (phase-body codegen `(begin ,(codegen-exported-types mods) ,(codegen-top big-let)) #f)) ;;; This is for interface modules. (predefine (haskell-codegen/interface mods)) (define (compile-interface-modules mods) (dynamic-let ((*context* '#f) (*recoverable-error-handler* '#f) (*abort-phase* '#f)) (haskell-import-export mods '#t) (haskell-process-type-declarations mods) (haskell-scope mods) (haskell-codegen/interface mods)))
false
7877f7be86ac9d7db336968191ce4d50005570e4
784dc416df1855cfc41e9efb69637c19a08dca68
/src/lang/scheme/process-context-impl.ss
2e43f01add08f5787beae0bcd1c44f81cbe1e9a0
[ "LGPL-2.1-only", "Apache-2.0", "LGPL-2.1-or-later" ]
permissive
danielsz/gerbil
3597284aa0905b35fe17f105cde04cbb79f1eec1
e20e839e22746175f0473e7414135cec927e10b2
refs/heads/master
2021-01-25T09:44:28.876814
2018-03-26T21:59:32
2018-03-26T21:59:32
123,315,616
0
0
Apache-2.0
2018-02-28T17:02:28
2018-02-28T17:02:28
null
UTF-8
Scheme
false
false
1,425
ss
process-context-impl.ss
;;; -*- Gerbil -*- ;;; (C) vyzo at hackzen.org ;;; R7RS (scheme process-context) library -- implementation details package: scheme (export #t) (def (get-environment-variable var) (getenv var #f)) (begin-foreign (c-declare #<<END-C #include <unistd.h> extern char **environ; static int ffi_count_envvars () { int x; char **env; for (env = environ; *env; ++env) ++x; return x; } static char *ffi_get_envvar (int x) { return environ[x]; } END-C ) (define-macro (define-c-lambda id args ret #!optional (name #f)) (let ((name (or name (##symbol->string id)))) `(define ,id (c-lambda ,args ,ret ,name)))) (define-c-lambda scheme/process-context-impl#count-envvars () int "ffi_count_envvars") (define-c-lambda scheme/process-context-impl#get-envvar (int) char-string "ffi_get_envvar") (define-c-lambda scheme/process-context-impl#_exit (int) void "_exit") ) (extern count-envvars get-envvar _exit) (def (get-environment-variables) (def (envvar str) (let (ix (string-index str #\=)) (cons (substring str 0 ix) (substring str (fx1+ ix) (string-length str))))) (let (count (count-envvars)) (let lp ((x 0) (vars [])) (if (fx< x count) (lp (fx1+ x) (cons (envvar (get-envvar x)) vars)) (reverse vars))))) (def (r7rs-exit (normally? #t)) (exit (if normally? 0 1))) (def (emergency-exit (normally? #t)) (_exit (if normally? 0 1)))
false
48f40f3480c0ef851b888fce439fcf60950945de
c2629a29a7cb2113987dc24e8a1fa8ba12ec92ae
/ssa-types.scm
2841aea17027e2134d7dcd7c1962b9efaf2bac34
[]
no_license
hellcoderz/scheme-compiler
e5b848e2d48cb44a1e7d6bc1a92cd8311e523229
c7b7649e9d0d3fb47e93ca40c1976b5d2a1e2962
refs/heads/master
2020-04-07T18:37:40.419648
2010-10-22T21:57:36
2010-10-22T21:57:36
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,383
scm
ssa-types.scm
(declare (unit ssa-types) (uses utils)) (use matchable) (use srfi-69) (include "struct-syntax") (define-struct ssa-type (code width points-to-type return-type param-types)) (define *ssa-type-codes* '(void label integer pointer function)) ;; raw type constructors (define (ssa-make-type-void) (make-ssa-type 'void '() '() '() '())) (define (ssa-make-type-label) (make-ssa-type 'label '() '() '() '())) (define (ssa-make-type-integer width) (make-ssa-type 'integer width '() '() '())) (define (ssa-make-type-pointer points-to-type) (make-ssa-type 'pointer '() points-to-type '() '())) (define (ssa-make-type-function return-type param-types) (make-ssa-type 'function '() '() return-type param-types)) ;; singleton constructors ;; core types (define <ssa-void> (ssa-make-type-void)) (define <ssa-i1> (ssa-make-type-integer 1)) (define <ssa-i8> (ssa-make-type-integer 8)) (define <ssa-i16> (ssa-make-type-integer 16)) (define <ssa-i32> (ssa-make-type-integer 32)) (define <ssa-i64> (ssa-make-type-integer 64)) (define <ssa-ptr-i32> (ssa-make-type-pointer <ssa-i32>)) (define <ssa-ptr-i64> (ssa-make-type-pointer <ssa-i64>)) (define <ssa-label> (ssa-make-type-label)) (define (ssa-type-void-get) <ssa-void>) (define (ssa-type-label-get) <ssa-label>) (define (ssa-type-integer-get width) (case width ((1) <ssa-i1>) ((8) <ssa-i8>) ((16) <ssa-i16>) ((32) <ssa-i32>) ((64) <ssa-i64>) (else (error 'ssa-type-integer-get "unsupported integer width" width)))) (define *ssa-pointers* '()) ;; 0800 99 01 23 / 800 654 25 93 (define (ssa-type-pointer-get points-to-type) (cond ((assq points-to-type *ssa-pointers*) => cdr) (else (let ((type (ssa-make-type-pointer points-to-type))) (set! *ssa-pointers* (cons (cons points-to-type type) *ssa-pointers*)) type)))) (define *ssa-functions* '()) (define (ssa-type-function-get return-type param-types) (define (func-equal? record) (match record (((rt pt) . _) (and (eq? rt return-type) (lset= eq? pt param-types) (= (length pt) (length param-types)))))) (define (add-record! rt pt type) (let ((record (cons (list return-type param-types) type))) (set! *ssa-functions* (cons record *ssa-functions*)) type)) (cond ((find func-equal? *ssa-functions*) => cdr) (else (let ((type (ssa-make-type-function return-type param-types))) (add-record! return-type param-types type))))) ;; type accessors (define (ssa-type-integer-width x) (ssa-type-width x)) (define (ssa-type-pointer-points-to-type x) (ssa-type-points-to-type x)) (define (ssa-type-function-return-type x) (ssa-type-return-type x)) (define (ssa-type-function-param-types x) (ssa-type-param-types x)) (define (ssa-type-function-pointer-return-type x) (ssa-type-function-return-type (ssa-type-pointer-points-to-type x))) (define (ssa-type-function-pointer-param-types x) (ssa-type-function-param-types (ssa-type-pointer-points-to-type x))) ;; type predicates (define (ssa-type-code? x code) (eq? (ssa-type-code x) code)) (define (ssa-type-integer? x) (ssa-type-code? x 'integer)) (define (ssa-type-pointer? x) (ssa-type-code? x 'pointer)) (define (ssa-type-void? x) (ssa-type-code? x 'void)) (define (ssa-type-label? x) (ssa-type-code? x 'label)) (define (ssa-type-function? x) (ssa-type-code? x 'function)) (define (ssa-type-function-pointer? x) (and (ssa-type-pointer? x) (ssa-type-function? (ssa-type-pointer-points-to-type x)))) ;; formatting (define (ssa-format-type x) (cond ((ssa-type-void? x) "void") ((ssa-type-integer? x) (case (ssa-type-integer-width x) ((1) "i1") ((8) "i8") ((16) "i16") ((32) "i32") ((64) "i64"))) ((ssa-type-label? x) "label") ((ssa-type-function? x) (sprintf "~a (~a)" (ssa-format-type (ssa-type-function-return-type x)) (string-join (map (lambda (type) (ssa-format-type type)) (ssa-type-function-param-types x)) ", "))) ((ssa-type-pointer? x) (format "~a*" (ssa-format-type (ssa-type-pointer-points-to-type x)))) (else (assert-not-reached 'ssa-format-type x))))
false
b4b0d0e17bfffd0e8696b700547ad3cc03cfe367
d881dacf2327ecd474f11318ea8e2b9536fe3e73
/srfi-tools/data.sld
724ec6a23ca902211e26a6f2d7e54ab200d825d9
[ "MIT" ]
permissive
scheme-requests-for-implementation/srfi-common
a84c7eaa6a40a4d1b80ef723759c2d3aed480177
78b45ab8028cfbd462fb1231cafec4ff4c5c5d30
refs/heads/master
2023-07-19T23:14:26.615668
2023-07-14T18:03:06
2023-07-14T18:03:06
37,961,335
31
7
MIT
2023-05-11T13:57:14
2015-06-24T04:00:50
HTML
UTF-8
Scheme
false
false
1,992
sld
data.sld
(define-library (srfi-tools data) (export srfi-format-keyword srfi-available-keywords srfi-keyword-alist srfi-by-number srfi-last-number srfi-number srfi-status srfi-status-string srfi-status->name srfi-title srfi-authors srfi-based-on srfi-see-also srfi-keywords srfi-library-name srfi-done-date srfi-draft-date srfi-draft? srfi-final? srfi-date-of-last-update srfi-date-to-show srfi-author-first-name srfi-author-name srfi-author-role srfi-format-author srfi-format-authors/first-names srfi-format-authors srfi-format srfi-data srfi-list srfi-range srfi-near srfi-age-in-days srfi-drafts srfi-by-author srfi-by-keyword srfi-search try-parse-srfi-number parse-srfi-number write-string-about-srfi write-line-about-srfi keyword->name write-custom-srfi-list write-srfi-list) (import (scheme base) (scheme case-lambda) (scheme char) (scheme cxr) (scheme read) (srfi-tools private error) (srfi-tools private list) (srfi-tools private format) (srfi-tools private string) (srfi-tools private port) (srfi-tools private file) (srfi-tools private time) (srfi-tools private command) (srfi-tools core) (srfi-tools path)) (include "data.scm") (cond-expand (mit (begin (set-record-type-unparser-method! srfi (standard-unparser-method 'srfi (lambda (srfi port) (write-string " #" port) (write (srfi-number srfi) port) (write-char #\space port) (write (srfi-title srfi) port)))))) (else)))
false
85776b9c9296533cf11d4d10c40bad9b20ec776b
f08220a13ec5095557a3132d563a152e718c412f
/logrotate/skel/usr/share/guile/2.0/system/vm/trace.scm
e27dc37843f02c06e4f4a983d6a738b0d616b8e2
[ "Apache-2.0" ]
permissive
sroettger/35c3ctf_chals
f9808c060da8bf2731e98b559babd4bf698244ac
3d64486e6adddb3a3f3d2c041242b88b50abdb8d
refs/heads/master
2020-04-16T07:02:50.739155
2020-01-15T13:50:29
2020-01-15T13:50:29
165,371,623
15
5
Apache-2.0
2020-01-18T11:19:05
2019-01-12T09:47:33
Python
UTF-8
Scheme
false
false
5,476
scm
trace.scm
;;; Guile VM tracer ;; Copyright (C) 2001, 2009, 2010, 2013 Free Software Foundation, Inc. ;;; This library is free software; you can redistribute it and/or ;;; modify it under the terms of the GNU Lesser General Public ;;; License as published by the Free Software Foundation; either ;;; version 3 of the License, or (at your option) any later version. ;;; ;;; This library is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;; Lesser General Public License for more details. ;;; ;;; You should have received a copy of the GNU Lesser General Public ;;; License along with this library; if not, write to the Free Software ;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ;;; Code: (define-module (system vm trace) #:use-module (system base syntax) #:use-module (system vm vm) #:use-module (system vm frame) #:use-module (system vm program) #:use-module (system vm objcode) #:use-module (system vm traps) #:use-module (rnrs bytevectors) #:use-module (system vm instruction) #:use-module (ice-9 format) #:export (trace-calls-in-procedure trace-calls-to-procedure trace-instructions-in-procedure call-with-trace)) ;; FIXME: this constant needs to go in system vm objcode (define *objcode-header-len* 8) (define (build-prefix prefix depth infix numeric-format max-indent) (let lp ((indent "") (n 0)) (cond ((= n depth) (string-append prefix indent)) ((< (+ (string-length indent) (string-length infix)) max-indent) (lp (string-append indent infix) (1+ n))) (else (string-append prefix indent (format #f numeric-format depth)))))) (define (print-application frame depth width prefix max-indent) (let ((prefix (build-prefix prefix depth "| " "~d> " max-indent))) (format (current-error-port) "~a~v:@y\n" prefix width (frame-call-representation frame)))) (define* (print-return frame depth width prefix max-indent) (let* ((len (frame-num-locals frame)) (nvalues (frame-local-ref frame (1- len))) (prefix (build-prefix prefix depth "| " "~d< "max-indent))) (case nvalues ((0) (format (current-error-port) "~ano values\n" prefix)) ((1) (format (current-error-port) "~a~v:@y\n" prefix width (frame-local-ref frame (- len 2)))) (else ;; this should work, but there appears to be a bug ;; "~a~d values:~:{ ~v:@y~}\n" (format (current-error-port) "~a~d values:~{ ~a~}\n" prefix nvalues (map (lambda (val) (format #f "~v:@y" width val)) (frame-return-values frame))))))) (define* (trace-calls-to-procedure proc #:key (width 80) (vm (the-vm)) (prefix "trace: ") (max-indent (- width 40))) (define (apply-handler frame depth) (print-application frame depth width prefix max-indent)) (define (return-handler frame depth) (print-return frame depth width prefix max-indent)) (trap-calls-to-procedure proc apply-handler return-handler #:vm vm)) (define* (trace-calls-in-procedure proc #:key (width 80) (vm (the-vm)) (prefix "trace: ") (max-indent (- width 40))) (define (apply-handler frame depth) (print-application frame depth width prefix max-indent)) (define (return-handler frame depth) (print-return frame depth width prefix max-indent)) (trap-calls-in-dynamic-extent proc apply-handler return-handler #:vm vm)) (define* (trace-instructions-in-procedure proc #:key (width 80) (vm (the-vm)) (max-indent (- width 40))) (define (trace-next frame) (let* ((ip (frame-instruction-pointer frame)) (objcode (program-objcode (frame-procedure frame))) (opcode (bytevector-u8-ref (objcode->bytecode objcode) (+ ip *objcode-header-len*)))) (format #t "~8d: ~a\n" ip (opcode->instruction opcode)))) (trap-instructions-in-dynamic-extent proc trace-next #:vm vm)) ;; Note that because this procedure manipulates the VM trace level ;; directly, it doesn't compose well with traps at the REPL. ;; (define* (call-with-trace thunk #:key (calls? #t) (instructions? #f) (width 80) (vm (the-vm)) (max-indent (- width 40))) (let ((call-trap #f) (inst-trap #f)) (dynamic-wind (lambda () (if calls? (set! call-trap (trace-calls-in-procedure thunk #:vm vm #:width width #:max-indent max-indent))) (if instructions? (set! inst-trap (trace-instructions-in-procedure thunk #:vm vm #:width width #:max-indent max-indent))) (set-vm-trace-level! vm (1+ (vm-trace-level vm)))) thunk (lambda () (set-vm-trace-level! vm (1- (vm-trace-level vm))) (if call-trap (call-trap)) (if inst-trap (inst-trap)) (set! call-trap #f) (set! inst-trap #f)))))
false
e1fb4df50b9e11da2b1da5ec56df019dab5094bb
0768e217ef0b48b149e5c9b87f41d772cd9917f1
/heap/boot/eval.scm
604338ecdbc439ef478bef4a9a8784b19201d3b8
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
fujita-y/ypsilon
e45c897436e333cf1a1009e13bfef72c3fb3cbe9
62e73643a4fe87458ae100e170bf4721d7a6dd16
refs/heads/master
2023-09-05T00:06:06.525714
2023-01-25T03:56:13
2023-01-25T04:02:59
41,003,666
45
7
BSD-2-Clause
2022-06-25T05:44:49
2015-08-19T00:05:35
Scheme
UTF-8
Scheme
false
false
27,996
scm
eval.scm
;;; Copyright (c) 2004-2022 Yoshikatsu Fujita / LittleWing Company Limited. ;;; See LICENSE file for terms and conditions of use. (define auto-compile-cache-validation-signature (string->symbol (format "ypsilon-~a.~a.~a" (architecture-feature 'program-version-major) (architecture-feature 'program-version-minor) (architecture-feature 'program-revision)))) (define auto-compile-cache-lock-path (lambda () (and (auto-compile-cache) (format "~a/ypsilon-auto-compile-cache.lock" (auto-compile-cache))))) (define auto-compile-verbose (make-parameter #f)) (define scheme-load-verbose (make-parameter #f)) (define scheme-load-paths (make-parameter '())) (define library-contains-implicit-main (make-parameter #t)) (define library-include-dependencies (make-core-hashtable)) (define current-include-files (make-parameter #f)) (define current-library-name (make-parameter #f)) (define track-file-open-operation (lambda (path) (and (current-include-files) (core-hashtable-set! (current-include-files) path #t)))) (define library-extensions (make-parameter (list ".ypsilon.sld" ".ypsilon.sls" ".ypsilon.ss" ".ypsilon.scm" ".sld" ".sls" ".ss" ".scm") (lambda (value) (if (and (list? value) (every1 string? value)) value (assertion-violation 'library-extensions (format "expected list of strings, but got ~s" value)))))) (define auto-compile-cache (make-parameter #f (lambda (p) (cond ((not p) p) ((and (string? p) (file-exists? (format "~//." p))) (format "~/" p)) (else (format (current-error-port) "~&;; warning in auto-compile-cache: directory ~s not exist (temporary disable caching)~!~%" p) #f))))) (define core-eval (lambda (form) (parameterize ((backtrace #f)) (interpret-coreform form)))) (define compile (lambda (form) (parameterize ((current-closure-comments (make-core-hashtable))) (compile-coreform (macro-expand form))))) (define interpret (lambda (form) (let ((code (parameterize ((current-closure-comments (make-core-hashtable))) (compile-coreform (macro-expand form))))) (run-vmi (cons '(1 . 0) code))))) (define interpret-coreform (lambda (form) (let ((code (cons '(1 . 0) (compile-coreform form)))) (run-vmi code)))) (define environment (lambda ref (parse-imports `(environment ,@ref) ref) (tuple 'type:eval-environment `,ref))) (define eval-enclosure-library `(,(string->symbol (format "library-~a" (make-uuid))))) (define eval-enclosure-result (string->symbol (format "result-~a" (make-uuid)))) (define eval-enclosure-quote (string->symbol (format "quote-~a" (make-uuid)))) (define eval-enclosure-set-top-level-value! (string->symbol (format "set-top-level-value!-~a" (make-uuid)))) (define eval (lambda (expr env) (cond ((environment? env) (parameterize ((current-environment env)) (interpret expr))) (else (or (eq? (tuple-ref env 0) 'type:eval-environment) (assertion-violation 'eval (format "expected environment, but got ~r, as argument 2" env))) (interpret `(begin (library ,eval-enclosure-library (export) (import (rename (only (core primitives) set-top-level-value! quote) (quote ,eval-enclosure-quote) (set-top-level-value! ,eval-enclosure-set-top-level-value!) ) ,@(tuple-ref env 1)) (,eval-enclosure-set-top-level-value! (,eval-enclosure-quote ,eval-enclosure-result) ,expr)) (let ((result ,eval-enclosure-result)) (|.set-top-level-value!| ',eval-enclosure-result |.&UNDEF|) (|.unintern-scheme-library| ',(generate-library-id eval-enclosure-library)) result))))))) (define expand-path (lambda (path) (let ((special (and (> (string-length path) 1) (memq (string-ref path 1) '(#\/ #\\))))) (cond ((and special (home-directory) (char=? (string-ref path 0) #\~)) (format "~a~/" (home-directory) (substring path 1 (string-length path)))) ((and special (char=? (string-ref path 0) #\.)) (format "~a~/" (current-directory) (substring path 1 (string-length path)))) ((string=? path ".") (format "~/" (current-directory))) ((and (home-directory) (string=? path "~")) (format "~/" (home-directory))) (else (format "~/" path)))))) (define locate-file (lambda (path form) (define path-not-found (lambda (path) (assertion-violation form (format "~a~/~a not found" #\" path #\")))) (define confirm-path (lambda (path) (and (file-exists? path) path))) (cond ((= (string-length path) 0) (path-not-found path)) ((or (string-contains path ":") (memq (string-ref path 0) '(#\/ #\\))) (or (confirm-path path) (path-not-found path))) ((memq (string-ref path 0) '(#\. #\~)) (or (confirm-path (expand-path path)) (path-not-found path))) ((any1 (lambda (e) (confirm-path (expand-path (string-append e "/" path)))) (cons "." (scheme-load-paths)))) (else (path-not-found path))))) (define locate-load-file (lambda (path) (locate-file path 'load))) (define load-file-has-r6rs-comment? (lambda (path) (parameterize ((lexical-syntax-version 7) (mutable-literals #f)) (let ((port (open-script-input-port (locate-load-file path)))) (core-read port #f 'load) (close-port port) (= (lexical-syntax-version) 6))))) (define load (lambda (path . env) (or (null? env) (null? (cdr env)) (assertion-violation 'load "wrong number of arguments" (cons path env))) (or (null? env) (environment? (car env)) (eq? (tuple-ref (car env) 0) 'type:eval-environment) (assertion-violation 'load (format "expected environment, but got ~r, as argument 2" (car env)))) (let ((abs-path (locate-load-file path))) (and (scheme-load-verbose) (format #t "~&;; loading ~s~%~!" abs-path)) (let ((port (open-script-input-port abs-path))) (with-exception-handler (lambda (c) (cond ((serious-condition? c) (close-port port) (raise c)) (else (raise-continuable c)))) (lambda () (parameterize ((current-source-comments (current-source-comments)) (current-temporaries (current-temporaries)) (current-environment (current-environment)) (lexical-syntax-version (lexical-syntax-version)) (mutable-literals (mutable-literals)) (backtrace (backtrace))) (current-temporaries (make-core-hashtable 'string=?)) (current-rename-count 0) (cond ((or (null? env) (environment? (car env))) (let loop ((acc '())) (let ((form (core-read port (current-source-comments) 'load))) (cond ((eof-object? form) (close-port port) (interpret (cons 'begin (reverse acc)))) (else (loop (cons form acc))))))) (else (let loop ((acc '())) (let ((form (core-read port (current-source-comments) 'load))) (cond ((eof-object? form) (close-port port) (eval (cons 'begin (reverse acc)) (car env))) (else (loop (cons form acc))))))))))))))) (define load-top-level-program (lambda (path) (let ((abs-path (locate-load-file path))) (and (scheme-load-verbose) (format #t "~&;; loading ~s~%~!" abs-path)) (let ((port (open-script-input-port abs-path))) (with-exception-handler (lambda (c) (cond ((serious-condition? c) (close-port port) (raise c)) (else (raise-continuable c)))) (lambda () (parameterize ((current-source-comments (current-source-comments)) (current-temporaries (current-temporaries)) (current-environment (current-environment)) (lexical-syntax-version (lexical-syntax-version)) (mutable-literals (mutable-literals)) (backtrace (backtrace))) (current-source-comments (and (backtrace) (make-core-hashtable))) (current-temporaries (make-core-hashtable 'string=?)) (current-rename-count 0) (let loop ((acc '())) (let ((form (core-read port (current-source-comments) 'load))) (cond ((eof-object? form) (close-port port) (let ((program (expand-top-level-program (reverse acc) '()))) (current-macro-expression #f) (interpret program))) (else (loop (cons form acc))))))))))))) (define encode-library-ref (lambda (library-name) (map (lambda (s) (let ((utf8 (string->utf8 (if (symbol? s) (symbol->string s) (number->string s))))) (let ((buf (make-string-output-port)) (end (bytevector-length utf8))) (let loop ((i 0)) (if (= i end) (string->symbol (extract-accumulated-string buf)) (let ((c (bytevector-u8-ref utf8 i))) (cond ((or (and (> c 96) (< c 123)) (and (> c 47) (< c 58)) (and (> c 64) (< c 91)) (= c 43) (= c 45) (= c 95)) (put-byte buf c) (loop (+ i 1))) (else (format buf "%~x~x" (div c 16) (mod c 16)) (loop (+ i 1)))))))))) library-name))) (define locate-include-file (lambda (library-name path who) (if library-name (let ((subdir (destructuring-match library-name ((_) "") ((base ... _) (id-list->string base "/"))))) (or (any1 (lambda (base) (let ((maybe-include-path (format "~a/~a/~a" base subdir path))) (and (file-exists? maybe-include-path) maybe-include-path))) (scheme-library-paths)) (locate-file path who))) (locate-file path who)))) (define locate-library-file (lambda (library-name) (let ((path (id-list->string (encode-library-ref library-name) "/"))) (any1 (lambda (base) (any1 (lambda (ext) (let ((maybe-path (format "~a/~a~a" base path ext))) (and (file-exists? maybe-path) (list maybe-path base)))) (library-extensions))) (scheme-library-paths))))) (define read-include-file (lambda (library-name path who) (let ((source-path (locate-include-file library-name path who))) (and (scheme-load-verbose) (format #t "~&;; including ~s~%~!" source-path)) (track-file-open-operation source-path) (let ((port (open-script-input-port source-path))) (with-exception-handler (lambda (c) (cond ((serious-condition? c) (close-port port) (raise c)) (else (raise-continuable c)))) (lambda () (parameterize ((current-source-comments (current-source-comments))) (current-source-comments (and (backtrace) (make-core-hashtable))) (let loop ((acc '())) (let ((form (core-read port (current-source-comments) who))) (cond ((eof-object? form) (close-port port) (reverse acc)) (else (loop (cons form acc))))))))))))) (define load-scheme-library (lambda (ref . vital) (let ((vital (or (not (pair? vital)) (car vital)))) (define make-cache (lambda (src dst source-ref source-time) (let ((cyclic-code #f)) (call-with-port (make-file-output-port dst) (lambda (output) (call-with-port (open-script-input-port src) (lambda (input) (with-exception-handler (lambda (c) (close-port input) (close-port output) (and (file-exists? dst) (delete-file dst)) (raise c)) (lambda () (parameterize ((current-source-comments (current-source-comments)) (current-temporaries (current-temporaries)) (current-environment (current-environment)) (lexical-syntax-version (lexical-syntax-version)) (mutable-literals (mutable-literals)) (backtrace (backtrace))) (let loop () (current-source-comments (and (backtrace) (make-core-hashtable))) (current-temporaries (make-core-hashtable 'string=?)) (current-rename-count 0) (let ((obj (core-read input (current-source-comments) 'load))) (cond ((eof-object? obj) (or cyclic-code (format output "~%"))) (else (let ((code (parameterize ((current-closure-comments (make-core-hashtable))) (compile-coreform (macro-expand obj))))) (or cyclic-code (cond ((cyclic-object? code) (close-port output) (and (file-exists? dst) (delete-file dst)) (set! cyclic-code #t)) (else (put-fasl output code) (format output "~%")))) (run-vmi (cons '(1 . 0) code)) (loop))))))))))))) cyclic-code))) (define locate-file (lambda (ref) (let ((path (id-list->string ref "/"))) (any1 (lambda (base) (any1 (lambda (ext) (let ((maybe-path (format "~a/~a~a" base path ext))) (and (file-exists? maybe-path) (list maybe-path base)))) (library-extensions))) (scheme-library-paths))))) (define locate-source (lambda (ref) (let ((safe-ref (encode-library-ref ref))) (or (if (library-contains-implicit-main) (if (eq? (list-ref safe-ref (- (length safe-ref) 1)) 'main) (or (locate-file (append safe-ref '(main))) (locate-file safe-ref)) (or (locate-file safe-ref) (locate-file (append safe-ref '(main))))) (locate-file safe-ref)) (and vital (error 'load-scheme-library (format "~s not found in scheme-library-paths: ~s" path (scheme-library-paths)))))))) (define locate-cache (lambda (ref source-path) (and (auto-compile-cache) (let ((cache-path (format "~a/~a.cache" (auto-compile-cache) (id-list->string (encode-library-ref ref) ".")))) (and (file-exists? cache-path) (let ((timestamp-path (string-append cache-path ".time"))) (and (file-exists? timestamp-path) (call-with-port (make-file-input-port timestamp-path) (lambda (timestamp-port) (get-datum timestamp-port) (get-datum timestamp-port) (cond ((equal? source-path (get-datum timestamp-port)) cache-path) (else (close-port timestamp-port) (cache-clean) #f)))))) cache-path))))) (define reorder-scheme-library-paths (lambda (top-path) (cons top-path (let loop ((lst (scheme-library-paths))) (cond ((null? lst) '()) ((equal? (car lst) top-path) (cdr lst)) (else (cons (car lst) (loop (cdr lst))))))))) (or (list? ref) (scheme-error "internal error in load-scheme-library: unrecognized argument: ~s" ref)) (cond ((locate-source ref) => (lambda (location) (destructuring-bind (source-path base-path) location (track-file-open-operation source-path) (parameterize ((scheme-library-paths (reorder-scheme-library-paths base-path))) (if (auto-compile-cache) (let ((cache-path (locate-cache ref source-path))) (if cache-path (load-cache cache-path) (let ((ref (encode-library-ref ref)) (library-id (generate-library-id ref))) (let ((cache-path (format "~a/~a.cache" (auto-compile-cache) (id-list->string ref ".")))) (and (auto-compile-verbose) (format #t "~&;; compile ~s~%~!" source-path)) (if (make-cache source-path cache-path ref (file-stat-mtime source-path)) (and (auto-compile-verbose) (format #t "~&;; delete ~s~%~!" cache-path)) (let ((timestamp-path (string-append cache-path ".time"))) (call-with-port (make-file-output-port timestamp-path) (lambda (output) (format output "~s ~s ~s ~s~%" (microsecond) (file-stat-mtime source-path) source-path auto-compile-cache-validation-signature) (cond ((core-hashtable-ref library-include-dependencies library-id #f) => (lambda (deps) (for-each (lambda (dep) (format output "~s ~s~%" (car dep) (file-stat-mtime (car dep)))) (core-hashtable->alist deps)) (core-hashtable-delete! library-include-dependencies library-id)))))))))))) (load source-path)))))))))) (define load-cache (lambda (path) (and (scheme-load-verbose) (format #t "~&;; loading ~s~%~!" path)) (let ((port (open-script-input-port path))) (with-exception-handler (lambda (c) (close-port port) (raise c)) (lambda () (parameterize ((backtrace #f) (current-source-comments #f) (current-temporaries (make-core-hashtable 'string=?)) (current-rename-count 0) (current-environment (current-environment))) (let loop () (let ((form (core-read port #f 'load))) (cond ((eof-object? form) (close-port port)) (else (run-vmi (cons '(1 . 0) form)) (loop))))))))))) (define cache-delete-files (lambda (cache-lst) (for-each (lambda (cache-name) (let* ((cache-path (string-append (auto-compile-cache) "/" cache-name)) (timestamp-path (string-append cache-path ".time"))) (and (file-exists? cache-path) (delete-file cache-path)) (and (file-exists? timestamp-path) (delete-file timestamp-path)) (and (auto-compile-verbose) (format #t "~&;; clean ~s~%" cache-path)))) cache-lst))) (define cache-clean (lambda () (cond ((auto-compile-cache) => (lambda (path) (let ((cache-lst (filter (lambda (s) (let ((p (string-contains s ".cache"))) (and p (= (string-contains s ".cache") (- (string-length s) 6))))) (directory-list path)))) (cache-delete-files cache-lst))))))) (define cache-update (lambda () (define inconsistent-cache-state (lambda (cache-lst) (and (auto-compile-verbose) (format #t "~&;; reset ~s~%" (auto-compile-cache))) (cache-delete-files cache-lst))) (cond ((auto-compile-cache) => (lambda (path) (let ((cache-lst (filter (lambda (s) (let ((p (string-contains s ".cache"))) (and p (= (string-contains s ".cache") (- (string-length s) 6))))) (directory-list path)))) (let loop ((lst cache-lst) (expiration #f)) (cond ((null? lst) (and expiration (for-each (lambda (cache-name) (let* ((cache-path (string-append (auto-compile-cache) "/" cache-name)) (timestamp-path (string-append cache-path ".time"))) (cond ((file-exists? timestamp-path) (call-with-port (make-file-input-port timestamp-path) (lambda (timestamp-port) (let ((cache-timestamp (get-datum timestamp-port))) (close-port timestamp-port) (cond ((>= cache-timestamp expiration) (delete-file timestamp-path) (delete-file cache-path) (and (auto-compile-verbose) (format #t "~&;; clean ~s~%" cache-path)))))))) (else (inconsistent-cache-state cache-lst))))) cache-lst)) (unspecified)) (else (let* ((cache-path (string-append (auto-compile-cache) "/" (car lst))) (timestamp-path (string-append cache-path ".time"))) (cond ((file-exists? timestamp-path) (call-with-port (make-file-input-port timestamp-path) (lambda (timestamp-port) (define get-dependencies-list (lambda () (let loop ((lst '())) (let* ((dep-path (get-datum timestamp-port)) (dep-time (get-datum timestamp-port))) (if (eof-object? dep-path) lst (loop (cons (cons dep-path dep-time) lst))))))) (define dependencies-exists? (lambda (lst) (every1 (lambda (b) (and (string? (car b)) (number? (cdr b)) (file-exists? (car b)))) lst))) (define dependencies-valid? (lambda (lst) (every1 (lambda (b) (= (file-stat-mtime (car b)) (cdr b))) lst))) (let* ((cache-timestamp (get-datum timestamp-port)) (source-timestamp (get-datum timestamp-port)) (source-path (get-datum timestamp-port)) (cache-signature (get-datum timestamp-port)) (dependencies (get-dependencies-list))) (close-port timestamp-port) (cond ((not (and (number? cache-timestamp) (number? source-timestamp) (string? source-path) (eq? cache-signature auto-compile-cache-validation-signature) (file-exists? source-path) (dependencies-exists? dependencies))) (inconsistent-cache-state cache-lst)) ((and (= (file-stat-mtime source-path) source-timestamp) (dependencies-valid? dependencies)) (loop (cdr lst) expiration)) (else (loop (cdr lst) (cond ((not expiration) cache-timestamp) ((< cache-timestamp expiration) cache-timestamp) (else expiration))))))))) (else (delete-file cache-path) (and (auto-compile-verbose) (format #t "~&;; clean ~s~%" cache-path)) (loop (cdr lst) expiration)))))))))) (else (unspecified))))) (define auto-compile-cache-clean (lambda () (define lock-fd #f) (dynamic-wind (lambda () (and (auto-compile-cache) (set! lock-fd (acquire-lockfile (auto-compile-cache-lock-path))))) (lambda () (cache-clean)) (lambda () (and (auto-compile-cache) (release-lockfile lock-fd)))))) (define auto-compile-cache-update (lambda () (define lock-fd #f) (dynamic-wind (lambda () (and (auto-compile-cache) (set! lock-fd (acquire-lockfile (auto-compile-cache-lock-path))))) (lambda () (cache-update)) (lambda () (and (auto-compile-cache) (release-lockfile lock-fd))))))
false
66b65e28a9ba8706ef90fc3de95714f00bc26c65
15b3f9425594407e43dd57411a458daae76d56f6
/bin/compiler/test/cond.scm
5a1b39765fdc44dcc118cea7d83ad2deb9d176d9
[]
no_license
aa10000/scheme
ecc2d50b9d5500257ace9ebbbae44dfcc0a16917
47633d7fc4d82d739a62ceec75c111f6549b1650
refs/heads/master
2021-05-30T06:06:32.004446
2015-02-12T23:42:25
2015-02-12T23:42:25
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
41
scm
cond.scm
(display (cond (1 1) (2 2)) )
false
2e23a5b4ad5a35b56e0eb521e89665c7c770e8d7
e92f708d2ca39757df4cf7e7d0d8f4ebb8bab0eb
/scheme-transforms-master/scheme-transforms-master/transforms.ss
583660edd4c7018f130da4ed7c51a864fd00ef40
[]
no_license
orthometa/304final
503d67345820cb769abedbc49c7029e90874f5b9
114eb45edeaf1a876f4c0a55f6d24213a589f35e
refs/heads/master
2020-03-18T12:57:52.580186
2018-05-24T18:23:08
2018-05-24T18:23:08
134,753,121
0
0
null
null
null
null
UTF-8
Scheme
false
false
817
ss
transforms.ss
#!r6rs (library (transforms) (export cps-transform cc-transform assignment-transform letrec-to-set redex-transform app-transform untag-transform transform) (import (rnrs) (transforms cps) (transforms cc) (transforms assignment) (transforms letrec-to-set) (transforms redex) (transforms app) (transforms untag)) (define (transform expr reserved-words return-calls) (let* ([a (letrec-to-set expr)] [b (assignment-transform a)] [c (cps-transform b reserved-words)] [d (redex-transform c)] [e (if return-calls (app-transform d) (untag-transform d))] [f (cc-transform e reserved-words)]) f)) )
false
0a9dbd1a816470e18bb8dfbde3fe0a7c7453b7db
defeada37d39bca09ef76f66f38683754c0a6aa0
/System/system/diagnostics/process-start-info.sls
dd3f5bb51c7918ae0ac6d6407b51084f97c7fa5b
[]
no_license
futsuki/ironscheme-port
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
4e7a81b0fbeac9a47440464988e53fb118286c54
refs/heads/master
2016-09-06T17:13:11.462593
2015-09-26T18:20:40
2015-09-26T18:20:40
42,757,369
0
0
null
null
null
null
UTF-8
Scheme
false
false
6,141
sls
process-start-info.sls
(library (system diagnostics process-start-info) (export new is? process-start-info? arguments-get arguments-set! arguments-update! create-no-window?-get create-no-window?-set! create-no-window?-update! environment-variables error-dialog?-get error-dialog?-set! error-dialog?-update! error-dialog-parent-handle-get error-dialog-parent-handle-set! error-dialog-parent-handle-update! file-name-get file-name-set! file-name-update! redirect-standard-error?-get redirect-standard-error?-set! redirect-standard-error?-update! redirect-standard-input?-get redirect-standard-input?-set! redirect-standard-input?-update! redirect-standard-output?-get redirect-standard-output?-set! redirect-standard-output?-update! standard-error-encoding-get standard-error-encoding-set! standard-error-encoding-update! standard-output-encoding-get standard-output-encoding-set! standard-output-encoding-update! use-shell-execute?-get use-shell-execute?-set! use-shell-execute?-update! verb-get verb-set! verb-update! verbs window-style-get window-style-set! window-style-update! working-directory-get working-directory-set! working-directory-update! load-user-profile?-get load-user-profile?-set! load-user-profile?-update! user-name-get user-name-set! user-name-update! domain-get domain-set! domain-update! password-get password-set! password-update!) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Diagnostics.ProcessStartInfo a ...))))) (define (is? a) (clr-is System.Diagnostics.ProcessStartInfo a)) (define (process-start-info? a) (clr-is System.Diagnostics.ProcessStartInfo a)) (define-field-port arguments-get arguments-set! arguments-update! (property:) System.Diagnostics.ProcessStartInfo Arguments System.String) (define-field-port create-no-window?-get create-no-window?-set! create-no-window?-update! (property:) System.Diagnostics.ProcessStartInfo CreateNoWindow System.Boolean) (define-field-port environment-variables #f #f (property:) System.Diagnostics.ProcessStartInfo EnvironmentVariables System.Collections.Specialized.StringDictionary) (define-field-port error-dialog?-get error-dialog?-set! error-dialog?-update! (property:) System.Diagnostics.ProcessStartInfo ErrorDialog System.Boolean) (define-field-port error-dialog-parent-handle-get error-dialog-parent-handle-set! error-dialog-parent-handle-update! (property:) System.Diagnostics.ProcessStartInfo ErrorDialogParentHandle System.IntPtr) (define-field-port file-name-get file-name-set! file-name-update! (property:) System.Diagnostics.ProcessStartInfo FileName System.String) (define-field-port redirect-standard-error?-get redirect-standard-error?-set! redirect-standard-error?-update! (property:) System.Diagnostics.ProcessStartInfo RedirectStandardError System.Boolean) (define-field-port redirect-standard-input?-get redirect-standard-input?-set! redirect-standard-input?-update! (property:) System.Diagnostics.ProcessStartInfo RedirectStandardInput System.Boolean) (define-field-port redirect-standard-output?-get redirect-standard-output?-set! redirect-standard-output?-update! (property:) System.Diagnostics.ProcessStartInfo RedirectStandardOutput System.Boolean) (define-field-port standard-error-encoding-get standard-error-encoding-set! standard-error-encoding-update! (property:) System.Diagnostics.ProcessStartInfo StandardErrorEncoding System.Text.Encoding) (define-field-port standard-output-encoding-get standard-output-encoding-set! standard-output-encoding-update! (property:) System.Diagnostics.ProcessStartInfo StandardOutputEncoding System.Text.Encoding) (define-field-port use-shell-execute?-get use-shell-execute?-set! use-shell-execute?-update! (property:) System.Diagnostics.ProcessStartInfo UseShellExecute System.Boolean) (define-field-port verb-get verb-set! verb-update! (property:) System.Diagnostics.ProcessStartInfo Verb System.String) (define-field-port verbs #f #f (property:) System.Diagnostics.ProcessStartInfo Verbs System.String[]) (define-field-port window-style-get window-style-set! window-style-update! (property:) System.Diagnostics.ProcessStartInfo WindowStyle System.Diagnostics.ProcessWindowStyle) (define-field-port working-directory-get working-directory-set! working-directory-update! (property:) System.Diagnostics.ProcessStartInfo WorkingDirectory System.String) (define-field-port load-user-profile?-get load-user-profile?-set! load-user-profile?-update! (property:) System.Diagnostics.ProcessStartInfo LoadUserProfile System.Boolean) (define-field-port user-name-get user-name-set! user-name-update! (property:) System.Diagnostics.ProcessStartInfo UserName System.String) (define-field-port domain-get domain-set! domain-update! (property:) System.Diagnostics.ProcessStartInfo Domain System.String) (define-field-port password-get password-set! password-update! (property:) System.Diagnostics.ProcessStartInfo Password System.Security.SecureString))
true
9b33e3bc8b7c5d1b5e0b56eed6b777a57de4ade1
e3f53651718faf505a71ebdf1c145274c20bec7d
/data-scripts/build-keyboard-adjacency-graphs.ss
3875257518e5252522755a65f984ca113fdb65d6
[ "MIT" ]
permissive
hinkelman/zxcvbn-chez
b66417262f55f54889d37e21c75a5351b12d5ece
ffc0567ae035f938447db38a0a26cb8bd1e50511
refs/heads/main
2023-04-06T16:33:51.868735
2021-04-10T15:43:37
2021-04-10T15:43:37
323,502,366
0
0
null
null
null
null
UTF-8
Scheme
false
false
5,106
ss
build-keyboard-adjacency-graphs.ss
#!/usr/bin/env scheme-script ;; -*- mode: scheme; coding: utf-8 -*- !# ;; Copyright (c) 2020 Travis Hinkelman ;; SPDX-License-Identifier: MIT #!r6rs ;; run this script with the following line in the terminal ;; scheme ./data-scripts/build-keyboard-adjacency-graphs.ss (define qwerty '(("`~" "1!" "2@" "3#" "4$" "5%" "6^" "7&" "8*" "9(" "0)" "-_" "=+") (() "qQ" "wW" "eE" "rR" "tT" "yY" "uU" "iI" "oO" "pP" "[{" "]}" "\\|") (() "aA" "sS" "dD" "fF" "gG" "hH" "jJ" "kK" "lL" ";:" "'\"") (() "zZ" "xX" "cC" "vV" "bB" "nN" "mM" ",<" ".>" "/?"))) (define dvorak '(("`~" "1!" "2@" "3#" "4$" "5%" "6^" "7&" "8*" "9(" "0)" "[{" "]}") (() "'\"" ",<" ".>" "pP" "yY" "fF" "gG" "cC" "rR" "lL" "/?" "=+" "\\|") (() "aA" "oO" "eE" "uU" "iI" "dD" "hH" "tT" "nN" "sS" "-_") (() ";:" "qQ" "jJ" "kK" "xX" "bB" "mM" "wW" "vV" "zZ"))) (define keypad '((() "/" "*" "-") ("7" "8" "9" "+") ("4" "5" "6") ("1" "2" "3") (() "0" "."))) (define keypad-mac '((() "=" "/" "*") ("7" "8" "9" "-") ("4" "5" "6" "+") ("1" "2" "3") (() "0" "."))) ;; loop through sub-lists in layout to build position table (define (x-loop x-lst y) (let loop ([x-lst x-lst] [x 0] [out '()]) (if (null? x-lst) (reverse out) (if (null? (car x-lst)) (loop (cdr x-lst) (add1 x) out) ;; count position but don't include in output (loop (cdr x-lst) (add1 x) (cons (list (car x-lst) (cons x y)) out)))))) ;; loop through lists in layout to build position table (define (y-loop layout) (let loop ([layout layout] [y 1] [out '()]) (if (null? layout) (reverse out) (loop (cdr layout) (add1 y) (cons (x-loop (car layout) y) out))))) (define (build-position-table layout) (apply append (y-loop layout))) ;; returns the six adjacent coordinates on a standard keyboard, where each row is slanted to the right from the last ;; adjacencies are clockwise, starting with key to the left, then two keys above, then right key, then two keys below ;; that is, only near-diagonal keys are adjacent, so g's coordinate is adjacent to those of t,y,b,v, but not those of r,u,n,c.) (define (get-slanted-adjacent-coords xy) (let ([x (car xy)] [y (cdr xy)]) (list (cons (sub1 x) y) (cons x (sub1 y)) (cons (add1 x) (sub1 y)) (cons (add1 x) y) (cons x (add1 y)) (cons (sub1 x) (add1 y))))) ;; returns the nine clockwise adjacent coordinates on a keypad, where each row is vert aligned (define (get-aligned-adjacent-coords xy) (let ([x (car xy)] [y (cdr xy)]) (list (cons (sub1 x) y) (cons (sub1 x) (sub1 y)) (cons x (sub1 y)) (cons (add1 x) (sub1 y)) (cons (add1 x) y) (cons (add1 x) (add1 y)) (cons x (add1 y)) (cons (sub1 x) (add1 y))))) (define (get-adjacent-keys token pos-table pos-table-rev adjacency-func) (let* ([xy-token (cadr (assoc token pos-table))] ;; xy for token [xy-adj-lst (adjacency-func xy-token)]) ;; list of xy pairs for keys adjacent to token (map (lambda (xy-adj) (let ([xy-key-adj (assoc xy-adj pos-table-rev)]) (if xy-key-adj (cadr xy-key-adj) '()))) xy-adj-lst))) (define (build-graph-helper layout slanted) (let* ([pos-table (build-position-table layout)] [pos-table-rev (map reverse pos-table)] [tokens (filter (lambda (x) (not (null? x))) (apply append layout))] [adjacency-func (if slanted get-slanted-adjacent-coords get-aligned-adjacent-coords)]) (map (lambda (token) (list token (get-adjacent-keys token pos-table pos-table-rev adjacency-func))) tokens))) ;; split key tokens and duplicate list of adjacent keys (where necessary) (define (build-graph layout slanted) (let* ([graph (build-graph-helper layout slanted)] [first-token-len (string-length (caar graph))]) (unless (for-all (lambda (x) (= first-token-len (string-length (car x)))) graph) (assertion-violation "build-graph" "not all tokens have same number of characters")) (cond [(= first-token-len 1) graph] [(= first-token-len 2) (apply append (map (lambda (lst) (let* ([token-char-lst (string->list (car lst))]) (list (cons (string (car token-char-lst)) (cdr lst)) (cons (string (cadr token-char-lst)) (cdr lst))))) graph))] [else (assertion-violation "build-graph" "token should have only 1 or 2 characters")]))) (with-output-to-file (string-append "zxcvbn" (string (directory-separator)) "adjacency-graphs.scm") (lambda () (write `(define adjacency-graphs '(,(list "qwerty" (build-graph qwerty #t)) ,(list "dvorak" (build-graph dvorak #t)) ,(list "keypad" (build-graph keypad #f)) ,(list "keypad-mac" (build-graph keypad-mac #f))))))) (exit)
false
1a84f43227a50e553d7673d637781d502b873eb7
47457420b9a1eddf69e2b2f426570567258f3afd
/1/31.scm
43931c507e4e7e1ce299218f6b8ee69e42e97a31
[]
no_license
adromaryn/sicp
797496916620e85b8d85760dc3f5739c4cc63437
342b56d233cc309ffb59dd13b2d3cf9cd22af6c9
refs/heads/master
2021-08-30T06:55:04.560128
2021-08-29T12:47:28
2021-08-29T12:47:28
162,965,433
0
0
null
null
null
null
UTF-8
Scheme
false
false
885
scm
31.scm
#lang sicp (define (product term a next b) (if (> a b) 1 (* (term a) (product term (next a) next b)))) (define (factorial n) (define (term x) x) (define (next x) (+ x 1)) (product term 1 next n)) (factorial 5) (factorial 10) (define (product2 term a next b) (define (iter a result) (if (> a b) result (iter (next a) (* (term a) result)))) (iter a 1)) (define (square x) (* x x)) (define (sum-pi n) (define (term x) x) (define (next x) (+ x 2)) (cond ((= n 1) (/ 2 3)) ((even? n) (/ (square (product term 2 next (+ 2 n))) (square (product term 3 next (+ 1 n))) 2 (+ 2 n))) (else (/ (square (product term 2 next (+ 1 n))) (square (product term 3 next (+ 2 n))) 2 (+ 2 n))))) (* 4.0 (sum-pi 10000))
false
fc1472d3ef5dd8779a6f0052f8d7dd4d4144a3c7
c24a946b86dbe91a078dd97536a6488eb52f6b77
/contrib/70.main/main.scm
92dba342a400611ad5aede55648a31347c533126
[ "MIT" ]
permissive
picrin-scheme/picrin
16090d88733e8c7b6e4a571dec0a5b65b3c02a7c
05a21b650c9083b67692599db1a50b640f73ae39
refs/heads/master
2023-08-04T23:21:14.814662
2023-01-12T06:11:19
2023-01-12T06:12:23
13,706,205
380
43
null
2017-08-06T02:43:44
2013-10-19T18:16:47
Scheme
UTF-8
Scheme
false
false
1,491
scm
main.scm
(define-library (picrin main) (import (scheme base) (scheme read) (scheme write) (scheme process-context) (scheme load) (scheme eval) (picrin repl)) (define (print-help) (display "picrin scheme\n") (display "\n") (display "Usage: picrin [options] [file]\n") (display "\n") (display "Options:\n") (display " -e [program] run one liner script\n") (display " -l [file] load the file then enter repl\n") (display " -h or --help show this help\n")) (define (getopt) (let ((args (cdr (command-line)))) (if (null? args) (values 'repl #f) (case (string->symbol (car args)) ((-h --help) (print-help) (exit 1)) ((-e) (values 'line (cadr args))) ((-l) (values 'load (cadr args))) (else (values 'file (car args))))))) (define (exec-file filename) (load filename)) (define (exec-line str) (call-with-port (open-input-string str) (lambda (in) (let loop ((expr (read in))) (unless (eof-object? expr) (eval expr '(picrin user)) (loop (read in))))))) (define (main) (call-with-values getopt (lambda (type dat) (case type ((repl) (repl)) ((load) (load dat) (repl)) ((line) (exec-line dat)) ((file) (exec-file dat)))))) (export main))
false
2fda8ce72708ad8bd482789bc9c7ac0562940ee9
398496271fc1e4bc679f8520e2aa12d958c71059
/A1/a1q3_calculations.scm
abb8827cdfb14f0db2657ed2918599552625fe4c
[]
no_license
guptamihir418/COMP-3007
f1d113d7f5fdc717eed424b486af6327e4b79efe
0d34a67658d9f7fab821cbaa922fa7b11889420a
refs/heads/main
2023-04-22T14:38:19.381362
2021-05-05T15:26:44
2021-05-05T15:26:44
364,622,119
2
0
null
null
null
null
UTF-8
Scheme
false
false
4,879
scm
a1q3_calculations.scm
; MIHIR GUPTA 101172281 ; Question 3 ; Part A-> Standard Round-off ; It takes an input number (A) and precision value (B) as parameters and returns the input ; number rounded to the specified precision value ; My logic -> if we multiply the input number i.e. A with 10^B ( where B is precision value) ; we will get a value which we can round off easily by adding or subtracting 0.5 to the specified decimal digits. (define (standard-roundf A B) (let ((pow (expt 10 B))) (/ (floor (+ 0.5 (* A pow))) pow))) ; Testing cases (display "Testing cases for part A\n\n") (display "(standard-roundf 2.5 0): ") (standard-roundf 2.5 0) ; Precision needed is 0 decimal point, the answer should be 2.5 + 0.5 -> 3.0 ; 3.0 Correct (display "(standard-roundf 1.2225 3): ") (standard-roundf 1.2225 3) ; Precision should be 3, so multiply 1.2225 by 10^3 = 1000 ; 1222.5 now add 0.5 -> 12223 now divide it by same value 10^3 = 1000 ; 1.223 Correct (display "(standard-roundf -1.82593 2): ") (standard-roundf -1.82593 2) ; Precision should be 2, so multiply -1.82593 by 10^2 = 100 ; -182.593 now subtract 0.5 -> -182.093 now we take floor of this number ; -183 -> now divide by 100 -> -1.83 Correct (display "(standard-roundf 186 1): ") (standard-roundf 186 1) ; Precision should be 1, so multiply 186 by 10 -> 1860 now we take floor ; of this number and we get 1860 -> now divide by 10 -> 186.0 Correct (newline) ; Part B -> Quadratic Equation ; This is the quadratic formula which calculates the roots of equation of form ax^2 + bx + c = 0 ; it returns #f if roots are not real or we can say that when term inside underoot is -ve which is ; -b^2 + 4ac and will also return false if a = 0 ; My algorithm: I first check if value of a is zero or not, if it is procedure is called off without ; actually running any code, it is efficient and next if condition checks if the term inside the square root ; is =ve if not it will return #f and at last I use standard-roundf to round off the answer to 3 DP (define (quadratic a b c) (if (= a 0) #f (if (< (- (* b b) (* 4 a c)) 0) #f (standard-roundf (/ (+ (sqrt (- (* b b) (* 4 a c))) (* -1 b)) (* 2 a)) 3)))) ; Testing cases (display "Testing cases for part B\n\n") (display "(quadratic 5 12 1)=> ") (display "A = 5 B = 12 C = 1 Discriminant = 124\n ") (display "Root: ") (quadratic 5 12 1) ; A = 5 B = 12 C = 1 -> A != 0 -> b^2 - 4ac = 144 - 20 = 124 which is positive ; and every condition is met it will return the root of th eequation 4x^2 + 12x + 1 =0 (newline) (display "(quadratic 0 12 1)=> ") (display "A = 0 B = 12 C = 1 Discriminant = 144\n ") (display "Root: ") (quadratic 0 12 1) ; A = 0 and hence program quits after checking first conditon (display "(quadratic 5 1 1)=> ") (display "A = 5 B = 1 C = 1 Discriminant = -19\n ") (display "Root: ") (quadratic 5 1 1) ; As Discriminant is -ve we get #f returned (newline) ; Part C -> This procedure converts any combination of Bytes "B", kibibytes "kiB" and Kilobytes "KB" ; My logic: Used cond to get all the cases, but how many cases to caluclate that I used PNC ; I have 3 option and I need to choose any 2 of them 3C2 = 6 ; Also what if we convert from and to one thing only those cases = 3 ; Total cases = 6+3 = 9, if there is any other case other than these 9 cases ; We give error message (define (convert N A B) ; N is the number we want to convert, A is the "from unit", B is "to unit" (cond ((and (equal? A "KB") (equal? B "B")) (* 1000 N)) ((and (equal? A "KB") (equal? B "KiB")) (* 0.9765625 N)) ((and (equal? A "KiB") (equal? B "B")) (* 1024 N)) ((and (equal? A "KiB") (equal? B "KB")) (* 1.024 N)) ((and (equal? A "B") (equal? B "KB")) (standard-roundf (/ N 1000) 3)) ((and (equal? A "B") (equal? B "KiB")) (standard-roundf (/ N 1024) 3)) ((and (equal? A "B") (equal? B "B")) N) ; Same unit conversions ((and (equal? A "KiB") (equal? B "KiB")) N) ; Same unit conversions ((and (equal? A "KB") (equal? B "KB")) N) ; Same unit conversions (else (string-append "Could not convert from " A " to " B)))) ; Testing cases (display "Testing cases for part C\n\n") (display "(convert 42 KB B ): ") (convert 42 "KB" "B"); conversion from kilo bytes to bytes we multiply 42 by 1000 -> 42000 (display "(convert 42 KiB B ): ") (convert 42 "KiB" "B"); conversion from kibibytes to bytes we multiply 42 by 1024 -> 43008 (display "(convert 42 KiB KB ): ") (convert 42 "KiB" "KB"); conversion from kibibytes to bytes we multiply 42 by 1.024 -> 43.008 (display "(convert 42 KiB KiB ): ") (convert 42 "KiB" "KiB"); conversion from kibibytes to kibibytes, same units return same number -> 42
false
a54a3d225957a069150fd3eea4c529faecd2e448
25a487e394b2c8369f295434cf862321c26cd29c
/lib/pikkukivi/commands/extattr.sls
9684b108918fd50099504d6765b70818cd06a0d6
[]
no_license
mytoh/loitsu
b11e1ed9cda72c0a0b0f59070c9636c167d01a2c
d197cade05ae4acbf64c08d1a3dd9be6c42aac58
refs/heads/master
2020-06-08T02:00:50.563515
2013-12-17T10:23:04
2013-12-17T10:23:04
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,474
sls
extattr.sls
(library (pikkukivi commands extattr) (export extattr) (import (silta base) (silta write) (only (srfi :13 strings) string-tokenize) (srfi :48) (loitsu match) (loitsu process)) (begin (define (get-extattr-command name file) (run-command `(getextattr -q user ,name ,file))) (define (get-extattr name file) (let ((value (get-extattr-command name file))) (if (not (string=? "" value)) (format #t "~a -> ~a" name value)))) (define (ls-extattr-command file) (run-command `(lsextattr -q user ,file))) (define (ls-extattr file) (let ((attrs (ls-extattr-command file))) (for-each (lambda (s) (get-extattr s file)) (string-tokenize attrs)))) (define (rm-extattr-command name file) (run-command `(rmextattr -q user ,name ,file))) (define (rm-extattr name file) (rm-extattr-command name file)) (define (set-extattr-command name value file) (run-command `(setextattr -q user ,name ,value ,file))) (define (set-extattr name value file) (set-extattr-command name value file)) (define (extattr args) (match (cddr args) (("get" name file) (get-extattr name file)) (("ls" file) (ls-extattr file)) (("rm" name file) (rm-extattr name file)) (("set" name value file) (set-extattr name value file)) )) ))
false
fa7cb0a98ee4c59e26ea25ceb69c6bcb993ed130
d47ddad953f999e29ce8ef02b059f945c76a791e
/scheme-built-in-functions.scm
d749a1184b7df22a407b0699c7c3f4b629abc2ea
[]
no_license
IvanIvanov/fp2013
7f1587ef1f2261f8cd0cd3dd99ec147c4043a2ae
2ac1bb1102cb65e0ecbfa8d2fb3ca69953ae4ecf
refs/heads/master
2016-09-11T10:08:59.873239
2014-01-23T20:38:27
2014-01-23T20:40:34
13,211,029
5
2
null
2014-01-10T15:55:14
2013-09-30T09:18:33
Scheme
UTF-8
Scheme
false
false
2,891
scm
scheme-built-in-functions.scm
;;; Cheat sheet of built-in functions in Scheme. ;;; Functions for working with numbers. (even? 2) ; #t (even? 1) ; #f (odd? 2) ; #f (odd? 1) ; #t ; a^b (expt 2 10) ; 1024 (sqrt 16) ; 4 (min 1 2) ; 1 (min 1 2 3 4 5 6 7 8 9 10) ; 1 (max 1 2) ; 2 (max 1 2 3 4 5 6 7 8 9 10) ; 10 ; Remainder and division with whole numbers. (remainder 10 3) ; 1 (remainder 12 3) ; 0 (quotient 10 3) ; 3 (quotient 12 3) ; 4 ;;; Built-in functions for working with booleans. (and #t #t) ; #t (and #t #f) ; #f (or #t #f) ; #t (or #f #f) ; #f (not #t) ; #f (not #f) ; #t ;;; Built-in functions for working with lists. ; Creating a pair - warning a pair is not a list. (cons 1 2) ; (1 . 2) (cons 2 1) ; (2 . 1) ; Creating a list - a sequence of linked pairs who's last pair has a second ; element pointing to the empty list '() (cons 1 '()) ; (1) (cons 1 (cons 2 '())) ; (1 2) (list) ; () (list 1) ; (1) (list 1 2) ; (1 2) (list (+ 0 1) (* 1 2)) ; (1 2) (list 1 2 3 4 5 6 7 8 9 10) ; (1 2 3 4 5 6 7 8 9 10) '() ; () '(1) ; (1) '(1 2) ; (1 2) '((+ 0 1) (* 1 2)) ; ((+ 0 1) (* 1 2)) '(1 2 3 4 5 6 7 8 9 10) ; (1 2 3 4 5 6 7 8 9 10) ; Accessing the elements of pairs (that may or may not be organized as lists. ; The first element of a pair. (car (cons 1 2)) ; 1 (car '(1 2)) ; 1 ; The second element of a pair. (cdr (cons 1 2)) ; 2 (cdr '(1 2)) ; (2) ; Same as (car (cdr '(1 2))). (cadr '(1 2)) ; 2 ; Same as (cdr (car '((1 2) 3))). (cdar '((1 2) 3)) ; (2) ; The empty list. '() ; Checks if something is the empty list. (null? '()) ; #t (null? '(1 2 3)) ; #f ; Checks if something is a pair. (pair? (cons 1 2)) ; #t (pair? '(1 2 3 4)) ; #t (pair? 1) ; #f ; Checks if something is an atom - not a pair. (not (pair? (cons 1 2))) ; #f (not (pair? '(1 2 3 4))) ; #f (not (pair? 1)) ; #t ; Finds the length of a list. (length '()) ; 0 (length '(1 2 3)) ; 3 (length '((1 2 3) (4 5) (6) (7 8))) ; 4 ; Reverses a list. (reverse '()) ; () (reverse '(1 2 3)) ; (3 2 1) ; Puts two lists one after the other. (append '() '()) ; () (append '(1 2 3) '(4 5 6)) ; (1 2 3 4 5 6) ; Applies a function over each element of a list. (map (lambda (x) (* x x)) '(1 2 3 4)) ; (1 4 9 16) ; NOT BUILT-IN ; A function that filters all elements of a list by only keeping those ; elements that satisfy a predicate given as an argument. (define (filter predicate items) (cond ((null? items) '()) ((predicate (car items)) (cons (car items) (filter predicate (cdr items)))) (else (filter predicate (cdr items))))) (filter even? '(1 2 3 4)) ; (2 4) (filter odd? '(1 2 3 4)) ; (1 3) ; NOT BUILT-IN ; Aggregates elements of a list with a specific operator and initial value. (define (accumulate op initial items) (if (null? items) initial (op (car items) (accumulate op initial (cdr items))))) (accumulate + 0 '(1 2 3 4 5)) ; 15 (accumulate * 1 '(1 2 3 4 5)) ; 120
false
ac938c43688a581a804e556edc63c057b83a1597
0bb7631745a274104b084f6684671c3ee9a7b804
/lib/gambit/prim/misc-r4rs#.scm
4f754fe895db2e3f581bc71c4e407229b41050ec
[ "Apache-2.0", "LGPL-2.1-only", "LicenseRef-scancode-free-unknown", "GPL-3.0-or-later", "LicenseRef-scancode-autoconf-simple-exception" ]
permissive
feeley/gambit
f87fd33034403713ad8f6a16d3ef0290c57a77d5
7438e002c7a41a5b1de7f51e3254168b7d13e8ba
refs/heads/master
2023-03-17T06:19:15.652170
2022-09-05T14:31:53
2022-09-05T14:31:53
220,799,690
0
1
Apache-2.0
2019-11-10T15:09:28
2019-11-10T14:14:16
null
UTF-8
Scheme
false
false
586
scm
misc-r4rs#.scm
;;;============================================================================ ;;; File: "misc-r4rs#.scm" ;;; Copyright (c) 1994-2021 by Marc Feeley, All Rights Reserved. ;;;============================================================================ ;;; Miscellaneous operations in R4RS. (##namespace ("##" apply call-with-current-continuation eq? equal? eqv? force (load unimplemented#load) procedure? (transcript-off unimplemented#transcript-off) (transcript-on unimplemented#transcript-on) )) ;;;============================================================================
false
14343ee90e2a6ae79429afb1ea0b70fd2c59a1d6
43612e5ed60c14068da312fd9d7081c1b2b7220d
/unit-tests/strings.scm
c60f8aec7d35cc3ec579bb06ff481d11a16679f5
[ "BSD-3-Clause" ]
permissive
bsaleil/lc
b1794065183b8f5fca018d3ece2dffabda6dd9a8
ee7867fd2bdbbe88924300e10b14ea717ee6434b
refs/heads/master
2021-03-19T09:44:18.905063
2019-05-11T01:36:38
2019-05-11T01:36:38
41,703,251
27
1
BSD-3-Clause
2018-08-29T19:13:33
2015-08-31T22:13:05
Scheme
UTF-8
Scheme
false
false
4,042
scm
strings.scm
;;--------------------------------------------------------------------------- ;; ;; Copyright (c) 2015, Baptiste Saleil. All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are ;; met: ;; 1. Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; 2. Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; 3. The name of the author may not be used to endorse or promote ;; products derived from this software without specific prior written ;; permission. ;; ;; THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED ;; WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF ;; MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN ;; NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ;; NOT LIMITED TO PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;; ;;--------------------------------------------------------------------------- ;; make-string ;;;(define s1 (make-string 10)) (define s1 (make-string 10 #\0)) (define s2 (make-string 10 #\a)) (pp s1) (pp s2) ;; string-fill! (string-fill! s1 #\b) (pp s1) (pp s2) ;; string-set! (string-set! s2 0 #\?) (string-set! s2 (- (string-length s2) 1) #\?) (pp s1) (pp s2) ;; string<->list (define s3 (list->string (list #\H #\i #\.))) (define s4 (list->string '())) (define l1 (string->list "Hello")) (define l2 (string->list (make-string 4 #\a))) (define l3 (string->list "")) (pp s3) (pp s4) (pp l1) (pp l2) (pp l3) ;; string (define s5 (string #\H #\e #\l #\l #\o #\!)) (define s6 (string)) (pp s5) (pp s6) ;; string-append (define s7 (string-append "Dark " (list->string (list #\V #\a #\d #\o #\r)))) (define s8 (string-append "A" "")) (define s9 (string-append "" "B")) (define s10 (string-append)) (define s11 (string-append "Hi")) (pp s7) (pp s8) (pp s9) (pp s10) (pp s11) ;; string-length (define s12 "Hello") (define s13 (string-append "Dark " (list->string (list #\V #\a #\d #\o #\r)))) (define s14 (list->string '())) (pp (string-length s12)) (pp (string-length s13)) (pp (string-length s14)) ;; substring (define s15 (string-append "Dark " (list->string (list #\V #\a #\d #\o #\r)))) (pp (substring s15 0 0)) (pp (substring s15 0 (string-length s15))) (pp (substring s15 3 7)) ;; string-ref (define s16 "Hello") (define s17 (string-append "Dark " (list->string (list #\V #\a #\d #\o #\r)))) (pp (string-ref s16 0)) (pp (string-ref s16 3)) (pp (string-ref s17 4)) (pp (string-ref s17 9)) ;; string-copy (define s18 (make-string 5 #\Z)) (define s19 (string-copy s18)) (pp s18) (pp s19) (string-set! s18 4 #\U) (pp s18) (pp s19) ;; string=? (define s20 "Hello") (define s21 "Hello World") (define s22 " Hello") (define s23 (list->string (list #\H #\e #\l #\l #\o))) (define s24 "") (define s25 (make-string 0)) (pp (string=? s20 s20)) (pp (string=? s20 s21)) (pp (string=? s20 s22)) (pp (string=? s20 s23)) (pp (string=? s20 s24)) (pp (string=? s24 s24)) (pp (string=? s24 s23)) (pp (string=? s24 s25)) (pp (string=? s21 s22)) ;"0000000000" ;"aaaaaaaaaa" ;"bbbbbbbbbb" ;"aaaaaaaaaa" ;"bbbbbbbbbb" ;"?aaaaaaaa?" ;"Hi." ;"" ;(#\H #\e #\l #\l #\o) ;(#\a #\a #\a #\a) ;() ;"Hello!" ;"" ;"Dark Vador" ;"A" ;"B" ;"" ;"Hi" ;5 ;10 ;0 ;"" ;"Dark Vador" ;"k Va" ;#\H ;#\l ;#\space ;#\r ;"ZZZZZ" ;"ZZZZZ" ;"ZZZZU" ;"ZZZZZ" ;#t ;#f ;#f ;#t ;#f ;#t ;#f ;#t ;#f
false
2e306db02a3a18be0c5c3378feb9a90a6729143c
d755de283154ca271ef6b3b130909c6463f3f553
/htdp-test/2htdp/utest/player
98d18e3447a46aca56430fd1ecf994caeb1cbfbf
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "Apache-2.0" ]
permissive
racket/htdp
2953ec7247b5797a4d4653130c26473525dd0d85
73ec2b90055f3ab66d30e54dc3463506b25e50b4
refs/heads/master
2023-08-19T08:11:32.889577
2023-08-12T15:28:33
2023-08-12T15:28:33
27,381,208
100
90
NOASSERTION
2023-07-08T02:13:49
2014-12-01T13:41:48
Racket
UTF-8
Scheme
false
false
287
player
#! /bin/sh #| -*- scheme -*- exec mred -qu "$0" ${1+"$@"} |# #lang racket (require "shared.ss") (define argv (current-command-line-arguments)) (unless (= (vector-length argv) 1) (error 'player "name of one player expected: $ ./player name")) (make-player 200 (vector-ref argv 0))
false
86c50ea094e2781288033a2853a8eb2995d54ddc
eeb788f85765d6ea5a495e1ece590f912bc8c657
/profj/libs/java/tester/installer.ss
74fb03cf4eebf16a21cd871aedeb4d5551090f9c
[]
no_license
mflatt/profj
f645aaae2b147a84b385e42f681de29535e13dd4
bc30ab369ac92ef3859d57be5c13c9562948bb8a
refs/heads/master
2023-08-28T14:13:17.153358
2023-08-08T13:08:04
2023-08-08T13:08:04
10,001,564
10
4
null
2020-12-01T18:41:00
2013-05-11T15:54:54
Scheme
UTF-8
Scheme
false
false
471
ss
installer.ss
(module installer mzscheme (require profj/compile) (provide installer) (define (installer plthome) (let ([java.test (build-path (collection-path "profj" "libs" "java" "tester"))]) (let ([javac (lambda (file) (parameterize ([current-load-relative-directory java.test]) (compile-java 'file 'file 'full (build-path java.test file) #f #f)))]) (javac "TestBase.djava")))))
false
b9fb2236572fdb49a703a24f788d361223a7de0e
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
/ext/crypto/tests/test-b-163.scm
c7dfe1757bf3f34134757a5ec77605cc9ff39652
[ "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "MIT", "BSD-2-Clause" ]
permissive
ktakashi/sagittarius-scheme
0a6d23a9004e8775792ebe27a395366457daba81
285e84f7c48b65d6594ff4fbbe47a1b499c9fec0
refs/heads/master
2023-09-01T23:45:52.702741
2023-08-31T10:36:08
2023-08-31T10:36:08
41,153,733
48
7
NOASSERTION
2022-07-13T18:04:42
2015-08-21T12:07:54
Scheme
UTF-8
Scheme
false
false
4,301
scm
test-b-163.scm
;; [B-163,SHA-1] #| Msg = 86752230200fc292fcb89597605c9ce117397779 d = 13486dc5ca0ba84956d2f6dc43df0415656f0eac5 Qx = 71765ccb031969d7332cc53890ee209520fb8ceab Qy = 2e99b4c30d3de389735cbeebb6e73ce9f67dc5412 k = 17cdf80f62e42b21349a55a62591436363ec43c59 R = 2ddace85a086746d8a4691ca61765719fbb69d928 S = 17a9d0c14ff04cb6ae6d72d26701e5f69c5320e6b |# (test-ecdsa NIST-B-163 no-20 #x86752230200fc292fcb89597605c9ce117397779 #x13486dc5ca0ba84956d2f6dc43df0415656f0eac5 #x71765ccb031969d7332cc53890ee209520fb8ceab #x2e99b4c30d3de389735cbeebb6e73ce9f67dc5412 #x17cdf80f62e42b21349a55a62591436363ec43c59 #x2ddace85a086746d8a4691ca61765719fbb69d928 #x17a9d0c14ff04cb6ae6d72d26701e5f69c5320e6b ) ;; [B-163,SHA-224] #| Msg = c6e9f645884a30ec4a4e036b4a4c1e08172706ebddd175400080eb83 d = 2195f750f10b89ba5c4fbefd0fe76a3213b5fc96a Qx = 48fa6845e9b35b43c832f782fc729495a92014f8f Qy = 4a967b26229bca6a234344f63eb4272f83254e45e k = 379eb8961d496aaba2b732d1215b3cfc62773da3f R = 029ccd4e3a372a2cf1a96f205583e5b85ec762f74 S = 304d311f55a40fed97677d56634a1615c56db96be |# (test-ecdsa NIST-B-163 no-28 #xc6e9f645884a30ec4a4e036b4a4c1e08172706ebddd175400080eb83 #x2195f750f10b89ba5c4fbefd0fe76a3213b5fc96a #x48fa6845e9b35b43c832f782fc729495a92014f8f #x4a967b26229bca6a234344f63eb4272f83254e45e #x379eb8961d496aaba2b732d1215b3cfc62773da3f #x029ccd4e3a372a2cf1a96f205583e5b85ec762f74 #x304d311f55a40fed97677d56634a1615c56db96be ) ;; [B-163,SHA-256] #| Msg = 29bf9800a1d491700fcc66640b0e9e54ee12dc05456dfad5d5726bf5d4aeb605 d = 09b9bcd6a80841c1163dd1ea86fd86a1ee7399942 Qx = 35ef74e1627d99fe9aee967e5f2cd687c77cbdf3b Qy = 435d36c7daba700a2030ab517eee552a1eab5ea30 k = 2af314a74ae776920a1dff218ec40ece8f6ca91fb R = 3b2615f9da8e6fd395c2f0c599a0fb661b298a232 S = 0c7aaa87ebdea0f90d47768cc43cee0608e0819a7 |# (test-ecdsa NIST-B-163 no-32 #x29bf9800a1d491700fcc66640b0e9e54ee12dc05456dfad5d5726bf5d4aeb605 #x09b9bcd6a80841c1163dd1ea86fd86a1ee7399942 #x35ef74e1627d99fe9aee967e5f2cd687c77cbdf3b #x435d36c7daba700a2030ab517eee552a1eab5ea30 #x2af314a74ae776920a1dff218ec40ece8f6ca91fb #x3b2615f9da8e6fd395c2f0c599a0fb661b298a232 #x0c7aaa87ebdea0f90d47768cc43cee0608e0819a7 ) ;; [B-163,SHA-384] #| Msg = 14b5a3cedb0364638b045e87adf5d324e658b528a0384473fb742cea62298aa5160974fee9e783b118f06e4599f20b16 d = 02526cdb99e6dfa06045bba0648b2282e0a9a5af1 Qx = 75224b91ef03cd8071fd777080e2c30380f941777 Qy = 777f007985f627c91259560964585a6c1fb1513cc k = 0e46ed9f90c268a7ce04273376390d9af3e787218 R = 1c8fe41a22eb05873a577332cca66130d57904836 S = 043e74e4f4cf2b890693ab5c8da788dbfbb9b8621 |# (test-ecdsa NIST-B-163 no-48 #x14b5a3cedb0364638b045e87adf5d324e658b528a0384473fb742cea62298aa5160974fee9e783b118f06e4599f20b16 #x02526cdb99e6dfa06045bba0648b2282e0a9a5af1 #x75224b91ef03cd8071fd777080e2c30380f941777 #x777f007985f627c91259560964585a6c1fb1513cc #x0e46ed9f90c268a7ce04273376390d9af3e787218 #x1c8fe41a22eb05873a577332cca66130d57904836 #x043e74e4f4cf2b890693ab5c8da788dbfbb9b8621 ) ;; [B-163,SHA-512] #| Msg = 42bd852de94dfb20fa365626b15ed4560a88535c3a5035e6078e42e1b18f9119d11f99f61bb1ce55a30ab0a23a6da6df876abb400b1581990d6415c04e3ddec2 d = 041bdf12d45017fe825a30247ad18a2884e44cb59 Qx = 7361b76f8060c1c5d05d46ade8fd82ff887861c24 Qy = 0b7e43da4aca8dc5ef4bd501f09496cec335f4736 k = 313f6b8eff840039c1d3f73b03c3456aefcc1727a R = 1db9b939df8762b5af3f592c929c1a795ee2fa193 S = 2b72d2c570d95ac68dba5de51cca21beaea9ad200 |# (test-ecdsa NIST-B-163 no-64 #x42bd852de94dfb20fa365626b15ed4560a88535c3a5035e6078e42e1b18f9119d11f99f61bb1ce55a30ab0a23a6da6df876abb400b1581990d6415c04e3ddec2 #x041bdf12d45017fe825a30247ad18a2884e44cb59 #x7361b76f8060c1c5d05d46ade8fd82ff887861c24 #x0b7e43da4aca8dc5ef4bd501f09496cec335f4736 #x313f6b8eff840039c1d3f73b03c3456aefcc1727a #x1db9b939df8762b5af3f592c929c1a795ee2fa193 #x2b72d2c570d95ac68dba5de51cca21beaea9ad200 )
false
aba616f06749cdb30bc9b0c92ad32417a581f27e
378e5f5664461f1cc3031c54d243576300925b40
/rsauex/packages/minipro.scm
997057632bf43a9d7f45c73491afc42bb9778025
[]
no_license
rsauex/dotfiles
7a787f003a768699048ffd068f7d2b53ff673e39
77e405cda4277e282725108528874b6d9ebee968
refs/heads/master
2023-08-07T17:07:40.074456
2023-07-30T12:59:48
2023-07-30T12:59:48
97,400,340
2
0
null
null
null
null
UTF-8
Scheme
false
false
2,563
scm
minipro.scm
(define-module (rsauex packages minipro) #:use-module ((gnu packages libusb) #:prefix libusb:) #:use-module ((gnu packages pkg-config) #:prefix pkg-config:) #:use-module ((guix build-system gnu)) #:use-module ((guix gexp)) #:use-module ((guix git-download)) #:use-module ((guix licenses) #:prefix licenses:) #:use-module ((guix packages))) (define-public minipro (let ((version "0.6") (commit "9db72e929c9ba98ea5ca9ffb72a684b534b770ec") (commit-short "9db72e92") (commit-date "2023-04-03 00:00:00 +000")) (package (name "minipro") (version (string-append version "-" commit-short)) (source (origin (method git-fetch) (uri (git-reference (url "https://gitlab.com/DavidGriffith/minipro") (commit commit))) (sha256 (base32 "192j0sl771ifrjzd6whp6ysnhivss7b7y01z068zckxy8imslx50")))) (build-system gnu-build-system) (arguments (list #:tests? #f #:make-flags #~(list (string-append "VERSION=" #$version) (string-append "GIT_BRANCH=" #$version) (string-append "GIT_HASH=" #$commit) (string-append "GIT_HASH_SHORT=" #$commit-short) (string-append "GIT_DATE=" #$commit-date) (string-append "PREFIX=" #$output) (string-append "UDEV_DIR=" #$output "/lib/udev") (string-append "COMPLETIONS_DIR=" #$output "/share/bash-completion/completions") (string-append "PKG_CONFIG=" #$(this-package-native-input "pkg-config") "/bin/pkg-config")) #:phases #~(modify-phases %standard-phases (delete 'configure)))) (native-inputs `(("pkg-config" ,pkg-config:pkg-config))) (inputs `(("libusb" ,libusb:libusb))) (synopsis "An open source program for controlling the MiniPRO TL866xx series of chip programmers.") (description "This program exists because the manufacturer of the MiniPRO TL866xx series of chip programmers does not provide a program for use on Linux or other flavors of Unix. We who keep this project going prefer a simple, free, and open-source program that presents a command-line interface that allows for a GUI front-end if desired.") (home-page "https://gitlab.com/DavidGriffith/minipro") (license licenses:gpl3))))
false
ba8a6193a5a86208092039a3cf2831c96a418a89
2ea224bcc26280406c4cc23f0efcb4130578cc74
/preludes/chicken.scm
a50aa06a9cc2514bec69fe01929fb5cdb1cfe53a
[]
no_license
dcurrie/r7rs-coverage
749168a7dad8a3024854d58e4896f75a806b35b8
23a090998db3dbbf1c0110e9b0f8da5784cd4315
refs/heads/master
2021-06-08T13:44:51.442016
2016-10-24T19:04:59
2016-10-24T19:04:59
100,296,173
1
0
null
2017-08-14T18:11:22
2017-08-14T18:11:22
null
UTF-8
Scheme
false
false
101
scm
chicken.scm
(use r7rs) (import (scheme complex)) (define (assert x) (unless x (error "assertion failed")))
false
1068e4f716527f453510db0a37679a4a0ae55358
9b2eb10c34176f47f7f490a4ce8412b7dd42cce7
/lib-runtime/generic/std/list-copy.scm
b911d224eeea59ea813fa0a44de2d81149f72cf9
[ "LicenseRef-scancode-public-domain", "CC0-1.0" ]
permissive
okuoku/yuni
8be584a574c0597375f023c70b17a5a689fd6918
1859077a3c855f3a3912a71a5283e08488e76661
refs/heads/master
2023-07-21T11:30:14.824239
2023-06-11T13:16:01
2023-07-18T16:25:22
17,772,480
36
6
CC0-1.0
2020-03-29T08:16:00
2014-03-15T09:53:13
Scheme
UTF-8
Scheme
false
false
324
scm
list-copy.scm
(define (list-copy/itr! cur lis) (cond ((pair? lis) (let ((c (cons (car lis) '()))) (set-cdr! cur c) (list-copy/itr! c (cdr lis)))) (else (set-cdr! cur lis)))) (define (list-copy obj) (if (pair? obj) (let ((c (cons (car obj) '()))) (list-copy/itr! c (cdr obj)) c) obj))
false
ffcad9b623982baab81cb587b16a6e8ad171f342
eb32c279a34737c769d4e2c498a62c761750aeb5
/lyonesse/parsing/parser.scm
14b0571db26bb265b7d17405d67a61bc3976d178
[ "Apache-2.0" ]
permissive
theschemer/lyonesse
baaf340be710f68b84c1969befc6ddbd2be3739b
9d9624e3141ea3acaa670526cbe52c2d6546beef
refs/heads/master
2021-06-10T02:58:28.040995
2016-11-29T21:28:11
2016-11-29T21:28:11
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,083
scm
parser.scm
(library (lyonesse parsing parser) (export define-parser) (import (rnrs base (6)) (rnrs syntax-case (6)) (only (rnrs io ports (6)) get-char) (only (lyonesse functional) pipe)) (define-syntax define-parser (lambda (x) (syntax-case x (else) [(_ (<name> <ch>) [<pred> <next> (<mutation1> ...)] ... [else <enext> (<emutation1> ...)]) (syntax (define (<name> state input) (let ([<ch> (get-char input)]) (cond [(<pred> <ch>) (<next> (pipe state <mutation1> ...) input)] ... [else (<enext> (pipe state <emutation1> ...) input)]))))] [(_ (<name> <ch>) [<pred> <next> (<mutation1> ...)] ...) (syntax (define (<name> state input) (let ([<ch> (get-char input)]) (cond [(<pred> <ch>) (<next> (pipe state <mutation1> ...) input)] ...))))]))) )
true
551b516fef6a739885e07de93443ff227d908094
acc632afe0d8d8b94b781beb1442bbf3b1488d22
/deps/utf8/utf8-case-map.scm
06d099d9cd113a8715bdd4758122ce182a73be51
[]
no_license
kdltr/life-is-so-pretty
6cc6e6c6e590dda30c40fdbfd42a5a3a23644794
5edccf86702a543d78f8c7e0f6ae544a1b9870cd
refs/heads/master
2021-01-20T21:12:00.963219
2016-05-13T12:19:02
2016-05-13T12:19:02
61,128,206
1
0
null
null
null
null
UTF-8
Scheme
false
false
11,176
scm
utf8-case-map.scm
;;;; utf8-case-map.scm -- Unicode locale-aware case-mappings ;; ;; Copyright (c) 2004-2010 Alex Shinn. All rights reserved. ;; BSD-style license: http://synthcode.com/license.txt ;; Usage: ;; ;; (utf8-string-upcase str-or-port [locale]) ;; (utf8-string-downcase str-or-port [locale]) ;; (utf8-string-titlecase str-or-port [locale]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (declare (no-bound-checks) (no-procedure-checks) ) (module utf8-case-map ( char-upcase-single char-downcase-single char-titlecase-single char-downcase* char-upcase* char-titlecase* utf8-string-upcase utf8-string-downcase utf8-string-titlecase) (import scheme chicken extras ports posix srfi-4 utf8-lolevel (except utf8-srfi-14 char-set:hex-digit) unicode-char-sets) (require-library posix srfi-4 utf8-lolevel utf8-srfi-14 unicode-char-sets) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define *data-file-path* (list "./data" (repository-path))) (define (find-data-file name) (let lp ((ls *data-file-path*)) (and (pair? ls) (let ((path (string-append (car ls) "/" name))) (if (file-exists? path) path (lp (cdr ls))))))) (define char->ucs char->integer) (define ucs->char integer->char) (define read-binary-uint32-le ;; files distributed as little-endian in egg (lambda (port) (let* ((b1 (read-byte port)) (b2 (read-byte port)) (b3 (read-byte port)) (b4 (read-byte port))) (if (eof-object? b4) b4 (bitwise-ior b1 (arithmetic-shift b2 8) (arithmetic-shift b3 16) (arithmetic-shift b4 24)))))) (define read-binary-uint16-le ;; files distributed as little-endian in egg (lambda (port) (let* ((b1 (read-byte port)) (b2 (read-byte port))) (if (eof-object? b2) b2 (bitwise-ior b1 (arithmetic-shift b2 8)))))) ;; currently only defined for u16 and u32 vectors (define (read-block! vec port) (cond ((u16vector? vec) (let ((len (u16vector-length vec))) (do ((i 0 (+ i 1))) ((= i len)) (u16vector-set! vec i (read-binary-uint16-le port))))) ((u32vector? vec) (let ((len (u32vector-length vec))) (do ((i 0 (+ i 1))) ((= i len)) (u32vector-set! vec i (read-binary-uint32-le port))))) (else (error 'read-block! "unsupported type" vec)))) (define (with-string-io* s thunk) (with-output-to-string (lambda () (with-input-from-port (if (string? s) (open-input-string s) s) thunk)))) (define (display-utf8 x) (if (char? x) (write-utf8-char x) (display x))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; simple case conversions (define *char-case-file-1* "case-map-1.dat") (define *char-case-table-1* (or (condition-case (and-let* ((file (find-data-file *char-case-file-1*)) (size (file-size file)) (vec (make-u32vector (quotient size 4)))) (call-with-input-file file (cut read-block! vec <>) #:binary) vec) (var () #f)) (begin (warning "couldn't load case-map-1.dat") (make-u32vector 0)))) (define *char-case-count-1* (- (quotient (u32vector-length *char-case-table-1*) 4) 1)) (define (char-case-index tab i) (if (zero? (u32vector-length tab)) 0 (do ((j 0 (+ j 4))) ((>= (u32vector-ref tab j) i) (quotient j 4))))) (define (char-case-search tab i off . opt) (let-optionals* opt ((lo 0) (hi *char-case-count-1*)) (and (>= hi lo) (cond ((= i (u32vector-ref tab (* lo 4))) (u32vector-ref tab (+ (* lo 4) off))) ((= i (u32vector-ref tab (* hi 4))) (u32vector-ref tab (+ (* hi 4) off))) (else (let loop ((a lo) (b hi)) (if (= a b) #f (let* ((mid (+ a (quotient (- b a) 2))) (ind (* mid 4)) (val (u32vector-ref tab ind))) (cond ((< i val) (if (= mid b) #f (loop a mid))) ((> i val) (if (= mid a) #f (loop mid b))) (else (u32vector-ref tab (+ ind off)))))))))))) ;; just inline these two indexes for speed (define *index-2500* (char-case-index *char-case-table-1* #x2500)) (define *index-FF20* (char-case-index *char-case-table-1* #xFF20)) (define (char-map-single-case i off) (cond ((< i 128) #f) ((< i #x2500) (and-let* ((j (char-case-search *char-case-table-1* i off 0 *index-2500*))) (ucs->char j))) ((> i #xFF20) (and-let* ((j (char-case-search *char-case-table-1* i off *index-FF20* *char-case-count-1*))) (ucs->char j))) (else #f))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; special casing (define *char-case-file-2* "case-map-2.dat") (define *char-case-table-2* (or (and-let* ((file (find-data-file *char-case-file-2*))) (condition-case (with-input-from-file file read) (var () #f))) (begin (warning "couldn't load case-map-2.dat") '#()))) (define *char-case-length-2* (vector-length *char-case-table-2*)) (define (char-map-multi-case i off) (let loop ((a 0) (b *char-case-length-2*)) (if (= a b) #f (let* ((mid (+ a (quotient (- b a) 2))) (vec (vector-ref *char-case-table-2* mid)) (val (vector-ref vec 0))) (cond ((< i val) (if (= mid b) #f (loop a mid))) ((> i val) (if (= mid a) #f (loop mid b))) (else (vector-ref vec off))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; interface ;; returns a single char (define (char-upcase-single c) (let ((i (char->ucs c))) (if (< i 128) (char-upcase c) (or (char-map-single-case i 1) c)))) (define (char-downcase-single c) (let ((i (char->ucs c))) (if (< i 128) (char-downcase c) (or (char-map-single-case i 2) c)))) (define (char-titlecase-single c) (let ((i (char->ucs c))) (if (< i 128) (char-upcase c) (or (char-map-single-case i 3) c)))) ;; may return a char or string (define (char-downcase* c) (or (char-map-multi-case (char->ucs c) 1) (char-downcase-single c))) (define (char-titlecase* c) (or (char-map-multi-case (char->ucs c) 2) (char-titlecase-single c))) (define (char-upcase* c) (or (char-map-multi-case (char->ucs c) 3) (char-upcase-single c))) (define (lang? opt . args) (and (pair? opt) (let ((lang (car opt))) (and (>= (string-length lang) 2) (let lp ((ls args)) (and (pair? ls) (or (let ((lang2 (car ls))) (and (eqv? (string-ref lang 0) (string-ref lang2 0)) (eqv? (string-ref lang 1) (string-ref lang2 1)))) (lp (cdr ls))))))))) (define grave-accent (char->utf8-string (ucs->char #x0300))) (define acute-accent (char->utf8-string (ucs->char #x0301))) (define tilde-accent (char->utf8-string (ucs->char #x0303))) (define dot-above (char->utf8-string (ucs->char #x0307))) (define dotted-capital-i (ucs->char #x0130)) (define dotless-small-i (ucs->char #x0131)) (define dotted-small-i (string-append "i" dot-above)) (define dotted-small-i/grave (string-append "i" dot-above grave-accent)) (define dotted-small-i/acute (string-append "i" dot-above acute-accent)) (define dotted-small-i/tilde (string-append "i" dot-above tilde-accent)) (define small-final-sigma (ucs->char #x03C2)) (define small-sigma (ucs->char #x03C3)) ;; takes an optional locale string (define (utf8-string-upcase str . opt) (with-string-io* str (lambda () (if (lang? opt "tr" "az") (let loop ((c (read-utf8-char))) (unless (eof-object? c) (display-utf8 (if (eqv? c #\i) dotted-capital-i (char-upcase* c))) (loop (read-utf8-char)))) (let loop ((c (read-utf8-char))) (unless (eof-object? c) (display-utf8 (char-upcase* c)) (loop (read-utf8-char)))))))) (define (char-downcase-locale c next opt) (or (case (char->ucs c) ;; Final Sigma ((#x03A3) (if (and (char? next) (char-set-contains? char-set:greek next)) small-sigma small-final-sigma)) ;; Lithuanian (XXXX add More_Above logic) ((#x00CC) (and (lang? opt "lt") dotted-small-i/grave)) ((#x00CD) (and (lang? opt "lt") dotted-small-i/acute)) ((#x0128) (and (lang? opt "lt") dotted-small-i/tilde)) ;; Turkish and Azeri ((#x0130) (if (lang? opt "tr" "az") #\i dotted-small-i)) ((#x0307) (and (lang? opt "tr" "az") "")) ((#x0049) (and (lang? opt "tr" "az") dotless-small-i)) (else #f)) (char-downcase* c))) (define (utf8-string-downcase str . opt) (with-string-io* str (lambda () (let loop ((c (read-utf8-char))) (unless (eof-object? c) (let ((next (read-utf8-char))) (display-utf8 (char-downcase-locale c next opt)) (loop next))))))) ;; Note: there are some characters which define case mappings (such as ;; the circled latin letters), but which unicode doesn't consider ;; alphabetic. So the faster and more natural test for the alphabetic ;; property doesn't work, and we somewhat clumsily test whether or not ;; the characters are either upper or lowercase. ;; ;; An alternative approach is to explicitly compare the script property ;; of successive characters and start a new word when that property ;; changes. So a consecutive string of Greek letters followed ;; immediately by Latin characters would result in the first Greek ;; letter and first Latin character being uppercased, as opposed to just ;; the first Greek letter as we do now. (define (has-case? c) ;;(char-set-contains? char-set:alphabetic c) (or (char-set-contains? char-set:uppercase c) (char-set-contains? char-set:lowercase c))) (define (utf8-string-titlecase str . opt) (with-string-io* str (lambda () (letrec ((in-word (lambda (c) (unless (eof-object? c) (let ((next (read-utf8-char))) (display-utf8 (char-downcase-locale c next opt)) (if (has-case? c) (in-word next) (out-word next)))))) (out-word (lambda (c) (unless (eof-object? c) (let ((next (read-utf8-char))) (cond ((has-case? c) (display-utf8 (if (eqv? c #\i) (if (lang? opt "tr" "az") dotted-capital-i #\I) (char-titlecase* c))) (in-word next)) (else (display-utf8 c) (out-word next)))))))) (out-word (read-utf8-char)))))) )
false
5f60930f89d7a59fff36b3b15dd6b1c0a46c931a
17d83ab8f459552b7c05c446940ce644f905a5d0
/token.scm
2cd6e6d709e09110adad975d439b80bbe41aba0a
[]
no_license
nikokozak/static_chicken
194743dec42d932467ab6a9d5b86378c3a27e3bf
8a3ca34d2c4ed3b9b435be44cf5d615ff8d40101
refs/heads/master
2023-05-31T03:37:15.505675
2021-06-22T22:49:48
2021-06-22T22:49:48
379,402,114
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,507
scm
token.scm
;; "Tokens" ;; (make-token Dir ;; name ;; abs-path ;; rel-path ;; contents) (module token ((make-token *)) (import scheme (chicken module) (chicken base) (chicken syntax)) (reexport records) (reexport (only (chicken format) fprintf)) ;; Creates getter and setter templates for records. (define-for-syntax (accessor-defs-for name struct fields) (cond ((null? fields) '()) (else (cons `(define ,(symbol-append name '- (car fields)) (getter-with-setter (record-accessor ,struct ',(car fields)) (record-modifier ,struct ',(car fields)))) (accessor-defs-for name struct (cdr fields)))))) ;; Creates accessor templates for records. NOTE: the x in the accessor is hardcoded atm, ;; this is cheeky and should be changed pronto. (define-for-syntax (accessors-for name fields var) (cond ((null? fields) '()) (else (cons `(,(symbol-append name '- (car fields)) x) (accessors-for name (cdr fields) var))))) ;; Creates format string template for print function (define-for-syntax (format-string name fields) (let ((field-length (length fields))) (letrec ((draw-s (lambda (fields-left) (if (= 0 fields-left) "" (string-append "~s " (draw-s (sub1 fields-left))))))) (string-append "#(" (symbol->string name) " " (draw-s field-length) ")")))) ;; Defines a new #Record ;; eg. (make-token Test a b) ;; eg. (define rec (Test a b ...)) ;; eg. (test-a rec) => a ;; eg. (test-record? rec) => #t ;; eg. (set! (test-a rec) 10) => 10 ;; rec => #(test "a" "b") (define-syntax make-token (er-macro-transformer (lambda (expr replace compare?) (let* ((capitalize-symbol (lambda (symb) (string->symbol (list->string (map char-upcase (string->list (symbol->string symb))))))) (downcase-symbol (lambda (symb) (string->symbol (list->string (map char-downcase (string->list (symbol->string symb))))))) (name (cadr expr)) (upcase (capitalize-symbol (cadr expr))) (downcase (downcase-symbol (cadr expr))) (fields (cddr expr)) (token-printer `(lambda (x out) (fprintf out ,(format-string downcase fields) ,@(accessors-for downcase fields 'x))))) `(begin ;; (define TEST (make-record-type test '(field1 field2 ...))) (define ,upcase (make-record-type ',downcase '(,@fields))) ;; (define Test (record-constructor TEST)) (define ,name (record-constructor ,upcase)) ;; (define test-token? (record-predicate TEST)) (define ,(symbol-append downcase '-token?) (record-predicate ,upcase)) ;; (define test-field1 (getter-with-setter TEST (record-accessor TEST 'test-field1) ...)) ,@(accessor-defs-for downcase upcase fields) (set-record-printer! ',downcase ,token-printer)))))) ;; (make-token File ;; name ;; type ;; abs-path ;; rel-path) ;; (make-token Img ;; name ;; type ;; abs-path ;; rel-path ;; width ;; height ;; uid) )
true
3304d3e5097bc1cdec13a3595782dd827fbc3e01
92b8d8f6274941543cf41c19bc40d0a41be44fe6
/testsuite/sva31180.scm
2c56a9c8c923e387128ef92c6c0f3bbfca9f4c7b
[ "MIT" ]
permissive
spurious/kawa-mirror
02a869242ae6a4379a3298f10a7a8e610cf78529
6abc1995da0a01f724b823a64c846088059cd82a
refs/heads/master
2020-04-04T06:23:40.471010
2017-01-16T16:54:58
2017-01-16T16:54:58
51,633,398
6
0
null
null
null
null
UTF-8
Scheme
false
false
412
scm
sva31180.scm
;; Savannah bug #31180: exception in inline-compiler ;; Note this only failed in immediate mode, with foo exported but bar private. (module-export foo foo2) (module-static #t) (define (bar (port-number ::int) name) (list port-number name)) (define (foo port name) (bar port name)) ;; Savannah bug 31256: Verify error (define (foo2) ((bar2))) (define (bar2) (lambda () 100)) ;;Output: (5 foo) ;;Output: 100
false
a39e61e6e3c4a2c476b0282323e755fa68de4393
84bd214ba2422524b8d7738fb82dd1b3e2951f73
/02/2.37_MatrixOperations.scm
94ba25d9c6c62ca19ac6be081603f786495a40ec
[]
no_license
aequanimitas/sicp-redux
e5ef32529fa727de0353da973425a326e152c388
560b2bd40a12df245a8532de5d76b0bd2e033a64
refs/heads/master
2020-04-10T06:49:13.302600
2016-03-15T00:59:24
2016-03-15T00:59:24
21,434,389
1
0
null
null
null
null
UTF-8
Scheme
false
false
391
scm
2.37_MatrixOperations.scm
(define (accumulate initial combiner seq) (if (null? seq) initial (combiner (car seq) (accumulate initial combiner (cdr seq))))) (define matrix-example (list (list 1 2 3 4) (list 4 5 6 6) (list 6 7 8 9))) (define vector-example (list 6 7 8 9)) (define (dot-product v w) (accumulate 0 + (map * v w))) (dot-product vector-example vector-example) (define (transpose mat)
false
626b847aaedc5017547ae2f5437ec9632afff080
0768e217ef0b48b149e5c9b87f41d772cd9917f1
/heap/boot/macro/synpat.scm
08e02e2888a75be4913a348efef3d5ff64668737
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
fujita-y/ypsilon
e45c897436e333cf1a1009e13bfef72c3fb3cbe9
62e73643a4fe87458ae100e170bf4721d7a6dd16
refs/heads/master
2023-09-05T00:06:06.525714
2023-01-25T03:56:13
2023-01-25T04:02:59
41,003,666
45
7
BSD-2-Clause
2022-06-25T05:44:49
2015-08-19T00:05:35
Scheme
UTF-8
Scheme
false
false
7,440
scm
synpat.scm
;;; Copyright (c) 2004-2022 Yoshikatsu Fujita / LittleWing Company Limited. ;;; See LICENSE file for terms and conditions of use. (define ellipsis-id (make-parameter '...)) (define ellipsis-id? (lambda (form) (and (symbol? form) (eq? form (ellipsis-id))))) (define ellipsis-pair? (lambda (form) (and (pair? form) (pair? (cdr form)) (ellipsis-id? (cadr form))))) (define ellipsis-splicing-pair? (lambda (form) (and (pair? form) (pair? (cdr form)) (ellipsis-id? (cadr form)) (pair? (cddr form)) (ellipsis-id? (caddr form))))) (define ellipsis-quote? (lambda (form) (and (pair? form) (ellipsis-id? (car form)) (pair? (cdr form)) (null? (cddr form))))) (define underscore? (lambda (form lites) (and (eq? form '_) (not (memq '_ lites))))) (define collect-unique-macro-ids ; excluding ellipsis-id (lambda (expr) (let loop ((lst expr) (ans '())) (cond ((pair? lst) (loop (cdr lst) (loop (car lst) ans))) ((ellipsis-id? lst) ans) ((symbol? lst) (if (memq lst ans) ans (cons lst ans))) ((vector? lst) (loop (vector->list lst) ans)) (else ans))))) (define collect-vars-ranks (lambda (pat lites depth ranks) (cond ((underscore? pat lites) ranks) ((symbol? pat) (if (memq pat lites) ranks (acons pat depth ranks))) ((ellipsis-pair? pat) (collect-vars-ranks (cddr pat) lites depth (if (symbol? (car pat)) (acons (car pat) (+ depth 1) ranks) (collect-vars-ranks (car pat) lites (+ depth 1) ranks)))) ((pair? pat) (collect-vars-ranks (cdr pat) lites depth (collect-vars-ranks (car pat) lites depth ranks))) ((vector? pat) (collect-vars-ranks (vector->list pat) lites depth ranks)) (else ranks)))) (define check-pattern (lambda (pat lites) (define check-duplicate-variable (lambda (pat lites) (let loop ((lst pat) (pool '())) (cond ((pair? lst) (loop (cdr lst) (loop (car lst) pool))) ((ellipsis-id? lst) pool) ((underscore? lst lites) pool) ((symbol? lst) (if (memq lst lites) pool (if (memq lst pool) (syntax-violation "syntax pattern" "duplicate pattern variables" pat lst) (cons lst pool)))) ((vector? lst) (loop (vector->list lst) pool)) (else pool))))) (define check-misplaced-ellipsis (lambda (pat lites) (let loop ((lst pat)) (cond ((ellipsis-id? lst) (syntax-violation "syntax pattern" "improper use of ellipsis" pat)) ((ellipsis-pair? lst) (let loop ((lst (cddr lst))) (and (pair? lst) (if (ellipsis-id? (car lst)) (syntax-violation "syntax pattern" "ambiguous use of ellipsis" pat) (loop (cdr lst)))))) ((pair? lst) (and (ellipsis-id? (car lst)) (syntax-violation "syntax pattern" "improper use of ellipsis" lst)) (or (loop (car lst)) (loop (cdr lst)))) ((vector? lst) (loop (vector->list lst))) (else #f))))) (check-misplaced-ellipsis pat lites) (check-duplicate-variable pat lites))) (define match-ellipsis? (lambda (expr pat lites) (or (null? expr) (and (pair? expr) (match-pattern? (car expr) (car pat) lites) (match-ellipsis? (cdr expr) pat lites))))) (define match-ellipsis-n? (lambda (expr pat n lites) (or (= n 0) (and (pair? expr) (match-pattern? (car expr) (car pat) lites) (match-ellipsis-n? (cdr expr) pat (- n 1) lites))))) (define match-pattern? (lambda (expr pat lites) (cond ((underscore? pat lites) #t) ((symbol? pat) (cond ((memq pat lites) (and (or (symbol? expr) (identifier? expr)) (free-id=? pat expr))) (else #t))) ((ellipsis-pair? pat) (if (and (null? (cddr pat)) (list? expr)) (if (symbol? (car pat)) (or (null? expr) (not (memq (car pat) lites)) (every1 (lambda (e) (eq? (car pat) e)) expr)) (match-ellipsis? expr pat lites)) (let ((n (- (count-pair expr) (count-pair (cddr pat))))) (if (= n 0) (match-pattern? expr (cddr pat) lites) (and (> n 0) (match-ellipsis-n? expr pat n lites) (match-pattern? (list-tail expr n) (cddr pat) lites)))))) ((pair? pat) (and (pair? expr) (match-pattern? (car expr) (car pat) lites) (match-pattern? (cdr expr) (cdr pat) lites))) ((vector? pat) (and (vector? expr) (match-pattern? (vector->list expr) (vector->list pat) lites))) (else (equal? pat expr))))) (define union-vars (lambda (lites vars evars) (if (null? evars) vars (union-vars lites (bind-var! (caar evars) lites (reverse (cdar evars)) vars) (cdr evars))))) (define bind-var! (lambda (pat lites expr vars) (cond ((underscore? pat lites) vars) (else (let ((slot (assq pat vars))) (if slot (begin (set-cdr! slot (cons expr (cdr slot))) vars) (acons pat (list expr) vars))))))) (define bind-null-ellipsis (lambda (pat lites vars) (let loop ((lst (collect-unique-macro-ids (car pat))) (vars vars)) (if (null? lst) vars (loop (cdr lst) (if (memq (car lst) lites) vars (bind-var! (car lst) lites '() vars))))))) (define bind-ellipsis (lambda (expr pat lites vars evars) (if (null? expr) (if (null? evars) (bind-null-ellipsis pat lites vars) (union-vars lites vars evars)) (bind-ellipsis (cdr expr) pat lites vars (bind-pattern (car expr) (car pat) lites evars))))) (define bind-ellipsis-n (lambda (expr pat lites n vars evars) (if (= n 0) (if (null? evars) (bind-null-ellipsis pat lites vars) (union-vars lites vars evars)) (bind-ellipsis-n (cdr expr) pat lites (- n 1) vars (bind-pattern (car expr) (car pat) lites evars))))) (define bind-pattern (lambda (expr pat lites vars) (cond ((symbol? pat) (if (memq pat lites) vars (bind-var! pat lites expr vars))) ((ellipsis-pair? pat) (if (and (null? (cddr pat)) (list? expr)) (if (symbol? (car pat)) (bind-var! (car pat) lites expr vars) (bind-ellipsis expr pat lites vars '())) (let ((n (- (count-pair expr) (count-pair (cddr pat))))) (bind-pattern (list-tail expr n) (cddr pat) lites (if (and (= n 0) (symbol? (car pat))) (bind-var! (car pat) lites '() vars) (bind-ellipsis-n expr pat lites n vars '())))))) ((pair? pat) (bind-pattern (cdr expr) (cdr pat) lites (bind-pattern (car expr) (car pat) lites vars))) ((vector? pat) (bind-pattern (vector->list expr) (vector->list pat) lites vars)) (else vars))))
false
6173f69364aeea46a5d7b8722ac3b5a4b57f0532
b9a78cfb8741183486b7d41c8798013e07c47574
/fun/monads/mytools/r7rs-with-execption.scm
978ed53375a3358cfb131ba7674a6f043940448f
[ "MIT" ]
permissive
BernardTatin/ChickenAndShout
87229cc193eaff582782e1227805eac33929c3db
c715a5cd2ee45acfde386dad8fd66dc4415471c6
refs/heads/master
2020-12-30T09:49:53.935113
2019-12-05T09:19:09
2019-12-05T09:19:09
54,066,891
0
0
null
2017-01-01T20:51:06
2016-03-16T21:14:40
Scheme
UTF-8
Scheme
false
false
1,074
scm
r7rs-with-execption.scm
(define-library (mytools r7rs-with-execption) (export with-exception abort) (cond-expand (owl-lisp (import (owl core) (owl defmac) (owl base) (scheme base) (scheme write))) (else (import (scheme base) (scheme write)))) (begin (cond-expand ((or foment sagittarius chicken) (define-syntax with-exception (syntax-rules (letry lecatch) ((with-exception <return> (letry <dotry>) (lecatch <docatch>)) (call-with-current-continuation (lambda (<return>) (with-exception-handler <docatch> <dotry>))))))) (else (define-syntax with-exception (syntax-rules (letry lecatch) ((with-exception <return> (letry <dotry>) (lecatch <docatch>)) (let ((<return> (lambda(a) a))) (guard (exc (else (let ((f <docatch>)) ;; (display "[SYS ERROR] --> ") ;; (display exc) ;; (display "\n") (f exc)))) (let ((g <dotry>)) (g))))))))) (define abort (lambda(v) v)) ))
true
02cea3993917c2cf63042ef283ae3267ed94fc7a
8d2197af6ab9abe4e7767b424499aeae2331e3f6
/examples/outputs/malfunction/erased.scm
93824a1f95b0a067d64918141f587c0b073cbe78
[]
permissive
ziman/ttstar
ade772d6dd2b31b40b736bd36bd9ef585bd0d389
4ac6e124bddfbeaa133713d829dccaa596626be6
refs/heads/master
2021-09-08T23:20:19.446353
2019-06-30T19:17:02
2019-06-30T19:17:02
35,721,993
19
1
BSD-3-Clause
2022-08-09T13:28:36
2015-05-16T11:58:56
Idris
UTF-8
Scheme
false
false
3,486
scm
erased.scm
(import (chicken process-context)) (require-extension matchable) (define Type '(Type)) (define (number->peano z s i) (if (= i 0) (list z) (list s (number->peano z s (- i 1))))) (define (rts-arg-peano z s i) (number->peano z s (string->number (list-ref (command-line-arguments) i)))) (define (rts-arg-read i) (read (open-input-string (list-ref (command-line-arguments) i)))) (print (letrec* ( (True `(True)) (False `(False)) (MkPair (lambda (_x7) (lambda (_x8) `(MkPair ,_x7 ,_x8)))) (snd (lambda (_e0) (match (list _e0) (((_ x y)) y)))) (MkSt (lambda (run) `(MkSt ,run))) (runState (lambda (_e0) (match (list _e0) (((_ run)) run)))) (execState (lambda (x) (lambda (s) (snd ((runState x) s))))) (stGet (MkSt (lambda (s) ((MkPair s) s)))) (stReturn (lambda (x) (MkSt (lambda (s) ((MkPair s) x))))) (stBind (lambda (_e0) (lambda (_e1) (match (list _e0 _e1) (((_ f) g) (letrec* ( (stBind3 (lambda (_e0) (lambda (_e1) (match (list _e0 _e1) ((s (_ f)) (f s)))))) (stBind2 (lambda (_e0) (lambda (_e1) (match (list _e0 _e1) ((g (_ s x)) ((stBind3 s) (g x))))))) ) (MkSt (lambda (s) ((stBind2 g) (f s)))))))))) (ioWrapImpure (lambda (impureF) ((stBind stGet) (lambda (w) (stReturn (impureF w)))))) (unsafePerformIO (lambda (x) (letrec* ((TheWorld `(TheWorld))) ((execState x) TheWorld)))) (int1 1) (int0 0) (plusInt (lambda ($x $y) (+ $x $y))) (minusInt (lambda ($x $y) (- $x $y))) (timesInt (lambda ($x $y) (* $x $y))) (intToString (global $Pervasives $string_of_int)) (ifRaw (lambda ($x $then $else) (switch $x (0 $else) (_ $then)))) (isZero (lambda (x) (((ifRaw x) False) True))) (isNonzero (lambda (x) (((ifRaw x) True) False))) (eqInt (lambda (x) (lambda (y) (letrec* ((eqInt_I (lambda ($x $y) (== $x $y)))) (isNonzero ((eqInt_I x) y)))))) (printString (lambda (s) (letrec* ((nativePrint (global $Pervasives $print_endline))) (ioWrapImpure (lambda (w) (nativePrint s)))))) (printInt (lambda (i) (printString (intToString i)))) (sumFor (lambda (n) (lambda (f) (letrec* ((_cf0 (lambda (_e0) (match (list _e0) ((('True)) int0) ((('False)) ((plusInt (f n)) ((sumFor ((minusInt n) int1)) f))))))) (_cf0 (isZero n)))))) (boolToInt (lambda (_e0) (match (list _e0) ((('True)) int1) ((('False)) int0)))) (isPythag (lambda (x) (lambda (y) (lambda (z) (boolToInt ((eqInt ((timesInt x) x)) ((plusInt ((timesInt y) y)) ((timesInt z) z)))))))) (pythag (lambda (n) ((sumFor n) (lambda (x) ((sumFor x) (lambda (y) ((sumFor y) (lambda (z) (((isPythag x) y) z))))))))) (main (unsafePerformIO (letrec* ( (int2 ((plusInt int1) int1)) (int4 ((timesInt int2) int2)) (int16 ((timesInt int4) int4)) (int256 ((timesInt int16) int16)) (int512 ((timesInt int256) int2)) ) (printInt (pythag int512))))) ) main))
false
3bdae495214137b551417fd84275a8301827ae62
af3b4c56ca4b1b891cb10f08bd71555181f256d5
/fatal/a9.scm
19bddfdcd7bd1a7150fd1cb4371b0a3edb78df75
[]
no_license
fangyuchen86/c311
7a9cd8b86072cc041b94e510faf33ff4c0075592
7da206f36922d876264f5f194a7a7dba789bde71
refs/heads/master
2020-12-28T21:39:56.087636
2014-12-05T06:17:21
2014-12-05T06:17:21
28,654,072
0
2
null
null
null
null
UTF-8
Scheme
false
false
3,991
scm
a9.scm
#| Samuel Waggoner srwaggon @ indiana.edu CSCI C311 Programming Languages Assignment 9 Fatal Assignment 10/11/7 |# (load "parenthec.ss") (define-union exp (const n) (var v) (if test conseq alt) (mult rand1 rand2) (sub1 rand) (zero rand) (letcc body) (throw vexp kexp) (let vexp body) (lambda body) (app rator rand)) (define value-of (lambda (expr env) (union-case expr exp [(const n) n] [(var v) (apply-env env v)] [(if test conseq alt) (if (value-of test env) (value-of conseq env) (value-of alt env))] [(mult rand1 rand2) (* (value-of rand1 env) (value-of rand2 env))] [(sub1 rand) (- (value-of rand env) 1)] [(zero rand) (zero? (value-of rand env))] [(letcc body) (call/cc (lambda (k) (value-of body (envr_extend k env))))] [(throw vexp kexp) ((value-of kexp env) (value-of vexp env))] [(let vexp body) (value-of body (envr_extend (value-of vexp env) env))] [(lambda body) (clos_closure body env)] [(app rator rand) (apply-proc (value-of rator env) (value-of rand env))]))) (define-union envr (empty) (extend arg env)) (define apply-env (lambda (env num) (union-case env envr [(empty) (error 'env "unbound variable")] [(extend arg env) (if (zero? num) arg (apply-env env (sub1 num)))]))) (define-union clos (closure code env)) (define apply-proc (lambda (c a) (union-case c clos [(closure code env) (value-of code (envr_extend a env))]))) ; Factorial of 5...should be 120. (pretty-print (value-of (exp_app (exp_lambda (exp_app (exp_app (exp_var 0) (exp_var 0)) (exp_const 5))) (exp_lambda (exp_lambda (exp_if (exp_zero (exp_var 0)) (exp_const 1) (exp_mult (exp_var 0) (exp_app (exp_app (exp_var 1) (exp_var 1)) (exp_sub1 (exp_var 0)))))))) (envr_empty))) ; Test of letcc and throw...should evaluate to 24. (pretty-print (value-of (exp_mult (exp_const 2) (exp_letcc (exp_mult (exp_const 5) (exp_throw (exp_mult (exp_const 2) (exp_const 6)) (exp_var 0))))) (envr_empty))) ;; (let ([fact (lambda (f) ;; (lambda (n) ;; (if (zero? n) ;; 1 ;; (* n ((f f) (sub1 n))))))]) ;; ((fact fact) 5)) (pretty-print (value-of (exp_let (exp_lambda (exp_lambda (exp_if (exp_zero (exp_var 0)) (exp_const 1) (exp_mult (exp_var 0) (exp_app (exp_app (exp_var 1) (exp_var 1)) (exp_sub1 (exp_var 0))))))) (exp_app (exp_app (exp_var 0) (exp_var 0)) (exp_const 5))) (envr_empty)))
false
6170d802cf73206c1131e6bd349607f75dcd0553
140a499a12332fa8b77fb738463ef58de56f6cb9
/worlds/core/verbcode/47/find-verb-3.scm
4e722a63d621adb740c759a4902c1bda7129f2bf
[ "MIT" ]
permissive
sid-code/nmoo
2a5546621ee8c247d4f2610f9aa04d115aa41c5b
cf504f28ab473fd70f2c60cda4d109c33b600727
refs/heads/master
2023-08-19T09:16:37.488546
2023-08-15T16:57:39
2023-08-15T16:57:39
31,146,820
10
0
null
null
null
null
UTF-8
Scheme
false
false
574
scm
find-verb-3.scm
(let ((obj (get args 0)) (name (get args 1)) (arg-spec (get args 2 nil)) (verb-list (verbs obj)) (num-verbs (len verb-list))) (get ($listutils:filter (lambda (idx) (let ((verb-name (get verb-list idx))) (and ($verbutils:verbname-matches? verb-name name) (if (nil? arg-spec) 1 (= arg-spec (getverbargs obj idx)))))) (range 0 (- num-verbs 1))) 0 nil))
false
1648728cdd57a867948039435995d9b81b6958ec
58f60306f9f5638fbb23ec8b6ff896c191da48d4
/3rd_party/s7/lint.scm
c4e0cc6b689389a59f24bb94b2dc1b3f3db202a0
[ "MIT" ]
permissive
mojmir-svoboda/BlackBoxTT
650cd9da608a9909da32dc88a362affe3df50320
0c87b989827107695538e1bf1266c08b083dda44
refs/heads/master
2021-01-23T22:00:11.999135
2018-01-04T20:54:42
2018-01-04T20:54:42
58,350,784
11
3
null
null
null
null
UTF-8
Scheme
false
false
726,079
scm
lint.scm
;;; lint for s7 scheme ;;; ;;; (lint "file.scm") checks file.scm for infelicities ;;; to control the kinds of checks, set the variables below. ;;; for tests and examples, see lint-test in s7test.scm (provide 'lint.scm) (define *report-unused-parameters* #f) ; many of these are reported anyway if they are passed some non-#f value (define *report-unused-top-level-functions* #f) ; very common in Scheme, but #t makes the ghastly leakage of names obvious (define *report-shadowed-variables* #f) ; shadowed parameters, etc (define *report-undefined-identifiers* #f) ; names we can't account for (define *report-multiply-defined-top-level-functions* #f) ; top-level funcs defined in more than one file (define *report-nested-if* 4) ; 3 is lowest, this sets the nesting level that triggers an if->cond suggestion (define *report-short-branch* 12) ; controls when a lop-sided if triggers a reordering suggestion (define *report-one-armed-if* 90) ; if -> when/unless, can be #f/#t; if an integer, sets tree length which triggers revision (80 is too small) (define *report-loaded-files* #f) ; if load is encountered, include that file in the lint process (define *report-any-!-as-setter* #t) ; unknown funcs/macros ending in ! are treated as setters (define *report-function-stuff* #t) ; checks for missed function uses etc (define *report-doc-strings* #f) ; old-style (CL) doc strings (define *report-func-as-arg-arity-mismatch* #f) ; as it says... (slow, and this error almost never happens) (define *report-constant-expressions-in-do* #f) ; kinda dumb (define *report-bad-variable-names* '(l ll O ~)) ; bad names -- a list to check such as: ;;; '(l ll .. ~ data datum new item info temp tmp temporary val vals value foo bar baz aux dummy O var res retval result count str) (define *report-built-in-functions-used-as-variables* #f) ; string and length are the most common cases (define *report-forward-functions* #f) ; functions used before being defined (define *report-sloppy-assoc* #t) ; i.e. (cdr (assoc x y)) and the like (define *report-bloated-arg* 24) ; min arg expr tree size that can trigger a rewrite-as-let suggestion (define *lint* #f) ; the lint let ;; this gives other programs a way to extend or edit lint's tables: for example, the ;; table of functions that are simple (no side effects) is (*lint* 'no-side-effect-functions) ;; see snd-lint.scm. ;;; -------------------------------------------------------------------------------- (when (provided? 'pure-s7) (define (make-polar mag ang) (complex (* mag (cos ang)) (* mag (sin ang)))) (define (char-ci=? . chars) (apply char=? (map char-upcase chars))) (define (char-ci<=? . chars) (apply char<=? (map char-upcase chars))) (define (char-ci>=? . chars) (apply char>=? (map char-upcase chars))) (define (char-ci<? . chars) (apply char<? (map char-upcase chars))) (define (char-ci>? . chars) (apply char>? (map char-upcase chars))) (define (string-ci=? . strs) (apply string=? (map string-upcase strs))) (define (string-ci<=? . strs) (apply string<=? (map string-upcase strs))) (define (string-ci>=? . strs) (apply string>=? (map string-upcase strs))) (define (string-ci<? . strs) (apply string<? (map string-upcase strs))) (define (string-ci>? . strs) (apply string>? (map string-upcase strs))) (define (let->list e) (if (let? e) (reverse! (map values e)) (error 'wrong-type-arg "let->list argument should be an environment: ~A" str)))) (format *stderr* "loading lint.scm~%") (set! reader-cond #f) (define-macro (reader-cond . clauses) `(values)) ; clobber reader-cond to avoid (incorrect) unbound-variable errors #| ;; debugging version (define-expansion (lint-format str caller . args) `(begin (format outport "lint.scm line ~A~%" ,(port-line-number)) (lint-format-1 ,str ,caller ,@args))) (define-expansion (lint-format* caller . args) `(begin (format outport "lint.scm line ~A~%" ,(port-line-number)) (lint-format*-1 ,caller ,@args))) |# (define-macro (let*-temporarily vars . body) `(with-let (#_inlet :orig (#_curlet) :saved (#_list ,@(map car vars))) (dynamic-wind (lambda () #f) (lambda () (with-let orig ,@(map (lambda (v) `(set! ,(car v) ,(cadr v))) vars) ,@body)) (lambda () ,@(map (let ((ctr -1)) (lambda (v) (if (symbol? (car v)) `(set! (orig ',(car v)) (list-ref saved ,(set! ctr (+ ctr 1)))) `(set! (with-let orig ,(car v)) (list-ref saved ,(set! ctr (+ ctr 1))))))) vars))))) (define-macro (let-temporarily vars . body) `(with-let (#_inlet :orig (#_curlet) :saved (#_list ,@(map car vars)) :new (#_list ,@(map cadr vars))) (dynamic-wind (lambda () #f) (lambda () ; this could be (with-let orig (let ,vars ,@body)) but I want to handle stuff like individual vector locations ,@(map (let ((ctr -1)) (lambda (v) (if (symbol? (car v)) `(set! (orig ',(car v)) (list-ref new ,(set! ctr (+ ctr 1)))) `(set! (with-let orig ,(car v)) (list-ref new ,(set! ctr (+ ctr 1))))))) vars) (with-let orig ,@body)) (lambda () ,@(map (let ((ctr -1)) (lambda (v) (if (symbol? (car v)) `(set! (orig ',(car v)) (list-ref saved ,(set! ctr (+ ctr 1)))) `(set! (with-let orig ,(car v)) (list-ref saved ,(set! ctr (+ ctr 1))))))) vars))))) ;;; -------------------------------------------------------------------------------- (define lint (let ((no-side-effect-functions (let ((ht (make-hash-table))) (for-each (lambda (op) (hash-table-set! ht op #t)) '(* + - / < <= = > >= abs acos acosh and angle append aritable? arity ash asin asinh assoc assq assv atan atanh begin boolean? byte-vector byte-vector? caaaar caaadr caaar caadar caaddr caadr caar cadaar cadadr cadar caddar cadddr caddr cadr call-with-input-string call-with-input-file c-pointer c-pointer? c-object? call-with-exit car case catch cdaaar cdaadr cdaar cdadar cdaddr cdadr cdar cddaar cddadr cddar cdddar cddddr cdddr cddr cdr ceiling char->integer char-alphabetic? char-ci<=? char-ci<? char-ci=? char-ci>=? char-ci>? char-downcase char-lower-case? char-numeric? char-position char-ready? char-upcase char-upper-case? char-whitespace? char<=? char<? char=? char>=? char>? char? complex complex? cond cons constant? continuation? cos cosh curlet current-error-port current-input-port current-output-port cyclic-sequences defined? denominator dilambda? do dynamic-wind eof-object? eq? equal? eqv? even? exact->inexact exact? exp expt float? float-vector float-vector-ref float-vector? floor for-each funclet gcd gensym gensym? ; why was gensym omitted earlier? hash-table hash-table* hash-table-entries hash-table-ref hash-table? help hook-functions if imag-part inexact->exact inexact? infinite? inlet input-port? int-vector int-vector-ref int-vector? iterator-at-end? iterator-sequence integer->char integer-decode-float integer-length integer? iterator? keyword->symbol keyword? lambda lambda* lcm let->list length let let* let-ref let? letrec letrec* list list->string list->vector list-ref list-tail list? log logand logbit? logior lognot logxor macro? magnitude make-byte-vector make-float-vector make-int-vector make-hash-table make-hook make-iterator make-keyword make-list make-polar make-rectangular make-shared-vector make-string make-vector map max member memq memv min modulo morally-equal? nan? negative? not null? number->string number? numerator object->string odd? openlet? or outlet output-port? owlet pair-line-number pair-filename pair? port-closed? port-filename port-line-number positive? procedure-documentation procedure-setter procedure-signature procedure-source procedure? proper-list? provided? quasiquote quote quotient random-state random-state->list random-state? rational? rationalize real-part real? remainder reverse rootlet round s7-version sequence? sin sinh square sqrt stacktrace string string->list string->number string->symbol string-append string-ci<=? string-ci<? string-ci=? string-ci>=? string-ci>? string-downcase string-length string-position string-ref string-upcase string<=? string<? string=? string>=? string>? string? sublet substring symbol symbol->dynamic-value symbol->keyword symbol->string symbol->value symbol? tan tanh tree-leaves truncate unless values vector vector-append vector->list vector-dimensions vector-length vector-ref vector? when with-baffle with-let with-input-from-file with-input-from-string with-output-to-string zero? #_{list} #_{apply_values} #_{append} unquote)) ;; do not include file-exists? or directory? ;; should this include peek-char or unlet ? ht)) (built-in-functions (let ((ht (make-hash-table))) (for-each (lambda (op) (hash-table-set! ht op #t)) '(symbol? gensym? keyword? let? openlet? iterator? constant? macro? c-pointer? c-object? input-port? output-port? eof-object? integer? number? real? complex? rational? random-state? char? string? list? pair? vector? float-vector? int-vector? byte-vector? hash-table? continuation? procedure? dilambda? boolean? float? proper-list? sequence? null? gensym symbol->string string->symbol symbol symbol->value symbol->dynamic-value symbol-access make-keyword symbol->keyword keyword->symbol outlet rootlet curlet unlet sublet varlet cutlet inlet owlet coverlet openlet let-ref let-set! make-iterator iterate iterator-sequence iterator-at-end? provided? provide defined? c-pointer port-line-number port-filename pair-line-number pair-filename port-closed? current-input-port current-output-port current-error-port let->list char-ready? close-input-port close-output-port flush-output-port open-input-file open-output-file open-input-string open-output-string get-output-string newline write display read-char peek-char write-char write-string read-byte write-byte read-line read-string read call-with-input-string call-with-input-file with-input-from-string with-input-from-file call-with-output-string call-with-output-file with-output-to-string with-output-to-file real-part imag-part numerator denominator even? odd? zero? positive? negative? infinite? nan? complex magnitude angle rationalize abs exp log sin cos tan asin acos atan sinh cosh tanh asinh acosh atanh sqrt expt floor ceiling truncate round lcm gcd + - * / max min quotient remainder modulo = < > <= >= logior logxor logand lognot ash random-state random inexact->exact exact->inexact integer-length make-polar make-rectangular logbit? integer-decode-float exact? inexact? random-state->list number->string string->number char-upcase char-downcase char->integer integer->char char-upper-case? char-lower-case? char-alphabetic? char-numeric? char-whitespace? char=? char<? char>? char<=? char>=? char-position string-position make-string string-ref string-set! string=? string<? string>? string<=? string>=? char-ci=? char-ci<? char-ci>? char-ci<=? char-ci>=? string-ci=? string-ci<? string-ci>? string-ci<=? string-ci>=? string-copy string-fill! list->string string-length string->list string-downcase string-upcase string-append substring string object->string format cons car cdr set-car! set-cdr! caar cadr cdar cddr caaar caadr cadar cdaar caddr cdddr cdadr cddar caaaar caaadr caadar cadaar caaddr cadddr cadadr caddar cdaaar cdaadr cdadar cddaar cdaddr cddddr cddadr cdddar assoc member list list-ref list-set! list-tail make-list length copy fill! reverse reverse! sort! append assq assv memq memv vector-append list->vector vector-fill! vector-length vector->list vector-ref vector-set! vector-dimensions make-vector make-shared-vector vector float-vector make-float-vector float-vector-set! float-vector-ref int-vector make-int-vector int-vector-set! int-vector-ref ->byte-vector byte-vector make-byte-vector hash-table hash-table* make-hash-table hash-table-ref hash-table-set! hash-table-entries cyclic-sequences call/cc call-with-current-continuation call-with-exit load autoload eval eval-string apply for-each map dynamic-wind values catch throw error procedure-documentation procedure-signature help procedure-source funclet procedure-setter arity aritable? not eq? eqv? equal? morally-equal? gc s7-version emergency-exit exit dilambda make-hook hook-functions stacktrace tree-leaves #_{list} #_{apply_values} #_{append} unquote)) ht)) (makers (let ((h (make-hash-table))) (for-each (lambda (op) (set! (h op) #t)) '(gensym sublet inlet make-iterator let->list random-state random-state->list number->string make-string string string-copy copy list->string string->list string-append substring object->string format cons list make-list reverse append vector-append list->vector vector->list make-vector make-shared-vector vector make-float-vector float-vector make-int-vector int-vector byte-vector hash-table hash-table* make-hash-table make-hook #_{list} #_{append} gentemp)) ; gentemp for other schemes h)) (non-negative-ops (let ((h (make-hash-table))) (for-each (lambda (op) (set! (h op) #t)) '(string-length vector-length abs magnitude denominator gcd lcm tree-leaves char->integer byte-vector-ref byte-vector-set! hash-table-entries write-byte char-position string-position pair-line-number port-line-number)) h)) (numeric-ops (let ((h (make-hash-table))) (for-each (lambda (op) (set! (h op) #t)) '(+ * - / sin cos tan asin acos atan sinh cosh tanh asinh acosh atanh log exp expt sqrt make-polar complex imag-part real-part abs magnitude angle max min exact->inexact modulo remainder quotient lcm gcd rationalize inexact->exact random logior lognot logxor logand numerator denominator floor round truncate ceiling ash)) h)) (bools (let ((h (make-hash-table))) (for-each (lambda (op) (set! (h op) #t)) '(symbol? integer? rational? real? number? complex? float? keyword? gensym? byte-vector? string? list? sequence? char? boolean? float-vector? int-vector? vector? let? hash-table? input-port? null? pair? proper-list? output-port? iterator? continuation? dilambda? procedure? macro? random-state? eof-object? c-pointer? unspecified? c-object? constant?)) h)) (booleans (let ((h (make-hash-table))) (for-each (lambda (op) (set! (h op) #t)) '(symbol? integer? rational? real? number? complex? float? keyword? gensym? byte-vector? string? list? sequence? char? boolean? float-vector? int-vector? vector? let? hash-table? input-port? null? pair? proper-list? output-port? iterator? continuation? dilambda? procedure? macro? random-state? eof-object? c-pointer? c-object? unspecified? exact? inexact? defined? provided? even? odd? char-whitespace? char-numeric? char-alphabetic? negative? positive? zero? constant? infinite? nan? char-upper-case? char-lower-case? directory? file-exists?)) h)) (reversibles (let ((h (make-hash-table))) (for-each (lambda (op) (set! (h (car op)) (cadr op))) '((< >) (> <) (<= >=) (>= <=) (* *) (+ +) (= =) (char=? char=?) (string=? string=?) (eq? eq?) (eqv? eqv?) (equal? equal?) (morally-equal? morally-equal?) (logand logand) (logxor logxor) (logior logior) (max max) (min min) (lcm lcm) (gcd gcd) (char<? char>?) (char>? char<?) (char<=? char>=?) (char>=? char<=?) (string<? string>?) (string>? string<?) (string<=? string>=?) (string>=? string<=?) (char-ci<? char-ci>?) (char-ci>? char-ci<?) (char-ci<=? char-ci>=?) (char-ci>=? char-ci<=?) (string-ci<? string-ci>?) (string-ci>? string-ci<?) (string-ci<=? string-ci>=?) (string-ci>=? string-ci<=?))) h)) (syntaces (let ((h (make-hash-table))) (for-each (lambda (op) (set! (h op) #t)) '(quote if begin let let* letrec letrec* cond case or and do set! unless when with-let with-baffle lambda lambda* define define* define-macro define-macro* define-bacro define-bacro* define-constant define-expansion)) h)) (outport #t) (linted-files ()) (big-constants (make-hash-table)) (equable-closures (make-hash-table)) (other-names-counts (make-hash-table)) (*e* #f) (other-identifiers (make-hash-table)) (quote-warnings 0) (last-simplify-boolean-line-number -1) (last-simplify-numeric-line-number -1) (last-simplify-cxr-line-number -1) (last-if-line-number -1) (last-checker-line-number -1) (last-cons-line-number -1) (last-rewritten-internal-define #f) (line-number -1) (pp-left-margin 4) (lint-left-margin 1) (*current-file* "") (*top-level-objects* (make-hash-table)) (*output-port* *stderr*) (*max-cdr-len* 16)) ; 40 is too high, 24 questionable, if #f the let+do rewrite is turned off (set! *e* (curlet)) (set! *lint* *e*) ; external access to (for example) the built-in-functions hash-table via (*lint* 'built-in-functions) ;; -------- lint-format -------- (define target-line-length 80) (define (truncated-list->string form) ;; return form -> string with limits on its length (let* ((str (object->string form)) (len (length str))) (if (< len target-line-length) str (do ((i (- target-line-length 6) (- i 1))) ((or (= i 40) (char-whitespace? (str i))) (string-append (substring str 0 (if (<= i 40) (- target-line-length 6) i)) "...")))))) (define lint-pp #f) ; avoid crosstalk with other schemes' definitions of pp and pretty-print (make-var also collides) (define lint-pretty-print #f) (let () (require write.scm) (set! lint-pp pp); (set! lint-pretty-print pretty-print)) (define (lists->string f1 f2) ;; same but 2 strings that may need to be lined up vertically (let ((str1 (object->string f1)) (str2 (object->string f2))) (let ((len1 (length str1)) (len2 (length str2))) (when (> len1 target-line-length) (set! str1 (truncated-list->string f1)) (set! len1 (length str1))) (when (> len2 target-line-length) (set! ((funclet lint-pretty-print) '*pretty-print-left-margin*) pp-left-margin) (set! ((funclet lint-pretty-print) '*pretty-print-length*) (- 114 pp-left-margin)) (set! str2 (lint-pp f2)) (set! len2 (length str2))) (format #f (if (< (+ len1 len2) target-line-length) (values "~A -> ~A" str1 str2) (values "~%~NC~A ->~%~NC~A" pp-left-margin #\space str1 pp-left-margin #\space str2)))))) (define (truncated-lists->string f1 f2) ;; same but 2 strings that may need to be lined up vertically and both are truncated (let ((str1 (object->string f1)) (str2 (object->string f2))) (let ((len1 (length str1)) (len2 (length str2))) (when (> len1 target-line-length) (set! str1 (truncated-list->string f1)) (set! len1 (length str1))) (when (> len2 target-line-length) (set! str2 (truncated-list->string f2)) (set! len2 (length str2))) (format #f (if (< (+ len1 len2) target-line-length) (values "~A -> ~A" str1 str2) (values "~%~NC~A ->~%~NC~A" pp-left-margin #\space str1 pp-left-margin #\space str2)))))) (define made-suggestion 0) (define (lint-format str caller . args) (let ((outstr (apply format #f (string-append (if (< 0 line-number 100000) "~NC~A (line ~D): " "~NC~A: ") str "~%") lint-left-margin #\space (truncated-list->string caller) (if (< 0 line-number 100000) (values line-number args) args)))) (set! made-suggestion (+ made-suggestion 1)) (display outstr outport) (if (> (length outstr) (+ target-line-length 40)) (newline outport)))) (define (lint-format* caller . strs) (let* ((outstr (format #f (if (< 0 line-number 100000) "~NC~A (line ~D): " "~NC~A:~A") lint-left-margin #\space (truncated-list->string caller) (if (< 0 line-number 100000) line-number " "))) (current-end (length outstr))) ;; (set! made-suggestion (+ made-suggestion 1)) (display outstr outport) (for-each (lambda (s) (let ((len (length s))) (if (> (+ len current-end) target-line-length) (begin (format outport "~%~NC~A" (+ lint-left-margin 4) #\space s) (set! current-end len)) (begin (display s outport) (set! current-end (+ current-end len)))))) strs) (newline outport))) (define (local-line-number tree) (let ((tree-line (if (pair? tree) (pair-line-number tree) 0))) (if (and (< 0 tree-line 100000) (not (= tree-line line-number))) (format #f " (line ~D)" tree-line) ""))) ;; -------- vars -------- (define var-name car) (define (var? v) (and (pair? v) (let? (cdr v)))) (define var-member assq) (define var-ref (dilambda (lambda (v) (let-ref (cdr v) 'ref)) (lambda (v x) (let-set! (cdr v) 'ref x)))) (define var-set (dilambda (lambda (v) (let-ref (cdr v) 'set)) (lambda (v x) (let-set! (cdr v) 'set x)))) (define var-history (dilambda (lambda (v) (let-ref (cdr v) 'history)) (lambda (v x) (let-set! (cdr v) 'history x)))) (define var-ftype (dilambda (lambda (v) (let-ref (cdr v) 'ftype)) (lambda (v x) (let-set! (cdr v) 'ftype x)))) (define var-arglist (dilambda (lambda (v) (let-ref (cdr v) 'arglist)) (lambda (v x) (let-set! (cdr v) 'arglist x)))) (define var-definer (dilambda (lambda (v) (let-ref (cdr v) 'definer)) (lambda (v x) (let-set! (cdr v) 'definer x)))) (define var-leaves (dilambda (lambda (v) (let-ref (cdr v) 'leaves)) (lambda (v x) (let-set! (cdr v) 'leaves x)))) (define var-scope (dilambda (lambda (v) (let-ref (cdr v) 'scope)) (lambda (v x) (let-set! (cdr v) 'scope x)))) (define var-setters (dilambda (lambda (v) (let-ref (cdr v) 'setters)) (lambda (v x) (let-set! (cdr v) 'setters x)))) (define var-env (dilambda (lambda (v) (let-ref (cdr v) 'env)) (lambda (v x) (let-set! (cdr v) 'env x)))) (define var-decl (dilambda (lambda (v) (let-ref (cdr v) 'decl)) (lambda (v x) (let-set! (cdr v) 'decl x)))) (define var-match-list (dilambda (lambda (v) (let-ref (cdr v) 'match-list)) (lambda (v x) (let-set! (cdr v) 'match-list x)))) (define var-initial-value (lambda (v) (let-ref (cdr v) 'initial-value))) ; not settable (define var-side-effect (dilambda (lambda (v) (if (null? (let-ref (cdr v) 'side-effect)) (let-set! (cdr v) 'side-effect (get-side-effect v)) (let-ref (cdr v) 'side-effect))) (lambda (v x) (let-set! (cdr v) 'side-effect x)))) (define var-signature (dilambda (lambda (v) (if (null? (let-ref (cdr v) 'signature)) (let-set! (cdr v) 'signature (get-signature v)) (let-ref (cdr v) 'signature))) (lambda (v x) (let-set! (cdr v) 'signature x)))) (define* (make-var name initial-value definer) (let ((old (hash-table-ref other-identifiers name))) (cons name (inlet 'initial-value initial-value 'definer definer 'history (if old (begin (hash-table-set! other-identifiers name #f) (if initial-value (cons initial-value old) old)) (if initial-value (list initial-value) ())) 'scope () 'setters () 'set 0 'ref (if old (length old) 0))))) ;; -------- the usual list functions -------- (define (remove item sequence) (cond ((null? sequence) ()) ((equal? item (car sequence)) (cdr sequence)) (else (cons (car sequence) (remove item (cdr sequence)))))) (define (remove-all item sequence) (map (lambda (x) (if (equal? x item) (values) x)) sequence)) (define (remove-if p lst) (cond ((null? lst) ()) ((p (car lst)) (remove-if p (cdr lst))) (else (cons (car lst) (remove-if p (cdr lst)))))) (define (lint-remove-duplicates lst env) (reverse (let rem-dup ((lst lst) (nlst ())) (cond ((null? lst) nlst) ((and (member (car lst) nlst) (not (and (pair? (car lst)) (side-effect? (car lst) env)))) (rem-dup (cdr lst) nlst)) (else (rem-dup (cdr lst) (cons (car lst) nlst))))))) (define applicable? arity) (define every? (let ((documentation "(every? func sequence) returns #t if func approves of every member of sequence") (signature '(boolean? procedure? sequence?))) (lambda (f sequence) (call-with-exit (lambda (return) (for-each (lambda (arg) (if (not (f arg)) (return #f))) sequence) #t))))) (define any? (let ((documentation "(any? func sequence) returns #t if func approves of any member of sequence") (signature '(boolean? procedure? sequence?))) (lambda (f sequence) (call-with-exit (lambda (return) (for-each (lambda (arg) (if (f arg) (return #t))) sequence) #f))))) (define collect-if (let ((documentation "(collect-if type func sequence) gathers the elements of sequence that satisfy func, and returns them via type:\n\ (collect-if list integer? #(1.4 2/3 1 1+i 2)) -> '(1 2)")) (lambda (type f sequence) (apply type (map (lambda (arg) (if (f arg) arg (values))) sequence))))) (define find-if (let ((documentation "(find-if func sequence) applies func to each member of sequence.\n\ If func approves of one, find-if returns that member of the sequence")) (lambda (f sequence) (call-with-exit (lambda (return) (for-each (lambda (arg) (if (f arg) (return arg))) sequence) #f))))) ;; -------- trees -------- (define copy-tree (let ((documentation "(copy-tree lst) returns a full copy of lst")) (lambda (lis) (if (pair? lis) (cons (copy-tree (car lis)) (copy-tree (cdr lis))) lis)))) (define (tree-count1 x tree count) (if (eq? x tree) (+ count 1) (if (or (>= count 2) (not (pair? tree)) (eq? (car tree) 'quote)) count (tree-count1 x (car tree) (tree-count1 x (cdr tree) count))))) (define (tree-count2 x tree count) (if (eq? x tree) (+ count 1) (if (or (>= count 3) (not (pair? tree)) (eq? (car tree) 'quote)) count (tree-count2 x (car tree) (tree-count2 x (cdr tree) count))))) (define (proper-tree? tree) (or (not (pair? tree)) (and (proper-list? tree) (every? proper-tree? (cdr tree))))) (define (gather-symbols tree) (let ((syms ())) (let walk ((p tree)) (if (pair? p) (if (symbol? (car p)) (if (not (eq? (car p) 'quote)) (for-each (lambda (a) (if (symbol? a) (if (not (memq a syms)) (set! syms (cons a syms))) (if (pair? a) (walk a)))) (cdr p))) (if (pair? (car p)) (begin (walk (car p)) (walk (cdr p))))) (if (and (symbol? tree) (not (memq tree syms))) (set! syms (cons tree syms))))) syms)) (define (tree-arg-member sym tree) (and (proper-list? tree) (or (and (memq sym (cdr tree)) tree) (and (pair? (car tree)) (tree-arg-member sym (car tree))) (and (pair? (cdr tree)) (call-with-exit (lambda (return) (for-each (lambda (b) (cond ((and (pair? b) (tree-arg-member sym b)) => return))) (cdr tree)) #f)))))) (define (tree-memq sym tree) ; ignore quoted lists, accept symbol outside a pair (or (eq? sym tree) (and (pair? tree) (not (eq? (car tree) 'quote)) (or (eq? (car tree) sym) (tree-memq sym (car tree)) (tree-memq sym (cdr tree)))))) (define (tree-member sym tree) (and (pair? tree) (or (eq? (car tree) sym) (tree-member sym (car tree)) (tree-member sym (cdr tree))))) (define (tree-unquoted-member sym tree) (and (pair? tree) (not (eq? (car tree) 'quote)) (or (eq? (car tree) sym) (tree-unquoted-member sym (car tree)) (tree-unquoted-member sym (cdr tree))))) (define (tree-car-member sym tree) (and (pair? tree) (or (eq? (car tree) sym) (and (pair? (car tree)) (tree-car-member sym (car tree))) (and (pair? (cdr tree)) (member sym (cdr tree) tree-car-member))))) (define (tree-sym-set-member sym set tree) ; sym as arg, set as car (and (pair? tree) (or (memq (car tree) set) (and (pair? (car tree)) (tree-sym-set-member sym set (car tree))) (and (pair? (cdr tree)) (or (member sym (cdr tree)) (member #f (cdr tree) (lambda (a b) (tree-sym-set-member sym set b)))))))) (define (tree-set-member set tree) (and (pair? tree) (not (eq? (car tree) 'quote)) (or (memq (car tree) set) (tree-set-member set (car tree)) (tree-set-member set (cdr tree))))) (define (tree-table-member table tree) (and (pair? tree) (or (hash-table-ref table (car tree)) (tree-table-member table (car tree)) (tree-table-member table (cdr tree))))) (define (tree-set-car-member set tree) ; set as car (and (pair? tree) (or (and (memq (car tree) set) tree) (and (pair? (car tree)) (tree-set-car-member set (car tree))) (and (pair? (cdr tree)) (member #f (cdr tree) (lambda (a b) (tree-set-car-member set b))))))) (define (tree-table-car-member set tree) ; hash-table as car (and (pair? tree) (or (and (hash-table-ref set (car tree)) tree) (and (pair? (car tree)) (tree-table-car-member set (car tree))) (and (pair? (cdr tree)) (member #f (cdr tree) (lambda (a b) (tree-table-car-member set b))))))) (define (maker? tree) (tree-table-car-member makers tree)) (define (tree-symbol-walk tree syms) (if (pair? tree) (if (eq? (car tree) 'quote) (if (and (pair? (cdr tree)) (symbol? (cadr tree)) (not (memq (cadr tree) (car syms)))) (tree-symbol-walk (cddr tree) (begin (set-car! syms (cons (cadr tree) (car syms))) syms))) (if (eq? (car tree) {list}) (if (and (pair? (cdr tree)) (pair? (cadr tree)) (eq? (caadr tree) 'quote) (symbol? (cadadr tree)) (not (memq (cadadr tree) (cadr syms)))) (tree-symbol-walk (cddr tree) (begin (list-set! syms 1 (cons (cadadr tree) (cadr syms))) syms))) (begin (tree-symbol-walk (car tree) syms) (tree-symbol-walk (cdr tree) syms)))))) ;; -------- types -------- (define (quoted-undotted-pair? x) (and (pair? x) (eq? (car x) 'quote) (pair? (cdr x)) (pair? (cadr x)) (positive? (length (cadr x))))) (define (quoted-null? x) (and (pair? x) (eq? (car x) 'quote) (pair? (cdr x)) (null? (cadr x)))) (define (any-null? x) (or (null? x) (and (pair? x) (case (car x) ((quote) (and (pair? (cdr x)) (null? (cadr x)))) ((list) (null? (cdr x))) (else #f))))) (define (quoted-not? x) (and (pair? x) (eq? (car x) 'quote) (pair? (cdr x)) (not (cadr x)))) (define (quoted-symbol? x) (and (pair? x) (eq? (car x) 'quote) (pair? (cdr x)) (symbol? (cadr x)))) (define (code-constant? x) (and (or (not (symbol? x)) (keyword? x)) (or (not (pair? x)) (eq? (car x) 'quote)))) (define (just-symbols? form) (or (null? form) (symbol? form) (and (pair? form) (symbol? (car form)) (just-symbols? (cdr form))))) (define (list-any? f lst) (if (pair? lst) (or (f (car lst)) (list-any? f (cdr lst))) (f lst))) (define syntax? (let ((syns (let ((h (make-hash-table))) (for-each (lambda (x) (hash-table-set! h x #t)) (list quote if when unless begin set! let let* letrec letrec* cond and or case do lambda lambda* define define* define-macro define-macro* define-bacro define-bacro* define-constant with-baffle macroexpand with-let)) h))) (lambda (obj) ; a value, not a symbol (hash-table-ref syns obj)))) ;; -------- func info -------- (define (arg-signature fnc env) (and (symbol? fnc) (let ((fd (var-member fnc env))) (if (var? fd) (and (symbol? (var-ftype fd)) (var-signature fd)) (or (and (eq? *e* *lint*) (procedure-signature fnc)) (let ((f (symbol->value fnc *e*))) (and (procedure? f) (procedure-signature f)))))))) (define (arg-arity fnc env) (and (symbol? fnc) (let ((fd (var-member fnc env))) (if (var? fd) (and (not (eq? (var-decl fd) 'error)) (arity (var-decl fd))) (let ((f (symbol->value fnc *e*))) (and (procedure? f) (arity f))))))) (define (dummy-func caller form f) (catch #t (lambda () (eval f)) (lambda args (lint-format* caller (string-append "in " (truncated-list->string form) ", ") (apply format #f (cadr args)))))) (define (count-values body) (let ((mn #f) (mx #f)) (if (pair? body) (let counter ((ignored #f) ; 'ignored is for member's benefit (tree (list-ref body (- (length body) 1)))) (if (pair? tree) (if (eq? (car tree) 'values) (let ((args (- (length tree) 1))) (for-each (lambda (p) (if (and (pair? p) (eq? (car p) 'values)) (set! args (- (+ (args (length p)) 2))))) (cdr tree)) (set! mn (min (or mn args) args)) (set! mx (max (or mx args) args))) (begin (if (pair? (car tree)) (counter 'values (car tree))) (if (pair? (cdr tree)) (member #f (cdr tree) counter))))) #f)) ; return #f so member doesn't quit early (and mn (list mn mx)))) (define (get-signature v) (define (signer endb env) (and (not (side-effect? endb env)) (cond ((not (pair? endb)) (and (not (symbol? endb)) (list (->lint-type endb)))) ((arg-signature (car endb) env) => (lambda (a) (and (pair? a) (list (car a))))) ((and (eq? (car endb) 'if) (pair? (cddr endb))) (let ((a1 (signer (caddr endb) env)) (a2 (and (pair? (cdddr endb)) (signer (cadddr endb) env)))) (if (not a2) a1 (and (equal? a1 a2) a1)))) (else #f)))) (let ((ftype (var-ftype v)) (initial-value (var-initial-value v)) (arglist (var-arglist v)) (env (var-env v))) (let ((body (and (memq ftype '(define define* lambda lambda* let)) (cddr initial-value)))) (and (pair? body) (let ((sig (signer (list-ref body (- (length body) 1)) env))) (if (not (pair? sig)) (set! sig (list #t))) (when (and (proper-list? arglist) (not (any? keyword? arglist))) (for-each (lambda (arg) ; new function's parameter (set! sig (cons #t sig)) ;; (if (pair? arg) (set! arg (car arg))) ;; causes trouble when tree-count1 sees keyword args in s7test.scm (if (= (tree-count1 arg body 0) 1) (let ((p (tree-arg-member arg body))) (when (pair? p) (let ((f (car p)) (m (memq arg (cdr p)))) (if (pair? m) (let ((fsig (arg-signature f env))) (if (pair? fsig) (let ((chk (catch #t (lambda () (fsig (- (length p) (length m)))) (lambda args #f)))) (if (and (symbol? chk) ; it defaults to #t (not (memq chk '(integer:any? integer:real?)))) (set-car! sig chk))))))))))) arglist)) (and (any? (lambda (a) (not (eq? a #t))) sig) (reverse sig))))))) (define (args->proper-list args) (cond ((symbol? args) (list args)) ((not (pair? args)) args) ((pair? (car args)) (cons (caar args) (args->proper-list (cdr args)))) (else (cons (car args) (args->proper-list (cdr args)))))) (define (out-vars func-name arglist body) ; t367 has tests (let ((ref ()) (set ())) (let var-walk ((tree body) (e (cons func-name arglist))) (define (var-walk-body tree e) (when (pair? tree) (for-each (lambda (p) (set! e (var-walk p e))) tree))) (define (shadowed v) (if (and (or (memq v e) (memq v ref)) (not (memq v set))) (set! set (cons v set))) v) (if (symbol? tree) (if (not (or (memq tree e) (memq tree ref) (defined? tree (rootlet)))) (set! ref (cons tree ref))) (when (pair? tree) (if (not (pair? (cdr tree))) (var-walk (car tree) e) (case (car tree) ((set! vector-set! list-set! hash-table-set! float-vector-set! int-vector-set! string-set! let-set! fill! string-fill! list-fill! vector-fill! reverse! sort! set-car! set-cdr!) (let ((sym (if (symbol? (cadr tree)) (cadr tree) (if (pair? (cadr tree)) (caadr tree))))) (if (not (or (memq sym e) (memq sym set))) (set! set (cons sym set))) (var-walk (cddr tree) e))) ((let letrec) (if (and (pair? (cdr tree)) (pair? (cddr tree))) (let* ((named (symbol? (cadr tree))) (vars (if named (list (shadowed (cadr tree))) ()))) (for-each (lambda (v) (when (and (pair? v) (pair? (cdr v))) (var-walk (cadr v) e) (set! vars (cons (shadowed (car v)) vars)))) ((if named caddr cadr) tree)) (var-walk-body ((if named cdddr cddr) tree) (append vars e))))) ((case) (when (and (pair? (cdr tree)) (pair? (cddr tree))) (for-each (lambda (c) (when (pair? c) (var-walk (cdr c) e))) (cddr tree)))) ((quote) #f) ((let* letrec*) (let* ((named (symbol? (cadr tree))) (vars (if named (list (cadr tree)) ()))) (for-each (lambda (v) (when (and (pair? v) (pair? (cdr v))) (var-walk (cadr v) (append vars e)) (set! vars (cons (shadowed (car v)) vars)))) ((if named caddr cadr) tree)) (var-walk-body ((if named cdddr cddr) tree) (append vars e)))) ((do) (let ((vars ())) (when (pair? (cadr tree)) (for-each (lambda (v) (when (and (pair? v) (pair? (cdr v))) (var-walk (cadr v) e) (set! vars (cons (shadowed (car v)) vars)))) (cadr tree)) (for-each (lambda (v) (if (and (pair? v) (pair? (cdr v)) (pair? (cddr v))) (var-walk (caddr v) (append vars e)))) (cadr tree))) (when (pair? (cddr tree)) (var-walk (caddr tree) (append vars e)) (var-walk-body (cdddr tree) (append vars e))))) ((lambda lambda*) (var-walk-body (cddr tree) (append (args->proper-list (cadr tree)) e))) ((define* define-macro define-macro* define-bacro define-bacro*) (if (and (pair? (cdr tree)) (pair? (cddr tree))) (begin (set! e (cons (caadr tree) e)) (var-walk-body (cddr tree) (append (args->proper-list (cdadr tree)) e))))) ((define define-constant) (if (and (pair? (cdr tree)) (pair? (cddr tree))) (if (symbol? (cadr tree)) (begin (var-walk (caddr tree) e) (set! e (cons (cadr tree) e))) (begin (set! e (cons (caadr tree) e)) (var-walk-body (cddr tree) (append (args->proper-list (cdadr tree)) e)))))) (else (var-walk (car tree) e) (var-walk (cdr tree) e)))))) e) (list ref set))) (define (get-side-effect v) (let ((ftype (var-ftype v))) (or (not (memq ftype '(define define* lambda lambda*))) (let ((body (cddr (var-initial-value v))) (env (var-env v)) (args (cons (var-name v) (args->proper-list (var-arglist v))))) (let ((outvars (append (cadr (out-vars (var-name v) args body)) args))) (any? (lambda (f) (side-effect-with-vars? f env outvars)) body)))))) (define (last-par x) (let ((len (length x))) (and (positive? len) (x (- len 1))))) (define* (make-fvar name ftype arglist decl initial-value env) (let ((new (let ((old (hash-table-ref other-identifiers name))) (cons name (inlet 'signature () 'side-effect () 'allow-other-keys (and (pair? arglist) (memq ftype '(define* define-macro* define-bacro* defmacro*)) (eq? (last-par arglist) :allow-other-keys)) 'scope () 'setters () 'env env 'initial-value initial-value 'values (and (pair? initial-value) (count-values (cddr initial-value))) 'leaves #f 'match-list #f 'decl decl 'arglist arglist 'ftype ftype 'history (if old (begin (hash-table-set! other-identifiers name #f) (if initial-value (cons initial-value old) old)) (if initial-value (list initial-value) ())) 'set 0 'ref (if old (length old) 0)))))) (when (and *report-function-stuff* (not (memq name '(:lambda :dilambda))) (memq ftype '(define lambda define* lambda*)) (pair? (caddr initial-value))) (hash-table-set! equable-closures (caaddr initial-value) (cons new (or (hash-table-ref equable-closures (caaddr initial-value)) ())))) new)) (define (return-type sym e) (let ((sig (arg-signature sym e))) (and (pair? sig) (or (eq? (car sig) 'values) ; turn it into #t for now (car sig))))) ; this might be undefined in the current context (eg oscil? outside clm) (define any-macro? (let ((macros (let ((h (make-hash-table))) (for-each (lambda (m) (set! (h m) #t)) '(call-with-values let-values define-values let*-values cond-expand require quasiquote multiple-value-bind reader-cond match while)) h))) (lambda (f env) (or (hash-table-ref macros f) (let ((fd (var-member f env))) (and (var? fd) (memq (var-ftype fd) '(define-macro define-macro* define-expansion define-bacro define-bacro* defmacro defmacro* define-syntax)))))))) (define (any-procedure? f env) (or (hash-table-ref built-in-functions f) (let ((v (var-member f env))) (and (var? v) (memq (var-ftype v) '(define define* lambda lambda*)))))) (define ->simple-type (let ((markers (list (cons :call/exit 'continuation?) (cons :call/cc 'continuation?) (cons :dilambda 'dilambda?) (cons :lambda 'procedure?)))) (lambda (c) (cond ((pair? c) 'pair?) ((integer? c) 'integer?) ((rational? c) 'rational?) ((real? c) 'real?) ((number? c) 'number?) ((string? c) 'string?) ((null? c) 'null?) ((char? c) 'char?) ((boolean? c) 'boolean?) ((keyword? c) (cond ((assq c markers) => cdr) (else 'keyword?))) ((vector? c) 'vector?) ((float-vector? c) 'float-vector?) ((int-vector? c) 'int-vector?) ((byte-vector? c) 'byte-vector?) ((let? c) 'let?) ((hash-table? c) 'hash-table?) ((input-port? c) 'input-port?) ((output-port? c) 'output-port?) ((iterator? c) 'iterator?) ((continuation? c) 'continuation?) ((dilambda? c) 'dilambda?) ((procedure? c) 'procedure?) ((macro? c) 'macro?) ((random-state? c) 'random-state?) ((c-pointer? c) 'c-pointer?) ((c-object? c) 'c-object?) ((eof-object? c) 'eof-object?) ((syntax? c) 'syntax?) ((assq c '((#<unspecified> . unspecified?) (#<undefined> . undefined?))) => cdr) (#t #t))))) (define (define->type c) (and (pair? c) (case (car c) ((define) (if (and (pair? (cdr c)) (pair? (cadr c))) 'procedure? (and (pair? (cddr c)) (->lint-type (caddr c))))) ((define* lambda lambda* case-lambda) 'procedure?) ((dilambda) 'dilambda?) ((define-macro define-macro* define-bacro define-bacro* defmacro defmacro* define-expansion) 'macro?) ((:call/cc :call/exit) 'continuation?) (else #t)))) (define (->lint-type c) (cond ((not (pair? c)) (->simple-type c)) ((not (symbol? (car c))) (or (pair? (car c)) 'pair?)) ((not (eq? (car c) 'quote)) (or (return-type (car c) ()) (define->type c))) ((symbol? (cadr c)) 'symbol?) (else (->simple-type (cadr c))))) ; don't look for return type! (define (compatible? type1 type2) ; we want type1, we have type2 -- is type2 ok? (or (eq? type1 type2) (not (symbol? type1)) (not (symbol? type2)) (not (hash-table-ref booleans type1)) (not (hash-table-ref booleans type2)) (eq? type2 'constant?) (case type1 ((number? complex?) (memq type2 '(float? real? rational? integer? number? complex? exact? inexact? zero? negative? positive? even? odd? infinite? nan?))) ((real?) (memq type2 '(float? rational? integer? complex? number? exact? inexact? zero? negative? positive? even? odd? infinite? nan?))) ((zero?) (memq type2 '(float? real? rational? integer? number? complex? exact? inexact? even?))) ((negative? positive?) (memq type2 '(float? real? rational? integer? complex? number? exact? inexact? even? odd? infinite? nan?))) ((float?) (memq type2 '(real? complex? number? inexact? zero? negative? positive? infinite? nan?))) ((rational?) (memq type2 '(integer? real? complex? number? exact? zero? negative? positive? even? odd?))) ((integer?) (memq type2 '(real? rational? complex? number? exact? even? odd? zero? negative? positive?))) ((odd? even?) (memq type2 '(real? rational? complex? number? exact? integer? zero? negative? positive?))) ((exact?) (memq type2 '(real? rational? complex? number? integer? zero? negative? positive?))) ((inexact?) (memq type2 '(real? number? complex? float? zero? negative? positive? infinite? nan?))) ((infinite? nan?) (memq type2 '(real? number? complex? positive? negative? inexact? float?))) ((vector?) (memq type2 '(float-vector? int-vector? sequence?))) ((float-vector? int-vector?) (memq type2 '(vector? sequence?))) ((sequence?) (memq type2 '(list? pair? null? proper-list? vector? float-vector? int-vector? byte-vector? string? let? hash-table? c-object? iterator? procedure?))) ; procedure? for extended iterator ((symbol?) (memq type2 '(gensym? keyword? defined? provided?))) ((constant?) #t) ((keyword? gensym? defined? provided?) (eq? type2 'symbol?)) ((list?) (memq type2 '(null? pair? proper-list? sequence?))) ((proper-list?) (memq type2 '(null? pair? list? sequence?))) ((pair? null?) (memq type2 '(list? proper-list? sequence?))) ((dilambda?) (memq type2 '(procedure? macro? iterator?))) ((procedure?) (memq type2 '(dilambda? iterator? macro? sequence?))) ((macro?) (memq type2 '(dilambda? iterator? procedure?))) ((iterator?) (memq type2 '(dilambda? procedure? sequence?))) ((string?) (memq type2 '(byte-vector? sequence? directory? file-exists?))) ((hash-table? let? c-object?) (eq? type2 'sequence?)) ((byte-vector? directory? file-exists?) (memq type2 '(string? sequence?))) ((input-port? output-port?) (eq? type2 'boolean?)) ((char? char-whitespace? char-numeric? char-alphabetic? char-upper-case? char-lower-case?) (memq type2 '(char? char-whitespace? char-numeric? char-alphabetic? char-upper-case? char-lower-case?))) (else #f)))) (define (any-compatible? type1 type2) ;; type1 and type2 can be either a list of types or a type (if (symbol? type1) (if (symbol? type2) (compatible? type1 type2) (and (pair? type2) (or (compatible? type1 (car type2)) (any-compatible? type1 (cdr type2))))) (and (pair? type1) (or (compatible? (car type1) type2) (any-compatible? (cdr type1) type2))))) (define (subsumes? type1 type2) (or (eq? type1 type2) (case type1 ((integer?) (memq type2 '(even? odd?))) ((rational?) (memq type2 '(integer? exact? odd? even?))) ((exact?) (memq type2 '(integer? rational?))) ((real?) (memq type2 '(integer? rational? float? negative? positive? zero? odd? even?))) ((complex? number?) (memq type2 '(integer? rational? float? real? complex? number? negative? positive? zero? even? odd? exact? inexact? nan? infinite?))) ((list?) (memq type2 '(pair? null? proper-list?))) ((proper-list?) (eq? type2 'null?)) ((vector?) (memq type2 '(float-vector? int-vector?))) ((symbol?) (memq type2 '(keyword? gensym? defined? provided?))) ((sequence?) (memq type2 '(list? pair? null? proper-list? vector? float-vector? int-vector? byte-vector? string? let? hash-table? c-object? directory? file-exists?))) ((char?) (memq type2 '(char-whitespace? char-numeric? char-alphabetic? char-upper-case? char-lower-case?))) (else #f)))) (define (never-false expr) (or (eq? expr #t) (let ((type (if (pair? expr) (return-type (car expr) ()) (->lint-type expr)))) (and (symbol? type) (not (symbol? expr)) (not (memq type '(boolean? values))))))) (define (never-true expr) (or (not expr) (and (pair? expr) (eq? (car expr) 'not) (pair? (cdr expr)) (never-false (cadr expr))))) (define (prettify-checker-unq op) (if (pair? op) (string-append (prettify-checker-unq (car op)) " or " (prettify-checker-unq (cadr op))) (case op ((rational?) "rational") ((real?) "real") ((complex?) "complex") ((null?) "null") ((length) "a sequence") ((unspecified?) "untyped") ((undefined?) "not defined") (else (let ((op-name (symbol->string op))) (string-append (if (memv (op-name 0) '(#\a #\e #\i #\o #\u)) "an " "a ") (substring op-name 0 (- (length op-name) 1)))))))) (define (prettify-checker op) (if (pair? op) (string-append (prettify-checker-unq (car op)) " or " (prettify-checker (cadr op))) (let ((op-name (symbol->string op))) (case op ((rational? real? complex? null?) op-name) ((unspecified?) "untyped") ((undefined?) "not defined") (else (string-append (if (memv (op-name 0) '(#\a #\e #\i #\o #\u)) "an " "a ") op-name)))))) (define (side-effect-with-vars? form env vars) ;; (format *stderr* "~A~%" form) ;; could evaluation of form have any side effects (like IO etc) (if (or (not (proper-list? form)) ; we don't want dotted lists or () here (null? form)) (and (symbol? form) (or (eq? form '=>) ; (cond ((x => y))...) -- someday check y... (let ((e (var-member form env))) (if (var? e) (and (symbol? (var-ftype e)) (var-side-effect e)) (and (not (hash-table-ref no-side-effect-functions form)) (procedure? (symbol->value form *e*))))))) ; i.e. function passed as argument ;; can't optimize ((...)...) because the car might eval to a function (or (and (not (hash-table-ref no-side-effect-functions (car form))) ;; if it's not in the no-side-effect table and ... (let ((e (var-member (car form) env))) (or (not (var? e)) (not (symbol? (var-ftype e))) (var-side-effect e))) (or (not (eq? (car form) 'format)) ; (format #f ...) (not (pair? (cdr form))) ; (format)! (cadr form)) (or (null? vars) (not (memq (car form) '(set! ;vector-set! list-set! hash-table-set! float-vector-set! int-vector-set! string-set! let-set! ;fill! string-fill! list-fill! vector-fill! ;reverse! sort! define define* define-macro define-macro* define-bacro define-bacro*))))) ;; it's not the common (format #f ...) special case, then...(goto case below) ;; else return #t: side-effects are possible -- this is too hard to read (case (car form) ((define-constant define-expansion) #t) ((define define* define-macro define-macro* define-bacro define-bacro*) (null? vars)) ((set! ;vector-set! list-set! hash-table-set! float-vector-set! int-vector-set! string-set! let-set! ;fill! string-fill! list-fill! vector-fill! ;reverse! sort! ) (or (not (pair? (cdr form))) (not (symbol? (cadr form))) (memq (cadr form) vars))) ((quote) #f) ((case) (or (not (pair? (cdr form))) (side-effect-with-vars? (cadr form) env vars) ; the selector (let case-effect? ((f (cddr form))) (and (pair? f) (or (not (pair? (car f))) (any? (lambda (ff) (side-effect-with-vars? ff env vars)) (cdar f)) (case-effect? (cdr f))))))) ((cond) (or (not (pair? (cadr form))) (let cond-effect? ((f (cdr form)) (e env)) (and (pair? f) (or (and (pair? (car f)) (any? (lambda (ff) (side-effect-with-vars? ff e vars)) (car f))) (cond-effect? (cdr f) e)))))) ((let let* letrec letrec*) ;; here if the var value involves a member of vars, we have to add it to vars (or (< (length form) 3) (let ((syms (cadr form)) (body (cddr form))) (when (symbol? (cadr form)) (set! syms (caddr form)) (set! body (cdddr form))) (if (and (pair? vars) (pair? syms)) (for-each (lambda (sym) (when (and (pair? sym) (pair? (cdr sym)) (tree-set-member vars (cdr sym))) (set! vars (cons (car sym) vars)))) syms)) (or (let let-effect? ((f syms) (e env) (v vars)) (and (pair? f) (or (not (pair? (car f))) (not (pair? (cdar f))) ; an error, reported elsewhere: (let ((x)) x) (side-effect-with-vars? (cadar f) e v) (let-effect? (cdr f) e v)))) (any? (lambda (ff) (side-effect-with-vars? ff env vars)) body))))) ((do) (or (< (length form) 3) (not (list? (cadr form))) (not (list? (caddr form))) (let do-effect? ((f (cadr form)) (e env)) (and (pair? f) (or (not (pair? (car f))) (not (pair? (cdar f))) (side-effect-with-vars? (cadar f) e vars) (and (pair? (cddar f)) (side-effect-with-vars? (caddar f) e vars)) (do-effect? (cdr f) e)))) (any? (lambda (ff) (side-effect-with-vars? ff env vars)) (caddr form)) (any? (lambda (ff) (side-effect-with-vars? ff env vars)) (cdddr form)))) ;; ((lambda lambda*) (any? (lambda (ff) (side-effect-with-vars? ff env vars)) (cddr form))) ; this is trickier than it looks (else ;(format *stderr* "check args: ~A~%" form) (or (any? (lambda (f) ; any subform has a side-effect (and (not (null? f)) (side-effect-with-vars? f env vars))) (cdr form)) (let ((sig (procedure-signature (car form)))) ; sig has func arg and it is not known safe (and (pair? sig) (memq 'procedure? (cdr sig)) (call-with-exit (lambda (return) (for-each (lambda (sg arg) (when (and (eq? sg 'procedure?) (not (and (symbol? arg) (hash-table-ref no-side-effect-functions arg)))) (return #t))) (cdr sig) (cdr form)) #f)))))))))) (define (side-effect? form env) (side-effect-with-vars? form env ())) (define (just-constants? form env) ;; can we probably evaluate form given just built-in stuff? ;; watch out here -- this is used later by 'if, so (defined 'hiho) should not be evalled to #f! (if (not (pair? form)) (constant? form) (and (symbol? (car form)) (hash-table-ref no-side-effect-functions (car form)) (hash-table-ref built-in-functions (car form)) ; and not hook-functions (not (var-member (car form) env)) ; e.g. exp declared locally as a list (every? (lambda (p) (just-constants? p env)) (cdr form))))) (define (equal-ignoring-constants? a b) (or (morally-equal? a b) (and (symbol? a) (constant? a) (morally-equal? (symbol->value a) b)) (and (symbol? b) (constant? b) (morally-equal? (symbol->value b) a)) (and (pair? a) (pair? b) (equal-ignoring-constants? (car a) (car b)) (equal-ignoring-constants? (cdr a) (cdr b))))) (define (repeated-member? lst env) (and (pair? lst) (or (and (not (and (pair? (car lst)) (side-effect? (car lst) env))) (pair? (cdr lst)) (member (car lst) (cdr lst))) (repeated-member? (cdr lst) env)))) (define (update-scope v caller env) (unless (or (memq caller (var-scope v)) (assq caller (var-scope v))) (let ((cv (var-member caller env))) (set! (var-scope v) (cons (if (and (var? cv) (memq (var-ftype cv) '(define lambda define* lambda*))) ; named-let does not define ftype caller (cons caller env)) (var-scope v)))))) (define (check-for-bad-variable-name caller vname) (define (bad-variable-name-numbered vname bad-names) (let ((str (symbol->string vname))) (let loop ((bads bad-names)) (and (pair? bads) (let* ((badstr (symbol->string (car bads))) (pos (string-position badstr str))) (or (and (eqv? pos 0) (string->number (substring str (length badstr)))) (loop (cdr bads)))))))) (if (and (symbol? vname) (pair? *report-bad-variable-names*) (or (memq vname *report-bad-variable-names*) (let ((sname (symbol->string vname))) (and (> (length sname) 8) (or (string=? "compute" (substring sname 0 7)) ; compute-* is as bad as get-* (string=? "calculate" (substring sname 0 9))))) ; perhaps one exception: computed-goto* (bad-variable-name-numbered vname *report-bad-variable-names*))) (lint-format "surely there's a better name for this variable than ~A" caller vname))) (define (set-ref name caller form env) ;; if name is in env, set its "I've been referenced" flag (let ((data (var-member name env))) (if (var? data) (begin (set! (var-ref data) (+ (var-ref data) 1)) (update-scope data caller env) (if (and form (not (memq form (var-history data)))) (set! (var-history data) (cons form (var-history data))))) (if (not (defined? name (rootlet))) (let ((old (hash-table-ref other-identifiers name))) (check-for-bad-variable-name caller name) (hash-table-set! other-identifiers name (if old (cons form old) (list form))))))) env) (define (set-set name caller form env) (let ((data (var-member name env))) (when (var? data) (set! (var-set data) (+ (var-set data) 1)) (update-scope data caller env) (if (not (memq caller (var-setters data))) (set! (var-setters data) (cons caller (var-setters data)))) (if (not (memq form (var-history data))) (set! (var-history data) (cons form (var-history data)))) (set! (var-signature data) #f) (set! (var-ftype data) #f)))) (define (proper-list lst) ;; return lst as a proper list (if (not (pair? lst)) lst (cons (car lst) (if (pair? (cdr lst)) (proper-list (cdr lst)) (if (null? (cdr lst)) () (list (cdr lst))))))) (define (keywords lst) (do ((count 0) (p lst (cdr p))) ((null? p) count) (if (keyword? (car p)) (set! count (+ count 1))))) (define (eqv-selector clause) (if (not (pair? clause)) (memq clause '(else #t)) (case (car clause) ((memq memv member) (and (= (length clause) 3) (cadr clause))) ((eq? eqv? = equal? char=? char-ci=? string=? string-ci=?) (and (= (length clause) 3) ((if (code-constant? (cadr clause)) caddr cadr) clause))) ((or) (and (pair? (cdr clause)) (eqv-selector (cadr clause)))) ((not null? eof-object? zero? boolean?) (and (pair? (cdr clause)) (cadr clause))) (else #f)))) (define (->eqf x) (case x ((char?) '(eqv? char=?)) ((integer? rational? real? number? complex?) '(eqv? =)) ((symbol? keyword? boolean? null? procedure? syntax? macro? undefined? unspecified?) '(eq? eq?)) ((string? byte-vector?) '(equal? string=?)) ((pair? vector? float-vector? int-vector? hash-table?) '(equal? equal?)) ((eof-object?) '(eq? eof-object?)) (else (if (and (pair? x) (pair? (cdr x)) (null? (cddr x)) (or (and (memq 'boolean? x) (or (memq 'real? x) (memq 'number? x) (memq 'integer? x))) (and (memq 'eof-object? x) (or (memq 'char? x) (memq 'integer? x))))) '(eqv? eqv?) '(#t #t))))) (define (eqf selector env) (cond ((symbol? selector) (if (and (not (var-member selector env)) (or (hash-table-ref built-in-functions selector) (hash-table-ref syntaces selector))) '(eq? eq?) '(#t #t))) ((not (pair? selector)) (->eqf (->lint-type selector))) ((eq? (car selector) 'quote) (cond ((or (symbol? (cadr selector)) (memq (cadr selector) '(#f #t #<unspecified> #<undefined> #<eof> ()))) '(eq? eq?)) ((char? (cadr selector)) '(eqv? char=?)) ((string? (cadr selector)) '(equal? string=?)) ((number? (cadr selector)) '(eqv? =)) (else '(equal? equal?)))) ((and (eq? (car selector) 'list) (null? (cdr selector))) '(eq? eq?)) ((symbol? (car selector)) (let ((sig (arg-signature (car selector) env))) (if (pair? sig) (->eqf (car sig)) '(#t #t)))) (else '(#t #t)))) (define (unquoted x) (if (and (pair? x) (eq? (car x) 'quote)) (cadr x) x)) (define (distribute-quote x) (map (lambda (item) (if (or (symbol? item) (pair? item)) `(quote ,item) item)) x)) (define (focus-str str focus) (let ((len (length str))) (if (< len 40) str (let ((pos (string-position focus str)) (focus-len (length focus))) (if (not pos) str (if (<= pos 20) (string-append (substring str 0 (min 60 (- len 1) (+ focus-len pos 20))) " ...") (string-append "... " (substring str (- pos 20) (min (- len 1) (+ focus-len pos 20))) " ..."))))))) (define (check-star-parameters f args env) (if (list-any? (lambda (k) (memq k '(:key :optional))) args) (let ((kw (if (memq :key args) :key :optional))) (format outport "~NC~A: ~A is no longer accepted: ~A~%" lint-left-margin #\space f kw (focus-str (object->string args) (symbol->string kw))))) (if (member 'pi args (lambda (a b) (or (eq? b 'pi) (and (pair? b) (eq? (car b) 'pi))))) (format outport "~NC~A: parameter can't be a constant: ~A~%" lint-left-margin #\space f (focus-str (object->string args) "pi"))) (let ((r (memq :rest args))) (when (pair? r) (if (not (pair? (cdr r))) (format outport "~NC~A: :rest parameter needs a name: ~A~%" lint-left-margin #\space f args) (if (pair? (cadr r)) (format outport "~NC~A: :rest parameter can't specify a default value: ~A~%" lint-left-margin #\space f args))))) (let ((a (memq :allow-other-keys args))) (if (and (pair? a) (pair? (cdr a))) (format outport "~NC~A: :allow-other-keys should be at the end of the parameter list: ~A~%" lint-left-margin #\space f (focus-str (object->string args) ":allow-other-keys")))) (for-each (lambda (p) (if (and (pair? p) (pair? (cdr p))) (lint-walk f (cadr p) env))) args)) (define (checked-eval form) (and (proper-list? form) ;(not (infinite? (length form))) but when would a dotted list work? (catch #t (lambda () (eval (copy form :readable))) (lambda args :checked-eval-error)))) (define (return-type-ok? type ret) (or (eq? type ret) (and (pair? ret) (memq type ret)))) (define last-and-incomplete-arg2 #f) (define (and-incomplete form head arg1 arg2 env) ; head: 'and | 'or (not ...) | 'if | 'if2 -- symbol arg1 in any case (unless (memq (car arg2) '(and or not list cons vector)) ; these don't tell us anything about arg1's type (let ((v (var-member arg1 env))) ; try to avoid the member->cdr trope (unless (or (eq? arg2 last-and-incomplete-arg2) (and (var? v) (pair? (var-history v)) (member #f (var-history v) (lambda (a b) (and (pair? b) (memq (car b) '(char-position string-position format string->number assoc assq assv memq memv member))))))) (let* ((pos (do ((i 0 (+ i 1)) ; get arg number of arg1 in arg2 (p arg2 (cdr p))) ; 0th=car -> (and x (x)) ((or (null? p) (eq? (car p) arg1)) i))) (arg-type (let ((sig (and (positive? pos) ; procedure-signature for arg2 (arg-signature (car arg2) env)))) (if (zero? pos) ; it's type indication for arg1's position 'procedure? ; or sequence? -- how to distinguish? use 'applicable? (and (pair? sig) (< pos (length sig)) (list-ref sig pos)))))) (let ((ln (and (< 0 line-number 100000) line-number)) (comment (if (and (eq? arg-type 'procedure?) (= pos 0) (pair? (cdr arg2))) " ; or maybe sequence? " ""))) (set! last-and-incomplete-arg2 arg2) ; ignore unwanted repetitions due to recursive simplifications (if (symbol? arg-type) (let ((old-arg (case head ((and if cond when) arg1) ((or if2) `(not ,arg1)))) (new-arg (case head ((and if cond when) `(,arg-type ,arg1)) ((or if2) `(not (,arg-type ,arg1)))))) (format outport "~NCin ~A~A,~%~NCperhaps change ~S to ~S~A~%" lint-left-margin #\space (truncated-list->string form) (if ln (format #f " (line ~D)" ln) "") (+ lint-left-margin 4) #\space old-arg new-arg comment))))))))) (define (and-redundant? arg1 arg2) (let ((type1 (car arg1)) (type2 (car arg2))) (and (symbol? type1) (symbol? type2) (hash-table-ref booleans type1) (or (hash-table-ref booleans type2) ; return #f if not (obviously) redundant, else return which of the two to keep (memq type2 '(= char=? string=? not eq?))) (if (eq? type1 type2) type1 (case type1 ((number? complex?) (case type2 ((float? real? rational? integer?) type2) ((number? complex?) type1) ((=) (let ((x ((if (number? (caddr arg2)) caddr cadr) arg2))) (and (number? x) (if (= x (floor x)) 'memv 'eqv?)))) (else #f))) ((real?) (case type2 ((float? rational? integer?) type2) ((number? complex?) type1) ((=) (let ((x ((if (real? (caddr arg2)) caddr cadr) arg2))) (and (real? x) (if (= x (floor x)) 'memv 'eqv?)))) (else #f))) ((float?) (and (memq type2 '(real? complex? number? inexact?)) type1)) ((rational?) (case type2 ((integer?) type2) ((real? complex? number? exact?) type1) ((=) (and (or (rational? (caddr arg2)) (rational? (cadr arg2))) 'eqv?)) (else #f))) ((integer?) (case type2 ((real? rational? complex? number? exact?) type1) ((=) (and (or (integer? (caddr arg2)) (integer? (cadr arg2))) 'eqv?)) (else #f))) ((exact?) (and (memq type2 '(rational? integer?)) type2)) ((even? odd?) (and (memq type2 '(integer? rational? real? complex? number?)) type1)) ; not zero? -> 0.0 ((zero?) (and (memq type2 '(complex? number? real?)) type1)) ((negative? positive?) (and (eq? type2 'real?) type1)) ((inexact?) (and (eq? type2 'float?) type2)) ((infinite? nan?) (and (memq type2 '(number? complex? inexact?)) type1)) ((vector?) (and (memq type2 '(float-vector? int-vector?)) type2)) ((float-vector? int-vector?) (and (eq? type2 'vector?) type1)) ((symbol?) (case type2 ((keyword? gensym?) type2) ((eq?) (and (or (quoted-symbol? (cadr arg2)) (quoted-symbol? (caddr arg2))) 'eq?)) (else #f))) ((keyword?) (case type2 ((symbol? constant?) type1) ((eq?) (and (or (keyword? (cadr arg2)) (keyword? (caddr arg2))) 'eq?)) (else #f))) ((gensym? defined? provided?) (and (eq? type2 'symbol?) type1)) ((boolean?) (and (or (eq? type2 'not) (and (eq? type2 'eq?) (or (boolean? (cadr arg2)) (boolean? (caddr arg2))))) type2)) ((list?) (and (memq type2 '(null? pair? proper-list?)) type2)) ((null?) (and (memq type2 '(list? proper-list?)) type1)) ((pair?) (and (eq? type2 'list?) type1)) ((proper-list?) (and (eq? type2 'null?) type2)) ((string?) (case type2 ((byte-vector?) type2) ((string=?) (and (or (eq? (->lint-type (cadr arg2)) 'string?) (eq? (->lint-type (caddr arg2)) 'string?)) 'equal?)) (else #f))) ((char?) (and (eq? type2 'char=?) (or (eq? (->lint-type (cadr arg2)) 'char?) (eq? (->lint-type (caddr arg2)) 'char?)) 'eqv?)) ((char-numeric? char-whitespace? char-alphabetic? char-upper-case? char-lower-case?) (and (eq? type2 'char?) type1)) ((byte-vector? directory? file-exists?) (and (eq? type2 'string?) type1)) (else #f)))))) (define (and-forgetful form head arg1 arg2 env) (unless (or (memq (car arg2) '(and or not list cons vector)) ; these don't tell us anything about arg1's type (eq? arg2 last-and-incomplete-arg2)) (let* ((pos (do ((i 0 (+ i 1)) ; get arg number of arg1 in arg2 (p arg2 (cdr p))) ; 0th=car -> (and x (x)) ((or (null? p) (equal? (car p) (cadr arg1))) (if (null? p) -1 i)))) (arg-type (let ((sig (and (positive? pos) ; procedure-signature for arg2 (arg-signature (car arg2) env)))) (if (zero? pos) ; its type indication for arg1's position 'procedure? ; or sequence? -- how to distinguish? use 'applicable? (and (pair? sig) (< pos (length sig)) (list-ref sig pos)))))) (when (symbol? arg-type) (let ((new-type (and-redundant? arg1 (cons arg-type (cdr arg1))))) (when (and new-type (not (eq? new-type (car arg1)))) (let ((old-arg (case head ((and if cond when) arg1) ((or if2) `(not ,arg1)))) (new-arg (case head ((and if cond when) `(,new-type ,(cadr arg1))) ((or if2) `(not (,new-type ,(cadr arg1)))))) (ln (and (< 0 line-number 100000) line-number)) (comment (if (and (eq? arg-type 'procedure?) (= pos 0) (pair? (cdr arg2))) " ; or maybe sequence? " ""))) (set! last-and-incomplete-arg2 arg2) (format outport "~NCin ~A~A,~%~NCperhaps change ~S to ~S~A~%" lint-left-margin #\space (truncated-list->string form) (if ln (format #f " (line ~D)" ln) "") (+ lint-left-margin 4) #\space old-arg new-arg comment))))))) ;; perhaps change pair? -> eq? or ignore it? (when (and (pair? (cdr arg2)) (not (eq? (car arg1) 'pair?))) (let ((a2 (if (eq? (car arg2) 'not) (cadr arg2) arg2))) (when (and (pair? a2) (memq (car a2) '(memq memv member assq assv assoc eq? eqv? equal?)) (equal? (cadr arg1) (cadr a2))) (let ((new-e (case (car (->eqf (car arg1))) ((eq?) (case (car a2) ((memq assq eq?) (car a2)) ((memv member) 'memq) ((assv assoc) 'assq) ((eqv? equal?) 'eq?))) ((eqv?) (case (car a2) ((memv assv eqv?) (car a2)) ((memq member) 'memv) ((assq assoc) 'assv) ((eq? equal?) 'eqv?))) ((equal?) (case (car a2) ((member assoc equal?) (car a2)) ((memq memv) 'member) ((assq assv) 'assoc) ((eq? eqv?) 'equal?))) (else (car a2))))) (when (and (not (eq? (car a2) new-e)) (symbol? new-e)) (let ((ln (and (< 0 line-number 100000) line-number))) (format outport "~NCin ~A~A,~%~NCperhaps change ~A to ~A~%" lint-left-margin #\space (truncated-list->string form) (if ln (format #f " (line ~D)" ln) "") (+ lint-left-margin 4) #\space (truncated-list->string a2) `(,new-e ...))))))))) ;; -------------------------------- (define simplify-boolean (let ((notables (let ((h (make-hash-table))) (for-each (lambda (op) (set! (h (car op)) (cadr op))) '((< >=) (> <=) (<= >) (>= <) (char<? char>=?) (char>? char<=?) (char<=? char>?) (char>=? char<?) (string<? string>=?) (string>? string<=?) (string<=? string>?) (string>=? string<?) (char-ci<? char-ci>=?) (char-ci>? char-ci<=?) (char-ci<=? char-ci>?) (char-ci>=? char-ci<?) (string-ci<? string-ci>=?) (string-ci>? string-ci<=?) (string-ci<=? string-ci>?) (string-ci>=? string-ci<?) (odd? even?) (even? odd?) (exact? inexact?) (inexact? exact?))) h)) (relsub (let ((relops '((< <= > number?) (<= < >= number?) (> >= < number?) (>= > <= number?) (char<? char<=? char>? char?) (char<=? char<? char>=? char?) ; these never happen (char>? char>=? char<? char?) (char>=? char>? char<=? char?) (string<? string<=? string>? string?) (string<=? string<? string>=? string?) (string>? string>=? string<? string?) (string>=? string>? string<=? string?)))) (lambda (A B rel-op env) (call-with-exit (lambda (return) (when (and (pair? A) (pair? B) (= (length A) (length B) 3)) (let ((Adata (assq (car A) relops)) (Bdata (assq (car B) relops))) (when (and Adata Bdata) (let ((op1 (car A)) (op2 (car B)) (A1 (cadr A)) (A2 (caddr A)) (B1 (cadr B)) (B2 (caddr B))) (let ((x (if (and (not (number? A1)) (member A1 B)) A1 (and (not (number? A2)) (member A2 B) A2)))) (when x (let ((c1 (if (equal? x A1) A2 A1)) (c2 (if (equal? x B1) B2 B1)) (type (cadddr Adata))) (if (or (side-effect? c1 env) (side-effect? c2 env) (side-effect? x env)) (return 'ok)) (if (equal? x A2) (set! op1 (caddr Adata))) (if (equal? x B2) (set! op2 (caddr Bdata))) (let ((typer #f) (gtes #f) (gts #f) (eqop #f)) (case type ((number?) (set! typer number?) (set! gtes '(>= <=)) (set! gts '(< >)) (set! eqop '=)) ((char?) (set! typer char?) (set! gtes '(char>=? char<=?)) (set! gts '(char<? char>?)) (set! eqop 'char=?)) ((string?) (set! typer string?) (set! gtes '(string>=? string<=?)) (set! gts '(string<? string>?)) (set! eqop 'string=?))) (case rel-op ((and) (cond ((equal? c1 c2) (cond ((eq? op1 op2) (return `(,op1 ,x ,c1))) ((eq? op2 (cadr (assq op1 relops))) (return `(,(if (memq op2 gtes) op1 op2) ,x ,c1))) ((and (memq op1 gtes) (memq op2 gtes)) (return `(,eqop ,x ,c1))) (else (return #f)))) ((and (typer c1) (typer c2)) (cond ((or (eq? op1 op2) (eq? op2 (cadr (assq op1 relops)))) (return (if ((symbol->value op1) c1 c2) `(,op1 ,x ,c1) `(,op2 ,x ,c2)))) ((eq? op1 (caddr (assq op2 relops))) (if ((symbol->value op1) c2 c1) (return `(,op1 ,c2 ,x ,c1)) (if (memq op1 gts) (return #f)))) ((and (eq? op2 (hash-table-ref reversibles (cadr (assq op1 relops)))) ((symbol->value op1) c1 c2)) (return #f)))) ((eq? op2 (caddr (assq op1 relops))) (return `(,op1 ,c2 ,x ,c1))))) ((or) (cond ((equal? c1 c2) (cond ((eq? op1 op2) (return `(,op1 ,x ,c1))) ((eq? op2 (cadr (assq op1 relops))) (return `(,(if (memq op2 gtes) op2 op1) ,x ,c1))) ((and (memq op1 gts) (memq op2 gts)) (return `(not (,eqop ,x ,c1)))) (else (return #t)))) ((and (typer c1) (typer c2)) (cond ((or (eq? op1 op2) (eq? op2 (cadr (assq op1 relops)))) (return (if ((symbol->value op1) c1 c2) `(,op2 ,x ,c2) `(,op1 ,x ,c1)))) ((eq? op1 (caddr (assq op2 relops))) (if ((symbol->value op1) c2 c1) (return #t)) (return `(not (,(cadr (assq op1 relops)) ,c1 ,x ,c2)))) ((and (eq? op2 (hash-table-ref reversibles (cadr (assq op1 relops)))) ((symbol->value op1) c2 c1)) (return #t)))) ((eq? op2 (caddr (assq op1 relops))) (return `(not (,(cadr (assq op1 relops)) ,c1 ,x ,c2))))))))))))))) 'ok)))))) (lambda (in-form true false env) (define (classify e) (if (not (just-constants? e env)) e (catch #t (lambda () (let ((val (eval e))) (if (boolean? val) val e))) (lambda ignore e)))) (define (contradictory? ands) (let ((vars ())) (call-with-exit (lambda (return) (do ((b ands (cdr b))) ((null? b) #f) (if (and (pair? b) (pair? (car b)) (pair? (cdar b))) (let ((func (caar b)) (args (cdar b))) (if (memq func '(eq? eqv? equal?)) (if (and (symbol? (car args)) (code-constant? (cadr args))) (set! func (->lint-type (cadr args))) (if (and (symbol? (cadr args)) (code-constant? (car args))) (set! func (->lint-type (car args)))))) (if (symbol? func) (for-each (lambda (arg) (if (symbol? arg) (let ((type (assq arg vars))) (if (not type) (set! vars (cons (cons arg func) vars)) (if (not (compatible? (cdr type) func)) (return #t)))))) args))))))))) (define (and-redundants env . args) (do ((locals ()) (diffs #f) (p args (cdr p))) ((or (null? p) (not (and (pair? (car p)) (pair? (cdar p)) (hash-table-ref booleans (caar p))))) (and (null? p) (pair? locals) (or diffs (any? (lambda (a) (pair? (cddr a))) locals)) (let ((keepers ())) (for-each (lambda (a) (cond ((null? (cddr a)) (set! keepers (cons (cadr a) keepers))) ((null? (cdddr a)) (let ((res (apply and-redundant? (reverse (cdr a))))) (if res (begin (set! keepers (cons ((if (eq? res (caadr a)) cadr caddr) a) keepers)) (set! diffs #t)) (set! keepers (cons (cadr a) (cons (caddr a) keepers)))))) (else (let ((ar (reverse (cdr a)))) (let ((res1 (and-redundant? (car ar) (cadr ar))) ; if res1 either 1 or 2 is out (res2 (and-redundant? (cadr ar) (caddr ar))) ; if res2 either 2 or 3 is out (res3 (and-redundant? (car ar) (caddr ar)))) ; if res3 either 1 or 3 is out ;; only in numbers can 3 actually be reducible (if (not (or res1 res2 res3)) (set! keepers (append (cdr a) keepers)) (begin (set! diffs #t) (if (and (or (not res1) (eq? res1 (caar ar))) (or (not res3) (eq? res3 (caar ar)))) (set! keepers (cons (car ar) keepers))) (if (and (or (not res1) (eq? res1 (caadr ar))) (or (not res2) (eq? res2 (caadr ar)))) (set! keepers (cons (cadr ar) keepers))) (if (and (or (not res2) (eq? res2 (car (caddr ar)))) (or (not res3) (eq? res3 (car (caddr ar))))) (set! keepers (cons (caddr ar) keepers))) (if (pair? (cdddr ar)) (set! keepers (append (reverse (cdddr ar)) keepers)))))))))) (reverse locals)) (and diffs (reverse keepers))))) (let* ((bool (car p)) (local (assoc (cadr bool) locals))) (if (pair? local) (if (member bool (cdr local)) (set! diffs #t) (set-cdr! local (cons bool (cdr local)))) (set! locals (cons (list (cadr bool) bool) locals)))))) (define (and-not-redundant arg1 arg2) (let ((type1 (car arg1)) ; (? ...) (type2 (caadr arg2))) ; (not (? ...)) (and (symbol? type1) (symbol? type2) (or (hash-table-ref booleans type1) (memq type1 '(= char=? string=?))) (hash-table-ref booleans type2) (if (eq? type1 type2) ; (and (?) (not (?))) -> #f 'contradictory (case type1 ((pair?) (case type2 ((list?) 'contradictory) ((proper-list?) #f) (else arg1))) ((null?) (if (eq? type2 'list?) 'contradictory arg1)) ((list?) (case type2 ((pair?) 'null?) ((null?) 'pair?) ((proper-list?) #f) (else arg1))) ((proper-list?) (case type2 ((list? pair?) 'contradictory) ((null?) #f) (else arg1))) ((symbol?) (and (not (memq type2 '(keyword? gensym?))) arg1)) ((char=?) (if (eq? type2 'char?) 'contradictory (and (or (char? (cadr arg1)) (char? (caddr arg1))) `(eqv? ,@(cdr arg1))))) ; arg2 might be (not (eof-object?...)) ((real?) (case type2 ((rational? exact?) `(float? ,@(cdr arg1))) ((inexact?) `(rational? ,@(cdr arg1))) ((complex? number?) 'contradictory) ((negative? positive? even? odd? zero? integer?) #f) (else arg1))) ((integer?) (case type2 ((real? complex? number? rational? exact?) 'contradictory) ((float? inexact? infinite? nan?) arg1) (else #f))) ((rational?) (case type2 ((real? complex? number? exact?) 'contradictory) ((float? inexact? infinite? nan?) arg1) (else #f))) ((complex? number?) (and (memq type2 '(complex? number?)) 'contradictory)) ((float?) (case type2 ((real? complex? number? inexact?) 'contradictory) ((rational? integer? exact?) arg1) (else #f))) ((exact?) (case type2 ((rational?) 'contradictory) ((inexact? infinite? nan?) arg1) (else #f))) ((even? odd?) (case type2 ((integer? exact? rational? real? number? complex?) 'contradictory) ((infinite? nan?) arg1) (else #f))) ((zero? negative? positive?) (and (memq type2 '(complex? number? real?)) 'contradictory)) ((infinite? nan?) (case type2 ((number? complex? inexact?) 'contradictory) ((integer? rational? exact? even? odd?) arg1) (else #f))) ((char-whitespace? char-numeric? char-alphabetic? char-upper-case? char-lower-case?) (and (eq? type2 'char?) 'contradictory)) ((directory? file-exists?) (and (memq type2 '(string? sequence?)) 'contradictory)) (else ;; none of the rest happen #f)))))) (define (or-not-redundant arg1 arg2) (let ((type1 (car arg1)) ; (? ...) (type2 (caadr arg2))) ; (not (? ...)) (and (symbol? type1) (symbol? type2) (or (hash-table-ref bools type1) (memq type1 '(= char=? string=?))) (hash-table-ref bools type2) (if (eq? type1 type2) ; (or (?) (not (?))) -> #t 'fatuous (case type1 ((null?) (case type2 ((list?) ; not proper-list? here `(not (pair? ,(cadr arg1)))) ((proper-list?) #f) (else arg2))) ((eof-object?) arg2) ; not keyword? here because (or (not (symbol? x)) (keyword? x)) is not reducible to (not (symbol? x)) ((string?) (and (not (eq? type2 'byte-vector?)) arg2)) (else #f)))))) (define (bsimp x) ; quick check for common easy cases (set! last-simplify-boolean-line-number line-number) (if (not (and (pair? x) (pair? (cdr x)))) x (case (car x) ((and) (and (cadr x) ; (and #f ...) -> #f x)) ((or) (if (and (cadr x) ; (or #t ...) -> #t (code-constant? (cadr x))) (cadr x) x)) (else (if (not (and (= (length x) 2) (pair? (cadr x)) (symbol? (caadr x)))) x (let ((rt (if (eq? (caadr x) 'quote) (->simple-type (cadadr x)) (return-type (caadr x) env))) (head (car x))) (or (and (subsumes? head rt) #t) ; don't return the memq list! (and (or (memq rt '(#t #f values)) (any-compatible? head rt)) (case head ((null?) (if (eq? (caadr x) 'list) (null? (cdadr x)) x)) ((pair?) (if (eq? (caadr x) 'list) (pair? (cdadr x)) x)) ((negative?) (and (not (hash-table-ref non-negative-ops (caadr x))) x)) (else x)))))))))) (define (bcomp x) ; not so quick... (cond ((not (pair? x)) x) ((eq? (car x) 'and) (call-with-exit (lambda (return) (let ((newx (list 'and))) (do ((p (cdr x) (cdr p)) (sidex newx) (endx newx)) ((null? p) newx) (let ((next (car p))) (if (or (not next) ; #f in and -> end of expr (member next false)) (if (eq? sidex newx) ; no side-effects (return #f) (begin (set-cdr! endx (list #f)) (return newx))) (if (or (code-constant? next) ; (and ... true-expr ...) (member next sidex) ; if a member, and no side-effects since, it must be true (member next true)) (if (and (null? (cdr p)) (not (equal? next (car endx)))) (set-cdr! endx (list next))) (begin (set-cdr! endx (list next)) (set! endx (cdr endx)) (if (side-effect? next env) (set! sidex endx))))))))))) ((not (eq? (car x) 'or)) x) (else (call-with-exit (lambda (return) (let ((newx (list 'or))) (do ((p (cdr x) (cdr p)) (sidex newx) (endx newx)) ((null? p) newx) (let ((next (car p))) (if (or (and next ; (or ... #t ...) (code-constant? next)) (member next true)) (begin (set-cdr! endx (list next)) (return newx)) ; we're done since this is true (if (or (not next) (member next sidex) ; so its false in some way (member next false)) (if (and (null? (cdr p)) (not (equal? next (car endx)))) (set-cdr! endx (list next))) (begin (set-cdr! endx (list next)) (set! endx (cdr endx)) (if (side-effect? next env) (set! sidex endx))))))))))))) (define (gather-or-eqf-elements eqfnc sym vals) (let* ((func (case eqfnc ((eq?) 'memq) ((eqv? char=?) 'memv) (else 'member))) (equals (if (and (eq? func 'member) (not (eq? eqfnc 'equal?))) (list eqfnc) ())) (elements (lint-remove-duplicates (map unquoted vals) env))) (cond ((null? (cdr elements)) `(,eqfnc ,sym ,@elements)) ((and (eq? eqfnc 'char=?) (= (length elements) 2) (char-ci=? (car elements) (cadr elements))) `(char-ci=? ,sym ,(car elements))) ((and (eq? eqfnc 'string=?) (= (length elements) 2) (string-ci=? (car elements) (cadr elements))) `(string-ci=? ,sym ,(car elements))) ((member elements '((#t #f) (#f #t))) `(boolean? ,sym)) ; zero? doesn't happen (else `(,func ,sym ',(reverse elements) ,@equals))))) (define (reversible-member expr lst) (and (pair? lst) (or (member expr lst) (and (eqv? (length expr) 3) (let ((rev-op (hash-table-ref reversibles (car expr)))) (and rev-op (member (list rev-op (caddr expr) (cadr expr)) lst))))))) (define and-rel-ops (let ((h (make-hash-table))) (for-each (lambda (op) (hash-table-set! h op #t)) '(< = > <= >= char-ci>=? char-ci<? char-ready? char<? char-ci=? char>? char<=? char-ci>? char-ci<=? char>=? char=? string-ci<=? string=? string-ci>=? string<? string-ci<? string-ci=? string-ci>? string>=? string<=? string>? eqv? equal? eq? morally-equal?)) h)) ;; -------------------------------- ;; start of simplify-boolean code ;; this is not really simplify boolean as in boolean algebra because in scheme there are many unequal truths, but only one falsehood ;; 'and and 'or are not boolean operators in a sense ;; (format *stderr* "simplify: ~A~%" in-form) (and (not (or (reversible-member in-form false) (and (pair? in-form) (eq? (car in-form) 'not) (pair? (cdr in-form)) ; (not)! (reversible-member (cadr in-form) true)))) (or (and (reversible-member in-form true) #t) (and (pair? in-form) (eq? (car in-form) 'not) (pair? (cdr in-form)) (reversible-member (cadr in-form) false) #t) (if (not (pair? in-form)) in-form (let ((form (bcomp (bsimp in-form)))) (if (not (and (pair? form) (memq (car form) '(or and not)))) (classify form) (let ((len (length form))) (let ((op (case (car form) ((or) 'and) ((and) 'or) (else #f)))) (if (and op (>= len 3) (every? (lambda (p) (and (pair? p) (pair? (cdr p)) (pair? (cddr p)) (eq? (car p) op))) (cdr form))) (let ((first (cadadr form))) (if (every? (lambda (p) (equal? (cadr p) first)) (cddr form)) (set! form `(,op ,first (,(car form) ,@(map (lambda (p) (if (null? (cdddr p)) (caddr p) `(,op ,@(cddr p)))) (cdr form))))) (if (null? (cdddr (cadr form))) (let ((last (caddr (cadr form)))) (if (every? (lambda (p) (and (null? (cdddr p)) (equal? (caddr p) last))) (cddr form)) (set! form `(,op (,(car form) ,@(map cadr (cdr form))) ,last))))))))) ;; (or (and A B) (and A C)) -> (and A (or B C)) ;; (or (and A B) (and C B)) -> (and (or A C) B) ;; (and (or A B) (or A C)) -> (or A (and B C)) ;; (and (or A B) (or C B)) -> (or (and A C) B) (case (car form) ;; -------------------------------- ((not) (if (not (= len 2)) form (let* ((arg (cadr form)) (val (classify (if (and (pair? arg) (memq (car arg) '(and or not))) (simplify-boolean arg true false env) arg))) (arg-op (and (pair? arg) (car arg)))) (cond ((boolean? val) (not val)) ((or (code-constant? arg) (and (pair? arg) (symbol? arg-op) (hash-table-ref no-side-effect-functions arg-op) (let ((ret (return-type arg-op env))) (and (or (symbol? ret) (pair? ret)) (not (return-type-ok? 'boolean? ret)))) (not (var-member arg-op env)))) #f) ((and (pair? val) ; (not (not ...)) -> ... (pair? (cdr val)) ; this is usually internally generated, (memq (car val) '(not if cond case begin))) ; so the message about (and x #t) is in special-case-functions below (case (car val) ((not) (cadr val)) ((if) (let ((if-true (simplify-boolean `(not ,(caddr val)) () () env)) (if-false (or (not (pair? (cdddr val))) ; (not #<unspecified>) -> #t (simplify-boolean `(not ,(cadddr val)) () () env)))) ;; ideally we'd call if-walker on this to simplify further `(if ,(cadr val) ,if-true ,if-false))) ((cond case) `(,(car val) ,@(if (eq? (car val) 'cond) () (list (cadr val))) ,@(map (lambda (c) (if (not (and (pair? c) (pair? (cdr c)))) c (let* ((len (length (cdr c))) (new-last (let ((last (list-ref c len))) (if (and (pair? last) (eq? (car last) 'error)) last (simplify-boolean `(not ,last) () () env))))) `(,(car c) ,@(copy (cdr c) (make-list (- len 1))) ,new-last)))) ((if (eq? (car val) 'cond) cdr cddr) val)))) ((begin) (let* ((len1 (- (length val) 1)) (new-last (simplify-boolean `(not ,(list-ref val len1)) () () env))) `(,@(copy val (make-list len1)) ,new-last))))) ((not (equal? val arg)) `(not ,val)) ((not (pair? arg)) form) ((and (memq arg-op '(and or)) ; (not (or|and x (not y))) -> (and|or (not x) y) (= (length arg) 3) (or (and (pair? (cadr arg)) (eq? (caadr arg) 'not)) (and (pair? (caddr arg)) (eq? (caaddr arg) 'not)))) (let ((rel (if (eq? arg-op 'or) 'and 'or))) `(,rel ,@(map (lambda (p) (if (and (pair? p) (eq? (car p) 'not)) (cadr p) (simplify-boolean `(not ,p) () () env))) (cdr arg))))) ((<= (length arg) 3) ; avoid (<= 0 i 12) and such (case arg-op ((< > <= >= odd? even? exact? inexact?char<? char>? char<=? char>=? string<? string>? string<=? string>=? char-ci<? char-ci>? char-ci<=? char-ci>=? string-ci<? string-ci>? string-ci<=? string-ci>=?) `(,(hash-table-ref notables arg-op) ,@(cdr arg))) ;; null? is not quite right because (not (null? 3)) -> #t ;; char-upper-case? and lower are not switchable here ((zero?) ; (not (zero? (logand p 2^n | (ash 1 i)))) -> (logbit? p i) (let ((zarg (cadr arg))) ; (logand...) (if (not (and (pair? zarg) (eq? (car zarg) 'logand) (pair? (cdr zarg)) (pair? (cddr zarg)) (null? (cdddr zarg)))) form (let ((arg1 (cadr zarg)) (arg2 (caddr zarg))) ; these are never reversed (or (and (pair? arg2) (pair? (cdr arg2)) (eq? (car arg2) 'ash) (eqv? (cadr arg2) 1) `(logbit? ,arg1 ,(caddr arg2))) (and (integer? arg2) (positive? arg2) (zero? (logand arg2 (- arg2 1))) ; it's a power of 2 `(logbit? ,arg1 ,(floor (log arg2 2)))) ; floor for freeBSD? form))))) (else form))) (else form))))) ;; -------------------------------- ((or) (case len ((1) #f) ((2) (if (code-constant? (cadr form)) (cadr form) (classify (cadr form)))) (else (call-with-exit (lambda (return) (when (= len 3) (let ((arg1 (cadr form)) (arg2 (caddr form))) (if (and (pair? arg2) ; (or A (and ... A ...)) -> A (eq? (car arg2) 'and) (member arg1 (cdr arg2)) (not (side-effect? arg2 env))) (return arg1)) (if (and (pair? arg1) ; (or (and ... A) A) -> A (eq? (car arg1) 'and) (equal? arg2 (list-ref arg1 (- (length arg1) 1))) (not (side-effect? arg1 env))) (return arg2)) (when (pair? arg2) (if (and (eq? (car arg2) 'and) ; (or A (and (not A) B)) -> (or A B) (pair? (cadr arg2)) (eq? (caadr arg2) 'not) (equal? arg1 (cadadr arg2))) (return `(or ,arg1 ,@(cddr arg2)))) (when (pair? arg1) (when (eq? (car arg1) 'not) (if (symbol? (cadr arg1)) (if (memq (cadr arg1) arg2) (begin (if (eq? (car arg2) 'boolean?) (return arg2)) (and-incomplete form 'or (cadr arg1) arg2 env)) (do ((p arg2 (cdr p))) ((or (not (pair? p)) (and (pair? (car p)) (memq (cadr arg1) (car p)))) (if (pair? p) (and-incomplete form 'or (cadr arg1) (car p) env))))) (if (and (pair? (cadr arg1)) ; (or (not (number? x)) (> x 2)) -> (or (not (real? x)) (> x 2)) (hash-table-ref bools (caadr arg1))) (if (member (cadadr arg1) arg2) (and-forgetful form 'or (cadr arg1) arg2 env) (do ((p arg2 (cdr p))) ((or (not (pair? p)) (and (pair? (car p)) (member (cadadr arg1) (car p)))) (if (pair? p) (and-forgetful form 'or (cadr arg1) (car p) env))))))) (if (and (eq? (car arg2) 'and) ; (or (not A) (and A B)) -> (or (not A) B) -- this stuff actually happens! (equal? (cadr arg1) (cadr arg2))) (return `(or ,arg1 ,@(cddr arg2))))) (when (and (eq? (car arg1) 'and) (eq? (car arg2) 'and) (= 3 (length arg1) (length arg2)) ;; (not (side-effect? arg1 env)) ; maybe?? (or (equal? (cadr arg1) `(not ,(cadr arg2))) (equal? `(not ,(cadr arg1)) (cadr arg2))) (not (equal? (caddr arg1) `(not ,(caddr arg2)))) (not (equal? `(not ,(caddr arg1)) (caddr arg2)))) ;; kinda dumb, but common: (or (and A B) (and (not A) C)) -> (if A B C) ;; the other side: (and (or A B) (or (not A) C)) -> (if A C (and B #t)), but it never happens (lint-format "perhaps ~A" 'or (lists->string form (if (and (pair? (cadr arg1)) (eq? (caadr arg1) 'not)) `(if ,(cadr arg2) ,(caddr arg2) ,(caddr arg1)) `(if ,(cadr arg1) ,(caddr arg1) ,(caddr arg2)))))) (let ((t1 (and (pair? (cdr arg1)) (pair? (cdr arg2)) (or (equal? (cadr arg1) (cadr arg2)) (and (pair? (cddr arg2)) (null? (cdddr arg2)) (equal? (cadr arg1) (caddr arg2)))) (not (side-effect? arg1 env)) (and-redundant? arg1 arg2)))) (if t1 (return (if (eq? t1 (car arg1)) arg2 arg1)))) ;; if all clauses are (eq-func x y) where one of x/y is a symbol|simple-expr repeated throughout ;; and the y is a code-constant, or -> memq and friends. ;; This could also handle cadr|caddr reversed, but it apparently never happens. (if (and (or (and (eq? (car arg2) '=) (memq (car arg1) '(< > <= >=))) (and (eq? (car arg1) '=) (memq (car arg2) '(< > <= >=)))) (= (length arg1) 3) (equal? (cdr arg1) (cdr arg2))) (return `(,(if (or (memq (car arg1) '(< <=)) (memq (car arg2) '(< <=))) '<= '>=) ,@(cdr arg1)))) ;; this makes some of the code above redundant (let ((rel (relsub arg1 arg2 'or env))) (if (or (boolean? rel) (pair? rel)) (return rel))) ;; (or (pair? x) (null? x)) -> (list? x) (when (and (pair? (cdr arg1)) (pair? (cdr arg2)) (equal? (cadr arg1) (cadr arg2))) (if (and (memq (car arg1) '(null? pair?)) (memq (car arg2) '(null? pair?)) (not (eq? (car arg1) (car arg2)))) (return `(list? ,(cadr arg1)))) (if (and (eq? (car arg1) 'zero?) ; (or (zero? x) (positive? x)) -> (not (negative? x)) -- other cases don't happen (memq (car arg2) '(positive? negative?))) (return `(not (,(if (eq? (car arg2) 'positive?) 'negative? 'positive?) ,(cadr arg1)))))) ;; (or (and A B) (and (not A) (not B))) -> (eq? (not A) (not B)) ;; more accurately (if A B (not B)), but every case I've seen is just boolean ;; perhaps also (or (not (or A B)) (not (or (not A) (not B)))), but it never happens (let ((a1 (cadr form)) (a2 (caddr form))) (when (and (pair? a1) (pair? a2) (eq? (car a1) 'and) (eq? (car a2) 'and) (= (length a1) 3) (= (length a2) 3)) (let ((A ((if (and (pair? (cadr a1)) (eq? (caadr a1) 'not)) cadadr cadr) a1)) (B (if (and (pair? (caddr a1)) (eq? (caaddr a1) 'not)) (cadr (caddr a1)) (caddr a1)))) (if (or (equal? form `(or (and ,A ,B) (and (not ,A) (not ,B)))) (equal? form `(or (and (not ,A) (not ,B)) (and ,A ,B)))) (return `(eq? (not ,A) (not ,B)))) (if (or (equal? form `(or (and ,A (not ,B)) (and (not ,A) ,B))) (equal? form `(or (and (not ,A) ,B) (and ,A (not ,B))))) (return `(not (eq? (not ,A) (not ,B)))))))) (when (and (pair? (cdr arg1)) (pair? (cdr arg2)) (not (eq? (car arg1) (car arg2)))) (when (subsumes? (car arg1) (car arg2)) (return arg1)) (if (eq? (car arg1) 'not) (let ((temp arg1)) (set! arg1 arg2) (set! arg2 temp))) (if (and (eq? (car arg2) 'not) (pair? (cadr arg2)) (pair? (cdadr arg2)) (not (eq? (caadr arg2) 'let?)) (or (equal? (cadr arg1) (cadadr arg2)) (and (pair? (cddr arg1)) (equal? (caddr arg1) (cadadr arg2)))) (eq? (return-type (car arg1) env) 'boolean?) (eq? (return-type (caadr arg2) env) 'boolean?)) (let ((t2 (or-not-redundant arg1 arg2))) (when t2 (if (eq? t2 'fatuous) (return #t) (if (pair? t2) (return t2))))))) ;; (or (if a c d) (if b c d)) -> (if (or a b) c d) never happens, sad to say ;; or + if + if does happen but not in this easily optimized form )))) ; len = 3 ;; len > 3 or nothing was caught above (let ((nots 0) (revers 0) (arglen (- len 1))) (for-each (lambda (a) (if (pair? a) (if (eq? (car a) 'not) (set! nots (+ nots 1)) (if (hash-table-ref notables (car a)) (set! revers (+ revers 1)))))) (cdr form)) (if (= nots arglen) ; every arg is `(not ...) (let ((nf (simplify-boolean `(and ,@(map cadr (cdr form))) () () env))) (return (simplify-boolean `(not ,nf) () () env))) (if (and (> arglen 2) (or (> nots (/ (* 2 arglen) 3)) (and (> arglen 2) (> nots (/ arglen 2)) (> revers 0)))) (let ((nf (simplify-boolean `(and ,@(map (lambda (p) (cond ((not (pair? p)) `(not ,p)) ((eq? (car p) 'not) (cadr p)) ((hash-table-ref notables (car p)) => (lambda (op) `(,op ,@(cdr p)))) (else `(not ,p)))) (cdr form))) () () env))) (return (simplify-boolean `(not ,nf) () () env)))))) (let ((sym #f) (eqfnc #f) (vals ()) (start #f)) (define (constant-arg p) (if (code-constant? (cadr p)) (set! vals (cons (cadr p) vals)) (and (code-constant? (caddr p)) (set! vals (cons (caddr p) vals))))) (define (upgrade-eqf) (set! eqfnc (if (memq eqfnc '(string=? string-ci=? = equal?)) 'equal? (if (memq eqfnc '(#f eq?)) 'eq? 'eqv?)))) (do ((fp (cdr form) (cdr fp))) ((null? fp)) (let ((p (and (pair? fp) (car fp)))) (if (and (pair? p) (if (not sym) (set! sym (eqv-selector p)) (equal? sym (eqv-selector p))) (or (not (memq eqfnc '(char-ci=? string-ci=? =))) (memq (car p) '(char-ci=? string-ci=? =))) ;; = can't share: (equal? 1 1.0) -> #f, so (or (not x) (= x 1)) can't be simplified ;; except via member+morally-equal? but that brings in float-epsilon and NaN differences. ;; We could add both: 1 1.0 as in cond? ;; ;; another problem: using memx below means the returned value of the expression ;; may not match the original (#t -> '(...)), so perhaps we should add a one-time ;; warning about this, and wrap it in (pair? (mem...)) as an example. ;; ;; and another thing... the original might be broken: (eq? x #(1)) where equal? ;; is more sensible, but that also changes the behavior of the expression: ;; (memq x '(#(1))) may be #f (or #t!) when (member x '(#(1))) is '(#(1)). ;; ;; I think I'll try to turn out a more-or-less working expression, but warn about it. (case (car p) ((string=? equal?) (set! eqfnc (if (or (not eqfnc) (eq? eqfnc (car p))) (car p) 'equal?)) (and (= (length p) 3) (constant-arg p))) ((char=?) (if (memq eqfnc '(#f char=?)) (set! eqfnc 'char=?) (if (not (eq? eqfnc 'equal?)) (set! eqfnc 'eqv?))) (and (= (length p) 3) (constant-arg p))) ((eq? eqv?) (let ((leqf (car (->eqf (->lint-type ((if (code-constant? (cadr p)) cadr caddr) p)))))) (cond ((not eqfnc) (set! eqfnc leqf)) ((or (memq leqf '(#t equal?)) (not (eq? eqfnc leqf))) (set! eqfnc 'equal?)) ((memq eqfnc '(#f eq?)) (set! eqfnc leqf)))) (and (= (length p) 3) (constant-arg p))) ((char-ci=? string-ci=? =) (and (or (not eqfnc) (eq? eqfnc (car p))) (set! eqfnc (car p)) (= (length p) 3) (constant-arg p))) ((eof-object?) (upgrade-eqf) (set! vals (cons #<eof> vals))) ((not) (upgrade-eqf) (set! vals (cons #f vals))) ((boolean?) (upgrade-eqf) (set! vals (cons #f (cons #t vals)))) ((zero?) (if (memq eqfnc '(#f eq?)) (set! eqfnc 'eqv?)) (set! vals (cons 0 (cons 0.0 vals)))) ((null?) (upgrade-eqf) (set! vals (cons () vals))) ((memq memv member) (cond ((eq? (car p) 'member) (set! eqfnc 'equal?)) ((eq? (car p) 'memv) (set! eqfnc (if (eq? eqfnc 'string=?) 'equal? 'eqv?))) ((not eqfnc) (set! eqfnc 'eq?))) (and (= (length p) 3) (pair? (caddr p)) (eq? 'quote (caaddr p)) (pair? (cadr (caddr p))) (set! vals (append (cadr (caddr p)) vals)))) (else #f))) (if (not start) (set! start fp) (if (null? (cdr fp)) (return (if (eq? start (cdr form)) (gather-or-eqf-elements eqfnc sym vals) `(or ,@(copy (cdr form) (make-list (let loop ((g (cdr form)) (len 0)) (if (eq? g start) len (loop (cdr g) (+ len 1)))))) ,(gather-or-eqf-elements eqfnc sym vals)))))) (when start (if (eq? fp (cdr start)) (begin (set! sym #f) (set! eqfnc #f) (set! vals ()) (set! start #f)) ;; here we have possible header stuff + more than one match + trailing stuff (let ((trailer (if (not (and (pair? fp) (pair? (cdr fp)))) fp (let ((nfp (simplify-boolean `(or ,@fp) () () env))) ((if (and (pair? nfp) (eq? (car nfp) 'or)) cdr list) nfp))))) (return (if (eq? start (cdr form)) `(or ,(gather-or-eqf-elements eqfnc sym vals) ,@trailer) `(or ,@(copy (cdr form) (make-list (let loop ((g (cdr form)) (len 0)) (if (eq? g start) len (loop (cdr g) (+ len 1)))))) ,(gather-or-eqf-elements eqfnc sym vals) ,@trailer))))))))) (do ((selector #f) ; (or (and (eq?...)...)....) -> (case ....) (keys ()) (fp (cdr form) (cdr fp))) ((or (null? fp) (let ((p (and (pair? fp) (car fp)))) (not (and (pair? p) (eq? (car p) 'and) (pair? (cdr p)) (pair? (cadr p)) (pair? (cdadr p)) (or selector (set! selector (cadadr p))) (let ((expr (cadr p))) (case (car expr) ((null?) (and (equal? selector (cadr expr)) (not (memq () keys)) (set! keys (cons () keys)))) ;; we have to make sure no keys are repeated: ;; (or (and (eq? x 'a) (< y 1)) (and (eq? x 'a) (< y 2))) ;; this rewrite has become much trickier than expected... ((boolean?) (and (equal? selector (cadr expr)) (not (memq #f keys)) (not (memq #t keys)) (set! keys (cons #f (cons #t keys))))) ((eof-object?) (and (equal? selector (cadr expr)) (not (memq #<eof> keys)) (set! keys (cons #<eof> keys)))) ((zero?) (and (equal? selector (cadr expr)) (not (memv 0 keys)) (not (memv 0.0 keys)) (set! keys (cons 0.0 (cons 0 keys))))) ((memq memv) (and (equal? selector (cadr expr)) (pair? (cddr expr)) (pair? (caddr expr)) (eq? (caaddr expr) 'quote) (pair? (cadr (caddr expr))) (not (any? (lambda (g) (memv g keys)) (cadr (caddr expr)))) (set! keys (append (cadr (caddr expr)) keys)))) ((eq? eqv? char=?) (and (pair? (cddr expr)) (null? (cdddr expr)) (or (and (equal? selector (cadr expr)) (code-constant? (caddr expr)) (not (memv (unquoted (caddr expr)) keys)) (set! keys (cons (unquoted (caddr expr)) keys))) (and (equal? selector (caddr expr)) (code-constant? (cadr expr)) (not (memv (unquoted (cadr expr)) keys)) (set! keys (cons (unquoted (cadr expr)) keys)))))) ((not) ;; no hits here for last+not eq(etc)+no collision in keys (and (equal? selector (cadr expr)) (not (memq #f keys)) (set! keys (cons #f keys)))) (else #f))))))) (if (null? fp) (return `(case ,selector ,@(map (lambda (p) (let ((result (if (null? (cdddr p)) (caddr p) `(and ,@(cddr p)))) (key (let ((expr (cadr p))) (case (car expr) ((eq? eqv? char=?) (if (equal? selector (cadr expr)) (list (unquoted (caddr expr))) (list (unquoted (cadr expr))))) ((memq memv) (unquoted (caddr expr))) ((null?) (list ())) ((eof-object?) (list #<eof>)) ((zero?) (list 0 0.0)) ((not) (list #f)) ((boolean?) (list #t #f)))))) (list key result))) (cdr form)) (else #f)))))) (do ((new-form ()) (retry #f) (exprs (cdr form) (cdr exprs))) ((null? exprs) (return (and (pair? new-form) (if (null? (cdr new-form)) (car new-form) (if retry (simplify-boolean `(or ,@(reverse new-form)) () () env) `(or ,@(reverse new-form))))))) (let ((val (classify (car exprs))) (old-form new-form)) (when (and (pair? val) (memq (car val) '(and or not))) (set! val (classify (simplify-boolean val true false env))) (when (and (> len 3) (pair? val) (eq? (car val) 'not) (pair? (cdr exprs))) (if (symbol? (cadr val)) (if (and (pair? (cadr exprs)) (memq (cadr val) (cadr exprs))) (and-incomplete form 'or (cadr val) (cadr exprs) env) (do ((ip (cdr exprs) (cdr ip)) (found-it #f)) ((or found-it (not (pair? ip)))) (do ((p (car ip) (cdr p))) ((or (not (pair? p)) (and (memq (cadr val) p) (set! found-it p))) (if (pair? found-it) (and-incomplete form 'or (cadr val) found-it env)))))) (when (and (pair? (cadr val)) (pair? (cadr exprs)) (hash-table-ref bools (caadr val))) (if (member (cadadr val) (cadr exprs)) (and-forgetful form 'or (cadr val) (cadr exprs) env) (do ((p (cadr exprs) (cdr p))) ((or (not (pair? p)) (and (pair? (car p)) (member (cadadr val) (car p)))) (if (pair? p) (and-forgetful form 'or (cadr val) (car p) env))))))))) (if (not (or retry (equal? val (car exprs)))) (set! retry #t)) (if val ; #f in or is ignored (cond ((or (eq? val #t) ; #t or any non-#f constant in or ends the expression (code-constant? val)) (set! new-form (if (null? new-form) ; (or x1 123) -> value of x1 first (list val) (cons val new-form))) ;; reversed when returned (set! exprs '(#t))) ((and (pair? val) ; (or ...) -> splice into current (eq? (car val) 'or)) (set! exprs (append val (cdr exprs)))) ; we'll skip the 'or in do step ((not (or (memq val new-form) (and (pair? val) ; and redundant tests (hash-table-ref booleans (car val)) (any? (lambda (p) (and (pair? p) (subsumes? (car p) (car val)) (equal? (cadr val) (cadr p)))) new-form)))) (set! new-form (cons val new-form))))) (if (and (not (eq? new-form old-form)) (pair? (cdr new-form))) (let ((rel (relsub (cadr new-form) (car new-form) 'or env))) ; new-form is reversed (if (or (boolean? rel) (pair? rel)) (set! new-form (cons rel (cddr new-form)))))))))))))) ;; -------------------------------- ((and) (case len ((1) #t) ((2) (classify (cadr form))) (else (and (not (contradictory? (cdr form))) (call-with-exit (lambda (return) (when (= len 3) (let ((arg1 (cadr form)) (arg2 (caddr form))) (if (and (pair? arg2) ; (and A (or A ...)) -> A (eq? (car arg2) 'or) (equal? arg1 (cadr arg2)) (not (side-effect? arg2 env))) (return arg1)) (if (and (pair? arg1) ; (and (or ... A ...) A) -> A (eq? (car arg1) 'or) (member arg2 (cdr arg1)) (not (side-effect? arg1 env))) (return arg2)) ;; the and equivalent of (or (not A) (and A B)) never happens (when (pair? arg2) (if (symbol? arg1) ; (and x (pair? x)) -> (pair? x) (if (memq arg1 arg2) (begin (case (car arg2) ((not) (return #f)) ((boolean?) (return `(eq? ,arg1 #t)))) (and-incomplete form 'and arg1 arg2 env) (if (hash-table-ref booleans (car arg2)) (return arg2))) (do ((p arg2 (cdr p))) ; (and x (+ (log x) 1)) -> (and (number? x)...) ((or (not (pair? p)) (and (pair? (car p)) (memq arg1 (car p)))) (if (pair? p) (and-incomplete form 'and arg1 (car p) env))))) (if (and (pair? arg1) ; (and (number? x) (> x 2)) -> (and (real? x) (> x 2)) (hash-table-ref bools (car arg1))) (if (member (cadr arg1) arg2) (and-forgetful form 'and arg1 arg2 env) (do ((p arg2 (cdr p))) ((or (not (pair? p)) (and (pair? (car p)) (member (cadr arg1) (car p)))) (if (pair? p) (and-forgetful form 'and arg1 (car p) env)))))))) (if (and (not (side-effect? arg1 env)) (equal? arg1 arg2)) ; (and x x) -> x (return arg1)) (when (and (pair? arg1) (pair? arg2) (pair? (cdr arg1)) (pair? (cdr arg2))) (let ((t1 (and (or (equal? (cadr arg1) (cadr arg2)) (and (pair? (cddr arg2)) (null? (cdddr arg2)) (equal? (cadr arg1) (caddr arg2)))) (not (side-effect? arg1 env)) (and-redundant? arg1 arg2)))) ; (and (integer? x) (number? x)) -> (integer? x) (if t1 (return (cond ((memq t1 '(eq? eqv? equal?)) `(,t1 ,@(cdr arg2))) ((eq? t1 'memv) (let ((x ((if (equal? (cadr arg1) (cadr arg2)) caddr cadr) arg2))) (if (rational? x) `(memv ,(cadr arg1) '(,x ,(* 1.0 x))) `(memv ,(cadr arg1) '(,(floor x) ,x))))) ((eq? t1 (car arg1)) arg1) (else arg2))))) (when (and (hash-table-ref reversibles (car arg1)) (pair? (cddr arg1)) (null? (cdddr arg1)) (pair? (cddr arg2)) (null? (cdddr arg2)) (not (side-effect? arg2 env)) ; arg1 is hit in any case (or (eq? (car arg1) (car arg2)) ; either ops are equal or (let ((rf (hash-table-ref reversibles (car arg2)))) ; try reversed op for arg2 (and (eq? (car arg1) rf) (set! arg2 (cons rf (reverse (cdr arg2)))))))) (when (and (memq (car arg1) '(< <= >= >)) ; (and (op x y) (op x z)) -> (op x (min|max y z)) (equal? (cadr arg1) (cadr arg2))) (if (and (rational? (caddr arg1)) (rational? (caddr arg2))) (return `(,(car arg1) ,(cadr arg1) ,((if (memq (car arg1) '(< <=)) min max) (caddr arg1) (caddr arg2))))) (return `(,(car arg1) ,(cadr arg1) (,(if (memq (car arg1) '(< <=)) 'min 'max) ,(caddr arg1) ,(caddr arg2))))) (when (or (equal? (caddr arg1) (cadr arg2)) ; (and (op x y) (op y z)) (equal? (cadr arg1) (caddr arg2)) ; (and (op x y) (op z x)) (and (memq (car arg1) '(= char=? string=? char-ci=? string-ci=?)) (or (equal? (cadr arg1) (cadr arg2)) (equal? (caddr arg1) (caddr arg2))))) (let ((op1 (car arg1)) (arg1-1 (cadr arg1)) (arg1-2 (caddr arg1)) (arg2-1 (cadr arg2)) (arg2-2 (caddr arg2))) (return (cond ((equal? arg1-2 arg2-1) ; (and (op x y) (op y z)) -> (op x y z) (if (equal? arg1-1 arg2-2) (if (memq op1 '(= char=? string=? char-ci=? string-ci=?)) arg1 (and (memq op1 '(<= >= char<=? char>=? string<=? string>=? char-ci<=? char-ci>=? string-ci<=? string-ci>=?)) `(,(case op1 ((>= <=) '=) ((char<= char>=) 'char=?) ((char-ci<= char-ci>=) 'char-ci=?) ((string<= string>=) 'string=?) ((string-ci<= string-ci>=) 'string-ci=?)) ,@(cdr arg1)))) (and (or (not (code-constant? arg1-1)) (not (code-constant? arg2-2)) ((symbol->value op1) arg1-1 arg2-2)) `(,op1 ,arg1-1 ,arg2-1 ,arg2-2)))) ((equal? arg1-1 arg2-2) ; (and (op x y) (op z x)) -> (op z x y) (if (equal? arg1-2 arg2-1) (and (memq op1 '(= char=? string=? char-ci=? string-ci=?)) arg1) (and (or (not (code-constant? arg2-1)) (not (code-constant? arg1-2)) ((symbol->value op1) arg2-1 arg1-2)) `(,op1 ,arg2-1 ,arg1-1 ,arg1-2)))) ;; here we're restricted to equalities and we know arg1 != arg2 ((equal? arg1-1 arg2-1) ; (and (op x y) (op x z)) -> (op x y z) (if (and (code-constant? arg1-2) (code-constant? arg2-2)) (and ((symbol->value op1) arg1-2 arg2-2) arg1) `(,op1 ,arg1-1 ,arg1-2 ,arg2-2))) ;; equalities again ((and (code-constant? arg1-1) (code-constant? arg2-1)) (and ((symbol->value op1) arg1-1 arg2-1) arg1)) (else `(,op1 ,arg1-1 ,arg1-2 ,arg2-1))))))) ;; check some special cases (when (and (or (equal? (cadr arg1) (cadr arg2)) (and (pair? (cddr arg2)) (null? (cdddr arg2)) (equal? (cadr arg1) (caddr arg2)))) (hash-table-ref booleans (car arg1))) (when (or (eq? (car arg1) 'zero?) ; perhaps rational? and integer? here -- not many hits (eq? (car arg2) 'zero?)) (if (or (memq (car arg1) '(integer? rational? exact?)) (memq (car arg2) '(integer? rational? exact?))) (return `(eqv? ,(cadr arg1) 0))) (if (or (eq? (car arg1) 'inexact?) (eq? (car arg2) 'inexact?)) (return `(eqv? ,(cadr arg1) 0.0)))) (when (hash-table-ref and-rel-ops (car arg2)) (when (and (eq? (car arg1) 'symbol?) (memq (car arg2) '(eq? eqv? equal?)) (or (quoted-symbol? (cadr arg2)) (quoted-symbol? (caddr arg2)))) (return `(eq? ,@(cdr arg2)))) (when (and (eq? (car arg1) 'positive?) (eq? (car arg2) '<) (eq? (cadr arg1) (cadr arg2))) (return `(< 0 ,(cadr arg1) ,(caddr arg2)))))) (when (and (member (cadr arg1) arg2) (memq (car arg2) '(string=? char=? eq? eqv? equal?)) (null? (cdddr arg2)) (hash-table-ref bools (car arg1)) (or (and (code-constant? (cadr arg2)) (compatible? (car arg1) (->lint-type (cadr arg2)))) (and (code-constant? (caddr arg2)) (compatible? (car arg1) (->lint-type (caddr arg2)))))) (return `(,(if (eq? (car arg1) 'char?) ,eqv? 'equal?) ,@(cdr arg2)))) (when (and (equal? (cadr arg1) (cadr arg2)) (eq? (car arg1) 'inexact?) (eq? (car arg2) 'real?)) (return `(and ,arg2 ,arg1))) ;; this makes some of the code above redundant (let ((rel (relsub arg1 arg2 'and env))) (if (or (boolean? rel) (pair? rel)) (return rel))) ;; (and ... (not...)) (unless (eq? (car arg1) (car arg2)) (if (eq? (car arg1) 'not) (let ((temp arg1)) (set! arg1 arg2) (set! arg2 temp))) (when (and (eq? (car arg2) 'not) (pair? (cadr arg2)) (pair? (cdadr arg2)) (not (eq? (caadr arg2) 'let?)) (or (equal? (cadr arg1) (cadadr arg2)) (and (pair? (cddr arg1)) (equal? (caddr arg1) (cadadr arg2)))) (eq? (return-type (car arg1) env) 'boolean?) (eq? (return-type (caadr arg2) env) 'boolean?)) (let ((t2 (and-not-redundant arg1 arg2))) (cond ;((not t2) #f) ((eq? t2 'contradictory) (return #f)) ((symbol? t2) (return `(,t2 ,@(cdr arg1)))) ((pair? t2) (return t2)))))) (if (hash-table-ref bools (car arg1)) (let ((p (member (cadr arg1) (cdr arg2)))) (when p (let ((sig (arg-signature (car arg2) env)) (pos (- (length arg2) (length p)))) (when (pair? sig) (let ((arg-type (and (> (length sig) pos) (list-ref sig pos)))) (unless (compatible? (car arg1) arg-type) (let ((ln (and (< 0 line-number 100000) line-number))) (format outport "~NCin ~A~A, ~A is ~A, but ~A wants ~A" lint-left-margin #\space (truncated-list->string form) (if ln (format #f " (line ~D)" ln) "") (cadr arg1) (prettify-checker-unq (car arg1)) (car arg2) (prettify-checker arg-type)))))))))) (cond ((not (and (eq? (car arg1) 'equal?) ; (and (equal? (car a1) (car a2)) (equal? (cdr a1) (cdr a2))) -> (equal? a1 a2) (eq? (car arg2) 'equal?) (pair? (cadr arg1)) (pair? (caddr arg1)) (pair? (cadr arg2)) (pair? (caddr arg2)) (eq? (caadr arg1) (caaddr arg1))))) ((assq (caadr arg1) '((car cdr #t) (caar cdar car) (cadr cddr cdr) (caaar cdaar caar) (caadr cdadr cadr) (caddr cdddr cddr) (cadar cddar cdar) (cadddr cddddr cdddr) (caaaar cdaaar caaar) (caaadr cdaadr caadr) (caadar cdadar cadar) (caaddr cdaddr caddr) (cadaar cddaar cdaar) (cadadr cddadr cdadr) (caddar cdddar cddar))) => (lambda (x) (if (and (eq? (caadr arg2) (cadr x)) (eq? (caaddr arg2) (cadr x)) (equal? (cadadr arg1) (cadadr arg2)) (equal? (cadr (caddr arg1)) (cadr (caddr arg2)))) (return (if (symbol? (caddr x)) `(equal? (,(caddr x) ,(cadadr arg1)) (,(caddr x) ,(cadr (caddr arg1)))) `(equal? ,(cadadr arg1) ,(cadr (caddr arg1))))))))) ))) ;; len > 3 or nothing was caught above (let ((nots 0) (revers 0) (arglen (- len 1))) (for-each (lambda (a) (if (pair? a) (if (eq? (car a) 'not) (set! nots (+ nots 1)) (if (hash-table-ref notables (car a)) (set! revers (+ revers 1)))))) (cdr form)) (if (= nots arglen) ; every arg is `(not ...) (let ((nf (simplify-boolean `(or ,@(map cadr (cdr form))) () () env))) (return (simplify-boolean `(not ,nf) () () env))) (if (and (> arglen 2) (or (>= nots (/ (* 3 arglen) 4)) ; > 2/3 seems to get some ugly rewrites (and (>= nots (/ (* 2 arglen) 3)) ; was > 1/2 here (> revers 0)))) (let ((nf (simplify-boolean `(or ,@(map (lambda (p) (cond ((not (pair? p)) `(not ,p)) ((eq? (car p) 'not) (cadr p)) ((hash-table-ref notables (car p)) => (lambda (op) `(,op ,@(cdr p)))) (else `(not ,p)))) (cdr form))) () () env))) (return (simplify-boolean `(not ,nf) () () env)))))) (if (every? (lambda (a) (and (pair? a) (eq? (car a) 'zero?))) (cdr form)) (return `(= 0 ,@(map cadr (cdr form))))) (let ((diff (apply and-redundants env (cdr form)))) (when diff (if (null? (cdr diff)) (return (car diff))) (return (simplify-boolean `(and ,@diff) () () env)))) ;; now there are redundancies below (see subsumes?) but they assumed the tests were side-by-side (do ((new-form ()) (retry #f) (exprs (cdr form) (cdr exprs))) ((null? exprs) (or (null? new-form) ; (and) -> #t (let ((newer-form (let ((nform (reverse new-form))) (map (lambda (x cdr-x) (if (and x (code-constant? x)) (values) x)) nform (cdr nform))))) (return (cond ((null? newer-form) (car new-form)) ((and (eq? (car new-form) #t) ; trailing #t is dumb if next-to-last is boolean func (pair? (cdr new-form)) (pair? (cadr new-form)) (symbol? (caadr new-form)) (eq? (return-type (caadr new-form) env) 'boolean?)) (if (null? (cdr newer-form)) (car newer-form) `(and ,@newer-form))) (retry (simplify-boolean `(and ,@newer-form ,(car new-form)) () () env)) (else `(and ,@newer-form ,(car new-form)))))))) (let* ((e (car exprs)) (val (classify e)) (old-form new-form)) (if (and (pair? val) (memq (car val) '(and or not))) (set! val (classify (set! e (simplify-boolean val () false env)))) (when (and (> len 3) (pair? (cdr exprs))) (if (symbol? val) (if (and (pair? (cadr exprs)) (memq val (cadr exprs))) (let ((nval (simplify-boolean `(and ,val ,(cadr exprs)) () false env))) (if (and (pair? nval) (eq? (car nval) 'and)) (and-incomplete form 'and val (cadr exprs) env) (begin (set! val nval) (set! exprs (cdr exprs))))) (do ((ip (cdr exprs) (cdr ip)) (found-it #f)) ((or found-it (not (pair? ip)))) (do ((p (car ip) (cdr p))) ((or (not (pair? p)) (and (memq val p) (let ((nval (simplify-boolean `(and ,val ,p) () false env))) (if (and (pair? nval) (eq? (car nval) 'and)) (set! found-it p) (let ((ln (and (< 0 line-number 100000) line-number))) (format outport "~NCin ~A~A,~%~NCperhaps change ~S to ~S~%" lint-left-margin #\space (truncated-list->string form) (if ln (format #f " (line ~D)" ln) "") (+ lint-left-margin 4) #\space `(and ... ,val ... ,p) nval) (set! found-it #t))))) (and (pair? (car p)) (memq val (car p)) (set! found-it (car p)))) (if (pair? found-it) (and-incomplete form 'and val found-it env)))))) (when (and (pair? val) (pair? (cadr exprs)) (hash-table-ref bools (car val))) (if (member (cadr val) (cadr exprs)) (and-forgetful form 'and val (cadr exprs) env) (do ((p (cadr exprs) (cdr p))) ((or (not (pair? p)) (and (pair? (car p)) (member (cadr val) (car p)))) (if (pair? p) (and-forgetful form 'and val (car p) env))))))))) (if (not (or retry (equal? e (car exprs)))) (set! retry #t)) ;(format *stderr* "val: ~A, e: ~A~%" val e) ;; (and x1 x2 x1) is not reducible ;; the final thing has to remain at the end, but can be deleted earlier if it can't short-circuit the evaluation, ;; but if there are expressions following the first x1, we can't be sure that it is not ;; protecting them: ;; (and false-or-0 (display (list-ref lst false-or-0)) false-or-0) ;; so I'll not try to optimize that case. But (and x x) is optimizable. (cond ((eq? val #t) (if (null? (cdr exprs)) ; (and x y #t) should not remove the #t (if (or (and (pair? e) (eq? (return-type (car e) env) 'boolean?)) (eq? e #t)) (set! new-form (cons val new-form)) (if (or (null? new-form) (not (equal? e (car new-form)))) (set! new-form (cons e new-form)))) (if (and (not (eq? e #t)) (or (null? new-form) (not (member e new-form)))) (set! new-form (cons e new-form))))) ((not val) ; #f in 'and' ends the expression (set! new-form (if (or (null? new-form) (just-symbols? new-form)) '(#f) (cons #f new-form))) (set! exprs '(#f))) ((and (pair? e) ; if (and ...) splice into current (eq? (car e) 'and)) (set! exprs (append e (cdr exprs)))) ((and (pair? e) ; (and (list? p) (pair? p) ...) -> (and (pair? p) ...) (pair? (cdr exprs)) (pair? (cadr exprs)) (eq? (and-redundant? e (cadr exprs)) (caadr exprs)) (equal? (cadr e) (cadadr exprs)))) ((and (pair? e) ; (and (list? p) (not (null? p)) ...) -> (and (pair? p) ...) (memq (car e) '(list? pair?)) (pair? (cdr exprs)) (let ((p (cadr exprs))) (and (pair? p) (eq? (car p) 'not) (pair? (cadr p)) (eq? (caadr p) 'null?) (equal? (cadr e) (cadadr p))))) (set! new-form (cons `(pair? ,(cadr e)) new-form)) (set! exprs (cdr exprs))) ((not (and (pair? e) ; (and ... (or ... 123) ...) -> splice out or (pair? (cdr exprs)) (eq? (car e) 'or) (pair? (cdr e)) (pair? (cddr e)) (cond ((list-ref e (- (length e) 1)) => code-constant?) ; (or ... #f) (else #f)))) (if (not (and (pair? new-form) (or (eq? val (car new-form)) ; omit repeated tests (and (pair? val) ; and redundant tests (hash-table-ref booleans (car val)) (any? (lambda (p) (and (pair? p) (subsumes? (car val) (car p)) (equal? (cadr val) (cadr p)))) new-form))))) (set! new-form (cons val new-form))))) (if (and (not (eq? new-form old-form)) (pair? (cdr new-form))) (let ((rel (relsub (car new-form) (cadr new-form) 'and env))) ;; rel #f should halt everything as above, and it looks ugly in the output, ;; but it never happens in real code (if (or (pair? rel) (boolean? rel)) (set! new-form (cons rel (cddr new-form)))))))))))))))))))))))) (define (splice-if f lst) (cond ((null? lst) ()) ((not (pair? lst)) lst) ((and (pair? (car lst)) (f (caar lst))) (append (splice-if f (cdar lst)) (splice-if f (cdr lst)))) (else (cons (car lst) (splice-if f (cdr lst)))))) (define (horners-rule form) (and (pair? form) (call-with-exit (lambda (return) (do ((p form (cdr p)) (coeffs #f) (top 0) (sym #f)) ((not (pair? p)) (do ((x (- top 1) (- x 1)) (result (coeffs top))) ((< x 0) result) (set! result (if (zero? (coeffs x)) `(* ,sym ,result) `(+ ,(coeffs x) (* ,sym ,result)))))) (let ((cx (car p))) (cond ((number? cx) (if (not coeffs) (set! coeffs (make-vector 4 0))) (set! (coeffs 0) (+ (coeffs 0) cx))) ((symbol? cx) (if (not sym) (set! sym cx) (if (not (eq? sym cx)) (return #f))) (if (not coeffs) (set! coeffs (make-vector 4 0))) (set! top (max top 1)) (set! (coeffs 1) (+ (coeffs 1) 1))) ((not (and (pair? cx) (eq? (car cx) '*))) (return #f)) (else (let ((ctr 0) (ax 1)) (for-each (lambda (qx) (if (symbol? qx) (if (not sym) (begin (set! sym qx) (set! ctr 1)) (if (not (eq? sym qx)) (return #f) (set! ctr (+ ctr 1)))) (if (number? qx) (set! ax (* ax qx)) (return #f)))) (cdr cx)) (if (not coeffs) (set! coeffs (make-vector 4 0))) (if (>= ctr (length coeffs)) (set! coeffs (copy coeffs (make-vector (* ctr 2) 0)))) (set! top (max top ctr)) (set! (coeffs ctr) (+ (coeffs ctr) ax))))))))))) (define (simplify-numerics form env) ;; this returns a form, possibly the original simplified (let ((real-result? (lambda (op) (memq op '(imag-part real-part abs magnitude angle max min exact->inexact inexact modulo remainder quotient lcm gcd)))) (rational-result? (lambda (op) (memq op '(rationalize inexact->exact exact)))) (integer-result? (lambda (op) (memq op '(logior lognot logxor logand numerator denominator floor round truncate ceiling ash))))) (define (inverse-op op) (case op ((sin) 'asin) ((cos) 'acos) ((tan) 'atan) ((asin) 'sin) ((acos) 'cos) ((atan) 'tan) ((sinh) 'asinh) ((cosh) 'acosh) ((tanh) 'atanh) ((asinh) 'sinh) ((acosh) 'cosh) ((atanh) 'tanh) ((log) 'exp) ((exp) 'log))) (define (just-rationals? form) (or (null? form) (rational? form) (and (pair? form) (rational? (car form)) (just-rationals? (cdr form))))) (define (just-reals? form) (or (null? form) (real? form) (and (pair? form) (real? (car form)) (just-reals? (cdr form))))) (define (just-integers? form) (or (null? form) (integer? form) (and (pair? form) (integer? (car form)) (just-integers? (cdr form))))) (define (simplify-arg x) (if (or (null? x) ; constants and the like look dumb if simplified (not (proper-list? x)) (not (hash-table-ref no-side-effect-functions (car x))) (var-member (car x) env)) x (let ((f (simplify-numerics x env))) (if (and (pair? f) (just-rationals? f)) (catch #t (lambda () (eval f)) (lambda ignore f)) f)))) (define (remove-inexactions val) (when (and (or (assq 'exact->inexact val) (assq 'inexact val)) (not (tree-member 'random val)) (any? number? val)) (set! val (map (lambda (x) (if (and (pair? x) (memq (car x) '(inexact exact->inexact))) (cadr x) x)) val)) (if (not (any? (lambda (x) (and (number? x) (inexact? x))) val)) (do ((p val (cdr p))) ((or (null? p) (number? (car p))) (if (pair? p) (set-car! p (* 1.0 (car p)))))))) val) (let* ((args (map simplify-arg (cdr form))) (len (length args))) (case (car form) ((+) (case len ((0) 0) ((1) (car args)) (else (let ((val (remove-all 0 (splice-if (lambda (x) (eq? x '+)) args)))) (if (every? (lambda (x) (or (not (number? x)) (rational? x))) val) (let ((rats (collect-if list rational? val))) (if (and (pair? rats) (pair? (cdr rats))) (let ((y (apply + rats))) (set! val (if (zero? y) (collect-if list (lambda (x) (not (number? x))) val) (cons y (collect-if list (lambda (x) (not (number? x))) val)))))))) (set! val (remove-inexactions val)) (if (any? (lambda (p) ; collect all + and - vals -> (- (+ ...) ...) (and (pair? p) (eq? (car p) '-))) val) (let ((plus ()) (minus ()) (c 0)) (for-each (lambda (p) (if (not (and (pair? p) (eq? (car p) '-))) (if (rational? p) (set! c (+ c p)) (set! plus (cons p plus))) (if (null? (cddr p)) (if (rational? (cadr p)) (set! c (- c (cadr p))) (set! minus (cons (cadr p) minus))) (begin (if (rational? (cadr p)) (set! c (+ c (cadr p))) (set! plus (cons (cadr p) plus))) (for-each (lambda (p1) (if (rational? p1) (set! c (- c p1)) (set! minus (cons p1 minus)))) (cddr p)))))) val) (simplify-numerics `(- (+ ,@(reverse plus) ,@(if (positive? c) (list c) ())) ,@(reverse minus) ,@(if (negative? c) (list (abs c)) ())) env)) (case (length val) ((0) 0) ((1) (car val)) ; (+ x) -> x ((2) (let ((arg1 (car val)) (arg2 (cadr val))) (cond ((and (real? arg2) ; (+ x -1) -> (- x 1) (negative? arg2) (not (number? arg1))) `(- ,arg1 ,(abs arg2))) ((and (real? arg1) ; (+ -1 x) -> (- x 1) (negative? arg1) (not (number? arg2))) `(- ,arg2 ,(abs arg1))) ((and (pair? arg1) (eq? (car arg1) '*) ; (+ (* a b) (* a c)) -> (* a (+ b c)) (pair? arg2) (eq? (car arg2) '*) (any? (lambda (a) (member a (cdr arg2))) (cdr arg1))) (do ((times ()) (pluses ()) (rset (cdr arg2)) (p (cdr arg1) (cdr p))) ((null? p) ;; times won't be () because we checked above for a match ;; if pluses is (), arg1 is completely included in arg2 ;; if rset is (), arg2 is included in arg1 (simplify-numerics `(* ,@(reverse times) (+ (* ,@(reverse (if (pair? pluses) pluses (list (if (null? pluses) 1 pluses))))) (* ,@rset))) env)) (if (member (car p) rset) (begin (set! times (cons (car p) times)) (set! rset (remove (car p) rset))) (set! pluses (cons (car p) pluses))))) ((and (pair? arg1) (eq? (car arg1) '/) ; (+ (/ a b) (/ c b)) -> (/ (+ a c) b) (pair? arg2) (eq? (car arg2) '/) (pair? (cddr arg1)) (pair? (cddr arg2)) (equal? (cddr arg1) (cddr arg2))) `(/ (+ ,(cadr arg1) ,(cadr arg2)) ,@(cddr arg1))) (else `(+ ,@val))))) (else (or (horners-rule val) ;; not many cases here, oddly enough, Horner's rule gets most ;; (+ (/ (f x) 3) (/ (g x) 3) (/ (h x) 3) 15) [ignoring problems involving overflow] `(+ ,@val))))))))) ((*) (case len ((0) 1) ((1) (car args)) (else (let ((val (remove-all 1 (splice-if (lambda (x) (eq? x '*)) args)))) (if (every? (lambda (x) (or (not (number? x)) (rational? x))) val) (let ((rats (collect-if list rational? val))) (if (and (pair? rats) (pair? (cdr rats))) (let ((y (apply * rats))) (set! val (if (= y 1) (collect-if list (lambda (x) (not (number? x))) val) (cons y (collect-if list (lambda (x) (not (number? x))) val)))))))) (set! val (remove-inexactions val)) (case (length val) ((0) 1) ((1) (car val)) ; (* x) -> x ((2) (let ((arg1 (car val)) (arg2 (cadr val))) (cond ((just-rationals? val) (let ((new-val (apply * val))) ; huge numbers here are less readable (if (< (abs new-val) 1000000) new-val `(* ,@val)))) ((memv 0 val) ; (* x 0) -> 0 0) ((memv -1 val) `(- ,@(remove -1 val))) ; (* -1 x) -> (- x) ((not (pair? arg2)) `(* ,@val)) ((pair? arg1) (let ((op1 (car arg1)) (op2 (car arg2))) (cond ((and (eq? op1 '-) ; (* (- x) (- y)) -> (* x y) (null? (cddr arg1)) (eq? op2 '-) (null? (cddr arg2))) `(* ,(cadr arg1) ,(cadr arg2))) ((and (eq? op1 '/) ; (* (/ x) (/ y)) -> (/ (* x y)) etc (eq? op2 '/)) (let ((op1-arg1 (cadr arg1)) (op2-arg1 (cadr arg2))) (if (null? (cddr arg1)) (if (null? (cddr arg2)) `(/ (* ,op1-arg1 ,op2-arg1)) (if (equal? op1-arg1 op2-arg1) `(/ ,(caddr arg2)) (simplify-numerics `(/ ,op2-arg1 (* ,op1-arg1 ,(caddr arg2))) env))) (if (null? (cddr arg2)) (if (equal? op1-arg1 op2-arg1) `(/ ,(caddr arg1)) (simplify-numerics `(/ ,op1-arg1 (* ,(caddr arg1) ,op2-arg1)) env)) (simplify-numerics `(/ (* ,op1-arg1 ,op2-arg1) (* ,@(cddr arg1) ,@(cddr arg2))) env))))) ((and (= (length arg1) 3) (equal? (cdr arg1) (cdr arg2)) (case op1 ((gcd) (eq? op2 'lcm)) ((lcm) (eq? op2 'gcd)) (else #f))) `(abs (* ,@(cdr arg1)))) ; (* (gcd a b) (lcm a b)) -> (abs (* a b)) but only if 2 args? ((and (eq? op1 'exp) ; (* (exp a) (exp b)) -> (exp (+ a b)) (eq? op2 'exp)) `(exp (+ ,(cadr arg1) ,(cadr arg2)))) ((and (eq? op1 'sqrt) ; (* (sqrt x) (sqrt y)) -> (sqrt (* x y)) (eq? op2 'sqrt)) `(sqrt (* ,(cadr arg1) ,(cadr arg2)))) ((not (and (eq? op1 'expt) (eq? op2 'expt))) `(* ,@val)) ((equal? (cadr arg1) (cadr arg2)) ; (* (expt x y) (expt x z)) -> (expt x (+ y z)) `(expt ,(cadr arg1) (+ ,(caddr arg1) ,(caddr arg2)))) ((equal? (caddr arg1) (caddr arg2)) ; (* (expt x y) (expt z y)) -> (expt (* x z) y) `(expt (* ,(cadr arg1) ,(cadr arg2)) ,(caddr arg1))) (else `(* ,@val))))) ((and (number? arg1) ; (* 2 (random 3.0)) -> (random 6.0) (eq? (car arg2) 'random) (number? (cadr arg2)) (not (rational? (cadr arg2)))) `(random ,(* arg1 (cadr arg2)))) (else `(* ,@val))))) (else (cond ((just-rationals? val) (let ((new-val (apply * val))) ; huge numbers here are less readable (if (< (abs new-val) 1000000) new-val `(* ,@val)))) ((memv 0 val) ; (* x 0 2) -> 0 0) ((memv -1 val) `(- (* ,@(remove -1 val)))) ; (* -1 x y) -> (- (* x y)) ((any? (lambda (p) ; collect * and / vals -> (/ (* ...) ...) (and (pair? p) (eq? (car p) '/))) val) (let ((mul ()) (div ())) (for-each (lambda (p) (if (not (and (pair? p) (eq? (car p) '/))) (set! mul (cons p mul)) (if (null? (cddr p)) (set! div (cons (cadr p) div)) (begin (set! mul (cons (cadr p) mul)) (set! div (append (cddr p) div)))))) val) (for-each (lambda (n) (when (member n div) (set! div (remove n div)) (set! mul (remove n mul)))) (copy mul)) (let ((expr (if (null? mul) (if (null? div) `(*) ; for simplify-numerics' benefit `(/ 1 ,@(reverse div))) (if (null? div) `(* ,@(reverse mul)) `(/ (* ,@(reverse mul)) ,@(reverse div)))))) (simplify-numerics expr env)))) (else `(* ,@val))))))))) ((-) (set! args (remove-inexactions args)) (case len ((0) form) ((1) ; negate (if (number? (car args)) (- (car args)) (if (not (list? (car args))) `(- ,@args) (case (length (car args)) ((2) (if (eq? (caar args) '-) (cadar args) ; (- (- x)) -> x `(- ,@args))) ((3) (if (eq? (caar args) '-) `(- ,(caddar args) ,(cadar args)) ; (- (- x y)) -> (- y x) `(- ,@args))) (else `(- ,@args)))))) ((2) (let ((arg1 (car args)) (arg2 (cadr args))) (cond ((just-rationals? args) (apply - args)) ; (- 3 2) -> 1 ((eqv? arg1 0) `(- ,arg2)) ; (- 0 x) -> (- x) ((eqv? arg2 0) arg1) ; (- x 0) -> x ((equal? arg1 arg2) 0) ; (- x x) -> 0 ((and (pair? arg2) (eq? (car arg2) '-) (pair? (cdr arg2))) (if (null? (cddr arg2)) `(+ ,arg1 ,(cadr arg2)) ; (- x (- y)) -> (+ x y) (simplify-numerics `(- (+ ,arg1 ,@(cddr arg2)) ,(cadr arg2)) env))) ; (- x (- y z)) -> (- (+ x z) y) ((and (pair? arg2) ; (- x (+ y z)) -> (- x y z) (eq? (car arg2) '+)) (simplify-numerics `(- ,arg1 ,@(cdr arg2)) env)) ((and (pair? arg1) ; (- (- x y) z) -> (- x y z) (eq? (car arg1) '-)) (if (> (length arg1) 2) `(- ,@(cdr arg1) ,arg2) (simplify-numerics `(- (+ ,(cadr arg1) ,arg2)) env))) ; (- (- x) y) -> (- (+ x y)) ((and (pair? arg2) ; (- x (truncate x)) -> (remainder x 1) (eq? (car arg2) 'truncate) (equal? arg1 (cadr arg2))) `(remainder ,arg1 1)) ((and (real? arg2) ; (- x -1) -> (+ x 1) (negative? arg2) (not (number? arg1))) `(+ ,arg1 ,(abs arg2))) (else `(- ,@args))))) (else (if (just-rationals? args) (apply - args) (let ((val (remove-all 0 (splice-if (lambda (x) (eq? x '+)) (cdr args))))) (if (every? (lambda (x) (or (not (number? x)) (rational? x))) val) (let ((rats (collect-if list rational? val))) (if (and (pair? rats) (pair? (cdr rats))) (let ((y (apply + rats))) (set! val (if (zero? y) (collect-if list (lambda (x) (not (number? x))) val) (cons y (collect-if list (lambda (x) (not (number? x))) val)))))))) (set! val (cons (car args) val)) (let ((first-arg (car args)) (nargs (cdr val))) (if (member first-arg nargs) (begin (set! nargs (remove first-arg nargs)) ; remove once (set! first-arg 0))) (cond ((null? nargs) first-arg) ; (- x 0 0 0)? ((eqv? first-arg 0) (if (null? (cdr nargs)) (if (number? (car nargs)) (- (car nargs)) `(- ,(car nargs))) ; (- 0 0 0 x)? `(- (+ ,@nargs)))) ; (- 0 z y) -> (- (+ x y)) ((not (and (pair? (car args)) (eq? (caar args) '-))) `(- ,@(cons first-arg nargs))) ((> (length (car args)) 2) ; (- (- x y) z w) -> (- x y z w) (simplify-numerics `(- ,@(cdar args) ,@(cdr args)) env)) (else (simplify-numerics `(- (+ ,(cadar args) ,@(cdr args))) env))))))))) ((/) (set! args (remove-inexactions args)) (case len ((0) form) ((1) ; invert (if (number? (car args)) (if (zero? (car args)) `(/ ,(car args)) (/ (car args))) (if (not (pair? (car args))) `(/ ,@args) (case (caar args) ((/) (case (length (car args)) ((2) ; (/ (/ x)) -> x (cadar args)) ((3) ; (/ (/ z x)) -> (/ x z) `(/ ,@(reverse (cdar args)))) (else (if (eqv? (cadar args) 1) `(* ,@(cddar args)) ; (/ (/ 1 x y)) -> (* x y) `(/ (* ,@(cddar args)) ,(cadar args)))))) ; (/ (/ z x y)) -> (/ (* x y) z) ((expt) ; (/ (expt x y)) -> (expt x (- y)) `(expt ,(cadar args) (- ,(caddar args)))) ((exp) ; (/ (exp x)) -> (exp (- x)) `(exp (- ,(cadar args)))) (else `(/ ,@args)))))) ((2) (if (and (just-rationals? args) (not (zero? (cadr args)))) (apply / args) ; including (/ 0 12) -> 0 (let ((arg1 (car args)) (arg2 (cadr args))) (let ((op1 (and (pair? arg1) (car arg1))) (op2 (and (pair? arg2) (car arg2)))) (let ((op1-arg1 (and op1 (pair? (cdr arg1)) (cadr arg1))) (op2-arg1 (and op2 (pair? (cdr arg2)) (cadr arg2)))) (cond ((eqv? arg1 1) ; (/ 1 x) -> (/ x) (simplify-numerics `(/ ,arg2) env)) ((eqv? arg2 1) ; (/ x 1) -> x arg1) ((and (pair? arg1) ; (/ (/ a b) c) -> (/ a b c) (eq? op1 '/) (pair? (cddr arg1)) (not (and (pair? arg2) (eq? op2 '/)))) `(/ ,op1-arg1 ,@(cddr arg1) ,arg2)) ((and (pair? arg1) ; (/ (/ a) (/ b)) -> (/ b a)?? (eq? op1 '/) (pair? arg2) (eq? '/ op2)) (let ((a1 (if (null? (cddr arg1)) (list 1 op1-arg1) (cdr arg1))) (a2 (if (null? (cddr arg2)) (list 1 op2-arg1) (cdr arg2)))) (simplify-numerics `(/ (* ,(car a1) ,@(cdr a2)) (* ,@(cdr a1) ,(car a2))) env))) ((and (pair? arg2) (eq? op2 '*) (not (side-effect? arg1 env)) (member arg1 (cdr arg2))) (let ((n (remove arg1 (cdr arg2)))) (if (and (pair? n) (null? (cdr n))) `(/ ,@n) ; (/ x (* y x)) -> (/ y) `(/ 1 ,@n)))) ; (/ x (* y x z)) -> (/ 1 y z) ((and (pair? arg2) ; (/ c (/ a b)) -> (/ (* c b) a) (eq? op2 '/)) (cond ((null? (cddr arg2)) `(* ,arg1 ,op2-arg1)) ; ignoring divide by zero here (/ x (/ y)) -> (* x y) ((eqv? op2-arg1 1) `(* ,arg1 ,@(cddr arg2))) ; (/ x (/ 1 y z)) -> (* x y z) -- these never actually happen ((not (pair? (cddr arg2))) `(/ ,@args)) ; no idea... ((and (rational? arg1) (rational? op2-arg1) (null? (cdddr arg2))) (let ((val (/ arg1 op2-arg1))) (if (= val 1) (caddr arg2) (if (= val -1) `(- ,(caddr arg2)) `(* ,val ,(caddr arg2)))))) (else `(/ (* ,arg1 ,@(cddr arg2)) ,op2-arg1)))) #| ;; can't decide about this -- result usually looks cruddy ((and (pair? arg2) ; (/ x (* y z)) -> (/ x y z) (eq? op2 '*)) `(/ ,arg1 ,@(cdr arg2))) |# ((and (pair? arg1) ; (/ (log x) (log y)) -> (log x y) -- (log number) for (log y) never happens (pair? arg2) (= (length arg1) (length arg2) 2) (case op1 ((log) (eq? op2 'log)) ((sin) (and (eq? op2 'cos) (equal? op1-arg1 op2-arg1))) (else #f))) (if (eq? op1 'log) `(log ,op1-arg1 ,op2-arg1) `(tan ,op1-arg1))) ((and (pair? arg1) ; (/ (- x) (- y)) -> (/ x y) (pair? arg2) (eq? op1 '-) (eq? op2 '-) (= (length arg1) (length arg2) 2)) `(/ ,op1-arg1 ,op2-arg1)) ((and (pair? arg1) ; (/ (* x y) (* z y)) -> (/ x z) (pair? arg2) (eq? op1 '*) (case op2 ((*) (and (= (length arg1) (length arg2) 3) (equal? (caddr arg1) (caddr arg2)))) ((log) (cond ((assq 'log (cdr arg1)) => (lambda (p) (= (length p) 2))) (else #f))) (else #f)) ; (/ (* 12 (log x)) (log 2)) -> (* 12 (log x 2)) (if (eq? op2 '*) `(/ ,op1-arg1 ,op2-arg1) (let ((used-log op2-arg1)) `(* ,@(map (lambda (p) (if (and used-log (pair? p) (eq? (car p) 'log)) (let ((val `(log ,(cadr p) ,used-log))) (set! used-log #f) val) p)) (cdr arg1))))))) ((and (pair? arg1) ; (/ (sqrt x) x) -> (/ (sqrt x)) (eq? (car arg1) 'sqrt) (equal? (cadr arg1) arg2)) `(/ ,arg1)) ((and (pair? arg2) ; (/ x (sqrt x)) -> (sqrt x) (eq? (car arg2) 'sqrt) (equal? (cadr arg2) arg1)) arg2) (else `(/ ,@args)))))))) (else (if (and (just-rationals? args) (not (memv 0 (cdr args))) (not (memv 0.0 (cdr args)))) (apply / args) (let ((nargs ; (/ x a (* b 1 c) d) -> (/ x a b c d) (remove-all 1 (splice-if (lambda (x) (eq? x '*)) (cdr args))))) (if (null? nargs) ; (/ x 1 1) -> x (car args) (if (and (member (car args) (cdr args)) (not (side-effect? (car args) env))) (let ((n (remove (car args) (cdr args)))) (if (null? (cdr n)) `(/ ,@n) ; (/ x y x) -> (/ y) `(/ 1 ,@n))) ; (/ x y x z) -> (/ 1 y z) `(/ ,@(cons (car args) nargs))))))))) ((sin cos tan asin acos sinh cosh tanh asinh acosh atanh exp) ;; perhaps someday, for amusement: ;; (sin (acos x)) == (cos (asin x)) == (sqrt (- 1 (expt x 2))) ;; (asin (cos x)) == (acos (sin x)) == (- (* 1/2 pi) x) (cond ((not (= len 1)) `(,(car form) ,@args)) ((and (pair? (car args)) ; (sin (asin x)) -> x (= (length (car args)) 2) (eq? (caar args) (inverse-op (car form)))) (cadar args)) ((eqv? (car args) 0) ; (sin 0) -> 0 (case (car form) ((sin asin sinh asinh tan tanh atanh) 0) ((exp cos cosh) 1) (else `(,(car form) ,@args)))) ((and (eq? (car form) 'cos) ; (cos (- x)) -> (cos x) (pair? (car args)) (eq? (caar args) '-) (null? (cddar args))) `(cos ,(cadar args))) ((or (eq? (car args) 'pi) ; (sin pi) -> 0.0 (and (pair? (car args)) (eq? (caar args) '-) (eq? (cadar args) 'pi) (null? (cddar args)))) (case (car form) ((sin tan) 0.0) ((cos) -1.0) (else `(,(car form) ,@args)))) ((eqv? (car args) 0.0) ; (sin 0.0) -> 0.0 ((symbol->value (car form)) 0.0)) ((and (eq? (car form) 'acos) ; (acos -1) -> pi (eqv? (car args) -1)) 'pi) ((and (eq? (car form) 'exp) ; (exp (* a (log b))) -> (expt b a) (pair? (car args)) (eq? (caar args) '*)) (let ((targ (cdar args))) (cond ((not (= (length targ) 2)) `(,(car form) ,@args)) ((and (pair? (car targ)) (eq? (caar targ) 'log) (pair? (cdar targ)) (null? (cddar targ))) `(expt ,(cadar targ) ,(cadr targ))) ((and (pair? (cadr targ)) (eq? (caadr targ) 'log) (pair? (cdadr targ)) (null? (cddadr targ))) `(expt ,(cadadr targ) ,(car targ))) (else `(,(car form) ,@args))))) (else `(,(car form) ,@args)))) ((log) (cond ((not (pair? args)) form) ((eqv? (car args) 1) 0) ; (log 1 ...) -> 0 ((and (= len 1) ; (log (exp x)) -> x (pair? (car args)) (= (length (car args)) 2) (eq? (caar args) 'exp)) (cadar args)) ((and (pair? (car args)) ; (log (sqrt x)) -> (* 1/2 (log x)) (eq? (caar args) 'sqrt)) `(* 1/2 (log ,(cadar args) ,@(cdr args)))) ((and (pair? (car args)) ; (log (expt x y)) -> (* y (log x)) (eq? (caar args) 'expt)) `(* ,(caddar args) (log ,(cadar args) ,@(cdr args)))) ((not (and (= len 2) ; (log x x) -> 1.0 (equal? (car args) (cadr args)))) `(log ,@args)) ((integer? (car args)) 1) (else 1.0))) ((sqrt) (cond ((not (pair? args)) form) ((and (rational? (car args)) (rational? (sqrt (car args))) (= (car args) (sqrt (* (car args) (car args))))) (sqrt (car args))) ; don't collapse (sqrt (* a a)), a=-1 for example, or -1-i -> 1+i whereas 1-i -> 1-i etc ((and (pair? (car args)) (eq? (caar args) 'exp)) `(exp (/ ,(cadar args) 2))) ; (sqrt (exp x)) -> (exp (/ x 2)) (else `(sqrt ,@args)))) ((floor round ceiling truncate) (cond ((not (= len 1)) form) ((number? (car args)) (catch #t (lambda () (apply (symbol->value (car form)) args)) (lambda any `(,(car form) ,@args)))) ((not (pair? (car args))) `(,(car form) ,@args)) ((or (integer-result? (caar args)) (and (eq? (caar args) 'random) (integer? (cadar args)))) (car args)) ((memq (caar args) '(inexact->exact exact)) `(,(car form) ,(cadar args))) ((memq (caar args) '(* + / -)) ; maybe extend this list `(,(car form) (,(caar args) ,@(map (lambda (p) (if (and (pair? p) (memq (car p) '(inexact->exact exact))) (cadr p) p)) (cdar args))))) ((and (eq? (caar args) 'random) (eq? (car form) 'floor) (float? (cadar args)) (= (floor (cadar args)) (cadar args))) `(random ,(floor (cadar args)))) (else `(,(car form) ,@args)))) ((abs magnitude) (cond ((not (= len 1)) form) ((and (pair? (car args)) ; (abs (abs x)) -> (abs x) (hash-table-ref non-negative-ops (caar args))) (car args)) ((rational? (car args)) (abs (car args))) ((not (pair? (car args))) `(,(car form) ,@args)) ((and (memq (caar args) '(modulo random)) (= (length (car args)) 3) ; (abs (modulo x 2)) -> (modulo x 2) (real? (caddar args)) (positive? (caddar args))) (car args)) ((and (eq? (caar args) '-) ; (abs (- x)) -> (abs x) (pair? (cdar args)) (null? (cddar args))) `(,(car form) ,(cadar args))) (else `(,(car form) ,@args)))) ((imag-part) (if (not (= len 1)) form (if (or (real? (car args)) (and (pair? (car args)) (real-result? (caar args)))) 0.0 `(imag-part ,@args)))) ((real-part) (if (not (= len 1)) form (if (or (real? (car args)) (and (pair? (car args)) (real-result? (caar args)))) (car args) `(real-part ,@args)))) ((denominator) (if (not (= len 1)) form (if (or (integer? (car args)) (and (pair? (car args)) (integer-result? (caar args)))) 1 `(denominator ,(car args))))) ((numerator) (cond ((not (= len 1)) form) ((or (integer? (car args)) (and (pair? (car args)) (integer-result? (caar args)))) (car args)) ((rational? (car args)) (numerator (car args))) (else `(numerator ,(car args))))) ((random) (cond ((not (and (= len 1) (number? (car args)))) `(random ,@args)) ((eqv? (car args) 0) 0) ((morally-equal? (car args) 0.0) 0.0) (else `(random ,@args)))) ((complex make-rectangular) (if (and (= len 2) (morally-equal? (cadr args) 0.0)) ; morally so that 0 matches (car args) `(complex ,@args))) ((make-polar) (if (and (= len 2) (morally-equal? (cadr args) 0.0)) (car args) `(make-polar ,@args))) ((rationalize lognot ash modulo remainder quotient) (cond ((just-rationals? args) (catch #t ; catch needed here for things like (ash 2 64) (lambda () (apply (symbol->value (car form)) args)) (lambda ignore `(,(car form) ,@args)))) ; use this form to pick up possible arg changes ((and (eq? (car form) 'ash) ; (ash x 0) -> x (= len 2) ; length of args (eqv? (cadr args) 0)) (car args)) ((case (car form) ((quotient) ; (quotient (remainder x y) y) -> 0 (and (= len 2) (pair? (car args)) (eq? (caar args) 'remainder) (= (length (car args)) 3) (eqv? (caddar args) (cadr args)))) ((ash modulo) ; (modulo 0 x) -> 0 (and (= len 2) (eqv? (car args) 0))) (else #f)) 0) ((and (eq? (car form) 'modulo) ; (modulo (abs x) y) -> (modulo x y) (= len 2) (pair? (car args)) (eq? (caar args) 'abs)) `(modulo ,(cadar args) ,(cadr args))) (else `(,(car form) ,@args)))) ((expt) (cond ((not (= len 2)) form) ((and (eqv? (car args) 0) ; (expt 0 x) -> 0 (not (eqv? (cadr args) 0))) (if (and (integer? (cadr args)) (negative? (cadr args))) (lint-format "attempt to divide by 0: ~A" 'expt (truncated-list->string form))) 0) ((or (and (eqv? (cadr args) 0) ; (expt x 0) -> 1 (not (eqv? (car args) 0))) (eqv? (car args) 1)) ; (expt 1 x) -> 1 1) ((eqv? (cadr args) 1) ; (expt x 1) -> x (car args)) ((eqv? (cadr args) -1) ; (expt x -1) -> (/ x) `(/ ,(car args))) ((just-rationals? args) ; (expt 2 3) -> 8 (catch #t (lambda () (let ((val (apply expt args))) (if (and (integer? val) (< (abs val) 1000000)) val `(expt ,@args)))) (lambda args `(expt ,@args)))) ; (expt (expt x y) z) -> (expt x (* y z)) ((and (pair? (car args)) (eq? (caar args) 'expt)) `(expt ,(cadar args) (* ,(caddar args) ,(cadr args)))) (else `(expt ,@args)))) ((angle) (cond ((not (pair? args)) form) ((eqv? (car args) -1) 'pi) ((or (morally-equal? (car args) 0.0) (eq? (car args) 'pi)) 0.0) (else `(angle ,@args)))) ((atan) (cond ((and (= len 1) ; (atan (x y)) -> (atan x y) (pair? (car args)) (= (length (car args)) 3) (eq? (caar args) '/)) `(atan ,@(cdar args))) ((and (= len 2) ; (atan 0 -1) -> pi (eqv? (car args) 0) (eqv? (cadr args) -1)) 'pi) (else `(atan ,@args)))) ((inexact->exact exact) (cond ((not (= len 1)) form) ((or (rational? (car args)) (and (pair? (car args)) (or (rational-result? (caar args)) (integer-result? (caar args)) (and (eq? (caar args) 'random) (rational? (cadar args)))))) (car args)) ((number? (car args)) (catch #t (lambda () (inexact->exact (car args))) (lambda any `(,(car form) ,@args)))) (else `(,(car form) ,@args)))) ((exact->inexact inexact) (cond ((not (= len 1)) form) ((memv (car args) '(0 0.0)) 0.0) ((not (and (pair? (car args)) (not (eq? (caar args) 'random)) (hash-table-ref numeric-ops (caar args)) (any? number? (cdar args)))) `(,(car form) ,@args)) ((any? (lambda (x) (and (number? x) (inexact? x))) (cdar args)) (car args)) (else (let ((new-form (copy (car args)))) (do ((p (cdr new-form) (cdr p))) ((or (null? p) (number? (car p))) (if (pair? p) (set-car! p (* 1.0 (car p)))) new-form)))))) ;; not (inexact (random 3)) -> (random 3.0) because results are different ((logior) (set! args (lint-remove-duplicates (remove-all 0 (splice-if (lambda (x) (eq? x 'logior)) args)) env)) (if (every? (lambda (x) (or (not (number? x)) (integer? x))) args) (let ((rats (collect-if list integer? args))) (if (and (pair? rats) (pair? (cdr rats))) (let ((y (apply logior rats))) (set! args (if (zero? y) (collect-if list (lambda (x) (not (number? x))) args) (cons y (collect-if list (lambda (x) (not (number? x))) args)))))))) (cond ((null? args) 0) ; (logior) -> 0 ((null? (cdr args)) (car args)) ; (logior x) -> x ((memv -1 args) -1) ; (logior ... -1 ...) -> -1 ((just-integers? args) (apply logior args)) (else `(logior ,@args)))) ((logand) (set! args (lint-remove-duplicates (remove-all -1 (splice-if (lambda (x) (eq? x 'logand)) args)) env)) (if (every? (lambda (x) (or (not (number? x)) (integer? x))) args) (let ((rats (collect-if list integer? args))) (if (and (pair? rats) (pair? (cdr rats))) (let ((y (apply logand rats))) (set! args (if (= y -1) (collect-if list (lambda (x) (not (number? x))) args) (cons y (collect-if list (lambda (x) (not (number? x))) args)))))))) (cond ((null? args) -1) ((null? (cdr args)) (car args)) ; (logand x) -> x ((memv 0 args) 0) ((just-integers? args) (apply logand args)) (else `(logand ,@args)))) ;; (logand 1 (logior 2 x)) -> (logand 1 x)? ;; (logand 1 (logior 1 x)) -> 1 ;; (logand 3 (logior 1 x))? ;; similarly for (logior...(logand...)) ((logxor) (set! args (splice-if (lambda (x) (eq? x 'logxor)) args)) ; is this correct?? (cond ((null? args) 0) ; (logxor) -> 0 ((null? (cdr args)) (car args)) ; (logxor x) -> x?? ((just-integers? args) (apply logxor args)) ; (logxor 1 2) -> 3 ((and (= len 2) (equal? (car args) (cadr args))) 0) ; (logxor x x) -> 0 (else `(logxor ,@args)))) ; (logxor x (logxor y z)) -> (logxor x y z) ((gcd) (set! args (lint-remove-duplicates (splice-if (lambda (x) (eq? x 'gcd)) args) env)) (cond ((null? args) 0) ((memv 1 args) 1) ((just-integers? args) (catch #t ; maybe (gcd -9223372036854775808 -9223372036854775808) (lambda () (apply gcd args)) (lambda ignore `(gcd ,@args)))) ((null? (cdr args)) `(abs ,(car args))) ((eqv? (car args) 0) `(abs ,(cadr args))) ((eqv? (cadr args) 0) `(abs ,(car args))) (else `(gcd ,@args)))) ((lcm) (set! args (lint-remove-duplicates (splice-if (lambda (x) (eq? x 'lcm)) args) env)) (cond ((null? args) 1) ; (lcm) -> 1 ((memv 0 args) 0) ; (lcm ... 0 ...) -> 0 ((just-integers? args) ; (lcm 3 4) -> 12 (catch #t (lambda () (apply lcm args)) (lambda ignore `(lcm ,@args)))) ((null? (cdr args)) ; (lcm x) -> (abs x) `(abs ,(car args))) (else `(lcm ,@args)))) ((max min) (if (not (pair? args)) form (begin (set! args (lint-remove-duplicates (splice-if (lambda (x) (eq? x (car form))) args) env)) (if (any? (lambda (p) ; if non-negative-op, remove any non-positive numbers (and (pair? p) (hash-table-ref non-negative-ops (car p)))) args) (set! args (remove-if (lambda (x) (and (real? x) (not (positive? x)))) args))) (if (= len 1) (car args) (if (just-reals? args) (apply (symbol->value (car form)) args) (let ((nums (collect-if list number? args)) (other (if (eq? (car form) 'min) 'max 'min))) (if (and (pair? nums) (just-reals? nums)) ; non-real case checked elsewhere (later) (let ((relop (if (eq? (car form) 'min) >= <=))) (if (pair? (cdr nums)) (set! nums (list (apply (symbol->value (car form)) nums)))) (let ((new-args (append nums (collect-if list (lambda (x) (not (number? x))) args)))) (let ((c1 (car nums))) (set! new-args (collect-if list (lambda (x) (or (not (pair? x)) (<= (length x) 2) (not (eq? (car x) other)) (let ((c2 (find-if number? (cdr x)))) (or (not c2) (relop c1 c2))))) new-args))) (if (< (length new-args) (length args)) (set! args new-args))))) ;; if (max c1 (min c2 . args1) . args2) where (> c1 c2) -> (max c1 . args2), if = -> c1 ;; if (min c1 (max c2 . args1) . args2) where (< c1 c2) -> (min c1 . args2), if = -> c1 ;; and if (max 4 x (min x 4)) -- is it (max x 4)? ;; (max a b) is (- (min (- a) (- b))), but that doesn't help here -- the "-" gets in our way ;; (min (- a) (- b)) -> (- (max a b))? ;; (+ a (max|min b c)) = (max|min (+ a b) (+ a c))) (if (null? (cdr args)) ; (max (min x 3) (min x 3)) -> (max (min x 3)) -> (min x 3) (car args) (if (and (null? (cddr args)) ; (max|min x (min|max x ...) -> x (or (and (pair? (car args)) (eq? (caar args) other) (member (cadr args) (car args)) (not (side-effect? (cadr args) env))) (and (pair? (cadr args)) (eq? (caadr args) other) (member (car args) (cadr args)) (not (side-effect? (car args) env))))) ((if (pair? (car args)) cadr car) args) `(,(car form) ,@args))))))))) (else `(,(car form) ,@args)))))) (define (binding-ok? caller head binding env second-pass) ;; check let-style variable binding for various syntactic problems (cond (second-pass (and (pair? binding) (symbol? (car binding)) (not (constant? (car binding))) (pair? (cdr binding)) (or (null? (cddr binding)) (and (eq? head 'do) (pair? (cddr binding)) ; (do ((i 0 . 1))...) (null? (cdddr binding)))))) ((not (pair? binding)) (lint-format "~A binding is not a list? ~S" caller head binding) #f) ; (let (a) a) ((not (symbol? (car binding))) (lint-format "~A variable is not a symbol? ~S" caller head binding) #f) ; (let ((1 2)) #f) ((keyword? (car binding)) (lint-format "~A variable is a keyword? ~S" caller head binding) #f) ; (let ((:a 1)) :a) ((constant? (car binding)) (lint-format "can't bind a constant: ~S" caller binding) #f) ; (let ((pi 2)) #f) ((not (pair? (cdr binding))) (lint-format (if (null? (cdr binding)) "~A variable value is missing? ~S" ; (let ((a)) #f) "~A binding is an improper list? ~S") ; (let ((a . 1)) #f) caller head binding) #f) ((and (pair? (cddr binding)) ; (let loop ((pi 1.0) (+ pi 1))...) (or (not (eq? head 'do)) (pair? (cdddr binding)))) (lint-format "~A binding is messed up: ~A" caller head binding) #f) (else (if (and *report-shadowed-variables* ; (let ((x 1)) (+ (let ((x 2)) (+ x 1)) x)) (var-member (car binding) env)) (lint-format "~A variable ~A in ~S shadows an earlier declaration" caller head (car binding) binding)) #t))) (define (check-char-cmp caller op form) (if (and (any? (lambda (x) (and (pair? x) (eq? (car x) 'char->integer))) (cdr form)) (every? (lambda (x) (or (and (integer? x) (<= 0 x 255)) (and (pair? x) (eq? (car x) 'char->integer)))) (cdr form))) (lint-format "perhaps ~A" caller ; (< (char->integer x) 95) -> (char<? x #\_) (lists->string form `(,(case op ((=) 'char=?) ((>) 'char>?) ((<) 'char<?) ((>=) 'char>=?) (else 'char<=?)) ,@(map (lambda (arg) ((if (integer? arg) integer->char cadr) arg)) (cdr form))))))) (define (write-port expr) ; ()=not specified (*stdout*), #f=something is wrong (not enough args) (and (pair? expr) (if (eq? (car expr) 'newline) (if (pair? (cdr expr)) (cadr expr) ()) (and (pair? (cdr expr)) (if (pair? (cddr expr)) (caddr expr) ()))))) (define (display->format d) (case (car d) ((newline) (copy "~%")) ((display) (let* ((arg (cadr d)) (arg-arg (and (pair? arg) (pair? (cdr arg)) (cadr arg)))) (cond ((string? arg) arg) ((char? arg) (string arg)) ((and (pair? arg) (eq? (car arg) 'number->string)) (if (= (length arg) 3) (case (caddr arg) ((2) (values "~B" arg-arg)) ((8) (values "~O" arg-arg)) ((10) (values "~D" arg-arg)) ((16) (values "~X" arg-arg)) (else (values "~A" arg))) (values "~A" arg-arg))) ((not (and (pair? arg) (eq? (car arg) 'string-append))) (values "~A" arg)) ((null? (cddr arg)) (if (string? arg-arg) arg-arg (values "~A" arg-arg))) ((not (null? (cdddr arg))) (values "~A" arg)) ((string? arg-arg) (values (string-append arg-arg "~A") (caddr arg))) ((string? (caddr arg)) (values (string-append "~A" (caddr arg)) arg-arg)) (else (values "~A" arg))))) ((write) ;; very few special cases actually happen here, unlike display above (if (string? (cadr d)) (string-append "\"" (cadr d) "\"") (if (char? (cadr d)) (string (cadr d)) (values "~S" (cadr d))))) ((write-char) (if (char? (cadr d)) (string (cadr d)) (values "~C" (cadr d)))) ((write-string) ; same as display but with possible start|end indices (let ((indices (and (pair? (cddr d)) ; port (pair? (cdddr d)) (cdddr d)))) (if (string? (cadr d)) (if (not indices) (cadr d) (if (and (integer? (car indices)) (or (null? (cdr indices)) (and (pair? indices) (integer? (cadr indices))))) (apply substring (cadr d) indices) (values "~A" `(substring ,(cadr d) ,@indices)))) (values "~A" (if indices `(substring ,(cadr d) ,@indices) (cadr d)))))))) (define (identity? x) ; (lambda (x) x), or (define (x) x) -> procedure-source (and (pair? x) (eq? (car x) 'lambda) (pair? (cdr x)) (pair? (cadr x)) (null? (cdadr x)) (pair? (cddr x)) (null? (cdddr x)) (eq? (caddr x) (caadr x)))) (define (cdr-count c) (case c ((cdr) 1) ((cddr) 2) ((cdddr) 3) (else 4))) (define (simple-lambda? x) (and (pair? x) (eq? (car x) 'lambda) (pair? (cdr x)) (pair? (cadr x)) (null? (cdadr x)) (pair? (cddr x)) (null? (cdddr x)) (= (tree-count1 (caadr x) (caddr x) 0) 1))) (define (less-simple-lambda? x) (and (pair? x) (eq? (car x) 'lambda) (pair? (cdr x)) (pair? (cadr x)) (null? (cdadr x)) (pair? (cddr x)) (= (tree-count1 (caadr x) (cddr x) 0) 1))) (define (tree-subst new old tree) (cond ((equal? old tree) new) ((not (pair? tree)) tree) ((eq? (car tree) 'quote) (copy-tree tree)) (else (cons (tree-subst new old (car tree)) (tree-subst new old (cdr tree)))))) (define* (find-unique-name f1 f2 (i 1)) (let ((sym (string->symbol (format #f "_~D_" i)))) (if (not (or (eq? sym f1) (eq? sym f2) (tree-member sym f1) (tree-member sym f2))) sym (find-unique-name f1 f2 (+ i 1))))) (define (unrelop caller head form) ; assume len=3 (let ((arg1 (cadr form)) (arg2 (caddr form))) (if (and (pair? arg1) (= (length arg1) 3)) (if (eq? (car arg1) '-) (if (memv arg2 '(0 0.0)) ; (< (- x y) 0) -> (< x y), need both 0 and 0.0 because (eqv? 0 0.0) is #f (lint-format "perhaps ~A" caller (lists->string form `(,head ,(cadr arg1) ,(caddr arg1)))) (if (and (integer? arg2) ; (> (- x 50868) 256) -> (> x 51124) (integer? (caddr arg1))) (lint-format "perhaps ~A" caller (lists->string form `(,head ,(cadr arg1) ,(+ (caddr arg1) arg2)))))) ;; (> (- x) (- y)) (> (- x 1) (- y 1)) and so on -- do these ever happen? (no, not even if we allow +-*/) (if (and (eq? (car arg1) '+) ; (< (+ x 1) 3) -> (< x 2) (integer? arg2) (integer? (caddr arg1))) (lint-format "perhaps ~A" caller (lists->string form `(,head ,(cadr arg1) ,(- arg2 (caddr arg1))))))) (if (and (pair? arg2) (= (length arg2) 3)) (if (eq? (car arg2) '-) (if (memv arg1 '(0 0.0)) ; (< 0 (- x y)) -> (> x y) (lint-format "perhaps ~A" caller (lists->string form `(,(hash-table-ref reversibles head) ,(cadr arg2) ,(caddr arg2)))) (if (and (integer? arg1) (integer? (caddr arg2))) (lint-format "perhaps ~A" caller (lists->string form `(,(hash-table-ref reversibles head) ,(cadr arg2) ,(+ arg1 (caddr arg2))))))) (if (and (eq? (car arg2) '+) ; (< 256 (+ fltdur 50868)) -> (> fltdur -50612) (integer? arg1) (integer? (caddr arg2))) (lint-format "perhaps ~A" caller (lists->string form `(,(hash-table-ref reversibles head) ,(cadr arg2) ,(- arg1 (caddr arg2))))))))))) (define (check-start-and-end caller head form ff env) (if (or (and (integer? (car form)) (integer? (cadr form)) (apply >= form)) (and (equal? (car form) (cadr form)) (not (side-effect? (car form) env)))) (lint-format "these ~A indices make no sense: ~A" caller head ff))) ; (copy x y 1 0) (define (other-case c) ((if (char-upper-case? c) char-downcase char-upcase) c)) (define (check-boolean-affinity caller form env) ;; does built-in boolean func's arg make sense (if (and (= (length form) 2) (not (symbol? (cadr form))) (not (= line-number last-simplify-boolean-line-number))) (let ((expr (simplify-boolean form () () env))) (if (not (equal? expr form)) (lint-format "perhaps ~A" caller (lists->string form expr))) ; (char? '#\a) -> #t (if (and (pair? (cadr form)) (symbol? (caadr form))) (let ((rt (if (eq? (caadr form) 'quote) (->simple-type (cadadr form)) (return-type (caadr form) env))) (head (car form))) (if (subsumes? head rt) (lint-format "~A is always #t" caller (truncated-list->string form)) ; (char? '#\a) is always #t (if (not (or (memq rt '(#t #f values)) (any-compatible? head rt))) (lint-format "~A is always #f" caller (truncated-list->string form))))))))) ; (number? (make-list 1)) is always #f (define combinable-cxrs (let ((h (make-hash-table))) (for-each (lambda (c) (hash-table-set! h c (let ((name (symbol->string c))) (substring name 1 (- (length name) 1))))) '(car cdr caar cadr cddr cdar caaar caadr caddr cdddr cdaar cddar cadar cdadr cadddr cddddr)) h)) ;; not combinable: caaaar caaadr caadar caaddr cadaar cadadr caddar cdaaar cdaadr cdadar cdaddr cddaar cddadr cdddar (define (combine-cxrs form) (let ((cxr? (lambda (s) (and (pair? (cdr s)) (pair? (cadr s)) (memq (caadr s) '(car cdr cadr cddr cdar cdddr cddddr)))))) (and (cxr? form) (let* ((arg1 (cadr form)) (arg2 (and arg1 (cxr? arg1) (cadr arg1))) (arg3 (and arg2 (cxr? arg2) (cadr arg2)))) (values (string-append (hash-table-ref combinable-cxrs (car form)) (hash-table-ref combinable-cxrs (car arg1)) (if arg2 (hash-table-ref combinable-cxrs (car arg2)) "") (if arg3 (hash-table-ref combinable-cxrs (car arg3)) "")) (cadr (or arg3 arg2 arg1))))))) #| ;; this builds the lists below: (let ((ci ()) (ic ())) (for-each (lambda (c) (let ((name (reverse (substring (symbol->string c) 1 (- (length (symbol->string c)) 1))))) (do ((sum 0) (len (length name)) (i 0 (+ i 1)) (bit 0 (+ bit 2))) ((= i len) (set! ci (cons (cons c sum) ci)) (set! ic (cons (cons sum c) ic))) (set! sum (+ sum (expt 2 (if (char=? (name i) #\a) bit (+ bit 1)))))))) '(car cdr caar cadr cddr cdar caaar caadr caddr cdddr cdaar cddar cadar cdadr cadddr cddddr caaaar caaadr caadar caaddr cadaar cadadr caddar cdaaar cdaadr cdadar cdaddr cddaar cddadr cdddar)) (list (reverse ci) (reverse ic))) |# (define match-cxr (let ((cxr->int (hash-table '(car . 1) '(cdr . 2) '(caar . 5) '(cadr . 6) '(cddr . 10) '(cdar . 9) '(caaar . 21) '(caadr . 22) '(caddr . 26) '(cdddr . 42) '(cdaar . 37) '(cddar . 41) '(cadar . 25) '(cdadr . 38) '(cadddr . 106) '(cddddr . 170) '(caaaar . 85) '(caaadr . 86) '(caadar . 89) '(caaddr . 90) '(cadaar . 101) '(cadadr . 102) '(caddar . 105) '(cdaaar . 149) '(cdaadr . 150) '(cdadar . 153) '(cdaddr . 154) '(cddaar . 165) '(cddadr . 166) '(cdddar . 169))) (int->cxr (hash-table '(1 . car) '(2 . cdr) '(5 . caar) '(6 . cadr) '(10 . cddr) '(9 . cdar) '(21 . caaar) '(22 . caadr) '(26 . caddr) '(42 . cdddr) '(37 . cdaar) '(41 . cddar) '(25 . cadar) '(38 . cdadr) '(106 . cadddr) '(170 . cddddr) '(85 . caaaar) '(86 . caaadr) '(89 . caadar) '(90 . caaddr) '(101 . cadaar) '(102 . cadadr) '(105 . caddar) '(149 . cdaaar) '(150 . cdaadr) '(153 . cdadar) '(154 . cdaddr) '(165 . cddaar) '(166 . cddadr) '(169 . cdddar)))) (lambda (c1 c2) (hash-table-ref int->cxr (logand (or (hash-table-ref cxr->int c1) 0) (or (hash-table-ref cxr->int c2) 0)))))) (define (mv-range producer env) (if (symbol? producer) (let ((v (var-member producer env))) (and (var? v) (pair? ((cdr v) 'values)) ((cdr v) 'values))) (and (pair? producer) (if (memq (car producer) '(lambda lambda*)) (count-values (cddr producer)) (if (eq? (car producer) 'values) (let ((len (- (length producer) 1))) (for-each (lambda (p) (if (and (pair? p) (eq? (car p) 'values)) (set! len (- (+ len (length p)) 2)))) (cdr producer)) (list len len)) (mv-range (car producer) env)))))) (define (eval-constant-expression caller form) (if (every? code-constant? (cdr form)) (catch #t (lambda () (let ((val (eval (copy form :readable)))) (lint-format "perhaps ~A" caller (lists->string form val)))) ; (eq? #(0) #(0)) -> #f (lambda args #t)))) (define (unbegin x) ((if (and (pair? x) (eq? (car x) 'begin)) cdr list) x)) (define (un_{list} tree) (if (not (pair? tree)) tree (if (eq? (car tree) #_{list}) (if (assq #_{apply_values} (cdr tree)) (if (and (pair? (cadr tree)) (eq? (caadr tree) #_{apply_values})) `(append ,(cadadr tree) ,(cadr (caddr tree))) `(cons ,(cadr tree) ,(cadr (caddr tree)))) (cons 'list (un_{list} (cdr tree)))) (cons (if (eq? (car tree) #_{append}) 'append (un_{list} (car tree))) (un_{list} (cdr tree)))))) (define (qq-tree? tree) (and (pair? tree) (or (eq? (car tree) #_{apply_values}) (if (and (eq? (car tree) #_{list}) (assq #_{apply_values} (cdr tree))) (or (not (= (length tree) 3)) (not (and (pair? (caddr tree)) (eq? (caaddr tree) #_{apply_values}))) (qq-tree? (cadr (caddr tree))) (if (and (pair? (cadr tree)) (eq? (caadr tree) #_{apply_values})) (qq-tree? (cadadr tree)) (qq-tree? (cadr tree)))) (or (qq-tree? (car tree)) (qq-tree? (cdr tree))))))) (define special-case-functions (let ((h (make-hash-table))) ;; ---------------- member and assoc ---------------- (let () (define (sp-memx caller head form env) (define (list-one? p) (and (pair? p) (pair? (cdr p)) (null? (cddr p)) (case (car p) ((list) cadr) ((quote) (and (pair? (cadr p)) (null? (cdadr p)) (if (symbol? (caadr p)) (lambda (x) (list 'quote (caadr x))) caadr))) (else #f)))) (when (= (length form) 4) (let ((func (list-ref form 3))) (if (symbol? func) (if (memq func '(eq? eqv? equal?)) ; (member x y eq?) -> (memq x y) (let ((op (if (eq? head 'member) ; (member (car x) entries equal?) -> (member (car x) entries) (case func ((eq?) 'memq) ((eqv?) 'memv) (else 'member)) (case func ((eq?) 'assq) ((eqv?) 'assv) (else 'assoc))))) (lint-format "perhaps ~A" caller (lists->string form `(,op ,(cadr form) ,(caddr form))))) (let ((sig (procedure-signature (symbol->value func)))) ; arg-signature here is too cranky (if (and (pair? sig) (not (eq? 'boolean? (car sig))) (not (and (pair? (car sig)) (memq 'boolean? (car sig))))) (lint-format "~A is a questionable ~A function" caller func head)))) ; (member 1 x abs) ;; func not a symbol (if (and (pair? func) (= (length func) 3) ; (member 'a x (lambda (a b c) (eq? a b))) (eq? (car func) 'lambda) (pair? (cadr func)) (pair? (caddr func))) (if (not (memv (length (cadr func)) '(2 -1))) (lint-format "~A equality function (optional third arg) should take two arguments" caller head) (if (eq? head 'member) (let ((eq (caddr func)) (args (cadr func))) (if (and (memq (car eq) '(eq? eqv? equal?)) (eq? (car args) (cadr eq)) (pair? (caddr eq)) (eq? (car (caddr eq)) 'car) (pair? (cdr (caddr eq))) (pair? (cdr args)) (eq? (cadr args) (cadr (caddr eq)))) (lint-format "member might perhaps be ~A" ; (member 'a x (lambda (a b) (eq? a (car b)))) caller (if (or (eq? func 'eq?) (eq? (car (caddr func)) 'eq?)) 'assq (if (eq? (car (caddr func)) 'eqv?) 'assv 'assoc))))))))))) (when (= (length form) 3) (let ((selector (cadr form)) (items (caddr form))) (let ((current-eqf (case head ((memq assq) 'eq?) ((memv assv) 'eqv?) (else 'equal?))) (selector-eqf (car (eqf selector env))) (one-item (and (memq head '(memq memv member)) (list-one? items)))) ;; one-item assoc doesn't simplify cleanly (if one-item (let* ((target (one-item items)) (iter-eqf (eqf target env))) (if (or (symbol? target) (and (pair? target) (not (eq? (car target) 'quote)))) (set! target (list 'quote target))) ; ; (member x (list "asdf")) -> (string=? x "asdf") -- maybe equal? here? (lint-format "perhaps ~A" caller (lists->string form `(,(cadr iter-eqf) ,selector ,target)))) ;; not one-item (letrec ((duplicates? (lambda (lst fnc) (and (pair? lst) (or (fnc (car lst) (cdr lst)) (duplicates? (cdr lst) fnc))))) (duplicate-constants? (lambda (lst fnc) (and (pair? lst) (or (and (constant? (car lst)) (fnc (car lst) (cdr lst))) (duplicate-constants? (cdr lst) fnc)))))) (if (and (symbol? selector-eqf) ; (memq 1.0 x): perhaps memq -> memv (not (eq? selector-eqf current-eqf))) (lint-format "~A: perhaps ~A -> ~A" caller (truncated-list->string form) head (if (memq head '(memq memv member)) (case selector-eqf ((eq?) 'memq) ((eqv?) 'memv) ((equal?) 'member)) (case selector-eqf ((eq?) 'assq) ((eqv?) 'assv) ((equal?) 'assoc))))) ;; -------------------------------- ;; check for head mismatch with items (when (pair? items) (when (or (eq? (car items) 'list) (and (eq? (car items) 'quote) (pair? (cadr items)))) (let ((elements ((if (eq? (car items) 'quote) cadr cdr) items))) (let ((baddy #f)) (catch #t (lambda () (set! baddy ((if (eq? (car items) 'list) duplicate-constants? duplicates?) elements (symbol->value head)))) (lambda args #f)) (if (pair? baddy) ; (member x (list "asd" "abc" "asd")) (lint-format "duplicated entry ~S in ~A" caller (car baddy) items))) (when (proper-list? elements) (let ((maxf #f) (keys (if (eq? (car items) 'quote) (if (memq head '(memq memv member)) elements (and (every? pair? elements) (map car elements))) (if (memq head '(memq memv member)) (and (every? code-constant? elements) elements) (and (every? (lambda (e) (and (pair? e) (eq? (car e) 'quote))) elements) (map caadr elements)))))) (when (proper-list? keys) (if (eq? (car items) 'quote) (do ((p keys (cdr p))) ((or (null? p) (memq maxf '(equal? #t)))) (let ((element (car p))) (if (symbol? element) (if (not maxf) (set! maxf 'eq?)) (if (pair? element) (begin (if (and (eq? (car element) 'quote) (pair? (cdr element))) (lint-format "stray quote? ~A" caller form)) ; (memq x '(a 'b c)) (set! maxf #t)) (let ((type (if (symbol? element) 'eq? (car (->eqf (->simple-type element)))))) (if (or (memq maxf '(#f eq?)) (memq type '(#t equal?))) (set! maxf type))))))) ;; else (list ...) (do ((p keys (cdr p))) ((or (null? p) (memq maxf '(equal? #t)))) (let ((element (car p))) (if (symbol? element) (set! maxf #t) (let ((type (car (eqf element env)))) (if (or (memq maxf '(#f eq?)) (memq type '(#t equal?))) (set! maxf type))))))) (case maxf ((eq?) (if (not (memq head '(memq assq))) ; (member (car op) '(x y z)) (lint-format "~A could be ~A in ~A" caller head (if (memq head '(memv member)) 'memq 'assq) form))) ((eqv?) (if (not (memq head '(memv assv))) ; (memq (strname 0) '(#\{ #\[ #\())) (lint-format "~A ~Aould be ~A in ~A" caller head (if (memq head '(memq assq)) "sh" "c") (if (memq head '(memq member)) 'memv 'assv) form))) ((equal? #t) ; (memq (car op) '("a" #())) (if (not (memq head '(member assoc))) (lint-format "~A should be ~A in ~A" caller head (if (memq head '(memq memv)) 'member 'assoc) form))))))) ;; -------------------------------- (if (and (= (length elements) 2) ; (memq expr '(#t #f)) (memq #t elements) (memq #f elements)) (lint-format "perhaps ~A" caller (lists->string form `(boolean? ,selector)))))) ;; not (memv x '(0 0.0)) -> (zero? x) because x might not be a number (let ((memx (memq head '(memq memv member)))) (case (car items) ((map) (when (and memx (= (length items) 3)) (let ((mapf (cadr items)) (map-items (caddr items))) (cond ((eq? mapf 'car) ; (memq x (map car y)) -> (assq x y) (lint-format "perhaps use assoc: ~A" caller (lists->string form `(,(case current-eqf ((eq?) 'assq) ((eqv?) 'assv) ((equal?) 'assoc)) ,selector ,map-items)))) ((eq? selector #t) (if (eq? mapf 'null?) ; (memq #t (map null? items)) -> (memq () items) (lint-format "perhaps ~A" caller (lists->string form `(memq () ,map-items))) (let ((b (if (eq? mapf 'b) 'c 'b))) ;; (memq #t (map cadr items)) -> (member #t items (lambda (a b) (cadr b))) (lint-format "perhaps avoid 'map: ~A" caller (lists->string form `(member #t ,map-items (lambda (a ,b) (,mapf ,b)))))))) ((and (pair? selector) (eq? (car selector) 'string->symbol) ; this could be extended, but it doesn't happen (eq? mapf 'string->symbol) (not (and (pair? map-items) (eq? (car map-items) 'quote)))) (lint-format "perhaps ~A" caller ;; (memq (string->symbol x) (map string->symbol y)) -> (member x y string=?) (lists->string form `(member ,(cadr selector) ,map-items string=?)))) (else ;; (member x (map b items)) -> (member x items (lambda (a c) (equal? a (b c)))) (let ((b (if (eq? mapf 'b) 'c 'b))) ; a below can't collide because eqf won't return 'a (lint-format "perhaps avoid 'map: ~A" caller (lists->string form `(member ,selector ,map-items (lambda (a ,b) (,current-eqf a (,mapf ,b)))))))))))) ((string->list) ; (memv c (string->list s)) -> (char-position c s) (lint-format "perhaps ~A" caller (lists->string form `(char-position ,(cadr form) ,@(cdr items))))) ((cons) ; (member x (cons y z)) -> (or (equal? x y) (member x z)) (if (not (pair? selector)) (lint-format "perhaps avoid 'cons: ~A" caller (lists->string form `(or (,current-eqf ,selector ,(cadr items)) (,head ,selector ,(caddr items))))))) ((append) ; (member x (append (list x) y)) -> (or (equal? x x) (member x y)) (if (and (not (pair? selector)) (= (length items) 3) (pair? (cadr items)) (eq? (caadr items) 'list) (null? (cddadr items))) (lint-format "perhaps ~A" caller (lists->string form `(or (,current-eqf ,selector ,(cadadr items)) (,head ,selector ,(caddr items))))))))))))) (when (and (memq head '(memq memv)) (pair? items) (eq? (car items) 'quote) (pair? (cadr items))) (let ((nitems (length (cadr items)))) (if (pair? selector) ; (memv (string-ref x 0) '(+ -)) -> #f etc (let ((sig (arg-signature (car selector) env))) (if (and (pair? sig) (symbol? (car sig)) (not (eq? (car sig) 'values))) (let ((vals (map (lambda (item) (if ((symbol->value (car sig)) item) item (values))) (cadr items)))) (if (not (= (length vals) nitems)) (lint-format "perhaps ~A" caller (lists->string form (and (pair? vals) `(,head ,selector ',vals))))))))) (if (> nitems 20) (lint-format "perhaps use a hash-table here, rather than ~A" caller (truncated-list->string form))) (let ((bad (find-if (lambda (x) (not (or (symbol? x) (char? x) (number? x) (procedure? x) ; (memq abs '(1 #_abs 2)) ! (memq x '(#f #t () #<unspecified> #<undefined> #<eof>))))) (cadr items)))) (if bad (lint-format (if (and (pair? bad) (eq? (car bad) 'unquote)) (values "stray comma? ~A" caller) ; (memq x '(a (unquote b) c)) (values "pointless list member: ~S in ~A" caller bad)) ;; quoted item here is caught above ; (memq x '(a (+ 1 2) 3)) form)))))))) (for-each (lambda (f) (hash-table-set! h f sp-memx)) '(memq assq memv assv member assoc))) ;; ---------------- car, cdr, etc ---------------- (let () (define (sp-crx caller head form env) (if (not (= line-number last-simplify-cxr-line-number)) ((lambda* (cxr arg) (when cxr (set! last-simplify-cxr-line-number line-number) (cond ((< (length cxr) 5) ; (car (cddr x)) -> (caddr x) (lint-format "perhaps ~A" caller (lists->string form `(,(symbol "c" cxr "r") ,arg)))) ;; if it's car|cdr followed by cdr's, use list-ref|tail ((not (char-position #\a cxr)) ; (cddddr (cddr x)) -> (list-tail x 6) (lint-format "perhaps ~A" caller (lists->string form `(list-tail ,arg ,(length cxr))))) ((not (char-position #\a (substring cxr 1))) ; (car (cddddr (cddr x))) -> (list-ref x 6) (lint-format "perhaps ~A" caller (lists->string form `(list-ref ,arg ,(- (length cxr) 1))))) (else (set! last-simplify-cxr-line-number -1))))) (combine-cxrs form))) (when (pair? (cadr form)) (let ((arg (cadr form))) (when (eq? head 'car) (case (car arg) ((list-tail) ; (car (list-tail x y)) -> (list-ref x y) (lint-format "perhaps ~A" caller (lists->string form `(list-ref ,(cadr arg) ,(caddr arg))))) ((memq memv member assq assv assoc) (if (pair? (cdr arg)) ; (car (memq x ...)) is either x or (car #f) -> error (lint-format "~A is ~A, or an error" caller (truncated-list->string form) (cadr arg)))))) (when (and (eq? (car arg) 'or) ; (cdr (or (assoc x y) (cons 1 2))) -> (cond ((assoc x y) => cdr) (else 2)) (not (eq? form last-rewritten-internal-define)) (= (length arg) 3)) (let ((arg1 (cadr arg)) (arg2 (caddr arg))) (if (and (pair? arg2) (or (and (memq (car arg2) '(cons list #_{list})) (eq? head 'cdr)) (memq (car arg2) '(error throw)) (and (eq? (car arg2) 'quote) (pair? (cdr arg2)) (pair? (cadr arg2))))) (lint-format "perhaps ~A" caller (lists->string form ; (cdr (or (assoc n oi) (list n y))) -> (cond ((assoc n oi) => cdr) (else (list y))) `(cond (,arg1 => ,head) (else ,(case (car arg2) ((quote) ((symbol->value head) (cadr arg2))) ((cons) (caddr arg2)) ((error throw) arg2) (else `(list ,@(cddr arg2))))))))))) (if (and (memq head '(car cdr)) (eq? (car arg) 'cons)) (lint-format "(~A~A) is the same as ~A" ; (car(cons 1 2)) is the same as 1 caller head (truncated-list->string arg) (if (eq? head 'car) (truncated-list->string (cadr arg)) (truncated-list->string (caddr arg))))) (when (memq head '(car cadr caddr cadddr)) (if (memq (car arg) '(string->list vector->list)) ; (car (string->list x)) -> (string-ref x 0) (lint-format "perhaps ~A" caller (lists->string form `(,(if (eq? (car arg) 'string->list) 'string-ref 'vector-ref) ,(cadr arg) ,(case head ((car) 0) ((cadr) 1) ((caddr) 2) (else 3))))) (if (memq (car arg) '(reverse reverse!)) (lint-format "perhaps ~A~A" caller ; (car (reverse x)) -> (list-ref x (- (length x) 1)) (if (eq? head 'car) "use 'last from srfi-1, or " "") (lists->string form (if (symbol? (cadr arg)) `(list-ref ,(cadr arg) (- (length ,(cadr arg)) ,(case head ((car) 1) ((cadr) 2) ((caddr) 3) (else 4)))) `(let ((_1_ ,(cadr arg))) ; let is almost certainly cheaper than reverse (list-ref _1_ (- (length _1_) ,(case head ((car) 1) ((cadr) 2) ((caddr) 3) (else 4)))))))))))))) (for-each (lambda (f) (hash-table-set! h (car f) sp-crx)) combinable-cxrs)) ;; ---------------- set-car! ---------------- (let () (define (sp-set-car! caller head form env) (when (= (length form) 3) (let ((target (cadr form))) (if (pair? target) (case (car target) ((list-tail) ; (set-car! (list-tail x y) z) -> (list-set! x y z) (lint-format "perhaps ~A" caller (lists->string form `(list-set! ,(cadr target) ,(caddr target) ,(caddr form))))) ((cdr cddr cdddr cddddr) ; (set-car! (cddr (cdddr x)) y) -> (list-set! x 5 y) (set! last-simplify-cxr-line-number line-number) (lint-format "perhaps ~A" caller (lists->string form (if (and (pair? (cadr target)) (memq (caadr target) '(cdr cddr cdddr cddddr))) ;; (set-car! (cdr (cddr x)) y) -> (list-set! x 3 y) `(list-set! ,(cadadr target) ,(+ (cdr-count (car target)) (cdr-count (caadr target))) ,(caddr form)) ;; (set-car! (cdr x) y) -> (list-set! x 1 y) `(list-set! ,(cadr target) ,(cdr-count (car target)) ,(caddr form))))))))))) (hash-table-set! h 'set-car! sp-set-car!)) ;; ---------------- not ---------------- (let () (define (sp-not caller head form env) (if (and (pair? (cdr form)) (pair? (cadr form))) (if (eq? (caadr form) 'not) (let ((str (truncated-list->string (cadadr form)))) ; (not (not x)) -> (and x #t) (lint-format "if you want a boolean, (not (not ~A)) -> (and ~A #t)" 'paranoia str str)) (let ((sig (arg-signature (caadr form) env))) (if (and (pair? sig) (if (pair? (car sig)) ; (not (+ x y)) (not (memq 'boolean? (car sig))) (not (memq (car sig) '(#t values boolean?))))) (lint-format "~A can't be true (~A never returns #f)" caller (truncated-list->string form) (caadr form)))))) (if (not (= line-number last-simplify-boolean-line-number)) (let ((val (simplify-boolean form () () env))) (set! last-simplify-boolean-line-number line-number) (if (not (equal? form val)) ; (not (and (> x 2) (not z))) -> (or (<= x 2) z) (lint-format "perhaps ~A" caller (lists->string form val)))))) (hash-table-set! h 'not sp-not)) ;; ---------------- and/or ---------------- (let () (define (sp-and caller head form env) (if (not (= line-number last-simplify-boolean-line-number)) (let ((val (simplify-boolean form () () env))) (set! last-simplify-boolean-line-number line-number) (if (not (equal? form val)) ; (and (not x) (not y)) -> (not (or x y)) (lint-format "perhaps ~A" caller (lists->string form val))))) (if (pair? (cdr form)) (do ((p (cdr form) (cdr p))) ((null? (cdr p))) (if (and (pair? (car p)) (eq? (caar p) 'if) (= (length (car p)) 3)) ; (and (member n cvars) (if (pair? open) (not (member n open))) (not (eq? n open))) (lint-format "one-armed if might cause confusion here: ~A" caller form))))) (hash-table-set! h 'and sp-and) (hash-table-set! h 'or sp-and)) ;; ---------------- = ---------------- (let () (define (sp-= caller head form env) (let ((len (length form))) (if (and (> len 2) (let any-real? ((lst (cdr form))) ; ignore 0.0 and 1.0 in this since they normally work (and (pair? lst) (or (and (number? (car lst)) (not (rational? (car lst))) (not (member (car lst) '(0.0 1.0) =))) (any-real? (cdr lst)))))) ; (= x 1.5) (lint-format "= can be troublesome with floats: ~A" caller (truncated-list->string form))) (let ((cleared-form (cons = (remove-if (lambda (x) (not (number? x))) (cdr form))))) (if (and (> (length cleared-form) 2) (not (checked-eval cleared-form))) ; (= 1 y 2) (lint-format "this comparison can't be true: ~A" caller (truncated-list->string form)))) (when (= len 3) (let ((arg1 (cadr form)) (arg2 (caddr form))) ;; (= (+ x a) (+ y a)) and various equivalents happen very rarely (only in test suites it appears) (let ((var (or (and (memv arg1 '(0 1)) (pair? arg2) (eq? (car arg2) 'length) (cadr arg2)) (and (memv arg2 '(0 1)) (pair? arg1) (eq? (car arg1) 'length) (cadr arg1))))) ;; we never seem to have var-member/initial-value/history here to distinguish types ;; and a serious attempt to do so was a bust. (if var (if (or (eqv? arg1 0) ; (= (length x) 0) -> (null? x) (eqv? arg2 0)) (lint-format "perhaps (assuming ~A is a list), ~A" caller var (lists->string form `(null? ,var))) (if (symbol? var) ; (= (length x) 1) -> (and (pair? x) (null? (cdr x))) (lint-format "perhaps (assuming ~A is a list), ~A" caller var (lists->string form `(and (pair? ,var) (null? (cdr ,var)))))))))) (unrelop caller '= form)) (check-char-cmp caller '= form))) (hash-table-set! h '= sp-=)) ;; ---------------- < > <= >= ---------------- (let () (define (sp-< caller head form env) (let ((cleared-form (cons head ; keep operator (remove-if (lambda (x) (not (number? x))) (cdr form))))) (if (and (> (length cleared-form) 2) (not (checked-eval cleared-form))) ; (< x 1 2 0 y) (lint-format "this comparison can't be true: ~A" caller (truncated-list->string form)))) (if (= (length form) 3) (unrelop caller head form) (when (> (length form) 3) (if (and (memq head '(< >)) ; (< x y x) -> #f (repeated-member? (cdr form) env)) (lint-format "perhaps ~A" caller (truncated-lists->string form #f)) (if (and (memq head '(<= >=)) (repeated-member? (cdr form) env)) (do ((last-arg (cadr form)) (new-args (list (cadr form))) (lst (cddr form) (cdr lst))) ((null? lst) (if (repeated-member? new-args env) ; (<= x y x z x) -> (= x y z) (lint-format "perhaps ~A" caller (truncated-lists->string form `(= ,@(lint-remove-duplicates (reverse new-args) env)))) (if (< (length new-args) (length (cdr form))) (lint-format "perhaps ~A" caller ; (<= x x y z) -> (= x y z) (truncated-lists->string form (or (null? (cdr new-args)) `(= ,@(reverse new-args)))))))) (unless (equal? (car lst) last-arg) (set! last-arg (car lst)) (set! new-args (cons last-arg new-args)))))))) (cond ((not (= (length form) 3))) ((and (real? (cadr form)) (or (< (cadr form) 0) (and (zero? (cadr form)) (eq? head '>))) (pair? (caddr form)) ; (> 0 (string-length x)) (hash-table-ref non-negative-ops (caaddr form))) (lint-format "~A can't be negative: ~A" caller (caaddr form) (truncated-list->string form))) ((and (real? (caddr form)) (or (< (caddr form) 0) (and (zero? (caddr form)) (eq? head '<))) (pair? (cadr form)) ; (< (string-length x) 0) (hash-table-ref non-negative-ops (caadr form))) (lint-format "~A can't be negative: ~A" caller (caadr form) (truncated-list->string form))) ((and (pair? (cadr form)) (eq? (caadr form) 'length)) (let ((arg (cadadr form))) (when (symbol? arg) ; (>= (length x) 0) -> (list? x) ;; see comment above about distinguishing types! (twice I've wasted my time) (if (eqv? (caddr form) 0) (lint-format "perhaps~A ~A" caller (if (eq? head '<) "" (format #f " (assuming ~A is a proper list)," arg)) (lists->string form (case head ((<) `(and (pair? ,arg) (not (proper-list? ,arg)))) ((<=) `(null? ,arg)) ((>) `(pair? ,arg)) ((>=) `(list? ,arg))))) (if (and (eqv? (caddr form) 1) (not (eq? head '>))) ; (<= (length x) 1) -> (or (null? x) (null? (cdr x))) (lint-format "perhaps (assuming ~A is a proper list), ~A" caller arg (lists->string form (case head ((<) `(null? ,arg)) ((<=) `(or (null? ,arg) (null? (cdr ,arg)))) ((>) `(and (pair? ,arg) (pair? (cdr ,arg)))) ((>=) `(pair? ,arg)))))))))) ((and (pair? (caddr form)) (eq? (caaddr form) 'length)) (let ((arg (cadr (caddr form)))) (when (symbol? arg) ; (>= 0 (length x)) -> (null? x) (if (eqv? (cadr form) 0) (lint-format "perhaps~A ~A" caller (if (eq? head '>) "" (format #f " (assuming ~A is a proper list)," arg)) (lists->string form (case head ((<) `(pair? ,arg)) ((<=) `(list? ,arg)) ((>) `(and (pair? ,arg) (not (proper-list? ,arg)))) ((>=) `(null? ,arg))))) (if (and (eqv? (cadr form) 1) (not (eq? head '<))) ; (> 1 (length x)) -> (null? x) (lint-format "perhaps (assuming ~A is a proper list), ~A" caller arg (lists->string form (case head ((<) `(and (pair? ,arg) (pair? (cdr ,arg)))) ((<=) `(pair? ,arg)) ((>) `(null? ,arg)) ((>=) `(or (null? ,arg) (null? (cdr ,arg)))))))))))) ((and (eq? head '<) (eqv? (caddr form) 1) (pair? (cadr form)) ; (< (vector-length x) 1) -> (equal? x #()) (memq (caadr form) '(string-length vector-length))) (lint-format "perhaps ~A" caller (lists->string form `(,(if (eq? (caadr form) 'string-length) 'string=? 'equal?) ,(cadadr form) ,(if (eq? (caadr form) 'string-length) "" #()))))) ((and (eq? head '>) (eqv? (cadr form) 1) (pair? (caddr form)) ; (> 1 (string-length x)) -> (string=? x "") (memq (caaddr form) '(string-length vector-length))) (lint-format "perhaps ~A" caller (lists->string form `(,(if (eq? (caaddr form) 'string-length) 'string=? 'equal?) ,(cadr (caddr form)) ,(if (eq? (caaddr form) 'string-length) "" #()))))) ((and (memq head '(<= >=)) (or (and (eqv? (caddr form) 0) (pair? (cadr form)) ; (<= (string-length m) 0) -> (= (string-length m) 0) (hash-table-ref non-negative-ops (caadr form))) (and (eqv? (cadr form) 0) (pair? (caddr form)) (hash-table-ref non-negative-ops (caaddr form))))) (lint-format "~A is never negative, so ~A" caller ((if (eqv? (caddr form) 0) caadr caaddr) form) (lists->string form (or (not (eq? (eq? head '<=) (eqv? (caddr form) 0))) `(= ,@(cdr form)))))) ((and (eqv? (caddr form) 256) (pair? (cadr form)) ; (< (char->integer key) 256) -> #t (eq? (caadr form) 'char->integer)) (lint-format "perhaps ~A" caller (lists->string form (and (memq head '(< <=)) #t)))) ((or (and (eqv? (cadr form) 0) ; (> (numerator x) 0) -> (> x 0) (pair? (caddr form)) (eq? (caaddr form) 'numerator)) (and (eqv? (caddr form) 0) (pair? (cadr form)) (eq? (caadr form) 'numerator))) (lint-format "perhaps ~A" caller (lists->string form (if (eqv? (cadr form) 0) `(,head ,(cadr form) ,(cadr (caddr form))) `(,head ,(cadadr form) ,(caddr form))))))) (check-char-cmp caller head form)) ;; could change (> x 0) to (positive? x) and so on, but the former is clear and ubiquitous (for-each (lambda (f) (hash-table-set! h f sp-<)) '(< > <= >=))) ; '= handled above ;; ---------------- char< char> etc ---------------- (let () (define (sp-char< caller head form env) ;; only once: (char<=? #\0 c #\1) (let ((cleared-form (cons head ; keep operator (remove-if (lambda (x) (not (char? x))) (cdr form))))) (if (and (> (length cleared-form) 2) ; (char>? x #\a #\b y) (not (checked-eval cleared-form))) (lint-format "this comparison can't be true: ~A" caller (truncated-list->string form)))) (if (and (eq? head 'char-ci=?) ; (char-ci=? x #\return) (pair? (cdr form)) (pair? (cddr form)) (null? (cdddr form)) ; (char-ci=? x #\return) (or (and (char? (cadr form)) (char=? (cadr form) (other-case (cadr form)))) (and (char? (caddr form)) (char=? (caddr form) (other-case (caddr form)))))) (lint-format "char-ci=? could be char=? here: ~A" caller form) (when (and (eq? head 'char=?) ; (char=? #\a (char-downcase x)) -> (char-ci=? #\a x) (let ((casef (let ((op #f)) (lambda (a) (or (char? a) (and (pair? a) (memq (car a) '(char-downcase char-upcase)) (if op (eq? op (car a)) (set! op (car a))))))))) (every? casef (cdr form)))) (lint-format "perhaps ~A" caller (lists->string form ; (char=? #\a (char-downcase x)) -> (char-ci=? #\a x) `(char-ci=? ,@(map (lambda (a) (if (and (pair? a) (memq (car a) '(char-upcase char-downcase))) (cadr a) a)) (cdr form)))))))) (for-each (lambda (f) (hash-table-set! h f sp-char<)) '(char<? char>? char<=? char>=? char=? char-ci<? char-ci>? char-ci<=? char-ci>=? char-ci=?))) ;; ---------------- string< string> etc ---------------- (let () (define (sp-string< caller head form env) (let ((cleared-form (cons head ; keep operator (remove-if (lambda (x) (not (string? x))) (cdr form))))) (if (and (> (length cleared-form) 2) ; (string>? "a" x "b" y) (not (checked-eval cleared-form))) (lint-format "this comparison can't be true: ~A" caller (truncated-list->string form)))) (if (and (> (length form) 2) (every? (let ((op #f)) ; (string=? x (string-downcase y)) -> (string-ci=? x y) (lambda (a) (and (pair? a) (memq (car a) '(string-downcase string-upcase)) (if op (eq? op (car a)) (set! op (car a)))))) (cdr form))) (lint-format "perhaps ~A" caller ; (string=? (string-downcase x) (string-downcase y)) -> (string-ci=? x y) (lists->string form (let ((op (case head ((string=?) 'string-ci=?) ((string<=?) 'string-ci<=?) ((string>=?) 'string-ci>=?) ((string<?) 'string-ci<?) ((string>?) 'string-ci>?) (else head)))) `(,op ,@(map (lambda (a) (if (and (pair? a) (memq (car a) '(string-upcase string-downcase))) (cadr a) a)) (cdr form))))))) (if (any? (lambda (a) ; string-copy is redundant in arg list (and (pair? a) (memq (car a) '(copy string-copy)) (null? (cddr a)))) (cdr form)) (let cleaner ((args (cdr form)) (new-args ())) ; (string=? "" (string-copy "")) -> (string=? "" "") (if (not (pair? args)) (lint-format "perhaps ~A" caller (lists->string form `(,head ,@(reverse new-args)))) (let ((a (car args))) (cleaner (cdr args) (cons (if (and (pair? a) (memq (car a) '(copy string-copy)) (null? (cddr a))) (cadr a) a) new-args)))))) (when (and (eq? head 'string=?) (= (length form) 3)) ; (string=? (symbol->string a) (symbol->string b)) -> (eq? a b) (if (and (pair? (cadr form)) (eq? (caadr form) 'symbol->string) (pair? (caddr form)) (eq? (caaddr form) 'symbol->string)) (lint-format "perhaps ~A" caller (lists->string form `(eq? ,(cadadr form) ,(cadr (caddr form))))) (let ((s1 #f) (s2 #f)) (if (and (string? (cadr form)) (= (length (cadr form)) 1)) (begin (set! s1 (cadr form)) (set! s2 (caddr form))) (if (and (string? (caddr form)) (= (length (caddr form)) 1)) (begin (set! s1 (caddr form)) (set! s2 (cadr form))))) (if (and s1 ; (string=? (substring r 0 1) "S") (pair? s2) (eq? (car s2) 'substring) (= (length s2) 4) (eqv? (list-ref s2 2) 0) (eqv? (list-ref s2 3) 1)) (lint-format "perhaps ~A" caller (lists->string form `(char=? (string-ref ,(cadr s2) 0) ,(string-ref s1 0)))))))) (if (every? (lambda (a) ; (string=? "#" (string (string-ref s 0))) -> (char=? #\# (string-ref s 0)) (or (and (string? a) (= (length a) 1)) (and (pair? a) (eq? (car a) 'string)))) (cdr form)) (lint-format "perhaps ~A" caller (lists->string form `(,(symbol "char" (substring (symbol->string head) 6)) ,@(map (lambda (a) (if (string? a) (string-ref a 0) (cadr a))) (cdr form))))))) (for-each (lambda (f) (hash-table-set! h f sp-string<)) '(string<? string>? string<=? string>=? string=? string-ci<? string-ci>? string-ci<=? string-ci>=? string-ci=?))) ;; ---------------- length ---------------- (let () (define (sp-length caller head form env) (when (pair? (cdr form)) (if (pair? (cadr form)) (let ((arg (cadr form))) (case (car arg) ((string->list vector->list) (if (null? (cddr arg)) ; string->list has start:end etc ; (length (string->list x)) -> (length x) (lint-format "perhaps ~A" caller (lists->string form `(length ,(cadr arg)))) (if (pair? (cdddr arg)) (if (and (integer? (cadddr arg)) ; (length (vector->list x 1)) -> (- (length x) 1) (integer? (caddr arg))) (lint-format "perhaps ~A -> ~A" caller (truncated-list->string form) (max 0 (- (cadddr arg) (caddr arg)))) (lint-format "perhaps ~A" caller (lists->string form `(- ,(cadddr arg) ,(caddr arg))))) (lint-format "perhaps ~A" caller (lists->string form `(- (length ,(cadr arg)) ,(caddr arg))))))) ((reverse reverse! list->vector list->string let->list) (lint-format "perhaps ~A" caller (lists->string form `(length ,(cadr arg))))) ((cons) ; (length (cons item items)) -> (+ (length items) 1) (lint-format "perhaps ~A" caller (lists->string form `(+ (length ,(caddr arg)) 1)))) ((make-list) ; (length (make-list 3)) -> 3 (lint-format "perhaps ~A" caller (lists->string form (cadr arg)))) ((list) ; (length (list 'a 'b 'c)) -> 3 (lint-format "perhaps ~A" caller (lists->string form (- (length arg) 1)))) ((append) ; (length (append x y)) -> (+ (length x) (length y)) (if (= (length arg) 3) (lint-format "perhaps ~A" caller (lists->string form `(+ (length ,(cadr arg)) (length ,(caddr arg))))))) ((quote) ; (length '(1 2 3)) -> 3 (if (list? (cadr arg)) (lint-format "perhaps ~A" caller (lists->string form (length (cadr arg)))))))) ;; not pair cadr (if (code-constant? (cadr form)) ; (length 0) -> #f (lint-format "perhaps ~A -> ~A" caller (truncated-list->string form) (length ((if (and (pair? (cadr form)) (eq? (caadr form) 'quote)) cadadr cadr) form))))))) (hash-table-set! h 'length sp-length)) ;; ---------------- zero? positive? negative? ---------------- (let () (define (sp-zero? caller head form env) (when (pair? (cdr form)) (let ((arg (cadr form))) (when (pair? arg) (if (and (eq? head 'negative?) ; (negative? (string-length s))") (hash-table-ref non-negative-ops (car arg))) (lint-format "~A can't be negative: ~A" caller (caadr form) (truncated-list->string form))) (case (car arg) ((-) (lint-format "perhaps ~A" caller ; (zero? (- x)) -> (zero? x) (lists->string form (let ((op '((zero? = zero?) (positive? > negative?) (negative? < positive?)))) (if (null? (cddr arg)) `(,(caddr (assq head op)) ,(cadr arg)) (if (null? (cdddr arg)) `(,(cadr (assq head op)) ,(cadr arg) ,(caddr arg)) `(,(cadr (assq head op)) ,(cadr arg) (+ ,@(cddr arg))))))))) ((numerator) ; (negative? (numerator x)) -> (negative? x) (lint-format "perhaps ~A" caller (lists->string form `(,head ,(cadadr form))))) ((denominator) ; (zero? (denominator x)) -> error (if (eq? head 'zero) (lint-format "denominator can't be zero: ~A" caller form))) ((string-length) ; (zero? (string-length x)) -> (string=? x "") (if (eq? head 'zero?) (lint-format "perhaps ~A" caller (lists->string form `(string=? ,(cadadr form) ""))))) ((vector-length) ; (zero? (vector-length c)) -> (equal? c #()) (if (eq? head 'zero?) (lint-format "perhaps ~A" caller (lists->string form `(equal? ,(cadadr form) #()))))) ((length) ; (zero? (length routes)) -> (null? routes) (if (eq? head 'zero?) (lint-format "perhaps (assuming ~A is list) use null? instead of length: ~A" caller (cadr arg) (lists->string form `(null? ,(cadr arg))))))))))) ;; (zero? (logand...)) is nearly always preceded by not and handled elsewhere (for-each (lambda (f) (hash-table-set! h f sp-zero?)) '(zero? positive? negative?))) ;; ---------------- / ---------------- (let () (define (sp-/ caller head form env) (when (pair? (cdr form)) (if (and (null? (cddr form)) (number? (cadr form)) (zero? (cadr form))) ; (/ 0) (lint-format "attempt to invert zero: ~A" caller (truncated-list->string form)) (if (and (pair? (cddr form)) ; (/ x y 2 0) (memv 0 (cddr form))) (lint-format "attempt to divide by 0: ~A" caller (truncated-list->string form)))))) (hash-table-set! h '/ sp-/)) ;; ---------------- copy ---------------- (let () (define (sp-copy caller head form env) (cond ((and (pair? (cdr form)) ; (copy (copy x)) could be (copy x) (or (number? (cadr form)) (boolean? (cadr form)) (char? (cadr form)) (and (pair? (cadr form)) (memq (caadr form) '(copy string-copy))) ; or any maker? (and (pair? (cddr form)) (equal? (cadr form) (caddr form))))) (lint-format "~A could be ~A" caller (truncated-list->string form) (cadr form))) ((and (pair? (cdr form)) ; (copy (owlet)) could be (owlet) (equal? (cadr form) '(owlet))) (lint-format "~A could be (owlet): owlet is copied internally" caller form)) ((= (length form) 5) (check-start-and-end caller 'copy (cdddr form) form env)))) (hash-table-set! h 'copy sp-copy)) ;; ---------------- string-copy ---------------- (hash-table-set! h 'string-copy (lambda (caller head form env) (if (and (pair? (cdr form)) ; (string-copy (string-copy x)) could be (string-copy x) (pair? (cadr form)) (memq (caadr form) '(copy string-copy string make-string string-upcase string-downcase string-append list->string symbol->string number->string))) (lint-format "~A could be ~A" caller (truncated-list->string form) (cadr form))))) ;; ---------------- string-down|upcase ---------------- (let () (define (sp-string-upcase caller head form env) (if (and (pair? (cdr form)) (string? (cadr form))) ; (string-downcase "SPEAK") -> "speak" (lint-format "perhaps ~A" caller (lists->string form ((if (eq? head 'string-upcase) string-upcase string-downcase) (cadr form)))))) (hash-table-set! h 'string-upcase sp-string-upcase) (hash-table-set! h 'string-downcase sp-string-upcase)) ;; ---------------- string ---------------- (let () (define (sp-string caller head form env) (if (every? (lambda (x) (and (char? x) (char<=? #\space x #\~))) ; #\0xx chars here look dumb (cdr form)) (lint-format "~A could be ~S" caller (truncated-list->string form) (apply string (cdr form))) (if (and (pair? (cdr form)) ; (string (string-ref x 0)) -> (substring x 0 1) (pair? (cadr form))) (if (and (eq? (caadr form) 'string-ref) (null? (cddr form))) (let ((arg (cdadr form))) (if (integer? (cadr arg)) ; (string (string-ref x 0)) -> (substring x 0 1) (lint-format "perhaps ~A" caller (lists->string form `(substring ,(car arg) ,(cadr arg) ,(+ 1 (cadr arg))))))) (if (and (not (null? (cddr form))) (memq (caadr form) '(char-upcase char-downcase)) (every? (lambda (p) (eq? (caadr form) (car p))) (cddr form))) ;; (string (char-downcase (string-ref x 1)) (char-downcase (string-ref x 2))) -> ;; (string-downcase (string (string-ref x 1) (string-ref x 2))) (lint-format "perhaps ~A" caller (lists->string form `(,(if (eq? (caadr form) 'char-upcase) 'string-upcase 'string-downcase) (string ,@(map cadr (cdr form))))))))))) ;; repeated args as in vector/list (sp-list below) got no hits (hash-table-set! h 'string sp-string)) ;; ---------------- string? ---------------- (let () (define (sp-string? caller head form env) (if (and (pair? (cdr form)) (pair? (cadr form)) (memq (caadr form) '(format number->string))) (if (eq? (caadr form) 'format) ; (string? (number->string x)) -> #t (lint-format "format returns either #f or a string, so ~A" caller (lists->string form (cadr form))) (lint-format "number->string always returns a string, so ~A" caller (lists->string form #t))) (check-boolean-affinity caller form env))) (hash-table-set! h 'string? sp-string?)) ;; ---------------- number? ---------------- (let () (define (sp-number? caller head form env) (if (and (pair? (cdr form)) (pair? (cadr form)) (eq? (caadr form) 'string->number)) ; (number? (string->number x)) -> (string->number x) (lint-format "string->number returns either #f or a number, so ~A" caller (lists->string form (cadr form))) (check-boolean-affinity caller form env))) (hash-table-set! h 'number? sp-number?)) ;; ---------------- symbol? etc ---------------- (let () (define (sp-symbol? caller head form env) (check-boolean-affinity caller form env)) (for-each (lambda (f) (hash-table-set! h f sp-symbol?)) '(symbol? rational? real? complex? float? keyword? gensym? byte-vector? proper-list? char? boolean? float-vector? int-vector? vector? let? hash-table? input-port? c-object? output-port? iterator? continuation? dilambda? procedure? macro? random-state? eof-object? c-pointer?))) ;; ---------------- pair? list? ---------------- (let () (define (sp-pair? caller head form env) (check-boolean-affinity caller form env) (if (and (pair? (cdr form)) ; (pair? (member x y)) -> (member x y) (pair? (cadr form)) (memq (caadr form) '(memq memv member assq assv assoc procedure-signature))) (lint-format "~A returns either #f or a pair, so ~A" caller (caadr form) (lists->string form (cadr form))))) (for-each (lambda (f) (hash-table-set! h f sp-pair?)) '(pair? list?))) ;; ---------------- integer? ---------------- (let () (define (sp-integer? caller head form env) (check-boolean-affinity caller form env) (if (and (pair? (cdr form)) ; (integer? (char-position x y)) -> (char-position x y) (pair? (cadr form)) (memq (caadr form) '(char-position string-position))) (lint-format "~A returns either #f or an integer, so ~A" caller (caadr form) (lists->string form (cadr form))))) (hash-table-set! h 'integer? sp-integer?)) ;; ---------------- null? ---------------- (let () (define (sp-null? caller head form env) (check-boolean-affinity caller form env) (if (and (pair? (cdr form)) ; (null? (string->list x)) -> (zero? (length x)) (pair? (cadr form)) (memq (caadr form) '(vector->list string->list let->list))) (lint-format "perhaps ~A" caller (lists->string form `(zero? (length ,(cadadr form))))))) (hash-table-set! h 'null? sp-null?)) ;; ---------------- odd? even? ---------------- (let () (define (sp-odd? caller head form env) (if (and (pair? (cdr form)) ; (odd? (- x 1)) -> (even? x) (pair? (cadr form)) (memq (caadr form) '(+ -)) (= (length (cadr form)) 3)) (let* ((arg1 (cadadr form)) (arg2 (caddr (cadr form))) (int-arg (or (and (integer? arg1) arg1) (and (integer? arg2) arg2)))) (if int-arg (lint-format "perhaps ~A" caller (lists->string form (if (and (integer? arg1) (integer? arg2)) (eval form) `(,(if (eq? (eq? head 'even?) (even? int-arg)) 'even? 'odd?) ,(if (integer? arg1) arg2 arg1))))))))) (hash-table-set! h 'odd? sp-odd?) (hash-table-set! h 'even? sp-odd?)) ;; ---------------- string-ref ---------------- (hash-table-set! h 'string-ref (lambda (caller head form env) (when (and (= (length form) 3) (pair? (cadr form))) (let ((target (cadr form))) (case (car target) ((substring) ; (string-ref (substring x 1) 2) -> (string-ref x (+ 2 1)) (if (= (length target) 3) (lint-format "perhaps ~A" caller (lists->string form `(string-ref ,(cadr target) (+ ,(caddr form) ,(caddr target))))))) ((symbol->string) ; (string-ref (symbol->string 'abs) 1) -> #\b (if (and (integer? (caddr form)) (pair? (cadr target)) (eq? (caadr target) 'quote) (symbol? (cadadr target))) (lint-format "perhaps ~A" caller (lists->string form (string-ref (symbol->string (cadadr target)) (caddr form)))))) ((make-string) ; (string-ref (make-string 3 #\a) 1) -> #\a (if (and (integer? (cadr target)) (integer? (caddr form)) (> (cadr target) (caddr form))) (lint-format "perhaps ~A" caller (lists->string form (if (= (length target) 3) (caddr target) #\space)))))))))) ;; ---------------- vector-ref etc ---------------- (let () (define (sp-vector-ref caller head form env) (unless (= line-number last-checker-line-number) (when (= (length form) 3) (let ((seq (cadr form))) (when (pair? seq) (if (and (memq (car seq) '(vector-ref int-vector-ref float-vector-ref list-ref hash-table-ref let-ref)) (= (length seq) 3)) ; (vector-ref (vector-ref x i) j) -> (x i j) (let ((seq1 (cadr seq))) ; x (lint-format "perhaps ~A" caller (lists->string form (if (and (pair? seq1) ; (vector-ref (vector-ref (vector-ref x i) j) k) -> (x i j k) (memq (car seq1) '(vector-ref int-vector-ref float-vector-ref list-ref hash-table-ref let-ref)) (= (length seq1) 3)) `(,(cadr seq1) ,(caddr seq1) ,(caddr seq) ,(caddr form)) `(,seq1 ,(caddr seq) ,(caddr form)))))) (if (memq (car seq) '(make-vector make-list vector list make-float-vector make-int-vector float-vector int-vector make-hash-table hash-table hash-table* inlet)) (lint-format "this doesn't make much sense: ~A" caller form))) (when (eq? head 'list-ref) (if (eq? (car seq) 'quote) (if (proper-list? (cadr seq)) ; (list-ref '(#t #f) (random 2)) -> (vector-ref #(#t #f) (random 2)) (lint-format "perhaps use a vector: ~A" caller (lists->string form `(vector-ref ,(apply vector (cadr seq)) ,(caddr form))))) (let ((index (caddr form))) ; (list-ref (cdddr f) 2) -> (list-ref f 5) (if (and (memq (car seq) '(cdr cddr cdddr)) (or (integer? index) (and (pair? index) (eq? (car index) '-) (integer? (caddr index))))) (let ((offset (cdr (assq (car seq) '((cdr . 1) (cddr . 2) (cdddr . 3)))))) (lint-format "perhaps ~A" caller (lists->string form `(list-ref ,(cadr seq) ,(if (integer? index) (+ index offset) (let ((noff (- (caddr index) offset))) (if (zero? noff) (cadr index) `(- ,(cadr index) ,noff))))))))))))))) (set! last-checker-line-number line-number))) (for-each (lambda (f) (hash-table-set! h f sp-vector-ref)) '(vector-ref list-ref hash-table-ref let-ref int-vector-ref float-vector-ref))) ;; ---------------- vector-set! etc ---------------- (let () (define (sp-vector-set! caller head form env) (when (= (length form) 4) (let ((target (cadr form)) (index (caddr form)) (val (cadddr form))) (cond ((and (pair? val) ; (vector-set! x 0 (vector-ref x 0)) (= (length val) 3) (eq? target (cadr val)) (equal? index (caddr val)) (memq (car val) '(vector-ref list-ref hash-table-ref string-ref let-ref float-vector-ref int-vector-ref))) (lint-format "redundant ~A: ~A" caller head (truncated-list->string form))) ((code-constant? target) ; (vector-set! #(0 1 2) 1 3)?? (lint-format "~A is a constant that is discarded; perhaps ~A" caller target (lists->string form val))) ((not (pair? target))) ((and (not (eq? head 'string-set!)) ; (vector-set! (vector-ref x 0) 1 2) -- vector within vector (memq (car target) '(vector-ref list-ref hash-table-ref let-ref float-vector-ref int-vector-ref))) (lint-format "perhaps ~A" caller (lists->string form `(set! (,@(cdr target) ,index) ,val)))) ((memq (car target) '(make-vector vector make-string string make-list list append cons vector-append inlet sublet copy vector-copy string-copy list-copy)) ;list-copy is from r7rs (lint-format "~A is simply discarded; perhaps ~A" caller (truncated-list->string target) ; (vector-set! (make-vector 3) 1 1) -- does this ever happen? (lists->string form val))) ((and (eq? head 'list-set!) (memq (car target) '(cdr cddr cdddr cddddr)) (integer? (caddr form))) ; (list-set! (cdr x) 0 y) -> (list-set! x 1 y) (lint-format "perhaps ~A" caller (lists->string form `(list-set! ,(cadr target) ,(+ (caddr form) (cdr-count (car target))) ,(cadddr form))))))))) (for-each (lambda (f) (hash-table-set! h f sp-vector-set!)) '(vector-set! list-set! hash-table-set! float-vector-set! int-vector-set! string-set! let-set!))) ;; ---------------- object->string ---------------- (hash-table-set! h 'object->string (lambda (caller head form env) (when (pair? (cdr form)) (if (and (pair? (cadr form)) ; (object->string (object->string x)) could be (object->string x) (eq? (caadr form) 'object->string)) (lint-format "~A could be ~A" caller (truncated-list->string form) (cadr form)) (if (pair? (cddr form)) (let ((arg2 (caddr form))) (if (and (code-constant? arg2) ; (object->string x :else) (not (memq arg2 '(#f #t :readable)))) ; #f and #t are display|write choice, :readable = ~W (lint-format "bad second argument: ~A" caller arg2)))))))) ;; ---------------- display ---------------- (hash-table-set! h 'display (lambda (caller head form env) (if (pair? (cdr form)) (let ((arg (cadr form)) (port (if (pair? (cddr form)) (caddr form) ()))) (cond ((and (string? arg) (or (string-position "ERROR" arg) (string-position "WARNING" arg))) (lint-format "There's no need to shout: ~A" caller (truncated-list->string form))) ((not (and (pair? arg) (pair? (cdr arg))))) ((and (eq? (car arg) 'format) ; (display (format #f str x)) -> (format () str x) (not (cadr arg))) (lint-format "perhaps ~A" caller (lists->string form `(format ,port ,@(cddr arg))))) ((and (eq? (car arg) 'apply) ; (display (apply format #f str x) p) -> (apply format p str x) (eq? (cadr arg) 'format) (pair? (cddr arg)) (not (caddr arg))) (lint-format "perhaps ~A" caller (lists->string form `(apply format ,port ,@(cdddr arg)))))))))) ;; ---------------- make-vector etc ---------------- (let () (define (sp-make-vector caller head form env) ;; type of initial value (for make-float|int-vector) is checked elsewhere (if (and (= (length form) 4) (eq? head 'make-vector)) ; (make-vector 3 0 #t) (lint-format "make-vector no longer has a fourth argument: ~A~%" caller form)) (if (>= (length form) 3) (case (caddr form) ((#<unspecified>) (if (eq? head 'make-vector) ; (make-vector 3 #<unspecified>) (lint-format "#<unspecified> is the default initial value in ~A" caller form))) ((0) (if (not (eq? head 'make-vector)) (lint-format "0 is the default initial value in ~A" caller form))) ((0.0) (if (eq? head 'make-float-vector) (lint-format "0.0 is the default initial value in ~A" caller form))))) (when (and (pair? (cdr form)) (integer? (cadr form)) (zero? (cadr form))) (if (pair? (cddr form)) ; (make-vector 0 0.0) (lint-format "initial value is pointless here: ~A" caller form)) (lint-format "perhaps ~A" caller (lists->string form #())))) (for-each (lambda (f) (hash-table-set! h f sp-make-vector)) '(make-vector make-int-vector make-float-vector))) ;; ---------------- make-string make-byte-vector ---------------- (let () (define (sp-make-string caller head form env) (when (and (pair? (cdr form)) (integer? (cadr form)) (zero? (cadr form))) (if (pair? (cddr form)) ; (make-byte-vector 0 0) (lint-format "initial value is pointless here: ~A" caller form)) (lint-format "perhaps ~A" caller (lists->string form "")))) ; #u8() but (equal? #u8() "") -> #t so lint combines these clauses! (for-each (lambda (f) (hash-table-set! h f sp-make-string)) '(make-string make-byte-vector))) ;; ---------------- make-list ---------------- (let () (define (sp-make-list caller head form env) (when (and (pair? (cdr form)) (integer? (cadr form)) (zero? (cadr form))) (if (pair? (cddr form)) ; (make-list 0 #f) (lint-format "initial value is pointless here: ~A" caller form)) (lint-format "perhaps ~A" caller (lists->string form ())))) (hash-table-set! h 'make-list sp-make-list)) ;; ---------------- reverse string->list etc ---------------- (let () (define (sp-reverse caller head form env) ;; not string->number -- no point in copying a number and it's caught below (when (pair? (cdr form)) (if (and (code-constant? (cadr form)) (not (memq head '(list->string list->vector string->list)))) (let ((seq (checked-eval form))) (if (not (eq? seq :checked-eval-error)) ; (symbol->string 'abs) -> "abs" (lint-format "perhaps ~A -> ~A~A" caller (truncated-list->string form) (if (pair? seq) "'" "") (if (symbol? seq) (object->string seq :readable) (object->string seq)))))) (let ((inverses '((reverse . reverse) (reverse! . reverse!) ;; reverse and reverse! are not completely interchangable: ;; (reverse (cons 1 2)): (2 . 1) ;; (reverse! (cons 1 2)): error: reverse! argument, (1 . 2), is a pair but should be a proper list (list->vector . vector->list) (vector->list . list->vector) (symbol->string . string->symbol) (string->symbol . symbol->string) (list->string . string->list) (string->list . list->string) (number->string . string->number)))) (when (and (pair? (cadr form)) (pair? (cdadr form))) (let ((inv-op (assq head inverses)) (arg (cadr form)) (arg-of-arg (cadadr form)) (func-of-arg (caadr form))) (if (pair? inv-op) (set! inv-op (cdr inv-op))) (cond ((eq? func-of-arg inv-op) ; (vector->list (list->vector x)) -> x (if (eq? head 'string->symbol) (lint-format "perhaps ~A" caller (lists->string form arg-of-arg)) (lint-format "~A could be (copy ~S)" caller form arg-of-arg))) ((and (eq? head 'list->string) ; (list->string (vector->list x)) -> (copy x (make-string (length x))) (eq? func-of-arg 'vector->list)) (lint-format "perhaps ~A" caller (lists->string form `(copy ,arg-of-arg (make-string (length ,arg-of-arg)))))) ((and (eq? head 'list->string) ; (list->string (make-list x y)) -> (make-string x y) (eq? func-of-arg 'make-list)) (lint-format "perhaps ~A" caller (lists->string form `(make-string ,@(cdr arg))))) ((and (eq? head 'string->list) ; (string->list (string x y)) -> (list x y) (eq? func-of-arg 'string)) (lint-format "perhaps ~A" caller (lists->string form `(list ,@(cdr arg))))) ((and (eq? head 'list->vector) ; (list->vector (make-list ...)) -> (make-vector ...) (eq? func-of-arg 'make-list)) (lint-format "perhaps ~A" caller (lists->string form `(make-vector ,@(cdr arg))))) ((and (eq? head 'list->vector) ; (list->vector (string->list x)) -> (copy x (make-vector (length x))) (eq? func-of-arg 'string->list)) (lint-format "perhaps ~A" caller (lists->string form `(copy ,arg-of-arg (make-vector (length ,arg-of-arg)))))) ((and (eq? head 'list->vector) ; (list->vector (append (vector->list v1) ...)) -> (append v1 ...) (eq? func-of-arg 'append) (every? (lambda (a) (and (pair? a) (eq? (car a) 'vector->list))) (cdadr form))) (lint-format "perhaps ~A" caller (lists->string form `(append ,@(map cadr (cdadr form)))))) ((and (eq? head 'vector->list) ; (vector->list (make-vector ...)) -> (make-list ...) (eq? func-of-arg 'make-vector)) (lint-format "perhaps ~A" caller (lists->string form `(make-list ,@(cdr arg))))) ((and (eq? head 'vector->list) ; (vector->list (vector ...)) -> (list ...) (eq? func-of-arg 'vector)) (lint-format "perhaps ~A" caller (lists->string form `(list ,@(cdr arg))))) ((and (eq? head 'vector->list) ; (vector->list (vector-copy ...)) -> (vector->list ...) (eq? func-of-arg 'vector-copy)) (lint-format "perhaps ~A" caller (lists->string form `(vector->list ,@(cdr arg))))) ((and (memq func-of-arg '(reverse reverse! copy)) (pair? (cadr arg)) ; (list->string (reverse (string->list x))) -> (reverse x) (eq? (caadr arg) inv-op)) (lint-format "perhaps ~A" caller (lists->string form `(,(if (eq? func-of-arg 'reverse!) 'reverse func-of-arg) ,(cadadr arg))))) ((and (memq head '(reverse reverse!)) ; (reverse (string->list x)) -> (string->list (reverse x)) -- often redundant (memq func-of-arg '(string->list vector->list sort!))) (if (eq? func-of-arg 'sort!) ; (reverse (sort! x <)) -> (sort x >) (if (and (pair? (cdr arg)) (pair? (cddr arg))) (cond ((hash-table-ref reversibles (caddr arg)) => (lambda (op) (lint-format "possibly ~A" caller (lists->string form `(sort! ,(cadr arg) ,op))))))) (if (null? (cddr arg)) (lint-format "perhaps less consing: ~A" caller (lists->string form `(,func-of-arg (reverse ,arg-of-arg))))))) ((and (pair? (cadr arg)) (memq func-of-arg '(cdr cddr cdddr cddddr list-tail)) (case head ((list->string) (eq? (caadr arg) 'string->list)) ((list->vector) (eq? (caadr arg) 'vector->list)) (else #f))) (let ((len-diff (if (eq? func-of-arg 'list-tail) (caddr arg) (cdr-count func-of-arg)))) (lint-format "perhaps ~A" caller ; (list->string (cdr (string->list x))) -> (substring x 1) (lists->string form (if (eq? head 'list->string) `(substring ,(cadadr arg) ,len-diff) `(copy ,(cadadr arg) (make-vector (- (length ,(cadadr arg)) ,len-diff)))))))) ((and (memq head '(list->vector list->string)) (eq? func-of-arg 'sort!) ; (list->vector (sort! (vector->list x) y)) -> (sort! x y) (pair? (cadr arg)) (eq? (caadr arg) (if (eq? head 'list->vector) 'vector->list 'string->list))) (lint-format "perhaps ~A" caller (lists->string form `(sort! ,(cadadr arg) ,(caddr arg))))) ((and (memq head '(list->vector list->string)) (or (memq func-of-arg '(list cons)) (quoted-undotted-pair? arg))) (let ((maker (if (eq? head 'list->vector) 'vector 'string))) (cond ((eq? func-of-arg 'list) (if (var-member maker env) ; (list->string (list x y z)) -> (string x y z) (lint-format "~A could be simplified, but you've shadowed '~A" caller (truncated-list->string form) maker) (lint-format "perhaps ~A" caller (lists->string form `(,maker ,@(cdr arg)))))) ((eq? func-of-arg 'cons) (if (any-null? (caddr arg)) (if (var-member maker env) ; (list->string (cons x ())) -> (string x) (lint-format "~A could be simplified, but you've shadowed '~A" caller (truncated-list->string form) maker) (lint-format "perhaps ~A" caller (lists->string form `(,maker ,(cadr arg))))))) ((or (null? (cddr form)) ; (list->string '(#\a #\b #\c)) -> "abc" (and (integer? (caddr form)) (or (null? (cdddr form)) (integer? (cadddr form))))) (lint-format "perhaps ~A" caller (lists->string form (apply (if (eq? head 'list->vector) vector string) (cadr arg)))))))) ((and (memq head '(list->string list->vector)) ; (list->string (reverse x)) -> (reverse (apply string x)) (memq func-of-arg '(reverse reverse!))) (lint-format "perhaps ~A" caller (lists->string form `(reverse (,head ,arg-of-arg))))) ((and (memq head '(string->list vector->list)) (= (length form) 4)) (check-start-and-end caller head (cddr form) form env)) ((and (eq? head 'string->symbol) ; (string->symbol (string-append...)) -> (symbol ...) (or (memq func-of-arg '(string-append append)) (and (eq? func-of-arg 'apply) (memq arg-of-arg '(string-append append))))) (lint-format "perhaps ~A" caller (lists->string form (if (eq? func-of-arg 'apply) `(apply symbol ,@(cddr arg)) `(symbol ,@(cdr arg)))))) ((and (eq? head 'string->symbol) ; (string->symbol (if (not (null? x)) x "abc")) -> (if (not (null? x)) (string->symbol x) 'abc) (eq? func-of-arg 'if) (or (string? (caddr arg)) (string? (cadddr arg))) (not (or (equal? (caddr arg) "") ; this is actually an error -- should we complain? (equal? (cadddr arg) "")))) (lint-format "perhaps ~A" caller (lists->string form (if (string? (caddr arg)) (if (string? (cadddr arg)) `(if ,(cadr arg) ',(string->symbol (caddr arg)) ',(string->symbol (cadddr arg))) `(if ,(cadr arg) ',(string->symbol (caddr arg)) (string->symbol ,(cadddr arg)))) `(if ,(cadr arg) (string->symbol ,(caddr arg)) ',(string->symbol (cadddr arg))))))) ((case head ; (reverse (reverse! x)) could be (copy x) ((reverse) (eq? func-of-arg 'reverse!)) ((reverse!) (eq? func-of-arg 'reverse)) (else #f)) (lint-format "~A could be (copy ~S)" caller form arg-of-arg)) ((and (pair? arg-of-arg) ; (op (reverse (inv-op x))) -> (reverse x) (eq? func-of-arg 'reverse) (eq? inv-op (car arg-of-arg))) (lint-format "perhaps ~A" caller (lists->string form `(reverse ,(cadr arg-of-arg))))))))) (unless (pair? (cadr form)) ; (string->list "123") -> (#\1 #\2 #\3) (let ((arg (cadr form))) (if (and (eq? head 'string->list) (string? arg) (or (null? (cddr form)) (and (integer? (caddr form)) (or (null? (cdddr form)) (integer? (cadddr form)))))) (lint-format "perhaps ~A -> ~A" caller (truncated-list->string form) (apply string->list (cdr form)))))) (when (pair? (cddr form)) ; (string->list x y y) is () (when (and (memq head '(vector->list string->list)) (pair? (cdddr form)) (equal? (caddr form) (cadddr form))) (lint-format "leaving aside errors, ~A is ()" caller (truncated-list->string form))) (when (and (eq? head 'number->string) ; (number->string saturation 10) (eqv? (caddr form) 10)) (lint-format "10 is the default radix for number->string: ~A" caller (truncated-list->string form)))) (when (memq head '(reverse reverse!)) (if (and (eq? head 'reverse!) (symbol? (cadr form))) (let ((v (var-member (cadr form) env))) (if (and (var? v) (eq? (var-definer v) 'parameter)) (lint-format "if ~A (a function argument) is a pair, ~A is ill-advised" caller (cadr form) (truncated-list->string form)))) (when (pair? (cadr form)) (let ((arg (cadr form))) (when (and (pair? (cdr arg)) (pair? (cadr arg))) (if (and (memq (car arg) '(cdr list-tail)) ; (reverse (cdr (reverse lst))) = all but last of lst -> copy to len-1 (memq (caadr arg) '(reverse reverse!)) (symbol? (cadadr arg))) (lint-format "perhaps ~A" caller (lists->string form `(copy ,(cadadr arg) (make-list (- (length ,(cadadr arg)) ,(if (eq? (car arg) 'cdr) 1 (caddr arg)))))))) (if (and (eq? (car arg) 'append) ; (reverse (append (reverse b) res)) = (append (reverse res) b) (eq? (caadr arg) 'reverse) (pair? (cddr arg)) (null? (cdddr arg))) (lint-format "perhaps ~A" caller (lists->string form `(append (reverse ,(caddr arg)) ,(cadadr arg)))))) (when (and (= (length arg) 3) (pair? (caddr arg))) (if (and (eq? (car arg) 'map) ; (reverse (map abs (sort! x <))) -> (map abs (sort! x >)) (eq? (caaddr arg) 'sort!)) (cond ((hash-table-ref reversibles (caddr (caddr arg))) => (lambda (op) (lint-format "possibly ~A" caller (lists->string form `(,(car arg) ,(cadr arg) (sort! ,(cadr (caddr arg)) ,op)))))))) ;; (reverse (apply vector (sort! x <))) doesn't happen (nor does this map case, but it's too pretty to leave out) (if (and (eq? (car arg) 'cons) ; (reverse (cons x (reverse lst))) -- adds x to end -- (append lst (list x)) (memq (car (caddr arg)) '(reverse reverse!))) (lint-format "perhaps ~A" caller (lists->string form `(append ,(cadr (caddr arg)) (list ,(cadr arg))))))))))))) (for-each (lambda (f) (hash-table-set! h f sp-reverse)) '(reverse reverse! list->vector vector->list list->string string->list symbol->string string->symbol number->string))) ;; ---------------- char->integer string->number etc ---------------- (let () (define (sp-char->integer caller head form env) (let ((inverses '((char->integer . integer->char) (integer->char . char->integer) (symbol->keyword . keyword->symbol) (keyword->symbol . symbol->keyword) (string->number . number->string)))) (when (pair? (cdr form)) (let ((arg (cadr form))) (if (and (pair? arg) (pair? (cdr arg)) ; (string->number (number->string x)) could be x (eq? (car arg) (cond ((assq head inverses) => cdr)))) (lint-format "~A could be ~A" caller (truncated-list->string form) (cadr arg)) (case head ((integer->char) (if (let walk ((tree (cdr form))) (if (pair? tree) (and (walk (car tree)) (walk (cdr tree))) (or (code-constant? tree) (not (side-effect? tree env))))) (let ((chr (checked-eval form))) ; (integer->char (+ (char->integer #\space) 215)) -> #\xf7 (if (char? chr) (lint-format "perhaps ~A" caller (lists->string form chr)))))) ((string->number) (if (and (pair? (cddr form)) (integer? (caddr form)) ; type error is checked elsewhere (not (<= 2 (caddr form) 16))) ; (string->number "123" 21) (lint-format "string->number radix should be between 2 and 16: ~A" caller form) (if (and (pair? arg) (eq? (car arg) 'string) (pair? (cdr arg)) (null? (cddr form)) (null? (cddr arg))) ; (string->number (string num-char)) -> (- (char->integer num-char) (char->integer #\0)) (lint-format "perhaps ~A" caller (lists->string form `(- (char->integer ,(cadr arg)) (char->integer #\0))))))) ((symbol->keyword) (if (and (pair? arg) ; (symbol->keyword (string->symbol x)) -> (make-keyword x) (eq? (car arg) 'string->symbol)) (lint-format "perhaps ~A" caller (lists->string form `(make-keyword ,(cadr arg)))))))))))) (for-each (lambda (f) (hash-table-set! h f sp-char->integer)) '(char->integer integer->char symbol->keyword keyword->symbol string->number))) ;; ---------------- string-append ---------------- (let () (define (sp-string-append caller head form env) (unless (= line-number last-checker-line-number) (let ((args (remove-all "" (splice-if (lambda (x) (eq? x 'string-append)) (cdr form)))) (combined #f)) (when (or (any? string? args) (member 'string args (lambda (a b) (and (pair? b) (eq? (car b) a))))) (do ((nargs ()) ; look for (string...) (string...) in the arg list and combine (p args (cdr p))) ((null? p) (set! args (reverse nargs))) (cond ((not (pair? (cdr p))) (set! nargs (cons (car p) nargs))) ((and (pair? (car p)) (eq? (caar p) 'string) (pair? (cadr p)) (eq? (caadr p) 'string)) (set! nargs (cons `(string ,@(cdar p) ,@(cdadr p)) nargs)) (set! combined #t) (set! p (cdr p))) ((and (string? (car p)) (string? (cadr p))) (set! nargs (cons (string-append (car p) (cadr p)) nargs)) (set! combined #t) (set! p (cdr p))) (else (set! nargs (cons (car p) nargs)))))) (cond ((null? args) ; (string-append) -> "" (lint-format "perhaps ~A" caller (lists->string form ""))) ((null? (cdr args)) ; (string-append a) -> a (if (not (tree-memq 'values (cdr form))) (lint-format "perhaps ~A~A" caller (lists->string form (car args)) (if combined "" ", or use copy")))) ; (string-append x "") appears to be a common substitute for string-copy ((every? string? args) ; (string-append "a" "b") -> "ab" (lint-format "perhaps ~A" caller (lists->string form (apply string-append args)))) ((every? (lambda (a) ; (string-append "a" (string #\b)) -> "ab" (or (string? a) (and (pair? a) (eq? (car a) 'string) (char? (cadr a))))) args) (catch #t (lambda () ; (string-append (string #\C) "ZLl*()def") -> "CZLl*()def" (let ((val (if (not (any? pair? args)) (apply string-append args) (eval (cons 'string-append args))))) (lint-format "perhaps ~A -> ~S" caller (truncated-list->string form) val))) (lambda args #f))) ((every? (lambda (c) ; (string-append (make-string 3 #\a) (make-string 2 #\b)) -> (format #f "~NC~NC" 3 #\a 2 #\b) (and (pair? c) (eq? (car c) 'make-string) (pair? (cdr c)) (pair? (cddr c)))) (cdr form)) (lint-format "perhaps ~A" caller (lists->string form `(format #f ,(apply string-append (make-list (abs (length (cdr form))) "~NC")) ,@(map (lambda (c) (values (cadr c) (caddr c))) (cdr form)))))) ((not (equal? args (cdr form))) ; (string-append x (string-append y z)) -> (string-append x y z) (lint-format "perhaps ~A" caller (lists->string form `(string-append ,@args))))) (set! last-checker-line-number line-number)))) (hash-table-set! h 'string-append sp-string-append)) ;; ---------------- vector-append ---------------- (let () (define (sp-vector-append caller head form env) (unless (= line-number last-checker-line-number) (let ((args (remove-all #() (splice-if (lambda (x) (eq? x 'vector-append)) (cdr form))))) (cond ((null? args) ; (vector-append) -> #() (lint-format "perhaps ~A" caller (lists->string form #()))) ((null? (cdr args)) ; (vector-append x) -> (copy x) (lint-format "perhaps ~A" caller (lists->string form `(copy ,(car args))))) ((every? vector? args) ; (vector-append #(1 2) (vector-append #(3))) -> #(1 2 3) (lint-format "perhaps ~A" caller (lists->string form (apply vector-append args)))) ((not (equal? args (cdr form))) ; (vector-append x (vector-append y z)) -> (vector-append x y z) (lint-format "perhaps ~A" caller (lists->string form `(vector-append ,@args))))) (set! last-checker-line-number line-number)))) (hash-table-set! h 'vector-append sp-vector-append)) ;; ---------------- cons ---------------- (let () (define (sp-cons caller head form env) (cond ((or (not (= (length form) 3)) (= last-cons-line-number line-number)) #f) ((and (pair? (caddr form)) (or (eq? (caaddr form) 'list) ; (cons x (list ...)) -> (list x ...) (and (eq? (caaddr form) #_{list}) (not (tree-member #_{apply_values} (cdaddr form)))))) (lint-format "perhaps ~A" caller (lists->string form `(list ,(cadr form) ,@(un_{list} (cdaddr form)))))) ((any-null? (caddr form)) ; (cons x '()) -> (list x) (lint-format "perhaps ~A" caller (lists->string form `(list ,(cadr form))))) ((not (pair? (caddr form)))) ((and (pair? (cadr form)) ; (cons (car x) (cdr x)) -> (copy x) (let ((x (assq (caadr form) '((car cdr #t) (caar cdar car) (cadr cddr cdr) (caaar cdaar caar) (caadr cdadr cadr) (caddr cdddr cddr) (cadar cddar cdar) (cadddr cddddr cdddr) (caaaar cdaaar caaar) (caaadr cdaadr caadr) (caadar cdadar cadar) (caaddr cdaddr caddr) (cadaar cddaar cdaar) (cadadr cddadr cdadr) (caddar cdddar cddar))))) (and x (eq? (cadr x) (caaddr form)) (caddr x)))) => (lambda (cfunc) (if (and cfunc (equal? (cadadr form) (cadr (caddr form))) (not (side-effect? (cadadr form) env))) (lint-format "perhaps ~A" caller (lists->string form (if (symbol? cfunc) `(copy (,cfunc ,(cadadr form))) `(copy ,(cadadr form)))))))) ((eq? (caaddr form) 'cons) ; list handled above ; (cons a (cons b (cons ...))) -> (list a b ...), input ending in nil of course (let loop ((args (list (cadr form))) (chain (caddr form))) (if (pair? chain) (if (eq? (car chain) 'list) (begin (lint-format "perhaps ~A" caller (lists->string form `(list ,@(reverse args) ,@(cdr chain)))) (set! last-cons-line-number line-number)) (if (and (eq? (car chain) 'cons) (pair? (cdr chain)) (pair? (cddr chain))) (if (any-null? (caddr chain)) (begin (lint-format "perhaps ~A" caller (lists->string form `(list ,@(reverse args) ,(cadr chain)))) (set! last-cons-line-number line-number)) (if (and (pair? (caddr chain)) (memq (caaddr chain) '(cons list))) (loop (cons (cadr chain) args) (caddr chain))))))))))) (hash-table-set! h 'cons sp-cons)) ;; ---------------- append ---------------- (let () (define (sp-append caller head form env) (unless (= line-number last-checker-line-number) (set! last-checker-line-number line-number) (letrec ((splice-append (lambda (lst) (cond ((null? lst) ()) ((not (pair? lst)) lst) ((and (pair? (car lst)) (eq? (caar lst) 'append)) (if (null? (cdar lst)) (if (null? (cdr lst)) ; (append) at end -> () to keep copy intact? (list ()) (splice-append (cdr lst))) (append (splice-append (cdar lst)) (splice-append (cdr lst))))) ((and (pair? (car lst)) (eq? (caar lst) 'copy) (pair? (cdr lst)) (null? (cddar lst))) (cons (cadar lst) (splice-append (cdr lst)))) ((or (null? (cdr lst)) (not (or (any-null? (car lst)) (and (pair? (car lst)) (eq? (caar lst) 'list) (null? (cdar lst)))))) (cons (car lst) (splice-append (cdr lst)))) (else (splice-append (cdr lst))))))) (let ((new-args (splice-append (cdr form)))) ; (append '(1) (append '(2) '(3))) -> (append '(1) '(2) '(3)) (let ((len1 (length new-args)) (suggestion made-suggestion)) (if (and (> len1 2) (null? (list-ref new-args (- len1 1))) (pair? (list-ref new-args (- len1 2))) (memq (car (list-ref new-args (- len1 2))) '(list cons append map string->list vector->list make-list))) (begin (set-cdr! (list-tail new-args (- len1 2)) ()) (set! len1 (- len1 1)))) (define (append->list . items) (let ((lst (list 'list))) (for-each (lambda (item) (set! lst (append lst (if (eq? (car item) 'list) (cdr item) (distribute-quote (cadr item)))))) items) lst)) (if (positive? len1) (let ((last (list-ref new-args (- len1 1)))) ;; (define (f) (append '(1) '(2))) (define a (f)) (set! (a 1) 32) (f) -> '(1 32) (if (and (pair? last) (eq? (car last) 'quote) (pair? (cdr last)) (pair? (cadr last))) (lint-format "append does not copy its last argument, so ~A is dangerous" caller form)))) (case len1 ((0) ; (append) -> () (lint-format "perhaps ~A" caller (lists->string form ()))) ((1) ; (append x) -> x (lint-format "perhaps ~A" caller (lists->string form (car new-args)))) ((2) ; (append (list x) ()) -> (list x) (let ((arg2 (cadr new-args)) (arg1 (car new-args))) (cond ((or (any-null? arg2) (equal? arg2 '(list))) ; (append x ()) -> (copy x) (lint-format "perhaps clearer: ~A" caller (lists->string form `(copy ,arg1)))) ((null? arg1) ; (append () x) -> x (lint-format "perhaps ~A" caller (lists->string form arg2))) ((not (pair? arg1))) ((and (pair? arg2) ; (append (list x y) '(z)) -> (list x y z) or extensions thereof (or (eq? (car arg1) 'list) (quoted-undotted-pair? arg1)) (or (eq? (car arg2) 'list) (quoted-undotted-pair? arg2))) (lint-format "perhaps ~A" caller (lists->string form (apply append->list new-args)))) ((and (eq? (car arg1) 'list) ; (append (list x) y) -> (cons x y) (pair? (cdr arg1)) (null? (cddr arg1))) (lint-format "perhaps ~A" caller (lists->string form `(cons ,(cadr arg1) ,arg2)))) ((and (eq? (car arg1) 'list) ; (append (list x y) z) -> (cons x (cons y z)) (pair? (cdr arg1)) (pair? (cddr arg1)) (null? (cdddr arg1))) (lint-format "perhaps ~A" caller (lists->string form `(cons ,(cadr arg1) (cons ,(caddr arg1) ,arg2))))) ;; not sure about this: reports the un-qq'd form (and never happens) ((and (eq? (car arg1) #_{list}) (not (qq-tree? arg1))) (set! last-checker-line-number -1) (sp-append caller 'append `(append ,(un_{list} arg1) ,arg2) env)) ((and (eq? (car arg1) 'vector->list) (pair? arg2) (eq? (car arg2) 'vector->list)) (lint-format "perhaps ~A" caller (lists->string form `(vector->list (append ,(cadr arg1) ,(cadr arg2)))))) ((and (eq? (car arg1) 'quote) ; (append '(x) y) -> (cons 'x y) (pair? (cadr arg1)) (null? (cdadr arg1))) (lint-format "perhaps ~A" caller (lists->string form (if (or (symbol? (caadr arg1)) (pair? (caadr arg1))) `(cons ',(caadr arg1) ,arg2) `(cons ,(caadr arg1) ,arg2))))) ((not (equal? (cdr form) new-args)) ; (append () '(1 2) 1) -> (append '(1 2) 1) (lint-format "perhaps ~A" caller (lists->string form `(append ,@new-args))))))) (else (cond ((every? (lambda (item) (and (pair? item) (or (eq? (car item) 'list) (quoted-undotted-pair? item)))) new-args) ; (append '(1) (append '(2) '(3)) '(4)) -> (list 1 2 3 4) (lint-format "perhaps ~A" caller (lists->string form (apply append->list new-args)))) ((and (pair? (car new-args)) ; (append (list x) y (list z)) -> (cons x (append y (list z)))? (eq? (caar new-args) 'list) (null? (cddar new-args))) (lint-format "perhaps ~A" caller (lists->string form `(cons ,(cadar new-args) (append ,@(cdr new-args)))))) ((let ((n-1 (list-ref new-args (- len1 2)))) (and (pair? n-1) (eq? (car n-1) 'list) (pair? (cdr n-1)) (null? (cddr n-1)))) ; (append x (list y) z) -> (append x (cons y z)) (lint-format "perhaps ~A" caller (lists->string form `(append ,@(copy new-args (make-list (- len1 2))) (cons ,(cadr (list-ref new-args (- len1 2))) ,(list-ref new-args (- len1 1))))))) ((not (equal? (cdr form) new-args)) ; (append x y (append)) -> (append x y ()) (lint-format "perhaps ~A" caller (lists->string form `(append ,@new-args))))))) (if (and (= made-suggestion suggestion) (not (equal? (cdr form) new-args))) (lint-format "perhaps ~A" caller (lists->string form `(append ,@new-args))))))))) (hash-table-set! h 'append sp-append)) ;; ---------------- apply ---------------- (let () (define (sp-apply caller head form env) (when (pair? (cdr form)) (let ((len (length form)) (suggestion made-suggestion)) (if (= len 2) ; (apply f) -> (f) (lint-format "perhaps ~A" caller (lists->string form (list (cadr form)))) (if (not (or (<= len 2) ; it might be (apply)... (symbol? (cadr form)) (applicable? (cadr form)))) (lint-format "~S is not applicable: ~A" caller (cadr form) (truncated-list->string form)) (let ((happy #f) (f (cadr form))) (unless (or (<= len 2) (any-macro? f env) (eq? f 'macroexpand)) ; handled specially (syntactic, not a macro) (when (and (symbol? f) (not (var-member f env))) (let ((func (symbol->value f *e*))) (if (procedure? func) (let ((ary (arity func))) (when (pair? ary) ; (apply real? 1 3 rest) (if (> (- len 3) (cdr ary)) ; last apply arg might be var=() (lint-format "too many arguments for ~A: ~A" caller f form)) (if (and (= len 3) (= (car ary) 1) (= (cdr ary) 1)) ; (apply car x) -> (car (car x)) (lint-format "perhaps ~A" caller (lists->string form `(,f (car ,(caddr form))))))))))) (let ((last-arg (form (- len 1)))) (if (and (not (list? last-arg)) (code-constant? last-arg)) ; (apply + 1) (lint-format "last argument should be a list: ~A" caller (truncated-list->string form)) (if (= len 3) (let ((args (caddr form))) (if (identity? f) ; (apply (lambda (x) x) y) -> (car y) (lint-format "perhaps (assuming ~A is a list of one element) ~A" caller args (lists->string form `(car ,args))) (if (simple-lambda? f) ; (apply (lambda (x) (f x)) y) -> (f (car y)) (lint-format "perhaps (assuming ~A is a list of one element) ~A" caller args (lists->string form (tree-subst (list 'car args) (caadr f) (caddr f)))))) (cond ((eq? f 'list) ; (apply list x) -> x? (lint-format "perhaps ~A" caller (lists->string form args))) ((any-null? args) ; (apply f ()) -> (f) (lint-format "perhaps ~A" caller (lists->string form (list f)))) ((or (not (pair? args)) (case (car args) ((list) ; (apply f (list a b)) -> (f a b) (lint-format "perhaps ~A" caller (lists->string form `(,f ,@(cdr args))))) ((quote) ; (apply eq? '(a b)) -> (eq? 'a 'b) (and (= suggestion made-suggestion) (lint-format "perhaps ~A" caller (lists->string form `(,f ,@(distribute-quote (cadr args))))))) ((cons) ; (apply f (cons a b)) -> (apply f a b) (lint-format "perhaps ~A" caller (lists->string form (if (and (pair? (caddr args)) (eq? (caaddr args) 'cons)) `(apply ,f ,(cadr args) ,@(cdaddr args)) `(apply ,f ,@(cdr args)))))) ((append) ; (apply f (append (list ...)...)) -> (apply f ... ...) (and (pair? (cadr args)) (eq? (caadr args) 'list) (lint-format "perhaps ~A" caller (lists->string form `(apply ,f ,@(cdadr args) ,(if (null? (cddr args)) () (if (null? (cdddr args)) (caddr args) `(append ,@(cddr args))))))))) ((reverse reverse!) ; (apply vector (reverse x)) -> (reverse (apply vector x)) (and (memq f '(string vector int-vector float-vector)) (lint-format "perhaps ~A" caller (lists->string form `(reverse (apply ,f ,(cadr args))))))) ((make-list) ; (apply string (make-list x y)) -> (make-string x y) (if (memq f '(string vector)) (lint-format "perhaps ~A" caller (lists->string form `(,(if (eq? f 'string) 'make-string 'make-vector) ,@(cdr args)))))) ((map) (case f ((string-append) ; (apply string-append (map ...)) (if (eq? (cadr args) 'symbol->string) (lint-format "perhaps ~A" caller ; (apply string-append (map symbol->string ...)) (lists->string form `(format #f "~{~A~}" ,(caddr args)))) (if (simple-lambda? (cadr args)) (let ((body (caddr (cadr args)))) (if (and (pair? body) (eq? (car body) 'string-append) (= (length body) 3) (or (and (string? (cadr body)) (eq? (caddr body) (caadr (cadr args)))) (and (string? (caddr body)) (eq? (cadr body) (caadr (cadr args)))))) (let ((str (string-append "~{" (if (string? (cadr body)) (cadr body) "~A") (if (string? (caddr body)) (caddr body) "~A") "~}"))) (lint-format "perhaps ~A" caller (lists->string form `(format #f ,str ,(caddr args)))))))))) ((string) ; (apply string (map char-downcase x)) -> (string-downcase (apply string x)) (if (memq (cadr args) '(char-upcase char-downcase)) (lint-format "perhaps, assuming ~A is a list, ~A" caller (caddr args) (lists->string form `(,(if (eq? (cadr args) 'char-upcase) 'string-upcase 'string-downcase) (apply string ,(caddr args))))))) ((append) ; (apply append (map vector->list args)) -> (vector->list (apply append args)) (and (eq? (cadr args) 'vector->list) (lint-format "perhaps ~A" caller (lists->string form `(vector->list (apply append ,@(cddr args))))))) (else #f))) ;; (apply append (map...)) is very common but changing it to ;; (map (lambda (x) (apply values (f x))) ...) from (apply append (map f ...)) ;; is not an obvious win. The code is more complicated, and currently apply values ;; copies its args (as do apply and append -- how many copies are there here?! ;; need to check for only one apply values ((#_{list}) ; (apply f `(,x ,@z)) -> (apply f x z) (let ((last-arg (list-ref args (- (length args) 1)))) (if (and (pair? last-arg) (eq? (car last-arg) #_{apply_values}) (= (tree-count1 #_{apply_values} args 0) 1)) (lint-format "perhaps ~A" caller (lists->string form `(apply ,f ,@(copy args (make-list (- (length args) 2)) 1) ,(cadr last-arg)))) (if (not (tree-member #_{apply_values} (cdr args))) (lint-format "perhaps ~A" caller (lists->string form `(,f ,@(un_{list} (cdr args)))))))))))))) (begin ; len > 3 (when (and (pair? last-arg) (eq? (car last-arg) 'list) ; (apply f y z (list a b)) -> (f y z a b) (not (hash-table-ref syntaces f))) ; also not any-macro I presume (lint-format "perhaps ~A" caller (lists->string form (append (copy (cdr form) (make-list (- len 2))) (cdr last-arg))))) ;; can't cleanly go from (apply write o p) to (write o (car p)) since p can be () (when (and (not happy) (not (memq f '(define define* define-macro define-macro* define-bacro define-bacro* lambda lambda*))) (any-null? last-arg)) ; (apply f ... ()) -> (f ...) (lint-format "perhaps ~A" caller (lists->string form `(,f ,@(copy (cddr form) (make-list (- len 3))))))))))))))) (if (and (= suggestion made-suggestion) (symbol? (cadr form))) (let ((ary (arg-arity (cadr form) env))) (if (and (pair? ary) ; (apply make-string tcnt initializer) -> (make-string tcnt (car initializer)) (= (cdr ary) (- len 2))) (lint-format "perhaps ~A" caller (lists->string form `(,@(copy (cdr form) (make-list (- len 2))) (car ,(list-ref form (- len 1)))))))))))) (hash-table-set! h 'apply sp-apply)) ;; ---------------- format ---------------- (let () (define (sp-format caller head form env) (if (< (length form) 3) (begin (cond ((< (length form) 2) ; (format) (lint-format "~A has too few arguments: ~A" caller head (truncated-list->string form))) ((and (pair? (cadr form)) ; (format (format #f str)) (eq? (caadr form) 'format)) (lint-format "redundant format: ~A" caller (truncated-list->string form))) ((and (code-constant? (cadr form)) ; (format 1) (not (string? (cadr form)))) (lint-format "format with one argument takes a string: ~A" caller (truncated-list->string form))) ((and (string? (cadr form)) ; (format "str") -> str (eq? head 'format) ; not snd-display (not (char-position #\~ (cadr form)))) (lint-format "perhaps ~A" caller (lists->string form (cadr form))))) env) (let ((control-string ((if (string? (cadr form)) cadr caddr) form)) (args ((if (string? (cadr form)) cddr cdddr) form))) (define count-directives (let ((format-control-char (let ((chars (make-vector 256 #f))) (for-each (lambda (c) (vector-set! chars (char->integer c) #t)) '(#\A #\S #\C #\F #\E #\G #\O #\D #\B #\X #\P #\N #\W #\, #\{ #\} #\* #\@ #\a #\s #\c #\f #\e #\g #\o #\d #\b #\x #\p #\n #\w #\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)) chars))) (lambda (str caller form) (let ((curlys 0) (dirs 0) (pos (char-position #\~ str))) (when pos (do ((len (length str)) (tilde-time #t) (i (+ pos 1) (+ i 1))) ((>= i len) (if tilde-time ; (format #f "asdf~") (lint-format "~A control string ends in tilde: ~A" caller head (truncated-list->string form)))) (let ((c (string-ref str i))) (if tilde-time (begin (when (and (= curlys 0) (not (memv c '(#\~ #\T #\t #\& #\% #\^ #\| #\newline #\}))) ; ~* consumes an arg (not (call-with-exit (lambda (return) (do ((k i (+ k 1))) ((= k len) #f) ;; this can be confused by pad chars in ~T (if (not (or (char-numeric? (string-ref str k)) (char=? (string-ref str k) #\,))) (return (char-ci=? (string-ref str k) #\t)))))))) ;; the possibilities are endless, so I'll stick to the simplest (if (not (vector-ref format-control-char (char->integer c))) ; (format #f "~H" 1) (lint-format "unrecognized format directive: ~C in ~S, ~S" caller c str form)) (set! dirs (+ dirs 1)) ;; ~n so try to figure out how many args are needed (this is not complete) (when (char-ci=? c #\n) (let ((j (+ i 1))) (if (>= j len) ; (format p "~A~A" x) (lint-format "missing format directive: ~S" caller str) (begin ;; if ,n -- add another, if then not T, add another (if (char=? (string-ref str j) #\,) (cond ((>= (+ j 1) len) (lint-format "missing format directive: ~S" caller str)) ((char-ci=? (string-ref str (+ j 1)) #\n) (set! dirs (+ dirs 1)) (set! j (+ j 2))) ((char-numeric? (string-ref str (+ j 1))) (set! j (+ j 2))) (else (set! j (+ j 1))))) (if (>= j len) (lint-format "missing format directive: ~S" caller str) (if (not (char-ci=? (string-ref str j) #\t)) (set! dirs (+ dirs 1))))))))) (set! tilde-time #f) (case c ((#\{) (set! curlys (+ curlys 1))) ((#\}) (set! curlys (- curlys 1))) ((#\^ #\|) (if (zero? curlys) ; (format #f "~^") (lint-format "~A has ~~~C outside ~~{~~}?" caller str c)))) (if (and (< (+ i 2) len) (member (substring str i (+ i 3)) '("%~&" "^~^" "|~|" "&~&" "\n~\n") string=?)) (lint-format "~A in ~A could be ~A" caller ; (format #f "~%~&") (substring str (- i 1) (+ i 3)) str (substring str (- i 1) (+ i 1))))) (begin (set! pos (char-position #\~ str i)) (if pos (begin (set! tilde-time #t) (set! i pos)) (set! i len))))))) (if (not (= curlys 0)) ; (format #f "~{~A" 1) (lint-format "~A has ~D unmatched ~A~A: ~A" caller head (abs curlys) (if (positive? curlys) "{" "}") (if (> curlys 1) "s" "") (truncated-list->string form))) dirs)))) (when (and (eq? head 'format) (string? (cadr form))) ; (format "s") (lint-format "please include the port argument to format, perhaps ~A" caller `(format () ,@(cdr form)))) (if (any? (lambda (arg) (and (string? arg) (or (string-position "ERROR" arg) (string-position "WARNING" arg)))) (cdr form)) (lint-format "There's no need to shout: ~A" caller (truncated-list->string form))) (if (and (eq? (cadr form) 't) ; (format t " ") (not (var-member 't env))) (lint-format "'t in ~A should probably be #t" caller (truncated-list->string form))) (if (not (string? control-string)) (if (not (proper-list? args)) (lint-format "~S looks suspicious" caller form)) (let ((ndirs (count-directives control-string caller form)) (nargs (if (list? args) (length args) 0))) (let ((pos (char-position #\null control-string))) (if (and pos (< pos (length control-string))) ; (format #f "~a\x00b" x) (lint-format "#\\null in a format control string will confuse both lint and format: ~S in ~A" caller control-string form))) (if (not (or (= ndirs nargs) (tree-memq 'values form))) (lint-format "~A has ~A arguments: ~A" ; (format #f "~nT" 1 2) caller head (if (> ndirs nargs) "too few" "too many") (truncated-list->string form)) (if (and (not (cadr form)) ; (format #f "123") (zero? ndirs) (not (char-position #\~ control-string))) (lint-format "~A could be ~S, (format is a no-op here)" caller (truncated-list->string form) (caddr form)))))) (when (pair? args) (for-each (lambda (a) (if (pair? a) (case (car a) ((number->string) (if (null? (cddr a)) ; (format #f "~A" (number->string x)) (lint-format "format arg ~A could be ~A" caller a (cadr a)) (if (and (pair? (cddr a)) (integer? (caddr a)) (memv (caddr a) '(2 8 10 16))) (if (= (caddr a) 10) (lint-format "format arg ~A could be ~A" caller a (cadr a)) (lint-format "format arg ~A could use the format directive ~~~A and change the argument to ~A" caller a (case (caddr a) ((2) "B") ((8) "O") (else "X")) (cadr a)))))) ((symbol->string) ; (format #f "~A" (symbol->string 'x)) (lint-format "format arg ~A could be ~A" caller a (cadr a))) ((make-string) ; (format #f "~A" (make-string len c)) (lint-format "format arg ~A could use the format directive ~~NC and change the argument to ... ~A ~A ..." caller a (cadr a) (if (char? (caddr a)) (format #f "~W" (caddr a)) (caddr a)))) ((string-append) ; (format #f "~A" (string-append x y)) (lint-format "format appends strings, so ~A seems wasteful" caller a))))) args))))) (hash-table-set! h 'format sp-format)) ;; ---------------- error ---------------- (hash-table-set! h 'error (lambda (caller head form env) (if (any? (lambda (arg) (and (string? arg) (or (string-position "ERROR" arg) (string-position "WARNING" arg)))) (cdr form)) (lint-format "There's no need to shout: ~A" caller (truncated-list->string form))))) ;; ---------------- sort! ---------------- (let () (define (sp-sort caller head form env) (if (= (length form) 3) (let ((func (caddr form))) (if (memq func '(= eq? eqv? equal? string=? char=? string-ci=? char-ci=?)) (lint-format "sort! with ~A may hang: ~A" caller func (truncated-list->string form)) (if (symbol? func) (let ((sig (procedure-signature (symbol->value func)))) (if (and (pair? sig) (not (eq? 'boolean? (car sig))) (not (and (pair? (car sig)) (memq 'boolean? (car sig))))) ; (sort! x abs) (lint-format "~A is a questionable sort! function" caller func)))))))) (hash-table-set! h 'sort! sp-sort)) ;; ---------------- substring ---------------- (let () (define (sp-substring caller head form env) (if (every? code-constant? (cdr form)) (catch #t (lambda () (let ((val (eval form))) ; (substring "abracadabra" 2 7) -> "racad" (lint-format "perhaps ~A -> ~S" caller (truncated-list->string form) val))) (lambda (type info) (lint-format "~A -> ~A" caller (truncated-list->string form) (apply format #f info)))) (let ((str (cadr form))) (when (string? str) ; (substring "++++++" 0 2) -> (make-string 2 #\+) (let ((len (length str))) (when (and (> len 0) (string=? str (make-string len (string-ref str 0)))) (lint-format "perhaps ~A" caller (lists->string form (let ((chars (if (null? (cddr form)) len (if (pair? (cdddr form)) (if (eqv? (caddr form) 0) (cadddr form) `(- ,(cadddr form) ,(caddr form))) `(- ,len ,(caddr form)))))) `(make-string ,chars ,(string-ref str 0)))))))) (when (pair? (cddr form)) (when (null? (cdddr form)) (when (and (pair? str) ; (substring (substring x 1) 2) -> (substring x 3) (eq? (car str) 'substring) (null? (cdddr str))) (lint-format "perhaps ~A" caller (lists->string form (if (and (integer? (caddr form)) (integer? (caddr str))) `(substring ,(cadr str) ,(+ (caddr str) (caddr form))) `(substring ,(cadr str) (+ ,(caddr str) ,(caddr form))))))) ;; end indices are complicated -- since this rarely happens, not worth the trouble (if (eqv? (caddr form) 0) ; (substring x 0) -> (copy x) (lint-format "perhaps clearer: ~A" caller (lists->string form `(copy ,str))))) (when (pair? (cdddr form)) (let ((end (cadddr form))) (if (equal? (caddr form) end) ; (substring x (+ y 1) (+ y 1)) is "" (lint-format "leaving aside errors, ~A is \"\"" caller form)) (when (and (pair? str) (eqv? (caddr form) 0) (eq? (car str) 'string-append) (= (length str) 3)) (let ((in-arg2 (caddr str))) (if (and (pair? in-arg2) ; (substring (string-append str (make-string len #\space)) 0 len) -> (copy str (make-string len #\space)) (eq? (car in-arg2) 'make-string) (equal? (cadddr form) (cadr in-arg2))) (lint-format "perhaps ~A" caller (lists->string form `(copy ,(cadr str) (make-string ,(cadddr form) ,(caddr in-arg2)))))))) (if (and (pair? end) ; (substring x start (length|string-length x)) -> (substring s start) (memq (car end) '(string-length length)) (equal? (cadr end) str)) (lint-format "perhaps ~A" caller (lists->string form (copy form (make-list 3)))) (when (symbol? end) (let ((v (var-member end env))) (if (and (var? v) (equal? `(string-length ,str) (var-initial-value v)) (not (any? (lambda (p) (set!? p env)) (var-history v)))) ; if len is still (string-length x), (substring x 1 len) -> (substring x 1) (lint-format "perhaps, if ~A is still ~A, ~A" caller end (var-initial-value v) (lists->string form (copy form (make-list 3)))))))))))))) (hash-table-set! h 'substring sp-substring)) ;; ---------------- list, *vector ---------------- (let ((seq-maker (lambda (seq) (cdr (assq seq '((list . make-list) (vector . make-vector) (float-vector . make-float-vector) (int-vector . make-int-vector) (byte-vector . make-byte-vector)))))) (seq-default (lambda (seq) (cdr (assq seq '((list . #f) (vector . #<unspecified>) (float-vector . 0.0) (int-vector . 0) (byte-vector . 0))))))) (define (sp-list caller head form env) (let ((len (length form)) (val (and (pair? (cdr form)) (cadr form)))) (when (and (> len 2) (every? (lambda (a) (equal? a val)) (cddr form))) (if (code-constant? val) (if (> len 4) ; (vector 12 12 12 12 12 12) -> (make-vector 6 12) (lint-format "perhaps ~A~A" caller (lists->string form (if (eqv? (seq-default head) val) `(,(seq-maker head) ,(- len 1)) `(,(seq-maker head) ,(- len 1) ,val))) (if (and (sequence? val) (not (null? val))) (format #f "~%~NCor wrap (copy ~S) in a function and call that ~A times" lint-left-margin #\space val (- len 1)) ""))) (if (pair? val) (if (or (side-effect? val env) (hash-table-ref makers (car val))) (if (> (tree-leaves val) 2) ;; I think we need to laboriously repeat the function call here: ;; (let ((a 1) (b 2) (c 3)) ;; (define f (let ((ctr 0)) (lambda (x y z) (set! ctr (+ ctr 1)) (+ x y ctr (* 2 z))))) ;; (list (f a b c) (f a b c) (f a b c) (f a b c)) ;; so (apply list (make-list 4 (_1_))) or variants thereof fail ;; (eval (append '(list) (make-list 4 '(_1_)))) ;; works, but it's too ugly. (lint-format "perhaps ~A" caller (lists->string form `(let ((_1_ (lambda () ,val))) (,head ,@(make-list (- len 1) '(_1_))))))) ;; if seq copy else (lint-format "perhaps ~A" caller ; (vector (car x) (car x) (car x) (car x)) -> (make-vector 4 (car x)) (lists->string form `(,(seq-maker head) ,(- len 1) ,val))))))))) (for-each (lambda (f) (hash-table-set! h f sp-list)) '(list vector int-vector float-vector byte-vector))) ;; ---------------- list-tail ---------------- (let () (define (sp-list-tail caller head form env) (if (= (length form) 3) (if (eqv? (caddr form) 0) ; (list-tail x 0) -> x (lint-format "perhaps ~A" caller (lists->string form (cadr form))) (if (and (pair? (cadr form)) (eq? (caadr form) 'list-tail)) (lint-format "perhaps ~A" caller ; (list-tail (list-tail x 1) 2) -> (list-tail x 3) (lists->string form (if (and (integer? (caddr form)) (integer? (caddr (cadr form)))) `(list-tail ,(cadadr form) ,(+ (caddr (cadr form)) (caddr form))) `(list-tail ,(cadadr form) (+ ,(caddr (cadr form)) ,(caddr form)))))))))) (hash-table-set! h 'list-tail sp-list-tail)) ;; ---------------- eq? ---------------- (let () (define (sp-eq? caller head form env) (if (< (length form) 3) ; (eq?) (lint-format "eq? needs 2 arguments: ~A" caller (truncated-list->string form)) (let* ((arg1 (cadr form)) (arg2 (caddr form)) (eq1 (eqf arg1 env)) (eq2 (eqf arg2 env)) (specific-op (and (eq? (cadr eq1) (cadr eq2)) (not (memq (cadr eq1) '(eqv? equal?))) (cadr eq1)))) (eval-constant-expression caller form) (if (or (eq? (car eq1) 'equal?) (eq? (car eq2) 'equal?)) ; (eq? #(0) #(0)) (lint-format "eq? should be equal?~A in ~S" caller (if specific-op (format #f " or ~A" specific-op) "") form) (if (or (eq? (car eq1) 'eqv?) (eq? (car eq2) 'eqv?)) ; (eq? x 1.5) (lint-format "eq? should be eqv?~A in ~S" caller (if specific-op (format #f " or ~A" specific-op) "") form))) (let ((expr 'unset)) (cond ((or (not arg1) ; (eq? #f x) -> (not x) (quoted-not? arg1)) (set! expr (simplify-boolean `(not ,arg2) () () env))) ((or (not arg2) ; (eq? x #f) -> (not x) (quoted-not? arg2)) (set! expr (simplify-boolean `(not ,arg1) () () env))) ((and (any-null? arg1) ; (eq? () x) -> (null? x) (not (code-constant? arg2))) (set! expr (or (equal? arg2 '(list)) ; (eq? () (list)) -> #t `(null? ,arg2)))) ((and (any-null? arg2) ; (eq? x ()) -> (null? x) (not (code-constant? arg1))) (set! expr (or (equal? arg1 '(list)) `(null? ,arg1)))) ((and (eq? arg1 #t) ; (eq? #t <boolean-expr>) -> boolean-expr (pair? arg2) (eq? (return-type (car arg2) env) 'boolean?)) (set! expr arg2)) ((and (eq? arg2 #t) ; (eq? <boolean-expr> #t) -> boolean-expr (pair? arg1) (eq? (return-type (car arg1) env) 'boolean?)) (set! expr arg1))) (if (not (eq? expr 'unset)) ; (eq? x '()) -> (null? x) (lint-format "perhaps ~A" caller (lists->string form expr))))))) (hash-table-set! h 'eq? sp-eq?)) ;; ---------------- eqv? equal? ---------------- (let () (define (sp-eqv? caller head form env) (define (useless-copy? a) (and (pair? a) (memq (car a) '(copy string-copy vector-copy list-copy)) (null? (cddr a)))) (if (< (length form) 3) (lint-format "~A needs 2 arguments: ~A" caller head (truncated-list->string form)) (let* ((arg1 (cadr form)) (arg2 (caddr form)) (eq1 (eqf arg1 env)) (eq2 (eqf arg2 env)) (specific-op (and (eq? (cadr eq1) (cadr eq2)) (not (memq (cadr eq1) '(eq? eqv? equal?))) (cadr eq1)))) (eval-constant-expression caller form) (if (or (useless-copy? arg1) (useless-copy? arg2)) ; (equal? (vector-copy #(a b c)) #(a b c)) -> (equal? #(a b c) #(a b c)) (lint-format "perhaps ~A" caller (lists->string form `(,head ,(if (useless-copy? arg1) (cadr arg1) arg1) ,(if (useless-copy? arg2) (cadr arg2) arg2))))) (if (and (string? (cadr form)) (= (length (cadr form)) 1)) (let ((s2 (caddr form))) (if (pair? s2) (if (eq? (car s2) 'string) ; (equal? "[" (string r)) -> (char=? #\[ r) (lint-format "perhaps ~A" caller (lists->string form `(char=? ,(string-ref (cadr form) 0) ,(cadr s2)))) (if (and (eq? (car s2) 'substring) (= (length s2) 4) ; (equal? "^" (substring s 0 1)) -> (char=? #\^ (string-ref s 0)) (eqv? (list-ref s2 2) 0) (eqv? (list-ref s2 3) 1)) (lint-format "perhaps ~A" caller (lists->string form `(char=? ,(string-ref (cadr form) 0) (string-ref ,(cadr s2) 0))))))))) (if (and (not (eq? (cadr eq1) (cadr eq2))) ; (eqv? ":" (string-ref s 0)) (memq (cadr eq1) '(char=? string=?)) (memq (cadr eq2) '(char=? string=?))) (lint-format "this can't be right: ~A" caller form)) ;; (equal? a (list b)) and equivalents happens a lot, but is the extra consing worse than ;; (and (pair? a) (equal? (car a) b) (null? (cdr a))) -- code readability seems more important here (cond ((or (eq? (car eq1) 'equal?) (eq? (car eq2) 'equal?)) (if (eq? head 'equal?) (if specific-op ; equal? could be string=? in (equal? (string x) (string-append y z)) (lint-format "~A could be ~A in ~S" caller head specific-op form)) (lint-format "~A should be equal?~A in ~S" caller head (if specific-op (format #f " or ~A" specific-op) "") form))) ((or (eq? (car eq1) 'eqv?) (eq? (car eq2) 'eqv?)) (if (eq? head 'eqv?) (if specific-op ; (eqv? (integer->char x) #\null) (lint-format "~A could be ~A in ~S" caller head specific-op form)) (lint-format "~A ~A be eqv?~A in ~S" caller head (if (eq? head 'eq?) "should" "could") (if specific-op (format #f " or ~A" specific-op) "") form))) ((not (or (eq? (car eq1) 'eq?) (eq? (car eq2) 'eq?)))) ((not (and arg1 arg2)) ; (eqv? x #f) -> (not x) (lint-format "~A could be not: ~A" caller head (lists->string form `(not ,(or arg1 arg2))))) ((or (any-null? arg1) (any-null? arg2)) ; (eqv? x ()) -> (null? x) (lint-format "~A could be null?: ~A" caller head (lists->string form (if (any-null? arg1) `(null? ,arg2) `(null? ,arg1))))) (else ; (eqv? x 'a) (lint-format "~A could be eq?~A in ~S" caller head (if specific-op (format #f " or ~A" specific-op) "") form)))))) (hash-table-set! h 'eqv? sp-eqv?) (hash-table-set! h 'equal? sp-eqv?)) ;; ---------------- map for-each ---------------- (let () (define (sp-map caller head form env) (let* ((len (length form)) (args (- len 2))) (if (< len 3) ; (map (lambda (v) (vector-ref v 0))) (lint-format "~A missing argument~A in: ~A" caller head (if (= len 2) "" "s") (truncated-list->string form)) (let ((func (cadr form)) (ary #f)) ;; if zero or one args, the map/for-each is either a no-op or a function call (if (any? any-null? (cddr form)) ; (map abs ()) (lint-format "this ~A has no effect (null arg)" caller (truncated-list->string form)) (if (and (not (tree-memq 'values form)) ; e.g. flatten in s7.html (any? (lambda (p) (and (pair? p) (case (car p) ((quote) (and (pair? (cadr p)) (null? (cdadr p)))) ((list) (null? (cddr p))) ((cons) (any-null? (caddr p))) (else #f)))) (cddr form))) ; (for-each display (list a)) -> (display a) (lint-format "perhaps ~A" caller (lists->string form (let ((args (map (lambda (a) (if (pair? a) (case (car a) ((list cons) (cadr a)) ; slightly inaccurate ((quote) (caadr a)) (else `(,a 0))) ; not car -- might not be a list `(,a 0))) ; but still not right -- arg might be a hash-table (cddr form)))) (if (eq? head 'for-each) `(,(cadr form) ,@args) `(list (,(cadr form) ,@args)))))))) ;; 2 happens a lot, but introduces evaluation order quibbles ;; we used to check for values if list arg -- got 4 hits! (if (and (symbol? func) (procedure? (symbol->value func *e*))) (begin (set! ary (arity (symbol->value func *e*))) (if (and (eq? head 'map) (hash-table-ref no-side-effect-functions func) (= len 3) (pair? (caddr form)) (or (eq? (caaddr form) 'quote) (and (eq? (caaddr form) 'list) (every? code-constant? (cdaddr form))))) (catch #t (lambda () ; (map symbol->string '(a b c d)) -> '("a" "b" "c" "d") (let ((val (eval form))) (lint-format "perhaps ~A" caller (lists->string form (list 'quote val))))) (lambda args #f)))) (when (and (pair? func) (memq (car func) '(lambda lambda*))) (if (pair? (cadr func)) (let ((arglen (length (cadr func)))) (set! ary (if (eq? (car func) 'lambda) (if (negative? arglen) (cons (abs arglen) 512000) (cons arglen arglen)) (cons 0 (if (or (negative? arglen) (memq :rest (cadr func))) 512000 arglen)))))) (if (= len 3) (let ((body (cddr func))) ; (map (lambda (a) #f) x) -> (make-list (abs (length x)) #f) (if (and (null? (cdr body)) (code-constant? (car body))) (lint-format "perhaps ~A" caller (lists->string form `(make-list (abs (length ,(caddr form))) ,(car body))))))))) (if (pair? ary) (if (< args (car ary)) ; (map (lambda (a b) a) '(1 2)) (lint-format "~A has too few arguments in: ~A" caller head (truncated-list->string form)) (if (> args (cdr ary)) ; (map abs '(1 2) '(3 4)) (lint-format "~A has too many arguments in: ~A" caller head (truncated-list->string form))))) (for-each (lambda (obj) (if (and (pair? obj) (memq (car obj) '(vector->list string->list let->list))) (lint-format* caller ; (vector->list #(1 2)) could be simplified to: #(1 2) (truncated-list->string obj) " could be simplified to: " (truncated-list->string (cadr obj)) (string-append " ; (" (symbol->string head) " accepts non-list sequences)")))) (cddr form)) (when (eq? head 'map) (when (and (memq func '(char-downcase char-upcase)) (pair? (caddr form)) ; (map char-downcase (string->list str)) -> (string->list (string-downcase str)) (eq? (caaddr form) 'string->list)) (lint-format "perhaps ~A" caller (lists->string form `(string->list (,(if (eq? func 'char-upcase) 'string-upcase 'string-downcase) ,(cadr (caddr form))))))) (when (identity? func) ; to check f here as var is more work ; (map (lambda (x) x) lst) -> lst (lint-format "perhaps ~A" caller (lists->string form (caddr form))))) (let ((arg1 (caddr form))) (when (and (pair? arg1) (memq (car arg1) '(cdr cddr cdddr cddddr list-tail)) (pair? (cdr arg1)) (pair? (cadr arg1)) (memq (caadr arg1) '(string->list vector->list))) (let ((string-case (eq? (caadr arg1) 'string->list)) (len-diff (if (eq? (car arg1) 'list-tail) (caddr arg1) (cdr-count (car arg1))))) ; (cdr (vector->list v)) -> (make-shared-vector v (- (length v) 1) 1) (lint-format "~A accepts ~A arguments, so perhaps ~A" caller head (if string-case 'string 'vector) (lists->string arg1 (if string-case `(substring ,(cadadr arg1) ,len-diff) `(make-shared-vector ,(cadadr arg1) (- (length ,(cadadr arg1)) ,len-diff) ,len-diff))))))) (when (and (eq? head 'for-each) (pair? (cadr form)) (eq? (caadr form) 'lambda) (pair? (cdadr form)) ; (for-each (lambda (x) (+ (abs x) 1)) lst) (not (any? (lambda (x) (side-effect? x env)) (cddadr form)))) (lint-format "pointless for-each: ~A" caller (truncated-list->string form))) (when (= args 1) (let ((seq (caddr form))) (when (pair? seq) (case (car seq) ((cons) ; (for-each display (cons msgs " ")) (if (and (pair? (cdr seq)) (pair? (cddr seq)) (code-constant? (caddr seq))) (lint-format "~A will ignore ~S in ~A" caller head (caddr seq) seq))) ((map) (when (= (length seq) 3) ;; a toss-up -- probably faster to combine funcs here, and easier to read? ;; but only if first arg is only used once in first func, and everything is simple (one-line or symbol) (let* ((seq-func (cadr seq)) (arg-name (find-unique-name func seq-func))) (if (symbol? func) ; (map f (map g h)) -> (map (lambda (_1_) (f (g _1_))) h) -- dubious (if (symbol? seq-func) (lint-format "perhaps ~A" caller (lists->string form `(,head (lambda (,arg-name) (,func (,seq-func ,arg-name))) ,(caddr seq)))) (if (simple-lambda? seq-func) ;; (map f (map (lambda (x) (g x)) h)) -> (map (lambda (x) (f (g x))) h) (lint-format "perhaps ~A" caller (lists->string form `(,head (lambda (,arg-name) (,func ,(tree-subst arg-name (caadr seq-func) (caddr seq-func)))) ,(caddr seq)))))) (if (less-simple-lambda? func) (if (symbol? seq-func) ;; (map (lambda (x) (f x)) (map g h)) -> (map (lambda (x) (f (g x))) h) (lint-format "perhaps ~A" caller (lists->string form `(,head (lambda (,arg-name) ,@(tree-subst (list seq-func arg-name) (caadr func) (cddr func))) ,(caddr seq)))) (if (simple-lambda? seq-func) ;; (map (lambda (x) (f x)) (map (lambda (x) (g x)) h)) -> (map (lambda (x) (f (g x))) h) (lint-format "perhaps ~A" caller (lists->string form `(,head (lambda (,arg-name) ,@(tree-subst (tree-subst arg-name (caadr seq-func) (caddr seq-func)) (caadr func) (cddr func))) ,(caddr seq))))))))))))) ;; repetitive code... (when (eq? head 'for-each) ; args = 1 above ; (for-each display (list a)) -> (format () "~A" a) (let ((func (cadr form))) (if (memq func '(display write newline write-char write-string)) (lint-format "perhaps ~A" caller (if (and (pair? seq) (memq (car seq) '(list quote))) (let ((op (if (eq? func 'write) "~S" "~A")) (len (- (length seq) 1))) (lists->string form `(format () ,(do ((i 0 (+ i 1)) (str "")) ((= i len) str) (set! str (string-append str op))) ,@(cdr seq)))) (let ((op (if (eq? func 'write) "~{~S~}" "~{~A~}"))) (lists->string form `(format () ,op ,seq))))) (when (and (pair? func) (eq? (car func) 'lambda)) (let ((body (cddr func))) (let ((op (write-port (car body))) (larg (and (pair? (cadr func)) (caadr func)))) (when (and (symbol? larg) (null? (cdadr func)) ; just one arg (one sequence to for-each) for now (every? (lambda (x) (and (pair? x) (memq (car x) '(display write newline write-char write-string)) (or (eq? (car x) 'newline) (eq? (cadr x) larg) (string? (cadr x)) (eqv? (cadr x) #\space) (and (pair? (cadr x)) (pair? (cdadr x)) (eq? (caadr x) 'number->string) (eq? (cadadr x) larg))) (eq? (write-port x) op))) body)) ;; (for-each (lambda (x) (display x) (write-char #\space)) msg) ;; (for-each (lambda (elt) (display elt)) lst) (let ((ctrl-string "") (arg-ctr 0)) (define* (gather-format str (arg :unset)) (set! ctrl-string (string-append ctrl-string str))) (for-each (lambda (d) (if (or (memq larg d) (and (pair? (cdr d)) (pair? (cadr d)) (memq larg (cadr d)))) (set! arg-ctr (+ arg-ctr 1))) (gather-format (display->format d))) body) (when (= arg-ctr 1) ; (for-each (lambda (x) (display x)) args) -> (format () "~{~A~}" args) (lint-format "perhaps ~A" caller (lists->string form `(format ,op ,(string-append "~{" ctrl-string "~}") ,seq))))))))) ))))))))) (for-each (lambda (f) (hash-table-set! h f sp-map)) '(map for-each))) ;; ---------------- magnitude ---------------- (hash-table-set! h 'magnitude (lambda (caller head form env) (if (and (= (length form) 2) ; (magnitude 2/3) (memq (->lint-type (cadr form)) '(integer? rational? real?))) (lint-format "perhaps use abs here: ~A" caller form)))) ;; (hash-table-set! h 'modulo (lambda (caller head form env) (format *stderr* "~A~%" form))) ;; (modulo (- 512 (modulo offset 512)) 512) ;; (modulo (char->integer (string-ref seed j)) 255) ;; ---------------- open-input-file open-output-file ---------------- (let () (define (sp-open-input-file caller head form env) (if (and (pair? (cdr form)) (pair? (cddr form)) (string? (caddr form)) ; (open-output-file x "fb+") (not (memv (string-ref (caddr form) 0) '(#\r #\w #\a)))) ; b + then e m c x if gcc (lint-format "unexpected mode: ~A" caller form))) (for-each (lambda (f) (hash-table-set! h f sp-open-input-file)) '(open-input-file open-output-file))) ;; ---------------- values ---------------- (let () (define (sp-values caller head form env) (cond ((member 'values (cdr form) (lambda (a b) (and (pair? b) ; (values 2 (values 3 4) 5) -> (values 2 3 4 5) (eq? (car b) 'values)))) (lint-format "perhaps ~A" caller (lists->string form `(values ,@(splice-if (lambda (x) (eq? x 'values)) (cdr form)))))) ((= (length form) 2) (lint-format "perhaps ~A" caller (lists->string form ; (values ({list} 'x ({apply_values} y))) -> (cons 'x y) (if (and (pair? (cadr form)) (eq? (caadr form) #_{list}) (not (qq-tree? (cadr form)))) (un_{list} (cadr form)) (cadr form))))) ((and (assq #_{list} (cdr form)) (not (any? (lambda (a) (and (pair? a) (memq (car a) '(#_{list} #_{apply_values})) (qq-tree? a))) (cdr form)))) (lint-format "perhaps ~A" caller (lists->string form ; (values ({list} 'x y) a) -> (values (list 'x y) a) `(values ,@(map (lambda (a) (if (and (pair? a) (eq? (car a) #_{list})) (un_{list} a) a)) (cdr form)))))))) (hash-table-set! h 'values sp-values)) ;; ---------------- call-with-values ---------------- (let () (define (sp-call/values caller head form env) ; (call/values p c) -> (c (p)) (when (= (length form) 3) (let ((producer (cadr form)) (consumer (caddr form))) (let* ((produced-values (mv-range producer env)) (consumed-values (and produced-values (or (and (symbol? consumer) (arg-arity consumer env)) (and (pair? consumer) (eq? (car consumer) 'lambda) (pair? (cadr consumer)) (let ((len (length (cadr consumer)))) (if (negative? len) (cons (abs len) (cdr (arity +))) ; 536870912 = MAX_ARITY in s7.c (cons len len)))))))) (if (and consumed-values (or (> (car consumed-values) (car produced-values)) (< (cdr consumed-values) (cadr produced-values)))) (let ((clen ((if (> (car consumed-values) (car produced-values)) car cdr) consumed-values))) (lint-format "call-with-values consumer ~A wants ~D value~P, but producer ~A returns ~A" caller (truncated-list->string consumer) clen clen (truncated-list->string producer) ((if (> (car consumed-values) (car produced-values)) car cadr) produced-values))))) (cond ((not (pair? producer)) ; (call-with-values log c) (if (and (symbol? producer) (not (memq (return-type producer ()) '(#t #f values)))) (lint-format "~A does not return multiple values" caller producer) (lint-format "perhaps ~A" caller (lists->string form `(,consumer (,producer)))))) ((not (eq? (car producer) 'lambda)) ; (call-with-values (eval p env) (eval c env)) -> ((eval c env) ((eval p env))) (lint-format "perhaps ~A" caller (lists->string form `(,consumer (,producer))))) ((pair? (cadr producer)) ; (call-with-values (lambda (x) 0) list) (lint-format "~A requires too many arguments" caller (truncated-list->string producer))) ((symbol? (cadr producer)) ; (call-with-values (lambda x 0) list) (lint-format "~A's parameter ~A will always be ()" caller (truncated-list->string producer) (cadr producer))) ((and (pair? (cddr producer)) ; (call-with-values (lambda () (read-char p)) cons) (null? (cdddr producer))) ; (call-with-values (lambda () (values 1 2 3)) list) -> (list 1 2 3) (let ((body (caddr producer))) (if (or (code-constant? body) (and (pair? body) (symbol? (car body)) (not (memq (return-type (car body) ()) '(#t #f values))))) (lint-format "~A does not return multiple values" caller body) (lint-format "perhaps ~A" caller (lists->string form (if (and (pair? body) (eq? (car body) 'values)) `(,consumer ,@(cdr body)) `(,consumer ,body))))))) (else (lint-format "perhaps ~A" caller (lists->string form `(,consumer (,producer))))))))) (hash-table-set! h 'call-with-values sp-call/values)) ;; ---------------- multiple-value-bind ---------------- (let () (define (sp-mvb caller head form env) (when (>= (length form) 4) (let ((vars (cadr form)) (producer (caddr form)) (body (cdddr form))) (if (null? vars) (lint-format "this multiple-value-bind is pointless; perhaps ~A" caller (lists->string form (if (side-effect? producer env) `(begin ,producer ,@body) (if (null? (cdr body)) (car body) `(begin ,@body))))) (unless (symbol? vars) ; else any number of values is ok (let ((vals (mv-range producer env)) ; (multiple-value-bind (a b) (values 1 2 3) b) (args (length vars))) (if (and (pair? vals) (not (<= (car vals) args (cadr vals)))) (lint-format "multiple-value-bind wants ~D values, but ~A returns ~A" caller args (truncated-list->string producer) ((if (< args (car vals)) car cadr) vals))) (if (and (pair? producer) ; (multiple-value-bind (a b) (f) b) -> ((lambda (a b) b) (f)) (symbol? (car producer)) (not (memq (return-type (car producer) ()) '(#t #f values)))) (lint-format "~A does not return multiple values" caller (car producer)) (lint-format "perhaps ~A" caller (lists->string form (if (and (null? (cdr body)) (pair? (car body)) (equal? vars (cdar body)) (defined? (caar body)) (equal? (arity (symbol->value (caar body))) (cons args args))) `(,(caar body) ,producer) `((lambda ,vars ,@body) ,producer))))))))))) (hash-table-set! h 'multiple-value-bind sp-mvb)) ;; ---------------- let-values ---------------- (let () (define (sp-let-values caller head form env) (if (and (pair? (cdr form)) (pair? (cadr form))) (if (null? (cdadr form)) ; just one set of vars (let ((call (caadr form))) (if (and (pair? call) (pair? (cdr call))) (lint-format "perhaps ~A" caller ; (let-values (((x) (values 1))) x) -> ((lambda (x) x) (values 1)) (lists->string form `((lambda ,(car call) ,@(cddr form)) ,(cadr call)))))) (if (every? pair? (cadr form)) (lint-format "perhaps ~A" caller ; (let-values (((x) (values 1)) ((y) (values 2))) (list x y)) ... (lists->string form `(with-let (apply sublet (curlet) (list ,@(map (lambda (v) `((lambda ,(car v) (values ,@(map (lambda (name) (values (symbol->keyword name) name)) (args->proper-list (car v))))) ,(cadr v))) (cadr form)))) ,@(cddr form)))))))) (hash-table-set! h 'let-values sp-let-values)) ;; ---------------- let*-values ---------------- (hash-table-set! h 'let*-values (lambda (caller head form env) (if (and (pair? (cdr form)) (pair? (cadr form))) (lint-format "perhaps ~A" caller (lists->string form ; (let*-values (((a) (f x))) (+ a b)) -> (let ((a (f x))) (+ a b)) (let loop ((var-data (cadr form))) (let ((v (car var-data))) (if (and (pair? (car v)) ; just one var (null? (cdar v))) (if (null? (cdr var-data)) `(let ((,(caar v) ,(cadr v))) ,@(cddr form)) `(let ((,(caar v) ,(cadr v))) ,(loop (cdr var-data)))) (if (null? (cdr var-data)) `((lambda ,(car v) ,@(cddr form)) ,(cadr v)) `((lambda ,(car v) ,(loop (cdr var-data))) ,(cadr v))))))))))) ;; ---------------- define-values ---------------- (hash-table-set! h 'define-values (lambda (caller head form env) (when (pair? (cdr form)) (if (null? (cadr form)) (lint-format "~A is pointless" caller (truncated-list->string form)) (when (pair? (cddr form)) (lint-format "perhaps ~A" caller ; (define-values (x y) (values 3 2)) -> (varlet (curlet) ((lambda (x y) (curlet)) (values 3 2))) (cond ((symbol? (cadr form)) (lists->string form `(define ,(cadr form) (list ,(caddr form))))) ((and (pair? (cadr form)) (null? (cdadr form))) (lists->string form `(define ,(caadr form) ,(caddr form)))) (else (let-temporarily ((target-line-length 120)) (truncated-lists->string form `(varlet (curlet) ((lambda ,(cadr form) (curlet)) ,(caddr form))))))))))))) ;; ---------------- eval ---------------- (let () (define (sp-eval caller head form env) (case (length form) ((2) (let ((arg (cadr form))) (if (not (pair? arg)) (if (not (symbol? arg)) ; (eval 32) (lint-format "this eval is pointless; perhaps ~A" caller (lists->string form arg))) (case (car arg) ((quote) ; (eval 'x) (lint-format "perhaps ~A" caller (lists->string form (cadr arg)))) ((string->symbol) ; (eval (string->symbol "x")) -> x (if (string? (cadr arg)) (lint-format "perhaps ~A" caller (lists->string form (string->symbol (cadr arg)))))) ((with-input-from-string call-with-input-string) (if (and (pair? (cdr arg)) ; (eval (call-with-input-string port read)) -> (eval-string port) (pair? (cddr arg)) (eq? (caddr arg) 'read)) (lint-format "perhaps ~A" caller (lists->string form `(eval-string ,(cadr arg)))))) ((read) (if (and (= (length arg) 2) ; (eval (read (open-input-string expr))) -> (eval-string expr) (pair? (cadr arg)) (eq? (caadr arg) 'open-input-string)) (lint-format "perhaps ~A" caller (lists->string form `(eval-string ,(cadadr arg)))))) ((list) (if (every? (lambda (p) ; (eval (list '* 2 x)) -> (* 2 (eval x)) (or (symbol? p) (code-constant? p))) (cdr arg)) (lint-format "perhaps ~A" caller (lists->string form (map (lambda (p) (if (and (pair? p) (eq? (car p) 'quote)) (cadr p) (if (code-constant? p) p (list 'eval p)))) (cdr arg)))))))))) ((3) (let ((arg (cadr form)) (e (caddr form))) (if (and (pair? arg) (eq? (car arg) 'quote)) (lint-format "perhaps ~A" caller ; (eval 'x env) -> (env 'x) (lists->string form (if (symbol? (cadr arg)) `(,e ,arg) `(with-let ,e ,@(unbegin (cadr arg))))))))))) (hash-table-set! h 'eval sp-eval)) ;; ---------------- fill! etc ---------------- (let () (define (sp-fill! caller head form env) (if (= (length form) 5) (check-start-and-end caller head (cdddr form) form env))) (for-each (lambda (f) (hash-table-set! h f sp-fill!)) '(fill! string-fill! list-fill! vector-fill!))) ;; ---------------- write-string ---------------- (hash-table-set! h 'write-string (lambda (caller head form env) (if (= (length form) 4) (check-start-and-end caller 'write-string (cddr form) form env)))) ;; ---------------- read-line ---------------- (hash-table-set! h 'read-line (lambda (caller head form env) (if (and (= (length form) 3) (code-constant? (caddr form)) (not (boolean? (caddr form)))) ; (read-line in-port 'concat) (lint-format "the third argument should be boolean (#f=default, #t=include trailing newline): ~A" caller form)))) ;; ---------------- string-length ---------------- (let () (define (sp-string-length caller head form env) (when (= (length form) 2) (if (string? (cadr form)) ; (string-length "asdf") -> 4 (lint-format "perhaps ~A -> ~A" caller (truncated-list->string form) (string-length (cadr form))) (if (and (pair? (cadr form)) ; (string-length (make-string 3)) -> 3 (eq? (caadr form) 'make-string)) (lint-format "perhaps ~A" caller (lists->string form (cadadr form))))))) (hash-table-set! h 'string-length sp-string-length)) ;; ---------------- vector-length ---------------- (let () (define (sp-vector-length caller head form env) (when (= (length form) 2) (if (vector? (cadr form)) (lint-format "perhaps ~A -> ~A" caller (truncated-list->string form) (vector-length (cadr form))) (let ((arg (cadr form))) (if (pair? arg) (if (eq? (car arg) 'make-vector) ; (vector-length (make-vector 10)) -> 10 (lint-format "perhaps ~A" caller (lists->string form (cadr arg))) (if (memq (car arg) '(copy vector-copy)) (lint-format "perhaps ~A" caller (lists->string form ; (vector-length (vector-copy arr start end)) -> (- end start) (if (null? (cddr arg)) `(vector-length ,(cadr arg)) (if (eq? (car arg) 'copy) `(vector-length ,(caddr arg)) (let ((start (caddr arg)) (end (if (null? (cdddr arg)) `(vector-length ,(cadr arg)) (cadddr arg)))) `(- ,end ,start))))))))))))) (hash-table-set! h 'vector-length sp-vector-length)) ;; ---------------- dynamic-wind ---------------- (let () (define (sp-dw caller head form env) (when (= (length form) 4) (let ((init (cadr form)) (body (caddr form)) (end (cadddr form)) (empty 0)) ;; (equal? init end) as a mistake doesn't seem to happen (when (and (pair? init) (eq? (car init) 'lambda)) (if (not (null? (cadr init))) (lint-format "dynamic-wind init function should be a thunk: ~A" caller init)) (if (pair? (cddr init)) (let ((last-expr (list-ref init (- (length init) 1)))) (if (not (pair? last-expr)) (if (null? (cdddr init)) (set! empty 1)) (unless (side-effect? last-expr env) (if (null? (cdddr init)) (set! empty 1)) ; (dynamic-wind (lambda () (s7-version)) (lambda () (list)) (lambda () #f)) (lint-format "this could be omitted: ~A in ~A" caller last-expr init)))))) (if (and (pair? body) (eq? (car body) 'lambda)) (if (not (null? (cadr body))) (lint-format "dynamic-wind body function should be a thunk: ~A" caller body)) (set! empty 3)) ; don't try to access body below (when (and (pair? end) (eq? (car end) 'lambda)) (if (not (null? (cadr end))) (lint-format "dynamic-wind end function should be a thunk: ~A" caller end)) (if (pair? (cddr end)) (let ((last-expr (list-ref end (- (length end) 1)))) (if (not (pair? last-expr)) (if (null? (cdddr end)) (set! empty (+ empty 1))) (unless (side-effect? last-expr env) ; or if no side-effects in any (also in init) (if (null? (cdddr end)) (set! empty (+ empty 1))) (lint-format "this could be omitted: ~A in ~A" caller last-expr end))) (if (= empty 2) ; (dynamic-wind (lambda () #f) (lambda () #()) (lambda () #f)) -> #() (lint-format "this dynamic-wind is pointless, ~A" caller (lists->string form (if (null? (cdddr body)) (caddr body) `(begin ,@(cddr body)))))))))))) (hash-table-set! h 'dynamic-wind sp-dw)) ;; ---------------- *s7* ---------------- (hash-table-set! h '*s7* (let ((s7-fields (let ((h (make-hash-table))) (for-each (lambda (f) (hash-table-set! h f #t)) '(print-length safety cpu-time heap-size free-heap-size gc-freed max-string-length max-list-length max-vector-length max-vector-dimensions default-hash-table-length initial-string-port-length gc-protected-objects file-names rootlet-size c-types stack-top stack-size stacktrace-defaults max-stack-size stack catches exits float-format-precision bignum-precision default-rationalize-error default-random-state morally-equal-float-epsilon hash-table-float-epsilon undefined-identifier-warnings gc-stats symbol-table-locked? c-objects history-size profile-info)) h))) (lambda (caller head form env) (if (= (length form) 2) (let ((arg (cadr form))) (if (and (pair? arg) (eq? (car arg) 'quote) (symbol? (cadr arg)) ; (*s7* 'vector-print-length) (not (hash-table-ref s7-fields (cadr arg)))) (lint-format "unknown *s7* field: ~A" caller arg))))))) ;; ---------------- throw ---------------- (hash-table-set! h 'throw (lambda (caller head form env) (if (pair? (cdr form)) (let* ((tag (cadr form)) (eq (eqf tag env))) (if (not (member eq '((eq? eq?) (#t #t)))) (lint-format "~A tag ~S is unreliable (catch uses eq? to match tags)" caller 'throw tag)))))) ;; ---------------- make-hash-table ---------------- (hash-table-set! h 'make-hash-table (lambda (caller head form env) (if (= (length form) 3) (let ((func (caddr form))) (if (and (symbol? func) ; (make-hash-table eq? symbol-hash) (not (memq func '(eq? eqv? equal? morally-equal? char=? char-ci=? string=? string-ci=? =)))) (lint-format "make-hash-table function, ~A, is not a hash function" caller func)))))) ;; ---------------- deprecated funcs ---------------- (let ((deprecated-ops '((global-environment . rootlet) (current-environment . curlet) (make-procedure-with-setter . dilambda) (procedure-with-setter? . dilambda?) (make-random-state . random-state)))) (define (sp-deprecate caller head form env) ; (make-random-state 123 432) (lint-format "~A is deprecated; use ~A" caller head (cond ((assq head deprecated-ops) => cdr)))) (for-each (lambda (op) (hash-table-set! h (car op) sp-deprecate)) deprecated-ops)) ;; ---------------- eq null eqv equal ---------------- (let () (define (sp-null caller head form env) (if (not (var-member head env)) ; (if (null (cdr x)) 0) (lint-format "misspelled '~A? in ~A?" caller head form))) (for-each (lambda (f) (hash-table-set! h f sp-null)) '(null eq eqv equal))) ; (null (cdr...)) ;; ---------------- string-index ---------------- (let () (define (sp-string-index caller head form env) (if (and (pair? (cdr form)) (pair? (cddr form)) (not (var-member 'string-index env)) (or (char? (caddr form)) (let ((sig (arg-signature (caddr form) env))) (and (pair? sig) (eq? (car sig) 'char?))))) (lint-format "perhaps ~A" caller ; (string-index path #\/) -> (char-position #\/ path) (lists->string form `(char-position ,(caddr form) ,(cadr form) ,@(cdddr form)))))) (hash-table-set! h 'string-index sp-string-index)) ;; ---------------- cons* ---------------- (let () (define (sp-cons* caller head form env) (unless (var-member 'cons env) (case (length form) ((2) (lint-format "perhaps ~A" caller (lists->string form (cadr form)))) ((3) (lint-format "perhaps ~A" caller (lists->string form ; cons* x y) -> (cons x y) (if (any-null? (caddr form)) `(list ,(cadr form)) `(cons ,@(cdr form)))))) ((4) (lint-format "perhaps ~A" caller (lists->string form ; (cons* (symbol->string v) " | " (w)) -> (cons (symbol->string v) (cons " | " (w))) (if (any-null? (cadddr form)) `(list ,(cadr form) ,(caddr form)) `(cons ,(cadr form) (cons ,@(cddr form)))))))))) (hash-table-set! h 'cons* sp-cons*)) ;; ---------------- the-environment etc ---------------- (let ((other-names '((the-environment . curlet) (interaction-environment . curlet) (system-global-environment . rootlet) (user-global-environment . rootlet) (user-initial-environment . rootlet) (procedure-environment . funclet) (environment? . let?) (environment-set! . let-set!) (environment-ref . let-ref) (fluid-let . let-temporarily) (unquote-splicing apply values ...) (bitwise-and . logand) (bitwise-ior . logior) (bitwise-xor . logxor) (bitwise-not . lognot) (bit-and . logand) (bit-or . logior) (bit-xor . logxor) (bit-not . lognot) (arithmetic-shift . ash) (vector-for-each . for-each) (string-for-each . for-each) (list-copy . copy) (bytevector? . byte-vector?) (bytevector . byte-vector) (make-bytevector . make-byte-vector) (bytevector-u8-ref . byte-vector-ref) (bytevector-u8-set! . byte-vector-set!) (bytevector-length . length) (write-bytevector . write-string) (hash-set! . hash-table-set!) ; Guile (hash-ref . hash-table-ref) (hashq-set! . hash-table-set!) (hashq-ref . hash-table-ref) (hashv-set! . hash-table-set!) (hashv-ref . hash-table-ref) (hash-table-get . hash-table-ref) ; Gauche (hash-table-put! . hash-table-set!) (hash-table-num-entries . hash-table-entries) (hashtable? . hash-table?) ; Bigloo (hashtable-size . hash-table-entries) (hashtable-get . hash-table-ref) (hashtable-put! . hash-table-set!) (hash-for-each . for-each) (exact-integer? . integer?) (truncate-quotient . quotient) (truncate-remainder . remainder) (floor-remainder . modulo) (read-u8 . read-byte) (write-u8 . write-byte) (write-simple . write) (peek-u8 . peek-char) (u8-ready? . char-ready?) (open-input-bytevector . open-input-string) (open-output-bytevector . open-output-string) (raise . error) (raise-continuable . error)))) (define (sp-other-names caller head form env) (if (not (var-member head env)) (let ((counts (or (hash-table-ref other-names-counts head) 0))) (when (< counts 2) (hash-table-set! other-names-counts head (+ counts 1)) (lint-format "~A is probably ~A in s7" caller head (cdr (assq head other-names))))))) (for-each (lambda (f) (hash-table-set! h (car f) sp-other-names)) other-names)) (hash-table-set! h '1+ (lambda (caller head form env) (if (not (var-member '1+ env)) (lint-format "perhaps ~A" caller (lists->string form `(+ ,(cadr form) 1)))))) (let () (define (sp-1- caller head form env) (if (not (var-member '-1+ env)) (lint-format "perhaps ~A" caller (lists->string form `(- ,(cadr form) 1))))) (hash-table-set! h '-1+ sp-1-) (hash-table-set! h '1- sp-1-)) ;; ---------------- push! pop! ---------------- (hash-table-set! h 'push! (lambda (caller head form env) ; not predefined (if (= (length form) 3) (set-set (caddr form) caller form env)))) (hash-table-set! h 'pop! (lambda (caller head form env) ; also not predefined (if (= (length form) 2) (set-set (cadr form) caller form env)))) ;; ---------------- receive ---------------- (hash-table-set! h 'receive (lambda (caller head form env) ; this definition comes from Guile (if (and (> (length form) 3) (not (var-member 'receive env))) ((hash-table-ref h 'call-with-values) caller 'call-with-values `(call-with-values (lambda () ,(caddr form)) (lambda ,(cadr form) ,@(cdddr form))) env)))) ;; ---------------- and=> ---------------- (hash-table-set! h 'and=> (lambda (caller head form env) ; (and=> (ref w k) v) -> (cond ((ref w k) => v) (else #f)) (when (and (= (length form) 3) (not (var-member 'and=> env))) (lint-format "perhaps ~A" caller (lists->string form `(cond (,(cadr form) => ,(caddr form)) (else #f))))))) ;; ---------------- and-let* ---------------- (hash-table-set! h 'and-let* (lambda (caller head form env) (when (and (> (length form) 2) (not (var-member 'and-let* env))) (let loop ((bindings (cadr form))) (cond ((pair? bindings) (if (binding-ok? caller 'and-let* (car bindings) env #f) (loop (cdr bindings)))) ((not (null? bindings)) (lint-format "~A variable list is not a proper list? ~S" caller 'and-let* bindings)) ((and (pair? (cadr form)) ; (and-let* ((x (f y))) (abs x)) -> (cond ((f y) => abs)) (null? (cdadr form)) (pair? (cddr form))) (lint-format "perhaps ~A" caller (lists->string form ; (and-let* ((x (f y))) (abs x)) -> (cond ((f y) => abs)) (if (and (null? (cdddr form)) (pair? (caddr form)) (pair? (cdaddr form)) (null? (cddr (caddr form))) (eq? (caaadr form) (cadr (caddr form)))) `(cond (,(cadar (cadr form)) => ,(caaddr form))) `(cond (,(cadar (cadr form)) => (lambda (,(caaadr form)) ,@(cddr form))))))))))))) h)) ;; end special-case-functions ;; ---------------------------------------- (define (unused-parameter? x) #t) (define (unused-set-parameter? x) #t) (define (check-args caller head form checkers env max-arity) ;; check for obvious argument type problems ;; caller = overall caller, head = current caller, checkers = proc or list of procs for checking args (define (every-compatible? type1 type2) (if (symbol? type1) (if (symbol? type2) (compatible? type1 type2) (and (pair? type2) ; here everything has to match (compatible? type1 (car type2)) (every-compatible? type1 (cdr type2)))) (and (pair? type1) ; here any match is good (or (compatible? (car type1) type2) (any-compatible? (cdr type1) type2))))) (define (check-checker checker at-end) (if (eq? checker 'integer:real?) (if at-end 'real? 'integer?) (if (eq? checker 'integer:any?) (or at-end 'integer?) checker))) (define (any-checker? types arg) (if (and (symbol? types) (not (eq? types 'values))) ((symbol->value types *e*) arg) (and (pair? types) (or (any-checker? (car types) arg) (any-checker? (cdr types) arg))))) (define (report-arg-trouble caller form head arg-number checker arg uop) (define (prettify-arg-number argn) (if (or (not (= argn 1)) (pair? (cddr form))) (format #f "~D " argn) "")) (let ((op (if (and (eq? checker 'real?) (eq? uop 'number?)) 'complex? uop))) (if (and (or arg (not (eq? checker 'output-port?))) (not (and (eq? checker 'string?) (pair? arg) (eq? (car arg) 'format))) ; don't try to untangle the format non-string case (not (and (pair? arg) (eq? (car arg) 'length)))) ; same for length (if (and (pair? op) (member checker op any-compatible?)) (if (and *report-sloppy-assoc* (not (var-member :catch env))) (lint-format* caller ; (round (char-position #\a "asb")) (string-append "in " (truncated-list->string form) ", ") (string-append (symbol->string head) "'s argument " (prettify-arg-number arg-number)) (string-append "should be " (prettify-checker-unq checker) ", ") (string-append "but " (truncated-list->string arg) " might also be " (object->string (car (remove-if (lambda (o) (any-compatible? checker o)) op)))))) (lint-format* caller ; (string-ref (char-position #\a "asb") 1) (string-append "in " (truncated-list->string form) ", ") (string-append (symbol->string head) "'s argument " (prettify-arg-number arg-number)) (string-append "should be " (prettify-checker-unq checker) ", ") (string-append "but " (truncated-list->string arg) " is " (prettify-checker op))))))) (when *report-func-as-arg-arity-mismatch* (let ((v (var-member head env))) (when (and (var? v) (memq (var-ftype v) '(define define* lambda lambda*)) (zero? (var-set v)) ; perhaps this needs to wait for report-usage? (pair? (var-arglist v))) (let ((source (var-initial-value v))) (when (and (pair? source) (pair? (cdr source)) (pair? (cddr source))) (let ((vhead (cddr source)) (head-arglist (var-arglist v)) (arg-number 1)) (when (pair? vhead) (for-each (lambda (arg) ;; only check func if head is var-member and has procedure-source (var-[initial-]value?) ;; and arg has known arity, and check only if arg(par) is car, not (for example) cadr of apply (let ((ari (if (symbol? arg) (arg-arity arg env) (and (pair? arg) (eq? (car arg) 'lambda) (let ((len (length (cadr arg)))) (and (integer? len) (cons (abs len) (if (negative? len) 500000 len))))))) (par (and (> (length head-arglist) (- arg-number 1)) (list-ref head-arglist (- arg-number 1))))) (when (and (symbol? par) (pair? ari) (or (> (car ari) 0) (< (cdr ari) 20))) ;; fwalk below needs to be smart about tree walking so that ;; it does not confuse (c) in (lambda (c)...) with a call on the function c. ;; check only if current parameter name is not shadowed (let fwalk ((sym par) (tree vhead)) (when (pair? tree) (if (eq? (car tree) sym) (let ((args (- (length tree) 1))) (if (> (car ari) args) (lint-format "~A's parameter ~A is passed ~A and called ~A, but ~A needs ~A argument~P" caller head par (truncated-list->string arg) (truncated-list->string tree) (truncated-list->string arg) (car ari) (car ari)) (if (> args (cdr ari)) (lint-format "~A's parameter ~A is passed ~A and called ~A, but ~A takes only ~A argument~P" caller head par (truncated-list->string arg) (truncated-list->string tree) (truncated-list->string arg) (cdr ari) (cdr ari))))) (case (car tree) ((let let*) (if (and (pair? (cdr tree)) (pair? (cddr tree))) (let ((vs ((if (symbol? (cadr tree)) caddr cadr) tree))) (if (not (any? (lambda (a) (or (not (pair? a)) (eq? sym (car a)))) vs)) (fwalk sym ((if (symbol? (cadr tree)) cdddr cddr) tree)))))) ((do letrec letrec*) (if (and (pair? (cdr tree)) (pair? (cddr tree)) (not (any? (lambda (a) (or (not (pair? a)) (eq? sym (car a)))) (cadr tree)))) (fwalk sym (cddr tree)))) ((lambda lambda*) (if (and (pair? (cdr tree)) (pair? (cddr tree)) (not (any? (lambda (a) (eq? sym a)) (args->proper-list (cadr tree))))) (fwalk sym (cddr tree)))) ((define define-constant) (if (and (not (eq? sym (cadr tree))) (pair? (cadr tree)) (not (any? (lambda (a) (eq? sym a)) (args->proper-list (cdadr tree))))) (fwalk sym (cddr tree)))) ((define* define-macro define-macro* define-expansion define-bacro define-bacro*) (if (and (pair? (cdr tree)) (pair? (cddr tree)) (not (any? (lambda (a) (eq? sym a)) (args->proper-list (cdadr tree))))) (fwalk sym (cddr tree)))) ((quote) #f) ((case) (if (and (pair? (cdr tree)) (pair? (cddr tree))) (for-each (lambda (c) (fwalk sym (cdr c))) (cddr tree)))) (else (if (pair? (car tree)) (fwalk sym (car tree))) (if (pair? (cdr tree)) (for-each (lambda (p) (fwalk sym p)) (cdr tree)))))))))) (set! arg-number (+ arg-number 1))) (cdr form))))))))) (when (pair? checkers) (let ((arg-number 1) (flen (- (length form) 1))) (call-with-exit (lambda (done) (for-each (lambda (arg) (let ((checker (check-checker (if (pair? checkers) (car checkers) checkers) (= arg-number flen)))) ;; check-checker only fixes up :at-end cases (define (check-arg expr) (unless (symbol? expr) (let ((op (->lint-type expr))) (if (not (or (memq op '(#f #t values)) (every-compatible? checker op))) (report-arg-trouble caller form head arg-number checker expr op))))) (define (check-cond-arg expr) (unless (symbol? expr) (let ((op (->lint-type expr))) (when (pair? op) (set! op (remove 'boolean? op)) ; this is for cond test, no result -- returns test if not #f, so it can't be #f! (if (null? (cdr op)) (set! op (car op)))) (if (not (or (memq op '(#f #t values)) (every-compatible? checker op))) (report-arg-trouble caller form head arg-number checker expr op))))) ;; special case checker? (if (and (symbol? checker) (not (memq checker '(unused-parameter? unused-set-parameter?))) (not (hash-table-ref built-in-functions checker))) (let ((chk (symbol->value checker))) (if (and (procedure? chk) (equal? (arity chk) '(2 . 2))) (catch #t (lambda () (let ((res (chk form arg-number))) (set! checker #t) (if (symbol? res) (set! checker res) (if (string? res) (lint-format "~A's argument, ~A, should be ~A" caller head arg res))))) (lambda (type info) (set! checker #t)))))) (if (and (pair? arg) (pair? (car arg))) (let ((rtn (return-type (caar arg) env))) (if (memq rtn '(boolean? real? integer? rational? number? complex? float? keyword? symbol? null? char?)) (lint-format* caller ; (cons ((pair? x) 2) y) (string-append (symbol->string head) "'s argument ") (string-append (truncated-list->string arg) " looks odd: ") (string-append (object->string (caar arg)) " returns " (symbol->string rtn)) " which is not applicable")))) (when (or (pair? checker) (symbol? checker)) ; otherwise ignore type check on this argument (#t -> anything goes) (if arg (if (eq? checker 'unused-parameter?) (lint-format* caller ; (define (f5 a . b) a) (f5 1 2) (string-append (symbol->string head) "'s parameter " (number->string arg-number)) " is not used, but a value is passed: " (truncated-list->string arg)) (if (eq? checker 'unused-set-parameter?) (lint-format* caller ; (define (f21 x y) (set! x 3) (+ y 1)) (f21 (+ z 1) z) (string-append (symbol->string head) "'s parameter " (number->string arg-number)) "'s value is not used, but a value is passed: " (truncated-list->string arg))))) (if (not (pair? arg)) (let ((val (cond ((not (symbol? arg)) arg) ((constant? arg) (symbol->value arg)) ((and (hash-table-ref built-in-functions arg) (not (var-member :with-let env)) (not (var-member arg env))) (symbol->value arg *e*)) (else arg)))) (if (not (or (and (symbol? val) (not (keyword? val))) (any-checker? checker val))) (let ((op (->lint-type val))) (unless (memq op '(#f #t values)) (report-arg-trouble caller form head arg-number checker arg op))))) (case (car arg) ((quote) ; '1 -> 1 (let ((op (if (pair? (cadr arg)) 'list? (if (symbol? (cadr arg)) 'symbol? (->lint-type (cadr arg)))))) ;; arg is quoted expression (if (not (or (memq op '(#f #t values)) (every-compatible? checker op))) (report-arg-trouble caller form head arg-number checker arg op)))) ;; arg is an expression ((begin let let* letrec letrec* with-let) (check-arg (and (pair? (cdr arg)) (list-ref arg (- (length arg) 1))))) ((if) (if (and (pair? (cdr arg)) (pair? (cddr arg))) (let ((t (caddr arg)) (f (if (pair? (cdddr arg)) (cadddr arg)))) (check-arg t) (when (and f (not (symbol? f))) (check-arg f))))) ((dynamic-wind catch) (if (= (length arg) 4) (let ((f (caddr arg))) (if (and (pair? f) (eq? (car f) 'lambda)) (let ((len (length f))) (if (> len 2) (check-arg (list-ref f (- len 1))))))))) ((do) (if (and (pair? (cdr arg)) (pair? (cddr arg))) (let ((end+res (caddr arg))) (check-arg (if (pair? (cdr end+res)) (list-ref end+res (- (length end+res) 1)) ()))))) ((case) (for-each (lambda (clause) (if (and (pair? clause) (pair? (cdr clause)) (not (eq? (cadr clause) '=>))) (check-arg (list-ref clause (- (length clause) 1))))) (cddr arg))) ((cond) (for-each (lambda (clause) (if (pair? clause) (if (pair? (cdr clause)) (if (not (eq? (cadr clause) '=>)) (check-arg (list-ref clause (- (length clause) 1)))) (check-cond-arg (car clause))))) (cdr arg))) ((call/cc call-with-exit call-with-current-continuation) ;; find func in body (as car of list), check its arg as return value (when (and (pair? (cdr arg)) (pair? (cadr arg)) (eq? (caadr arg) 'lambda)) (let ((f (cdadr arg))) (when (and (pair? f) (pair? (car f)) (symbol? (caar f)) (null? (cdar f))) (define c-walk (let ((rtn (caar f))) (lambda (tree) (if (pair? tree) (if (eq? (car tree) rtn) (check-arg (if (null? (cdr tree)) () (cadr tree))) (begin (c-walk (car tree)) (for-each (lambda (x) (if (pair? x) (c-walk x))) (cdr tree)))))))) (for-each c-walk (cdr f)))))) ((values) (cond ((not (positive? (length arg)))) ((null? (cdr arg)) ; #<unspecified> (if (not (any-checker? checker #<unspecified>)) (report-arg-trouble caller form head arg-number checker arg 'unspecified?))) ((null? (cddr arg)) (check-arg (cadr arg))) (else (for-each (lambda (expr rest) (check-arg expr) (set! arg-number (+ arg-number 1)) (if (> arg-number max-arity) (done)) (if (list? checkers) (if (null? (cdr checkers)) (done) (set! checkers (cdr checkers))))) (cdr arg) (cddr arg)) (check-arg (list-ref arg (- (length arg) 1)))))) (else (let ((op (return-type (car arg) env))) (let ((v (var-member (car arg) env))) (if (and (var? v) (not (memq form (var-history v)))) (set! (var-history v) (cons form (var-history v))))) ;; checker is arg-type, op is expression type (can also be a pair) (if (and (not (memq op '(#f #t values))) (not (memq checker '(unused-parameter? unused-set-parameter?))) (or (not (every-compatible? checker op)) (and (just-constants? arg env) ; try to eval the arg (catch #t (lambda () (not (any-checker? checker (eval arg)))) (lambda ignore-catch-error-args #f))))) (report-arg-trouble caller form head arg-number checker arg op))))))) (if (list? checkers) (if (null? (cdr checkers)) (done) (set! checkers (cdr checkers))) (if (memq checker '(unused-parameter? unused-set-parameter?)) (set! checker #t))) (set! arg-number (+ arg-number 1)) (if (> arg-number max-arity) (done)))) (cdr form))))))) (define check-unordered-exprs (let ((changers (let ((h (make-hash-table))) (for-each (lambda (s) (hash-table-set! h s #t)) '(set! read read-byte read-char read-line read-string write write-byte write-char write-string format display newline reverse! set-cdr! sort! string-fill! vector-fill! fill! emergency-exit exit error throw)) h))) (lambda (caller form vals env) (define (report-trouble) (lint-format* caller ; (let ((x (read-byte)) (y (read-byte))) (- x y)) (string-append "order of evaluation of " (object->string (car form)) "'s ") (string-append (if (memq (car form) '(let letrec do)) "bindings" "arguments") " is unspecified, ") (string-append "so " (truncated-list->string form) " is trouble"))) (let ((reads ()) (writes ()) (jumps ())) (call-with-exit (lambda (return) (for-each (lambda (p) (when (and (pair? p) (not (var-member (car p) env)) (hash-table-ref changers (car p))) (if (pair? jumps) (return (report-trouble))) (case (car p) ((read read-char read-line read-byte) (if (null? (cdr p)) (if (memq () reads) (return (report-trouble)) (set! reads (cons () reads))) (if (memq (cadr p) reads) (return (report-trouble)) (set! reads (cons (cadr p) reads))))) ((read-string) (if (or (null? (cdr p)) (null? (cddr p))) (if (memq () reads) (return (report-trouble)) (set! reads (cons () reads))) (if (memq (caddr p) reads) (return (report-trouble)) (set! reads (cons (caddr p) reads))))) ((display write write-char write-string write-byte) (if (null? (cddr p)) (if (memq () writes) (return (report-trouble)) (set! writes (cons () writes))) (if (memq (caddr p) writes) (return (report-trouble)) (set! writes (cons (caddr p) writes))))) ((newline) (if (null? (cdr p)) (if (memq () writes) (return (report-trouble)) (set! writes (cons () writes))) (if (memq (cadr p) writes) (return (report-trouble)) (set! writes (cons (cadr p) writes))))) ((format) (if (and (pair? (cdr p)) (not (string? (cadr p))) (cadr p)) ; i.e. not #f (if (memq (cadr p) writes) (return (report-trouble)) (set! writes (cons (cadr p) writes))))) ((fill! string-fill! vector-fill! reverse! sort! set! set-cdr!) ;; here there's trouble if cadr used anywhere -- but we need to check for shadowing (if (any? (lambda (np) (and (not (eq? np p)) (tree-memq (cadr p) np))) vals) (return (report-trouble)))) ((throw error exit emergency-exit) (if (or (pair? reads) ; jumps already checked above (pair? writes)) (return (report-trouble)) (set! jumps (cons p jumps))))))) vals))))))) (define check-call (let ((repeated-args-table (let ((h (make-hash-table))) (for-each (lambda (op) (set! (h op) #t)) '(= / max min < > <= >= - quotient remainder modulo rationalize and or string=? string<=? string>=? string<? string>? string-ci=? string-ci<=? string-ci>=? string-ci<? string-ci>? char=? char<=? char>=? char<? char>? char-ci=? char-ci<=? char-ci>=? char-ci<? char-ci>? boolean=? symbol=?)) h)) (repeated-args-table-2 (let ((h (make-hash-table))) (for-each (lambda (op) (set! (h op) #t)) '(= max min < > <= >= and or string=? string<=? string>=? string<? string>? string-ci=? string-ci<=? string-ci>=? string-ci<? string-ci>? char=? char<=? char>=? char<? char>? char-ci=? char-ci<=? char-ci>=? char-ci<? char-ci>? boolean=? symbol=?)) h))) (lambda (caller head form env) (let ((data (var-member head env))) (if (and (pair? (cdr form)) (pair? (cddr form)) (any-procedure? head env)) (check-unordered-exprs caller form (cdr form) env)) (if (var? data) (let ((fdata (cdr data))) ;; a local var (when (symbol? (fdata 'ftype)) (let ((args (fdata 'arglist)) (ary (and (not (eq? (fdata 'decl) 'error)) (arity (fdata 'decl)))) (sig (var-signature data))) (when (pair? ary) (let ((req (car ary)) (opt (cdr ary)) (pargs (if (pair? args) (proper-list args) (if (symbol? args) (list args) ())))) (let ((call-args (- (length form) 1))) (if (< call-args req) (begin (for-each (lambda (p) (if (pair? p) (let ((v (var-member (car p) env))) (if (var? v) (let ((vals (let-ref (cdr v) 'values))) (if (pair? vals) (set! call-args (+ call-args -1 (cadr vals))))))))) (cdr form)) (if (and (< call-args req) (not (tree-memq 'values (cdr form)))) (lint-format "~A needs ~D argument~A: ~A" caller head req (if (> req 1) "s" "") (truncated-list->string form)))) (if (> (- call-args (keywords (cdr form))) opt) ; multiple-values can make this worse, (values)=nothing doesn't apply here (lint-format "~A has too many arguments: ~A" caller head (truncated-list->string form))))) (unless (fdata 'allow-other-keys) (let ((last-was-key #f) (have-keys 0) (warned #f) (rest (if (and (pair? form) (pair? (cdr form))) (cddr form) ()))) (for-each (lambda (arg) (if (and (keyword? arg) (not last-was-key)) ; keyarg might have key value (begin (set! have-keys (+ have-keys 1)) (if (not (member (keyword->symbol arg) pargs (lambda (a b) (eq? a (if (pair? b) (car b) b))))) (lint-format "~A keyword argument ~A (in ~A) does not match any argument in ~S" caller head arg (truncated-list->string form) pargs)) (if (memq arg rest) (lint-format "~W is repeated in ~A" caller arg (cdr form))) (set! last-was-key #t)) (begin (when (and (positive? have-keys) (not last-was-key) (not warned)) (set! warned #t) (lint-format "non-keyword argument ~A follows previous keyword~P" caller arg have-keys)) (set! last-was-key #f))) (if (pair? rest) (set! rest (cdr rest)))) (cdr form)))) (check-args caller head form (if (pair? sig) (cdr sig) ()) env opt) ;; for a complete var-history, we could run through the args here even if no type info ;; also if var passed to macro -- what to do? ;; look for problematic macro expansion (when (memq (fdata 'ftype) '(define-macro define-macro* defmacro defmacro*)) (unless (list? (fdata 'macro-ops)) (let ((syms (list () ()))) (tree-symbol-walk ((if (memq (fdata 'ftype) '(define-macro define-macro*)) cddr cdddr) (fdata 'initial-value)) syms) (varlet fdata 'macro-locals (car syms) 'macro-ops (cadr syms)))) (when (or (pair? (fdata 'macro-locals)) (pair? (fdata 'macro-ops))) (let ((bad-locals ()) (bad-quoted-locals ())) (for-each (lambda (local) (if (tree-unquoted-member local (cdr form)) (set! bad-locals (cons local bad-locals)))) (fdata 'macro-locals)) (when (null? bad-locals) (for-each (lambda (local) (if (tree-member local (cdr form)) (set! bad-quoted-locals (cons local bad-quoted-locals)))) (fdata 'macro-locals))) (let ((bad-ops ())) (for-each (lambda (op) (let ((curf (var-member op env)) (oldf (var-member op (fdata 'env)))) (if (and (not (eq? curf oldf)) (or (pair? (fdata 'env)) (defined? op (rootlet)))) (set! bad-ops (cons op bad-ops))))) (fdata 'macro-ops)) (when (or (pair? bad-locals) (pair? bad-quoted-locals) ;; (define-macro (mac8 b) `(let ((a 12)) (+ (symbol->value ,b) a))) ;; (let ((a 1)) (mac8 'a)) ;; far-fetched! (pair? bad-ops)) (lint-format "possible problematic macro expansion:~% ~A ~A collide with subsequently defined ~A~A~A" caller (truncated-list->string form) (if (or (pair? bad-locals) (pair? bad-ops)) "may" "could conceivably") (if (pair? bad-locals) (format #f "~{'~A~^, ~}" bad-locals) (if (pair? bad-quoted-locals) (format #f "~{'~A~^, ~}" bad-quoted-locals) "")) (if (and (pair? bad-locals) (pair? bad-ops)) ", " "") (if (pair? bad-ops) (format #f "~{~A~^, ~}" bad-ops) ""))))))) ))))) ;; not local var (when (symbol? head) (let ((head-value (symbol->value head *e*))) ; head might be "arity"! (when (or (procedure? head-value) (macro? head-value)) ;; check arg number (let ((ary (arity head-value))) (let ((args (- (length form) 1)) (min-arity (car ary)) (max-arity (cdr ary))) (if (< args min-arity) (lint-format "~A needs ~A~D argument~A: ~A" caller head (if (= min-arity max-arity) "" "at least ") min-arity (if (> min-arity 1) "s" "") (truncated-list->string form)) (if (and (not (procedure-setter head-value)) (> (- args (keywords (cdr form))) max-arity)) (lint-format "~A has too many arguments: ~A" caller head (truncated-list->string form)))) (when (and (procedure? head-value) (pair? (cdr form))) ; there are args (the not-enough-args case is checked above) (if (zero? max-arity) (lint-format "too many arguments: ~A" caller (truncated-list->string form)) (begin (for-each (lambda (arg) (if (pair? arg) (if (negative? (length arg)) (lint-format "missing quote? ~A in ~A" caller arg form) (if (eq? (car arg) 'unquote) (lint-format "stray comma? ~A in ~A" caller arg form))))) (cdr form)) ;; if keywords, check that they are acceptable ;; this only applies to lambda*'s that have been previously loaded (lint doesn't create them) (let ((source (procedure-source head-value))) (if (and (pair? source) (eq? (car source) 'lambda*)) (let ((decls (cadr source))) (if (not (memq :allow-other-keys decls)) (for-each (lambda (arg) (if (and (keyword? arg) (not (eq? arg :rest)) (not (member arg decls (lambda (a b) (eq? (keyword->symbol a) (if (pair? b) (car b) b)))))) (lint-format "~A keyword argument ~A (in ~A) does not match any argument in ~S" caller head arg (truncated-list->string form) decls))) (cdr form)))))) ;; we've already checked for head in the current env above (if (and (or (memq head '(eq? eqv?)) (and (= (length form) 3) (hash-table-ref repeated-args-table head))) (repeated-member? (cdr form) env)) (lint-format "this looks odd: ~A" caller ;; sigh (= a a) could be used to check for non-finite numbers, I suppose, ;; and (/ 0 0) might be deliberate (as in gmp) ;; also (min (random x) (random x)) is not pointless (truncated-list->string form)) (if (and (hash-table-ref repeated-args-table-2 head) (repeated-member? (cdr form) env)) (lint-format "it looks odd to have repeated arguments in ~A" caller (truncated-list->string form)))) (when (memq head '(eq? eqv?)) (define (repeated-member-with-not? lst env) (and (pair? lst) (let ((this-repeats (and (not (and (pair? (car lst)) (side-effect? (car lst) env))) (or (member (list 'not (car lst)) (cdr lst)) (and (pair? (car lst)) (eq? (caar lst) 'not) (= (length (car lst)) 2) (member (cadar lst) (cdr lst))))))) (or this-repeats (repeated-member-with-not? (cdr lst) env))))) (if (repeated-member-with-not? (cdr form) env) (lint-format "this looks odd: ~A" caller (truncated-list->string form)))) ;; now try to check arg types (let ((arg-data (cond ((procedure-signature (symbol->value head *e*)) => cdr) (else #f)))) (if (pair? arg-data) (check-args caller head form arg-data env max-arity)) )))))))))))))) (define (indirect-set? vname func arg1) (case func ((set-car! set-cdr! vector-set! list-set! string-set!) (eq? arg1 vname)) ((set!) (and (pair? arg1) (eq? (car arg1) vname))) (else #f))) (define (env-difference name e1 e2 lst) (if (or (null? e1) (null? e2) (eq? (car e1) (car e2))) (reverse lst) (env-difference name (cdr e1) e2 (if (eq? name (var-name (car e1))) lst (cons (car e1) lst))))) (define report-usage (let ((unwrap-cxr (hash-table '(caar car) '(cadr cdr) '(cddr cdr) '(cdar car) '(caaar caar car) '(caadr cadr cdr) '(caddr cddr cdr) '(cdddr cddr cdr) '(cdaar caar car) '(cddar cdar car) '(cadar cadr car) '(cdadr cadr cdr) '(cadddr cdddr cddr cdr) '(cddddr cdddr cddr cdr) '(caaaar caaar caar car) '(caaadr caadr cadr cdr) '(caadar cadar cdar car) '(caaddr caddr cddr cdr) '(cadaar cdaar caar car) '(cadadr cdadr cadr cdr) '(caddar cddar cdar car) '(cdaaar caaar caar car) '(cdaadr caadr cadr cdr) '(cdadar cadar cdar car) '(cdaddr caddr cddr cdr) '(cddaar cdaar caar car) '(cddadr cdadr cadr cdr) '(cdddar cddar cdar car)))) (lambda (caller head vars env) ;; report unused or set-but-unreferenced variables, then look at the overall history (define (all-types-agree v) (let ((base-type (->lint-type (var-initial-value v))) (vname (var-name v))) (and (every? (lambda (p) (or (not (and (pair? p) (eq? (car p) 'set!) (eq? vname (cadr p)))) (let ((nt (->lint-type (caddr p)))) (or (subsumes? base-type nt) (and (subsumes? nt base-type) (set! base-type nt)) (and (memq nt '(pair? null? proper-list?)) (memq base-type '(pair? null? proper-list?)) (set! base-type 'list?)))))) (var-history v)) base-type))) (when (and (not (eq? head 'begin)) ; begin can redefine = set a variable (pair? vars) (proper-list? vars)) (do ((cur vars (cdr cur)) (rst (cdr vars) (cdr rst))) ((null? rst)) (let ((vn (var-name (car cur)))) (if (not (memq vn '(:lambda :dilambda))) (let ((repeat (var-member vn rst))) (when repeat (let ((type (if (eq? (var-definer repeat) 'parameter) 'parameter 'variable))) (if (eq? (var-definer (car cur)) 'define) (lint-format "~A ~A ~A is redefined ~A" caller head type vn (if (equal? head "") (if (not (tree-memq vn (var-initial-value (car cur)))) "at the top level." (format #f "at the top level. Perhaps use set! instead: ~A" (truncated-list->string `(set! ,vn ,(var-initial-value (car cur)))))) (format #f "in the ~A body. Perhaps use set! instead: ~A" head (truncated-list->string `(set! ,vn ,(var-initial-value (car cur))))))) (lint-format "~A ~A ~A is declared twice" caller head type vn))))))))) (let ((old-line-number line-number)) (for-each (lambda (local-var) (let ((vname (var-name local-var)) (otype (if (eq? (var-definer local-var) 'parameter) 'parameter 'variable))) ;; do all refs to an unset var go through the same function (at some level) (when (and (zero? (var-set local-var)) (> (var-ref local-var) 1) (not (eq? otype 'parameter))) (let ((hist (var-history local-var))) (when (pair? hist) (let ((outer-form (cond ((var-member :let env) => var-initial-value) (else #f)))) ;; if outer-form is #f, local-var is probably a top-level var (when (and (pair? outer-form) (not (and (memq (car outer-form) '(let let*)) ; not a named-let parameter (symbol? (cadr outer-form))))) (let ((first (car hist))) ; all but the initial binding have to match this (when (pair? first) (let ((op (car first))) (when (and (symbol? op) (not (eq? op 'unquote)) (not (hash-table-ref makers op)) (not (eq? vname op)) ; not a function (this kind if repetition is handled elsewhere) (pair? (cdr hist)) (pair? (cddr hist)) (pair? (cdr first)) (not (side-effect? first env)) (every? (lambda (a) (or (eq? a vname) (code-constant? a))) (cdr first)) (or (code-constant? (var-initial-value local-var)) (= (tree-count1 vname first 0) 1)) (every? (lambda (a) (and (pair? a) (or (equal? first a) (and (eq? (hash-table-ref reversibles (car first)) (car a)) (equal? (cdr first) (reverse (cdr a)))) (set! op (match-cxr op (car a)))))) (copy (cdr hist) (make-list (- (length hist) 2))))) (let* ((new-op (or op (car first))) (set-target (let walker ((tree outer-form)) ; check for new-op dilambda as target of set! (and (pair? tree) (or (and (eq? (car tree) 'set!) (pair? (cdr tree)) (pair? (cadr tree)) (eq? (caadr tree) new-op)) (walker (car tree)) (walker (cdr tree))))))) (unless set-target (lint-format* caller (symbol->string vname) " is not set, and is always accessed via " (object->string `(,new-op ,@(cdr first))) " so its binding could probably be " ;; "probably" here because the accesses could have hidden protective assumptions ;; i.e. full accessor is not valid at point of let binding (object->string `(,vname (,new-op ,@(tree-subst (var-initial-value local-var) vname (cdr first))))) " in " (truncated-list->string outer-form))))))))))))) ;; translate to dilambda fixing arg if necessary and mention generic set! (let ((init (var-initial-value local-var))) (when (and (pair? init) (eq? (car init) 'define) (pair? (cadr init))) (let* ((vstr (symbol->string vname)) (len (length vstr))) (when (> len 4) (let ((setv #f) (newv #f)) (if (string=? (substring vstr 0 4) "get-") (let ((sv (symbol "set-" (substring vstr 4)))) (set! setv (or (var-member sv vars) (var-member sv env))) (set! newv (string->symbol (substring vstr 4)))) (if (string=? (substring vstr (- len 4)) "-ref") (let ((sv (symbol (substring vstr 0 (- len 4)) "-set!"))) (set! setv (or (var-member sv vars) (var-member sv env))) (set! newv (string->symbol (substring vstr 0 (- len 4))))) (let ((pos (string-position "-get-" vstr))) (when pos ; this doesn't happen very often, others: Get-, -ref-, -set!- are very rare (let ((sv (let ((s (copy vstr))) (set! (s (+ pos 1)) #\s) (string->symbol s)))) (set! setv (or (var-member sv vars) (var-member sv env))) (set! newv (symbol (substring vstr 0 pos) (substring vstr (+ pos 4))))))))) ; +4 to include #\- (when (and setv (not (var-member newv vars)) (not (var-member newv env))) (let ((getter init) (setter (var-initial-value setv))) (when (and (pair? setter) (eq? (car setter) 'define) (pair? (cadr setter))) (let ((getargs (cdadr getter)) (setargs (cdadr setter))) (unless (null? setargs) (if (or (eq? newv getargs) (and (pair? getargs) (memq newv getargs))) (let ((unique (find-unique-name getter newv))) (set! getter (tree-subst unique newv getter)) (set! getargs (cdadr getter)))) (if (or (eq? newv setargs) (and (pair? setargs) (memq newv setargs))) (let ((unique (find-unique-name setter newv))) (set! setter (tree-subst unique newv setter)) (set! setargs (cdadr setter)))) (let ((getdots (if (null? getargs) "" " ...")) (setdots (if (or (not (pair? setargs)) (null? (cdr setargs))) "" " ...")) (setvalue (and (proper-list? setargs) (list-ref setargs (- (length setargs) 1))))) (if setvalue (format outport "~NC~A: perhaps use dilambda and generalized set! for ~A and ~A:~%~ ~NCreplace (~A~A) with (~A~A) and (~A~A ~A) with (set! (~A~A) ~A)~%~ ~NC~A~%" lint-left-margin #\space caller vname (var-name setv) (+ lint-left-margin 4) #\space vname getdots newv getdots (var-name setv) setdots setvalue newv setdots setvalue (+ lint-left-margin 4) #\space (lint-pp `(define ,newv (dilambda (lambda ,getargs ,@(cddr getter)) (lambda ,setargs ,@(cddr setter)))))))))))))))))) ;; bad variable names (cond ((hash-table-ref syntaces vname) (lint-format "~A ~A named ~A is asking for trouble" caller head otype vname)) ((eq? vname 'l) (lint-format "\"l\" is a really bad variable name" caller)) ((and *report-built-in-functions-used-as-variables* (hash-table-ref built-in-functions vname)) (lint-format "~A ~A named ~A is asking for trouble" caller (if (and (pair? (var-scope local-var)) (null? (cdr (var-scope local-var))) (symbol? (car (var-scope local-var)))) (car (var-scope local-var)) head) otype vname)) (else (check-for-bad-variable-name caller vname))) (unless (memq vname '(:lambda :dilambda)) (if (and (eq? otype 'variable) (or *report-unused-top-level-functions* (not (eq? caller top-level:)))) (let ((scope (var-scope local-var))) ; might be #<undefined>? (if (pair? scope) (set! scope (remove vname scope))) (when (and (pair? scope) (null? (cdr scope)) (symbol? (car scope)) (not (var-member (car scope) (let search ((e env)) (if (null? e) env (if (eq? (caar e) vname) e (search (cdr e)))))))) (format outport "~NC~A~A is ~A only in ~A~%" lint-left-margin #\space (if (eq? caller top-level:) "top-level: " "") vname (if (memq (var-ftype local-var) '(define lambda define* lambda*)) "called" "used") (car scope))))) (if (and (eq? (var-ftype local-var) 'define-expansion) (not (eq? caller top-level:))) (format outport "~NCdefine-expansion for ~A is not at the top-level, so it is ignored~%" lint-left-margin #\space vname)) (when (and *report-function-stuff* (memq (var-ftype local-var) '(define lambda define* lambda*)) (pair? (caddr (var-initial-value local-var)))) (let ((cur (hash-table-ref equable-closures (caaddr (var-initial-value local-var))))) (if (pair? cur) (hash-table-set! equable-closures (caaddr (var-initial-value local-var)) (remove local-var cur))))) ;; redundant vars are hard to find -- tons of false positives (if (zero? (var-ref local-var)) (when (and (or (not (equal? head "")) *report-unused-top-level-functions*) (or *report-unused-parameters* (not (eq? otype 'parameter)))) (if (positive? (var-set local-var)) (let ((sets (map (lambda (call) (if (and (pair? call) (not (eq? (var-definer local-var) 'do)) (eq? (car call) 'set!) (eq? (cadr call) vname)) call (values))) (var-history local-var)))) (if (pair? sets) (if (null? (cdr sets)) (lint-format "~A set, but not used: ~A" caller vname (truncated-list->string (car sets))) (lint-format "~A set, but not used: ~{~S~^ ~}" caller vname sets)) (lint-format "~A set, but not used: ~A from ~A" caller vname (truncated-list->string (var-initial-value local-var)) (var-definer local-var)))) ;; not ref'd or set (if (not (memq vname '(documentation signature iterator? defanimal))) (let ((val (if (pair? (var-history local-var)) (car (var-history local-var)) (var-initial-value local-var))) (def (var-definer local-var))) (let-temporarily ((line-number (if (eq? caller top-level:) -1 line-number))) ;; eval confuses this message (eval '(+ x 1)), no other use of x [perhaps check :let initial-value = outer-form] ;; so does let-ref syntax: (apply (*e* 'g1)...) will miss this reference to g1 (if (symbol? def) (if (eq? otype 'parameter) (lint-format "~A not used" caller vname) (lint-format* caller (string-append (object->string vname) " not used, initially: ") (string-append (truncated-list->string val) " from " (symbol->string def)))) (lint-format* caller (string-append (object->string vname) " not used, value: ") (truncated-list->string val)))))))) ;; not zero var-ref (let ((arg-type #f)) (when (and (not (memq (var-definer local-var) '(parameter named-let named-let*))) (pair? (var-history local-var)) (or (zero? (var-set local-var)) (set! arg-type (all-types-agree local-var)))) (let ((vtype (or arg-type ; this can't be #f unless no sets so despite appearances there's no contention here (eq? caller top-level:) ; might be a global var where init value is largely irrelevant (->lint-type (var-initial-value local-var)))) (lit? (code-constant? (var-initial-value local-var)))) (do ((clause (var-history local-var) (cdr clause))) ((null? (cdr clause))) ; ignore the initial value which depends on a different env (let ((call (car clause))) (if (pair? call) (set! line-number (pair-line-number call))) (when (pair? call) (let ((func (car call)) (call-arg1 (and (pair? (cdr call)) (cadr call)))) ;; check for assignments into constants (if (and lit? (indirect-set? vname func call-arg1)) (lint-format "~A's value, ~A, is a literal constant, so this set! is trouble: ~A" caller vname (var-initial-value local-var) (truncated-list->string call))) (when (symbol? vtype) (when (and (not (eq? caller top-level:)) (not (memq vtype '(boolean? #t values))) (memq func '(if when unless)) ; look for (if x ...) where x is never #f, this happens a dozen or so times (or (eq? (cadr call) vname) (and (pair? (cadr call)) (eq? (caadr call) 'not) (eq? (cadadr call) vname)))) (lint-format "~A is never #f, so ~A" caller vname (lists->string call (if (eq? vname (cadr call)) (case func ((if) (caddr call)) ((when) (if (pair? (cdddr call)) `(begin ,@(cddr call)) (caddr call))) ((unless) #<unspecified>)) (case func ((if) (if (pair? (cdddr call)) (cadddr call))) ((when) #<unspecified>) ((unless) (if (pair? (cdddr call)) `(begin ,@(cddr call)) (caddr call)))))))) ;; check for incorrect types in function calls (unless (memq vtype '(boolean? null?)) ; null? here avoids problems with macros that call set! (let ((p (memq vname (cdr call)))) (when (pair? p) (let ((sig (arg-signature func env)) (pos (- (length call) (length p)))) (when (and (pair? sig) (< pos (length sig))) (let ((desired-type (list-ref sig pos))) (if (not (compatible? vtype desired-type)) (lint-format "~A is ~A, but ~A in ~A wants ~A" caller vname (prettify-checker-unq vtype) func (truncated-list->string call) (prettify-checker desired-type)))))))) (let ((suggest made-suggestion)) ;; check for pointless vtype checks (when (and (hash-table-ref bools func) (not (eq? vname func))) (when (or (eq? vtype func) (and (compatible? vtype func) (not (subsumes? vtype func)))) (lint-format "~A is ~A, so ~A is #t" caller vname (prettify-checker-unq vtype) call)) (unless (compatible? vtype func) (lint-format "~A is ~A, so ~A is #f" caller vname (prettify-checker-unq vtype) call))) (case func ;; need a way to mark exported variables so they won't be checked in this process ;; case can happen here, but it never seems to trigger a type error ((eq? eqv? equal?) ;; (and (pair? x) (eq? x #\a)) etc (when (or (and (code-constant? call-arg1) (not (compatible? vtype (->lint-type call-arg1)))) (and (code-constant? (caddr call)) (not (compatible? vtype (->lint-type (caddr call)))))) (lint-format "~A is ~A, so ~A is #f" caller vname (prettify-checker-unq vtype) call))) ((and or) (when (let amidst? ((lst call)) (and (pair? lst) (pair? (cdr lst)) (or (eq? (car lst) vname) (amidst? (cdr lst))))) ; don't clobber possible trailing vname (returned by expression) (lint-format "~A is ~A, so ~A~%" caller ; (let ((x 1)) (and x (< x 1))) -> (< x 1) vname (prettify-checker-unq vtype) (lists->string call (simplify-boolean (remove vname call) () () vars))))) ((not) (if (eq? vname (cadr call)) (lint-format "~A is ~A, so ~A" caller vname (prettify-checker-unq vtype) (lists->string call #f)))) ((/) (if (and (number? (var-initial-value local-var)) (zero? (var-initial-value local-var)) (zero? (var-set local-var)) (memq vname (cddr call))) (lint-format "~A is ~A, so ~A is an error" caller vname (var-initial-value local-var) call)))) ;; the usual eqx confusion (when (and (= suggest made-suggestion) (memq vtype '(char? number? integer? real? float? rational? complex?))) (if (memq func '(eq? equal?)) (lint-format "~A is ~A, so ~A ~A be eqv? in ~A" caller vname (prettify-checker-unq vtype) func (if (eq? func 'eq?) "should" "could") call)) ;; check other boolean exprs (when (and (zero? (var-set local-var)) (number? (var-initial-value local-var)) (eq? vname call-arg1) (null? (cddr call)) (hash-table-ref booleans func)) (let ((val (catch #t (lambda () ((symbol->value func (rootlet)) (var-initial-value local-var))) (lambda args 'error)))) (if (boolean? val) (lint-format "~A is ~A, so ~A is ~A" caller vname (var-initial-value local-var) call val)))))) ;; implicit index checks -- these are easily fooled by macros (when (and (memq vtype '(vector? float-vector? int-vector? string? list? byte-vector?)) (pair? (cdr call))) (when (eq? func vname) (let ((init (var-initial-value local-var))) (if (not (compatible? 'integer? (->lint-type call-arg1))) (lint-format "~A is ~A, but the index ~A is ~A" caller vname (prettify-checker-unq vtype) call-arg1 (prettify-checker (->lint-type call-arg1)))) (if (integer? call-arg1) (if (negative? call-arg1) (lint-format "~A's index ~A is negative" caller vname call-arg1) (if (zero? (var-set local-var)) (let ((lim (cond ((code-constant? init) (length init)) ((memq (car init) '(vector float-vector int-vector string list byte-vector)) (- (length init) 1)) (else (and (pair? (cdr init)) (integer? (cadr init)) (memq (car init) '(make-vector make-float-vector make-int-vector make-string make-list make-byte-vector)) (cadr init)))))) (if (and (real? lim) (>= call-arg1 lim)) (lint-format "~A has length ~A, but index is ~A" caller vname lim call-arg1)))))))) (when (eq? func 'implicit-set) ;; ref is already checked in other history entries (let ((ref-type (case vtype ((float-vector?) 'real?) ; not 'float? because ints are ok here ((int-vector? byte-vector?) 'integer) ((string?) 'char?) (else #f)))) (if ref-type (let ((val-type (->lint-type (caddr call)))) (if (not (compatible? val-type ref-type)) (lint-format "~A wants ~A, but the value in ~A is ~A" caller vname (prettify-checker-unq ref-type) `(set! ,@(cdr call)) (prettify-checker val-type))))) )))))) ))) ; do loop through clauses ;; check for duplicated calls involving local-var (when (and (> (var-ref local-var) 8) (zero? (var-set local-var)) (eq? (var-ftype local-var) #<undefined>)) (let ((h (make-hash-table))) (for-each (lambda (call) (when (and (pair? call) (not (eq? (car call) vname)) ; ignore functions for now (not (side-effect? call env))) (hash-table-set! h call (+ 1 (or (hash-table-ref h call) 0))) (cond ((hash-table-ref unwrap-cxr (car call)) => (lambda (lst) (for-each (lambda (c) (hash-table-set! h (cons c (cdr call)) (+ 1 (or (hash-table-ref h (cons c (cdr call))) 0)))) lst)))))) (var-history local-var)) (let ((repeats ())) (for-each (lambda (call) (if (and (> (cdr call) (max 3 (/ 20 (tree-leaves (car call))))) ; was 5 (not (memq (caar call) '(make-vector make-float-vector))) (or (null? (cddar call)) (every? (lambda (p) (or (not (symbol? p)) (eq? p vname))) (cdar call)))) (set! repeats (cons (string-append (truncated-list->string (car call)) " occurs ") (cons (string-append (object->string (cdr call)) " times" (if (pair? repeats) ", " "")) repeats))))) h) (if (pair? repeats) (apply lint-format* caller (string-append (object->string vname) " is not set, but ") repeats))))) ;; check for function parameters whose values never change and are not just symbols (when (and (> (var-ref local-var) 3) (zero? (var-set local-var)) (memq (var-ftype local-var) '(define lambda)) (pair? (var-arglist local-var)) (let loop ((calls (var-history local-var))) ; if func passed as arg, ignore it (or (null? calls) (null? (cdr calls)) (and (pair? (car calls)) (not (memq (var-name local-var) (cdar calls))) (loop (cdr calls)))))) (let ((pars (map list (proper-list (var-arglist local-var))))) (do ((clauses (var-history local-var) (cdr clauses))) ((null? (cdr clauses))) ; ignore the initial value (if (and (pair? (car clauses)) (eq? (caar clauses) (var-name local-var))) (for-each (lambda (arg par) ; collect all arguments for each parameter (if (not (member arg (cdr par))) ; we haven't seen this argument yet, so (set-cdr! par (cons arg (cdr par))))) ; add it to the list for this parameter (cdar clauses) pars))) (for-each (lambda (p) (if (and (pair? (cdr p)) (null? (cddr p)) ; so all calls, this parameter has the same value (not (symbol? (cadr p)))) (lint-format "~A's '~A parameter is always ~S (~D calls)" caller (var-name local-var) (car p) (cadr p) (var-ref local-var)))) pars))) )))) ; end (if zero var-ref) ;; vars with multiple incompatible ascertainable types don't happen much and obvious type errors are extremely rare ))) vars) (set! line-number old-line-number))))) ;; ---------------------------------------- ;; preloading built-in definitions, and looking for them here found less than a dozen (list-ref, list-tail, and boolean?) (define (code-equal? p1 p2 matches e1 e2) (define (match-vars r1 r2 mat) (and (pair? r1) (pair? r2) (pair? (cdr r1)) (pair? (cdr r2)) ((if (and (pair? (cadr r1)) (pair? (cadr r2)) (memq (caadr r1) '(let let* letrec letrec* do lambda lambda* define define-constant define-macro define-bacro define-expansion define* define-macro* define-bacro*))) code-equal? structures-equal?) (cadr r1) (cadr r2) mat e1 e2) (cons (car r1) (car r2)))) (let ((f1 (car p1)) (f2 (car p2))) (and (eq? f1 f2) (let ((rest1 (cdr p1)) (rest2 (cdr p2))) (and (pair? rest1) (pair? rest2) (call-with-exit (lambda (return) (case f1 ((let) (let ((name ())) (if (symbol? (car rest1)) ; named let -- match funcs too (if (symbol? (car rest2)) (begin (set! name (list (cons (car rest1) (car rest2)))) (set! rest1 (cdr rest1)) (set! rest2 (cdr rest2))) (return #f)) (if (symbol? (car rest2)) (return #f))) (and (= (length (car rest1)) (length (car rest2))) (let ((new-matches (append (map (lambda (var1 var2) (or (match-vars var1 var2 matches) (return #f))) (car rest1) (car rest2)) name ; append will splice out nil matches))) (structures-equal? (cdr rest1) (cdr rest2) ; refs in values are to outer matches new-matches e1 e2))))) ((let*) ; refs move with the vars (and (= (length (car rest1)) (length (car rest2))) (let ((new-matches matches)) (for-each (lambda (var1 var2) (cond ((match-vars var1 var2 new-matches) => (lambda (v) (set! new-matches (cons v new-matches)))) (else (return #f)))) (car rest1) (car rest2)) (structures-equal? (cdr rest1) (cdr rest2) new-matches e1 e2)))) ((do) ; matches at init are outer, but at step are inner (and (= (length (car rest1)) (length (car rest2))) (let ((new-matches matches)) (for-each (lambda (var1 var2) (cond ((match-vars var1 var2 matches) => (lambda (v) (set! new-matches (cons v new-matches)))) (else (return #f)))) (car rest1) (car rest2)) (for-each (lambda (var1 var2) (unless (structures-equal? (cddr var1) (cddr var2) new-matches e1 e2) (return #f))) (car rest1) (car rest2)) (structures-equal? (cdr rest1) (cdr rest2) new-matches e1 e2)))) ((letrec letrec*) ; ??? refs are local I think (and (= (length (car rest1)) (length (car rest2))) (let ((new-matches (append (map (lambda (var1 var2) (cons (car var1) (car var2))) (car rest1) (car rest2)) matches))) (for-each (lambda (var1 var2) (unless (structures-equal? (cadr var1) (cadr var2) new-matches e1 e2) (return #f))) (car rest1) (car rest2)) (structures-equal? (cdr rest1) (cdr rest2) new-matches e1 e2)))) ((lambda) (if (symbol? (car rest1)) (and (symbol? (car rest2)) (structures-equal? (cdr rest1) (cdr rest2) (cons (cons (car rest1) (car rest2)) matches) e1 e2)) (and (eqv? (length (car rest1)) (length (car rest2))) ; (car rest2) might be a symbol, dotted lists ok here (let ((new-matches (append (map cons (proper-list (car rest1)) (proper-list (car rest2))) matches))) (structures-equal? (cdr rest1) (cdr rest2) new-matches e1 e2))))) ((define define-constant define-macro define-bacro define-expansion) (if (symbol? (car rest1)) (and (symbol? (car rest2)) (let ((new-matches (cons (cons (car rest1) (car rest2)) matches))) (and (structures-equal? (cdr rest1) (cdr rest2) new-matches e1 e2) new-matches))) (and (eqv? (length (car rest1)) (length (car rest2))) ; (car rest2) might be a symbol, dotted lists ok here (let ((new-matches (append (map cons (proper-list (car rest1)) (proper-list (car rest2))) matches))) (structures-equal? (cdr rest1) (cdr rest2) new-matches e1 e2)) (cons (cons (caar rest1) (caar rest2)) matches)))) ;; for define we add the new name to matches before walking the body (shadow is immediate), ;; but then the new name is added to matches and returned (see below) ((lambda*) (if (symbol? (car rest1)) (and (symbol? (car rest2)) (structures-equal? (cdr rest1) (cdr rest2) (cons (cons (car rest1) (car rest2)) matches) e1 e2)) (and (eqv? (length (car rest1)) (length (car rest2))) ; (car rest2) might be a symbol, dotted lists ok here (let ((new-matches (map (lambda (a b) (if (or (pair? a) ; if default, both must have the same value (pair? b)) (if (not (and (pair? a) (pair? b) (equal? (cadr a) (cadr b)))) (return #f) (cons (car a) (car b))) (cons a b))) (proper-list (car rest1)) (proper-list (car rest2))))) (structures-equal? (cdr rest1) (cdr rest2) (append new-matches matches) e1 e2))))) ((define* define-macro* define-bacro*) (if (symbol? (car rest1)) (and (symbol? (car rest2)) (let ((new-matches (cons (cons (car rest1) (car rest2)) matches))) (and (structures-equal? (cdr rest1) (cdr rest2) new-matches e1 e2) new-matches))) (and (eqv? (length (car rest1)) (length (car rest2))) ; (car rest2) might be a symbol, dotted lists ok here (let ((new-matches (map (lambda (a b) (if (or (pair? a) ; if default, both must have the same value (pair? b)) (if (not (and (pair? a) (pair? b) (equal? (cadr a) (cadr b)))) (return #f) (cons (car a) (car b))) (cons a b))) (proper-list (car rest1)) (proper-list (car rest2))))) (structures-equal? (cdr rest1) (cdr rest2) (append new-matches new-matches) e1 e2)) (cons (cons (caar rest1) (caar rest2)) matches)))) (else #f))))))))) ; can't happen I hope (define (structures-equal? p1 p2 matches e1 e2) (if (pair? p1) (and (pair? p2) (if (eq? (car p1) 'quote) (and (eq? (car p2) 'quote) (equal? (cdr p1) (cdr p2))) (and (if (not (and (pair? (car p1)) (pair? (car p2)))) (structures-equal? (car p1) (car p2) matches e1 e2) (case (caar p1) ((let let* letrec letrec* do lambda lambda*) (code-equal? (car p1) (car p2) matches e1 e2)) ((define define-constant define-macro define-bacro define-expansion define* define-macro* define-bacro*) (let ((mat (code-equal? (car p1) (car p2) matches e1 e2))) (and (pair? mat) (set! matches mat)))) ;; this ignores possible reversible equivalence (i.e. (< x 0) is the same as (> 0 x) ;; (structures-equal? (car p1) (car p2) matches e1 e2))) ;; check for reversible equivalence ;; half-humorous problem: infinite loop here switching back and forth! ;; so I guess we have to check cdar by hand ;; we could also check for not+notable here, but lint will complain ;; about that elsewhere, causing this check to be ignored. (else (or (structures-equal? (car p1) (car p2) matches e1 e2) (and (eq? (hash-table-ref reversibles (caar p1)) (caar p2)) (not (any? (lambda (p) (side-effect? p e1)) (cdar p1))) ; (+ (oscil g) (oscil g x)) is not reversible! (do ((a (cdar p1) (cdr a)) (b (reverse (cdar p2)) (cdr b))) ((or (null? a) (null? b) (not (structures-equal? a b matches e1 e2))) (and (null? a) (null? b))))))))) (structures-equal? (cdr p1) (cdr p2) matches e1 e2)))) (let ((match (assq p1 matches))) (if match (or (and (eq? (cdr match) :unset) (set-cdr! match p2)) (equal? (cdr match) p2)) (if (symbol? p1) (and (eq? p1 p2) (or (eq? e1 e2) (eq? (assq p1 e1) (assq p2 e2)))) (equal? p1 p2)))))) ;; code-equal? and structures-equal? called in function-match and each other (define (function-match caller form env) (define func-min-cutoff 6) (define func-max-cutoff 120) (define (proper-list* lst) ;; return lst as a proper list (might have defaults, keywords etc) (if (or (not (pair? lst)) (eq? (car lst) :allow-other-keys)) () (if (eq? (car lst) :rest) (cdr lst) (cons ((if (pair? (car lst)) caar car) lst) (if (pair? (cdr lst)) (proper-list* (cdr lst)) (if (null? (cdr lst)) () (list (cdr lst)))))))) (let ((leaves (tree-leaves form))) (when (<= func-min-cutoff leaves func-max-cutoff) (let ((new-form (if (pair? (car form)) form (list form))) (name-args #f) (name-args-len :unset) (e2 ())) (let ((v (var-member caller env))) (when (and (var? v) (memq (var-ftype v) '(define lambda define* lambda*)) (or (eq? form (cddr (var-initial-value v))) ; only check args if this is the complete body (and (null? (cdddr (var-initial-value v))) (eq? form (caddr (var-initial-value v)))))) (set! e2 (var-env v)) (if (symbol? (var-arglist v)) (begin (set! name-args-len #f) (set! name-args (list (var-arglist v)))) (begin (set! name-args-len (length (var-arglist v))) (set! name-args (map (lambda (arg) (if (symbol? arg) arg (values))) (proper-list* (var-arglist v)))))))) (let ((find-code-match (let ((e1 ()) (cutoff (max func-min-cutoff (- leaves 12)))) (lambda (v) (and (not (memq (var-name v) '(:lambda :dilambda))) (memq (var-ftype v) '(define lambda define* lambda*)) (not (eq? caller (var-name v))) (let ((body (cddr (var-initial-value v))) (args (var-arglist v))) (set! e1 (var-env v)) (let ((args-len (length args))) (when (or (eq? name-args-len :unset) (equal? args-len name-args-len) (and (integer? args-len) (integer? name-args-len) (not (negative? (* args-len name-args-len))))) (unless (var-leaves v) (set! (var-leaves v) (tree-leaves body)) (set! (var-match-list v) (if (symbol? args) (list (cons args :unset)) (map (lambda (arg) (if (symbol? arg) (cons arg :unset) (values))) (proper-list* args))))) ;; var-leaves is size of func (v) body ;; leaves is size of form which we want to match with func ;; func-min-cutoff avoids millions of uninteresting matches (and (<= cutoff (var-leaves v) leaves) (let ((match-list (do ((p (var-match-list v) (cdr p))) ((null? p) (var-match-list v)) (set-cdr! (car p) :unset)))) (and (structures-equal? body new-form (cons (cons (var-name v) caller) match-list) e1 e2) ;; if the functions are recursive, we also need those names matched, hence the extra entry ;; but we treat match-list below as just the args, so add the func names at the call, ;; but this can be fooled if we're playing games with eq? basically -- the function ;; names should only match if used as functions. (not (member :unset match-list (lambda (a b) (eq? (cdr b) :unset)))) (let ((new-args (map cdr match-list))) (if (and (equal? new-args name-args) (equal? args-len name-args-len)) (lint-format "~A could be ~A" caller caller `(define ,caller ,(var-name v))) (lint-format "perhaps ~A" caller (lists->string form `(,(var-name v) ,@new-args)))) #t)))))))))))) (do ((vs (or (hash-table-ref equable-closures (caar new-form)) ()) (cdr vs))) ;; instead of hashing on car as above, hash on composite of cars+base statements ((or (null? vs) (find-code-match (car vs)))))))))) (define (find-call sym body) (call-with-exit (lambda (return) (let tree-call ((tree body)) (if (and (pair? tree) (not (eq? (car tree) 'quote))) (begin (if (eq? (car tree) sym) (return tree)) (if (memq (car tree) '(let let* letrec letrec* do lambda lambda* define)) (return #f)) ; possible shadowing -- not worth the infinite effort to corroborate (if (pair? (car tree)) (tree-call (car tree))) (if (pair? (cdr tree)) (do ((p (cdr tree) (cdr p))) ((not (pair? p)) #f) (tree-call (car p)))))))))) (define (check-returns caller f env) ; f is not the last form in the body (if (not (or (side-effect? f env) (eq? '=> f))) (lint-format "this could be omitted: ~A" caller (truncated-list->string f)) (when (pair? f) (case (car f) ((if) (when (and (pair? (cdr f)) (pair? (cddr f))) (let ((true (caddr f)) (false (if (pair? (cdddr f)) (cadddr f) 'no-false))) (let ((true-ok (side-effect? true env)) (false-ok (or (eq? false 'no-false) (side-effect? false env)))) (if true-ok (if (pair? true) (check-returns caller true env)) (lint-format "this branch is pointless~A: ~A in ~A" caller (local-line-number true) (truncated-list->string true) (truncated-list->string f))) (if false-ok (if (pair? false) (check-returns caller false env)) (lint-format "this branch is pointless~A: ~A in ~A" caller (local-line-number false) (truncated-list->string false) (truncated-list->string f))))))) ((cond case) ;; here all but last result exprs are already checked ;; redundant begin can confuse this, but presumably we'll complain about that elsewhere ;; also even in mid-body, if else clause has a side-effect, an earlier otherwise pointless clause might be avoiding that (let ((has-else (let ((last-clause (list-ref f (- (length f) 1)))) (and (pair? last-clause) (memq (car last-clause) '(else #t)) (any? (lambda (c) (side-effect? c env)) (cdr last-clause)))))) (for-each (lambda (c) (if (and (pair? c) (pair? (cdr c)) (not (memq '=> (cdr c)))) (let ((last-expr (list-ref c (- (length c) 1)))) (cond ((side-effect? last-expr env) (if (pair? last-expr) (check-returns caller last-expr env))) (has-else (if (or (pair? (cddr c)) (eq? (car f) 'cond)) (lint-format "this ~A clause's result could be omitted" caller (truncated-list->string c)) (if (not (memq last-expr '(#f #t #<unspecified>))) ; it's not already obvious (lint-format "this ~A clause's result could be simply #f" caller (truncated-list->string c))))) ((and (eq? (car f) 'case) (or (eq? last-expr (cadr c)) (not (any? (lambda (p) (side-effect? p env)) (cdr c))))) (lint-format "this case clause can be omitted: ~A" caller (truncated-list->string c))) (else (lint-format "this is pointless: ~A in ~A" caller (truncated-list->string last-expr) (truncated-list->string c))))))) ((if (eq? (car f) 'cond) cdr cddr) f)))) ((let let*) (if (and (pair? (cdr f)) (not (symbol? (cadr f))) (pair? (cddr f))) (let ((last-expr (list-ref f (- (length f) 1)))) (if (side-effect? last-expr env) (if (pair? last-expr) (check-returns caller last-expr env)) (lint-format "this is pointless~A: ~A in ~A" caller (local-line-number last-expr) (truncated-list->string last-expr) (truncated-list->string f)))))) ;; perhaps use truncated-lists->string here?? ((and) (let ((len (length f))) (case len ((1) (lint-format "this ~A is pointless" caller f)) ((2) (lint-format "perhaps ~A" caller (lists->string f (cadr f)))) ((3) (lint-format "perhaps ~A" caller (lists->string f `(if ,(cadr f) ,(caddr f))))) ; (begin (and x (display y)) (log z)) -> (if x (display y)) (else (lint-format "perhaps ~A" caller (lists->string f `(if ,(cadr f) (and ,@(cddr f))))))))) ((or) (let ((len (length f))) (case len ((1) (lint-format "this ~A is pointless" caller f)) ((2) (lint-format "perhaps ~A" caller (lists->string f (cadr f)))) ((3) (lint-format "perhaps ~A" caller (lists->string f `(if (not ,(cadr f)) ,(caddr f))))) (else (lint-format "perhaps ~A" caller (lists->string f `(if (not ,(cadr f)) (or ,@(cddr f))))))))) ((not) (lint-format "this ~A is pointless" caller f)) ((letrec letrec* with-let unless when begin with-baffle) (if (and (pair? (cdr f)) (pair? (cddr f))) (let ((last-expr (list-ref f (- (length f) 1)))) (if (side-effect? last-expr env) (if (pair? last-expr) (check-returns caller last-expr env)) ;; (begin (if x (begin (display x) z)) z) (lint-format "this is pointless~A: ~A in ~A" caller (local-line-number last-expr) (truncated-list->string last-expr) (truncated-list->string f)))))) ((do) (let ((returned (if (and (pair? (cdr f)) (pair? (cddr f))) (let ((end+res (caddr f))) (if (pair? (cdr end+res)) (list-ref end+res (- (length end+res) 1))))))) (if (or (eq? returned #<unspecified>) (and (pair? returned) (side-effect? returned env))) (if (pair? returned) (check-returns caller returned env)) ;; (begin (do ((i 0 (+ i 1))) ((= i 10) i) (display i)) x) (lint-format "~A: result ~A~A is not used" caller (truncated-list->string f) (truncated-list->string returned) (local-line-number returned))))) ((call-with-exit) (if (and (pair? (cdr f)) (pair? (cadr f)) (eq? (caadr f) 'lambda) (pair? (cdadr f)) (pair? (cadadr f))) (let ((return (car (cadadr f)))) (let walk ((tree (cddadr f))) (if (pair? tree) (if (eq? (car tree) return) (if (and (pair? (cdr tree)) (or (not (boolean? (cadr tree))) (pair? (cddr tree)))) ;; (begin (call-with-exit (lambda (quit) (if (< x 0) (quit (+ x 1))) (display x))) (+ x 2)) (lint-format "th~A call-with-exit return value~A will be ignored: ~A" caller (if (pair? (cddr tree)) (values "ese" "s") (values "is" "")) tree)) (for-each walk tree))))))) ((map) (if (pair? (cdr f)) ; (begin (map g123 x) x) (lint-format "map could be for-each: ~A" caller (truncated-list->string `(for-each ,@(cdr f)))))) ((reverse!) (if (pair? (cdr f)) ; (let ((x (list 23 1 3))) (reverse! x) x) (lint-format "~A might leave ~A in an undefined state; perhaps ~A" caller (car f) (cadr f) `(set! ,(cadr f) ,f)))) ((format) (if (and (pair? (cdr f)) (eq? (cadr f) #t)) ; (let () (format #t "~A" x) x) (lint-format "perhaps use () with format since the string value is discarded:~% ~A" caller `(format () ,@(cddr f))))))))) (define lint-current-form #f) (define lint-mid-form #f) (define (escape? form env) (and (pair? form) (let ((v (var-member (car form) env))) (if (var? v) (memq (var-definer v) '(call/cc call-with-current-continuation call-with-exit)) (memq (car form) '(error throw)))))) (define (lint-walk-body caller head body env) (when (pair? body) (when (and (pair? (car body)) (pair? (cdar body))) (when (and (not (eq? last-rewritten-internal-define (car body))) ; we already rewrote this (pair? (cdr body)) ; define->named let, but this is only ok in a "closed" situation, not (begin (define...)) for example (pair? (cadr body)) (memq (caar body) '(define define*)) (pair? (cadar body))) (let ((fname (caadar body)) (fargs (cdadar body)) (fbody (cddar body))) (when (and (symbol? fname) (proper-list? fargs) (= (tree-count1 fname (cdr body) 0) 1) (not (any? keyword? fargs))) (let ((call (find-call fname (cdr body)))) (when (pair? call) (let ((new-args (if (eq? (caar body) 'define) (map list fargs (cdr call)) (let loop ((pars fargs) (vals (cdr call)) (args ())) (if (null? pars) (reverse args) (loop (cdr pars) (if (pair? vals) (values (cdr vals) (cons (list ((if (pair? (car pars)) caar car) pars) (car vals)) args)) (values () (cons (if (pair? (car pars)) (car pars) (list (car pars) #f)) args)))))))) (new-let (if (eq? (caar body) 'define) 'let 'let*))) (if (and (pair? fbody) (pair? (cdr fbody)) (string? (car fbody))) (set! fbody (cdr fbody))) ;; (... (define* (f1 a b) (+ a b)) (f1 :c 1)) -> (... (let ((a :c) (b 1)) (+ a b))) (lint-format "perhaps ~A" caller (lists->string `(... ,@body) (if (= (tree-count2 fname body 0) 2) (if (null? fargs) (if (null? (cdr fbody)) `(... ,@(tree-subst (car fbody) call (cdr body))) `(... ,@(tree-subst `(let () ,@fbody) call (cdr body)))) `(... ,@(tree-subst `(let ,new-args ,@fbody) call (cdr body)))) `(... ,@(tree-subst `(,new-let ,fname ,new-args ,@fbody) call (cdr body)))))))))))) ;; look for non-function defines at the start of the body and use let(*) instead ;; we're in a closed body here, so the define can't propagate backwards (let ((first-expr (car body))) ;; another case: f(args) (let(...)set! arg < no let>) (when (and (eq? (car first-expr) 'define) (symbol? (cadr first-expr)) (pair? (cddr first-expr)) ;;(not (tree-car-member (cadr first-expr) (caddr first-expr))) ;;(not (tree-set-car-member '(lambda lambda*) (caddr first-expr))) (not (and (pair? (caddr first-expr)) (memq (caaddr first-expr) '(lambda lambda*))))) ;; this still is not ideal -- we need to omit let+lambda as well (do ((names ()) (letx 'let) (vars&vals ()) (p body (cdr p))) ((not (and (pair? p) (let ((expr (car p))) (and (pair? expr) (eq? (car expr) 'define) (symbol? (cadr expr)) (pair? (cddr expr)) ;;(not (tree-set-car-member '(lambda lambda*) (caddr expr))))) (not (and (pair? (caddr expr)) (memq (caaddr expr) '(lambda lambda*)))))))) ;; (... (define x 3) 32) -> (... (let ((x 3)) ...)) (lint-format "perhaps ~A" caller (lists->string `(... ,@body) `(... (,letx ,(reverse vars&vals) ...))))) ;; define acts like letrec(*), not let -- reference to name in lambda body is current name (let ((expr (cdar p))) (set! vars&vals (cons (if (< (tree-leaves (cdr expr)) 12) expr (list (car expr) '...)) vars&vals)) (if (tree-set-member names (cdr expr)) (set! letx 'let*)) (set! names (cons (car expr) names))))))) (let ((len (length body))) (when (> len 2) ; ... (define (x...)...) (x ...) -> (let (...) ...) or named let -- this happens a lot! (let ((n-1 (list-ref body (- len 2))) ; or (define (x ...)...) (some expr calling x once) -> named let etc (n (list-ref body (- len 1)))) (when (and (pair? n-1) (eq? (car n-1) 'define) (pair? (cadr n-1)) (symbol? (caadr n-1)) (proper-list? (cdadr n-1)) (pair? n) (or (and (eq? (car n) (caadr n-1)) (eqv? (length (cdadr n-1)) (length (cdr n)))) ; not values -> let! (and (< (tree-leaves n-1) 12) (tree-car-member (caadr n-1) (cdr n)) ; skip car -- see preceding (= (tree-count1 (caadr n-1) n 0) 1)))) (let ((outer-form (cond ((var-member :let env) => var-initial-value) (else #f))) (new-var (caadr n-1))) (when (and (pair? outer-form) (not (let walker ((tree outer-form)) ; check even the enclosing env -- define in do body back ref'd in stepper for example (or (eq? new-var tree) (and (pair? tree) (not (eq? n tree)) (not (eq? n-1 tree)) (not (eq? (car tree) 'quote)) (or (walker (car tree)) (walker (cdr tree)))))))) (let ((named (if (tree-memq new-var (cddr n-1)) (list new-var) ()))) (if (eq? (car n) (caadr n-1)) (lint-format "perhaps change ~A to a ~Alet: ~A" caller new-var (if (pair? named) "named " "") (lists->string outer-form `(... (let ,@named ,(map list (cdadr n-1) (cdr n)) ...)))) (let ((call (find-call new-var n))) (when (and (pair? call) (eqv? (length (cdadr n-1)) (length (cdr call)))) (let ((new-call `(let ,@named ,(map list (cdadr n-1) (cdr call)) ,@(cddr n-1)))) (lint-format "perhaps embed ~A: ~A" caller new-var (lists->string outer-form `(... ,(tree-subst new-call call n)))))))))))))) ;; this comment has strayed? ;; needs to check outer let also -- and maybe complain? [outer = form: we're already closed?] ;; bounds of closable context might be dependent on body length ;; (let ((outer-form (cond ((var-member :let env) => var-initial-value) (else #f))) ;; if used just once, move to that point in the expr+1? -- need to point it out somehow? (let ((suggest made-suggestion)) (when (and (> len 2) (not (tree-memq 'curlet (list-ref body (- len 1))))) (do ((q body (cdr q)) (k 0 (+ k 1))) ((null? q)) (let ((expr (car q))) (when (and (pair? expr) (eq? (car expr) 'define) (pair? (cdr expr)) (pair? (cddr expr)) (null? (cdddr expr))) (let ((name (and (symbol? (cadr expr)) (cadr expr)))) (when name (do ((last-ref k) (p (cdr q) (cdr p)) (i (+ k 1) (+ i 1))) ((null? p) (if (and (< k last-ref (+ k 2)) (pair? (list-ref body (+ k 1)))) (let ((end-dots (if (< last-ref (- len 1)) '(...) ())) (letx (if (tree-member name (cddr expr)) 'letrec 'let)) (use-expr (list-ref body (+ k 1))) (seen-earlier (or (var-member name env) (do ((s body (cdr s))) ((or (eq? s q) (and (pair? (car s)) (tree-memq name (car s)))) (not (eq? s q))))))) (cond (seen-earlier) ((not (eq? (car use-expr) 'define)) (let-temporarily ((target-line-length 120)) ;; (... (define f14 (lambda (x y) (if (positive? x) (+ x y) y))) (+ (f11 1 2) (f14 1 2))) -> ;; (... (let ((f14 (lambda (x y) (if (positive? x) (+ x y) y)))) (+ (f11 1 2) (f14 1 2)))) (lint-format "the scope of ~A could be reduced: ~A" caller name (truncated-lists->string `(... ,expr ,use-expr ,@end-dots) `(... (,letx ((,name ,(caddr expr))) ,use-expr) ,@end-dots))))) ((eq? (cadr use-expr) name) ;; (let () (display 33) (define x 2) (define x (+ x y)) (display 43)) -> ;; (... (set! x (+ x y)) ...) (lint-format "use set! to redefine ~A: ~A" caller name (lists->string `(... ,use-expr ,@end-dots) `(... (set! ,name ,(caddr use-expr)) ,@end-dots)))) ((pair? (cadr use-expr)) (if (symbol? (caadr use-expr)) (let-temporarily ((target-line-length 120)) ;; (let () (display 32) (define x 2) (define (f101 y) (+ x y)) (display 41) (f101 2)) -> ;; (... (define f101 (let ((x 2)) (lambda (y) (+ x y)))) ...) (lint-format "perhaps move ~A into ~A's closure: ~A" caller name (caadr use-expr) (truncated-lists->string `(... ,expr ,use-expr ,@end-dots) `(... (define ,(caadr use-expr) (,letx ((,name ,(caddr expr))) (lambda ,(cdadr use-expr) ,@(cddr use-expr)))) ,@end-dots)))))) ((and (symbol? (cadr use-expr)) (pair? (cddr use-expr))) (let-temporarily ((target-line-length 120)) (if (and (pair? (caddr use-expr)) (eq? (caaddr use-expr) 'lambda)) ;; (let () (display 34) (define x 2) (define f101 (lambda (y) (+ x y))) (display 41) (f101 2)) ;; (... (define f101 (let ((x 2)) (lambda (y) (+ x y)))) ...) (lint-format "perhaps move ~A into ~A's closure: ~A" caller name (cadr use-expr) (truncated-lists->string `(... ,expr ,use-expr ,@end-dots) `(... (define ,(cadr use-expr) (,letx ((,name ,(caddr expr))) ,(caddr use-expr))) ,@end-dots))) ;; (... (define lib (r file)) (define exports (caddr lib)) ...) -> ;; (... (define exports (let ((lib (r file))) (caddr lib))) ...) (lint-format "the scope of ~A could be reduced: ~A" caller name (truncated-lists->string `(... ,expr ,use-expr ,@end-dots) `(... (define ,(cadr use-expr) (,letx ((,name ,(caddr expr))) ,(caddr use-expr))) ,@end-dots)))))))) (when (and (> len 3) (< k last-ref (+ k 3)) ; larger cases happen very rarely -- 3 or 4 altogether (pair? (list-ref body (+ k 1))) (pair? (list-ref body (+ k 2)))) (let ((end-dots (if (< last-ref (- len 1)) '(...) ())) (letx (if (tree-member name (cddr expr)) 'letrec 'let)) (seen-earlier (or (var-member name env) (do ((s body (cdr s))) ((or (eq? s q) (and (pair? (car s)) (tree-memq name (car s)))) (not (eq? s q))))))) (unless seen-earlier (let ((use-expr1 (list-ref body (+ k 1))) (use-expr2 (list-ref body (+ k 2)))) (if (not (or (tree-set-member '(define lambda) use-expr1) (tree-set-member '(define lambda) use-expr2))) ;; (... (define f101 (lambda (y) (+ x y))) (display 41) (f101 2)) -> ;; (... (let ((f101 (lambda (y) (+ x y)))) (display 41) (f101 2))) (lint-format "the scope of ~A could be reduced: ~A" caller name (let-temporarily ((target-line-length 120)) (truncated-lists->string `(... ,expr ,use-expr1 ,use-expr2 ,@end-dots) `(... (,letx ((,name ,(caddr expr))) ,use-expr1 ,use-expr2) ,@end-dots))))))))))) (when (tree-memq name (car p)) (set! last-ref i))))))))) (when (= suggest made-suggestion) ;; look for define+binding-expr at end and combine (do ((prev-f #f) (fs body (cdr fs))) ((not (pair? fs))) (let ((f (car fs))) ;; define can come after the use, and in an open body can be equivalent to set!: ;; (let () (if x (begin (define y 12) (do ((i 0 (+ i 1))) ((= i y)) (f i))) (define y 21)) y) ;; (let () (define (f x) (+ y x)) (if z (define y 12) (define y 1)) (f 12)) ;; so we can't do this check in walk-open-body ;; ;; define + do -- if cadr prev-f not used in do inits, fold into do, else use let ;; the let case is semi-redundant (it's already reported elsewhere) (when (and (pair? prev-f) (pair? f) (eq? (car prev-f) 'define) (symbol? (cadr prev-f)) (not (hash-table-ref other-identifiers (cadr prev-f))) ; (cadr prev-f) already ref'd, so it's a member of env (or (null? (cdr fs)) (not (tree-memq (cadr prev-f) (cdr fs))))) (if (eq? (car f) 'do) ;; (... (define z (f x)) (do ((i z (+ i 1))) ((= i 3)) (display (+ z i))) ...) -> (do ((i (f x) (+ i 1))) ((= i 3)) (display (+ z i))) (lint-format "perhaps ~A" caller (lists->string `(... ,prev-f ,f ...) (if (any? (lambda (p) (tree-memq (cadr prev-f) (cadr p))) (cadr f)) (if (and (eq? (cadr prev-f) (cadr (caadr f))) (null? (cdadr f))) `(do ((,(caaadr f) ,(caddr prev-f) ,(caddr (caadr f)))) ,@(cddr f)) `(let (,(cdr prev-f)) ,f)) `(do (,(cdr prev-f) ,@(cadr f)) ,@(cddr f))))) ;; just changing define -> let seems officious, though it does reduce (cadr prev-f)'s scope (if (and (or (and (eq? (car f) 'let) (not (tree-memq (cadr prev-f) (cadr f)))) (eq? (car f) 'let*)) (not (symbol? (cadr f)))) (lint-format "perhaps ~A" caller (lists->string `(... ,prev-f ,f ,@(if (null? (cdr fs)) () '(...))) `(... (,(car f) (,(cdr prev-f) ,@(cadr f)) ...) ,@(if (null? (cdr fs)) () '(...)))))))) (set! prev-f f))))))) ;; definer as last in body is rare outside let-syntax, and tricky -- only one clear optimizable case found (lint-walk-open-body caller head body env)) (define (lint-walk-open-body caller head body env) ;; walk a body (a list of forms, the value of the last of which might be returned) (if (not (proper-list? body)) (lint-format "stray dot? ~A" caller (truncated-list->string body)) (let ((prev-f #f) (old-current-form lint-current-form) (old-mid-form lint-mid-form) (prev-len 0) (f-len 0) (repeats 0) (start-repeats body) (repeat-arg 0) (dpy-f #f) (dpy-start #f) (rewrote-already #f) (len (length body))) (if (eq? head 'do) (set! len (+ len 1))) ; last form in do body is not returned (when (and (pair? body) *report-function-stuff* (not (null? (cdr body)))) (function-match caller body env)) (do ((fs body (cdr fs)) (ctr 0 (+ ctr 1))) ((not (pair? fs))) (let* ((f (car fs)) (f-func (and (pair? f) (car f)))) (when (and (pair? f) (pair? (cdr f))) (if (eq? f-func 'define) (let ((vname (if (symbol? (cadr f)) (cadr f) (and (pair? (cadr f)) (symbol? (caadr f)) (caadr f))))) ;; if already in env, check shadowing request (if (and *report-shadowed-variables* (var-member vname env)) ;; (let ((f33 33)) (define f33 4) (g f33 1)) (lint-format "~A variable ~A in ~S shadows an earlier declaration" caller head vname f)))) ;; mid-body defines happen by the million, so resistance is futile ;; -------- repeated if/when etc -------- (when (and (pair? prev-f) ; (if A ...) (if A ...) -> (when A ...) or equivalents (memq (car prev-f) '(if when unless)) (memq f-func '(if when unless)) (pair? (cdr prev-f)) (pair? (cddr f)) ; possible broken if statement (pair? (cddr prev-f))) (define (tree-change-member set tree) (and (pair? tree) (not (eq? (car tree) 'quote)) (or (and (eq? (car tree) 'set!) (memq (cadr tree) set)) (tree-change-member set (car tree)) (tree-change-member set (cdr tree))))) (let ((test1 (cadr prev-f)) (test2 (cadr f))) (let ((equal-tests ; test1 = test2 (lambda () ;; (... (if (and A B) (f C)) (if (and B A) (g E) (h F)) ...) -> (... (if (and A B) (begin (f C) (g E)) (begin (h F))) ...) (lint-format "perhaps ~A" caller (lists->string `(... ,prev-f ,f ...) (if (eq? f-func 'if) (if (and (null? (cdddr prev-f)) (null? (cdddr f))) ;; if (null (cdr fs)) we have to make sure the returned value is not changed by our rewrite ;; but when/unless return their last value in s7 (or #<unspecified>), so I think this is ok (if (and (pair? test1) (eq? (car test1) 'not)) `(... (unless ,(cadr test1) ,@(unbegin (caddr prev-f)) ,@(unbegin (caddr f))) ...) `(... (when ,test1 ,@(unbegin (caddr prev-f)) ,@(unbegin (caddr f))) ...)) `(... (if ,test1 (begin ,@(unbegin (caddr prev-f)) ,@(unbegin (caddr f))) (begin ,@(if (pair? (cdddr prev-f)) (unbegin (cadddr prev-f)) ()) ,@(if (pair? (cdddr f)) (unbegin (cadddr f)) ()))) ...)) `(,f-func ,test1 ; f-func = when|unless ,@(cddr prev-f) ,@(cddr f))))))) (test1-in-test2 (lambda () (if (null? (cddr test2)) (set! test2 (cadr test2))) ;; (... (if A (f B)) (when (and A C) (g D) (h E)) ...) -> (... (when A (f B) (when C (g D) (h E))) ...) (lint-format "perhaps ~A" caller (lists->string `(... ,prev-f ,f ...) (if (or (null? (cdddr prev-f)) (eq? (car prev-f) 'when)) ; so prev-f is when or 1-arm if (as is f) `(... (when ,test1 ,@(cddr prev-f) (when ,test2 ,@(cddr f))) ,@(if (null? (cdr fs)) () '(...))) ;; prev-f is 2-arm if and f is when or 1-arm if (the other case is too ugly) `(... (if ,test1 (begin ,(caddr prev-f) (when ,test2 ,@(cddr f))) ,@(cdddr prev-f)) ...)))))) (test2-in-test1 (lambda () (if (null? (cddr test1)) (set! test1 (cadr test1))) ;; (... (if (and A B) (f C)) (if A (g E)) ...) -> (... (when A (when B (f C)) (g E))) (lint-format "perhaps ~A" caller (lists->string `(... ,prev-f ,f ...) (if (or (null? (cdddr f)) (eq? f-func 'when)) ; so f is when or 1-arm if (as is prev-f) `(... (when ,test2 (when ,test1 ,@(cddr prev-f)) ,@(cddr f)) ,@(if (null? (cdr fs)) () '(...))) ;; f is 2-arm if and prev-f is when or 1-arm if `(... (if ,test2 (begin (when ,test1 ,@(cddr prev-f)) ,(caddr f)) ,(cadddr f)) ,@(if (null? (cdr fs)) () '(...))))))))) (cond ((equal? test1 test2) (if (and (eq? f-func (car prev-f)) (not (side-effect? test1 env)) (not (tree-change-member (gather-symbols test1) (cdr prev-f)))) (equal-tests))) ((or (eq? f-func 'unless) (eq? (car prev-f) 'unless))) ; too hard! ;; look for test1 as member of test2 (so we can use test1 as the outer test) ((and (pair? test2) (eq? (car test2) 'and) (member test1 (cdr test2)) (or (eq? f-func 'when) ; f has to be when or 1-arm if (null? (cdddr f))) (or (pair? (cdr fs)) ; if prev-f has false branch, we have to ignore the return value of f (eq? (car prev-f) 'when) (null? (cdddr prev-f))) (not (side-effect? test2 env)) (not (tree-change-member (gather-symbols test1) (cddr prev-f)))) (set! test2 (remove test1 test2)) (test1-in-test2)) ;; look for test2 as member of test1 ((and (pair? test1) (eq? (car test1) 'and) (member test2 (cdr test1)) (or (eq? (car prev-f) 'when) ; prev-f has to be when or 1-arm if (null? (cdddr prev-f))) (not (side-effect? test1 env)) (not (tree-change-member (gather-symbols test2) (cddr prev-f)))) (set! test1 (remove test2 test1)) (test2-in-test1)) ;; look for some intersection of test1 and test2 ((and (pair? test1) (pair? test2) (eq? (car test1) 'and) (eq? (car test2) 'and) (not (side-effect? test1 env)) (not (side-effect? test2 env)) (not (tree-change-member (gather-symbols test2) (cddr prev-f)))) (let ((intersection ()) (new-test1 ()) (new-test2 ())) (for-each (lambda (tst) (if (member tst test2) (set! intersection (cons tst intersection)) (set! new-test1 (cons tst new-test1)))) (cdr test1)) (for-each (lambda (tst) (if (not (member tst test1)) (set! new-test2 (cons tst new-test2)))) (cdr test2)) (when (pair? intersection) (if (null? new-test1) (if (null? new-test2) (begin (set! test1 `(and ,@(reverse intersection))) (equal-tests)) (when (and (or (eq? f-func 'when) (null? (cdddr f))) (or (pair? (cdr fs)) (eq? (car prev-f) 'when) (null? (cdddr prev-f)))) (set! test1 `(and ,@(reverse intersection))) (set! test2 `(and ,@(reverse new-test2))) (test1-in-test2))) (if (null? new-test2) (when (or (eq? (car prev-f) 'when) (null? (cdddr prev-f))) (set! test2 `(and ,@(reverse intersection))) (set! test1 `(and ,@(reverse new-test1))) (test2-in-test1)) (when (and (or (eq? f-func 'when) (null? (cdddr f))) (or (eq? (car prev-f) 'when) (null? (cdddr prev-f)))) ;; (... (if (and A B) (f C)) (when (and B C) (g E)) ...) -> (... (when B (when A (f C)) (when C (g E)))) (lint-format "perhaps ~A" caller (let ((outer-test (if (null? (cdr intersection)) (car intersection) `(and ,@(reverse intersection))))) (set! new-test1 (if (null? (cdr new-test1)) (car new-test1) `(and ,@(reverse new-test1)))) (set! new-test2 (if (null? (cdr new-test2)) (car new-test2) `(and ,@(reverse new-test2)))) (lists->string `(... ,prev-f ,f ...) `(... (when ,outer-test (when ,new-test1 ,@(cddr prev-f)) (when ,new-test2 ,@(cddr f))) ,@(if (null? (cdr fs)) () '(...))))))))))))))))) ;; -------- ;; check for repeated calls, but only one arg currently can change (more args = confusing separation in code) (let ((feq (and (pair? prev-f) (pair? f) (eq? f-func (car prev-f)) (or (equal? (cdr f) (cdr prev-f)) (do ((fp (cdr f) (cdr fp)) (pp (cdr prev-f) (cdr pp)) (i 1 (+ i 1))) ((or (and (null? pp) (null? fp)) (not (pair? pp)) (not (pair? fp)) (if (= i repeat-arg) ; ignore the arg that's known to be changing (side-effect? (car pp) env) (and (not (equal? (car pp) (car fp))) (or (positive? repeat-arg) (and (set! repeat-arg i) ; call this one the changer #f))))) (and (null? pp) (null? fp)))))))) (if feq (set! repeats (+ repeats 1))) (when (or (not feq) (= ctr (- len 1))) ; this assumes we're not returning the last value? (when (and (> repeats 2) (not (hash-table-ref syntaces (car prev-f)))) ; macros should be ok here if args are constants (let ((fs-end (if (not feq) fs (cdr fs)))) (if (zero? repeat-arg) ; simple case -- all exprs are identical (let ((step 'i)) (if (tree-member step prev-f) (set! step (find-unique-name prev-f))) (lint-format "perhaps ~A... ->~%~NC(do ((~A 0 (+ ~A 1))) ((= ~A ~D)) ~A)" caller (truncated-list->string prev-f) pp-left-margin #\space step step step (+ repeats 1) prev-f)) (let ((args ()) (constants? #t) (func-name (car prev-f)) (new-arg (if (tree-member 'arg prev-f) (find-unique-name prev-f) 'arg))) (do ((p start-repeats (cdr p))) ((eq? p fs-end)) (set! args (cons (list-ref (car p) repeat-arg) args)) (if constants? (set! constants? (code-constant? (car args))))) (let ((func (if (and (= repeat-arg 1) (null? (cddar start-repeats))) func-name `(lambda (,new-arg) ,(let ((call (copy prev-f))) (list-set! call repeat-arg new-arg) call))))) (if constants? (lint-format "perhaps ~A... ->~%~NC(for-each ~S '(~{~S~^ ~}))" caller (truncated-list->string (car start-repeats)) pp-left-margin #\space func (map unquoted (reverse args))) (let ((v (var-member func-name env))) (if (or (and (var? v) (memq (var-ftype v) '(define define* lambda lambda*))) (procedure? (symbol->value func-name *e*))) ;; (let () (write-byte 0) (write-byte 1) (write-byte 2) (write-byte 3) (write-byte 4)) -> ;; (for-each write-byte '(0 1 2 3 4)) (lint-format "perhaps ~A... ->~%~NC(for-each ~S (vector ~{~S~^ ~}))" caller ;; vector rather than list because it is easier on the GC (list copies in s7) (truncated-list->string (car start-repeats)) pp-left-margin #\space func (reverse args)) (if (not (or (var? v) (macro? (symbol->value func-name *e*)))) ;; (let () (writ 0) (writ 1) (writ 2) (writ 3) (writ (* x 2))) -> (for-each writ (vector 0 1 2 3 (* x 2))) (lint-format "assuming ~A is not a macro, perhaps ~A" caller func-name (lists->string (list '... (car start-repeats) '...) `(for-each ,func (vector ,@(reverse args)))))))))))))) (set! repeats 0) (set! repeat-arg 0) (set! start-repeats fs))) ;; -------- (if (pair? f) (begin (set! f-len (length f)) (if (eq? f-func 'begin) (lint-format "redundant begin: ~A" caller (truncated-list->string f)))) (begin (if (symbol? f) (set-ref f caller f env)) (set! f-len 0))) ;; set-car! + set-cdr! here is usually "clever" code assuming eq?ness, so we can't rewrite it using cons ;; but copy does not create a new cons... [if at end of body, the return values will differ] (when (= f-len prev-len 3) (when (and (memq f-func '(set-car! set-cdr!)) ; ...(set-car! x (car y)) (set-cdr! x (cdr y))... -> (copy y x) (memq (car prev-f) '(set-car! set-cdr!)) (not (eq? (car prev-f) f-func)) (equal? (cadr f) (cadr prev-f))) (let ((ncar (caddr (if (eq? f-func 'set-car!) f prev-f))) (ncdr (caddr (if (eq? f-func 'set-car!) prev-f f)))) (if (and (pair? ncar) (eq? (car ncar) 'car) (pair? ncdr) (eq? (car ncdr) 'cdr) (equal? (cadr ncar) (cadr ncdr))) (lint-format "perhaps ~A~A ~A~A -> ~A" caller (if (= ctr 0) "" "...") (truncated-list->string prev-f) (truncated-list->string f) (if (= ctr (- len 1)) "" "...") `(copy ,(cadr ncar) ,(cadr f)))))) ;; successive if's that can be combined into case ;; else in last if could be accomodated as well (when (and (not rewrote-already) (eq? f-func 'if) (eq? (car prev-f) 'if) (pair? (cadr f)) (pair? (cadr prev-f)) (= (length f) 3) (= (length prev-f) 3) (memq (caadr prev-f) '(eq? eqv? = char=?)) ; not memx (memq (caadr f) '(eq? eqv? = char=?))) (let ((a1 (cadadr prev-f)) (a2 (caddr (cadr prev-f))) (b1 (cadadr f)) (b2 (caddr (cadr f)))) ; other possibilities are never hit (when (and (equal? a1 b1) (code-constant? a2) (code-constant? b2) (not (tree-change-member (list a1) (cddr prev-f)))) ; or any symbol in a1? (set! rewrote-already #t) ;; (... (if (= x 1) (display y)) (if (= x 2) (f y)) ...) -> (case x ((1) (display y)) ((2) (f y)) ((3) (display z))) (lint-format "perhaps ~A" caller (lists->string `(... ,prev-f ,f ...) `(case ,a1 ((,(unquoted a2)) ,@(unbegin (caddr prev-f))) ((,(unquoted b2)) ,@(unbegin (caddr f))) ,@(do ((more ()) (nfs (cdr fs) (cdr nfs))) ((let ((nf (if (pair? nfs) (car nfs) ()))) (not (and (pair? nf) (eq? (car nf) 'if) (= (length nf) 3) (pair? (cadr nf)) (memq (caadr nf) '(eq? eqv? = char=?)) (equal? a1 (cadadr nf)) (code-constant? (caddr (cadr nf)))))) ;; maybe add (not (tree-change-member (list a1) (cddr last-f))) ;; but it never is needed (reverse more)) (if (pair? nfs) (set! more (cons (cons (list (unquoted (caddr (cadar nfs)))) (unbegin (caddar nfs))) more)))))))))) (when (and (eq? f-func 'set!) (eq? (car prev-f) 'set!)) (let ((arg1 (caddr prev-f)) (arg2 (caddr f)) (settee (cadr f))) (if (eq? settee (cadr prev-f)) (cond ((not (and (pair? arg2) ; (set! x 0) (set! x 1) -> "this could be omitted: (set! x 0)" (tree-unquoted-member settee arg2))) (if (not (or (side-effect? arg1 env) (side-effect? arg2 env))) (lint-format "this could be omitted: ~A" caller prev-f))) ((and (pair? arg1) ; (set! x (cons 1 z)) (set! x (cons 2 x)) -> (set! x (cons 2 (cons 1 z))) (pair? arg2) (eq? (car arg1) 'cons) (eq? (car arg2) 'cons) (eq? settee (caddr arg2)) (not (eq? settee (cadr arg2)))) (lint-format "perhaps ~A ~A -> ~A" caller prev-f f `(set! ,settee (cons ,(cadr arg2) (cons ,@(cdr arg1)))))) ((and (pair? arg1) ; (set! x (append x y)) (set! x (append x z)) -> (set! x (append x y z)) (pair? arg2) (eq? (car arg1) 'append) (eq? (car arg2) 'append) (eq? settee (cadr arg1)) (eq? settee (cadr arg2)) (not (tree-memq settee (cddr arg1))) (not (tree-memq settee (cddr arg2)))) (lint-format "perhaps ~A ~A -> ~A" caller prev-f f `(set! ,settee (append ,settee ,@(cddr arg1) ,@(cddr arg2))))) ((and (= (tree-count1 settee arg2 0) 1) ; (set! x y) (set! x (+ x 1)) -> (set! x (+ y 1)) (or (not (pair? arg1)) (< (tree-leaves arg1) 5))) (lint-format "perhaps ~A ~A ->~%~NC~A" caller prev-f f pp-left-margin #\space (object->string `(set! ,settee ,(tree-subst arg1 settee arg2)))))) (if (and (symbol? (cadr prev-f)) ; (set! x (A)) (set! y (A)) -> (set! x (A)) (set! y x) (pair? arg1) ; maybe more trouble than it's worth (equal? arg1 arg2) (not (eq? (car arg1) 'quote)) (hash-table-ref no-side-effect-functions (car arg1)) (not (tree-unquoted-member (cadr prev-f) arg1)) (not (side-effect? arg1 env)) (not (maker? arg1))) (lint-format "perhaps ~A" caller (lists->string f `(set! ,settee ,(cadr prev-f))))))))) (if (< ctr (- len 1)) (begin ; f is not the last form, so its value is ignored (if (and (escape? f env) (pair? (cdr fs)) ; do special case (every? (lambda (arg) (not (and (symbol? arg) (let ((v (var-member arg env))) (and (var? v) (eq? (var-initial-value v) :call/cc)))))) (cdr f))) (if (= ctr (- len 2)) ;; (let () (error 'oops "an error") #t) (lint-format "~A makes this pointless: ~A" caller (truncated-list->string f) (truncated-list->string (cadr fs))) ;; (begin (stop) (exit 6) (print 4) (stop)) (lint-format "~A makes the rest of the body unreachable: ~A" caller (truncated-list->string f) (truncated-list->string (list '... (cadr fs) '...))))) (check-returns caller f env)) ;; here f is the last form in the body (when (and (pair? prev-f) (pair? (cdr prev-f))) (case (car prev-f) ((display write write-char write-byte) (if (and (equal? f (cadr prev-f)) (not (side-effect? f env))) ;; (cond ((= x y) y) (else (begin (display x) x))) (lint-format "~A returns its first argument, so this could be omitted: ~A" caller (car prev-f) (truncated-list->string f)))) ((vector-set! float-vector-set! int-vector-set! byte-vector-set! string-set! list-set! hash-table-set! let-set! set-car! set-cdr!) (if (equal? f (list-ref prev-f (- (length prev-f) 1))) ;; (begin (vector-set! x 0 (* y 2)) (* y 2)) (lint-format "~A returns the new value, so this could be omitted: ~A" caller (car prev-f) (truncated-list->string f))) (if (and (pair? f) (pair? (cdr f)) (eq? (cadr prev-f) (cadr f)) (not (code-constant? (cadr f))) (case (car prev-f) ((vector-set! float-vector-set! int-vector-set!) (memq f-func '(vector-ref float-vector-ref int-vector-ref))) ((list-set!) (eq? f-func 'list-ref)) ((string-set!) (eq? f-func 'string-ref)) ((set-car!) (eq? f-func 'car)) ((set-cdr!) (eq? f-func 'cdr)) (else #f)) (or (memq f-func '(car cdr)) ; no indices (and (pair? (cddr f)) ; for the others check that indices match (equal? (caddr f) (caddr prev-f)) (pair? (cdddr prev-f)) (not (pair? (cddddr prev-f))) (not (pair? (cdddr f))) (not (side-effect? (caddr f) env))))) ;; (let ((x (list 1 2))) (set-car! x 3) (car x)) (lint-format "~A returns the new value, so this could be omitted: ~A" caller (car prev-f) (truncated-list->string f)))) ((copy) (if (or (and (null? (cddr prev-f)) (equal? (cadr prev-f) f)) (and (pair? (cddr prev-f)) (null? (cdddr prev-f)) (equal? (caddr prev-f) f))) (lint-format "~A returns the new value, so ~A could be omitted" caller (truncated-list->string prev-f) (truncated-list->string f)))) ((set! define define* define-macro define-constant define-macro* defmacro defmacro* define-expansion define-bacro define-bacro*) (cond ((not (and (pair? (cddr prev-f)) ; (set! ((L 1) 2)) an error, but lint should keep going (or (and (equal? (caddr prev-f) f) ; (begin ... (set! x (...)) (...)) (not (side-effect? f env))) (and (symbol? f) ; (begin ... (set! x ...) x) (eq? f (cadr prev-f))) ; also (begin ... (define x ...) x) (and (not (eq? (car prev-f) 'set!)) (pair? (cadr prev-f)) ; (begin ... (define (x...)...) x) (eq? f (caadr prev-f))))))) ((not (memq (car prev-f) '(define define*))) (lint-format "~A returns the new value, so this could be omitted: ~A" caller (car prev-f) (truncated-list->string f))) ((symbol? (cadr prev-f)) (lint-format "perhaps omit ~A and return ~A" caller (cadr prev-f) (caddr prev-f))) ((= (tree-count2 f body 0) 2) ;; (let () (define (f1 x) (+ x 1)) f1) -> (lambda (x) ...) (lint-format "perhaps omit ~A, and change ~A" caller f (lists->string `(,(car prev-f) ,(cadr prev-f) ...) `(,(if (eq? (car prev-f) 'define) 'lambda 'lambda*) ,(cdadr prev-f) ...)))) (else (lint-format "~A returns the new value, so this could be omitted: ~A" caller (car prev-f) f))))))) ; possibly still not right if letrec? ;; needs f fs prev-f dpy-f dpy-start ctr len ;; trap lint-format (let ((dpy-case (and (pair? f) (memq f-func '(display write newline write-char write-string))))) ; flush-output-port? (when (and dpy-case (not dpy-start)) (set! dpy-f fs) (set! dpy-start ctr)) (when (and (integer? dpy-start) (> (- ctr dpy-start) (if dpy-case 1 2)) (or (= ctr (- len 1)) (not dpy-case))) ;; display sequence starts at dpy-start, goes to ctr (prev-f) unless not dpy-case (let ((ctrl-string "") (args ()) (dctr 0) (dpy-last (if (not dpy-case) prev-f f)) (op (write-port (car dpy-f))) (exprs (make-list (if dpy-case (- ctr dpy-start -1) (- ctr dpy-start)) ()))) (define* (gather-format str (arg :unset)) (set! ctrl-string (string-append ctrl-string str)) (unless (eq? arg :unset) (set! args (cons arg args)))) (call-with-exit (lambda (done) (for-each (lambda (d) (if (not (equal? (write-port d) op)) (begin (lint-format "unexpected port change: ~A -> ~A in ~A" caller op (write-port d) d) ; ?? (done))) (list-set! exprs dctr d) (set! dctr (+ dctr 1)) (gather-format (display->format d)) (when (eq? d dpy-last) ; op can be null => send to (current-output-port), return #f or #<unspecified> ;; (begin (display x) (newline) (display y) (newline)) -> (format () "~A~%~A~%" x y) (lint-format "perhaps ~A" caller (lists->string `(... ,@exprs) `(format ,op ,ctrl-string ,@(reverse args)))) (done))) dpy-f)))) (set! dpy-start #f)) (unless dpy-case (set! dpy-start #f))) (if (and (pair? f) (memq head '(defmacro defmacro* define-macro define-macro* define-bacro define-bacro*)) (tree-member 'unquote f)) (lint-format "~A probably has too many unquotes: ~A" caller head (truncated-list->string f))) (set! prev-f f) (set! prev-len f-len) (set! lint-current-form f) (if (= ctr (- len 1)) (set! env (lint-walk caller f env)) (begin (set! lint-mid-form f) (let ((e (lint-walk caller f env))) (if (and (pair? e) (not (memq (var-name (car e)) '(:lambda :dilambda)))) (set! env e))))) (set! lint-current-form #f) (set! lint-mid-form #f) ;; need to put off this ref tick until we have a var for it (lint-walk above) (when (and (= ctr (- len 1)) (pair? f) (pair? (cdr f))) (if (and (pair? (cadr f)) (memq f-func '(define define* define-macro define-constant define-macro* define-expansion define-bacro define-bacro*))) (set-ref (caadr f) caller #f env) (if (memq f-func '(defmacro defmacro*)) (set-ref (cadr f) caller #f env)))) )) (set! lint-mid-form old-mid-form) (set! lint-current-form old-current-form))) env) (define (check-sequence-constant function-name last) (let ((seq (if (not (pair? last)) last (and (eq? (car last) 'quote) (pair? (cdr last)) ; (quote . 1) (cadr last))))) (if (and (sequence? seq) (> (length seq) 0)) (begin (lint-format "returns ~A constant: ~A~S" function-name ; (define-macro (m a) `(+ 1 a)) (if (pair? seq) (values "a list" "'" seq) (values (prettify-checker-unq (->lint-type last)) "" seq))) (throw 'sequence-constant-done)) ; just report one constant -- the full list is annoying (when (pair? last) (case (car last) ((begin let let* letrec letrec* when unless with-baffle with-let) (when (pair? (cdr last)) (let ((len (length last))) (when (positive? len) (check-sequence-constant function-name (list-ref last (- len 1))))))) ((if) (when (and (pair? (cdr last)) (pair? (cddr last))) (check-sequence-constant function-name (caddr last)) (if (pair? (cdddr last)) (check-sequence-constant function-name (cadddr last))))) ((cond) (for-each (lambda (c) (if (and (pair? c) (pair? (cdr c))) (check-sequence-constant function-name (list-ref c (- (length c) 1))))) (cdr last))) ((case) (when (and (pair? (cdr last)) (pair? (cddr last))) (for-each (lambda (c) (if (and (pair? c) (pair? (cdr c))) (check-sequence-constant function-name (list-ref c (- (length c) 1))))) (cddr last)))) ((do) (if (and (pair? (cdr last)) (pair? (cddr last)) (pair? (caddr last)) (pair? (cdaddr last))) (check-sequence-constant function-name (list-ref (caddr last) (- (length (caddr last)) 1)))))))))) (define (lint-walk-function-body definer function-name args body env) ;; walk function body, with possible doc string at the start (when (and (pair? body) (pair? (cdr body)) (string? (car body))) (if *report-doc-strings* (lint-format "old-style doc string: ~S, in s7 use 'documentation:~%~NC~A" function-name (car body) (+ lint-left-margin 4) #\space (lint-pp `(define ,function-name (let ((documentation ,(car body))) (,(if (eq? definer 'define) 'lambda (if (eq? definer 'define*) 'lambda* definer)) ,args ,@(cdr body))))))) (set! body (cdr body))) ; ignore old-style doc-string ;; (set! arg ...) never happens as last in body ;; but as first in body, it happens ca 100 times (if (and (pair? body) (pair? (car body)) (eq? (caar body) 'set!) (or (eq? (cadar body) args) (and (pair? args) (memq (cadar body) args)))) ;; (define (f21 x y) (set! x 3) (+ y 1)) (lint-format "perhaps ~A" function-name (lists->string (car body) `(let ((,(cadar body) ,(caddar body))) ...)))) ;; as first in let of body, maybe a half-dozen (catch 'sequence-constant-done (lambda () (check-sequence-constant function-name (list-ref body (- (length body) 1)))) (lambda args #f)) (lint-walk-body function-name definer body env)) (define (lint-walk-function definer function-name args body form env) ;; check out function arguments (adding them to the current env), then walk its body ;; first check for (define (hi...) (ho...)) where ho has no opt args (and try to ignore possible string constant doc string) (when (eq? definer 'define) (let ((bval (if (and (pair? body) (string? (car body))) (cdr body) ; strip away the (old-style) documentation string body))) (cond ((not (and (pair? bval) ; not (define (hi a) . 1)! (pair? (car bval)) (null? (cdr bval)) (symbol? (caar bval))))) ; not (define (hi) ((if #f + abs) 0)) ((or (equal? args (cdar bval)) (and (hash-table-ref reversibles (caar bval)) (equal? args (reverse (cdar bval))))) (let* ((cval (caar bval)) (p (symbol->value cval *e*)) (ary (arity p))) (if (or (procedure? p) (let ((e (var-member cval env) )) (and e (var? e) (symbol? (var-ftype e)) (let ((def (var-initial-value e)) (e-args (var-arglist e))) (and (pair? def) (memq (var-ftype e) '(define lambda)) (or (and (null? args) (null? e-args)) (and (symbol? args) (symbol? e-args)) (and (pair? args) (pair? e-args) (= (length args) (length e-args))))))))) (lint-format "~A~A could be (define ~A ~A)" function-name (if (and (procedure? p) (not (= (car ary) (cdr ary))) (not (= (length args) (cdr ary)))) (format #f "leaving aside ~A's optional arg~P, " cval (- (cdr ary) (length args))) "") function-name function-name (if (equal? args (cdar bval)) cval (hash-table-ref reversibles (caar bval)))) (if (and (null? args) ; perhaps this can be extended to any equal args (null? (cdar bval))) ;; (define (getservent) (getserv)) -> (define getservent getserv) (lint-format "~A could probably be ~A" function-name (truncated-list->string form) (truncated-list->string `(define ,function-name ,cval))))))) ((and (or (symbol? args) (and (pair? args) (negative? (length args)))) (eq? (caar bval) 'apply) (pair? (cdar bval)) (symbol? (cadar bval)) (not (memq (cadar bval) '(and or))) (pair? (cddar bval)) (or (and (eq? args (caddar bval)) (null? (cdddar bval))) (and (pair? args) (equal? (cddar bval) (proper-list args))))) ;; (define (f1 . x) (apply + x)) -> (define f1 +) (lint-format "~A could be (define ~A ~A)" function-name function-name function-name (cadar bval))) ((and (hash-table-ref combinable-cxrs (caar bval)) (pair? (cadar bval))) ((lambda* (cr arg) (and cr (< (length cr) 5) (pair? args) (null? (cdr args)) (eq? (car args) arg) (let ((f (symbol "c" cr "r"))) (if (eq? f function-name) ;; (define (cadddr l) (caddr (cdr l))) (lint-format "this redefinition of ~A is pointless (use (with-let (unlet)...) or #_~A)" definer function-name function-name) ;; (define (f1 x) (cdr (car x))) -> (define f1 cdar) (lint-format "~A could be (define ~A ~A)" function-name function-name function-name f))))) (combine-cxrs (car bval)))) ((not (and (memq (caar bval) '(list-ref list-tail)) (pair? (cdar bval)) (pair? (cddar bval)) (pair? args) (eq? (car args) (cadar bval)) (null? (cdr args))))) ((eq? (caar bval) 'list-ref) (case (caddar bval) ((0) (lint-format "~A could be (define ~A car)" function-name function-name function-name)) ((1) (lint-format "~A could be (define ~A cadr)" function-name function-name function-name)) ((2) (lint-format "~A could be (define ~A caddr)" function-name function-name function-name)) ((3) (lint-format "~A could be (define ~A cadddr)" function-name function-name function-name)))) (else (case (caddar bval) ((1) (lint-format "~A could be (define ~A cdr)" function-name function-name function-name)) ((2) (lint-format "~A could be (define ~A cddr)" function-name function-name function-name)) ((3) (lint-format "~A could be (define ~A cdddr)" function-name function-name function-name)) ((4) (lint-format "~A could be (define ~A cddddr)" function-name function-name function-name))))))) (let ((fvar (and (symbol? function-name) (make-fvar :name (if (memq definer '(lambda lambda*)) :lambda (if (eq? definer 'dilambda) :dilambda function-name)) :ftype definer :initial-value form :env env :arglist (if (memq definer '(lambda lambda*)) (cadr form) ((if (memq definer '(defmacro defmacro*)) caddr cdadr) form)))))) (when fvar (let ((fvar-let (cdr fvar))) (set! (fvar-let 'decl) (catch #t (lambda () (case definer ((lambda) (set! (fvar-let 'allow-other-keys) #t) (eval (list definer (cadr form) #f))) ((lambda*) (set! (fvar-let 'allow-other-keys) (eq? (last-par (cadr form)) :allow-other-keys)) (eval (list definer (copy (cadr form)) #f))) ; eval can remove :allow-other-keys! ((define*) (set! (fvar-let 'allow-other-keys) (eq? (last-par (cdadr form)) :allow-other-keys)) (eval (list definer (cons '_ (copy (cdadr form))) #f))) ((defmacro defmacro*) (set! (fvar-let 'allow-other-keys) (or (not (eq? definer 'defmacro*)) (eq? (last-par (caddr form)) :allow-other-keys))) (eval (list definer '_ (caddr form) #f))) ((define-constant) (set! (fvar-let 'allow-other-keys) #t) (eval (list 'define (cons '_ (cdadr form)) #f))) (else (set! (fvar-let 'allow-other-keys) (or (not (memq definer '(define-macro* define-bacro*))) (eq? (last-par (cdadr form)) :allow-other-keys))) (eval (list definer (cons '_ (cdadr form)) #f))))) (lambda args 'error))))) (if (null? args) (begin (if (memq definer '(define* lambda* defmacro* define-macro* define-bacro*)) (lint-format "~A could be ~A" ; (define* (f1) 32) function-name definer (symbol (substring (symbol->string definer) 0 (- (length (symbol->string definer)) 1))))) (let ((cur-env (if fvar (cons fvar env) env))) (let ((nvars (let ((e (lint-walk-function-body definer function-name args body cur-env))) (and (not (eq? e cur-env)) (env-difference function-name e cur-env ()))))) (if (pair? nvars) (report-usage function-name definer nvars cur-env))) cur-env)) (if (not (or (symbol? args) (pair? args))) (begin (lint-format "strange ~A parameter list ~A" function-name definer args) env) (let ((args-as-vars (if (symbol? args) ; this is getting arg names to add to the environment (list (make-var :name args :definer 'parameter)) (map (lambda (arg) (if (symbol? arg) (if (memq arg '(:rest :allow-other-keys)) (values) ; omit :rest and :allow-other-keys (make-var :name arg :definer 'parameter)) (if (not (and (pair? arg) (= (length arg) 2) (memq definer '(define* lambda* defmacro* define-macro* define-bacro* definstrument define*-public)))) (begin (lint-format "strange parameter for ~A: ~S" function-name definer arg) (values)) (begin (if (not (cadr arg)) ; (define* (f4 (a #f)) a) (lint-format "the default argument value is #f in ~A ~A" function-name definer arg)) (make-var :name (car arg) :definer 'parameter))))) (proper-list args))))) (let* ((cur-env (cons (make-var :name :let :initial-value form :definer definer) (append args-as-vars (if fvar (cons fvar env) env)))) (nvars (let ((e (lint-walk-function-body definer function-name args body cur-env))) (and (not (eq? e cur-env)) (env-difference function-name e cur-env ()))))) (report-usage function-name definer (append (or nvars ()) args-as-vars) cur-env)) (when (and (var? fvar) (memq definer '(define lambda define-macro))) ;; look for unused parameters that are passed a value other than #f (let ((set ()) (unused ())) (for-each (lambda (arg-var) (if (zero? (var-ref arg-var)) (if (positive? (var-set arg-var)) (set! set (cons (var-name arg-var) set)) (if (not (memq (var-name arg-var) '(documentation signature iterator?))) (set! unused (cons (var-name arg-var) unused)))))) args-as-vars) (when (or (pair? set) (pair? unused)) (let ((proper-args (args->proper-list args))) (let ((sig (var-signature fvar)) (len (+ (length proper-args) 1))) (if (not sig) (set! sig (make-list len #t)) (if (< (length sig) len) (set! sig (copy sig (make-list len #t))))) (let ((siglist (cdr sig))) (for-each (lambda (arg) (if (memq arg unused) (set-car! siglist 'unused-parameter?) (if (memq arg set) (set-car! siglist 'unused-set-parameter?))) (set! siglist (cdr siglist))) proper-args)) (set! (var-signature fvar) sig)))))) (if fvar (cons fvar env) env)))))) (define (check-bool-cond caller form c1 c2 env) ;; (cond (x #f) (#t #t)) -> (not x) ;; c1/c2 = possibly combined, so in (cond (x #t) (y #t) (else #f)), c1: ((or x y) #t), so -> (or x y) (and (pair? c1) (= (length c1) 2) (pair? c2) (pair? (cdr c2)) (memq (car c2) '(#t else)) (or (and (boolean? (cadr c1)) (or (and (null? (cddr c2)) (boolean? (cadr c2)) (not (equal? (cadr c1) (cadr c2))) ; handled elsewhere (lint-format "perhaps ~A" caller (lists->string form (if (eq? (cadr c1) #t) (car c1) (simplify-boolean `(not ,(car c1)) () () env))))) (and (not (cadr c1)) ; (cond (x #f) (else y)) -> (and (not x) y) (let ((cc1 (simplify-boolean `(not ,(car c1)) () () env))) (lint-format "perhaps ~A" caller (lists->string form (if (null? (cddr c2)) `(and ,cc1 ,(cadr c2)) `(and ,cc1 (begin ,@(cdr c2)))))))) (and (pair? (car c1)) ; (cond ((null? x) #t) (else y)) -> (or (null? x) y) (eq? (return-type (caar c1) env) 'boolean?) (lint-format "perhaps ~A" caller (lists->string form (if (null? (cddr c2)) `(or ,(car c1) ,(cadr c2)) `(or ,(car c1) (begin ,@(cdr c2))))))))) (and (boolean? (cadr c2)) (null? (cddr c2)) (not (equal? (cadr c1) (cadr c2))) ;; (cond ((= 3 (length eq)) (caddr eq)) (else #f)) -> (and (= 3 (length eq)) (caddr eq)) (lint-format "perhaps ~A" caller (lists->string form (if (cadr c2) `(or (not ,(car c1)) ,(cadr c1)) (if (and (pair? (car c1)) (eq? (caar c1) 'and)) (append (car c1) (cdr c1)) `(and ,@c1))))))))) (define (case-branch test eqv-select exprs) (case (car test) ((eq? eqv? = equal? char=?) (if (equal? eqv-select (cadr test)) `((,(unquoted (caddr test))) ,@exprs) `((,(unquoted (cadr test))) ,@exprs))) ((memq memv member) `(,(unquoted (caddr test)) ,@exprs)) ((not) `((#f) ,@exprs)) ((null?) `((()) ,@exprs)) ((eof-object?) `((#<eof>) ,@exprs)) ((zero?) `((0 0.0) ,@exprs)) ((boolean?) `((#t #f) ,@exprs)) ((char-ci=?) (if (equal? eqv-select (cadr test)) `(,(list (caddr test) (other-case (caddr test))) ,@exprs) `(,(list (cadr test) (other-case (cadr test))) ,@exprs))) (else `(,(map (lambda (p) (case (car p) ((eq? eqv? = equal? char=?) (unquoted ((if (equal? eqv-select (cadr p)) caddr cadr) p))) ((memq memv member) (apply values (caddr p))) ((not) #f) ((null?) ()) ((eof-object?) #<eof>) ((zero?) (values 0 0.0)) ((boolean?) (values #t #f)) ((char-ci=?) (if (equal? eqv-select (cadr p)) (values (caddr p) (other-case (caddr p))) (values (cadr p) (other-case (cadr p))))) (else (error "oops")))) (cdr test)) ,@exprs)))) (define (cond->case eqv-select new-clauses) `(case ,eqv-select ,@(map (lambda (clause) (let ((test (car clause)) (exprs (cdr clause))) (if (null? exprs) ; cond returns the test result if no explicit results (set! exprs (list #t))) ; but all tests here return a boolean, and we win only if #t?? (memx is an exception) (if (memq test '(else #t)) `(else ,@exprs) (case-branch test eqv-select exprs)))) new-clauses))) (define (eqv-code-constant? x) (or (number? x) (char? x) (and (pair? x) (eq? (car x) 'quote) (or (symbol? (cadr x)) (and (not (pair? (cadr x))) (eqv-code-constant? (cadr x))))) (memq x '(#t #f () #<unspecified> #<undefined> #<eof>)))) (define (cond-eqv? clause eqv-select or-ok) (if (not (pair? clause)) (memq clause '(else #t)) ;; it's eqv-able either directly or via memq/memv, or via (or ... eqv-able clauses) ;; all clauses involve the same (eventual case) selector (case (car clause) ((eq? eqv? = equal? char=? char-ci=?) (if (eqv-code-constant? (cadr clause)) (equal? eqv-select (caddr clause)) (and (eqv-code-constant? (caddr clause)) (equal? eqv-select (cadr clause))))) ((memq memv member) (and (equal? eqv-select (cadr clause)) (pair? (caddr clause)) (eq? (caaddr clause) 'quote) (or (not (eq? (car clause) 'member)) (every? (lambda (x) (or (number? x) (char? x) (symbol? x) (memq x '(#t #f () #<unspecified> #<undefined> #<eof>)))) (cdr (caddr clause)))))) ((or) (and or-ok (every? (lambda (p) (cond-eqv? p eqv-select #f)) (cdr clause)))) ((not null? eof-object? zero? boolean?) (equal? eqv-select (cadr clause))) (else #f)))) (define (find-constant-exprs caller vars body) (if (or (tree-set-member '(call/cc call-with-current-continuation lambda lambda* define define* define-macro define-macro* define-bacro define-bacro* define-constant define-expansion) body) (let set-walk ((tree body)) ; generalized set! causes confusion (and (pair? tree) (or (and (eq? (car tree) 'set!) (pair? (cdr tree)) (pair? (cadr tree))) (set-walk (car tree)) (set-walk (cdr tree)))))) () (let ((refs (let ((vs (out-vars caller vars body))) (remove-if (lambda (v) (or (assq v vars) ; vars = do-loop steppers (memq v (cadr vs)))) ; (cadr vs) = sets (car vs)))) ;; refs are the external variables accessed in the do-loop body ;; that are not set or shadowed or changed (vector-set! etc) (constant-exprs ())) (let expr-walk ((tree body)) (when (pair? tree) (if (let all-ok? ((tree tree)) (if (symbol? tree) (memq tree refs) (or (not (pair? tree)) (eq? (car tree) 'quote) (and (hash-table-ref no-side-effect-functions (car tree)) (or (not (hash-table-ref syntaces (car tree))) (memq (car tree) '(if begin cond or and unless when))) (not (hash-table-ref makers (car tree))) (list? (cdr tree)) (every? all-ok? (cdr tree)))))) (if (not (or (eq? (car tree) 'quote) (member tree constant-exprs))) (set! constant-exprs (cons tree constant-exprs))) (begin (if (pair? (car tree)) (expr-walk (car tree))) (when (pair? (cdr tree)) (let ((f (cdr tree))) (case (car f) ((case) (when (and (pair? (cdr f)) (pair? (cddr f))) (expr-walk (cadr f)) (for-each (lambda (c) (expr-walk (cdr c))) (cddr f)))) ((letrec letrec*) (when (pair? (cddr f)) (for-each (lambda (c) (if (and (pair? c) (pair? (cdr c))) (expr-walk (cadr c)))) (cadr f)) (expr-walk (cddr f)))) ((let let*) (when (pair? (cddr f)) (if (symbol? (cadr f)) (set! f (cdr f))) (for-each (lambda (c) (if (and (pair? c) (pair? (cdr c))) (expr-walk (cadr c)))) (cadr f)) (expr-walk (cddr f)))) ((do) (when (and (list? (cadr f)) (list? (cddr f)) (pair? (cdddr f))) (for-each (lambda (c) (if (pair? (cddr c)) (expr-walk (caddr c)))) (cadr f)) (expr-walk (cdddr f)))) (else (for-each expr-walk f))))))))) (when (pair? constant-exprs) (set! constant-exprs (remove-if (lambda (p) (or (null? (cdr p)) (and (null? (cddr p)) (memq (car p) '(not -)) (symbol? (cadr p))) (tree-unquoted-member 'port-line-number p))) constant-exprs))) constant-exprs))) (define (partition-form start len) (let ((ps (make-vector len)) (qs (make-vector len))) (do ((i 0 (+ i 1)) (p start (cdr p))) ((= i len)) (set! (ps i) (cadar p)) (set! (qs i) (reverse (cadar p)))) (let ((header-len (length (ps 0)))) (let ((trailer-len header-len) (result-min-len header-len)) (do ((i 1 (+ i 1))) ((= i len)) (set! result-min-len (min result-min-len (length (ps i)))) (do ((k 1 (+ k 1)) (p (cdr (ps i)) (cdr p)) (f (cdr (ps 0)) (cdr f))) ((or (= k header-len) (not (pair? p)) (not (equal? (car p) (car f)))) (set! header-len k))) (do ((k 0 (+ k 1)) (q (qs i) (cdr q)) (f (qs 0) (cdr f))) ((or (= k trailer-len) (not (pair? q)) (not (equal? (car q) (car f)))) (set! trailer-len k)))) (if (= result-min-len header-len) (begin (set! header-len (- header-len 1)) (set! trailer-len 0))) (if (<= result-min-len (+ header-len trailer-len)) (set! trailer-len (- result-min-len header-len 1))) (values header-len trailer-len result-min-len))))) (define (one-call-and-dots body) ; body is unchanged here, so it's not interesting (if (< (tree-leaves body) 30) (if (null? (cdr body)) body (list (car body) '...)) (if (pair? (car body)) (list (list (caar body) '...)) (list (car body) '...)))) (define (replace-redundant-named-let caller form outer-name outer-args inner) (when (proper-list? outer-args) ; can be null (let ((inner-name (cadr inner)) (inner-args (caddr inner)) (inner-body (cdddr inner))) (do ((p outer-args (cdr p)) (a inner-args (cdr a))) ((or (null? p) (not (pair? a)) (not (pair? (car a))) (and (not (eq? (car p) (caar a))) (tree-memq (car p) inner-body))) ;; args can be reversed, but rarely match as symbols (when (and (null? p) (or (null? a) (and (null? (cdr a)) (code-constant? (cadar a))))) (let* ((args-match (do ((p outer-args (cdr p)) (a inner-args (cdr a))) ((or (null? p) (not (eq? (car p) (caar a))) (not (eq? (caar a) (cadar a)))) (null? p)))) (args-aligned (and (not args-match) (do ((p outer-args (cdr p)) (a inner-args (cdr a))) ((or (null? p) (not (eq? (car p) (cadar a)))) (null? p)))))) (when (or args-match args-aligned) (let ((definer (if (null? a) 'define 'define*)) (extras (if (and (pair? a) (quoted-null? (cadar a))) (list (list (caar a) ())) a))) ;; (define (f61 x) (let loop ((y x)) (if (positive? y) (loop (- y 1)) 0))) -> (define (f61 y) (if (positive? y) (f61 (- y 1)) 0)) (lint-format "~A ~A" caller (if (null? a) "perhaps" "a toss-up -- perhaps") (lists->string form `(,definer (,outer-name ,@(if args-match outer-args (do ((result ()) (p outer-args (cdr p)) (a inner-args (cdr a))) ((null? p) (reverse result)) (set! result (cons (caar a) result)))) ,@extras) ,@(tree-subst outer-name inner-name inner-body))))))))))))) (define (set!? form env) (and *report-any-!-as-setter* ; (inc! x) when inc! is unknown, assume it sets x (symbol? (car form)) (pair? (cdr form)) (or (symbol? (cadr form)) (and (pair? (cddr form)) (symbol? (caddr form)))) (not (var-member (car form) env)) (not (hash-table-ref built-in-functions (car form))) (let ((str (symbol->string (car form)))) (char=? (string-ref str (- (length str) 1)) #\!)))) (define (set-target name form env) (and (pair? form) (or (and (pair? (cdr form)) (or (eq? (cadr form) name) ; (pop! x) (and (pair? (cddr form)) ; (push! y x) (eq? (caddr form) name))) (or (eq? (car form) 'set!) ; (set! x y) (set!? form env))) (set-target name (car form) env) (set-target name (cdr form) env)))) (define (check-definee caller sym form env) (cond ((keyword? sym) ; (define :x 1) (lint-format "keywords are constants ~A" caller sym)) ((and (eq? sym 'pi) ; (define pi (atan 0 -1)) (member (caddr form) '((atan 0 -1) (acos -1) (* 2 (acos 0)) (* 4 (atan 1)) (* 4 (atan 1 1))))) (lint-format "~A is one of its many names, but pi is a predefined constant in s7" caller (caddr form))) ((constant? sym) ; (define most-positive-fixnum 432) (lint-format "~A is a constant in s7: ~A" caller sym form)) ((eq? sym 'quote) (lint-format "either a stray quote, or a real bad idea: ~A" caller (truncated-list->string form))) ((pair? sym) (check-definee caller (car sym) form env)) ((let ((v (var-member sym env))) (and (var? v) (eq? (var-definer v) 'define-constant) (not (equal? (caddr form) (var-initial-value v))))) => (lambda (v) (let ((line (if (and (pair? (var-initial-value v)) (positive? (pair-line-number (var-initial-value v)))) (format #f "(line ~D): " (pair-line-number (var-initial-value v))) ""))) (lint-format "~A in ~A is already a constant, defined ~A~A" caller sym (truncated-list->string form) line (truncated-list->string (var-initial-value v)))))))) (define binders (let ((h (make-hash-table))) (for-each (lambda (op) (set! (h op) #t)) '(let let* letrec letrec* do lambda lambda* define define* call/cc call-with-current-continuation define-macro define-macro* define-bacro define-bacro* define-constant define-expansion load eval eval-string require)) h)) (define lint-let-reduction-factor 3) ; maybe make this a global switch -- the higher this number, the fewer let-reduction suggestions (define walker-functions (let ((h (make-hash-table))) ;; ---------------- define ---------------- (let () (define (define-walker caller form env) (if (< (length form) 2) (begin (lint-format "~S makes no sense" caller form) env) (let ((sym (cadr form)) (val (cddr form)) (head (car form))) (if (symbol? sym) (begin (check-definee caller sym form env) (if (memq head '(define define-constant define-envelope define-public define*-public defmacro-public define-inlinable define-integrable define^)) (let ((len (length form))) (if (not (= len 3)) ; (define a b c) (lint-format "~A has ~A value~A?" caller (truncated-list->string form) (if (< len 3) (values "no" "") (values "too many" "s"))))) (lint-format "~A is messed up" caller (truncated-list->string form))) (if (not (pair? val)) env (begin (if (and (null? (cdr val)) (equal? sym (car val))) ; (define a a) (lint-format "this ~A is either not needed, or is an error: ~A" caller head (truncated-list->string form))) (if (not (pair? (car val))) (begin (if (not (memq caller '(module cond-expand))) (cond ((hash-table-ref other-identifiers sym) => (lambda (p) (lint-format "~A is used before it is defined: ~A" caller sym form))))) (cons (make-var :name sym :initial-value (car val) :definer head) env)) (let ((e (lint-walk (if (and (pair? (car val)) (eq? (caar val) 'letrec)) 'define sym) (car val) env))) (if (or (not (pair? e)) (eq? e env) (not (memq (var-name (car e)) '(:lambda :dilambda)))) ; (define x (lambda ...)) (cons (make-var :name sym :initial-value (car val) :definer head) env) (begin (set! (var-name (car e)) sym) (let ((val (caddr form))) (when (and (eq? (car val) 'lambda) ; (define sym (lambda args (let name...))), let here happens rarely (proper-list? (cadr val)) (pair? (caddr val)) (null? (cdddr val)) (eq? (caaddr val) 'let) (symbol? (cadr (caddr val)))) (replace-redundant-named-let caller form sym (cadr val) (caddr val)))) ;; (define x (letrec ((y (lambda...))) (lambda (...) (y...)))) -> (define (x...)...) (let* ((let-form (cdaddr form)) (var (and (pair? (car let-form)) (null? (cdar let-form)) ; just one var in let/rec (caar let-form)))) ;; let-form here can be cdr of (lambda...) or (let|letrec ... lambda) (when (and (pair? var) (symbol? (car var)) (pair? (cdr let-form)) (pair? (cadr let-form)) (null? (cddr let-form)) ; just one form in the let/rec (pair? (cdr var)) (pair? (cadr var)) (pair? (cdadr var)) (eq? (caadr var) 'lambda) ; var is lambda (proper-list? (cadadr var))) ; it has no rest arg (let ((body (cadr let-form))) (when (and (eq? (car body) 'lambda) ; let/rec body is lambda calling var (proper-list? (cadr body)) ; rest args are a headache (pair? (caddr body))) ; (lambda (...) (...) where car is letrec func name (if (eq? (caaddr body) (car var)) (lint-format "perhaps ~A" caller (lists->string form `(define (,sym ,@(cadr body)) (let ,(car var) ,(map list (cadadr var) (cdaddr body)) ,@(cddadr var))))) (let ((call (find-call (car var) (caddr body)))) (when (and (pair? call) ; inner lambda body is (...some-expr...(sym...) ...) (= (tree-count1 (car var) (caddr body) 0) 1)) (let ((new-call `(let ,(car var) ,(map list (cadadr var) (cdr call)) ,@(cddadr var)))) (lint-format "perhaps ~A" caller (lists->string form `(define (,sym ,@(cadr body)) ,(tree-subst new-call call (caddr body))))))))))))) (when (and *report-function-stuff* (pair? (caddr (var-initial-value (car e))))) (hash-table-set! equable-closures (caaddr (var-initial-value (car e))) (cons (car e) (or (hash-table-ref equable-closures (caaddr (var-initial-value (car e)))) ())))) e))))))) ; symbol? sym ;; not (symbol? sym) (if (and (pair? sym) ; cadr form (pair? val) ; cddr form (not (pair? (car sym)))) ; pair would indicate a curried func or something equally stupid (let ((outer-args (cdr sym)) (outer-name (car sym))) (cond ((not *report-forward-functions*)) ;; need to ignore macro usages here -- this happens ca 20000 times! ((hash-table-ref other-identifiers (car sym)) => (lambda (p) (lint-format "~A is used before it is defined" caller (car sym))))) (check-definee caller (car sym) form env) (when (pair? (car val)) (when (eq? (caar val) 'let) (when (pair? (cadar val)) (do ((inner-vars (cadar val)) (p outer-args (cdr p))) ((not (pair? p))) (cond ((assq (car p) inner-vars) => (lambda (v) (if (eq? (cadr v) (car p)) ;; (define (f70 a b) (let ((a a) (b b)) (+ a b))) (lint-format "in ~A this let binding is pointless: ~A" caller (truncated-list->string form) v))))))) ;; define + redundant named-let -- sometimes rewrites to define* (when (and (symbol? (cadar val)) (null? (cdr val))) (replace-redundant-named-let caller form outer-name outer-args (car val)))) ;; perhaps this block should be on a *report-* switch -- ;; it translates some internal defines into named lets ;; (or just normal lets, etc) ;; this is not redundant given the walk-body translations because here ;; we have the outer parameters and can check those against the inner ones ;; leading (sometimes) to much nicer rewrites. (when (and (eq? (caar val) 'define) ; define* does not happen here (pair? (cdr val)) (pair? (cadar val))) ; inner define (name ...) (let ((inner-name (caadar val)) (inner-args (cdadar val)) (inner-body (cddar val)) (outer-body (cdddr form))) (when (and (symbol? inner-name) (proper-list? inner-args) (pair? (car outer-body)) (= (tree-count1 inner-name outer-body 0) 1)) (let ((call (find-call inner-name outer-body))) (when (pair? call) (set! last-rewritten-internal-define (car val)) (let ((new-call (if (tree-memq inner-name inner-body) (if (and (null? inner-args) (null? outer-args)) (if (null? (cdr inner-body)) (car (tree-subst outer-name inner-name inner-body)) `(begin ,@(tree-subst outer-name inner-name inner-body))) `(let ,inner-name ,(if (null? inner-args) () (map list inner-args (cdr call))) ,@inner-body)) (if (or (null? inner-args) (and (equal? inner-args outer-args) (equal? inner-args (cdr call)))) (if (null? (cdr inner-body)) (car (tree-subst outer-name inner-name inner-body)) `(begin ,@(tree-subst outer-name inner-name inner-body))) `(let ,(map list inner-args (cdr call)) ,@inner-body))))) ;; (define (f11 a b) (define (f12 a b) (if (positive? a) (+ a b) b)) (f12 a b)) -> ;; (define (f11 a b) (if (positive? a) (+ a b) b)) (lint-format "perhaps ~A" caller (lists->string form `(,head ,sym ,@(let ((p (tree-subst new-call call outer-body))) (if (and (pair? p) (pair? (car p)) (eq? (caar p) 'begin)) (cdar p) p)))))))))))) (when (pair? outer-args) (if (repeated-member? (proper-list outer-args) env) (lint-format "~A parameter is repeated: ~A" caller head (truncated-list->string sym))) (cond ((memq head '(define* define-macro* define-bacro* define*-public)) (check-star-parameters outer-name outer-args env)) ((list-any? keyword? outer-args) (lint-format "~A parameter can't be a keyword: ~A" caller outer-name sym)) ((memq 'pi outer-args) (lint-format "~A parameter can't be a constant: ~A" caller outer-name sym))) ;; look for built-in names used as parameter names and used as functions internally(!) ;; this requires a tree walker to ignore (for example) (let loop ((string string))...) (for-each (lambda (p) (let ((par (if (pair? p) (car p) p))) (when (or (hash-table-ref built-in-functions par) (hash-table-ref syntaces par)) (let ((call (call-with-exit (lambda (return) (let loop ((tree (cddr form))) (if (pair? tree) (if (eq? (car tree) par) (return tree) (case (car tree) ((quote) #f) ((let let*) (if (pair? (cdr tree)) (if (symbol? (cadr tree)) (if (not (tree-memq par (caddr tree))) (loop (cdddr tree))) (if (not (tree-memq par (cadr tree))) (loop (cddr tree)))))) ((letrec letrec*) (if (and (pair? (cdr tree)) (not (tree-memq par (cadr tree)))) (loop (cddr tree)))) ((do) (if (and (pair? (cdr tree)) (pair? (cddr tree)) (not (tree-memq par (cadr tree)))) (loop (cdddr tree)))) (else (if (pair? (cdr tree)) (for-each loop (cdr tree))) (if (pair? (car tree)) (loop (car tree)))))))))))) (if (and (pair? call) (pair? (cdr call)) (not (eq? par (cadr call)))) (lint-format* caller ; (define (f50 abs) (abs -1)) (string-append (object->string outer-name) "'s parameter " (symbol->string par)) (string-append " is called " (truncated-list->string call)) ": find a less confusing parameter name!")))))) outer-args)) (when (and (eq? head 'define-macro) (pair? val) (null? (cdr val))) (let ((body (car val))) (if (and (null? outer-args) ; look for C macros translated as define-macro! -- this happens a lot sad to say (or (not (symbol? body)) (keyword? body)) (or (not (pair? body)) (and (eq? (car body) 'quote) (not (symbol? (cadr body))) (or (not (pair? (cadr body))) (eq? (caadr body) 'quote))) (not (or (memq (car body) '(quote quasiquote list cons append)) (tree-set-member '(#_{list} #_{apply_values} #_{append}) body))))) (lint-format "perhaps ~A or ~A" caller (lists->string form `(define ,outer-name ,(unquoted (car val)))) (truncated-list->string `(define (,outer-name) ,(unquoted (car val)))))) (when (pair? body) (case (car body) ((#_{list}) (when (and (quoted-symbol? (cadr body)) (proper-list? outer-args)) (if (and (equal? (cddr body) outer-args) (or (not (hash-table-ref syntaces (cadadr body))) ; (define-macro (x y) `(lambda () ,y)) (memq (cadadr body) '(set! define)))) (lint-format "perhaps ~A" caller (lists->string form `(define ,outer-name ,(cadadr body)))) (if (and (not (hash-table-ref syntaces (cadadr body))) (not (any-macro? (cadadr body) env)) (every? (lambda (a) (or (code-constant? a) (and (memq a outer-args) (= (tree-count1 a (cddr body) 0) 1)))) (cddr body))) ;; marginal -- there are many debatable cases here (lint-format "perhaps ~A" caller (lists->string form `(define (,outer-name ,@outer-args) (,(cadadr body) ,@(map unquoted (cddr body))))))))) (let ((pargs (args->proper-list outer-args))) (for-each (lambda (p) (if (and (pair? p) (eq? (car p) 'quote) (pair? (cdr p)) (pair? (cadr p)) (tree-set-member pargs (cadr p))) (lint-format "missing comma? ~A" caller form))) (cdr body)))) ((quote) ;; extra comma (unquote) is already caught elsewhere (if (and (pair? (cdr body)) (pair? (cadr body)) (tree-set-member (args->proper-list outer-args) (cadr body))) (lint-format "missing comma? ~A" caller form))))))) (if (and (eq? head 'definstrument) (string? (car val))) (set! val (cdr val))) (if (keyword? outer-name) env (lint-walk-function head outer-name outer-args val form env))) (begin ; not (and (pair? sym)...) (lint-format "strange form: ~A" head (truncated-list->string form)) (when (and (pair? sym) (pair? (car sym))) (let ((outer-args (cdr sym)) (outer-name (if (eq? head 'define*) (remove :optional (car sym)) (car sym)))) (if (symbol? (car outer-name)) ;; perhaps a curried definition -- as a public service, we'll rewrite the dumb thing (begin (lint-format "perhaps ~A" caller (lists->string form `(,head ,outer-name (lambda ,outer-args ,@(cddr form))))) (lint-walk-function head (car outer-name) (cdr outer-name) val form env)) ;val=(cddr form) I think (when (pair? (car outer-name)) (if (symbol? (caar outer-name)) (begin (lint-format "perhaps ~A" caller (lists->string form `(,head ,(car outer-name) (lambda ,(cdr outer-name) (lambda ,outer-args ,@(cddr form)))))) (lint-walk-function head (caar outer-name) (cdar outer-name) val form env)) (when (and (pair? (caar outer-name)) (symbol? (caaar outer-name))) (lint-format "perhaps ~A" caller (lists->string form `(,head ,(caar outer-name) (lambda ,(cdar outer-name) (lambda ,(cdr outer-name) (lambda ,outer-args ,@(cddr form))))))) (lint-walk-function head (caaar outer-name) (cdaar outer-name) val form env))))))) env)))))) (for-each (lambda (op) (hash-table-set! h op define-walker)) '(define define* define-constant define-macro define-macro* define-bacro define-bacro* define-expansion definstrument defanimal define-envelope ; for clm define-public define*-public defmacro-public define-inlinable define-integrable define^))) ; these give more informative names in Guile and scmutils (MIT-scheme)) ;; ---------------- dilambda ---------------- (let () (define (dilambda-walker caller form env) ;(format *stderr* "~A~%" form) (let ((len (length form))) (if (not (= len 3)) (begin (lint-format "dilambda takes two arguments: ~A" caller (truncated-list->string form)) env) (let ((getter (cadr form)) (setter (caddr form))) (lint-walk caller setter env) (let ((e (lint-walk caller getter env))) ; goes to lint-walk-function -> :lambda as first in e (if (and (pair? e) (eq? (var-name (car e)) :lambda)) (set! (var-name (car e)) :dilambda)) e))))) (hash-table-set! h 'dilambda dilambda-walker)) ;; ---------------- lambda ---------------- (let () (define (lambda-walker caller form env) (let ((len (length form)) (head (car form))) (if (< len 3) (begin (lint-format "~A is messed up in ~A" caller head (truncated-list->string form)) env) (let ((args (cadr form))) (when (list? args) (let ((arglen (length args))) (if (null? args) (if (eq? head 'lambda*) ; (lambda* ()...) -> (lambda () ...) (lint-format "lambda* could be lambda ~A" caller form)) (begin ; args is a pair ; (lambda (a a) ...) (let ((val (caddr form))) (if (and (pair? val) (eq? (car val) 'let) (pair? (cadr val))) (do ((inner-vars (cadr val)) (p (cadr form) (cdr p))) ((not (pair? p))) (cond ((assq (car p) inner-vars) => (lambda (v) (if (eq? (cadr v) (car p)) (lint-format "in ~A this let binding is pointless: ~A" caller (truncated-list->string form) v)))))))) (if (repeated-member? (proper-list args) env) (lint-format "~A parameter is repeated: ~A" caller head (truncated-list->string args))) (if (eq? head 'lambda*) ; (lambda* (a :b) ...) (check-star-parameters head args env) (if (list-any? keyword? args) ; (lambda (:key) ...) (lint-format "lambda arglist can't handle keywords (use lambda*)" caller))))) (when (and (eq? head 'lambda) ; (lambda () (f)) -> f, (lambda (a b) (f a b)) -> f (not (eq? caller 'case-lambda)) (= len 3) (>= arglen 0)) ; not a dotted list (let ((body (caddr form))) (cond ((not (and (pair? body) (symbol? (car body)) (not (memq (car body) '(and or)))))) ((equal? args (cdr body)) ;; (lambda (a b) (> a b)) -> > (lint-format "perhaps ~A" caller (lists->string form (car body)))) ((equal? (reverse args) (cdr body)) (let ((rf (hash-table-ref reversibles (car body)))) ;; (lambda (a b) (> b a)) -> < (if rf (lint-format "perhaps ~A" caller (lists->string form rf))))) ((and (= arglen 1) (hash-table-ref combinable-cxrs (car body))) ((lambda* (cr arg) ; lambda* not lambda because combine-cxrs might return just #f (and cr (< (length cr) 5) (eq? (car args) arg) ;; (lambda (x) (cdr (cdr (car x)))) -> cddar (lint-format "perhaps ~A" caller (lists->string form (symbol "c" cr "r"))))) (combine-cxrs body)))))))) (if (and (or (symbol? args) ; (lambda args (apply f args)) -> f (and (pair? args) ; (lambda #\a ...) ! (negative? (length args)))) (eq? head 'lambda) (not (eq? caller 'case-lambda)) (= len 3)) (let ((body (caddr form))) (if (and (pair? body) (eq? (car body) 'apply) (pair? (cdr body)) (symbol? (cadr body)) (not (memq (cadr body) '(and or))) (pair? (cddr body)) (or (eq? args (caddr body)) (and (pair? args) (equal? (cddr body) (proper-list args))))) ;; (lambda args (apply + args)) -> + (lint-format "perhaps ~A" caller (lists->string form (cadr body)))))) (lint-walk-function head caller args (cddr form) form env) ;; not env as return value here -- return the lambda+old env via lint-walk-function )))) (hash-table-set! h 'lambda lambda-walker) (hash-table-set! h 'lambda* lambda-walker)) ;; ---------------- set! ---------------- (let () (define (set-walker caller form env) (if (not (= (length form) 3)) (begin (lint-format "set! has too ~A arguments: ~S" caller (if (> (length form) 3) "many" "few") form) env) (let ((settee (cadr form)) (setval (caddr form))) (if (symbol? setval) (set-ref setval caller form env)) (let ((result (lint-walk caller setval env))) (if (symbol? settee) (if (constant? settee) ; (set! pi 3) (lint-format "can't set! ~A (it is a constant)" caller (truncated-list->string form)) (let ((v (var-member settee env))) (if (and (var? v) (eq? (var-definer v) 'define-constant)) (let ((line (if (and (pair? (var-initial-value v)) (positive? (pair-line-number (var-initial-value v)))) (format #f "(line ~D): " (pair-line-number (var-initial-value v))) ""))) (lint-format "can't set! ~A in ~A (it is a constant: ~A~A)" caller settee (truncated-list->string form) line (truncated-list->string (var-initial-value v))))))) (if (not (pair? settee)) ; (set! 3 1) (lint-format "can't set! ~A" caller (truncated-list->string form)) (begin (if (memq (car settee) '(vector-ref list-ref string-ref hash-table-ref)) ;; (set! (vector-ref v 0) 3) (lint-format "~A as target of set!~A" caller (car settee) (truncated-list->string form))) (lint-walk caller settee env) ; this counts as a reference since it's by reference so to speak ;; try type check (dilambda signatures) (when (symbol? (car settee)) (let ((f (symbol->value (car settee) *e*))) (when (dilambda? f) (let ((sig (procedure-signature (procedure-setter f))) (settee-len (length settee))) (when (and (pair? sig) (positive? settee-len) (pair? (list-tail sig settee-len))) (let ((checker (list-ref sig settee-len)) (arg-type (->lint-type setval))) (when (and (symbol? checker) (not (compatible? checker arg-type))) ;; (set! (print-length) "asd") (lint-format "~A: new value should be a~A ~A: ~S: ~A" caller (car settee) (if (char=? (string-ref (format #f "~A" checker) 0) #\i) "n" "") checker arg-type (truncated-list->string form))))))))) (set! settee (do ((sym (car settee) (car sym))) ((not (pair? sym)) sym)))))) (if (symbol? (cadr form)) ; see do directly above -- sets settee so we have to go back to (cadr form) (set-set (cadr form) caller form env) (if (and (pair? (cadr form)) (symbol? settee)) (set-ref settee caller `(implicit-set ,@(cdr form)) env))) (if (equal? (cadr form) setval) ; not settee here! ; (set! a a) (lint-format "pointless set! ~A" caller (truncated-list->string form))) (when (and (pair? setval) (symbol? settee)) (case (car setval) ((if) ; (set! x (if y x 1)) -> (if (not y) (set! x 1)) (if (= (length setval) 4) (if (eq? settee (caddr setval)) (lint-format "perhaps ~A" caller (lists->string form `(if (not ,(cadr setval)) (set! ,settee ,(cadddr setval))))) (if (eq? settee (cadddr setval)) (lint-format "perhaps ~A" caller (lists->string form `(if ,(cadr setval) (set! ,settee ,(caddr setval))))))))) ((or) ; (set! x (or x y)) -> (if (not x) (set! x y)) (if (and (= (length setval) 3) ; the other case here is not improved by using 'if (eq? settee (cadr setval))) (lint-format "perhaps ~A" caller (lists->string form `(if (not ,settee) (set! ,settee ,(caddr setval))))))) ((and) (if (= (length setval) 3) ; (set! x (and x y)) -> (if x (set! x y)) (if (eq? settee (cadr setval)) (lint-format "perhaps ~A" caller (lists->string form `(if ,settee (set! ,settee ,(caddr setval))))) (if (eq? settee (caddr setval)) (lint-format "perhaps ~A" caller (lists->string form `(if (not ,(cadr setval)) (set! ,settee #f)))))))))) result)))) (hash-table-set! h 'set! set-walker)) ;; ---------------- quote ---------------- (let () (define (quote-walker caller form env) (let ((len (length form))) (if (negative? len) (lint-format "stray dot in quote's arguments? ~S" caller form) (if (not (= len 2)) (lint-format "quote has too ~A arguments: ~S" caller (if (> len 2) "many" "few") form) (let ((arg (cadr form))) (if (pair? arg) (if (> (length arg) 8) (hash-table-set! big-constants arg (+ 1 (or (hash-table-ref big-constants arg) 0)))) (unless (or (>= quote-warnings 20) (and (symbol? arg) (not (keyword? arg)))) (set! quote-warnings (+ quote-warnings 1)) ; (char? '#\a) (lint-format "quote is not needed here: ~A~A" caller ; this is by far the most common message from lint (truncated-list->string form) (if (= quote-warnings 20) "; will ignore this error henceforth." "")))))))) env) (hash-table-set! h 'quote quote-walker)) ;; ---------------- if ---------------- (let () (define (if-walker caller form env) (let ((len (length form))) (if (> len 4) (lint-format "if has too many clauses: ~A" caller (truncated-list->string form)) (if (< len 3) (lint-format "if has too few clauses: ~A" caller (truncated-list->string form)) (let ((test (cadr form)) (true (caddr form)) (false (if (= len 4) (cadddr form) 'no-false)) (expr (simplify-boolean (cadr form) () () env)) (suggestion made-suggestion) (true-op (and (pair? (caddr form)) (caaddr form))) (false-op (and (= len 4) (pair? (cadddr form)) (car (cadddr form))))) (if (eq? false #<unspecified>) (lint-format "this #<unspecified> is redundant: ~A" caller form)) (if (and (symbol? test) (pair? true) (memq test true)) (and-incomplete form 'if test true env) (when (pair? test) (if (and (eq? (car test) 'not) (symbol? (cadr test)) (pair? false) (memq (cadr test) false)) (and-incomplete form 'if2 (cadr test) false env)) (if (and (hash-table-ref bools (car test)) (pair? true)) (if (member (cadr test) true) (and-forgetful form 'if test true env) (do ((p true (cdr p))) ((or (not (pair? p)) (and (pair? (car p)) (member (cadr test) (car p)))) (if (pair? p) (and-forgetful form 'if test (car p) env))))) (if (and (eq? (car test) 'not) (pair? (cadr test)) (pair? false) (hash-table-ref bools (caadr test))) (if (member (cadadr test) false) (and-forgetful form 'if2 (cadr test) false env) (do ((p false (cdr p))) ((or (not (pair? p)) (and (pair? (car p)) (member (cadadr test) (car p)))) (if (pair? p) (and-forgetful form 'if2 (cadr test) (car p) env))))))))) (when (and (pair? true) (pair? false) (not (memq true-op (list 'quote {list}))) (not (any-macro? true-op env)) (or (not (hash-table-ref syntaces true-op)) (memq true-op '(let let* set! and or begin))) (pair? (cdr true))) (define (tree-subst-eq new old tree) ;; tree-subst above substitutes every occurence of 'old with 'new, so we check ;; in advance that 'old only occurs once in the tree (via tree-count1). Here ;; 'old may occur any number of times, but we want to change it only once, ;; so we keep the actual pointer to it and use eq?. (This assumes no shared code?) (cond ((eq? old tree) (cons new (cdr tree))) ((not (pair? tree)) tree) ((eq? (car tree) 'quote) (copy-tree tree)) (else (cons (tree-subst-eq new old (car tree)) (tree-subst-eq new old (cdr tree)))))) ;; maybe move the unless before this (let ((diff (let differ-in-one ((p true) (q false)) (and (pair? p) (pair? q) (if (equal? (car p) (car q)) (differ-in-one (cdr p) (cdr q)) (and (equal? (cdr p) (cdr q)) (or (and (pair? (car p)) (not (eq? (caar p) 'quote)) (pair? (car q)) (not (eq? (caar q) 'quote)) (differ-in-one (car p) (car q))) (list p (list (car p) (car q)))))))))) (if (pair? diff) (unless (or (and (equal? true-op (caadr diff)) ; (if x (+ y 1) (- y 1)) -- are we trying to keep really simple stuff out? (or (hash-table-ref syntaces true-op) (hash-table-ref syntaces false-op)) (any? pair? (cdr true))) ; (if x (set! y (+ x 1)) (set! y 1)) (and (eq? true-op 'set!) ; (if x (set! y w) (set! z w)) (equal? (caar diff) (cadr true)))) (let ((subst-loc (car diff))) ;; for let/let* if tree-subst position can't affect the test, just subst, else save test first ;; named let diff in args gets no hits (if (memq true-op '(let let*)) (if (not (or (symbol? (cadr true)) ; assume named let is moving an if outside the loop (eq? subst-loc (cdr true)))) ; avoid confusion about the vars list (let ((vars (cadr true))) ;; (if x (let ((y (abs x))) (display z) y) (let ((y (log x))) (display z) y)) -> (let ((y ((if x abs log) x))) (display z) y) (lint-format "perhaps ~A" caller (lists->string form (if (and (pair? vars) (case true-op ((let) (tree-memq subst-loc vars)) ((let*) (tree-memq subst-loc (car vars))) (else #f))) (tree-subst-eq `(if ,expr ,@(cadr diff)) subst-loc true) `(let ((_1_ ,expr)) ,(tree-subst-eq `(if _1_ ,@(cadr diff)) subst-loc true))))))) ;; also not any-macro? (car true|false) probably ;; (if x (set! y #t) (set! y #f)) -> (set! y x) (lint-format "perhaps ~A" caller (lists->string form (cond ((eq? true-op (caadr diff)) ; very common! ;; (if x (f y) (g y)) -> ((if x f g) y) ;; but f and g can't be or/and unless there are no expressions ;; I now like all of these -- originally found them odd: CL influence! (if (equal? true-op test) `((or ,test ,false-op) ,@(cdr true)) `((if ,test ,true-op ,false-op) ,@(cdr true)))) ((and (eq? (caadr diff) #t) (not (cadadr diff))) ;; (if x (set! y #t) (set! y #f)) -> (set! y x) (tree-subst-eq test subst-loc true)) ((and (not (caadr diff)) (eq? (cadadr diff) #t)) ;; (if x (set! y #f) (set! y #t)) -> (set! y (not x)) (tree-subst-eq (simplify-boolean `(not ,expr) () () env) subst-loc true)) ((equal? (caadr diff) test) ;; (if x (set! y x) (set! y 21)) -> (set! y (or x 21)) (tree-subst-eq (simplify-boolean `(or ,@(cadr diff)) () () env) subst-loc true)) ((or (memq true-op '(set! begin and or)) (let list-memq ((a subst-loc) (lst true)) (and (pair? lst) (or (eq? a lst) (list-memq a (cdr lst)))))) ;; (if x (set! y z) (set! y w)) -> (set! y (if x z w)) ;; true op moved out, if expr moved in ;; (if A (and B C) (and B D)) -> (and B (if A C D)) ;; here differ-in-one means that preceding/trailing stuff must subst-loc exactly (tree-subst-eq `(if ,expr ,@(cadr diff)) subst-loc true)) ;; paranoia... normally the extra let is actually not needed, ;; but it's very hard to distinguish the bad cases (else `(let ((_1_ ,expr)) ,(tree-subst-eq `(if _1_ ,@(cadr diff)) subst-loc true))))))))) ;; else not pair? diff (unless (memq true-op '(let let*)) ;; differ-in-trailers can (sometimes) take advantage of values (let ((enddiff (let differ-in-trailers ((p true) (q false) (c 0)) (and (pair? p) (pair? q) (if (equal? (car p) (car q)) (differ-in-trailers (cdr p) (cdr q) (+ c 1)) (and (> c 1) (let ((op (if (memq true-op '(and or + * begin max min)) true-op 'values))) (list p (if (null? (cdr p)) (car p) `(,op ,@p)) (if (null? (cdr q)) (car q) `(,op ,@q)))))))))) ;; (if A (+ B C E) (+ B D)) -> (+ B (if A (+ C E) D)) ;; if p/q null, don't change because for example ;; (if A (or B C) (or B C D F)) can't be (or B C (if A ...)) ;; but if this were not and/or, it could be (+ B (if A C (values C D F))) (if (pair? enddiff) (lint-format "perhaps ~A" caller (lists->string form (tree-subst `((if ,expr ,@(cdr enddiff))) (car enddiff) true))) ;; differ-in-headers looks for equal trailers ;; (if A (+ B B E C) (+ D D E C)) -> (+ (if A (+ B B) (+ D D)) E C) ;; these are not always (read: almost never) an improvement (when (and (eq? true-op false-op) (not (eq? true-op 'values)) (or (not (eq? true-op 'set!)) (equal? (cadr true) (cadr false)))) (let ((headdiff (let differ-in-headers ((p (cdr true)) (q (cdr false)) (c 0) (rp ()) (rq ())) (and (pair? p) (pair? q) (if (equal? p q) (and (> c 0) ; once case is handled elsewhere? (list p (reverse rp) (reverse rq))) (differ-in-headers (cdr p) (cdr q) (+ c 1) (cons (car p) rp) (cons (car q) rq))))))) (when (pair? headdiff) (let ((op (if (memq true-op '(and or + * begin max min)) true-op 'values))) (let ((tp (if (null? (cdadr headdiff)) (caadr headdiff) `(,op ,@(cadr headdiff)))) (tq (if (null? (cdaddr headdiff)) (caaddr headdiff) `(,op ,@(caddr headdiff))))) ;; (if A (+ B B E C) (+ D D E C)) -> (+ (if A (+ B B) (+ D D)) E C) (lint-format "perhaps ~A" caller (lists->string form `(,true-op (if ,expr ,tp ,tq) ,@(car headdiff))))))))))))))) ;; (when (and (pair? true)...) ;; end tree-subst section (unless (= last-if-line-number line-number) (do ((iff form (cadddr iff)) (iffs 0 (+ iffs 1))) ((not (and (<= iffs 2) (pair? iff) (= (length iff) 4) (eq? (car iff) 'if))) (when (or (> iffs 2) (and (= iffs 2) (pair? iff) (= (length iff) 3) (eq? (car iff) 'if))) (set! last-if-line-number line-number) ;; (if a b (if c d (if e f g))) -> (cond (a b) (c d) (e f) (else g)) (lint-format "perhaps use cond: ~A" caller (lists->string form `(cond ,@(do ((iff form (cadddr iff)) (clauses ())) ((not (and (pair? iff) (= (length iff) 4) (eq? (car iff) 'if))) (append (reverse clauses) (if (and (pair? iff) (= (length iff) 3) (eq? (car iff) 'if)) `((,(cadr iff) ,@(unbegin (caddr iff)))) `((else ,@(unbegin iff)))))) (set! clauses (cons (cons (cadr iff) (unbegin (caddr iff))) clauses)))))))))) (if (never-false test) (lint-format "if test is never false: ~A" caller (truncated-list->string form)) (if (and (never-true test) true) ; complain about (if #f #f) later ;; (if #f x y) (lint-format "if test is never true: ~A" caller (truncated-list->string form)))) (cond ((side-effect? test env)) ((or (equal? test true) ; (if x x y) -> (or x y) (equal? expr true)) (lint-format "perhaps ~A" caller (lists->string form (simplify-boolean (if (eq? false 'no-false) `(or ,expr #<unspecified>) `(or ,expr ,false)) () () env)))) ((or (equal? test `(not ,true)) ; (if x (not x) y) -> (and (not x) y) (equal? `(not ,test) true)) ; (if (not x) x y) -> (and x y) (lint-format "perhaps ~A" caller (lists->string form (simplify-boolean (if (eq? false 'no-false) `(and ,true #<unspecified>) `(and ,true ,false)) () () env)))) ((or (equal? test false) ; (if x y x) -> (and x y) (equal? expr false)) (lint-format "perhaps ~A" caller (lists->string form (simplify-boolean `(and ,expr ,true) () () env)))) ((or (equal? `(not ,test) false) ; (if x y (not x)) -> (or (not x) y) (equal? test `(not ,false))) ; (if (not x) y x) -> (or x y) (lint-format "perhaps ~A" caller (lists->string form (simplify-boolean `(or ,false ,true) () () env))))) (when (= len 4) (when (and (pair? true) (eq? true-op 'if)) (let ((true-test (cadr true)) (true-true (caddr true))) (if (= (length true) 4) (let ((true-false (cadddr true))) (if (equal? expr (simplify-boolean `(not ,true-test) () () env)) ;; (if a (if (not a) B C) A) -> (if a C A) (lint-format "perhaps ~A" caller (lists->string form `(if ,expr ,true-false ,false)))) (if (equal? expr true-test) ;; (if x (if x z w) y) -> (if x z y) (lint-format "perhaps ~A" caller (lists->string form `(if ,expr ,true-true ,false)))) (if (equal? false true-false) ;; (if a (if b B A) A) -> (if (and a b) B A) (lint-format "perhaps ~A" caller (lists->string form (simplify-boolean (if (not false) `(and ,expr ,true-test ,true-true) `(if (and ,expr ,true-test) ,true-true ,false)) () () env))) (if (equal? false true-true) ;; (if a (if b A B) A) -> (if (and a (not b)) B A) (lint-format "perhaps ~A" caller (lists->string form (simplify-boolean (if (not false) `(and ,expr (not ,true-test) ,true-false) `(if (and ,expr (not ,true-test)) ,true-false ,false)) () () env))))) ;; (if a (if b d e) (if c d e)) -> (if (if a b c) d e)? reversed does not happen. ;; (if a (if b d) (if c d)) -> (if (if a b c) d) ;; (if a (if b d e) (if (not b) d e)) -> (if (eq? (not a) (not b)) d e) (when (and (pair? false) (eq? false-op 'if) (= (length false) 4) (not (equal? true-test (cadr false))) (equal? (cddr true) (cddr false))) (let ((false-test (cadr false))) (lint-format "perhaps ~A" caller (lists->string form (cond ((and (pair? true-test) (eq? (car true-test) 'not) (equal? (cadr true-test) false-test)) `(if (not (eq? (not ,expr) ,true-test)) ,@(cddr true))) ((and (pair? false-test) (eq? (car false-test) 'not) (equal? true-test (cadr false-test))) `(if (eq? (not ,expr) ,false-test) ,@(cddr true))) ((> (+ (tree-leaves expr) (tree-leaves true-test) (tree-leaves false-test)) 12) `(let ((_1_ (if ,expr ,true-test ,false-test))) (if _1_ ,@(cddr true)))) (else `(if (if ,expr ,true-test ,false-test) ,@(cddr true))))))))) (begin ; (length true) != 4 (if (equal? expr (simplify-boolean `(not ,true-test) () () env)) (lint-format "perhaps ~A" caller ; (if a (if (not a) B) A) -> (if (not a) A) (lists->string form `(if (not ,expr) ,false)))) (if (equal? expr true-test) ; (if x (if x z) w) -> (if x z w) (lint-format "perhaps ~A" caller (lists->string form `(if ,expr ,true-true ,false)))) (if (equal? false true-true) ; (if a (if b A) A) (lint-format "perhaps ~A" caller (let ((nexpr (simplify-boolean `(or (not ,expr) ,true-test) () () env))) (lists->string form `(if ,nexpr ,false))))))))) (when (pair? false) (case false-op ((cond) ; (if a A (cond...)) -> (cond (a A) ...) (lint-format "perhaps ~A" caller (lists->string form `(cond (,expr ,true) ,@(cdr false))))) ((if) (when (= (length false) 4) (let ((false-test (cadr false)) (false-true (caddr false)) (false-false (cadddr false))) (if (equal? true false-true) ;; (if a A (if b A B)) -> (if (or a b) A B) (lint-format "perhaps ~A" caller (if (and (pair? false-false) (eq? (car false-false) 'if) (equal? true (caddr false-false))) (lists->string form (let ((nexpr (simplify-boolean `(or ,expr ,false-test ,(cadr false-false)) () () env))) `(if ,nexpr ,true ,@(cdddr false-false)))) (if true (let ((nexpr (simplify-boolean `(or ,expr ,false-test) () () env))) (lists->string form `(if ,nexpr ,true ,false-false))) (lists->string form (simplify-boolean `(and (not (or ,expr ,false-test)) ,false-false) () () env))))) (if (equal? true false-false) ;; (if a A (if b B A)) -> (if (or a (not b)) A B) (lint-format "perhaps ~A" caller (if true (let ((nexpr (simplify-boolean `(or ,expr (not ,false-test)) () () env))) (lists->string form `(if ,nexpr ,true ,false-true))) (lists->string form (simplify-boolean `(and (not (or ,expr (not ,false-test))) ,false-true) () () env)))))))) (if (and (pair? true) (eq? true-op 'if) (= (length true) 3) (= (length false) 3) (equal? (cddr true) (cddr false))) ;; (if a (if b d) (if c d)) -> (if (if a b c) d) (lint-format "perhaps ~A" caller (lists->string form (if (> (+ (tree-leaves expr) (tree-leaves (cadr true)) (tree-leaves (cadr false))) 12) `(let ((_1_ (if ,expr ,(cadr true) ,(cadr false)))) (if _1_ ,@(cddr true))) `(if (if ,expr ,(cadr true) ,(cadr false)) ,@(cddr true))))))) ((map) ; (if (null? x) () (map abs x)) -> (map abs x) (if (and (pair? test) (eq? (car test) 'null?) (or (null? true) (equal? true (cadr test))) (equal? (cadr test) (caddr false)) (or (null? (cdddr false)) (not (side-effect? (cdddr false) env)))) (lint-format "perhaps ~A" caller (lists->string form false)))) ((case) (if (and (pair? expr) (cond-eqv? expr (cadr false) #t)) ;; (if (eof-object? x) 32 (case x ((#\\a) 3) (else 4))) -> (case x ((#<eof>) 32) ((#\\a) 3) (else 4)) (lint-format "perhaps ~A" caller (lists->string form `(case ,(cadr false) ,(case-branch expr (cadr false) (list true)) ,@(cddr false)))))))) ) ; (= len 4) (if (pair? false) (let ((false-test (and (pair? (cdr false)) (cadr false)))) (if (and (eq? false-op 'if) ; (if x 3 (if (not x) 4)) -> (if x 3 4) (pair? (cdr false)) (not (side-effect? test env))) (if (or (equal? test false-test) (equal? expr false-test)) (lint-format "perhaps ~A" caller (lists->string form `(if ,expr ,true ,@(cdddr false)))) (if (and (pair? false-test) (eq? (car false-test) 'not) (or (equal? test (cadr false-test)) (equal? expr (cadr false-test)))) (lint-format "perhaps ~A" caller (lists->string form `(if ,expr ,true ,(caddr false))))))) (if (and (eq? false-op 'if) ; (if test0 expr (if test1 expr)) -> if (or test0 test1) expr) (null? (cdddr false)) ; other case is dealt with above (equal? true (caddr false))) (let ((test1 (simplify-boolean `(or ,expr ,false-test) () () env))) (lint-format "perhaps ~A" caller (lists->string form `(if ,test1 ,true ,@(cdddr false))))))) (when (and (eq? false 'no-false) ; no false branch (pair? true)) (when (pair? test) (let ((test-op (car test))) ;; the min+max case is seldom hit, and takes about 50 lines (when (and (memq test-op '(< > <= >=)) (null? (cdddr test))) (let ((rel-arg1 (cadr test)) (rel-arg2 (caddr test))) ;; (if (< x y) (set! x y) -> (set! x (max x y)) (if (eq? true-op 'set!) (let ((settee (cadr true)) (setval (caddr true))) (if (and (member settee test) (member setval test)) ; that's all there's room for (let ((f (if (equal? settee (if (memq test-op '(< <=)) rel-arg1 rel-arg2)) 'max 'min))) (lint-format "perhaps ~A" caller (lists->string form `(set! ,settee (,f ,@(cdr true)))))))) ;; (if (<= (list-ref ind i) 32) (list-set! ind i 32)) -> (list-set! ind i (max (list-ref ind i) 32)) (if (memq true-op '(list-set! vector-set!)) (let ((settee (cadr true)) (index (caddr true)) (setval (cadddr true))) (let ((mx-op (if (and (equal? setval rel-arg1) (eqv? (length rel-arg2) 3) (equal? settee (cadr rel-arg2)) (equal? index (caddr rel-arg2))) (if (memq test-op '(< <=)) 'min 'max) (and (equal? setval rel-arg2) (eqv? (length rel-arg1) 3) (equal? settee (cadr rel-arg1)) (equal? index (caddr rel-arg1)) (if (memq test-op '(< <=)) 'max 'min))))) (if mx-op (lint-format "perhaps ~A" caller (lists->string form `(,true-op ,settee ,index (,mx-op ,@(cdr test)))))))))))))) (if (eq? (car true) 'if) ; (if test0 (if test1 expr)) -> (if (and test0 test1) expr) (cond ((null? (cdddr true)) (let ((test1 (simplify-boolean `(and ,expr ,(cadr true)) () () env))) (lint-format "perhaps ~A" caller (lists->string form `(if ,test1 ,(caddr true)))))) ((equal? expr (cadr true)) (lint-format "perhaps ~A" caller (lists->string form true))) ((equal? (cadr true) `(not ,expr)) (lint-format "perhaps ~A" caller (lists->string form (cadddr true))))) (if (memq true-op '(when unless)) ; (if test0 (when test1 expr...)) -> (when (and test0 test1) expr...) (let ((test1 (simplify-boolean (if (eq? true-op 'when) `(and ,expr ,(cadr true)) `(and ,expr (not ,(cadr true)))) () () env))) ;; (if (and (< x 1) y) (when z (display z) x)) -> (when (and (< x 1) y z) (display z) x) (lint-format "perhaps ~A" caller (lists->string form (if (and (pair? test1) (eq? (car test1) 'not)) `(unless ,(cadr test1) ,@(cddr true)) `(when ,test1 ,@(cddr true)))))))))) (if (and (pair? test) (memq (car test) '(< <= > >= =)) ; (if (< x y) x y) -> (min x y) (null? (cdddr test)) (member false test) (member true test)) (if (eq? (car test) '=) ; (if (= x y) y x) -> y [this never happens] (lint-format "perhaps ~A" caller (lists->string form false)) (let ((f (if (equal? (cadr test) (if (memq (car test) '(< <=)) true false)) 'min 'max))) (lint-format "perhaps ~A" caller (lists->string form `(,f ,true ,false)))))) (cond ((eq? expr #t) ; (if #t #f) -> #f (lint-format "perhaps ~A" caller (lists->string form true))) ((not expr) (if (eq? false 'no-false) (if true ; (if #f x) as a kludgey #<unspecified> (lint-format "perhaps ~A" caller (lists->string form #<unspecified>))) ;; (if (negative? (gcd x y)) a b) -> b (lint-format "perhaps ~A" caller (lists->string form false)))) ((not (equal? true false)) (if (boolean? true) (if (boolean? false) ; ! (if expr #t #f) turned into something less verbose ;; (if x #f #t) -> (not x) (lint-format "perhaps ~A" caller (lists->string form (if true expr (simplify-boolean `(not ,expr) () () env)))) (when (= suggestion made-suggestion) ;; (if x #f y) -> (and (not x) y) (lint-format "perhaps ~A" caller (lists->string form (if true (if (eq? false 'no-false) expr (simplify-boolean `(or ,expr ,false) () () env)) (simplify-boolean (if (eq? false 'no-false) `(not ,expr) `(and (not ,expr) ,false)) () () env)))))) (if (and (boolean? false) (= suggestion made-suggestion)) ;; (if x y #t) -> (or (not x) y) (lint-format "perhaps ~A" caller (let ((nexpr (if false (if (and (pair? expr) (eq? (car expr) 'not)) `(or ,(cadr expr) ,true) `(or (not ,expr) ,true)) `(and ,expr ,true)))) (lists->string form (simplify-boolean nexpr () () env))))))) ((= len 4) ;; (if x (+ y 1) (+ y 1)) -> (+ y 1) (lint-format "if is not needed here: ~A" caller (lists->string form (if (not (side-effect? test env)) true `(begin ,expr ,true)))))) (when (and (= suggestion made-suggestion) (not (equal? expr test))) ; make sure the boolean simplification gets reported ;; (or (not (pair? x)) (not (pair? z))) -> (not (and (pair? x) (pair? z))) (lint-format "perhaps ~A" caller (lists->string test expr))) (when (pair? true) (if (and (pair? test) (pair? (cdr true)) (null? (cddr true)) (or (equal? test (cadr true)) (equal? expr (cadr true)))) (lint-format "perhaps ~A" caller (lists->string form (if (eq? false 'no-false) `(cond (,expr => ,true-op)) `(cond (,expr => ,true-op) (else ,false)))))) (when (and (pair? false) (eq? true-op 'if) (eq? false-op 'if) (= (length true) (length false) 4) (equal? (cadr true) (cadr false))) (if (and (equal? (caddr true) (cadddr false)) ; (if A (if B a b) (if B b a)) -> (if (eq? (not A) (not B)) a b) (equal? (cadddr true) (caddr false))) (let* ((switch #f) (a (if (and (pair? expr) (eq? (car expr) 'not)) (begin (set! switch #t) expr) (simplify-boolean `(not ,expr) () () env))) (b (if (and (pair? (cadr true)) (eq? (caadr true) 'not)) (begin (set! switch (not switch)) (cadr true)) (simplify-boolean `(not ,(cadr true)) () () env)))) (lint-format "perhaps ~A" caller (lists->string form (if switch `(if (eq? ,a ,b) ,(caddr false) ,(caddr true)) `(if (eq? ,a ,b) ,(caddr true) ,(caddr false)))))) (unless (or (side-effect? expr env) (equal? (cddr true) (cddr false))) ; handled elsewhere (if (equal? (caddr true) (caddr false)) ; (if A (if B a b) (if B a c)) -> (if B a (if A b c)) (lint-format "perhaps ~A" caller (lists->string form `(if ,(cadr true) ,(caddr true) (if ,expr ,(cadddr true) ,(cadddr false))))) (if (equal? (cadddr true) (cadddr false)) ; (if A (if B a b) (if B c b)) -> (if B (if A a c) b) (lint-format "perhaps ~A" caller (lists->string form `(if ,(cadr true) (if ,expr ,(caddr true) ,(caddr false)) ,(cadddr true)))))))))) ;; -------- (when (and (= suggestion made-suggestion) (not (= line-number last-if-line-number))) ;; unravel complicated if-then-else nestings into a single cond, if possible. ;; ;; The (> new-len *report-nested-if*) below can mean (nearly) all nested ifs are turned into conds. ;; For a long time I thought the if form was easier to read, but now ;; I like cond better. But cond also has serious readability issues: ;; it needs to be clearer where the test separates from the result, ;; and in a stack of these clauses, it's hard to see anything at all. ;; Maybe a different color for the test than the result? ;; ;; Also, the check for tree-leaves being hugely different is taken ;; from C -- I think it is easier to read a large if statement if ;; the shortest clause is at the start -- especially in a nested if where ;; it can be nearly impossible to see which dangling one-liner matches ;; which if (this even in emacs because it unmarks or doesn't remark the matching ;; paren as you're trying to scroll up to it). ;; ;; the cond form is not always an improvement: ;; (if A (if B (if C a b) (if C c d)) (if B (if C e f) (if C g h))) ;; (cond (A (cond (B (cond (C a) (else b))) ... oh forget it ...)))) ;; perhaps: (case (+ (if A 4 0) (if B 2 0) (if C 1 0)) ((#b000)...))! ;; how often (and how deeply nested) does this happen? -- not very, but nesting can be ridiculous. ;; and this assumes all tests are always hit (define (swap-clauses form) (if (not (pair? (cdddr form))) form (let ((expr (cadr form)) (ltrue (caddr form)) (lfalse (cadddr form))) (let ((true-n (tree-leaves ltrue)) (false-n (if (not (pair? lfalse)) 1 (tree-leaves lfalse)))) (if (< false-n (/ true-n 4)) (let ((new-expr (simplify-boolean `(not ,expr) () () env))) (if (and (pair? ltrue) (eq? (car ltrue) 'if)) (set! ltrue (swap-clauses ltrue))) (if (and (pair? ltrue) (eq? (car ltrue) 'cond)) `(cond (,new-expr ,@(unbegin lfalse)) ,@(cdr ltrue)) `(cond (,new-expr ,@(unbegin lfalse)) (else ,@(unbegin ltrue))))) (begin (if (and (pair? lfalse) (eq? (car lfalse) 'if)) (set! lfalse (swap-clauses lfalse))) (if (and (pair? lfalse) (eq? (car lfalse) 'cond)) `(cond (,expr ,@(unbegin ltrue)) ,@(cdr lfalse)) `(cond (,expr ,@(unbegin ltrue)) (else ,@(unbegin lfalse)))))))))) (let ((new-if (swap-clauses form))) (if (eq? (car new-if) 'cond) (if (> (length new-if) *report-nested-if*) (begin (set! last-if-line-number line-number) (lint-format "perhaps ~A" caller (lists->string form new-if))) (when (= len 4) (let ((true-len (tree-leaves (caddr form)))) (if (and (> true-len *report-short-branch*) (< (tree-leaves (cadddr form)) (/ true-len *report-short-branch*))) (let ((new-expr (simplify-boolean `(not ,(cadr form)) () () env))) (lint-format "perhaps place the much shorter branch first~A: ~A" caller (local-line-number (cadr form)) (truncated-lists->string form `(if ,new-expr ,false ,true)))))))))) ;; -------- (when (= len 4) ;; move repeated test to top, if no inner false branches ;; (if A (if B C) (if B D)) -> (if B (if A C D)) (when (and (pair? true) (pair? false) (eq? true-op 'if) (eq? false-op 'if) (equal? (cadr true) (cadr false)) (null? (cdddr true)) (null? (cdddr false))) (lint-format "perhaps ~A" caller (lists->string form `(if ,(cadr (caddr form)) (if ,expr ,(caddr (caddr form)) ,(caddr (cadddr form))))))) ;; move repeated start/end statements out of the if (let ((ltrue (if (and (pair? true) (eq? true-op 'begin)) true (list 'begin true))) (lfalse (if (and (pair? false) (eq? false-op 'begin)) false (list 'begin false)))) (let ((true-len (length ltrue)) (false-len (length lfalse))) (let ((start (if (and (equal? (cadr ltrue) (cadr lfalse)) (not (side-effect? expr env))) ; expr might affect start, so we can't pull it ahead (list (cadr ltrue)) ())) (end (if (and (not (= true-len false-len 2)) (equal? (list-ref ltrue (- true-len 1)) (list-ref lfalse (- false-len 1)))) (list (list-ref ltrue (- true-len 1))) ()))) (when (or (pair? start) (pair? end)) (let ((new-true (cdr ltrue)) (new-false (cdr lfalse))) (when (pair? end) (set! new-true (copy new-true (make-list (- true-len 2)))) ; (copy lst ()) -> () (set! new-false (copy new-false (make-list (- false-len 2))))) (when (pair? start) (if (pair? new-true) (set! new-true (cdr new-true))) (if (pair? new-false) (set! new-false (cdr new-false)))) (when (or (pair? end) (and (pair? new-true) (pair? new-false))) ; otherwise the rewrite changes the returned value (if (pair? new-true) (set! new-true (if (null? (cdr new-true)) (car new-true) (cons 'begin new-true)))) (if (pair? new-false) (set! new-false (if (null? (cdr new-false)) (car new-false) (cons 'begin new-false)))) ;; (if x (display y) (begin (set! z y) (display y))) -> (begin (if (not x) (set! z y)) (display y)) (lint-format "perhaps ~A" caller (lists->string form (let ((body (if (null? new-true) `(if (not ,expr) ,new-false) (if (null? new-false) `(if ,expr ,new-true) `(if ,expr ,new-true ,new-false))))) `(begin ,@start ,body ,@end)))))))))) (when (and (= suggestion made-suggestion) ; (if (not a) A B) -> (if a B A) (not (= line-number last-if-line-number)) (pair? expr) (eq? (car expr) 'not) (> (tree-leaves true) (tree-leaves false))) (lint-format "perhaps ~A" caller (lists->string form `(if ,(cadr expr) ,false ,true)))) ;; this happens occasionally -- scarcely worth this much code! (gather copied vars outside the if) (when (and (pair? true) (pair? false) (eq? true-op 'let) (eq? false-op 'let) (pair? (cadr true)) (pair? (cadr false))) (let ((true-vars (map car (cadr true))) (false-vars (map car (cadr false))) (shared-vars ())) (for-each (lambda (v) (if (and (memq v false-vars) (equal? (cadr (assq v (cadr true))) (cadr (assq v (cadr false))))) (set! shared-vars (cons v shared-vars)))) true-vars) (when (pair? shared-vars) ;; now remake true/false lets (maybe nil) without shared-vars (let ((ntv ()) (nfv ()) (sv ())) (for-each (lambda (v) (if (memq (car v) shared-vars) (set! sv (cons v sv)) (set! ntv (cons v ntv)))) (cadr true)) (set! ntv (if (or (pair? ntv) (pair? (cdddr true))) ; even define is safe here because outer let blocks it just as inner let used to `(let ,(reverse ntv) ,@(cddr true)) (caddr true))) (for-each (lambda (v) (if (not (memq (car v) shared-vars)) (set! nfv (cons v nfv)))) (cadr false)) (set! nfv (if (or (pair? nfv) (pair? (cdddr false))) `(let ,(reverse nfv) ,@(cddr false)) (caddr false))) ;; (if (> (+ a b) 3) (let ((a x) (c y)) (* a (log c))) (let ((b z) (c y)) (+... -> ;; (let ((c y)) (if (> (+ a b) 3) (let ((a x)) (* a (log c))) (let ((b z)) (+ b (log c))))) (lint-format "perhaps ~A" caller (lists->string form (if (not (or (side-effect? expr env) (tree-set-member (map car sv) expr))) `(let ,(reverse sv) (if ,expr ,ntv ,nfv)) (let ((uniq (find-unique-name form))) `(let ((,uniq ,expr)) (let ,(reverse sv) (if ,uniq ,ntv ,nfv))))))))))))) (when (and *report-one-armed-if* (eq? false 'no-false) (or (not (integer? *report-one-armed-if*)) (> (tree-leaves true) *report-one-armed-if*))) ;; (if a (begin (set! x y) z)) -> (when a (set! x y) z) (lint-format "~A~A~A perhaps ~A" caller (if (integer? *report-one-armed-if*) "this one-armed if is too big" "") (local-line-number test) (if (integer? *report-one-armed-if*) ";" "") (truncated-lists->string form (if (and (pair? expr) (eq? (car expr) 'not)) `(unless ,(cadr expr) ,@(unbegin true)) `(when ,expr ,@(unbegin true)))))) (if (symbol? expr) (set-ref expr caller form env) (lint-walk caller expr env)) (set! env (lint-walk caller true env)) (if (= len 4) (set! env (lint-walk caller false env)))))) env)) (hash-table-set! h 'if if-walker)) ;; -------- when, unless -------- (let () (define (when-walker caller form env) (if (< (length form) 3) (begin (lint-format "~A is messed up: ~A" caller (car form) (truncated-list->string form)) env) (let ((test (cadr form)) (head (car form))) (if (and (pair? test) (eq? (car test) 'not)) ;; (when (not a) (set! x y)) -> (unless a (set! x y)) (lint-format "perhaps ~A" caller (truncated-lists->string form `(,(if (eq? head 'when) 'unless 'when) ,(cadr test) ,@(cddr form))))) (if (never-false test) (lint-format "~A test is never false: ~A" caller head (truncated-list->string form)) (if (never-true test) ; (unless #f...) (lint-format "~A test is never true: ~A" caller head (truncated-list->string form)))) (if (symbol? test) (begin (set-ref test caller form env) (if (and (eq? head 'when) (pair? (cddr form)) (pair? (caddr form))) (if (memq test (caddr form)) (and-incomplete form head test (caddr form) env) (do ((p (caddr form) (cdr p))) ((or (not (pair? p)) (and (pair? (car p)) (memq test (car p)))) (if (pair? p) (and-incomplete form head test (car p) env))))))) (when (pair? test) (if (and (eq? (car test) 'and) (pair? (cdr test)) (pair? (cddr test)) (null? (cdddr test))) (let ((arg1 (cadr test)) (arg2 (caddr test))) (if (or (and (pair? arg1) (eq? (car arg1) 'not)) (and (pair? arg2) (eq? (car arg2) 'not))) (if (eq? head 'unless) ;; (unless (and x (not y)) (display z)) -> (when (or (not x) y) ...) (lint-format "perhaps ~A" caller (lists->string form `(when ,(simplify-boolean `(not ,test) () () env) ...))) (if (and (pair? arg1) (eq? (car arg1) 'not) (pair? arg2) (eq? (car arg2) 'not)) ;; (when (and (not x) (not y)) (display z)) -> (unless (or x y) ...) (lint-format "perhaps ~A" caller (lists->string form `(unless (or ,(cadr arg1) ,(cadr arg2)) ...)))))))) (lint-walk caller test env))) (when (and (pair? (cddr form)) ; (when t1 (if t2 A)) -> (when (and t1 t2) A) (null? (cdddr form)) (pair? (caddr form))) (let ((body (caddr form))) (if (eq? (car body) 'cond) ; (when (cond ...)) -> (cond ...) (lint-format "perhaps ~A" caller (truncated-lists->string form `(cond (,(if (eq? (car form) 'when) (simplify-boolean `(not ,(cadr form)) () () env) (cadr form)) #f) ,@(cdr body)))) (when (or (memq (car body) '(when unless)) (and (eq? (car body) 'if) (pair? (cdr body)) (pair? (cddr body)) (null? (cdddr body)))) (let ((new-test (let ((inner-test (if (eq? (car body) 'unless) `(not ,(cadr body)) (cadr body))) (outer-test (if (eq? head 'unless) `(not ,test) test))) (simplify-boolean `(and ,outer-test ,inner-test) () () env)))) ;; (when (and (< x 1) y) (if z (display z))) -> (when (and (< x 1) y z) (display z)) (lint-format "perhaps ~A" caller (lists->string form (if (and (pair? new-test) (eq? (car new-test) 'not)) `(unless ,(cadr new-test) ,@(cddr body)) `(when ,new-test ,@(cddr body)))))))))) (lint-walk-open-body caller head (cddr form) env)))) (hash-table-set! h 'when when-walker) (hash-table-set! h 'unless when-walker)) ;; ---------------- cond ---------------- (let () (define (cond-walker caller form env) (let ((ctr 0) (suggest made-suggestion) (len (- (length form) 1))) (if (< len 1) (lint-format "cond is messed up: ~A" caller (truncated-list->string form)) (let ((exprs ()) (result :unset) (has-else #f) (has-combinations #f) (simplifications ()) (prev-clause #f) (all-eqv #t) (eqv-select #f)) ;; (cond (A (and B C)) (else (and B D))) et al never happens ;; also (cond (A C) (B C)) -> (if (or A B) C) [non-pair C] ;; ---------------- ;; if regular cond + else ;; scan all return blocks ;; if all one form, and either header or trailer always match, ;; rewrite as header + cond|if + trailer ;; given values and the presence of else, every possibility is covered ;; at least (car result) has to match across all (when (and (> len 1) ; (cond (else ...)) is handled elsewhere (pair? (cdr form)) (pair? (cadr form)) (not (tree-set-member '(unquote #_{list}) form))) (let ((first-clause (cadr form)) (else-clause (list-ref form len))) (when (and (pair? (cdr first-clause)) (null? (cddr first-clause)) (pair? (cadr first-clause)) (pair? else-clause)) (let ((first-result (cadr first-clause)) (first-func (caadr first-clause))) (if (and (memq (car else-clause) '(#t else)) (pair? (cdr else-clause)) (pair? (cadr else-clause)) (or (equal? (caadr first-clause) (caadr else-clause)) ; there's some hope we'll match (escape? (cadr else-clause) env))) (let ((else-error (escape? (cadr else-clause) env))) (when (and (pair? (cdr first-result)) (not (eq? first-func 'values)) (or (not (hash-table-ref syntaces first-func)) (eq? first-func 'set!)) (every? (lambda (c) (and (pair? c) (pair? (cdr c)) (pair? (cadr c)) (null? (cddr c)) (pair? (cdadr c)) (or (equal? first-func (caadr c)) (and (eq? c else-clause) else-error)))) (cddr form))) ((lambda (header-len trailer-len result-min-len) (when (and (or (not (eq? first-func 'set!)) (> header-len 1)) (or (not (eq? first-func '/)) (> header-len 1) (> trailer-len 0))) (let ((header (copy first-result (make-list header-len))) (trailer (copy first-result (make-list trailer-len) (- (length first-result) trailer-len)))) (if (= len 2) (unless (equal? first-result (cadr else-clause)) ; handled elsewhere (all results equal -> result) ;; (cond (x (for-each (lambda (x) (display (+ x a))) (f y))) (else (for-each... -> ;; (for-each (lambda (x) (display (+ x a))) (if x (f y) (g y))) (lint-format "perhaps ~A" caller (let ((else-result (cadr else-clause))) (let ((first-mid-len (- (length first-result) header-len trailer-len)) (else-mid-len (- (length else-result) header-len trailer-len))) (let ((fmid (if (= first-mid-len 1) (list-ref first-result header-len) `(values ,@(copy first-result (make-list first-mid-len) header-len)))) (emid (if else-error else-result (if (= else-mid-len 1) (list-ref else-result header-len) `(values ,@(copy else-result (make-list else-mid-len) header-len)))))) (lists->string form `(,@header (if ,(car first-clause) ,fmid ,emid) ,@trailer))))))) ;; len > 2 so use cond in the revision (let ((middle (map (lambda (c) (let ((test (car c)) (result (cadr c))) (let ((mid-len (- (length result) header-len trailer-len))) (if (and else-error (eq? c else-clause)) else-clause `(,test ,(if (= mid-len 1) (list-ref result header-len) `(values ,@(copy result (make-list mid-len) header-len)))))))) (cdr form)))) ;; (cond ((< x 1) (+ x 1)) ((< y 1) (+ x 3)) (else (+ x 2))) -> (+ x (cond ((< x 1) 1) ((< y 1) 3) (else 2))) (lint-format "perhaps ~A" caller (lists->string form `(,@header (cond ,@middle) ,@trailer)))))))) (partition-form (cdr form) (if else-error (- len 1) len))))) ;; not escaping else here because the trailing args might be evaluated first (when (and (not (hash-table-ref syntaces (car first-result))) (every? (lambda (c) (and (pair? c) (pair? (cdr c)) (pair? (cadr c)) (null? (cddr c)) (not (hash-table-ref syntaces (caadr c))) (equal? (cdadr c) (cdr first-result)))) (cddr form))) (if (every? (lambda (c) (eq? first-func (caadr c))) ; all result clauses are the same!? (cddr form)) ; possibly no else, so not always a duplicate message ;; (cond (X (f y z)) (Y (f y z)) (Z (f y z))) -> (if (or X Y Z) (f y z)) (lint-format "perhaps ~A" caller (lists->string form `(if (or ,@(map car (cdr form))) ,first-result))) ;; here we need an else clause else (apply #<unspecified> args) (if (memq (car else-clause) '(#t else)) ;; (cond (X (f y z)) (else (g y z))) -> ((cond (X f) (else g)) y z) (lint-format "perhaps ~A" caller (lists->string form `((cond ,@(map (lambda (c) (list (car c) (caadr c))) (cdr form))) ,@(cdr first-result)))))))))))) ;; ---------------- (let ((falses ()) (trues ())) (for-each (lambda (clause) (set! ctr (+ ctr 1)) (if (not (pair? clause)) (begin (set! all-eqv #f) (set! has-combinations #f) ;; ; (cond 1) (lint-format "cond clause ~A in ~A is not a pair?" caller clause (truncated-list->string form))) (begin (when all-eqv (unless eqv-select (set! eqv-select (eqv-selector (car clause)))) (set! all-eqv (and eqv-select (not (and (pair? (cdr clause)) (eq? (cadr clause) '=>))) ; case sends selector, but cond sends test result (cond-eqv? (car clause) eqv-select #t)))) (if (and (pair? prev-clause) (not has-combinations) (> len 2) (equal? (cdr clause) (cdr prev-clause))) (if (memq (car clause) '(else #t)) ; (cond ... (x z) (else z)) -> (cond ... (else z)) (unless (side-effect? (car prev-clause) env) ;; (cond (x y) (z 32) (else 32)) (lint-format* caller "this clause could be omitted: " (truncated-list->string prev-clause))) (set! has-combinations #t))) ; handle these later (set! prev-clause clause) (let ((expr (simplify-boolean (car clause) trues falses env)) (test (car clause)) (sequel (cdr clause)) (first-sequel (and (pair? (cdr clause)) (cadr clause)))) (if (not (equal? expr test)) (set! simplifications (cons (cons clause expr) simplifications))) (if (symbol? test) (if (and (not (eq? test 'else)) (pair? first-sequel)) (if (memq test first-sequel) (and-incomplete form 'cond test first-sequel env) (do ((p first-sequel (cdr p))) ((or (not (pair? p)) (and (pair? (car p)) (memq test (car p)))) (if (pair? p) (and-incomplete form 'cond test (car p) env)))))) (if (and (pair? test) (pair? first-sequel) (hash-table-ref bools (car test))) (if (member (cadr test) first-sequel) (and-forgetful form 'cond test first-sequel env) (do ((p first-sequel (cdr p))) ((or (not (pair? p)) (and (pair? (car p)) (member (cadr test) (car p)))) (if (pair? p) (and-forgetful form 'cond test (car p) env))))))) ;; code here to check every arg against its use in the sequel found no problems?!? (cond ((memq test '(else #t)) (set! has-else #t) (when (pair? sequel) (if (eq? first-sequel #<unspecified>) ;; (cond ((= x y) z) (else #<unspecified>) (lint-format "this #<unspecified> is redundant: ~A" caller clause)) (if (and (pair? first-sequel) ; (cond (a A) (else (cond ...))) -> (cond (a A) ...) (null? (cdr sequel))) ; similarly for if, when, and unless (case (car first-sequel) ((cond) ;; (cond ((< x 1) 2) (else (cond ((< y 3) 2) (#t 4)))) (lint-format "else clause could be folded into the outer cond: ~A" caller (lists->string form (append (copy form (make-list ctr)) (cdr first-sequel))))) ((if) ;; (cond (a A) (else (if b B))) (lint-format "else clause could be folded into the outer cond: ~A" caller (lists->string form (append (copy form (make-list ctr)) (if (= (length first-sequel) 3) (list (cdr first-sequel)) `((,(cadr first-sequel) ,@(unbegin (caddr first-sequel))) (else ,@(unbegin (cadddr first-sequel))))))))) ((when unless) ;; (cond (a A) (else (when b B))) (lint-format "else clause could be folded into the outer cond: ~A" caller (lists->string form (append (copy form (make-list ctr)) (if (eq? (car first-sequel) 'when) `((,(cadr first-sequel) ,@(cddr first-sequel))) `(((not ,(cadr first-sequel)) ,@(cddr first-sequel)))))))))))) ((not (= ctr len))) ((equal? test ''else) ;; (cond (x y) ('else z)) (lint-format "odd cond clause test: is 'else supposed to be else? ~A" caller (truncated-list->string clause))) ((and (eq? test 't) (not (var-member 't env))) ;; (cond ((= x 1) 1) (t 2) (lint-format "odd cond clause test: is t supposed to be #t? ~A" caller (truncated-list->string clause)))) (if (never-false expr) (if (not (= ctr len)) ;; (cond ((getenv s) x) ((= y z) w)) (lint-format "cond test ~A is never false: ~A" caller (car clause) (truncated-list->string form)) (if (not (or (memq expr '(#t else)) (side-effect? test env))) (lint-format "cond last test could be #t: ~A" caller form))) (if (never-true expr) ;; (cond ((< 3 1) 2)) (lint-format "cond test ~A is never true: ~A" caller (car clause) (truncated-list->string form)))) (unless (side-effect? test env) (if (and (not (memq test '(else #t))) (pair? sequel) (null? (cdr sequel))) (cond ((equal? test first-sequel) ;; (cond ((= x 0) x) ((= x 1) (= x 1))) (lint-format "no need to repeat the test: ~A" caller (lists->string clause (list test)))) ((and (pair? first-sequel) (pair? (cdr first-sequel)) (null? (cddr first-sequel)) (equal? test (cadr first-sequel))) (if (eq? (car first-sequel) 'not) ;; (cond ((> x 2) (not (> x 2)))) (lint-format "perhaps replace ~A with #f" caller first-sequel) ;; (cond (x (abs x))) (lint-format "perhaps use => here: ~A" caller (lists->string clause (list test '=> (car first-sequel)))))) ((and (eq? first-sequel #t) (pair? test) (not (memq (car test) '(or and))) (eq? (return-type (car test) env) 'boolean?)) ;; (cond ((null? x) #t) (else y)) (lint-format "this #t could be omitted: ~A" caller (truncated-list->string clause))))) (if (member test exprs) ;; (cond ((< x 2) 3) ((> x 0) 4) ((< x 2) 5)) (lint-format "cond test repeated: ~A" caller (truncated-list->string clause)) (set! exprs (cons test exprs)))) (if (boolean? expr) (if (not expr) ;; (cond ((< 3 1) 2)) (lint-format "cond test is always false: ~A" caller (truncated-list->string clause)) (if (not (= ctr len)) ;; (cond (#t 2) (x 3)) (lint-format "cond #t clause is not the last: ~A" caller (truncated-list->string form)))) (if (eq? test 'else) (if (not (= ctr len)) ;; (cond (else 2) (x 3)) (lint-format "cond else clause is not the last: ~A" caller (truncated-list->string form))) (lint-walk caller test env))) (if (and (symbol? expr) (not (var-member expr env)) (procedure? (symbol->value expr *e*))) ;; (cond (< x 1) (else 1)) (lint-format "strange cond test: ~A in ~A is a procedure" caller expr clause)) (if (eq? result :unset) (set! result sequel) (if (not (equal? result sequel)) (set! result :unequal))) (cond ((not (pair? sequel)) (if (not (null? sequel)) ; (not (null?...)) here is correct -- we're looking for stray dots (lint-format "cond clause is messed up: ~A" caller (truncated-list->string clause)))) ((not (eq? first-sequel '=>)) (lint-walk-open-body caller 'cond sequel env)) ((or (not (pair? (cdr sequel))) (pair? (cddr sequel))) ;; (cond (x =>)) (lint-format "cond => target is messed up: ~A" caller (truncated-list->string clause))) (else (let ((f (cadr sequel))) (if (symbol? f) (let ((val (symbol->value f *e*))) (when (procedure? val) (if (not (aritable? val 1)) ; here values might be in test expr ;; (cond (x => expt)) (lint-format "=> target (~A) may be unhappy: ~A" caller f clause)) (let ((sig (procedure-signature val))) (if (and (pair? sig) (pair? (cdr sig))) (let ((from-type (->lint-type expr)) (to-type (cadr sig))) (if (not (or (memq from-type '(#f #t values)) (memq to-type '(#f #t values)) (any-compatible? to-type from-type))) ;; (cond ((> x 0) => abs) (else y)) (lint-format "in ~A, ~A returns a ~A, but ~A expects ~A" caller (truncated-list->string clause) expr (prettify-checker-unq from-type) f to-type))))))) (if (and (pair? f) (eq? (car f) 'lambda) (pair? (cdr f)) (pair? (cadr f)) (not (= (length (cadr f)) 1))) (lint-format "=> target (~A) may be unhappy: ~A" caller f clause))) (lint-walk caller f env)))) (if (side-effect? expr env) (begin (set! falses ()) (set! trues ()) (set! result :unequal)) (begin (if (not (member expr falses)) (set! falses (cons expr falses))) (when (pair? expr) (if (and (eq? (car expr) 'not) (not (member (cadr expr) trues))) (set! trues (cons (cadr expr) trues))) (if (eq? (car expr) 'or) (for-each (lambda (p) (if (not (member p falses)) (set! falses (cons p falses)))) (cdr expr)))))))))) (cdr form))) ; for-each clause (if has-else (if (pair? result) ; all result clauses are the same (and not implicit) ;; (cond (x #t) (else #t)) -> #t (lint-format "perhaps ~A" caller (lists->string form (if (null? (cdr result)) (car result) `(begin ,@result))))) (let* ((last-clause (and (> len 1) (list-ref form len))) (last-res (let ((clen (and (pair? last-clause) (length last-clause)))) (and (integer? clen) (> clen 1) (list-ref last-clause (- clen 1)))))) (if (and (pair? last-res) (memq (car last-res) '(#t else))) ;; (cond (x y) (y z (else 3))) (lint-format "perhaps cond else clause is misplaced: ~A in ~A" caller last-res last-clause)))) (when (and (= len 2) (not (check-bool-cond caller form (cadr form) (caddr form) env)) (pair? (cadr form)) ; (cond 1 2)! (pair? (caddr form))) (let ((c1 (cadr form)) (c2 (caddr form))) (if (equal? (simplify-boolean (car c1) () () env) (simplify-boolean `(not ,(car c2)) () () env)) (lint-format "perhaps ~A" caller ; (cond ((x) y) ((not (x)) z)) -> (cond ((x) y) (else z)) (lists->string form `(cond ,c1 (else ,@(cdr c2))))) (when (and (pair? (car c1)) ; (cond ((not x) y) (else z)) -> (cond (x z) (else y)) (pair? (cdr c1)) ; null case is handled elsewhere (eq? (caar c1) 'not) (memq (car c2) '(else #t))) (let ((c1-len (tree-leaves (cdr c1))) ; try to avoid the dangling short case as in if (c2-len (tree-leaves (cdr c2)))) (when (and (< (+ c1-len c2-len) 100) (> (* c1-len 4) c2-len)) ; maybe 4 is too much (lint-format "perhaps ~A" caller (lists->string form (if (or (pair? (cddr c1)) (pair? (cddr c2))) `(cond (,(cadar c1) ,@(cdr c2)) (else ,@(cdr c1))) `(if ,(cadar c1) ,(cadr c2) ,(cadr c1))))))))))) (when has-combinations (do ((new-clauses ()) (current-clauses ()) (clauses (cdr form) (cdr clauses))) ((null? clauses) (let ((len2 (= (length new-clauses) 2))) (unless (and len2 ; i.e. don't go to check-bool-cond (check-bool-cond caller form (cadr new-clauses) (car new-clauses) env)) ;; (cond ((= x 3) 3) ((= x 2) 4) ((= x 1) 4)) -> (case x ((3) 3) ((2 1) 4)) (lint-format "perhaps ~A" caller (lists->string form (cond (all-eqv (cond->case eqv-select (reverse new-clauses))) ((not (and len2 (pair? (car new-clauses)) (memq (caar new-clauses) '(else #t)) (pair? (cadr new-clauses)) (pair? (caadr new-clauses)) (eq? (caaadr new-clauses) 'or) (null? (cdadr new-clauses)))) `(cond ,@(reverse new-clauses))) ((null? (cddar new-clauses)) ; (cond (A) (B) (else C)) -> (or A B C) `(or ,@(cdaadr new-clauses) ,(cadar new-clauses))) (else `(or ,@(cdaadr new-clauses) (begin ,@(cdar new-clauses)))))))) (set! simplifications ()) (set! all-eqv #f))) (let* ((clause (car clauses)) (result (cdr clause))) ; can be null in which case the test is the result (cond ((and (pair? simplifications) (assq clause simplifications)) => (lambda (e) (set! clause (cons (cdr e) result))))) (if (and (pair? (cdr clauses)) (equal? result (cdadr clauses))) (set! current-clauses (cons clause current-clauses)) (if (pair? current-clauses) (begin (set! current-clauses (cons clause current-clauses)) (set! new-clauses (cons (cons (simplify-boolean `(or ,@(map car (reverse current-clauses))) () () env) result) new-clauses)) (set! current-clauses ())) (set! new-clauses (cons clause new-clauses))))))) (when (and all-eqv (> len (if has-else 2 1))) ; (cond (x y)) -- kinda dumb, but (if x y) isn't much shorter ;; (cond ((= x 0) x) ((= x 1) (= x 1))) -> (case x ((0) x) ((1) (= x 1))) (lint-format "perhaps use case instead of cond: ~A" caller (lists->string form (cond->case eqv-select (cdr form))))) (if (and (= len 2) has-else (null? (cdadr form))) (let ((else-clause (if (null? (cddr (caddr form))) (cadr (caddr form)) `(begin ,@(cdr (caddr form)))))) ;; (cond ((a)) (else A)) -> (or (a) A) (lint-format "perhaps ~A" caller (lists->string form `(or ,(caadr form) ,else-clause))))) ;; -------- (unless (or has-combinations all-eqv) ;; look for repeated ((op x c1) c2) -> ((assoc x '((c1 . c2)...)) => cdr) anywhere in the clause list (let ((nc ()) (op #f) (sym-access #f) (start #f) (changed #f)) ;; extending this to memx possibilities got only 1 hit and involved ca. 20 lines (define (car-with-expr cls) (cond ((and (pair? simplifications) (assq cls simplifications)) => (lambda (e) (set! changed #t) (cons (cdr e) (cdr cls)))) (else cls))) (define (start-search clauses test) (if (code-constant? (cadr test)) (if (memq (car test) '(= string=? string-ci=? eq? eqv? equal? char=? char-ci=?)) (set! sym-access caddr)) (if (code-constant? (caddr test)) (set! sym-access cadr))) (if sym-access (begin (set! start clauses) (set! op (car test))) (set! nc (cons (car-with-expr (car clauses)) nc)))) (do ((clauses (cdr form) (cdr clauses))) ((or (null? clauses) (not (pair? (car clauses)))) (if (and changed (null? clauses)) ;; (cond ((< x 2) 3) ((> x 0) 4) ((< x 2) 5)) -> (cond ((< x 2) 3) ((> x 0) 4)) (lint-format "perhaps ~A" caller (lists->string form `(cond ,@(reverse (map (lambda (c) (if (not (car c)) (values) c)) nc))))))) (let ((test (caar clauses))) (let ((ok-but-at-end #f) (looks-ok (let ((result (cdar clauses))) (and (pair? test) (pair? (cdr test)) (pair? (cddr test)) (null? (cdddr test)) (pair? result) (null? (cdr result)) (not (symbol? (car result))) (or (not (pair? (car result))) ; quoted lists look bad in this context (and (eq? (caar result) 'quote) (not (pair? (cadar result))))))))) (if (not start) (if (and looks-ok (not (null? (cdr clauses)))) (start-search clauses test) (set! nc (cons (car-with-expr (car clauses)) nc))) (unless (and looks-ok (eq? (car test) op) (equal? (sym-access test) (sym-access (caar start))) (code-constant? ((if (eq? sym-access cadr) caddr cadr) test)) (not (set! ok-but-at-end (null? (cdr clauses))))) (if (eq? (cdr start) clauses) ; only one item in the block, or two but it's just two at the end (begin (set! nc (cons (car start) nc)) (if (and looks-ok (not (null? (cdr clauses)))) (start-search clauses test) (begin (set! start #f) (set! nc (cons (car-with-expr (car clauses)) nc))))) ;; multiple hits -- can we combine them? (let ((alist ()) (cc (if (eq? sym-access cadr) caddr cadr))) (set! changed #t) (do ((sc start (cdr sc))) ((if ok-but-at-end (null? sc) (eq? sc clauses)) (case op ((eq?) (set! nc (cons `((assq ,(sym-access (caar start)) ',(reverse alist)) => cdr) nc))) ((eqv? char=?) (set! nc (cons `((assv ,(sym-access (caar start)) ',(reverse alist)) => cdr) nc))) ((equal?) (set! nc (cons `((assoc ,(sym-access (caar start)) ',(reverse alist)) => cdr) nc))) ((string=?) ;; this is probably faster than assoc + string=?, but it creates symbols (let ((nlst (map (lambda (c) (cons (string->symbol (car c)) (cdr c))) alist))) (set! nc (cons `((assq (string->symbol ,(sym-access (caar start))) ',(reverse nlst)) => cdr) nc)))) (else (set! nc (cons `((assoc ,(sym-access (caar start)) ',(reverse alist) ,op) => cdr) nc))))) (set! alist (cons (cons (unquoted (cc (caar sc))) (unquoted (cadar sc))) alist))) (if (and looks-ok (not (null? (cdr clauses)))) (start-search clauses test) (begin (set! start #f) (if (not ok-but-at-end) (set! nc (cons (car-with-expr (car clauses)) nc)))))))))))))) ;; look for case at end (case in the middle is tricky due to #f handling) (when (and (> len 3) (= suggest made-suggestion)) (let ((rform (reverse form)) (eqv-select #f) (elen (if has-else (- len 1) len))) (if has-else (set! rform (cdr rform))) (set! eqv-select (eqv-selector (caar rform))) (when eqv-select (do ((clauses rform (cdr clauses)) (ctr 0 (+ ctr 1))) ((or (null? clauses) (let ((clause (car clauses))) (or (and (pair? (cdr clause)) (eq? (cadr clause) '=>)) ; case sends selector, but cond sends test result (not (cond-eqv? (car clause) eqv-select #t))))) (when (and (pair? clauses) (> ctr 1)) ;; (cond ((pair? x) 3) ((eq? x 'a) z) ((eq? x 'b) (* 2 z)) ((eq? x 'c)... -> ;; (if (pair? x) 3 (case x ((a) z) ((b) (* 2 z)) ((c) (display z)))) (lint-format "possibly use case at the end: ~A" caller (lists->string form (let ((else-case (cond->case eqv-select ; cond->case will handle the else branch (list-tail (cdr form) (- elen ctr))))) (if (= (- elen ctr) 1) (if (equal? (cdadr form) '(#f)) `(and (not ,(caadr form)) ,else-case) `(if ,@(cadr form) ,else-case)) `(cond ,@(copy (cdr form) (make-list (- elen ctr))) (else ,else-case)))))))))))) ;; -------- ;; repeated test exprs handled once (let ((exprs ()) (reps ()) (ctr 0) (pos 0) (head-len 0) (else-leaves 0) (else-result #f)) (for-each (lambda (c) (set! pos (+ pos 1)) (cond ((and (pair? c) (memq (car c) '(#t else))) (set! else-result (cdr c)) (set! else-leaves (tree-leaves else-result))) ((not (and (pair? c) (pair? (car c)) (or (eq? (caar c) 'and) (member (car c) reps)))) (set! exprs ()) (set! reps ()) (set! ctr 0)) ((null? exprs) (set! head-len pos) (set! exprs (cdar c)) (set! reps exprs) (set! ctr 1)) (else (set! ctr (+ ctr 1)) (set! reps (remove-if (lambda (rc) (not (or (equal? rc (car c)) (member rc (cdar c))))) reps))))) (cdr form)) (when (and (pair? reps) (> ctr 1) (< else-leaves (* ctr (length reps) 3))) ;; (cond ((pair? z) 32) ((and (pair? x) (pair? w)) 12) ((pair? x) 2) (else 0)) -> ;; (cond ((pair? z) 32) ((not (pair? x)) 0) ((pair? w) 12) (else 2)) (lint-format "perhaps ~A" caller (lists->string form (let ((not-reps (simplify-boolean (if (null? (cdr reps)) `(not ,(car reps)) `(not (and ,@reps))) () () env))) `(,@(copy form (make-list head-len)) (,not-reps ,@(or else-result '(#<unspecified>))) ,@(let mapper ((clauses (list-tail form head-len)) (lst ())) (if (null? clauses) (reverse lst) (let ((new-clause (let ((c (car clauses))) (if (memq (car c) '(else #t)) c `(,(if (member (car c) reps) 'else (remove-if (lambda (rc) (member rc reps)) (car c))) ,@(cdr c)))))) (if (and (pair? new-clause) (pair? (car new-clause)) (eq? (caar new-clause) 'and) (pair? (cdar new-clause)) (null? (cddar new-clause))) (set-car! new-clause (cadar new-clause))) (if (memq (car new-clause) '(else #t)) (reverse (cons new-clause lst)) (mapper (cdr clauses) (cons new-clause lst)))))))))))) (when (pair? (cadr form)) (if (= len 1) (let ((clause (cadr form))) ; (cond (a)) -> a, (cond (a b)) -> (if a b) etc (if (null? (cdr clause)) (lint-format "perhaps ~A" caller (lists->string form (car clause))) (if (and (not (eq? (cadr clause) '=>)) (or (pair? (cddr clause)) (= suggest made-suggestion))) ;; (cond ((= x 1) 32)) -> (if (= x 1) 32) (lint-format "perhaps ~A" caller (lists->string form (if (null? (cddr clause)) `(if ,(car clause) ,(cadr clause)) (if (and (pair? (car clause)) (eq? (caar clause) 'not)) `(unless ,@(cdar clause) ,@(cdr clause)) `(when ,(car clause) ,@(cdr clause))))))))) (when has-else ; len > 1 here (let ((last-clause (list-ref form (- len 1)))) ; not the else branch! -- just before it. (when (and (= suggest made-suggestion) ; look for all results the same (pair? (cadr form)) (pair? (cdadr form))) (let ((result (list-ref (cadr form) (- (length (cadr form)) 1))) (else-clause (cdr (list-ref form len)))) (when (every? (lambda (c) (and (pair? c) (pair? (cdr c)) (equal? result (list-ref c (- (length c) 1))))) (cddr form)) ;; (cond ((and (display x) x) 32) (#t 32)) -> (begin (and (display x) x) 32) (lint-format "perhaps ~A" caller (lists->string form (if (= len 2) ; one is else -- this case is very common (let* ((c1-len (length (cdr last-clause))) (new-c1 (case c1-len ((1) #f) ((2) (cadr last-clause)) (else `(begin ,@(copy (cdr last-clause) (make-list (- c1-len 1))))))) (else-len (length else-clause)) (new-else (case else-len ((1) #f) ((2) (car else-clause)) (else `(begin ,@(copy else-clause (make-list (- else-len 1)))))))) `(begin ,(if (= c1-len 1) (if new-else `(if (not ,(car last-clause)) ,new-else) (car last-clause)) (if (= else-len 1) (if new-c1 `(if ,(car last-clause) ,new-c1) (car last-clause)) `(if ,(car last-clause) ,new-c1 ,new-else))) ,result)) `(begin ; this almost never happens (cond ,@(map (lambda (c) (let ((len (length c))) (if (= len 2) (if (or (memq (car c) '(else #t)) (not (side-effect? (car c) env))) (values) (car c)) (copy c (make-list (- len 1)))))) (cdr form))) ,result))))))) ;; a few dozen hits here ;; the 'case parallel gets 2 hits, complex selectors ;; len = (- (length form) 1) = number of clauses (when (and (> len 2) (or (null? (cdr last-clause)) (and (pair? (cdr last-clause)) (null? (cddr last-clause)) (boolean? (cadr last-clause))))) (let ((else-clause (cdr (list-ref form len))) (next-clause (cdr (list-ref form (- len 2))))) (when (and (pair? else-clause) (null? (cdr else-clause)) (boolean? (car else-clause)) (not (equal? (cdr last-clause) else-clause)) (pair? next-clause) (null? (cdr next-clause)) (not (boolean? (car next-clause)))) (lint-format "perhaps ~A" caller (lists->string form `(,@(copy form (make-list (- len 1))) (else ,(if (car else-clause) `(not ,(car last-clause)) (car last-clause))))))))) ;; (cond ((= x y) 2) ((= x 2) #f) (else #t)) -> (cond ((= x y) 2) (else (not (= x 2)))) ;; (cond ((= x y) 2) ((= x 2) #t) (else #f)) -> (cond ((= x y) 2) (else (= x 2))) (when (= len 3) (let ((first-clause (cadr form)) (else-clause (cdr (list-ref form len)))) (when (and (or (null? (cdr first-clause)) (and (null? (cddr first-clause)) (boolean? (cadr first-clause)))) (pair? last-clause) (or (null? (cdr last-clause)) (null? (cddr last-clause)))) (if (and (pair? (cdr first-clause)) (not (cadr first-clause)) ; (cond (A #f) (B #t) (else C)) -> (and (not A) (or B C)) (or (null? (cdr last-clause)) (eq? (cadr last-clause) #t))) (lint-format "perhaps ~A" caller (lists->string form (simplify-boolean `(and (not ,(car first-clause)) (or ,(car last-clause) ,@(if (null? (cdr else-clause)) else-clause `(begin ,@else-clause)))) () () env))) (if (and (or (null? (cdr first-clause)) ; (cond (A #t) (B C) (else #f)) -> (or A (and B C)) (eq? (cadr first-clause) #t)) (not (car else-clause)) (null? (cdr else-clause))) (lint-format "perhaps ~A" caller (lists->string form `(or ,(car first-clause) (and ,@last-clause))))))) (when (and (equal? (cdr first-clause) else-clause) ; a = else result (pair? (cdr last-clause)) ; b does exist (not (eq? (cadr last-clause) '=>))) ; no => in b ;; (cond (A a) (B b) (else a)) -> (if (or A (not B)) a b) (lint-format "perhaps ~A" caller (lists->string form (let ((A (car first-clause)) (a (cdr first-clause)) (B (car last-clause)) (b (cdr last-clause))) (let ((nexpr (simplify-boolean `(or ,A (not ,B)) () () env))) (cond ((not (and (null? (cdr a)) (null? (cdr b)))) `(cond (,nexpr ,@a) (else ,@b))) ((eq? (car a) #t) (if (not (car b)) nexpr (simplify-boolean `(or ,nexpr ,(car b)) () () env))) ((car a) ; i.e a is not #f `(if ,nexpr ,(car a) ,(car b))) ((eq? (car b) #t) (simplify-boolean `(not ,nexpr) () () env)) (else (simplify-boolean `(and (not ,nexpr) ,(car b)) () () env)))))))))) (when (> len 3) ;; this is not ideal (let ((e (list-ref form len)) ; (cond (W X) (A B) (C D) (else B)) -> (cond (W X) ((or A (not C)) B) (else D)) (b (list-ref form (- len 1))) (a (list-ref form (- len 2)))) (if (and (pair? a) (pair? (cdr a)) ; is (else) a legal cond clause? -- yes, it returns else... (pair? e) (equal? (cdr a) (cdr e)) (pair? b) (pair? (cdr b)) (not (eq? (cadr b) '=>))) (let ((expr (simplify-boolean `(or ,(car a) (not ,(car b))) () () env))) (lint-format "perhaps ~A" caller (lists->string form `(cond ,(if (> len 4) '... (cadr form)) (,expr ,@(cdr a)) (else ,@(cdr b))))))))) (let ((arg1 (cadr form)) (arg2 (caddr form))) (when (and (pair? arg1) (pair? (car arg1)) (pair? (cdr arg1)) (pair? arg2) (eq? (caar arg1) 'and) (null? (cddr arg1)) (pair? (cdr arg2)) (null? (cddr arg2)) (member (car arg2) (cdar arg1)) (= (length (cdar arg1)) 2)) ;; (cond ((and A B) c) (B d) (else e)) -> (cond (B (if A c d)) (else e)) (lint-format "perhaps ~A" caller (lists->string form `(cond (,(car arg2) (if ,((if (equal? (car arg2) (cadar arg1)) caddar cadar) arg1) ,(cadr arg1) ,(cadr arg2))) ,@(cdddr form)))))) (if (and (pair? last-clause) ; (cond ... ((or ...)) (else ...)) -> (cond ... (else (or ... ...))) (pair? (car last-clause)) (null? (cdr last-clause)) (eq? (caar last-clause) 'or)) (let ((else-clause (let ((e (cdr (list-ref form len)))) (if (null? (cdr e)) (car e) `(begin ,@e))))) ;; (cond ((A) B) ((or C D)) (else E)) -> (cond ((A) B) (else (or C D E))) (lint-format "perhaps ~A" caller (lists->string form `(cond ,@(copy (cdr form) (make-list (- len 2))) (else (or ,@(cdar last-clause) ,else-clause)))))))))) (let ((last-clause (list-ref form (if has-else (- len 1) len)))) ; not the else branch! -- just before it. (if (and (pair? last-clause) ; (cond ... (A (cond ...)) (else B)) -> (cond ... ((not A) B) ...) (pair? (cdr last-clause)) (null? (cddr last-clause)) (pair? (cadr last-clause)) (memq (caadr last-clause) '(if cond))) (let ((new-test (simplify-boolean `(not ,(car last-clause)) () () env)) (new-result (if has-else (cdr (list-ref form len)) (if (eq? form lint-mid-form) () (list #<unspecified>))))) (if (eq? (caadr last-clause) 'cond) ;; (cond (A (cond (B c) (else D))) (else E)) -> (cond ((not A) E) (B c) (else D)) (lint-format "perhaps ~A" caller (lists->string form `(cond ,@(copy (cdr form) (make-list (- len (if has-else 2 1)))) (,new-test ,@new-result) ,@(cdadr last-clause)))) (if (= (length (cadr last-clause)) 4) (let ((if-form (cdadr last-clause))) ;; (cond (A B) (C (if D d E)) (else F)) -> (cond (A B) ((not C) F) (D d) (else E)) (lint-format "perhaps ~A" caller (lists->string form `(cond ,@(copy (cdr form) (make-list (- len (if has-else 2 1)))) (,new-test ,@new-result) (,(car if-form) ,@(unbegin (cadr if-form))) (else ,@(unbegin (caddr if-form)))))))))) (when (> len 2) ; rewrite nested conds as one cond (let ((lim (if has-else (- len 2) len)) (tlen (tree-leaves form))) (when (< tlen 200) (set! tlen (/ tlen 4)) (do ((i 0 (+ i 1)) (k (+ lim 1) (- k 1)) (p (cdr form) (cdr p))) ((or (not (pair? p)) (= i lim))) (let ((nc (car p))) (if (and (pair? nc) (pair? (cdr nc)) (null? (cddr nc)) (pair? (cadr nc)) (eq? (caadr nc) 'cond) (>= (length (cdadr nc)) (* 2 k)) (> (tree-leaves nc) tlen)) (let ((new-test (simplify-boolean `(not ,(car nc)) () () env)) (new-result (if (and has-else (= i (- lim 1)) (null? (cddadr p)) (null? (cddr (caddr p)))) `(if ,(caadr p) ,(cadadr p) ,(cadr (caddr p))) `(cond ,@(cdr p))))) ;; (cond ((= x 0) 1) ((= x 3) (cond ((not y) 1) ((pair? y) 2) ((eq? y 'a) 3) (else 4))) ((< x 200) 2) (else 5)) -> ;; (cond ((= x 0) 1) ((not (= x 3)) (if (< x 200) 2 5)) ((not y) 1) ((pair? y) 2) ((eq? y 'a) 3) (else 4)) (lint-format "perhaps ~A" caller (lists->string form `(cond ,@(copy (cdr form) (make-list i)) (,new-test ,new-result) ,@(cdadr nc)))))))))))))))) env)) (hash-table-set! h 'cond cond-walker)) ;; ---------------- case ---------------- (let () (define case-walker (let ((selector-types '(#t symbol? char? boolean? integer? rational? real? complex? number? null? eof-object?))) (lambda (caller form env) ;; here the keys are not evaluated, so we might have a list like (letrec define ...) ;; also unlike cond, only 'else marks a default branch (not #t) (if (< (length form) 3) ;; (case 3) (lint-format "case is messed up: ~A" caller (truncated-list->string form)) (let ((sel-type #t) (selector (cadr form)) (suggest made-suggestion)) ;; ---------------- ;; if regular case + else -- just like cond above (let ((len (- (length form) 2))) ; number of clauses (when (and (> len 1) ; (case x (else ...)) is handled elsewhere (pair? (cdr form)) (pair? (cddr form)) (pair? (caddr form)) (not (tree-set-member '(unquote #_{list}) form))) (let ((first-clause (caddr form)) (else-clause (list-ref form (+ len 1)))) (when (and (pair? else-clause) (eq? (car else-clause) 'else) (pair? (cdr first-clause)) (pair? (cadr first-clause)) (not (hash-table-ref syntaces (caadr first-clause))) (pair? (cdadr first-clause)) (null? (cddr first-clause)) (every? (lambda (c) (and (pair? c) (pair? (cdr c)) (pair? (cadr c)) (null? (cddr c)) (not (hash-table-ref syntaces (caadr c))) (equal? (cdadr first-clause) (cdadr c)))) (cdddr form))) ;; (case x ((a) (f y z)) (else (g y z))) -> ((if (eq? x 'a) f g) y z) (lint-format "perhaps ~A" caller ; all results share trailing args (lists->string form (if (and (= len 2) (symbol? (caar first-clause)) (null? (cdar first-clause))) `((if (eq? ,(cadr form) ',(caar first-clause)) ,(caadr first-clause) ,(caadr else-clause)) ,@(cdadr first-clause)) `((case ,(cadr form) ,@(map (lambda (c) (list (car c) (caadr c))) (cddr form))) ,@(cdadr first-clause)))))) (when (and (pair? (cdr first-clause)) (null? (cddr first-clause)) (pair? (cadr first-clause)) (pair? else-clause) (eq? (car else-clause) 'else) (pair? (cdr else-clause)) (pair? (cadr else-clause)) (or (equal? (caadr first-clause) (caadr else-clause)) ; there's some hope we'll match (escape? (cadr else-clause) env))) (let ((first-result (cadr first-clause)) (first-func (caadr first-clause)) (else-error (escape? (cadr else-clause) env))) (when (and (pair? (cdr first-result)) (not (eq? first-func 'values)) (or (not (hash-table-ref syntaces first-func)) (eq? first-func 'set!)) (every? (lambda (c) (and (pair? c) (pair? (cdr c)) (pair? (cadr c)) (null? (cddr c)) (pair? (cdadr c)) (or (equal? first-func (caadr c)) (and (eq? c else-clause) else-error)))) (cdddr form))) ((lambda (header-len trailer-len result-mid-len) (when (and (or (not (eq? first-func 'set!)) (> header-len 1)) (or (not (eq? first-func '/)) (> header-len 1) (> trailer-len 0))) (let ((header (copy first-result (make-list header-len))) (trailer (copy first-result (make-list trailer-len) (- (length first-result) trailer-len)))) (if (= len 2) (unless (equal? first-result (cadr else-clause)) ; handled elsewhere (all results equal -> result) ;; (case x ((1) (+ x 1)) (else (+ x 3))) -> (+ x (if (eqv? x 1) 1 3)) (lint-format "perhaps ~A" caller (let ((else-result (cadr else-clause))) (let ((first-mid-len (- (length first-result) header-len trailer-len)) (else-mid-len (- (length else-result) header-len trailer-len))) (let* ((fmid (if (= first-mid-len 1) (list-ref first-result header-len) `(values ,@(copy first-result (make-list first-mid-len) header-len)))) (emid (if else-error else-result (if (= else-mid-len 1) (list-ref else-result header-len) `(values ,@(copy else-result (make-list else-mid-len) header-len))))) (middle (if (= (length (car first-clause)) 1) `(eqv? ,(cadr form) ,(caar first-clause)) `(memv ,(cadr form) ',(car first-clause))))) (lists->string form `(,@header (if ,middle ,fmid ,emid) ,@trailer))))))) ;; len > 2 so use case in the revision (let ((middle (map (lambda (c) (let ((test (car c)) (result (cadr c))) (let ((mid-len (- (length result) header-len trailer-len))) (if (and else-error (eq? c else-clause)) else-clause `(,test ,(if (= mid-len 1) (list-ref result header-len) `(values ,@(copy result (make-list mid-len) header-len)))))))) (cddr form)))) ;; (case x ((0) (log x 2)) ((1) (log x 3)) (else (error 'oops))) -> (log x (case x ((0) 2) ((1) 3) (else (error 'oops)))) (lint-format "perhaps ~A" caller (lists->string form `(,@header (case ,(cadr form) ,@middle) ,@trailer)))))))) (partition-form (cddr form) (if else-error (- len 1) len))))))))) ;; ---------------- (if (every? (lambda (c) ; (case x ((a) a) ((b) b)) -> (symbol->value x) (and (pair? c) (pair? (car c)) (symbol? (caar c)) (null? (cdar c)) (pair? (cdr c)) (null? (cddr c)) (eq? (caar c) (cadr c)))) ; the quoted case happens only in test suites (cddr form)) (lint-format "perhaps (ignoring the unmatched case) ~A" caller (lists->string form `(symbol->value ,(cadr form))))) (when (= suggest made-suggestion) (let ((clauses (cddr form))) ; (case x ((a) #t) (else #f)) -> (eq? x 'a) -- this stuff actually happens! (if (null? (cdr clauses)) (let ((clause (car clauses))) (when (and (pair? clause) (pair? (car clause)) (pair? (cdr clause))) ;; (case 3 ((0) #t)) -> (if (eqv? 3 0) #t) ;; (case x ((#(0)) 2)) -> (if (eqv? x #(0)) 2) (lint-format "perhaps ~A" caller (lists->string form (let ((test (cond ((pair? (cdar clause)) `(memv ,(cadr form) ',(car clause))) ((and (symbol? (caar clause)) (not (keyword? (caar clause)))) `(eq? ,(cadr form) ',(caar clause))) ((or (keyword? (caar clause)) (null? (caar clause))) `(eq? ,(cadr form) ,(caar clause))) ((not (boolean? (caar clause))) `(eqv? ,(cadr form) ,(caar clause))) ((caar clause) (cadr form)) (else `(not ,(cadr form))))) (op (if (and (pair? (cdr clause)) (pair? (cddr clause))) 'when 'if))) `(,op ,test ,@(cdr clause))))))) (when (and (null? (cddr clauses)) (pair? (car clauses)) (pair? (cadr clauses)) (eq? (caadr clauses) 'else) (pair? (cdar clauses)) (pair? (cdadr clauses)) (null? (cddar clauses)) (null? (cddadr clauses)) (not (equal? (cadadr clauses) (cadar clauses)))) (let* ((akey (null? (cdaar clauses))) (keylist ((if akey caaar caar) clauses)) (quoted (or (not akey) (symbol? keylist))) (op (if (every? symbol? (caar clauses)) (if akey 'eq? 'memq) (if akey 'eqv? 'memv)))) ;; can't use '= or 'char=? here because the selector may return anything ;; (case x ((#\a) 3) (else 4)) -> (if (eqv? x #\a) 3 4) ;; (case x ((a) #t) (else #f)) -> (eq? x 'a) (lint-format "perhaps ~A" caller (lists->string form (cond ((and (boolean? (cadar clauses)) (boolean? (cadadr clauses))) (if (cadadr clauses) (if quoted `(not (,op ,selector ',keylist)) `(not (,op ,selector ,keylist))) (if quoted `(,op ,selector ',keylist) `(,op ,selector ,keylist)))) ((not (cadadr clauses)) ; (else #f) happens a few times (simplify-boolean (if quoted `(and (,op ,selector ',keylist) ,(cadar clauses)) `(and (,op ,selector ,keylist) ,(cadar clauses))) () () env)) (quoted `(if (,op ,selector ',keylist) ,(cadar clauses) ,(cadadr clauses))) (else (let ((select-expr (if (and (eq? op 'eqv?) (boolean? keylist) (or (and (symbol? selector) (not keylist)) (and (pair? selector) (symbol? (car selector)) (let ((sig (arg-signature (car selector) env))) (and (pair? sig) (eq? (car sig) 'boolean?)))))) (if keylist selector `(not ,selector)) `(,op ,selector ,keylist)))) `(if ,select-expr ,(cadar clauses) ,(cadadr clauses)))))))))))) (if (and (not (pair? selector)) (constant? selector)) ;; (case 3 ((0) #t)) (lint-format "case selector is a constant: ~A" caller (truncated-list->string form))) (if (symbol? selector) (set-ref selector caller form env) (lint-walk caller selector env)) (if (and (pair? selector) (symbol? (car selector))) (begin (set! sel-type (return-type (car selector) env)) (if (and (symbol? sel-type) (not (memq sel-type selector-types))) ;; (case (list 1) ((0) #t)) (lint-format "case selector may not work with eqv: ~A" caller (truncated-list->string selector))))) (let ((all-keys ()) (all-exprs ()) (ctr 0) (result :unset) (exprs-repeated #f) (else-foldable #f) (has-else #f) (len (length (cddr form)))) (for-each (lambda (clause) (set! ctr (+ ctr 1)) (if (not (pair? clause)) (lint-format "case clause should be a list: ~A" caller (truncated-list->string clause)) (let ((keys (car clause)) (exprs (cdr clause))) (if (null? exprs) ;; (case x (0)) (lint-format "clause result is missing: ~A" caller clause)) (if (eq? result :unset) (set! result exprs) (if (not (equal? result exprs)) (set! result :unequal))) (if (member exprs all-exprs) (set! exprs-repeated exprs) (set! all-exprs (cons exprs all-exprs))) (if (and (pair? exprs) (null? (cdr exprs)) (pair? (car exprs)) (pair? (cdar exprs)) (null? (cddar exprs)) (equal? selector (cadar exprs))) (if (and (eq? (caar exprs) 'not) (not (memq #f keys))) ;; (case x ((0) (f x)) ((1) (not x))) (lint-format "in ~A, perhaps replace ~A with #f" caller clause (car exprs)) ;; (case x ((0 1) (abs x))) (lint-format "perhaps use => here: ~A" caller (lists->string clause (list keys '=> (caar exprs)))))) (if (pair? keys) (if (not (proper-list? keys)) ;; (case x ((0) 1) ((1) 2) ((3 . 0) 4)) (lint-format (if (null? keys) "null case key list: ~A" "stray dot in case case key list: ~A") caller (truncated-list->string clause)) (for-each (lambda (key) (if (or (vector? key) (string? key) (pair? key)) ;; (case x ((#(0)) 2)) (lint-format "case key ~S in ~S is unlikely to work (case uses eqv? but it is a ~A)" caller key clause (cond ((vector? key) 'vector) ((pair? key) 'pair) (else 'string)))) (if (member key all-keys) ;; (case x ((0) 1) ((1) 2) ((3 0) 4)) (lint-format "repeated case key ~S in ~S" caller key clause) (set! all-keys (cons key all-keys))) ;; unintentional quote here, as in (case x ('a b)...) never happens and ;; is hard to distinguish from (case x ((quote a) b)...) which happens a lot (if (not (compatible? sel-type (->lint-type key))) ;; (case (string->symbol x) ((a) 1) ((2 3) 3)) (lint-format "case key ~S in ~S is pointless" caller key clause))) keys)) (if (not (eq? keys 'else)) ;; (case ((1) 1) (t 2)) (lint-format "bad case key ~S in ~S" caller keys clause) (begin (set! has-else clause) ;; exprs: (res) or if case, ((case ...)...) (if (not (= ctr len)) ;; (case x (else 2) ((0) 1)) (lint-format "case else clause is not the last: ~A" caller (truncated-list->string (cddr form))) (when (and (pair? exprs) (pair? (car exprs)) (null? (cdr exprs))) (case (caar exprs) ((case) ; just the case statement in the else clause (when (and (equal? selector (cadar exprs)) (not (side-effect? selector env))) (set! else-foldable (cddar exprs)))) ((if) ; just if -- if foldable, make it look like it came from case (when (and (equal? selector (eqv-selector (cadar exprs))) (cond-eqv? (cadar exprs) selector #t) (not (side-effect? selector env))) ;; else-foldable as (((keys-from-test) true-branch) (else false-branch)) (set! else-foldable (if (pair? (cdddar exprs)) `(,(case-branch (cadar exprs) selector (list (caddar exprs))) (else ,(car (cdddar exprs)))) (list (case-branch (cadar exprs) selector (cddar exprs))))))))))))) (lint-walk-open-body caller (car form) exprs env)))) (cddr form)) (if (and has-else (pair? result) (not else-foldable)) (begin ;; (case x (else (case x (else 1)))) -> 1 (lint-format "perhaps ~A" caller (lists->string form (if (null? (cdr result)) (car result) `(begin ,@result)))) (set! exprs-repeated #f))) ;; repeated result (but not all completely equal) and with else never happens (when (or exprs-repeated else-foldable) (let ((new-keys-and-exprs ()) (mergers ()) (else-clause (if else-foldable (call-with-exit (lambda (return) (for-each (lambda (c) (if (eq? (car c) 'else) (return c))) else-foldable) ())) (or has-else ())))) (let ((merge-case-keys (let ((else-exprs (and (pair? else-clause) (cdr else-clause)))) (define (a-few lst) (if (> (length lst) 3) (copy lst (make-list 4 '...) 0 3) lst)) (lambda (clause) (let ((keys (car clause)) (exprs (cdr clause))) (when (and (pair? exprs) ; ignore clauses that are messed up (not (eq? keys 'else)) (not (equal? exprs else-exprs))) (let ((prev (member exprs new-keys-and-exprs (lambda (a b) (equal? a (cdr b)))))) (if prev (let* ((cur-clause (car prev)) (cur-keys (car cur-clause))) (when (pair? cur-keys) (set! mergers (cons (list (a-few keys) (a-few cur-keys)) mergers)) (set-car! cur-clause (append cur-keys (map (lambda (key) (if (memv key cur-keys) (values) key)) keys))))) (set! new-keys-and-exprs (cons (cons (copy (car clause)) (cdr clause)) new-keys-and-exprs)))))))))) (for-each merge-case-keys (cddr form)) (if (pair? else-foldable) (for-each merge-case-keys else-foldable))) (if (null? new-keys-and-exprs) (lint-format "perhaps ~A" caller ;; (case x (else (case x (else 1)))) -> 1 (lists->string form (if (or (null? else-clause) ; can this happen? (it's caught above as an error) (null? (cdr else-clause))) () (if (null? (cddr else-clause)) (cadr else-clause) `(begin ,@(cdr else-clause)))))) (begin ;; (null? (cdr new-keys-and-exprs)) is rare and kinda dumb -- cases look like test suite entries (for-each (lambda (clause) (if (and (pair? (car clause)) (pair? (cdar clause))) (if (every? integer? (car clause)) (set-car! clause (sort! (car clause) <)) (if (every? char? (car clause)) (set-car! clause (sort! (car clause) char<?)))))) new-keys-and-exprs) (let ((new-form (if (pair? else-clause) `(case ,(cadr form) ,@(reverse new-keys-and-exprs) ,else-clause) `(case ,(cadr form) ,@(reverse new-keys-and-exprs))))) ;; (case x ((0) 32) ((1) 32)) -> (case x ((0 1) 32)) (lint-format "perhaps ~A" caller (if (pair? mergers) (format #f "merge keys ~{~{~A with ~A~}~^, ~}: ~A" (reverse mergers) (lists->string form new-form)) (lists->string form new-form))))))))))) env))) (hash-table-set! h 'case case-walker)) ;; ---------------- do ---------------- (let ((cxars (hash-table (cons 'car (lambda (sym) sym)) (cons 'caar (lambda (sym) (list 'car sym))) (cons 'cdar (lambda (sym) (list 'cdr sym))) (cons 'caaar (lambda (sym) (list 'caar sym))) (cons 'cdaar (lambda (sym) (list 'cdar sym))) (cons 'cddar (lambda (sym) (list 'cddr sym))) (cons 'cadar (lambda (sym) (list 'cadr sym))) (cons 'caaaar (lambda (sym) (list 'caaar sym))) (cons 'caadar (lambda (sym) (list 'caadr sym))) (cons 'cadaar (lambda (sym) (list 'cadar sym))) (cons 'caddar (lambda (sym) (list 'caddr sym))) (cons 'cdaaar (lambda (sym) (list 'cdaar sym))) (cons 'cdadar (lambda (sym) (list 'cdadr sym))) (cons 'cddaar (lambda (sym) (list 'cddar sym))) (cons 'cdddar (lambda (sym) (list 'cdddr sym)))))) (define (car-subst sym new-sym tree) (cond ((or (not (pair? tree)) (eq? (car tree) 'quote)) tree) ((not (and (symbol? (car tree)) (pair? (cdr tree)) (null? (cddr tree)) (eq? sym (cadr tree)))) (cons (car-subst sym new-sym (car tree)) (car-subst sym new-sym (cdr tree)))) ((hash-table-ref cxars (car tree)) => (lambda (f) (f new-sym))) (else tree))) (define (var-step v) ((cdr v) 'step)) (define (do-walker caller form env) (let ((vars ())) (if (not (and (>= (length form) 3) (proper-list? (cadr form)) (proper-list? (caddr form)))) (lint-format "do is messed up: ~A" caller (truncated-list->string form)) (let ((step-vars (cadr form)) (inner-env #f)) ;; do+lambda in body with stepper as free var never happens (if (not (side-effect? form env)) (let ((end+result (caddr form))) (if (or (not (pair? end+result)) (null? (cdr end+result))) ;; (do ((i 0 (+ i 1))) ((= i 1))) (lint-format "this do-loop could be replaced by (): ~A" caller (truncated-list->string form)) (if (and (null? (cddr end+result)) (code-constant? (cadr end+result))) ;; (begin (z 1) (do ((i 0 (+ i 1))) ((= i n) 32))): 32 (lint-format "this do-loop could be replaced by ~A: ~A" caller (cadr end+result) (truncated-list->string form)))))) ;; walk the init forms before adding the step vars to env (do ((bindings step-vars (cdr bindings))) ((not (pair? bindings)) (if (not (null? bindings)) (lint-format "do variable list is not a proper list? ~S" caller step-vars))) (when (binding-ok? caller 'do (car bindings) env #f) (for-each (lambda (v) (if (not (or (eq? (var-initial-value v) (var-name v)) (not (tree-memq (var-name v) (cadar bindings))) (hash-table-ref built-in-functions (var-name v)) (tree-table-member binders (cadar bindings)))) (if (not (var-member (var-name v) env)) ;; (let ((xx 0)) (do ((x 1 (+ x 1)) (y x (- y 1))) ((= x 3) xx) (display y)): x (lint-format "~A in ~A does not appear to be defined in the calling environment" caller (var-name v) (car bindings)) ;; (let ((x 0)) (do ((x 1 (+ x 1)) (y x (- y 1))) ((= x 3)) (display y))): y (lint-format "~A in ~A refers to the caller's ~A, not the do-loop variable" caller (var-name v) (car bindings) (var-name v))))) vars) (lint-walk caller (cadar bindings) env) (let ((new-var (let ((v (make-var :name (caar bindings) :definer 'do :initial-value (cadar bindings)))) (let ((stepper (and (pair? (cddar bindings)) (caddar bindings)))) (varlet (cdr v) :step stepper) (if stepper (set! (var-history v) (cons (list 'set! (caar bindings) stepper) (var-history v))))) v))) (set! vars (cons new-var vars))))) (set! inner-env (append vars env)) ;; walk the step exprs (let ((baddies ())) ; these are step vars (with step exprs) used within other step vars step expressions (do ((bindings step-vars (cdr bindings))) ((not (pair? bindings))) (let ((stepper (car bindings))) ; the entire binding: '(i 0 (+ i 1)) (when (and (binding-ok? caller 'do stepper env #t) (pair? (cddr stepper))) (let ((data (var-member (car stepper) vars))) (let ((old-ref (var-ref data))) (lint-walk caller (caddr stepper) inner-env) (set! (var-ref data) old-ref)) (if (eq? (car stepper) (caddr stepper)) ; (i 0 i) -> (i 0) (lint-format "perhaps ~A" caller (lists->string stepper (list (car stepper) (cadr stepper))))) ;; pointless caddr here happens very rarely (set! (var-set data) (+ (var-set data) 1))) ; (pair? cddr) above (when (and (pair? (caddr stepper)) (not (eq? (car stepper) (cadr stepper))) ; (lst lst (cdr lst)) (eq? (car (caddr stepper)) 'cdr) (eq? (cadr stepper) (cadr (caddr stepper)))) ;; (do ((x lst (cdr lst))) ((null? x) y)) (lint-format "this looks suspicious: ~A" caller stepper)) (for-each (lambda (v) (if (and (var-step v) (not (eq? (var-name v) (car stepper))) (or (eq? (var-name v) (caddr stepper)) (and (pair? (caddr stepper)) (tree-unquoted-member (var-name v) (caddr stepper))))) (set! baddies (cons (car stepper) baddies)))) vars)))) (check-unordered-exprs caller form (map var-initial-value vars) env) (when (pair? baddies) ;; (do ((i 0 j) (j ...))...) is unreadable -- which (binding of) j is i set to? ;; but this is tricky if there is more than one such variable -- if cross links, we'll need named let ;; and if no step expr, there's no confusion. ;; (do ((i 0 j) (j 1 i) (k 0 (+ k 1))) ((= k 4)) (format *stderr* "~A ~A~%" i j)) ;; (let __1__ ((i 0) (j 1) (k 0)) (if (= k 4) () (begin (format *stderr* "~A ~A~%" i j) (__1__ j i (+ k 1))))) (let ((new-steppers (map (lambda (stepper) (if (memq (car stepper) baddies) `(,(car stepper) ,(cadr stepper)) stepper)) step-vars)) (new-sets (map (lambda (stepper) (if (memq (car stepper) baddies) `(set! ,(car stepper) ,(caddr stepper)) (values))) step-vars))) (if (or (null? (cdr baddies)) (let ((trails new-sets)) (not (any? (lambda (v) ; for each baddy, is it used in any following set!? (and (pair? (cdr trails)) (set! trails (cdr trails)) (tree-unquoted-member v trails))) (reverse baddies))))) (lint-format "perhaps ~A" caller (lists->string form `(do ,new-steppers ,(caddr form) ,@(cdddr form) ,@new-sets))) ;; (do ((i 0 (+ i j)) (j 0 (+ k 1)) (k 1)) ((= i 10)) (display (+ i j k))) -> ;; (do ((i 0) (j 0 (+ k 1)) (k 1)) ((= i 10)) (display (+ i j k)) (set! i (+ i j))) (let* ((loop (find-unique-name form)) (new-body (let ((let-loop `(,loop ,@(map (lambda (s) ((if (pair? (cddr s)) caddr car) s)) step-vars)))) (if (pair? (cdddr form)) `(begin ,@(cdddr form) ,let-loop) let-loop)))) (let ((test (if (pair? (caddr form)) (caaddr form) ())) (result (if (not (and (pair? (caddr form)) (pair? (cdaddr form)))) () (if (null? (cdr (cdaddr form))) (car (cdaddr form)) `(begin ,@(cdaddr form)))))) ;; (do ((i 0 j) (j 1 i) (k 0 (+ k 1))) ((= k 5) (set! x k) (+ k 1)) (display (+ i j)) -> use named let (lint-format "this do loop is unreadable; perhaps ~A" caller (lists->string form `(let ,loop ,(map (lambda (s) (list (car s) (cadr s))) step-vars) (if ,test ,result ,new-body)))))))))) ;; walk the body and end stuff (it's too tricky to find infinite do loops) (when (pair? (caddr form)) (let ((end+result (caddr form))) (when (pair? end+result) (let ((end (car end+result))) (lint-walk caller end inner-env) ; this will call simplify-boolean (if (pair? (cdr end+result)) (if (null? (cddr end+result)) (begin (if (any-null? (cadr end+result)) ;; (do ((i 0 (+ i 1))) ((= i 3) ()) (display i)) (lint-format "nil return value is redundant: ~A" caller end+result)) (lint-walk caller (cadr end+result) inner-env)) (lint-walk-open-body caller 'do-result (cdr end+result) inner-env))) (if (and (symbol? end) (memq end '(= > < >= <= null? not))) ;; (do ((i 0 (+ i 1))) (= i 10) (display i)) (lint-format "perhaps missing parens: ~A" caller end+result)) (cond ((never-false end) ;; (do ((i 0 (+ i 1))) ((+ i 10) i)) (lint-format "end test is never false: ~A" caller end)) (end ; it's not #f (if (never-true end) (lint-format "end test is never true: ~A" caller end) (let ((v (and (pair? end) (memq (car end) '(< > <= >=)) (pair? (cdr end)) (symbol? (cadr end)) (var-member (cadr end) vars)))) ;; if found, v is the var info (when (pair? v) (let ((step (var-step v))) (when (pair? step) (let ((inc (and (memq (car step) '(+ -)) (pair? (cdr step)) (pair? (cddr step)) (or (and (real? (cadr step)) (cadr step)) (and (real? (caddr step)) (caddr step)))))) (when (and (real? inc) (case (car step) ((+) (and (positive? inc) (memq (car end) '(< <=)))) ((-) (and (positive? inc) (memq (car end) '(> >=)))) (else #f))) ;; (do ((i 0 (+ i 1))) ((< i len)) (display i) ;; (do ((i 0 (- i 1))) ((> i len)) (display i)) (lint-format "do step looks like it doesn't match end test: ~A" caller (lists->string step end)))))))))) ((pair? (cdr end+result)) ;; (do ((i 0 (+ i 1))) (#f i)) (lint-format "result is unreachable: ~A" caller end+result))) (if (and (symbol? end) (not (var-member end env)) (procedure? (symbol->value end *e*))) ;; (do ((i 0 (+ i 1))) (abs i) (display i)) (lint-format "strange do end-test: ~A in ~A is a procedure" caller end end+result)))))) (lint-walk-body caller 'do (cdddr form) (cons (make-var :name :let :initial-value form :definer 'do) inner-env)) ;; before report-usage, check for unused variables, and don't complain about them if ;; they are referenced in an earlier step expr. (do ((v vars (cdr v))) ((null? v)) (let ((var (car v))) (when (zero? (var-ref var)) ;; var was not seen in the end+result/body or any subsequent step exprs ;; vars is reversed order, so we need only scan var-step of the rest (if (side-effect? (var-step var) env) (set! (var-ref var) (+ (var-ref var) 1)) (for-each (lambda (nv) (if (or (eq? (var-name var) (var-step nv)) (and (pair? (var-step nv)) (tree-unquoted-member (var-name var) (var-step nv)))) (set! (var-ref var) (+ (var-ref var) 1)))) (cdr v)))))) (report-usage caller 'do vars inner-env) ;; look for constant expressions in the do body (when *report-constant-expressions-in-do* (let ((constant-exprs (find-constant-exprs 'do (map var-name vars) (cdddr form)))) (if (pair? constant-exprs) (if (null? (cdr constant-exprs)) ;; (do ((p (list 1) (cdr p))) ((null? p)) (set! y (log z 2)) (display x)) (lint-format "in ~A, ~A appears to be constant" caller (truncated-list->string form) (car constant-exprs)) (lint-format "in ~A, the following expressions appear to be constant:~%~NC~A" caller (truncated-list->string form) (+ lint-left-margin 4) #\space (format #f "~{~A~^, ~}" constant-exprs)))))) ;; if simple lambda expanded and exists only for the loop, remove let as well? ;; this can sometimes be simplified (let ((body (cdddr form))) (when (and (pair? body) (null? (cdr body)) (pair? (car body))) (let ((v (var-member (caar body) env))) (when (and (var? v) (memq (var-ftype v) '(define lambda))) (let* ((vfunc (var-initial-value v)) (vbody (cddr vfunc))) ;; we already detect a do body with no side-effects (walk-body) (if (and (proper-list? ((if (eq? (var-ftype v) 'define) cdadr cadr) vfunc)) (null? (cdr vbody)) (< (tree-leaves vbody) 16)) (do ((pp (var-arglist v) (cdr pp))) ((or (null? pp) (> (tree-count1 (car pp) vbody 0) 1)) (when (null? pp) (let ((new-body (copy vbody))) (for-each (lambda (par arg) (if (not (eq? par arg)) (set! new-body (tree-subst arg par new-body)))) (var-arglist v) (cdar body)) ;; (do ((i 0 (+ i 1))) ((= i 10)) (f i)) -> (do ((i 0 (+ i 1))) ((= i 10)) (abs (* 2 i))) (lint-format "perhaps ~A" caller (lists->string form `(do ,(cadr form) ,(caddr form) ,@new-body))))))))))))) ;; do -> for-each ;; TODO: handle two lists (when (and (pair? (cadr form)) (null? (cdadr form))) (let ((var (caadr form))) (when (and (pair? (cdr var)) (pair? (cddr var)) (pair? (caddr var)) (eq? (caaddr var) 'cdr) (eq? (car var) (cadr (caddr var))) (pair? (caddr form)) (pair? (caaddr form)) (null? (cdaddr form))) (let ((vname (car var)) (end (caaddr form))) (when (and (case (car end) ((null?) (eq? (cadr end) vname)) ((not) (and (pair? (cadr end)) (eq? (caadr end) 'pair?) (eq? (cadadr end) vname))) (else #f)) (not (let walker ((tree (cddr form))) ; since only (cxar sym) is accepted, surely sym can't be shadowed? (and (pair? tree) (or (and (match-cxr 'cdr (car tree)) (pair? (cdr tree)) (eq? vname (cadr tree))) (and (not (hash-table-ref cxars (car tree))) (pair? (cdr tree)) (any? (lambda (p) (or (eq? p vname) (and (pair? p) (walker p)))) (cdr tree)))))))) ;; this assumes slightly more than the do-loop if (not (pair? var)) is the end-test ;; for-each wants a sequence, but the do loop checks that in advance. (lint-format "perhaps ~A" caller (lists->string form (let ((new-sym (symbol "[" (symbol->string vname) "]"))) `(for-each (lambda (,new-sym) ,@(car-subst vname new-sym (cdddr form))) ,(cadr var)))))))))) ;; check for do-loop as copy/fill! stand-in and other similar cases (when (and (pair? vars) (null? (cdr vars))) (let ((end-test (and (pair? (caddr form)) (caaddr form))) (first-var (caadr form)) (body (cdddr form)) (setv #f)) (when (and (pair? end-test) (pair? body) (null? (cdr body)) (pair? (car body)) (memq (car end-test) '(>= =))) (let ((vname (car first-var)) (start (cadr first-var)) (step (and (pair? (cddr first-var)) (caddr first-var))) (end (caddr end-test))) (when (and (pair? step) (eq? (car step) '+) (memq vname step) (memv 1 step) (null? (cdddr step)) (or (eq? (cadr end-test) vname) (and (eq? (car end-test) '=) (eq? (caddr end-test) vname) (set! end (cadr end-test))))) ;; we have (do ((v start (+ v 1)|(+ 1 v))) ((= v end)|(= end v)|(>= v end)) one-statement) (set! body (car body)) ;; write-char is the only other common case here -> write-string in a few cases (when (and (memq (car body) '(vector-set! float-vector-set! int-vector-set! list-set! string-set! byte-vector-set!)) ;; integer type check here isn't needed because we're using this as an index below ;; the type error will be seen in report-usage if not earlier (eq? (caddr body) vname) (let ((val (cadddr body))) (set! setv val) (or (code-constant? val) (and (pair? val) (memq (car val) '(vector-ref float-vector-ref int-vector-ref list-ref string-ref byte-vector-ref)) (eq? (caddr val) vname))))) ;; (do ((i 2 (+ i 1))) ((= i len)) (string-set! s i #\a)) -> (fill! s #\a 2 len) (lint-format "perhaps ~A" caller (lists->string form (if (code-constant? setv) `(fill! ,(cadr body) ,(cadddr body) ,start ,end) `(copy ,(cadr setv) ,(cadr body) ,start ,end)))))))))))) env)) (hash-table-set! h 'do do-walker)) ;; ---------------- let ---------------- (let () (define (let-walker caller form env) (if (or (< (length form) 3) (not (or (symbol? (cadr form)) (list? (cadr form))))) ;; (let ((a 1) (set! a 2))) (lint-format "let is messed up: ~A" caller (truncated-list->string form)) (let ((named-let (and (symbol? (cadr form)) (cadr form)))) (if (keyword? named-let) ;; (let :x ((i y)) (x i)) (lint-format "bad let name: ~A" caller named-let)) (unless named-let (if (and (null? (cadr form)) ; this can be fooled by macros that define things (eq? form lint-current-form) ; i.e. we're in a body? (not (tree-set-member '(call/cc call-with-current-continuation lambda lambda* define define* define-macro define-macro* define-bacro define-bacro* define-constant define-expansion load eval eval-string require) (cddr form)))) ;; (begin (let () (display x)) y) (lint-format "pointless let: ~A" caller (truncated-list->string form)) (let ((body (cddr form))) (when (and (null? (cdr body)) (pair? (car body))) (if (memq (caar body) '(let let*)) (if (null? (cadr form)) ;; (let () (let ((a x)) (+ a 1))) (lint-format "pointless let: ~A" caller (lists->string form (car body))) (if (null? (cadar body)) ;; (let ((a x)) (let () (+ a 1))) (lint-format "pointless let: ~A" caller (lists->string form `(let ,(cadr form) ,@(cddar body)))))) (if (and (memq (caar body) '(lambda lambda*)) ; or any definer? (null? (cadr form))) ;; (let () (lambda (a b) (if (positive? a) (+ a b) b))) -> (lambda (a b) (if (positive? a) (+ a b) b)) (lint-format "pointless let: ~A" caller (lists->string form (car body))))))))) (let ((vars (if (or (not named-let) (keyword? named-let) (not (or (null? (caddr form)) (and (proper-list? (caddr form)) (every? pair? (caddr form)))))) () (list (make-fvar :name named-let :ftype 'let :decl (dummy-func caller form (list 'define (cons '_ (map car (caddr form))) #f)) :arglist (map car (caddr form)) :initial-value form :env env)))) (varlist ((if named-let caddr cadr) form)) (body ((if named-let cdddr cddr) form))) (if (not (list? varlist)) (lint-format "let is messed up: ~A" caller (truncated-list->string form)) (if (and (null? varlist) (pair? body) (null? (cdr body)) (not (side-effect? (car body) env))) ;; (let xx () z) (lint-format "perhaps ~A" caller (lists->string form (car body))))) (do ((bindings varlist (cdr bindings))) ((not (pair? bindings)) (if (not (null? bindings)) ;; (let ((a 1) . b) a) (lint-format "let variable list is not a proper list? ~S" caller varlist))) (when (binding-ok? caller 'let (car bindings) env #f) (let ((val (cadar bindings))) (if (and (pair? val) (eq? 'lambda (car val)) (tree-car-member (caar bindings) val) (not (var-member (caar bindings) env))) ;; (let ((x (lambda (a) (x 1)))) x) (lint-format "let variable ~A is called in its binding? Perhaps let should be letrec: ~A" caller (caar bindings) (truncated-list->string bindings)) (unless named-let (for-each (lambda (v) (if (and (tree-memq (var-name v) (cadar bindings)) (not (hash-table-ref built-in-functions (var-name v))) (not (tree-table-member binders (cadar bindings)))) (if (not (var-member (var-name v) env)) ;; (let ((x 1) (y x)) (+ x y)): x in (y x) (lint-format "~A in ~A does not appear to be defined in the calling environment" caller (var-name v) (car bindings)) ;; (let ((x 3)) (+ x (let ((x 1) (y x)) (+ x y)))): x in (y x) (lint-format "~A in ~A refers to the caller's ~A, not the let variable" caller (var-name v) (car bindings) (var-name v))))) vars))) (lint-walk caller val env) (set! vars (cons (make-var :name (caar bindings) :initial-value val :definer (if named-let 'named-let 'let)) vars))))) (check-unordered-exprs caller form (map (if (not named-let) var-initial-value (lambda (v) (if (eq? (var-name v) named-let) (values) (var-initial-value v)))) vars) env) (let ((suggest made-suggestion)) (when (and (pair? varlist) ; (let ((x (A))) (if x (f x) B)) -> (cond ((A) => f) (else B) (pair? body) (pair? (car body)) (null? (cdr body)) (pair? (cdar body))) (when (and (pair? (car varlist)) ; ^ this happens a lot, so it's worth this tedious search (null? (cdr varlist)) ; also (let ((x (A))) (cond (x (f x))...) (pair? (cdar varlist)) (pair? (cadar varlist))) (let ((p (car body)) (vname (caar varlist)) (vvalue (cadar varlist))) (when (and (not named-let) ; (let ((x (assq a y))) (set! z (if x (cadr x) 0))) -> (set! z (cond ((assq a y) => cadr) (else 0))) (not (memq (car p) '(if cond))) ; handled separately below (= (tree-count2 vname p 0) 2)) (do ((i 0 (+ i 1)) (bp (cdr p) (cdr bp))) ((or (null? bp) (let ((b (car bp))) (and (pair? b) (eq? (car b) 'if) (= (tree-count2 vname b 0) 2) (eq? vname (cadr b)) (pair? (caddr b)) (pair? (cdaddr b)) (null? (cddr (caddr b))) (eq? vname (cadr (caddr b)))))) (if (pair? bp) (let ((else-clause (if (pair? (cdddar bp)) `((else ,@(cdddar bp))) ()))) (lint-format "perhaps ~A" caller (lists->string form `(,@(copy p (make-list (+ i 1))) (cond (,vvalue => ,(caaddr (car bp))) ,@else-clause) ,@(cdr bp))))))))) (when (and (eq? (car p) 'cond) ; (let ((x (f y))) (cond (x (g x)) ...)) -> (cond ((f y) => g) ...) (pair? (cadr p)) (eq? (caadr p) vname) (pair? (cdadr p)) (null? (cddadr p)) (or (and (pair? (cadadr p)) (pair? (cdr (cadadr p))) (null? (cddr (cadadr p))) ; one arg to func (eq? vname (cadr (cadadr p)))) (eq? vname (cadadr p))) (or (null? (cddr p)) (not (tree-unquoted-member vname (cddr p))))) (lint-format "perhaps ~A" caller (lists->string form (if (eq? vname (cadadr p)) (if (and (pair? (cddr p)) (pair? (caddr p)) (memq (caaddr p) '(else #t t))) (if (null? (cddr (caddr p))) `(or ,vvalue ,(cadr (caddr p))) `(or ,vvalue (begin ,@(cdaddr p)))) `(or ,vvalue (cond ,@(cddr p)))) `(cond (,vvalue => ,(caadr (cadr p))) ,@(cddr p)))))) (when (and (null? (cddr p)) ; (let ((x (+ y 1))) (abs x)) -> (abs (+ y 1)) (eq? vname (cadr p))) ; not tree-subst or trailing (pair) args: the let might be forcing evaluation order (let ((v (var-member (car p) env))) (if (or (and (var? v) (memq (var-definer v) '(define define* lambda lambda*))) (hash-table-ref built-in-functions (car p))) (lint-format "perhaps ~A" caller (lists->string form `(,(car p) ,vvalue))) (if (not (or (any-macro? vname env) (tree-unquoted-member vname (car p)))) (lint-format "perhaps, assuming ~A is not a macro, ~A" caller (car p) (lists->string form `(,(car p) ,vvalue))))))) (when (pair? (cddr p)) (when (and (eq? (car p) 'if) (pair? (cdddr p))) (let ((if-true (caddr p)) (if-false (cadddr p))) (when (and (eq? (cadr p) vname) ; (let ((x (g y))) (if x #t #f)) -> (g y) (boolean? if-true) (boolean? if-false) (not (eq? if-true if-false))) (lint-format "perhaps ~A" caller (lists->string form (if if-true vvalue `(not ,vvalue))))) (when (and (pair? (cadr p)) ; (let ((x (f y))) (if (not x) B (g x))) -> (cond ((f y) => g) (else B)) (eq? (caadr p) 'not) (eq? (cadadr p) vname) (pair? if-false) (pair? (cdr if-false)) (null? (cddr if-false)) (eq? vname (cadr if-false))) (let ((else-clause (if (eq? if-true vname) `((else #f)) (if (and (pair? if-true) (tree-unquoted-member vname if-true)) :oops! ; if the let var appears in the else portion, we can't do anything with => `((else ,if-true)))))) (unless (eq? else-clause :oops!) (lint-format "perhaps ~A" caller (lists->string form `(cond (,vvalue => ,(car if-false)) ,@else-clause)))))))) (let ((crf #f)) ;; all this stuff still misses (cond ((not x)...)) and (set! y (if x (cdr x)...)) i.e. need embedding in this case (when (and (or (and (memq (car p) '(if and)) ; (let ((x (f y))) (and x (g x))) -> (cond ((f y) => g) (else #f)) (eq? (cadr p) vname)) (and (eq? (car p) 'or) (equal? (cadr p) `(not ,vname))) (and (pair? vvalue) (memq (car vvalue) '(assoc assv assq member memv memq)) (pair? (cadr p)) (or (eq? (caadr p) 'pair?) (and (eq? (caadr p) 'null?) ;; (let ((x (assoc y z))) (if (null? x) (g x))) (lint-format "in ~A, ~A can't be null because ~A in ~A only returns #f or a pair" caller p vname (car vvalue) (truncated-list->string (car varlist))) #f)) (eq? (cadadr p) vname))) (or (and (pair? (caddr p)) (pair? (cdaddr p)) (null? (cddr (caddr p))) ; one func arg (or (eq? vname (cadr (caddr p))) (and (hash-table-ref combinable-cxrs (caaddr p)) ((lambda* (cr arg) ; lambda* not lambda because combine-cxrs might return just #f (and cr (< (length cr) 5) (eq? vname arg) (set! crf (symbol "c" cr "r")))) (combine-cxrs (caddr p)))))) (and (eq? (car p) 'if) (eq? (caddr p) vname) (not (tree-unquoted-member vname (cdddr p))) ;; (let ((x (g y))) (if x x (g z))) -> (or (g y) (g z)) (lint-format "perhaps ~A" caller (lists->string form (if (null? (cdddr p)) vvalue `(or ,vvalue ,(cadddr p))))) #f)) (pair? (caddr p)) (or (eq? (car p) 'if) (null? (cdddr p)))) (let ((else-clause (if (pair? (cdddr p)) (if (eq? (cadddr p) vname) `((else #f)) ; this stands in for the local var (if (and (pair? (cadddr p)) (tree-unquoted-member vname (cadddr p))) :oops! ; if the let var appears in the else portion, we can't do anything with => `((else ,(cadddr p))))) (case (car p) ((and) '((else #f))) ((or) '((else #t))) (else ()))))) (unless (eq? else-clause :oops!) ;; (let ((x (assoc y z))) (if x (cdr x))) -> (cond ((assoc y z) => cdr)) (lint-format "perhaps ~A" caller (lists->string form `(cond (,vvalue => ,(or crf (caaddr p))) ,@else-clause)))))))) )) ; one var in varlist ;; (let ((x 1) (y 2)) (+ x y)) -> (+ 1 2) ;; this happens a lot, but it often looks like a form of documentation (when (and (= suggest made-suggestion) (not named-let) (< (length varlist) 8) (not (memq (caar body) '(lambda lambda* define define* define-macro))) (not (and (eq? (caar body) 'set!) (any? (lambda (v) (eq? (car v) (cadar body))) varlist))) (not (any-macro? (caar body) env)) (not (any? (lambda (p) (and (pair? p) (not (eq? (car p) 'quote)) (or (not (hash-table-ref no-side-effect-functions (car p))) (any? pair? (cdr p))))) (cdar body))) (every? (lambda (v) (and (pair? v) (pair? (cdr v)) (< (tree-leaves (cadr v)) 8) (= (tree-count1 (car v) body 0) 1))) varlist)) (let ((new-body (copy (car body))) (bool-arg? #f)) (for-each (lambda (v) (if (not bool-arg?) (let tree-walk ((tree body)) (if (pair? tree) (if (and (memq (car tree) '(or and)) (memq (car v) (cdr tree))) (set! bool-arg? #t) (begin (tree-walk (car tree)) (tree-walk (cdr tree))))))) (set! new-body (tree-subst (cadr v) (car v) new-body))) varlist) (lint-format (if bool-arg? "perhaps, ignoring short-circuit issues, ~A" "perhaps ~A") caller (lists->string form new-body)))) ) ; null cdr body etc (when (and (pair? (cadr form)) ; (let ((x x)) (+ x 1)) -> (+ x 1), (let ((x x))...) does not copy x if x is a sequence (= suggest made-suggestion) (every? (lambda (c) (and (pair? c) ; the usual... (let binding might be messed up) (pair? (cdr c)) (eq? (car c) (cadr c)))) (cadr form)) (not (and (pair? (caddr form)) (memq (caaddr form) '(lambda lambda*))))) (let ((vs (map car (cadr form)))) (unless (any? (lambda (p) (and (pair? p) (memq (cadr p) vs) (or (eq? (car p) 'set!) (set!? p env)))) (cddr form)) (lint-format "perhaps omit this useless let: ~A" caller (truncated-lists->string form (if (null? (cdddr form)) (caddr form) `(begin ,@(cddr form)))))))) ) ; suggest let (let* ((cur-env (cons (make-var :name :let :initial-value form :definer 'let) (append vars env))) (e (lint-walk-body (or named-let caller) 'let body cur-env))) (let ((nvars (and (not (eq? e cur-env)) (env-difference caller e cur-env ())))) (if (pair? nvars) (if (memq (var-name (car nvars)) '(:lambda :dilambda)) (begin (set! env (cons (car nvars) env)) (set! nvars (cdr nvars))) (set! vars (append nvars vars))))) (if (and (pair? body) (equal? (list-ref body (- (length body) 1)) '(curlet))) ; the standard library tag (for-each (lambda (v) (set! (var-ref v) (+ (var-ref v) 1))) e)) (report-usage caller 'let vars cur-env) ;; look for splittable lets and let-temporarily possibilities (when (and (pair? vars) (pair? (cadr form)) (pair? (caadr form))) (for-each (lambda (local-var) (let ((vname (var-name local-var))) ;; ideally we'd collect vars that fit into one let etc (when (> (length body) (* 5 (var-set local-var)) 0) (do ((i 0 (+ i 1)) (preref #f) (p body (cdr p))) ((or (not (pair? (cdr p))) (and (pair? (car p)) (eq? (caar p) 'set!) (eq? (cadar p) vname) (> i 5) (begin (if (or preref (side-effect? (var-initial-value local-var) env)) ;; (let ((x 32)) (display x) (set! y (f x)) (g (+ x 1) y) (a y) (f y) (g y) (h y) (i y) (set! x 3) (display x) (h y x)) ;; (let ... (let ((x 3)) ...)) (lint-format "perhaps add a new binding for ~A to replace ~A: ~A" caller vname (truncated-list->string (car p)) (lists->string form `(let ... (let ((,vname ,(caddar p))) ...)))) ;; (let ((x 32)) (set! y (f 1)) (a y) (f y) (g y) (h y) (i y) (set! x (+ x... -> (let () ... (let ((x (+ 32 1))) ...)) (lint-format "perhaps move the ~A binding to replace ~A: ~A" caller vname (truncated-list->string (car p)) (let ((new-value (if (tree-member vname (caddar p)) (tree-subst (var-initial-value local-var) vname (copy (caddar p))) (caddar p)))) (lists->string form `(let ,(let rewrite ((lst (cadr form))) (cond ((null? lst) ()) ((and (pair? (car lst)) (eq? (caar lst) vname)) (rewrite (cdr lst))) (else (cons (if (< (tree-leaves (cadar lst)) 30) (car lst) (list (caar lst) '...)) (rewrite (cdr lst)))))) ... (let ((,vname ,new-value)) ...)))))) #t)))) (if (tree-member vname (car p)) (set! preref i)))) (when (and (zero? (var-set local-var)) (= (var-ref local-var) 2) ; initial value and set! (symbol? (var-initial-value local-var))) (do ((saved-name (var-initial-value local-var)) (p body (cdr p)) (last-pos #f) (first-pos #f)) ((not (pair? p)) (when (and (pair? last-pos) (not (eq? first-pos last-pos)) (not (tree-member saved-name (cdr last-pos)))) ;; (let ((old-x x)) (set! x 12) (display (log x)) (set! x 1) (set! x old-x)) -> ;; (let-temporarily ((x 12)) (display (log x)) (set! x 1)) (lint-format "perhaps use let-temporarily here (see stuff.scm): ~A" caller (lists->string form (let ((new-let `(let-temporarily ((,saved-name ,(if (pair? first-pos) (caddar first-pos) saved-name))) ,@(map (lambda (expr) (if (or (and (pair? first-pos) (eq? expr (car first-pos))) (eq? expr (car last-pos))) (values) expr)) body)))) (if (null? (cdr vars)) ; we know vars is a pair, want len=1 new-let `(let ,(map (lambda (v) (if (eq? (car v) vname) (values) v)) (cadr form)) ,new-let))))))) ;; someday maybe look for additional saved vars, but this happens only in snd-test ;; also the let-temp could be reduced to the set locations (so the tree-member ;; check above would be unneeded). (let ((expr (car p))) (when (and (pair? expr) (eq? (car expr) 'set!) (eq? (cadr expr) saved-name) (pair? (cddr expr))) (if (not first-pos) (set! first-pos p)) (if (eq? (caddr expr) vname) (set! last-pos p)))))))) vars))) (when (and (pair? varlist) (pair? (car varlist)) (null? (cdr varlist))) (if (and (pair? body) ; (let ((x y)) x) -> y, named let is possible here (null? (cdr body)) (eq? (car body) (caar varlist)) (pair? (cdar varlist))) ; (let ((a))...) (lint-format "perhaps ~A" caller (lists->string form (cadar varlist)))) ;; also (let ((x ...)) (let ((y x)...))) happens but it looks like automatically generated code or test suite junk ;; copied from letrec below -- happens about a dozen times (when (and (not named-let) (pair? (cddr form)) (pair? (caddr form)) (null? (cdddr form))) (let ((body (caddr form)) (sym (caar varlist)) (lform (and (pair? (caadr form)) (pair? (cdaadr form)) (cadar (cadr form))))) (if (and (pair? lform) (pair? (cdr lform)) (eq? (car lform) 'lambda) (proper-list? (cadr lform))) ;; unlike in letrec, here there can't be recursion (ref to same name is ref to outer env) (if (eq? sym (car body)) (if (not (tree-memq sym (cdr body))) ;; (let ((x (lambda (y) (+ y (x (- y 1)))))) (x 2)) -> (let ((y 2)) (+ y (x (- y 1)))) (lint-format "perhaps ~A" caller (lists->string form `(let ,(map list (cadr lform) (cdr body)) ,@(cddr lform))))) (if (= (tree-count1 sym body 0) 1) (let ((call (find-call sym body))) (when (pair? call) (let ((new-call `(let ,(map list (cadr lform) (cdr call)) ,@(cddr lform)))) ;; (let ((f60 (lambda (x) (* 2 x)))) (+ 1 (f60 y))) -> (+ 1 (let ((x y)) (* 2 x))) (lint-format "perhaps ~A" caller (lists->string form (tree-subst new-call call body)))))))))))) (when (pair? body) (when (and (pair? (car body)) (pair? (cdar body)) (pair? (cddar body)) (eq? (caar body) 'set!)) (let ((settee (cadar body)) (setval (caddar body))) (if (and (not named-let) ; (let ((x 0)...) (set! x 1)...) -> (let ((x 1)...)...) (not (tree-memq 'curlet setval)) (cond ((assq settee vars) => (lambda (v) (or (and (code-constant? (var-initial-value v)) (code-constant? setval)) (not (any? (lambda (v1) (or (tree-memq (car v1) setval) (side-effect? (cadr v1) env))) varlist))))) (else #f))) (lint-format "perhaps ~A" caller ; (let ((a 1)) (set! a 2)) -> 2 (lists->string form (if (null? (cdr body)) ; this only happens in test suites... (if (null? (cdr varlist)) setval `(let ,(map (lambda (v) (if (eq? (car v) settee) (values) v)) varlist) ,setval)) `(let ,(map (lambda (v) (if (eq? (car v) settee) (list (car v) setval) v)) varlist) ,@(if (null? (cddr body)) (cdr body) `(,(cadr body) ...)))))) ;; repetition for the moment (when (and (pair? varlist) (assq settee vars) ; settee is a local var (not (eq? settee named-let)) ; (let loop () (set! loop 3))! (or (null? (cdr body)) (and (null? (cddr body)) (eq? settee (cadr body))))) ; (let... (set! local val) local) (lint-format "perhaps ~A" caller (lists->string form (if (or (tree-memq settee setval) (side-effect? (cadr (assq settee varlist)) env)) `(let ,varlist ,setval) (if (null? (cdr varlist)) setval `(let ,(remove-if (lambda (v) (eq? (car v) settee)) varlist) ,setval))))))))) (unless named-let ;; if var val is symbol, val not used (not set!) in body (even hidden via function call) ;; and var not set!, and not a function parameter (we already reported those), ;; remove it (the var) and replace with val throughout (when (and (proper-list? (cadr form)) (not (tree-set-member '(curlet lambda lambda* define define*) (cddr form)))) (do ((changes ()) (vs (cadr form) (cdr vs))) ((null? vs) (if (pair? changes) (let ((new-form (copy form))) (for-each (lambda (v) (list-set! new-form 1 (remove-if (lambda (p) (equal? p v)) (cadr new-form))) (set! new-form (tree-subst (cadr v) (car v) new-form))) changes) (lint-format "assuming we see all set!s, the binding~A ~{~A~^, ~} ~A pointless: perhaps ~A" caller (if (pair? (cdr changes)) "s" "") changes (if (pair? (cdr changes)) "are" "is") (lists->string form (if (< (tree-leaves new-form) 200) new-form `(let ,(cadr new-form) ,@(one-call-and-dots (cddr new-form))))))))) (let ((v (car vs))) (if (and (pair? v) (pair? (cdr v)) (null? (cddr v)) ; good grief (symbol? (cadr v)) (not (set-target (cadr v) body env)) (not (set-target (car v) body env)) (let ((data (var-member (cadr v) env))) (or (not (var? data)) (and (not (eq? (var-definer data) 'parameter)) (or (null? (var-setters data)) (not (tree-set-member (var-setters data) body))))))) (set! changes (cons v changes)))))) (when (pair? varlist) ;; if last is (set! local-var...) and no complications, complain (let ((last (list-ref body (- (length body) 1)))) (if (and (pair? last) (eq? (car last) 'set!) (pair? (cdr last)) (pair? (cddr last)) ; (set! a) (symbol? (cadr last)) (assq (cadr last) varlist) ; (let ((a 1) (b (display 2))) (set! a 2)) ;; this is overly restrictive: (not (tree-set-member '(call/cc call-with-current-continuation curlet lambda lambda*) form))) (lint-format "set! is pointless in ~A: use ~A" caller last (caddr last)))) (when (and (pair? (car body)) (eq? (caar body) 'do)) (when (and (null? (cdr body)) ; removing this restriction gets only 3 hits (pair? (cadar body))) (let ((inits (map cadr (cadar body)))) (when (every? (lambda (v) (and (= (tree-count1 (car v) (car body) 0) 1) (tree-memq (car v) inits))) varlist) (let ((new-cadr (copy (cadar body)))) (for-each (lambda (v) (set! new-cadr (tree-subst (cadr v) (car v) new-cadr))) varlist) ;; (let ((a 1)) (do ((i a (+ i 1))) ((= i 3)) (display i))) -> (do ((i 1 (+ i 1))) ...) (lint-format "perhaps ~A" caller (lists->string form `(do ,new-cadr ...))))))) ;; let->do -- sometimes a bad idea, set *max-cdr-len* to #f to disable this. ;; (the main objection is that the s7/clm optimizer can't handle it, and ;; instruments using it look kinda dumb -- the power of habit or something) (when (integer? *max-cdr-len*) (let ((inits (if (pair? (cadar body)) (map cadr (cadar body)) ())) (locals (if (pair? (cadar body)) (map car (cadar body)) ()))) (unless (or (and (pair? inits) (any? (lambda (v) (or (memq (car v) locals) ; shadowing (tree-memq (car v) inits) (side-effect? (cadr v) env))) ; let var opens *stdin*, do stepper reads it at init varlist)) (> (tree-leaves (cdr body)) *max-cdr-len*)) ;; (let ((xx 0)) (do ((x 1 (+ x 1)) (y x (- y 1))) ((= x 3) xx) (display y))) -> ;; (do ((xx 0) (x 1 (+ x 1)) (y x (- y 1))) ...) (lint-format "perhaps ~A" caller (lists->string form (let ((do-form (cdar body))) (if (null? (cdr body)) ; do is only expr in let `(do ,(append varlist (car do-form)) ...) `(do ,(append varlist (car do-form)) (,(and (pair? (cadr do-form)) (caadr do-form)) ,@(if (side-effect? (cdr (cadr do-form)) env) (cdr (cadr do-form)) ()) ,@(cdr body)) ; include rest of let as do return value ...))))))))) (when (and (> (length body) 3) ; setting this to 1 did not catch anything new (every? pair? varlist) (not (tree-set-car-member '(define define* define-macro define-macro* define-bacro define-bacro* define-constant define-expansion) body))) ;; define et al are like a continuation of the let bindings, so we can't restrict them by accident ;; (let ((x 1)) (define y x) ...) (let ((last-refs (map (lambda (v) (vector (var-name v) #f 0 v)) vars)) (got-lambdas (tree-set-car-member '(lambda lambda*) body))) ;; (let ((x #f) (y #t)) (set! x (lambda () y)) (set! y 5) (x)) (do ((p body (cdr p)) (i 0 (+ i 1))) ((null? p) (let ((end 0)) (for-each (lambda (v) (set! end (max end (v 2)))) last-refs) (if (and (< end (/ i lint-let-reduction-factor)) (eq? form lint-current-form) (< (tree-leaves (car body)) 100)) (let ((old-start (let ((old-pp ((funclet lint-pretty-print) '*pretty-print-left-margin*))) (set! ((funclet lint-pretty-print) '*pretty-print-left-margin*) (+ lint-left-margin 4)) (let ((res (lint-pp `(let ,(cadr form) ,@(copy body (make-list (+ end 1))))))) (set! ((funclet lint-pretty-print) '*pretty-print-left-margin*) old-pp) res)))) (lint-format "this let could be tightened:~%~NC~A ->~%~NC~A~%~NC~A ..." caller (+ lint-left-margin 4) #\space (truncated-list->string form) (+ lint-left-margin 4) #\space old-start (+ lint-left-margin 4) #\space (lint-pp (list-ref body (+ end 1))))) (begin ;; look for bindings that can be severely localized (let ((locals (map (lambda (v) (if (and (integer? (v 1)) (< (- (v 2) (v 1)) 2) (code-constant? (var-initial-value (v 3)))) v (values))) last-refs))) ;; should this omit cases where most the let is in the one or two lines? (when (pair? locals) (set! locals (sort! locals (lambda (a b) (or (< (a 1) (b 1)) (< (a 2) (b 2)))))) (do ((lv locals (cdr lv))) ((null? lv)) (let* ((v (car lv)) (cur-line (v 1))) (let gather ((pv lv) (cur-vars ()) (max-line (v 2))) (if (or (null? (cdr pv)) (not (= cur-line ((cadr pv) 1)))) (begin (set! cur-vars (reverse (cons (car pv) cur-vars))) (set! max-line (max max-line ((car pv) 2))) (set! lv pv) (lint-format "~{~A~^, ~} ~A only used in expression~A (of ~A),~%~NC~A~A of~%~NC~A" caller (map (lambda (v) (v 0)) cur-vars) (if (null? (cdr cur-vars)) "is" "are") (if (= cur-line max-line) (format #f " ~D" (+ cur-line 1)) (format #f "s ~D and ~D" (+ cur-line 1) (+ max-line 1))) (length body) (+ lint-left-margin 6) #\space (truncated-list->string (list-ref body cur-line)) (if (= cur-line max-line) "" (format #f "~%~NC~A" (+ lint-left-margin 6) #\space (truncated-list->string (list-ref body max-line)))) (+ lint-left-margin 4) #\space (truncated-list->string form))) (gather (cdr pv) (cons (car pv) cur-vars) (max max-line ((car pv) 2))))))))) (let ((mnv ()) (cur-end i)) (for-each (lambda (v) (when (and (or (null? mnv) (<= (v 2) cur-end)) (positive? (var-ref (v 3))) (let ((expr (var-initial-value (v 3)))) (not (any? (lambda (ov) ; watch out for shadowed vars (tree-memq (car ov) expr)) varlist)))) (set! mnv (if (= (v 2) cur-end) (cons v mnv) (list v))) (set! cur-end (v 2)))) last-refs) ;; look for vars used only at the start of the let (when (and (pair? mnv) (< cur-end (/ i lint-let-reduction-factor)) (> (- i cur-end) 3)) ;; mnv is in the right order because last-refs is reversed (lint-format "the scope of ~{~A~^, ~} could be reduced: ~A" caller (map (lambda (v) (v 0)) mnv) (lists->string form `(let ,(map (lambda (v) (if (member (car v) mnv (lambda (a b) (eq? a (b 0)))) (values) v)) varlist) (let ,(map (lambda (v) (list (v 0) (var-initial-value (v 3)))) mnv) ,@(copy body (make-list (+ cur-end 1)))) ,(list-ref body (+ cur-end 1)) ...))))))))) ;; body of do loop above (if (and (not got-lambdas) (pair? (car p)) (pair? (cdr p)) (eq? (caar p) 'set!) (var-member (cadar p) vars) (not (tree-memq (cadar p) (cdr p)))) (if (not (side-effect? (caddar p) env)) ; (set! v0 (channel->vct 1000 100)) -> (channel->vct 1000 100) (lint-format "~A in ~A could be omitted" caller (car p) (truncated-list->string form)) (lint-format "perhaps ~A" caller (lists->string (car p) (caddar p))))) ;; 1 use in cadr and none thereafter happens a few times, but looks like set-as-documentation mostly (for-each (lambda (v) (when (tree-memq (v 0) (car p)) (set! (v 2) i) (if (not (v 1)) (set! (v 1) i)))) last-refs)))))) ) ; (when (pair? body)...) ;; out of place and repetitive code... (when (and (pair? (cadr form)) (pair? (cddr form)) (null? (cdddr form)) (pair? (caddr form))) (let ((inner (caddr form)) ; the inner let (outer-vars (cadr form))) (when (pair? (cdr inner)) (let ((inner-vars (cadr inner))) (when (and (eq? (car inner) 'let) (symbol? inner-vars)) (let ((named-body (cdddr inner)) (named-args (caddr inner))) (unless (any? (lambda (v) (or (not (= (tree-count1 (car v) named-args 0) 1)) (tree-memq (car v) named-body))) varlist) (let ((new-args (copy named-args))) (for-each (lambda (v) (set! new-args (tree-subst (cadr v) (car v) new-args))) varlist) ;; (let ((x 1) (y (f g 2))) (let loop ((a (+ x 1)) (b y)) (loop a b))) -> (let loop ((a (+ 1 1)) (b (f g 2))) (loop a b)) (lint-format "perhaps ~A" caller (lists->string form `(let ,inner-vars ,new-args ,@named-body))))))) ;; maybe more code than this is worth -- combine lets (when (and (memq (car inner) '(let let*)) (pair? inner-vars)) (define (letstar . lets) (let loop ((vars (list 'curlet)) (forms lets)) (and (pair? forms) (or (and (pair? (car forms)) (or (tree-set-member vars (car forms)) (any? (lambda (a) (or (not (pair? a)) (not (pair? (cdr a))) (side-effect? (cadr a) env))) (car forms)))) (loop (append (map car (car forms)) vars) (cdr forms)))))) (cond ((and (null? (cdadr form)) ; let(1) + let* -> let* (eq? (car inner) 'let*) (not (symbol? inner-vars))) ; not named let* ;; (let ((a 1)) (let* ((b (+ a 1)) (c (* b 2))) (display (+ a b c)))) -> (let* ((a 1) (b (+ a 1)) (c (* b 2))) (display (+ a b c))) (lint-format "perhaps ~A" caller (lists->string form `(let* ,(append outer-vars inner-vars) ,@(one-call-and-dots (cddr inner)))))) ((and (pair? (cddr inner)) (pair? (caddr inner)) (null? (cdddr inner)) (eq? (caaddr inner) 'let) (pair? (cdr (caddr inner))) (pair? (cadr (caddr inner)))) (let* ((inner1 (cdaddr inner)) (inner1-vars (car inner1))) (if (and (pair? (cdr inner1)) (null? (cddr inner1)) (pair? (cadr inner1)) (eq? (caadr inner1) 'let) (pair? (cdadr inner1)) (pair? (cadadr inner1))) (let* ((inner2 (cdadr inner1)) (inner2-vars (car inner2))) (if (not (letstar outer-vars inner-vars inner1-vars inner2-vars)) ;; (let ((a 1)) (let ((b 2)) (let ((c 3)) (let ((d 4)) (+ a b c d))))) -> (let ((a 1) (b 2) (c 3) (d 4)) (+ a b c d)) (lint-format "perhaps ~A" caller (lists->string form `(let ,(append outer-vars inner-vars inner1-vars inner2-vars) ,@(one-call-and-dots (cdr inner2))))))) (if (not (letstar outer-vars inner-vars inner1-vars)) ;; (let ((b 2)) (let ((c 3)) (let ((d 4)) (+ a b c d)))) -> (let ((b 2) (c 3) (d 4)) (+ a b c d)) (lint-format "perhaps ~A" caller (lists->string form `(let ,(append outer-vars inner-vars inner1-vars) ,@(one-call-and-dots (cdr inner1))))))))) ((not (letstar outer-vars inner-vars)) ;; (let ((c 3)) (let ((d 4)) (+ a b c d))) -> (let ((c 3) (d 4)) (+ a b c d)) (lint-format "perhaps ~A" caller (lists->string form `(let ,(append outer-vars inner-vars) ,@(one-call-and-dots (cddr inner)))))) ((and (null? (cdadr form)) ; 1 outer var (pair? inner-vars) (null? (cdadr inner))) ; 1 inner var, dependent on outer ;; (let ((x 0)) (let ((y (g 0))) (+ x y))) -> (let* ((x 0) (y (g 0))) (+ x y)) (lint-format "perhaps ~A" caller (lists->string form `(let* ,(append outer-vars inner-vars) ,@(one-call-and-dots (cddr inner)))))))))))) ))) ; messed up let env) (hash-table-set! h 'let let-walker)) ;; ---------------- let* ---------------- (let () (define (let*-walker caller form env) (if (< (length form) 3) (lint-format "let* is messed up: ~A" caller (truncated-list->string form)) (let ((named-let (and (symbol? (cadr form)) (cadr form)))) (let ((vars (if named-let (list (make-var :name named-let :definer 'let*)) ())) ; TODO: fvar (varlist ((if named-let caddr cadr) form)) (body ((if named-let cdddr cddr) form))) (if (not (list? varlist)) (lint-format "let* is messed up: ~A" caller (truncated-list->string form))) ;; let->do (could go further down) (when (and (integer? *max-cdr-len*) (pair? varlist) (pair? body) (pair? (car body)) (eq? (caar body) 'do) (< (tree-leaves (cdr body)) *max-cdr-len*)) (let ((inits (if (pair? (cadar body)) (map cadr (cadar body)) ())) (locals (if (pair? (cadar body)) (map car (cadar body)) ())) (lv (list-ref varlist (- (length varlist) 1)))) (unless (and (pair? inits) (or (memq (car lv) locals) ; shadowing (tree-memq (car lv) inits) (side-effect? (cadr lv) env))) ;; (let* ((x (log z))) (do ((i 0 (+ x z))) ((= i 3)) (display x))) -> (do ((x (log z)) (i 0 (+ x z))) ...) (lint-format "perhaps ~A" caller (lists->string form (let ((new-do (let ((do-form (cdar body))) (if (null? (cdr body)) `(do ,(cons lv (car do-form)) ...) `(do ,(cons lv (car do-form)) (,(and (pair? (cadr do-form)) (caadr do-form)) ,@(if (side-effect? (cdadr do-form) env) (cdadr do-form) ()) ,@(cdr body)) ; include rest of let as do return value ...))))) (case (length varlist) ((1) new-do) ((2) `(let (,(car varlist)) ,new-do)) (else `(let* ,(copy varlist (make-list (- (length varlist) 1))) ,new-do))))))))) (do ((side-effects #f) (bindings varlist (cdr bindings))) ((not (pair? bindings)) (if (not (null? bindings)) (lint-format "let* variable list is not a proper list? ~S" caller ((if named-let caddr cadr) form))) (if (not (or side-effects (any? (lambda (v) (positive? (var-ref v))) vars))) ;; (let* ((x (log y))) x) (lint-format "let* could be let: ~A" caller (truncated-list->string form)))) ;; in s7, let evaluates var values top down, so this message is correct ;; even in cases like (let ((ind (open-sound...)) (mx (maxamp))) ...) ;; in r7rs, the order is not specified (section 4.2.2 of the spec), so ;; here we would restrict this message to cases where there is only ;; one variable, or where subsequent values are known to be independent. ;; if each function could tell us what globals it depends on or affects, ;; we could make this work in all cases. (when (binding-ok? caller 'let* (car bindings) env #f) (let ((expr (cadar bindings)) (side (side-effect? (cadar bindings) env))) (if (not (or (eq? bindings varlist) ;; first var side-effect is innocuous (especially if it's the only one!) ;; does this need to protect against a side-effect that the next var accesses? ;; I think we're ok -- the accessed var must be exterior, and we go down in order side-effects)) (set! side-effects side)) (lint-walk caller expr (append vars env)) (set! vars (cons (make-var :name (caar bindings) :initial-value expr :definer (if named-let 'named-let* 'let*)) vars)) ;; look for duplicate values ;; TODO: protect against any shadows if included in any expr (if (not (or side (not (pair? expr)) (code-constant? expr) (maker? expr))) (let ((name (caar bindings))) (let dup-check ((vs (cdr vars))) (if (and (pair? vs) (pair? (car vs)) (not (eq? name (caar vs))) (not (tree-memq (caar vs) expr))) ;; perhaps also not side-effect of car vs initial-value (char-ready? + read + char-ready? again) (if (equal? expr (var-initial-value (car vs))) ;; (let* ((x (log y 2)) (y (log y 2)) (z (f x))) (+ x y z z)) (lint-format "~A's value ~A could be ~A" caller name expr (caar vs)) (dup-check (cdr vs)))))))))) ;; if var is not used except in other var bindings, it can be moved out of this let* ;; collect vars not in body, used in only one binding, gather these cases, and rewrite the let* ;; repeated names are possible here ;; also cascading dependencies: (let* ((z 1) (y (+ z 2)) (x (< y 3))) (if x (f x))) ;; (let ((x (let ((y (let ((z 1))) (+ z 2))) (< y 3)))) ...) ?? ;; new-vars: ((z y) (y x)) (when (and (pair? vars) (pair? (cdr vars))) (let ((new-vars ()) (vs-pos vars) (repeats (do ((p vars (cdr p))) ((or (null? p) (var-member (var-name (car p)) (cdr p))) (pair? p))))) (for-each (lambda (v) (let ((vname (var-name v)) (vvalue #f)) (if (not (tree-memq vname body)) (let walker ((vs vars)) (if (not (pair? vs)) (if (and vvalue (or (not (side-effect? (var-initial-value v) env)) (eq? vvalue (var-name (car vs-pos))))) (set! new-vars (cons (list vvalue vname (var-initial-value v)) new-vars))) (let ((b (car vs))) (if (or (eq? (var-name b) vname) (not (tree-memq vname (var-initial-value b)))) ; tree-memq matches the bare symbol (tree-member doesn't) (walker (cdr vs)) (if (not vvalue) (begin (set! vvalue (var-name b)) (walker (cdr vs))))))))) (set! vs-pos (cdr vs-pos)))) (cdr vars)) ; vars is reversed from code order, new-vars is in code order (when (pair? new-vars) (define (gather-dependencies var val env) (let ((deps ())) (for-each (lambda (nv) (if (and (eq? (car nv) var) (or (not repeats) (tree-memq (cadr nv) val))) (set! deps (cons (list (cadr nv) (gather-dependencies (cadr nv) (caddr nv) env)) deps)))) new-vars) (if (> (tree-leaves val) 30) (set! val '...)) (if (pair? deps) `(,(if (null? (cdr deps)) 'let 'let*) ,deps ,val) val))) (let ((new-let-binds (map (lambda (v) (if (member (var-name v) new-vars (lambda (name lst) (eq? name (cadr lst)))) (values) `(,(var-name v) ,(gather-dependencies (var-name v) (var-initial-value v) env)))) (reverse vars)))) ;; (let* ((a 1) (b 2) (c (+ a 1))) (* c 2)) -> (let* ((b 2) (c (let ((a 1)) (+ a 1)))) ...) (lint-format "perhaps restrict ~{~A~^, ~} which ~A not used in the let* body ~A" caller (map cadr new-vars) (if (null? (cdr new-vars)) "is" "are") (lists->string form `(,(if (null? (cdr new-let-binds)) 'let 'let*) ,new-let-binds ...))))) ;; this could be folded into the for-each above (unless repeats (let ((outer-vars ()) (inner-vars ())) (do ((vs (reverse vars) (cdr vs))) ((null? vs)) (let* ((v (car vs)) (vname (var-name v))) (if (not (or (side-effect? (var-initial-value v) env) (any? (lambda (trailing-var) ;; vname is possible inner let var if it is not mentioned in any trailing initial value ;; (repeated name can't happen here) (tree-memq vname (var-initial-value trailing-var))) (cdr vs)))) (set! inner-vars (cons v inner-vars)) (set! outer-vars (cons v outer-vars))))) (if (and (pair? outer-vars) (pair? inner-vars) (pair? (cdr inner-vars))) ;; (let* ((a 1) (b 2) (c (+ a 1))) (* c 2)) -> (let ((a 1)) (let ((b 2) (c (+ a 1))) ...)) (lint-format "perhaps split this let*: ~A" caller (lists->string form `(,(if (pair? (cdr outer-vars)) 'let* 'let) ,(map (lambda (v) `(,(var-name v) ,(var-initial-value v))) (reverse outer-vars)) (let ,(map (lambda (v) `(,(var-name v) ,(var-initial-value v))) (reverse inner-vars)) ...))))))) )) ; pair? vars (let* ((cur-env (cons (make-var :name :let :initial-value form :definer 'let*) (append vars env))) (e (lint-walk-body caller 'let* body cur-env))) (let ((nvars (and (not (eq? e cur-env)) (env-difference caller e cur-env ())))) (if (pair? nvars) (if (memq (var-name (car nvars)) '(:lambda :dilambda)) (begin (set! env (cons (car nvars) env)) (set! nvars (cdr nvars))) (set! vars (append nvars vars))))) (report-usage caller 'let* vars cur-env)) (when (and (not named-let) (pair? body) (pair? varlist)) ; from here to end ;; (let*->let*) combined into one (when (and (pair? (car body)) (or (eq? (caar body) 'let*) ; let*+let* -> let* (and (eq? (caar body) 'let) ; let*+let(1) -> let* (or (null? (cadar body)) (and (pair? (cadar body)) (null? (cdadar body)))))) (null? (cdr body)) (not (symbol? (cadar body)))) ;; (let* ((a 1) (b (+ a 2))) (let* ((c (+ b 3)) (d (+ c 4))) (display a) (+ a... -> ;; (let* ((a 1) (b (+ a 2)) (c (+ b 3)) (d (+ c 4))) (display a) ...) (lint-format "perhaps ~A" caller (lists->string form `(let* ,(append varlist (cadar body)) ,@(one-call-and-dots (cddar body)))))) (when (and (proper-list? (cadr form)) (not (tree-set-member '(curlet lambda lambda* define define*) (cddr form)))) ;; see let above (do ((changes ()) (vs (cadr form) (cdr vs))) ((null? vs) (if (pair? changes) (let ((new-form (copy form))) (for-each (lambda (v) (list-set! new-form 1 (remove-if (lambda (p) (equal? p v)) (cadr new-form))) (set! new-form (tree-subst (cadr v) (car v) new-form))) changes) ;; (let* ((x y) (a (* 2 x))) (+ (f a (+ a 1)) (* 3 x))) -> (let ((a (* 2 y))) (+ (f a (+ a 1)) (* 3 y))) (lint-format "assuming we see all set!s, the binding~A ~{~A~^, ~} ~A pointless: perhaps ~A" caller (if (pair? (cdr changes)) "s" "") changes (if (pair? (cdr changes)) "are" "is") (lists->string form (let ((header (if (and (pair? (cadr new-form)) (pair? (cdadr new-form))) 'let* 'let))) (if (< (tree-leaves new-form) 200) `(,header ,@(cdr new-form)) `(,header ,(cadr new-form) ,@(one-call-and-dots (cddr new-form)))))))))) (let ((v (car vs))) (if (and (pair? v) (pair? (cdr v)) (null? (cddr v)) (symbol? (cadr v)) (not (assq (cadr v) (cadr form))) ; value is not a local var (not (set-target (car v) body env)) (not (set-target (cadr v) body env))) (let ((data (var-member (cadr v) env))) (if (and (or (not (var? data)) (and (not (eq? (var-definer data) 'parameter)) (or (null? (var-setters data)) (not (tree-set-member (var-setters data) body))))) (not (any? (lambda (p) (and (pair? p) (pair? (cdr p)) (or (set-target (cadr v) (cdr p) env) (set-target (car v) (cdr p) env) (and (var? data) (pair? (var-setters data)) (tree-set-member (var-setters data) body))))) (cdr vs)))) (set! changes (cons v changes)))))))) (let* ((varlist-len (length varlist)) (last-var (and (positive? varlist-len) (list-ref varlist (- varlist-len 1))))) ; from here to end (when (pair? last-var) ; successive vars, first used in second but nowhere else -- combine if (very!) simple-looking (do ((gone-vars ()) (v varlist (cdr v))) ((or (null? v) (null? (cdr v))) (when (pair? gone-vars) (let ((waiter #f) (new-vars ()) (save-vars ())) (set! gone-vars (reverse gone-vars)) (set! new-vars (map (lambda (v) (if (and (pair? gone-vars) (eq? v (car gone-vars))) (begin (set! waiter v) (set! gone-vars (cdr gone-vars)) (values)) (if (not waiter) v (let ((new-v (tree-subst (cadr waiter) (car waiter) v))) (set! save-vars (cons (list (car waiter) (car v)) save-vars)) (set! waiter #f) new-v)))) varlist)) ;; (let* ((y 3) (x (log y))) x) -> (let ((x (log 3))) ...) (lint-format "perhaps substitute ~{~{~A into ~A~}~^, ~}: ~A" caller (reverse save-vars) (lists->string form `(,(if (null? (cdr new-vars)) 'let 'let*) ,new-vars ...)))))) (let ((cur-var (car v)) (nxt-var (cadr v))) (when (and (pair? cur-var) (pair? nxt-var) (pair? (cdr cur-var)) (pair? (cdr nxt-var)) (< (tree-leaves (cadr cur-var)) 8) (not (and (pair? (cadr nxt-var)) (eq? (caadr nxt-var) 'let) ; if named-let, forget it (pair? (cdadr nxt-var)) (symbol? (cadadr nxt-var)))) (or (not (pair? (cadr nxt-var))) (not (side-effect? (cadr cur-var) env)) (every? (lambda (a) (or (code-constant? a) (assq a varlist))) (cdadr nxt-var))) (= (tree-count1 (car cur-var) (cadr nxt-var) 0) 1) (not (tree-memq (car cur-var) (cddr v))) (not (tree-memq (car cur-var) body))) (set! gone-vars (cons cur-var gone-vars)) (set! v (cdr v))))) ;; if last var only occurs once in body, and timing can't be an issue, substitute its value ;; this largely copied from the let case above (but only one substitution) ;; in both cases, we're assuming that the possible last-var value's side-effect won't ;; affect other vars (in let* the local, in let something outside that might be used locally) ;; perhaps add (not (side-effect (cadr last-var) env))? (when (and (pair? (cdr last-var)) ; varlist-len can be 1 here (< (tree-leaves (cadr last-var)) 12) (= (tree-count1 (car last-var) body 0) 1) (pair? (car body)) (null? (cdr body)) (not (memq (caar body) '(lambda lambda* define define* define-macro))) (not (and (eq? (caar body) 'set!) (eq? (car last-var) (cadar body)))) (not (any-macro? (caar body) env)) (not (any? (lambda (p) (and (pair? p) (not (eq? (car p) 'quote)) (or (not (hash-table-ref no-side-effect-functions (car p))) (any? pair? (cdr p))))) (cdar body)))) ;; (let* ((a 1) (b 2) (c (+ a 1))) (* c 2)) -> (let* ((a 1) (b 2)) (* (+ a 1) 2)) (lint-format "perhaps ~A" caller (lists->string form `(,(if (<= varlist-len 2) 'let 'let*) ,(copy varlist (make-list (- varlist-len 1))) ,@(tree-subst (cadr last-var) (car last-var) body))))) (when (null? (cdr body)) ; (let* (...(x A)) (if x (f A) B)) -> (let(*) (...) (cond (A => f) (else B))) (when (pair? (cdr last-var)) (let ((p (car body))) (when (and (pair? p) (pair? (cdr p)) (case (car p) ((if and) (eq? (cadr p) (car last-var))) ((or) (equal? (cadr p) `(not ,(car last-var)))) (else #f)) (pair? (cddr p)) (pair? (caddr p)) (or (eq? (car p) 'if) (null? (cdddr p))) (pair? (cdaddr p)) (not (eq? (caaddr p) (car last-var))) ; ! (let* (...(x A)) (if x (x x))) (null? (cddr (caddr p))) (eq? (car last-var) (cadr (caddr p)))) (let ((else-clause (if (pair? (cdddr p)) ; only if 'if (see above) (if (eq? (cadddr p) (car last-var)) `((else #f)) ; this stands in for the local var (if (and (pair? (cadddr p)) (tree-unquoted-member (car last-var) (cadddr p))) :oops! ; if the let var appears in the else portion, we can't do anything with => `((else ,(cadddr p))))) (case (car p) ((and) '((else #f))) ((or) '((else #t))) (else ()))))) (if (not (eq? else-clause :oops!)) ;; (let* ((x (f y))) (and x (g x))) -> (cond ((f y) => g) (else #f) (lint-format "perhaps ~A" caller (case varlist-len ((1) (lists->string form `(cond (,(cadr last-var) => ,(caaddr p)) ,@else-clause))) ((2) (lists->string form `(let (,(car varlist)) (cond (,(cadr last-var) => ,(caaddr p)) ,@else-clause)))) (else (lists->string form `(let* ,(copy varlist (make-list (- varlist-len 1))) (cond (,(cadr last-var) => ,(caaddr p)) ,@else-clause))))))))))) (when (and (pair? (car varlist)) ; same as let: (let* ((x y)) x) -> y -- (let* (x) ...) (not (pair? (car body)))) (if (and (eq? (car body) (caar varlist)) (null? (cdr varlist)) (pair? (cdar varlist))) ; (let* ((a...)) a) ;; (let* ((x (log y))) x) -> (log y) (lint-format "perhaps ~A" caller (lists->string form (cadar varlist))) (if (and (> varlist-len 1) ; (let* (... (x y)) x) -> (let(*)(...) y) (pair? last-var) (pair? (cdr last-var)) (null? (cddr last-var)) (eq? (car body) (car last-var))) ;; (let* ((y 3) (x (log y))) x) -> (let ((y 3)) (log y)) (lint-format "perhaps ~A" caller (lists->string form `(,(if (= varlist-len 2) 'let 'let*) ,(copy varlist (make-list (- varlist-len 1))) ,(cadr last-var))))))))) (when (and (> (length body) 3) (> (length vars) 1) (every? pair? varlist) (not (tree-set-car-member '(define define* define-macro define-macro* define-bacro define-bacro* define-constant define-expansion) body))) (let ((last-ref (vector (var-name (car vars)) #f 0 (car vars)))) (do ((p body (cdr p)) (i 0 (+ i 1))) ((null? p) (let ((cur-line (last-ref 1)) (max-line (last-ref 2)) (vname (last-ref 0))) (if (and (< max-line (/ i lint-let-reduction-factor)) (> (- i max-line) 3)) (lint-format "the scope of ~A could be reduced: ~A" caller vname (lists->string form `(,(if (> (length vars) 2) 'let* 'let) ,(copy varlist (make-list (- (length vars) 1))) (let (,(list vname (var-initial-value (last-ref 3)))) ,@(copy body (make-list (+ max-line 1)))) ,(list-ref body (+ max-line 1)) ...))) (if (and (integer? cur-line) (< (- max-line cur-line) 2) (code-constant? (var-initial-value (last-ref 3)))) (lint-format "~A is only used in expression~A (of ~A),~%~NC~A~A of~%~NC~A" caller vname (if (= cur-line max-line) (format #f " ~D" (+ cur-line 1)) (format #f "s ~D and ~D" (+ cur-line 1) (+ max-line 1))) (length body) (+ lint-left-margin 6) #\space (truncated-list->string (list-ref body cur-line)) (if (= cur-line max-line) "" (format #f "~%~NC~A" (+ lint-left-margin 6) #\space (truncated-list->string (list-ref body max-line)))) (+ lint-left-margin 4) #\space (truncated-list->string form)))))) (when (tree-memq (last-ref 0) (car p)) (set! (last-ref 2) i) (if (not (last-ref 1)) (set! (last-ref 1) i)))))) ))))) env) (hash-table-set! h 'let* let*-walker)) ;; ---------------- letrec ---------------- (let () (define (letrec-walker caller form env) (if (< (length form) 3) ; (letrec () . 1) (lint-format "~A is messed up: ~A" caller (car form) (truncated-list->string form)) (let ((vars ()) (head (car form))) (cond ((null? (cadr form)) ; (letrec () 1) (lint-format "~A could be let: ~A" caller head (truncated-list->string form))) ((not (pair? (cadr form))) ; (letrec a b) (lint-format "~A is messed up: ~A" caller head (truncated-list->string form))) ((and (null? (cdadr form)) (eq? head 'letrec*)) ; (letrec* ((a (lambda b (a 1)))) a) (lint-format "letrec* could be letrec: ~A" caller (truncated-list->string form)))) (do ((warned (or (eq? head 'letrec*) (not (pair? (cadr form))) (negative? (length (cadr form))))) ; malformed letrec (baddy #f) (bindings (cadr form) (cdr bindings))) ((not (pair? bindings)) (if (not (null? bindings)) ; (letrec* letrec)! (lint-format "~A variable list is not a proper list? ~S" caller head (cadr form)))) (when (and (not warned) ; letrec -> letrec* (pair? (car bindings)) (pair? (cdar bindings)) ;; type of current var is not important -- if used in non-function elsewhere, ;; it has to be letrec* (any? (lambda (b) (and (pair? b) (pair? (cdr b)) (or (and (not (pair? (cadr b))) (eq? (caar bindings) (cadr b))) (tree-memq (caar bindings) (cadr b))) (not (tree-set-member '(lambda lambda* define define* case-lambda) (cadr b))) (set! baddy b))) (cdr bindings))) (set! warned #t) ;; (letrec ((x 32) (f1 (let ((y 1)) (lambda (z) (+ x y z)))) (f2 (f1 x))) (+ x f2)) (lint-format "in ~A,~%~NCletrec should be letrec* because ~A is used in ~A's value (not a function): ~A" caller (truncated-list->string form) (+ lint-left-margin 4) #\space (caar bindings) (car baddy) (cadr baddy))) (when (binding-ok? caller head (car bindings) env #f) (let ((init (if (and (eq? (caar bindings) (cadar bindings)) (or (eq? head 'letrec) (not (var-member (caar bindings) vars)))) (begin ; (letrec ((x x)) x) (lint-format "~A is the same as (~A #<undefined>) in ~A" caller (car bindings) (caar bindings) head) ;; in letrec* ((x 12) (x x)) is an error #<undefined>) (cadar bindings)))) (set! vars (cons (make-var :name (caar bindings) :initial-value init :definer head) vars))))) (when (eq? head 'letrec) (check-unordered-exprs caller form (map var-initial-value vars) env)) (when (pair? vars) (do ((bindings (cadr form) (cdr bindings)) ; if none of the local vars occurs in any of the values, no need for the "rec" (vs (map var-name vars))) ((or (not (pair? bindings)) (not (pair? (car bindings))) (not (pair? (cdar bindings))) (memq (cadar bindings) vs) (tree-set-member vs (cadar bindings))) (if (null? bindings) (let ((letx (if (or (eq? head 'letrec) (do ((p (map cadr (cadr form)) (cdr p)) (q (map car (cadr form)) (cdr q))) ((or (null? p) (side-effect? (car p) env) (memq (car q) (cdr q))) (null? p)))) 'let 'let*))) ;; (letrec ((f1 (lambda (a) a))) 32) (lint-format "~A could be ~A: ~A" caller head letx (truncated-list->string form)))))) (when (and (null? (cdr vars)) (pair? (cddr form)) (pair? (caddr form)) (null? (cdddr form))) (let ((body (caddr form)) (sym (var-name (car vars))) (lform (cadar (cadr form)))) ; the letrec var's lambda (when (and (pair? lform) (pair? (cdr lform)) (eq? (car lform) 'lambda) (proper-list? (cadr lform))) ; includes () (if (eq? sym (car body)) ; (letrec ((x (lambda ...))) (x...)) -> (let x (...)...) (if (and (not (tree-memq sym (cdr body))) (< (tree-leaves body) 100)) ;; the limit on tree-leaves is for cases where the args are long lists of data -- ;; more like for-each than let, and easier to read if the code is first, I think. (lint-format "perhaps ~A" caller (lists->string form `(let ,sym ,(map list (cadr lform) (cdr body)) ,@(cddr lform))))) (if (and (not (eq? caller 'define)) (= (tree-count1 sym body 0) 1)) (let ((call (find-call sym body))) (when (pair? call) (let ((new-call `(let ,sym ,(map list (cadr lform) (cdr call)) ,@(cddr lform)))) (lint-format "perhaps ~A" caller (lists->string form (tree-subst new-call call body)))))))))))) ;; maybe (let () ...) here because (letrec ((x (lambda (y) (+ y 1)))) (x (define z 32))) needs to block z? ;; currently we get (let x ((y (define z 32))) (+ y 1)) ;; and even that should be (let () (define z 32) (+ z 1)) or something similar ;; lambda here is handled under define?? (let ((new-env (append vars env))) (when (pair? (cadr form)) (for-each (lambda (binding) (if (binding-ok? caller head binding env #t) (lint-walk caller (cadr binding) new-env))) (cadr form))) (let* ((cur-env (cons (make-var :name :let :initial-value form :definer head) (append vars env))) (e (lint-walk-body caller head (cddr form) cur-env))) (let ((nvars (and (not (eq? e cur-env)) (env-difference caller e cur-env ())))) (if (pair? nvars) (if (memq (var-name (car nvars)) '(:lambda :dilambda)) (begin (set! env (cons (car nvars) env)) (set! nvars (cdr nvars))) (set! vars (append nvars vars))))) (report-usage caller head vars cur-env))))) ; constant exprs never happen here env) (hash-table-set! h 'letrec letrec-walker) (hash-table-set! h 'letrec* letrec-walker)) ;; ---------------- begin ---------------- (let () (define (begin-walker caller form env) (if (not (proper-list? form)) (begin ; (begin . 1) (lint-format "stray dot in begin? ~A" caller (truncated-list->string form)) env) (begin (if (and (pair? (cdr form)) (null? (cddr form))) ; (begin (f y)) (lint-format "begin could be omitted: ~A" caller (truncated-list->string form))) (lint-walk-open-body caller 'begin (cdr form) env)))) (hash-table-set! h 'begin begin-walker)) ;; ---------------- with-baffle ---------------- (let () (define (with-baffle-walker caller form env) ;; with-baffle introduces a new frame, so we need to handle it here (lint-walk-body caller 'with-baffle (cdr form) (cons (make-var :name :let :initial-value form :definer 'with-baffle) env)) env) (hash-table-set! h 'with-baffle with-baffle-walker)) ;; -------- with-let -------- (let () (define (with-let-walker caller form env) (if (< (length form) 3) (lint-format "~A is messed up: ~A" 'with-let caller (truncated-list->string form)) (let ((e (cadr form))) (if (or (and (code-constant? e) (not (let? e))) (and (pair? e) (let ((op (return-type (car e) env))) (and op (not (return-type-ok? 'let? op)))))) ; (with-let 123 123) (lint-format "~A: first argument should be an environment: ~A" 'with-let caller (truncated-list->string form))) (if (symbol? e) (set-ref e caller form env) (if (pair? e) (begin (if (and (null? (cdr e)) (eq? (car e) 'curlet)) ; (with-let (curlet) x) (lint-format "~A is not needed here: ~A" 'with-let caller (truncated-list->string form))) (lint-walk caller e (cons (make-var :name :let :initial-value form :definer 'with-let) env))))) (let ((walked #f) (new-env (cons (make-var :name :with-let :initial-value form :definer 'with-let) env))) (if (or (and (symbol? e) (memq e '(*gtk* *motif* *gl* *libc* *libm* *libgdbm* *libgsl*))) (and (pair? e) (eq? (car e) 'sublet) (pair? (cdr e)) (memq (cadr e) '(*gtk* *motif* *gl* *libc* *libm* *libgdbm* *libgsl*)) (set! e (cadr e)))) (let ((lib (if (defined? e) (symbol->value e) (let ((file (*autoload* e))) (and (string? file) (load file)))))) (when (let? lib) (let-temporarily ((*e* lib)) (let ((e (lint-walk-open-body caller 'with-let (cddr form) new-env))) (report-usage caller 'with-let (if (eq? e env) () (env-difference caller e env ())) new-env))) (set! walked #t)))) (unless walked (lint-walk-open-body caller 'with-let (cddr form) new-env))))) env) (hash-table-set! h 'with-let with-let-walker)) ;; ---------------- defmacro ---------------- (let () (define (defmacro-walker caller form env) (if (or (< (length form) 4) (not (symbol? (cadr form)))) (begin (lint-format "~A declaration is messed up: ~A" caller (car form) (truncated-list->string form)) env) (let ((sym (cadr form)) (args (caddr form)) (body (cdddr form)) (head (car form))) (if (and (pair? args) (repeated-member? args env)) ; (defmacro hi (a b a) a) (lint-format "~A parameter is repeated: ~A" caller head (truncated-list->string args)) (lint-format "~A is deprecated; perhaps ~A" caller head ; (defmacro hi (a b) `(+ ,a ,b)) (truncated-lists->string form `(,(if (eq? head 'defmacro) 'define-macro 'define-macro*) ,(cons sym args) ,@body)))) (lint-walk-function head sym args body form env) (cons (make-var :name sym :initial-value form :definer head) env)))) (hash-table-set! h 'defmacro defmacro-walker) (hash-table-set! h 'defmacro* defmacro-walker)) ;; ---------------- load ---------------- (let () (define (load-walker caller form env) (lint-walk caller (cdr form) env) (if (and *report-loaded-files* (string? (cadr form))) (catch #t (lambda () (lint-file (cadr form) env)) (lambda args env)) env)) (hash-table-set! h 'load load-walker)) ;; ---------------- require ---------------- (let () (define (require-walker caller form env) (if (not (pair? (cdr form))) ; (require) (lint-format "~A is pointless" caller form) (if (any? string? (cdr form)) ; (require "repl.scm") (lint-format "in s7, require's arguments should be symbols: ~A" caller (truncated-list->string form)))) (if (not *report-loaded-files*) env (let ((vars env)) (for-each (lambda (f) (let ((file (*autoload* f))) (if (string? file) (catch #t (lambda () (set! vars (lint-file file vars))) (lambda args #f))))) (cdr form)) vars))) (hash-table-set! h 'require require-walker)) ;; ---------------- call-with-input-file etc ---------------- (let () (define (call-with-io-walker caller form env) (let ((len (if (eq? (car form) 'call-with-output-string) 2 3))) ; call-with-output-string func is the first arg, not second (when (= (length form) len) (let ((func (list-ref form (- len 1)))) (if (= len 3) (lint-walk caller (cadr form) env)) (if (not (and (pair? func) (eq? (car func) 'lambda))) (lint-walk caller func env) (let ((args (cadr func))) (let ((body (cddr func)) (port (and (pair? args) (car args))) (head (car form))) (if (or (not port) (pair? (cdr args))) ;; (lambda () (write args) (newline)) (lint-format "~A argument should be a function of one argument: ~A" caller head func) (if (and (null? (cdr body)) (pair? (car body)) (pair? (cdar body)) (eq? (cadar body) port) (null? (cddar body))) ;; (call-with-input-file "file" (lambda (p) (read-char p))) -> (call-with-input-file "file" read-char) (lint-format "perhaps ~A" caller (lists->string form (if (= len 2) `(,head ,(caar body)) `(,head ,(cadr form) ,(caar body))))) (let ((cc (make-var :name port :initial-value (list (case head ((call-with-input-string) 'open-input-string) ((call-with-output-string) 'open-output-string) ((call-with-input-file) 'open-input-file) ((call-with-output-file) 'open-output-file))) :definer head))) (lint-walk-body caller head body (cons cc (cons (make-var :name :let :initial-value form :definer head) env))) (report-usage caller head (list cc) env)))))))))) env) (for-each (lambda (op) (hash-table-set! h op call-with-io-walker)) '(call-with-input-string call-with-input-file call-with-output-file call-with-output-string))) ;; ---------------- catch ---------------- (let () (define (catch-walker caller form env) ;; catch tag is tricky -- it is evaluated, then eq? matches at error time, so we need ;; to catch constants that can't be eq? (if (not (= (length form) 4)) (begin (lint-format "catch takes 3 arguments (tag body error-handler): ~A" caller (truncated-list->string form)) (lint-walk caller (cdr form) env)) (let ((tag (cadr form))) (if (or (and (not (pair? tag)) (or (number? tag) (char? tag) (length tag))) (and (pair? tag) (eq? (car tag) 'quote) (or (not (pair? (cdr tag))) (length (cadr tag))))) ;; (catch #(0) (lambda () #f) (lambda a a)) (lint-format "catch tag ~S is unreliable (catch uses eq? to match tags)" caller tag)) (let ((body (caddr form)) (error-handler (cadddr form))) ;; empty catch+catch apparently never happens (lint-walk caller body (cons (make-var :name :let :initial-value form :definer 'catch) (cons (make-var :name :catch :initial-value form :definer 'catch) env))) (lint-walk caller error-handler env)))) env) (hash-table-set! h 'catch catch-walker)) ;; ---------------- call-with-exit etc ---------------- (let () (define (call-with-exit-walker caller form env) (let ((continuation (and (pair? (cdr form)) (pair? (cadr form)) (eq? (caadr form) 'lambda) (pair? (cdadr form)) (pair? (cddadr form)) (pair? (cadadr form)) (car (cadadr form))))) (if (not (symbol? continuation)) (lint-walk caller (cdr form) env) (let ((body (cddadr form)) (head (car form))) (if (not (or (eq? head 'call-with-exit) (eq? continuation (car body)) (tree-sym-set-member continuation '(lambda lambda* define define* curlet error apply) body))) ;; this checks for continuation as arg (of anything), and any of set as car ;; (call/cc (lambda (p) (+ x (p 1)))) (lint-format* caller (string-append "perhaps " (symbol->string head)) " could be call-with-exit: " (truncated-list->string form))) (if (not (tree-unquoted-member continuation body)) ;; (call-with-exit (lambda (p) (+ x 1))) (lint-format "~A ~A ~A appears to be unused: ~A" caller head (if (eq? head 'call-with-exit) "exit function" "continuation") continuation (truncated-list->string form)) (let ((last (and (proper-list? body) (list-ref body (- (length body) 1))))) (if (and (pair? last) (eq? (car last) continuation)) ;; (call-with-exit (lambda (return) (display x) (return (+ x y)))) (lint-format "~A is redundant here: ~A" caller continuation (truncated-list->string last))))) (let ((cc (make-var :name continuation :initial-value (if (eq? head 'call-with-exit) :call/exit :call/cc) :definer head))) (lint-walk-body caller head body (cons cc env)) (report-usage caller head (list cc) env))))) env) (for-each (lambda (op) (hash-table-set! h op call-with-exit-walker)) '(call/cc call-with-current-continuation call-with-exit))) ;; ---------------- import etc ---------------- (for-each (lambda (op) (hash-table-set! h op (lambda (caller form env) env))) '(define-module import export)) (hash-table-set! h 'provide (lambda (caller form env) (if (not (= (length form) 2)) ;; (provide a b c) (lint-format "provide takes one argument: ~A" caller (truncated-list->string form)) (unless (symbol? (cadr form)) (let ((op (->lint-type (cadr form)))) (if (not (memq op '(symbol? #f #t values))) ;; (provide "test") (lint-format "provide's argument should be a symbol: ~S" caller form))))) env)) (hash-table-set! h 'module ; module apparently has different syntax and expectations in various schemes (lambda (caller form env) (if (and (pair? (cdr form)) (pair? (cddr form))) (lint-walk 'module (cddr form) env)) env)) (hash-table-set! h 'define-syntax (lambda (caller form env) ;; we need to put the macro name in env with ftype=define-syntax (if (and (pair? (cdr form)) (symbol? (cadr form)) (not (keyword? (cadr form)))) ; !! this thing is a disaster from the very start (cons (make-fvar (cadr form) :ftype 'define-syntax) env) env))) (hash-table-set! h 'define-method ; guile and mit-scheme have different syntaxes here (lambda (caller form env) (if (not (and (pair? (cdr form)) (pair? (cddr form)))) env (if (symbol? (cadr form)) (if (keyword? (cadr form)) (lint-walk-body caller 'define-method (cdddr form) env) (let ((new-env (if (var-member (cadr form) env) env (cons (make-fvar (cadr form) :ftype 'define-method) env)))) (lint-walk-body caller (cadr form) (cdddr form) new-env))) (let ((new-env (if (var-member (caadr form) env) env (cons (make-fvar (caadr form) :ftype 'define-method) env)))) (lint-walk-body caller (caadr form) (cddr form) new-env)))))) (hash-table-set! h 'let-syntax (lambda (caller form env) (lint-walk-body caller 'define-method (cddr form) env) env)) (hash-table-set! h 'letrec-syntax (lambda (caller form env) (lint-walk-body caller 'define-method (cddr form) env) env)) ;; ---------------- case-lambda ---------------- (let () (define (case-lambda-walker caller form env) (when (pair? (cdr form)) (let ((lens ()) (body ((if (string? (cadr form)) cddr cdr) form)) ; might have a doc string before the clauses (doc-string (and (string? (cadr form)) (cadr form)))) (define (arg->defaults arg b1 b2 defaults) (and defaults (cond ((null? b1) (and (null? b2) defaults)) ((null? b2) (and (null? b1) defaults)) ((eq? arg b1) (cons b2 defaults)) ((eq? arg b2) (cons b1 defaults)) ((pair? b1) (and (pair? b2) (arg->defaults arg (car b1) (car b2) (arg->defaults arg (cdr b1) (cdr b2) defaults)))) (else (and (equal? b1 b2) defaults))))) (for-each (lambda (choice) (if (pair? choice) (let ((len (length (car choice)))) (if (member len lens) ;; (case-lambda (() 0) ((x y) x) ((x y) (+ x y)) ((x y z) (+ x y z)) (args (apply + args)) (lint-format "repeated parameter list? ~A in ~A" caller (car choice) form)) (set! lens (cons len lens)) (lint-walk 'case-lambda (cons 'lambda choice) env)))) body) (case (length lens) ((1) ;; (case-lambda (() (if #f #f))) -> (lambda () (if #f #f)) (lint-format "perhaps ~A" caller (lists->string form (if doc-string `(let ((documentation ,doc-string)) (lambda ,(caar body) ,@(cdar body))) `(lambda ,(caar body) ,@(cdar body)))))) ((2) (when (let arglists-equal? ((args1 (caar body)) (args2 (caadr body))) (if (null? args1) (and (pair? args2) (null? (cdr args2))) (and (pair? args1) (if (null? args2) (null? (cdr args1)) (and (pair? args2) (eq? (car args1) (car args2)) (arglists-equal? (cdr args1) (cdr args2))))))) (let* ((clause1 (car body)) (body1 (cdr clause1)) (clause2 (cadr body)) (body2 (cdr clause2)) (arglist (let ((arg1 (car clause1)) (arg2 (car clause2))) (if (> (car lens) (cadr lens)) arg2 arg1))) ; lens is reversed (arg-name (list-ref arglist (- (length arglist) 1))) (diffs (arg->defaults arg-name body1 body2 ()))) (when (and (pair? diffs) (null? (cdr diffs)) (code-constant? (car diffs))) (let ((new-body (if (> (car lens) (cadr lens)) body2 body1)) (new-arglist (if (not (car diffs)) arglist (if (null? (cdr arglist)) `((,arg-name ,(car diffs))) `(,(car arglist) (,arg-name ,(car diffs))))))) ;; (case-lambda (() (display x #f)) ((y) (display x y))) -> (lambda* (y) (display x y)) (lint-format "perhaps ~A" caller (lists->string form (if doc-string `(let ((documentation ,doc-string)) (lambda* ,new-arglist ,@new-body)) `(lambda* ,new-arglist ,@new-body)))))))))))) env) (hash-table-set! h 'case-lambda case-lambda-walker)) h)) ;; end walker-functions ;; ---------------------------------------- (define lint-walk-pair (let ((unsafe-makers '(sublet inlet copy cons list append make-shared-vector vector hash-table hash-table* make-hash-table make-hook #_{list} #_{append} gentemp or and not)) (qq-form #f)) (lambda (caller form env) (let ((head (car form))) (set! line-number (pair-line-number form)) (when *report-function-stuff* (function-match caller form env)) ;; differ-in-one here across args gets few interesting hits (cond ((hash-table-ref walker-functions head) => (lambda (f) (f caller form env))) (else (if (not (proper-list? form)) ;; these appear to be primarily macro/match arguments ;; other cases (not list) have already been dealt with far above (if (and (pair? form) (symbol? head) (procedure? (symbol->value head *e*))) ;; (+ . 1) (lint-format "unexpected dot: ~A" caller (truncated-list->string form))) (begin (cond ((symbol? head) (let ((v (var-member head env))) (if (and (var? v) (not (memq form (var-history v)))) (set! (var-history v) (cons form (var-history v)))) (check-call caller head form env) ;; look for one huge argument leaving lonely trailing arguments somewhere off the screen ;; (it needs to be one arg, not a call on values) (let ((branches (length form))) (when (and (= branches 2) (any-procedure? head env) (not (eq? head 'unquote))) (let ((arg (cadr form))) ;; begin=(car arg) happens very rarely (when (pair? arg) (when (and (memq (car arg) '(let let*)) (not (or (symbol? (cadr arg)) (and (pair? (cddr arg)) (pair? (caddr arg)) (eq? 'lambda (caaddr arg))) (assq head (cadr arg))))) ;; (string->symbol (let ((s (copy vstr))) (set! (s (+ pos 1)) #\s) s)) -> ;; (let ((s (copy vstr))) (set! (s (+ pos 1)) #\s) (string->symbol s))") (lint-format "perhaps~%~NC~A ->~%~NC~A" caller (+ lint-left-margin 4) #\space (truncated-list->string form) (+ lint-left-margin 4) #\space (let* ((body (cddr arg)) (len (- (length body) 1)) (str (object->string `(,(car arg) ,(cadr arg) ,@(copy body (make-list len)) (,head ,(list-ref body len)))))) (if (<= (length str) target-line-length) str (format #f "(~A ... (~A ~A))" (car arg) head (truncated-list->string (list-ref body len))))))) (when (eq? (car arg) 'or) (let ((else-clause (let ((last-clause (list-ref arg (- (length arg) 1)))) (if (and (pair? last-clause) (memq (car last-clause) '(error throw))) last-clause (if (or (not (code-constant? last-clause)) (side-effect? `(,head ,last-clause) env)) :checked-eval-error (let ((res (checked-eval `(,head ,last-clause)))) (if (or (and (symbol? res) (not (eq? res :checked-eval-error))) (pair? res)) (list 'quote res) res))))))) (unless (eq? else-clause :checked-eval-error) (set! last-rewritten-internal-define form) ;; (string->number (or (f x) "4")) -> (cond ((f x) => string->number) (else 4)) (lint-format "perhaps ~A" caller (lists->string form `(cond (,(if (or (null? (cddr arg)) (null? (cdddr arg))) (cadr arg) (copy arg (make-list (- (length arg) 1)))) => ,head) (else ,else-clause)))))))))) (unless (or (<= branches 2) (any-macro? head env) (memq head '(for-each map #_{list} * + - /))) (let ((leaves (tree-leaves form))) (when (> leaves (max *report-bloated-arg* (* branches 3))) (do ((p (cdr form) (cdr p)) (i 1 (+ i 1))) ((or (not (pair? p)) (null? (cdr p)) (and (pair? (car p)) (symbol? (caar p)) (not (memq (caar p) '(lambda quote call/cc list vector match-lambda values))) (> (tree-leaves (car p)) (- leaves (* branches 2))) (or (not (memq head '(or and))) (= i 1)) (not (tree-member 'values (car p))) (let ((header (copy form (make-list i))) (trailer (copy form (make-list (- branches i 1)) (+ i 1))) (disclaimer (if (or (any-procedure? head env) (hash-table-ref no-side-effect-functions head)) "" (format #f ", assuming ~A is not a macro," head)))) ;; begin=(caar p) here is almost entirely as macro arg ;; (apply env-channel (make-env ...) args) -> (let ((_1_ (make-env ...))) (apply env-channel _1_ args)) (lint-format "perhaps~A~%~NC~A ->~%~NC~A" caller disclaimer (+ lint-left-margin 4) #\space (lint-pp `(,@header ,(one-call-and-dots (car p)) ,@trailer)) (+ lint-left-margin 4) #\space (if (and (memq (caar p) '(let let*)) (list? (cadar p)) (not (assq head (cadar p)))) ; actually not intersection header+trailer (map car cadr) (let ((last (let ((body (cddar p))) (list-ref body (- (length body) 1))))) (if (< (tree-leaves last) 12) (format #f "(~A ... ~A)" (caar p) (lint-pp `(,@header ,last ,@trailer))) (lint-pp `(let ((_1_ ,(one-call-and-dots (car p)))) (,@header _1_ ,@trailer))))) (lint-pp `(let ((_1_ ,(one-call-and-dots (car p)))) (,@header _1_ ,@trailer))))) #t))))))))) (when (pair? form) ;; save any references to vars in their var-history (type checked later) ;; this can be fooled by macros, as everywhere else (for-each (lambda (arg) (if (symbol? arg) (let ((v (var-member arg env))) (if (and (var? v) (not (memq form (var-history v)))) (set! (var-history v) (cons form (var-history v))))))) form) (if (set!? form env) (set-set (cadr form) caller form env))) (if (var? v) (if (and (memq (var-ftype v) '(define lambda define* lambda*)) (not (memq caller (var-scope v)))) (let ((cv (var-member caller env))) (set! (var-scope v) (cons (if (and (var? cv) (memq (var-ftype cv) '(define lambda define* lambda*))) ; named-let does not define ftype caller (cons caller env)) (var-scope v))))) (begin (cond ((hash-table-ref special-case-functions head) => (lambda (f) (f caller head form env)))) ;; change (list ...) to '(....) if it's safe as a constant list ;; and (vector ...) -> #(...) (if (and (pair? (cdr form)) (hash-table-ref no-side-effect-functions head) (not (memq head unsafe-makers))) (for-each (lambda (p) (if (let constable? ((cp p)) (and (pair? cp) (memq (car cp) '(list vector)) (pair? (cdr cp)) (every? (lambda (inp) (or (code-constant? inp) (constable? inp))) (cdr cp)))) (lint-format "perhaps ~A -> ~A~A" caller (truncated-list->string p) (if (eq? (car p) 'list) "'" "") (object->string (eval p))))) (cdr form))) (if (and (not (= line-number last-simplify-numeric-line-number)) (hash-table-ref numeric-ops head) (proper-tree? form)) (let ((val (simplify-numerics form env))) (if (not (equal-ignoring-constants? form val)) (begin (set! last-simplify-numeric-line-number line-number) ;; (+ 1 2) -> 3, and many others (lint-format "perhaps ~A" caller (lists->string form val)))))) ;; if a var is used before it is defined, the var history and ref/set ;; info needs to be saved until the definition, so other-identifiers collects it (unless (defined? head (rootlet)) (hash-table-set! other-identifiers head (if (not (hash-table-ref other-identifiers head)) (list form) (cons form (hash-table-ref other-identifiers head))))))) ;; ---------------- ;; (f ... (if A B C) (if A D E) ...) -> (f ... (if A (values B D) (values C E)) ...) ;; these happen up to almost any number of clauses ;; need true+false in every case, and need to be contiguous ;; case/cond happen here, but very rarely in a way we can combine via values (unless (any-macro? head env) ; actually most macros are safe here... (let ((p (member 'if (cdr form) (lambda (x q) (and (pair? q) (eq? (car q) 'if) ; it's an if expression (pair? (cdr q)) (pair? (cddr q)) ; there's a true branch (pair? (cdddr q))))))) ; and a false branch (similarly below) (when (pair? p) (do ((test (cadar p)) (q (cdr p) (cdr q))) ((not (and (pair? q) (let ((x (car q))) (and (pair? x) (eq? (car x) 'if) (pair? (cdr x)) (equal? (cadr x) test) (pair? (cddr x)) (pair? (cdddr x)))))) (unless (eq? q (cdr p)) (let ((header (do ((i 1 (+ i 1)) (r (cdr form) (cdr r))) ((eq? r p) (copy form (make-list i))))) (middle (do ((r p (cdr r)) (trues ()) (falses ())) ((eq? r q) `(if ,test (values ,@(reverse trues)) (values ,@(reverse falses)))) (set! trues (cons (caddar r) trues)) (set! falses (cons (car (cdddar r)) falses))))) ;; (+ (if A B C) (if A C D) y) -> (+ (if A (values B C) (values C D)) y) (lint-format "perhaps~A ~A" caller (if (side-effect? test env) (format #f " (ignoring ~S's possible side-effects)" test) "") (lists->string form `(,@header ,middle ,@q)))))))))))) ((pair? head) (cond ((not (and (pair? (cdr head)) (memq (car head) '(lambda lambda*))))) ((and (identity? head) (pair? (cdr form))) ; identity needs an argument ;; ((lambda (x) x) 32) -> 32 (lint-format "perhaps ~A" caller (truncated-lists->string form (cadr form)))) ((and (null? (cadr head)) (pair? (cddr head))) ;; ((lambda () 32) 0) -> 32 (lint-format "perhaps ~A" caller (truncated-lists->string form (if (and (null? (cdddr head)) (not (and (pair? (caddr head)) (memq (caaddr head) '(define define* define-constant define-macro define-macro*))))) (caddr head) `(let () ,@(cddr head)))))) ((and (pair? (cddr head)) ; ((lambda (...) ...) ...) -> (let ...) -- lambda here is ugly and slow (proper-list? (cddr head)) (not (any? (lambda (a) (mv-range a env)) (cdr form)))) (call-with-exit (lambda (quit) ; uncountably many things can go wrong with the lambda form (let ((vars ()) (vals ())) (do ((v (cadr head) (cdr v)) (a (cdr form) (cdr a))) ((not (and (pair? a) (pair? v))) (if (symbol? v) (begin (set! vars (cons v vars)) (set! vals (cons `(list ,@a) vals))) (do ((v v (cdr v))) ((not (pair? v))) (if (not (pair? v)) (quit)) (if (pair? (car v)) (begin (if (not (pair? (cdar v))) (quit)) (set! vars (cons (caar v) vars)) (set! vals (cons (cadar v) vals))) (begin (set! vars (cons (car v) vars)) (set! vals (cons #f vals))))))) (set! vars (cons ((if (pair? (car v)) caar car) v) vars)) (set! vals (cons (car a) vals))) ;; ((lambda* (a b) (+ a b)) 1) -> (let ((a 1) (b #f)) (+ a b)) (lint-format "perhaps ~A" caller (lists->string form `(,(if (or (eq? (car head) 'lambda) (not (pair? (cadr head))) (null? (cdadr head))) 'let 'let*) ,(map list (reverse vars) (reverse vals)) ,@(cddr head)))))))))) ((and (procedure? head) (memq head '(#_{list} #_{apply_values} #_{append}))) (for-each (lambda (p) (let ((sym (and (symbol? p) p))) (when sym (let ((v (var-member sym env))) (if (var? v) (set-ref sym caller form env) (if (not (defined? sym (rootlet))) (hash-table-set! other-identifiers sym (if (not (hash-table-ref other-identifiers sym)) (list form) (cons form (hash-table-ref other-identifiers sym)))))))))) (cdr form)) (when (and (eq? head #_{list}) (not (eq? lint-current-form qq-form))) (let ((len (length form))) (set! qq-form lint-current-form) ; only interested in simplest cases here (case len ((2) (if (and (pair? (cadr form)) (eq? (caadr form) #_{apply_values}) ; `(,@x) -> (copy x) (not (qq-tree? (cadadr form)))) (lint-format "perhaps ~A" caller (lists->string form (un_{list} (if (pair? (cadadr form)) (cadadr form) `(copy ,(cadadr form)))))) (if (symbol? (cadr form)) (lint-format "perhaps ~A" caller ; `(,x) -> (list x) (lists->string form `(list ,(cadr form))))))) ((3) (if (and (pair? (caddr form)) (eq? (caaddr form) #_{apply_values}) (not (qq-tree? (cadr (caddr form)))) (pair? (cadr form)) ; `(,@x ,@y) -> (append x y) (eq? (caadr form) #_{apply_values}) (not (qq-tree? (cadadr form)))) (lint-format "perhaps ~A" caller (lists->string form `(append ,(un_{list} (cadadr form)) ,(un_{list} (cadr (caddr form)))))))) (else (if (every? (lambda (a) ; `(,@x ,@y etc) -> (append x y ...) (and (pair? a) (eq? (car a) #_{apply_values}) (not (qq-tree? (cdr a))))) (cdr form)) (lint-format "perhaps ~A" caller (lists->string form `(append ,@(map (lambda (a) (un_{list} (cadr a))) (cdr form))))))) ))))) (let ((vars env)) (for-each (lambda (f) (set! vars (lint-walk caller f vars))) form)))) env)))))) (define (lint-walk caller form env) (cond ((symbol? form) (if (memq form '(+i -i)) (format outport "~NC~A is not a number in s7~%" lint-left-margin #\space form)) (set-ref form caller #f env)) ; returns env ((pair? form) (lint-walk-pair caller form env)) ((string? form) (let ((len (length form))) (if (and (> len 16) (string=? form (make-string len (string-ref form 0)))) ;; "*****************************" -> (format #f "~NC" 29 #\\*) (lint-format "perhaps ~S -> ~A" caller form `(format #f "~NC" ,len ,(string-ref form 0))))) env) ((vector? form) (let ((happy #t)) (for-each (lambda (x) (when (and (pair? x) (eq? (car x) 'unquote)) (lint-walk caller (cadr x) env) ; register refs (set! happy #f))) form) ;; (begin (define x 1) `#(,x)) (if (not happy) ; these are used exactly 4 times (in a test suite!) in 2 million lines of open source scheme code (lint-format "quasiquoted vectors are not supported: ~A" caller form))) ;; `(x #(,x)) for example will not work in s7, but `(,x ,(vector x)) will env) (else env))) ;; -------- lint-file -------- (define *report-input* #t) ;; lint-file is called via load etc above and it's a pain to thread this variable all the way down the call chain (define (lint-file-1 file env) (set! linted-files (cons file linted-files)) (let ((fp (if (input-port? file) file (begin (set! *current-file* file) (catch #t (lambda () (let ((p (open-input-file file))) (if *report-input* (format outport (if (and (output-port? outport) (not (memq outport (list *stderr* *stdout*)))) (values "~%~NC~%;~A~%" (+ lint-left-margin 16) #\-) ";~A~%") file)) p)) (lambda args (format outport "~NCcan't open ~S: ~A~%" lint-left-margin #\space file (apply format #f (cadr args))) #f)))))) (when (input-port? fp) (do ((vars env) (line 0) (last-form #f) (last-line-number -1) (form (read fp) (read fp))) ((eof-object? form) (if (not (input-port? file)) (close-input-port fp)) vars) (if (pair? form) (set! line (max line (pair-line-number form)))) (if (not (or (= last-line-number -1) (side-effect? last-form vars))) (format outport "~NCtop-level (line ~D): this has no effect: ~A~%" lint-left-margin #\space last-line-number (truncated-list->string last-form))) (set! last-form form) (set! last-line-number line) (if (and (pair? form) (memq (car form) '(define define-macro)) (pair? (cdr form)) (pair? (cadr form))) (let ((f (caadr form))) (if (and (symbol? f) (hash-table-ref built-in-functions f)) (format outport "~NCtop-level ~Aredefinition of built-in function ~A: ~A~%" lint-left-margin #\space (if (> (pair-line-number form) 0) (format #f "(line ~D) " (pair-line-number form)) "") f (truncated-list->string form))))) (set! vars (lint-walk (if (symbol? form) form (and (pair? form) (car form))) form vars)))))) (define (lint-file file env) ;; (if (string? file) (format *stderr* "lint ~S~%" file)) (if (member file linted-files) env (let ((old-current-file *current-file*) (old-pp-left-margin pp-left-margin) (old-lint-left-margin lint-left-margin) (old-load-path *load-path*)) (dynamic-wind (lambda () (set! pp-left-margin (+ pp-left-margin 4)) (set! lint-left-margin (+ lint-left-margin 4)) (when (and (string? file) (char=? (file 0) #\/)) (let ((last-pos 0)) (do ((pos (char-position #\/ file (+ last-pos 1)) (char-position #\/ file (+ last-pos 1)))) ((not pos) (if (> last-pos 0) (set! *load-path* (cons (substring file 0 last-pos) *load-path*)))) (set! last-pos pos))))) (lambda () (lint-file-1 file env)) (lambda () (set! pp-left-margin old-pp-left-margin) (set! lint-left-margin old-lint-left-margin) (set! *current-file* old-current-file) (set! *load-path* old-load-path) (if (positive? (length *current-file*)) (newline outport))))))) ;;; --------------------------------------------------------------------------------' ;;; lint itself ;;; (let ((documentation "(lint file port) looks for infelicities in file's scheme code") (signature (list #t string? output-port? boolean?))) (lambda* (file (outp *output-port*) (report-input #t)) (set! outport outp) (set! other-identifiers (make-hash-table)) (set! linted-files ()) (fill! other-names-counts 0) (set! last-simplify-boolean-line-number -1) (set! last-simplify-numeric-line-number -1) (set! last-simplify-cxr-line-number -1) (set! last-checker-line-number -1) (set! last-cons-line-number -1) (set! last-if-line-number -1) (set! last-rewritten-internal-define #f) (set! line-number -1) (set! quote-warnings 0) (set! pp-left-margin 0) (set! lint-left-margin -3) ; lint-file above adds 4 (set! big-constants (make-hash-table)) (set! equable-closures (make-hash-table)) (set! *report-input* report-input) (set! *report-nested-if* (if (integer? *report-nested-if*) (max 3 *report-nested-if*) 4)) (set! *report-short-branch* (if (integer? *report-short-branch*) (max 0 *report-short-branch*) 12)) (set! *#readers* (list (cons #\e (lambda (str) (if (not (string=? str "e")) (let ((num (string->number (substring str 1)))) (if num (cond ((rational? num) (format outport "~NCthis #e is dumb, #~A -> ~A~%" lint-left-margin #\space str (substring str 1))) ((not (real? num)) (format outport "~NC#e can't handle complex numbers, #~A -> ~A~%" lint-left-margin #\space str num)) ((= num (floor num)) (format outport "~NCperhaps #~A -> ~A~%" lint-left-margin #\space str (floor num))))))) #f)) (cons #\i (lambda (str) (if (not (string=? str "i")) (let ((num (string->number (substring str 1)))) (if num (format outport (if (not (rational? num)) (values "~NCthis #i is dumb, #~A -> ~A~%" lint-left-margin #\space str (substring str 1)) (values "~NCperhaps #~A -> ~A~%" lint-left-margin #\space str (* 1.0 num))))))) #f)) (cons #\d (lambda (str) (if (and (not (string=? str "d")) (string->number (substring str 1))) (format outport "~NC#d is pointless, #~A -> ~A~%" lint-left-margin #\space str (substring str 1))) #f)) (cons #\' (lambda (str) ; for Guile (and syntax-rules, I think) (list 'syntax (if (string=? str "'") (read) (string->symbol str))))) (cons #\` (lambda (str) ; for Guile (sigh) (list 'quasisyntax (if (string=? str "'") (read) (string->symbol str))))) (cons #\, (lambda (str) ; the same, the last is #,@ -> unsyntax-splicing -- right. (list 'unsyntax (if (string=? str "'") (read) (string->symbol str))))) (cons #\& (lambda (str) ; ancient Guile code (make-keyword (substring str 1)))) (cons #\\ (lambda (str) (cond ((assoc str '(("\\x0" . #\null) ("\\x7" . #\alarm) ("\\x8" . #\backspace) ("\\x9" . #\tab) ("\\xd" . #\return) ("\\xa" . #\newline) ("\\1b" . #\escape) ("\\x20" . #\space) ("\\x7f" . #\delete))) => (lambda (c) (format outport "~NC#\\~A is ~W~%" lint-left-margin #\space (substring str 1) (cdr c))))) #f)) (cons #\! (lambda (str) (if (member str '("!optional" "!default" "!rest" "!key" "!aux" "!false" "!true" "!r6rs") string-ci=?) ; for MIT-scheme (make-keyword (substring str 1)) (let ((lc (str 0))) ; s7 should handle this, but... (do ((c (read-char) (read-char))) ((or (and (eof-object? c) (or (format outport "~NCunclosed block comment~%" lint-left-margin #\space) #t)) (and (char=? lc #\!) (char=? c #\#))) #f) (set! lc c)))))))) ;; try to get past all the # and \ stuff in other Schemes ;; main remaining problem: [] used as parentheses (Gauche and Chicken for example) (set! (hook-functions *read-error-hook*) (list (lambda (h) (let ((data (h 'data)) (line (port-line-number))) (if (not (h 'type)) (begin (format outport "~NCreader[~A]: unknown \\ usage: \\~C~%" lint-left-margin #\space line data) (set! (h 'result) data)) (begin (format outport "~NCreader[~A]: unknown # object: #~A~%" lint-left-margin #\space line data) (set! (h 'result) (catch #t (lambda () (case (data 0) ((#\;) (read) (values)) ((#\T) (string=? data "T")) ((#\F) (and (string=? data "F") ''#f)) ((#\X #\B #\O #\D) (let ((num (string->number (substring data 1) (case (data 0) ((#\X) 16) ((#\O) 8) ((#\B) 2) ((#\D) 10))))) (if (number? num) (begin (format outport "~NCuse #~A~A not #~A~%" lint-left-margin #\space (char-downcase (data 0)) (substring data 1) data) num) (string->symbol data)))) ((#\l #\z) (let ((num (string->number (substring data 1)))) ; Bigloo (also has #ex #lx #z and on and on) (if (number? num) (begin (format outport "~NCjust omit this silly #~C!~%" lint-left-margin #\space (data 0)) num) (string->symbol data)))) ((#\u) ; for Bigloo (if (string=? data "unspecified") (format outport "~NCuse #<unspecified>, not #unspecified~%" lint-left-margin #\space)) ;; #<unspecified> seems to hit the no-values check? (string->symbol data)) ;; Bigloo also seems to use #" for here-doc concatenation?? ((#\v) ; r6rs byte-vectors? (if (string=? data "vu8") (format outport "~NCuse #u8 in s7, not #vu8~%" lint-left-margin #\space)) (string->symbol data)) ((#\>) ; for Chicken, apparently #>...<# encloses in-place C code (do ((last #\#) (c (read-char) (read-char))) ((and (char=? last #\<) (char=? c #\#)) (values)) (if (char=? c #\newline) (set! (port-line-number ()) (+ (port-line-number) 1))) (set! last c))) ((#\<) ; Chicken also, #<<EOF -> EOF (if (and (char=? (data 1) #\<) (> (length data) 2)) (do ((end (substring data 2)) (c (read-line) (read-line))) ((string-position end c) (values))) (string->symbol data))) ((#\\) (cond ((assoc data '(("\\newline" . #\newline) ("\\return" . #\return) ("\\space" . #\space) ("\\tab" . #\tab) ("\\null" . #\null) ("\\nul" . #\null) ("\\linefeed" . #\linefeed) ("\\alarm" . #\alarm) ("\\esc" . #\escape) ("\\escape" . #\escape) ("\\rubout" . #\delete) ("\\delete" . #\delete) ("\\backspace" . #\backspace) ("\\page" . #\xc) ("\\altmode" . #\escape) ("\\bel" . #\alarm) ; #\x07 ("\\sub" . #\x1a) ("\\soh" . #\x01) ;; these are for Guile ("\\vt" . #\xb) ("\\bs" . #\backspace) ("\\cr" . #\newline) ("\\sp" . #\space) ("\\lf" . #\linefeed) ("\\nl" . #\null) ("\\ht" . #\tab) ("\\ff" . #\xc) ("\\np" . #\xc)) string-ci=?) => (lambda (c) (format outport "~NCperhaps use ~W instead~%" (+ lint-left-margin 4) #\space (cdr c)) (cdr c))) (else (string->symbol (substring data 1))))) (else (string->symbol data)))) (lambda args #f))))))))) (let ((vars (lint-file file ()))) (set! lint-left-margin (max lint-left-margin 1)) (when (pair? vars) (if *report-multiply-defined-top-level-functions* (for-each (lambda (var) (let ((var-file (hash-table-ref *top-level-objects* (car var)))) (if (not var-file) (hash-table-set! *top-level-objects* (car var) *current-file*) (if (and (string? *current-file*) (not (string=? var-file *current-file*))) (format outport "~NC~S is defined at the top level in ~S and ~S~%" lint-left-margin #\space (car var) var-file *current-file*))))) vars)) (if (string? file) (report-usage top-level: "" vars vars)))) (for-each (lambda (p) (if (or (> (cdr p) 5) (and (> (cdr p) 3) (> (length (car p)) 12))) (format outport "~A~A occurs ~D times~%" (if (pair? (car p)) "'" "") (truncated-list->string (car p)) (cdr p)))) big-constants) (if (and *report-undefined-identifiers* (positive? (hash-table-entries other-identifiers))) (let ((lst (sort! (map car other-identifiers) (lambda (a b) (string<? (symbol->string a) (symbol->string b)))))) (format outport "~NCth~A identifier~A not defined~A: ~{~S~^ ~}~%" lint-left-margin #\space (if (= (hash-table-entries other-identifiers) 1) (values "is" " was") (values "e following" "s were")) (if (string? file) (format #f " in ~S" file) "") lst) (fill! other-identifiers #f))))))) ;;; -------------------------------------------------------------------------------- ;;; this reads an HTML file, finds likely-looking scheme code, and runs lint over it. ;;; called on all snd files in hg.scm (define (html-lint file) (define (remove-markups str) (let ((tpos (string-position "<b>" str))) (if tpos (let ((epos (string-position "</b>" str))) (remove-markups (string-append (substring str 0 tpos) (substring str (+ tpos 3) epos) (substring str (+ epos 4))))) (let ((apos (string-position "<a " str)) (epos (string-position "<em " str))) (if (not (or apos epos)) str (let* ((pos ((if (and apos epos) min or) apos epos)) (bpos (+ (char-position #\> str (+ pos 1)) 1)) (epos (string-position (if (and apos (= pos apos)) "</a>" "</em>") str bpos))) (string-append (substring str 0 pos) (substring str bpos epos) (remove-markups (substring str (+ epos (if (and apos (= apos pos)) 4 5))))))))))) (define (fixup-html str) (let ((pos (char-position #\& str))) (if (not pos) str (string-append (substring str 0 pos) (let* ((epos (char-position #\; str pos)) (substr (substring str (+ pos 1) epos))) (string-append (cond ((assoc substr '(("gt" . ">") ("lt" . "<") ("mdash" . "-") ("amp" . "&")) string=?) => cdr) (else (format () "unknown: ~A~%" substr))) (fixup-html (substring str (+ epos 1))))))))) (call-with-input-file file (lambda (f) (do ((line-num 0 (+ line-num 1)) (line (read-line f #t) (read-line f #t))) ((eof-object? line)) ;; look for <pre , gather everything until </pre> ;; decide if it is scheme code (first char is #\() ;; if so, clean out html markup stuff, call lint on that (let ((pos (string-position "<pre" line))) (when pos (let ((code (substring line (+ (char-position #\> line) 1)))) (do ((cline (read-line f #t) (read-line f #t)) (rline 1 (+ rline 1))) ((string-position "</pre>" cline) (set! line-num (+ line-num rline))) (set! code (string-append code cline))) ;; is first non-whitespace char #\(? ignoring comments (do ((len (length code)) (i 0 (+ i 1))) ((>= i len)) (let ((c (string-ref code i))) (if (not (char-whitespace? c)) (if (char=? c #\;) (set! i (char-position #\newline code i)) (begin (set! i (+ len 1)) (if (char=? c #\() (catch #t (lambda () (let ((outstr (call-with-output-string (lambda (op) (call-with-input-string (object->string (with-input-from-string (fixup-html (remove-markups code)) read) #t) ; write, not display (lambda (ip) (let-temporarily ((*report-shadowed-variables* #t)) (lint ip op #f)))))))) (if (> (length outstr) 1) ; possible newline at end (format () ";~A ~D: ~A~%" file line-num outstr)))) (lambda args (format () ";~A ~D, error in read: ~A ~A~%" file line-num args (fixup-html (remove-markups code)))))))))))))))))) ;;; -------------------------------------------------------------------------------- ;;; and this reads C code looking for s7_eval_c_string. No attempt here to ;;; handle weird cases. (define (C-lint file) (call-with-input-file file (lambda (f) (do ((line-num 0 (+ line-num 1)) (line (read-line f #t) (read-line f #t))) ((eof-object? line)) ;; look for s7_eval_c_string, get string arg without backslashes, call lint (let ((pos (string-position "s7_eval_c_string(sc, \"(" line))) (when pos (let ((code (substring line (+ pos (length "s7_eval_c_string(sc, \""))))) (if (not (string-position "\");" code)) (do ((cline (read-line f #t) (read-line f #t)) (rline 1 (+ rline 1))) ((string-position "\");" cline) (set! code (string-append code cline)) (set! line-num (+ line-num rline))) (set! code (string-append code cline)))) (let ((len (string-position "\");" code))) (set! code (substring code 0 len)) ;; clean out backslashes (do ((i 0 (+ i 1))) ((>= i (- len 3))) (if (char=? (code i) #\\) (cond ((char=? (code (+ i 1)) #\n) (set! (code i) #\space) (set! (code (+ i 1)) #\space)) ((memv (code (+ i 1)) '(#\newline #\")) (set! (code i) #\space)) ((and (char=? (code (+ i 1)) #\\) (char=? (code (- i 1)) #\#)) (set! (code (- i 1)) #\space) (set! (code i) #\#)))))) (catch #t (lambda () (let ((outstr (call-with-output-string (lambda (op) (call-with-input-string code (lambda (ip) (let-temporarily ((*report-shadowed-variables* #t)) (lint ip op #f)))))))) (if (> (length outstr) 1) ; possible newline at end (format () ";~A ~D: ~A~%" file line-num outstr)))) (lambda args (format () ";~A ~D, error in read: ~A ~A~%" file line-num args code)))))))))) ;;; -------------------------------------------------------------------------------- #| ;;; external use of lint contents (see also snd-lint.scm): (for-each (lambda (f) (if (not (hash-table-ref (*lint* 'no-side-effect-functions) (car f))) (format *stderr* "~A " (car f)))) (*lint* 'built-in-functions)) ;;; get rid of []'s! (using Snd) (define (edit file) (let* ((str (file->string file)) (len (length str))) (do ((i 0 (+ i 1))) ((= i len)) (case (str i) ((#\]) (set! (str i) #\))) ((#\[) (set! (str i) #\()))) (call-with-output-file file (lambda (p) (display str p))) #f)) |# ;;; -------------------------------------------------------------------------------- ;;; TODO: ;;; ;;; code-equal if/when/unless/cond, case: any order of clauses, let: any order of vars, etc, zero/=0 ;;; include named-lets in this search ;;; these should translate when/unless first -> if? ;;; (abs|magnitude (- x y)) is reversible internally ;;; indentation is confused in pp by if expr+values?, pp handling of (list ((lambda...)..)) is bad ;;; there are now lots of cases where we need to check for values (/ as invert etc) ;;; the ((lambda ...)) -> let rewriter is still tricked by values ;;; for scope calc, each macro call needs to be expanded or use out-vars? ;;; if we know a macro's value, expand via macroexpand each time encountered and run lint on that? [see tmp for expansion] ;;; hg-results has a lot of changes ;;; lint output needs to be organized somehow ;;; define-macro used once -> expand? -- would have to be a local definition [see define-walker] ;;; accessor rep 9349 misses if <expr> sym, and let name ((arg sym)) -- how to store these in the history? ;;; [<syntax> sym]? -- need to check binding forms etc ;;; do->map similar to do->for-each? named-let|recursive func->for-each|map ;;; what about do+int-step from 0+1 using list|vector|string-ref? ;;; for-each/map stepping explicitly (not using added args), or similarly for do ;;; named-let->do if one arg is counter, ->for-each if only null? ends ;;; ;;; 148 24013 656883
true
1c9fa7c1903356089d86c34c5e2108cefd8ccf06
95cf66a8b36c421b6e04da3e91c22d97b88d6e48
/Scheme/DZ2/1.scm
dabe76f7fb76560e0e083c28e2ad878f4ce18d09
[]
no_license
AleksMa/Tasks
79ab063888fd0544a7c7ba569febc7ed46796ae6
bc516a02bf94f8502f1d56384ef6c5bd3165d2c9
refs/heads/master
2020-03-18T02:14:00.562793
2020-02-28T17:22:01
2020-02-28T17:22:01
134,180,799
2
0
null
null
null
null
UTF-8
Scheme
false
false
2,169
scm
1.scm
(define a 1) (define b 2) ;(define expression (list '+ 'a 'b) ; (eval expression (interaction-environment))) (define (x^2? expr) ; (expt b 2) (and (list? expr) (= (length expr) 3) (eq? (list-ref expr 0) 'expt) (= (list-ref expr 2) 2) (or (number? (list-ref expr 1)) (list? (list-ref expr 1)) (symbol? (list-ref expr 1))))) (define (x^3? expr) ; (expt b 3) (and (list? expr) (= (length expr) 3) (eq? (list-ref expr 0) 'expt) (= (list-ref expr 2) 3) (or (number? (list-ref expr 1)) (list? (list-ref expr 1)) (symbol? (list-ref expr 1))))) (define (a^2-b^2? expr) (and (list? expr) (= (length expr) 3) (eq? (list-ref expr 0) '-) (x^2? (list-ref expr 1)) (x^2? (list-ref expr 2)))) (define (a^3-b^3? expr) (and (list? expr) (= (length expr) 3) (eq? (list-ref expr 0) '-) (x^3? (list-ref expr 1)) (x^3? (list-ref expr 2)))) (define (a^3+b^3? expr) (and (list? expr) (= (length expr) 3) (eq? (list-ref expr 0) '+) (x^3? (list-ref expr 1)) (x^3? (list-ref expr 2)))) (define (factorize-a^2-b^2 expr) ; (- (expt a 2) (expt b 2)) (define a (list-ref (list-ref expr 1) 1)) (define b (list-ref (list-ref expr 2) 1)) ;(list '* (list '- a b) (list '+ a b))) ; ;Quasiquote ; `(цитирование) ,(подстановка) @(== apply) `(* (- ,a ,b) (+ ,a ,b))) (define (factorize-a^3-b^3 expr) (define a (list-ref (list-ref expr 1) 1)) (define b (list-ref (list-ref expr 2) 1)) `(* (- ,a ,b) (+ (expt ,a 2) (* ,a ,b) (expt ,b 2)))) (define (factorize-a^3+b^3 expr) (define a (list-ref (list-ref expr 1) 1)) (define b (list-ref (list-ref expr 2) 1)) `(* (+ ,a ,b) (+ (expt ,a 2) (- (* ,a ,b)) (expt ,b 2)))) (define (factorize expr) (or (and (a^2-b^2? expr) (factorize-a^2-b^2 expr)) (and (a^3-b^3? expr) (factorize-a^3-b^3 expr)) (and (a^3+b^3? expr) (factorize-a^3+b^3 expr)))) ;(factorize '(- (expt x 2) (expt y 2))) ;(factorize '(- (expt 1 2) (expt 2 2))) ;(factorize '(- (expt a 2) (expt b 2)))
false
6468bd53ceba3a9b8a09e428c94b8803419318eb
43612e5ed60c14068da312fd9d7081c1b2b7220d
/tools/benchtimes/prefix/Pycket.scm
5ee343a1be69af305d8faedc17d02e28c3bb4315
[ "BSD-3-Clause" ]
permissive
bsaleil/lc
b1794065183b8f5fca018d3ece2dffabda6dd9a8
ee7867fd2bdbbe88924300e10b14ea717ee6434b
refs/heads/master
2021-03-19T09:44:18.905063
2019-05-11T01:36:38
2019-05-11T01:36:38
41,703,251
27
1
BSD-3-Clause
2018-08-29T19:13:33
2015-08-31T22:13:05
Scheme
UTF-8
Scheme
false
false
4,101
scm
Pycket.scm
#lang r5rs (#%require compatibility/defmacro) (#%require (only racket/base time arithmetic-shift bitwise-and)) (define-syntax define-syntax-rule (syntax-rules () ((define-syntax-rule (name . pattern) template) (define-syntax name (syntax-rules () ((name . pattern) template)))))) (define-syntax-rule (error a ...) #f) (define-syntax-rule (fatal-error a ...) #f) (define-syntax-rule (list->f64vector lst) (list->vector lst)) (define-syntax-rule (f64vector? lst) (vector? lst)) (define-syntax-rule (f64vector a ...) (vector a ...)) (define-syntax-rule (make-f64vector a ...) (make-vector a ...)) (define-syntax-rule (f64vector-ref a ...) (vector-ref a ...)) (define-syntax-rule (f64vector-set! a ...) (vector-set! a ...)) (define-syntax-rule (f64vector-length a ...) (vector-length a ...)) ;------------------------------------------------------------------------------ ; Macros (define-syntax-rule (nuc-const a ...) '#(a ...)) (define-syntax-rule (floatvector-const a ...) (vector a ...)) ;(define-macro (FLOATvector-const . lst) `',(list->f64vector lst)) (define-syntax-rule (FLOATvector? x) (f64vector? x)) (define-syntax-rule (FLOATvector a ...) (f64vector a ...)) (define-syntax-rule (FLOATmake-vector n a ...) (make-f64vector n a ...)) (define-syntax-rule (FLOATvector-ref v i) (f64vector-ref v i)) (define-syntax-rule (FLOATvector-set! v i x) (f64vector-set! v i x)) (define-syntax-rule (FLOATvector-length v) (f64vector-length v)) ; (define-macro (nuc-const . lst) ; `',(list->vector ; (map (lambda (x) ; (if (vector? x) ; (list->f64vector (vector->list x)) ; x)) ; lst))) (define-syntax-rule (FLOAT+ a ...) (+ a ...)) (define-syntax-rule (FLOAT- a ...) (- a ...)) (define-syntax-rule (FLOAT* a ...) (* a ...)) (define-syntax-rule (FLOAT/ a ...) (/ a ...)) (define-syntax-rule (FLOAT= a ...) (= a ...)) (define-syntax-rule (FLOAT< a ...) (< a ...)) (define-syntax-rule (FLOAT<= a ...) (<= a ...)) (define-syntax-rule (FLOAT> a ...) (> a ...)) (define-syntax-rule (FLOAT>= a ...) (>= a ...)) (define-syntax-rule (FLOATnegative? a ...) (negative? a ...)) (define-syntax-rule (FLOATpositive? a ...) (positive? a ...)) (define-syntax-rule (FLOATzero? a ...) (zero? a ...)) (define-syntax-rule (FLOATabs a ...) (abs a ...)) (define-syntax-rule (FLOATsin a ...) (sin a ...)) (define-syntax-rule (FLOATcos a ...) (cos a ...)) (define-syntax-rule (FLOATatan a ...) (atan a ...)) (define-syntax-rule (FLOATsqrt a ...) (sqrt a ...)) (define-syntax-rule (FLOATmin a ...) (min a ...)) (define-syntax-rule (FLOATmax a ...) (max a ...)) (define-syntax-rule (FLOATround a ...) (round a ...)) (define-syntax-rule (FLOATinexact->exact a ...) (inexact->exact a ...)) (define-syntax-rule (GENERIC+ a ...) (+ a ...)) (define-syntax-rule (GENERIC- a ...) (- a ...)) (define-syntax-rule (GENERIC* a ...) (* a ...)) (define-syntax-rule (GENERIC/ a ...) (/ a ...)) (define-syntax-rule (GENERICquotient a ...) (quotient a ...)) (define-syntax-rule (GENERICremainder a ...) (remainder a ...)) (define-syntax-rule (GENERICmodulo a ...) (modulo a ...)) (define-syntax-rule (GENERIC= a ...) (= a ...)) (define-syntax-rule (GENERIC< a ...) (< a ...)) (define-syntax-rule (GENERIC<= a ...) (<= a ...)) (define-syntax-rule (GENERIC> a ...) (> a ...)) (define-syntax-rule (GENERIC>= a ...) (>= a ...)) (define-syntax-rule (GENERICexpt a ...) (expt a ...)) ;;------------------------------------------------------------------------------ (define (run-bench name count ok? run) (let loop ((i count) (result '(undefined))) (if (< 0 i) (loop (- i 1) (run)) result))) (define (run-benchmark name count ok? run-maker . args) (let ((run (apply run-maker args))) (let ((result (time (run-bench name count ok? run)))) (if (not (ok? result)) (begin (display "*** wrong result ***") (newline) (display "*** got: ") (write result) (newline))))))
true
92e77e831530507a67240b7b6a804ef5cb5cd35c
4b5dddfd00099e79cff58fcc05465b2243161094
/chapter_3/exercise_3_33.scm
e7b1d24a75db7a3f9d679279f88215d2d67369b4
[ "MIT" ]
permissive
hjcapple/reading-sicp
c9b4ef99d75cc85b3758c269b246328122964edc
f54d54e4fc1448a8c52f0e4e07a7ff7356fc0bf0
refs/heads/master
2023-05-27T08:34:05.882703
2023-05-14T04:33:04
2023-05-14T04:33:04
198,552,668
269
41
MIT
2022-12-20T10:08:59
2019-07-24T03:37:47
Scheme
UTF-8
Scheme
false
false
512
scm
exercise_3_33.scm
#lang racket ;; P205 - [练习 3.33] (#%require "constraints.scm") ;; (a + b) = 2 * c (define (averager a b c) (let ((x (make-connector)) (y (make-connector))) (adder a b x) (multiplier y c x) (constant 2 y) 'ok)) ;;;;;;;;;;;;;;;;;;;;;;; (define a (make-connector)) (define b (make-connector)) (define c (make-connector)) (probe "a" a) (probe "b" b) (probe "c" c) (averager a b c) (set-value! a 20 'user) (set-value! b 10 'user) (forget-value! a 'user) (set-value! c 40 'user)
false