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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ba3b9be36205ea1c54ca0bf06a61f8eb8edad56c
|
589c645f2653e48bb38c018ae4e211b002a280a9
|
/user-settings.scm
|
1f0832b03330281eb68f51029db50dae1e5f70f5
|
[] |
no_license
|
ziotom78/plancknull_generate_html
|
f596bdd0f03a8bd946e7ac21060195b4884cd9c1
|
e7007a371d9b6d399cf580e4568e02f96e11d592
|
refs/heads/master
| 2020-08-25T03:32:12.105347 | 2013-05-09T10:08:31 | 2013-05-09T10:08:31 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,722 |
scm
|
user-settings.scm
|
(module user-settings
(parse-command-line user-args)
(import chicken scheme extras)
;; Command-line parsing
;; ====================
;; Here we implement the code that will read the JSON files from the
;; command-line and merge them into one big list of dictionaries
;; (a-lists).
;; If `args` is the list of command-line arguments provided to the
;; program, function `parse-command-line` analyzes them and returns
;; an associative list containing the following fields:
;; `'output-dir` is a string specifying the directory where to save
;; the report, `'input-dir` is a string containing the path where to
;; look for JSON files, and `'data-release-name` is a string
;; containing the name of the data release, to be put at the top of
;; each HTML page of the report.
(define (parse-command-line program-name args)
(if (not (eq? (length args) 3))
(begin (format #t #<<EOF
Usage: ~a DATA_RELEASE_NAME NULL_TEST_DIR OUTPUT_PATH
where DATA_RELEASE_NAME is a string identifying the data release (e.g.
DX9), NULL_TEST_DIR is the path to the directory containing the
results of the null tests to be included in the report, and
OUTPUT_PATH is the path where to save the files of the HTML report. If
OUTPUT_PATH does not exist, it will be created.
EOF
program-name)
(exit 1)))
(list (cons 'data-release-name (car args))
(cons 'input-dir (cadr args))
(cons 'output-dir (caddr args))))
;; The variable `user-args` holds all the information the user
;; specified from the command line. Note that `argv` (function, not
;; variable!) is not part of R5RS: it is a Chicken extension.
(define user-args (parse-command-line (car (argv))
(cdr (argv)))))
| false |
ff7da245206697ae68cc055f71c2da725a7026f8
|
557c51d080c302a65e6ef37beae7d9b2262d7f53
|
/workspace/comp-tester/a/a10.ss
|
711699235cc93252504fdc4c09558e9625650643
|
[] |
no_license
|
esaliya/SchemeStack
|
286a18a39d589773d33e628f81a23bcdd0fc667b
|
dcfa1bbfa63b928a7ea3fc244f305369763678ad
|
refs/heads/master
| 2020-12-24T16:24:08.591437 | 2016-03-08T15:30:37 | 2016-03-08T15:30:37 | 28,023,003 | 3 | 4 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 8,425 |
ss
|
a10.ss
|
; Saliya Ekanayake
; sekanaya
; Assignment 10
;---------------------------------------------------------------
; Pass:
; specify-representation
;
; Description:
; This pass encodes Scheme objects as integers in UIL.
; The representation, ptr, is based on the low-tagging.
; Immediate objects, i.e. fixnum, #t, #t, (), and void
; primitive are tagged with three low order bit tags
; leaving the value (for fixnum) in the remaining 61 high
; order bits. The rest other than fixnums use a common
; three low order bit tag with a unique high order five
; bit tag following that.
;
; Heap allocated objects are represented by a ptr with
; true-address + tag. The memory alignment in x64 system
; naturally makes it all zero for low 3 bits for memory
; addresses. This makes it possible to use the tagging
; without distorting the effective true address bits.
;
; This pass also transforms Scheme primitive operations
; to UIL operations.
;
; Input Language:
; Program --> (letrec ([label (lambda (uvar*) Value)]*) Value)
; Value --> label
; | uvar
; | (quote Immediate)
; | (if Pred Value Value)
; | (begin Effect* Value)
; | (let ([uvar Value]*) Value)
; | (value-prim Value*)
; | (Value Value*)
; Pred --> (true)
; | (false)
; | (if Pred Pred Pred)
; | (begin Effect* Pred)
; | (let ([uvar Value]*) Pred)
; | (pred-prim Value*)
; Effect --> (nop)
; | (if Pred Effect Effect)
; | (begin Effect* Effect)
; | (let ([uvar Value]*) Effect)
; | (effect-prim Value*)
; | (Value Value*)
; Immediate --> fixnum | () | #t | #f
;
; value-prim:
; +, -, *, car, cdr, cons, make-vector, vector-length,
; vector-ref, void
;
; pred-prim:
; <, <=, =, >=, >, boolean?, eq?, fixnum?, null?, pair?, vector?
;
; effect-prim:
; set-car!, set-cdr!, vector-set!
;
; Output Language:
; Program --> (letrec ([label (lambda (uvar*) Tail)]*) Tail)
; Tail --> Triv
; | (alloc Value)
; | (binop Value Value)
; | (Value Value*)
; | (if Pred Tail Tail)
; | (begin Effect* Tail)
; | (let ([uvar Value]*) Tail)
; Pred --> (true)
; | (false)
; | (relop Value Value)
; | (if Pred Pred Pred)
; | (begin Effect* Pred)
; | (let ([uvar Value]*) Pred)
; Effect --> (nop)
; | (mset! Value Value Value)
; | (Value Value*)
; | (if Pred Effect Effect)
; | (begin Effect* Effect)
; | (let ([uvar Value]*) Effect)
; Value --> Triv
; | (alloc Value)
; | (binop Value Value)
; | (Value Value*)
; | (if Pred Value Value)
; | (begin Effect* Value)
; | (let ([uvar Value]*) Value)
; Triv --> uvar | int | label
;---------------------------------------------------------------
(define-who specify-representation
(define value-prim '(+ - * car cdr cons make-vector vector-length vector-ref void))
(define pred-prim '(< <= = >= > boolean? eq? fixnum? null? pair? vector?))
(define effect-prim '(set-car! set-cdr! vector-set!))
(define imm-op '(+ - * < <= = >= > void))
(define non-imm-op '(car cdr cons make-vector vector-length vector-ref set-car! set-cdr! vector-set!))
(define pred-op '(boolean? fixnum? null? pair? vector? eq?))
(define (handle-primitive x)
(match x
[(,prim ,val* ...)
(let ([f (cond
[(memq prim imm-op) handle-imm-op]
[(memq prim non-imm-op) handle-non-imm-op]
[(memq prim pred-op) handle-pred-op])])
(f `(,prim ,val* ...)))]))
(define (handle-imm-op x)
(match x
[(void) $void]
[(* ,x ,y)
(cond
[(integer? x) `(* ,(sra x shift-fixnum) ,y)]
[(integer? y) `(* ,x ,(sra y shift-fixnum))]
[else `(* ,x (sra ,y ,shift-fixnum))])]
[(,op ,val* ...) `(,op ,val* ...)]))
(define (handle-non-imm-op x)
(match x
[(car ,e) `(mref ,e ,(- disp-car tag-pair))]
[(cdr ,e) `(mref ,e ,(- disp-cdr tag-pair))]
[(cons ,e1 ,e2)
(let ([tmp-car (unique-name 't)]
[tmp-cdr (unique-name 't)]
[tmp (unique-name 't)])
`(let ([,tmp-car ,e1] [,tmp-cdr ,e2])
(let ([,tmp (+ (alloc ,size-pair) ,tag-pair)])
,(make-begin
`((mset! ,tmp ,(- disp-car tag-pair) ,tmp-car)
(mset! ,tmp ,(- disp-cdr tag-pair) ,tmp-cdr)
,tmp)))))]
[(set-car! ,e1 ,e2)
`(mset! ,e1 ,(- disp-car tag-pair) ,e2)]
[(set-cdr! ,e1 ,e2)
`(mset! ,e1 ,(- disp-cdr tag-pair) ,e2)]
[(vector-ref ,e1 ,e2)
(if (and (integer? e2) (exact? e2))
`(mref ,e1 ,(+ (- disp-vector-data tag-vector) e2))
`(mref ,e1 (+ ,(- disp-vector-data tag-vector) ,e2)))]
[(vector-set! ,e1 ,e2 ,e3)
(if (and (integer? e2) (exact? e2))
`(mset! ,e1 ,(+ (- disp-vector-data tag-vector) e2) ,e3)
`(mset! ,e1 (+ ,(- disp-vector-data tag-vector) ,e2) ,e3))]
[(vector-length ,e)
`(mref ,e ,(- disp-vector-length tag-vector))]
[(make-vector ,e)
(if (and (integer? e) (exact? e))
(let ([tmp (unique-name 't)])
`(let ([,tmp (+ (alloc ,(+ disp-vector-data e)) ,tag-vector)])
,(make-begin
`((mset! ,tmp ,(- disp-vector-length tag-vector) ,e)
,tmp))))
(let ([tmp1 (unique-name 't)] [tmp2 (unique-name 't)])
`(let ([,tmp1 ,e])
(let ([,tmp2 (+ (alloc (+ ,disp-vector-data ,tmp1)) ,tag-vector)])
,(make-begin
`((mset! ,tmp2 ,(- disp-vector-length tag-vector) ,tmp1)
,tmp2))))))]))
(define (handle-pred-op x)
(match x
[(boolean? ,e) `(= (logand ,e ,mask-boolean) ,tag-boolean)]
[(fixnum? ,e) `(= (logand ,e ,mask-fixnum) ,tag-fixnum)]
[(pair? ,e) `(= (logand ,e ,mask-pair) ,tag-pair)]
[(vector? ,e) `(= (logand ,e ,mask-vector) ,tag-vector)]
[(null? ,e) `(= ,e ,$nil)]
[(eq? ,e1 ,e2) `(= ,e1 ,e2)]))
(define (Immediate imm)
(match imm
[#t $true]
[#f $false]
[() $nil]
[,x (guard (and (integer? x) (exact? x) (fixnum-range? x)))
(ash x shift-fixnum)]
[,x (error who "invalid Immediate ~s" x)]))
(define (Effect ef)
(match ef
[(nop) '(nop)]
[(begin ,[ef*] ... ,[ef])
(make-begin `(,ef* ... ,ef))]
[(if ,[Pred -> pred] ,[conseq] ,[alter])
`(if ,pred ,conseq ,alter)]
[(let ([,uvar* ,[Value -> val*]] ...) ,[ef])
`(let ([,uvar* ,val*] ...) ,ef)]
[(,prim ,[Value -> val*] ...) (guard (memq prim effect-prim))
(handle-primitive `(,prim ,val* ...))]
[(,[Value -> rator] ,[Value -> rand*] ...)
`(,rator ,rand* ...)]
[,x (error who "invalid Effect ~s" x)]))
(define (Pred pred)
(match pred
[(true) '(true)]
[(false) '(false)]
[(begin ,[Effect -> ef*] ... ,[pred])
(make-begin `(,ef* ... ,pred))]
[(if ,[pred] ,[conseq] ,[alter])
`(if ,pred ,conseq ,alter)]
[(let ([,uvar* ,[Value -> val*]] ...) ,[pred])
`(let ([,uvar* ,val*] ...) ,pred)]
[(,prim ,[Value -> val*] ...) (guard (memq prim pred-prim))
(handle-primitive `(,prim ,val* ...))]
[,x (error who "invalid Pred ~s" x)]))
(define (Value val)
(match val
[(begin ,[Effect -> ef*] ... ,[val])
(make-begin `(,ef* ... ,val))]
[(if ,[Pred -> pred] ,[conseq] ,[alter])
`(if ,pred ,conseq ,alter)]
[(let ([,uvar* ,[val*]] ...) ,[val])
`(let ([,uvar* ,val*] ...) ,val)]
[(quote ,[Immediate -> imm]) imm]
[(,prim ,[val*] ...) (guard (memq prim value-prim))
(handle-primitive `(,prim ,val* ...))]
[(,[rator] ,[rand*] ...) `(,rator ,rand* ...)]
[,label (guard (label? label)) label]
[,uvar (guard (uvar? uvar)) uvar]
[,x (error who "invalid Value ~s" x)]))
(lambda (x)
(match x
[(letrec ([,label* (lambda (,fml** ...) ,[Value -> val*])] ...) ,[Value -> val])
`(letrec ([,label* (lambda (,fml** ...) ,val*)] ...) ,val)]
[,x (error who "invalid Program ~s" x)])))
| false |
6fd35b075275626f52174c809cc77fad95961391
|
ac2a3544b88444eabf12b68a9bce08941cd62581
|
/tests/unit-tests/13-modules/prim_exception.scm
|
937f14a52dcd99d086bcf9fa2e5b97ebc513b305
|
[
"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 | 6,308 |
scm
|
prim_exception.scm
|
(include "#.scm")
(check-same-behavior ("" "##" "~~lib/_prim-exception#.scm")
;; Gambit
;;unimplemented;;abort
;;unimplemented;;cfun-conversion-exception-arguments
;;unimplemented;;cfun-conversion-exception-code
;;unimplemented;;cfun-conversion-exception-message
;;unimplemented;;cfun-conversion-exception-procedure
;;unimplemented;;cfun-conversion-exception?
;;unimplemented;;current-exception-handler
;;unimplemented;;datum-parsing-exception-kind
;;unimplemented;;datum-parsing-exception-parameters
;;unimplemented;;datum-parsing-exception-readenv
;;unimplemented;;datum-parsing-exception?
;;unimplemented;;divide-by-zero-exception-arguments
;;unimplemented;;divide-by-zero-exception-procedure
;;unimplemented;;divide-by-zero-exception?
;;unimplemented;;error
;;unimplemented;;error-exception-message
;;unimplemented;;error-exception-parameters
;;unimplemented;;error-exception?
;;unimplemented;;error-object-irritants
;;unimplemented;;error-object-message
;;unimplemented;;error-object?
;;unimplemented;;expression-parsing-exception-kind
;;unimplemented;;expression-parsing-exception-parameters
;;unimplemented;;expression-parsing-exception-source
;;unimplemented;;expression-parsing-exception?
;;unimplemented;;fixnum-overflow-exception-arguments
;;unimplemented;;fixnum-overflow-exception-procedure
;;unimplemented;;fixnum-overflow-exception?
;;unimplemented;;heap-overflow-exception?
;;unimplemented;;invalid-hash-number-exception-arguments
;;unimplemented;;invalid-hash-number-exception-procedure
;;unimplemented;;invalid-hash-number-exception?
;;unimplemented;;invalid-utf8-encoding-exception-arguments
;;unimplemented;;invalid-utf8-encoding-exception-procedure
;;unimplemented;;invalid-utf8-encoding-exception?
;;unimplemented;;keyword-expected-exception-arguments
;;unimplemented;;keyword-expected-exception-procedure
;;unimplemented;;keyword-expected-exception?
;;unimplemented;;length-mismatch-exception-arg-num
;;unimplemented;;length-mismatch-exception-arguments
;;unimplemented;;length-mismatch-exception-procedure
;;unimplemented;;length-mismatch-exception?
;;unimplemented;;module-not-found-exception-arguments
;;unimplemented;;module-not-found-exception-procedure
;;unimplemented;;module-not-found-exception?
;;unimplemented;;multiple-c-return-exception?
;;unimplemented;;no-such-file-or-directory-exception-arguments
;;unimplemented;;no-such-file-or-directory-exception-procedure
;;unimplemented;;no-such-file-or-directory-exception?
;;unimplemented;;noncontinuable-exception-reason
;;unimplemented;;noncontinuable-exception?
;;unimplemented;;nonempty-input-port-character-buffer-exception-arguments
;;unimplemented;;nonempty-input-port-character-buffer-exception-procedure
;;unimplemented;;nonempty-input-port-character-buffer-exception?
;;unimplemented;;nonprocedure-operator-exception-arguments
;;unimplemented;;nonprocedure-operator-exception-code
;;unimplemented;;nonprocedure-operator-exception-operator
;;unimplemented;;nonprocedure-operator-exception-rte
;;unimplemented;;nonprocedure-operator-exception?
;;unimplemented;;number-of-arguments-limit-exception-arguments
;;unimplemented;;number-of-arguments-limit-exception-procedure
;;unimplemented;;number-of-arguments-limit-exception?
;;unimplemented;;os-exception-arguments
;;unimplemented;;os-exception-code
;;unimplemented;;os-exception-message
;;unimplemented;;os-exception-procedure
;;unimplemented;;os-exception?
;;unimplemented;;primordial-exception-handler
(##with-exception-catcher ##list (lambda () (raise 123)))
;;unimplemented;;range-exception-arg-num
;;unimplemented;;range-exception-arguments
;;unimplemented;;range-exception-procedure
;;unimplemented;;range-exception?
;;unimplemented;;rpc-remote-error-exception-arguments
;;unimplemented;;rpc-remote-error-exception-message
;;unimplemented;;rpc-remote-error-exception-procedure
;;unimplemented;;rpc-remote-error-exception?
;;unimplemented;;scheduler-exception-reason
;;unimplemented;;scheduler-exception?
;;unimplemented;;sfun-conversion-exception-arguments
;;unimplemented;;sfun-conversion-exception-code
;;unimplemented;;sfun-conversion-exception-message
;;unimplemented;;sfun-conversion-exception-procedure
;;unimplemented;;sfun-conversion-exception?
;;unimplemented;;stack-overflow-exception?
;;unimplemented;;type-exception-arg-num
;;unimplemented;;type-exception-arguments
;;unimplemented;;type-exception-procedure
;;unimplemented;;type-exception-type-id
;;unimplemented;;type-exception?
;;unimplemented;;unbound-global-exception-code
;;unimplemented;;unbound-global-exception-rte
;;unimplemented;;unbound-global-exception-variable
;;unimplemented;;unbound-global-exception?
;;unimplemented;;unbound-key-exception-arguments
;;unimplemented;;unbound-key-exception-procedure
;;unimplemented;;unbound-key-exception?
;;unimplemented;;unbound-os-environment-variable-exception-arguments
;;unimplemented;;unbound-os-environment-variable-exception-procedure
;;unimplemented;;unbound-os-environment-variable-exception?
;;unimplemented;;unbound-serial-number-exception-arguments
;;unimplemented;;unbound-serial-number-exception-procedure
;;unimplemented;;unbound-serial-number-exception?
;;unimplemented;;uncaught-exception-arguments
;;unimplemented;;uncaught-exception-procedure
;;unimplemented;;uncaught-exception-reason
;;unimplemented;;uncaught-exception?
;;unimplemented;;unknown-keyword-argument-exception-arguments
;;unimplemented;;unknown-keyword-argument-exception-procedure
;;unimplemented;;unknown-keyword-argument-exception?
;;unimplemented;;unterminated-process-exception-arguments
;;unimplemented;;unterminated-process-exception-procedure
;;unimplemented;;unterminated-process-exception?
(with-exception-catcher ##list (lambda () (##raise 123)))
(with-exception-handler ##list (lambda () (##cons 1 (##raise 123))))
;;unimplemented;;with-exception-catcher
;;unimplemented;;with-exception-handler
;;unimplemented;;wrong-number-of-arguments-exception-arguments
;;unimplemented;;wrong-number-of-arguments-exception-procedure
;;unimplemented;;wrong-number-of-arguments-exception?
;;unimplemented;;wrong-number-of-values-exception-code
;;unimplemented;;wrong-number-of-values-exception-rte
;;unimplemented;;wrong-number-of-values-exception-vals
;;unimplemented;;wrong-number-of-values-exception?
;;unimplemented;;wrong-processor-c-return-exception?
)
| false |
27f6bb910a53b628b06aafb983fda87345fcb1db
|
736e7201d8133f7b5262bbe3f313441c70367a3d
|
/misc/internal/windows/TeXmacs/progs/ice-9/getopt-long.scm
|
2bf3e921fe20ee6c8c7bb68cb0a7cc27eb616c26
|
[] |
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 | 25,462 |
scm
|
getopt-long.scm
|
;;; Author: Russ McManus
;;; $Id$
;;;
;;; Copyright (C) 1998 FSF
;;;
;;; 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 of the License, 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 program; if not, write to the Free Software
;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
;;;
;;; This module implements some complex command line option parsing, in
;;; the spirit of the GNU C library function 'getopt_long'. Both long
;;; and short options are supported.
;;;
;;; The theory is that people should be able to constrain the set of
;;; options they want to process using a grammar, rather than some arbitrary
;;; structure. The grammar makes the option descriptions easy to read.
;;;
;;; getopt-long is a function for parsing command-line arguments in a
;;; manner consistent with other GNU programs.
;;; (getopt-long ARGS GRAMMAR)
;;; Parse the arguments ARGS according to the argument list grammar GRAMMAR.
;;;
;;; ARGS should be a list of strings. Its first element should be the
;;; name of the program; subsequent elements should be the arguments
;;; that were passed to the program on the command line. The
;;; `program-arguments' procedure returns a list of this form.
;;;
;;; GRAMMAR is a list of the form:
;;; ((OPTION (PROPERTY VALUE) ...) ...)
;;;
;;; Each OPTION should be a symbol. `getopt-long' will accept a
;;; command-line option named `--OPTION'.
;;; Each option can have the following (PROPERTY VALUE) pairs:
;;;
;;; (single-char CHAR) --- Accept `-CHAR' as a single-character
;;; equivalent to `--OPTION'. This is how to specify traditional
;;; Unix-style flags.
;;; (required? BOOL) --- If BOOL is true, the option is required.
;;; getopt-long will raise an error if it is not found in ARGS.
;;; (value BOOL) --- If BOOL is #t, the option accepts a value; if
;;; it is #f, it does not; and if it is the symbol
;;; `optional', the option may appear in ARGS with or
;;; without a value.
;;; (predicate FUNC) --- If the option accepts a value (i.e. you
;;; specified `(value #t)' for this option), then getopt
;;; will apply FUNC to the value, and throw an exception
;;; if it returns #f. FUNC should be a procedure which
;;; accepts a string and returns a boolean value; you may
;;; need to use quasiquotes to get it into GRAMMAR.
;;;
;;; The (PROPERTY VALUE) pairs may occur in any order, but each
;;; property may occur only once. By default, options do not have
;;; single-character equivalents, are not required, and do not take
;;; values.
;;;
;;; In ARGS, single-character options may be combined, in the usual
;;; Unix fashion: ("-x" "-y") is equivalent to ("-xy"). If an option
;;; accepts values, then it must be the last option in the
;;; combination; the value is the next argument. So, for example, using
;;; the following grammar:
;;; ((apples (single-char #\a))
;;; (blimps (single-char #\b) (value #t))
;;; (catalexis (single-char #\c) (value #t)))
;;; the following argument lists would be acceptable:
;;; ("-a" "-b" "bang" "-c" "couth") ("bang" and "couth" are the values
;;; for "blimps" and "catalexis")
;;; ("-ab" "bang" "-c" "couth") (same)
;;; ("-ac" "couth" "-b" "bang") (same)
;;; ("-abc" "couth" "bang") (an error, since `-b' is not the
;;; last option in its combination)
;;;
;;; If an option's value is optional, then `getopt-long' decides
;;; whether it has a value by looking at what follows it in ARGS. If
;;; the next element is a string, and it does not appear to be an
;;; option itself, then that string is the option's value.
;;;
;;; The value of a long option can appear as the next element in ARGS,
;;; or it can follow the option name, separated by an `=' character.
;;; Thus, using the same grammar as above, the following argument lists
;;; are equivalent:
;;; ("--apples" "Braeburn" "--blimps" "Goodyear")
;;; ("--apples=Braeburn" "--blimps" "Goodyear")
;;; ("--blimps" "Goodyear" "--apples=Braeburn")
;;;
;;; If the option "--" appears in ARGS, argument parsing stops there;
;;; subsequent arguments are returned as ordinary arguments, even if
;;; they resemble options. So, in the argument list:
;;; ("--apples" "Granny Smith" "--" "--blimp" "Goodyear")
;;; `getopt-long' will recognize the `apples' option as having the
;;; value "Granny Smith", but it will not recognize the `blimp'
;;; option; it will return the strings "--blimp" and "Goodyear" as
;;; ordinary argument strings.
;;;
;;; The `getopt-long' function returns the parsed argument list as an
;;; assocation list, mapping option names --- the symbols from GRAMMAR
;;; --- onto their values, or #t if the option does not accept a value.
;;; Unused options do not appear in the alist.
;;;
;;; All arguments that are not the value of any option are returned
;;; as a list, associated with the empty list.
;;;
;;; `getopt-long' throws an exception if:
;;; - it finds an unrecognized option in ARGS
;;; - a required option is omitted
;;; - an option that requires an argument doesn't get one
;;; - an option that doesn't accept an argument does get one (this can
;;; only happen using the long option `--opt=value' syntax)
;;; - an option predicate fails
;;;
;;; So, for example:
;;;
;;; (define grammar
;;; `((lockfile-dir (required? #t)
;;; (value #t)
;;; (single-char #\k)
;;; (predicate ,file-is-directory?))
;;; (verbose (required? #f)
;;; (single-char #\v)
;;; (value #f))
;;; (x-includes (single-char #\x))
;;; (rnet-server (single-char #\y)
;;; (predicate ,string?))))
;;;
;;; (getopt-long '("my-prog" "-vk" "/tmp" "foo1" "--x-includes=/usr/include"
;;; "--rnet-server=lamprod" "--" "-fred" "foo2" "foo3")
;;; grammar)
;;; => ((() "foo1" "-fred" "foo2" "foo3")
;;; (rnet-server . "lamprod")
;;; (x-includes . "/usr/include")
;;; (lockfile-dir . "/tmp")
;;; (verbose . #t))
(define-module (ice-9 getopt-long)
:use-module (ice-9 common-list))
;;; end-header
;;; The code on this page was expanded by hand using the following code:
;;; (pretty-print
;;; (macroexpand
;;; '(define-record option-spec
;;; (name
;;; value
;;; value-required?
;;; single-char
;;; predicate-ls
;;; parse-ls))))
;;;
;;; This avoids the need to load slib for records.
(define slib:error error)
(begin (define
option-spec->name
(lambda
(obj)
(if (option-spec? obj)
(vector-ref obj 1)
(slib:error
(quote option-spec->name)
": bad record"
obj))))
(define
option-spec->value
(lambda
(obj)
(if (option-spec? obj)
(vector-ref obj 2)
(slib:error
(quote option-spec->value)
": bad record"
obj))))
(define
option-spec->value-required?
(lambda
(obj)
(if (option-spec? obj)
(vector-ref obj 3)
(slib:error
(quote option-spec->value-required?)
": bad record"
obj))))
(define
option-spec->single-char
(lambda
(obj)
(if (option-spec? obj)
(vector-ref obj 4)
(slib:error
(quote option-spec->single-char)
": bad record"
obj))))
(define
option-spec->predicate-ls
(lambda
(obj)
(if (option-spec? obj)
(vector-ref obj 5)
(slib:error
(quote option-spec->predicate-ls)
": bad record"
obj))))
(define
option-spec->parse-ls
(lambda
(obj)
(if (option-spec? obj)
(vector-ref obj 6)
(slib:error
(quote option-spec->parse-ls)
": bad record"
obj))))
(define
set-option-spec-name!
(lambda
(obj val)
(if (option-spec? obj)
(vector-set! obj 1 val)
(slib:error
(quote set-option-spec-name!)
": bad record"
obj))))
(define
set-option-spec-value!
(lambda
(obj val)
(if (option-spec? obj)
(vector-set! obj 2 val)
(slib:error
(quote set-option-spec-value!)
": bad record"
obj))))
(define
set-option-spec-value-required?!
(lambda
(obj val)
(if (option-spec? obj)
(vector-set! obj 3 val)
(slib:error
(quote set-option-spec-value-required?!)
": bad record"
obj))))
(define
set-option-spec-single-char!
(lambda
(obj val)
(if (option-spec? obj)
(vector-set! obj 4 val)
(slib:error
(quote set-option-spec-single-char!)
": bad record"
obj))))
(define
set-option-spec-predicate-ls!
(lambda
(obj val)
(if (option-spec? obj)
(vector-set! obj 5 val)
(slib:error
(quote set-option-spec-predicate-ls!)
": bad record"
obj))))
(define
set-option-spec-parse-ls!
(lambda
(obj val)
(if (option-spec? obj)
(vector-set! obj 6 val)
(slib:error
(quote set-option-spec-parse-ls!)
": bad record"
obj))))
(define
option-spec?
(lambda
(obj)
(and (vector? obj)
(= (vector-length obj) 7)
(eq? (vector-ref obj 0) (quote option-spec)))))
(define
make-option-spec
(lambda
(option-spec->name
option-spec->value
option-spec->value-required?
option-spec->single-char
option-spec->predicate-ls
option-spec->parse-ls)
(vector
(quote option-spec)
option-spec->name
option-spec->value
option-spec->value-required?
option-spec->single-char
option-spec->predicate-ls
option-spec->parse-ls))))
;;;
;;; parse functions go on this page.
;;;
(define make-user-predicate
(lambda (pred)
(lambda (spec)
(let ((val (option-spec->value spec)))
(if (and val
(pred val)) #t
(error "option predicate failed:" (option-spec->name spec)))))))
(define make-not-allowed-value-fn
(lambda ()
(lambda (spec)
(let ((val (option-spec->value spec)))
(if (not (or (eq? val #t)
(eq? val #f)))
(let ((name (option-spec->name spec)))
(error "option does not support argument:" name)))))))
(define make-option-required-predicate
(lambda ()
(lambda (spec)
(let ((val (option-spec->value spec)))
(if (not val)
(let ((name (option-spec->name spec)))
(error "option must be specified:" name)))))))
(define make-option-value-predicate
(lambda (predicate)
(lambda (spec)
(let ((val (option-spec->value spec)))
(if (not (predicate val))
(let ((name (option-spec->name spec)))
(error "Bad option value:" name val)))))))
(define make-required-value-fn
(lambda ()
(lambda (spec)
(let ((val (option-spec->value spec)))
(if (eq? val #t)
(let ((name (option-spec->name spec)))
(error "option must be specified with argument:" name)))))))
(define single-char-value?
(lambda (val)
(char? val)))
(define (parse-option-spec desc)
(letrec ((parse-iter
(lambda (spec)
(let ((parse-ls (option-spec->parse-ls spec)))
(if (null? parse-ls)
spec
(let ((ls (car parse-ls)))
(if (or (not (list? ls))
(not (= (length ls) 2)))
(error "Bad option specification:" ls))
(let ((key (car ls))
(val (cadr ls)))
(cond ((and (eq? key 'required?) val)
;; required values are implemented as a predicate
(parse-iter (make-option-spec (option-spec->name spec)
(option-spec->value spec)
(option-spec->value-required? spec)
(option-spec->single-char spec)
(cons (make-option-required-predicate)
(option-spec->predicate-ls spec))
(cdr parse-ls))))
;; if the value is not required, then don't add a predicate,
((eq? key 'required?)
(parse-iter (make-option-spec (option-spec->name spec)
(option-spec->value spec)
(option-spec->value-required? spec)
(option-spec->single-char spec)
(option-spec->predicate-ls spec)
(cdr parse-ls))))
;; handle value specification
((eq? key 'value)
(cond ((eq? val #t)
;; when value is required, add a predicate to that effect
;; and record the fact in value-required? field.
(parse-iter (make-option-spec (option-spec->name spec)
(option-spec->value spec)
#t
(option-spec->single-char spec)
(cons (make-required-value-fn)
(option-spec->predicate-ls spec))
(cdr parse-ls))))
((eq? val #f)
;; when the value is not allowed, add a predicate to that effect.
;; one can detect that a value is not supplied by checking the option
;; value against #f.
(parse-iter (make-option-spec (option-spec->name spec)
(option-spec->value spec)
#f
(option-spec->single-char spec)
(cons (make-not-allowed-value-fn)
(option-spec->predicate-ls spec))
(cdr parse-ls))))
((eq? val 'optional)
;; for optional values, don't add a predicate. do, however
;; put the value 'optional in the value-required? field. this
;; setting checks whether optional values are 'greedy'. set
;; to #f to make optional value clauses 'non-greedy'.
(parse-iter (make-option-spec (option-spec->name spec)
(option-spec->value spec)
'optional
(option-spec->single-char spec)
(option-spec->predicate-ls spec)
(cdr parse-ls))))
(#t
;; error case
(error "Bad value specification for option:" (cons key val)))))
;; specify which single char is defined for this option.
((eq? key 'single-char)
(if (not (single-char-value? val))
(error "Not a single-char-value:" val " for option:" key)
(parse-iter (make-option-spec (option-spec->name spec)
(option-spec->value spec)
(option-spec->value-required? spec)
val
(option-spec->predicate-ls spec)
(cdr parse-ls)))))
((eq? key 'predicate)
(if (procedure? val)
(parse-iter (make-option-spec (option-spec->name spec)
(option-spec->value spec)
(option-spec->value-required? spec)
(option-spec->single-char spec)
(cons (make-user-predicate val)
(option-spec->predicate-ls spec))
(cdr parse-ls)))
(error "Bad predicate specified for option:" (cons key val))))))))))))
(if (or (not (pair? desc))
(string? (car desc)))
(error "Bad option specification:" desc))
(parse-iter (make-option-spec (car desc)
#f
#f
#f
'()
(cdr desc)))))
;;;
;;;
;;;
(define (split-arg-list argument-list)
"Given an ARGUMENT-LIST, decide which part to process for options.
Everything before an arg of \"--\" is fair game, everything after it
should not be processed. The \"--\" is discarded. A cons pair is
returned whose car is the list to process for options, and whose cdr
is the list to not process."
(let loop ((process-ls '())
(not-process-ls argument-list))
(cond ((null? not-process-ls)
(cons (reverse process-ls) '()))
((string=? "--" (car not-process-ls))
(cons (reverse process-ls) (cdr not-process-ls)))
(#t
(loop (cons (car not-process-ls) process-ls)
(cdr not-process-ls))))))
(define short-opt-rx (make-regexp "^-([a-zA-Z]+)"))
(define long-opt-no-value-rx (make-regexp "^--([^=]+)$"))
(define long-opt-with-value-rx (make-regexp "^--([^=]+)=(.*)"))
(define (single-char-expander specifications opt-ls)
"Expand single letter options that are mushed together."
(let ((response #f))
(define (is-short-opt? str)
(set! response (regexp-exec short-opt-rx str))
response)
(define (iter opt-ls ret-ls)
(cond ((null? opt-ls)
(reverse ret-ls))
((is-short-opt? (car opt-ls))
(let* ((orig-str (car opt-ls))
(match-pair (vector-ref response 2))
(match-str (substring orig-str (car match-pair) (cdr match-pair))))
(if (= (string-length match-str) 1)
(iter (cdr opt-ls)
(cons (string-append "-" match-str) ret-ls))
(iter (cons (string-append "-" (substring match-str 1)) (cdr opt-ls))
(cons (string-append "-" (substring match-str 0 1)) ret-ls)))))
(#t (iter (cdr opt-ls)
(cons (car opt-ls) ret-ls)))))
(iter opt-ls '())))
(define (process-short-option specifications argument-ls alist)
"Process a single short option that appears at the front of the ARGUMENT-LS,
according to SPECIFICATIONS. Returns #f is there is no such argument. Otherwise
returns a pair whose car is the list of remaining arguments, and whose cdr is a
new association list, constructed by adding a pair to the supplied ALIST.
The pair on the front of the returned association list describes the option
found at the head of ARGUMENT-LS. The way this routine currently works, an
option that never takes a value that is followed by a non option will cause
an error, which is probably a bug. To fix the bug the option specification
needs to record whether the option ever can take a value."
(define (short-option->char option)
(string-ref option 1))
(define (is-short-option? option)
(regexp-exec short-opt-rx option))
(define (is-long-option? option)
(or (regexp-exec long-opt-with-value-rx option)
(regexp-exec long-opt-no-value-rx option)))
(define (find-matching-spec option)
(let ((key (short-option->char option)))
(find-if (lambda (spec) (eq? key (option-spec->single-char spec))) specifications)))
(let ((option (car argument-ls)))
(if (is-short-option? option)
(let ((spec (find-matching-spec option)))
(if spec
(let* ((next-value (if (null? (cdr argument-ls)) #f (cadr argument-ls)))
(option-value (if (and next-value
(not (is-short-option? next-value))
(not (is-long-option? next-value))
(option-spec->value-required? spec))
next-value
#t))
(new-alist (cons (cons (option-spec->name spec) option-value) alist)))
(cons (if (eq? option-value #t)
(cdr argument-ls) ; there was one value specified, skip just one
(cddr argument-ls)) ; there must have been a value specified, skip two
new-alist))
(error "No such option:" option)))
#f)))
(define (process-long-option specifications argument-ls alist)
(define (find-matching-spec key)
(find-if (lambda (spec) (eq? key (option-spec->name spec))) specifications))
(define (split-long-option option)
;; returns a pair whose car is a symbol naming the option, cdr is
;; the option value. as a special case, if the option value is
;; #f, then the caller should use the next item in argument-ls as
;; the option value.
(let ((resp (regexp-exec long-opt-no-value-rx option)))
(if resp
;; Aha, we've found a long option without an equal sign.
;; Maybe we need to grab a value from argument-ls. To find
;; out we need to refer to the option-spec.
(let* ((key-pair (vector-ref resp 2))
(key (string->symbol (substring option (car key-pair) (cdr key-pair))))
(spec (find-matching-spec key)))
(cons key (if (option-spec->value-required? spec) #f #t)))
(let ((resp (regexp-exec long-opt-with-value-rx option)))
;; Aha, we've found a long option with an equal sign. The
;; option value is simply the value to the right of the
;; equal sign.
(if resp
(let* ((key-pair (vector-ref resp 2))
(key (string->symbol (substring option (car key-pair) (cdr key-pair))))
(value-pair (vector-ref resp 3))
(value (substring option (car value-pair) (cdr value-pair))))
(cons key value))
#f)))))
(let* ((option (car argument-ls))
(pair (split-long-option option)))
(cond ((and pair (eq? (cdr pair) #f))
(if (null? (cdr argument-ls))
(error "Not enough options.")
(cons (cddr argument-ls)
(cons (cons (car pair) (cadr argument-ls)) alist))))
(pair
(cons (cdr argument-ls) (cons pair alist)))
(else #f))))
(define (process-options specifications argument-ls)
(define (iter argument-ls alist rest-ls)
(if (null? argument-ls)
(cons alist (reverse rest-ls))
(let ((pair (process-short-option specifications argument-ls alist)))
(if pair
(let ((argument-ls (car pair))
(alist (cdr pair)))
(iter argument-ls alist rest-ls))
(let ((pair (process-long-option specifications argument-ls alist)))
(if pair
(let ((argument-ls (car pair))
(alist (cdr pair)))
(iter argument-ls alist rest-ls))
(iter (cdr argument-ls)
alist
(cons (car argument-ls) rest-ls))))))))
(iter argument-ls '() '()))
(define (getopt-long program-arguments option-desc-list)
"Process options, handling both long and short options, similar to
the glibc function 'getopt_long'. PROGRAM-ARGUMENTS should be a value
similar to what (program-arguments) returns. OPTION-DESC-LIST is a
list of option descriptions. Each option description must satisfy the
following grammar:
<option-spec> :: (<name> . <attribute-ls>)
<attribute-ls> :: (<attribute> . <attribute-ls>)
| ()
<attribute> :: <required-attribute>
| <arg-required-attribute>
| <single-char-attribute>
| <predicate-attribute>
| <value-attribute>
<required-attribute> :: (required? <boolean>)
<single-char-attribute> :: (single-char <char>)
<value-attribute> :: (value #t)
(value #f)
(value optional)
<predicate-attribute> :: (predicate <1-ary-function>)
The procedure returns an alist of option names and values. Each
option name is a symbol. The option value will be '#t' if no value
was specified. There is a special item in the returned alist with a
key of the empty list, (): the list of arguments that are not options
or option values.
By default, options are not required, and option values are not
required. By default, single character equivalents are not supported;
if you want to allow the user to use single character options, you need
to add a 'single-char' clause to the option description."
(let* ((specifications (map parse-option-spec option-desc-list))
(pair (split-arg-list (cdr program-arguments)))
(split-ls (single-char-expander specifications (car pair)))
(non-split-ls (cdr pair)))
(let* ((opt-pair (process-options specifications split-ls))
(alist (car opt-pair))
(rest-ls (append (cdr opt-pair) non-split-ls)))
;; loop through the returned alist, and set the values into the specifications
(for-each (lambda (pair)
(let* ((key (car pair))
(val (cdr pair))
(spec (find-if (lambda (spec) (eq? key (option-spec->name spec)))
specifications)))
(if spec (set-option-spec-value! spec val))))
alist)
;; now fire all the predicates
(for-each (lambda (spec)
(let ((predicate-ls (option-spec->predicate-ls spec)))
(for-each (lambda (predicate)
(predicate spec))
predicate-ls)))
specifications)
(cons (cons '() rest-ls) alist))))
(define (option-ref options key default)
"Look for an option value in OPTIONS using KEY. If no such value is
found, return DEFAULT."
(let ((pair (assq key options)))
(if pair
(cdr pair)
default)))
(export option-ref)
(export getopt-long)
| false |
9c037bd0a878f51fe095967051a33541dc81b7c9
|
ac2a3544b88444eabf12b68a9bce08941cd62581
|
/tests/unit-tests/03-number/cos.scm
|
30e26f1ec33bf4b635a316f92176d8db67252fdc
|
[
"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 | 144 |
scm
|
cos.scm
|
(include "#.scm")
;;; Test special values
(check-eqv? (cos 0) 1)
;;; Test exceptions
(check-tail-exn type-exception? (lambda () (cos 'a)))
| false |
b5bcb809f3e1dbf396b5d2414838a162919091b7
|
0021f53aa702f11464522ed4dff16b0f1292576e
|
/scm/p15-2.scm
|
6027db662cc18f40ae02ee898361ef3fb30fde6a
|
[] |
no_license
|
mtsuyugu/euler
|
fe40dffbab1e45a4a2a297c34b729fb567b2dbf2
|
4b17df3916f1368eff44d6bc36202de4dea3baf7
|
refs/heads/master
| 2021-01-18T14:10:49.908612 | 2016-10-07T15:35:45 | 2016-10-07T15:35:45 | 3,059,459 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 105 |
scm
|
p15-2.scm
|
(define (c n m)
(if (= m 0) 1
(* (/ (- (+ n 1) m) m)
(c n (- m 1)))))
(print (c 40 20))
| false |
cf8b442ec5cd30dda5bbceeb280deb80977547d0
|
a416300cfff2efcf5749349330566b7db70cf4a6
|
/label-model.scm
|
0f782e6b671c9fe9e72f70459d654cc87d9a8141
|
[] |
no_license
|
lukaspj/LaBSec-Project
|
c4e24ba395a990c8facd24d8a4cb5780bfa69e20
|
47f37726f7531080b14f4039276968e942b34c02
|
refs/heads/master
| 2020-04-02T03:07:49.662099 | 2016-06-13T10:04:41 | 2016-06-13T10:04:41 | 58,653,567 | 0 | 0 | null | 2016-06-12T11:54:08 | 2016-05-12T15:26:05 |
Scheme
|
UTF-8
|
Scheme
| false | false | 10,407 |
scm
|
label-model.scm
|
;(define check-integrity-flows-to
; (trace-lambda check-integrity (l1 l2)
; (let ([readers1 (cadr l1)]
; [readers2 (cadr l2)])
; #t)))
;(define check-confidentiality-flows-to
; (trace-lambda check-confidentiality (l1 l2)
; (let ([writers1 (caddr l1)]
; [writers2 (caddr l2)])
; #t)))
;; Label Bnf
;; <Label> ::= (<Label>*)
;; | <value-label>
;; | <lambda-label>
;; <value-label> ::= (label integrity confidentiality)
;; <lambda-label> ::= (lambda-label <value-label> (<value-label>*) <value-label>)
;; | (lambda-label <label-var> (<value-label>*) <value-label>)
;; <label-var> ::= (label-var <symbol>)
(define is-given-type?
(lambda (v length type)
(and (proper-list-of-given-length? v length)
(equal? (car v) type))))
(define is-given-variadic-type?
(lambda (v length type)
(and (proper-list-longer-than-given-length? v length)
(equal? (car v) type))))
(define is-value-label?
(lambda (v)
(is-given-variadic-type? v 1 'label)))
(define is-lambda-label?
(lambda (v)
(is-given-type? v 4 'lambda-label)))
(define value-label-integrity
(lambda (v)
(list-ref v 1)))
(define value-label-confidentiality
(lambda (v)
(list-ref v 2)))
(define lambda-label-begin
(lambda (v)
(list-ref v 1)))
(define lambda-label-params
(lambda (v)
(list-ref v 2)))
(define lambda-label-end
(lambda (v)
(list-ref v 3)))
(define check-label
(lambda (v)
(cond
[(is-value-label? v)
(check-value-label (value-label-integrity v)
(value-label-confidentiality v))]
[(is-lambda-label? v)
(check-lambda-label (lambda-label-begin v)
(lambda-label-params v)
(lambda-label-end v))]
[(pair? v)
(if (null? (cdr v))
(check-label (car v))
(and (check-label (car v))
(check-label (cdr v))))]
[else
(printf "Not a recognized label: ~s~n" v)])))
(define check-value-label
(lambda (integrity confidentiality)
(and (or (null? integrity)
(and (pair? integrity)
(equal? (car integrity) 'integrity)
(number? (cdr integrity))))
(or (null? confidentiality)
(and (pair? confidentiality)
(equal? (car confidentiality) 'confidentiality)
(number? (cdr confidentiality)))))))
(define check-lambda-label
(lambda (begin-label params end-label)
(and (check-label begin-label)
(check-labels params)
(check-label end-label))))
(define check-labels
(lambda (vs)
(if (null? vs)
#t
(and (check-label (car vs))
(check-labels (cdr vs))))))
(define get-label-attribute
(lambda (l a)
(cond
[(null? l)
'()]
[(and (pair? (car l))
(equal? (caar l) a))
(cdar l)]
[else
(get-label-attribute (cdr l) a)])))
(define get-label-confidentiality
(lambda (l)
(get-label-attribute l 'confidentiality)))
(define get-label-integrity
(lambda (l)
(get-label-attribute l 'integrity)))
;;;;;;;;;;;;
;;; Flows and joins
;;;;;;;;;;;;
;;; Centralized-One-dimensional label model
(define check-integrity-flows-to
(lambda (l1 l2)
(let ([integrity1 (get-label-integrity l1)]
[integrity2 (get-label-integrity l2)])
(if (null? integrity1)
#t
(and (not (null? integrity2))
(>= integrity1 integrity2))))))
(define check-confidentiality-flows-to
(lambda (l1 l2)
(let ([confidentiality1 (get-label-confidentiality l1)]
[confidentiality2 (get-label-confidentiality l2)])
(if (null? confidentiality1)
(null? confidentiality2)
(or (null? confidentiality2)
(<= confidentiality1 confidentiality2))))))
(define join-integrity
(lambda (l1 l2)
(let ([integrity1 (get-label-integrity l1)]
[integrity2 (get-label-integrity l2)])
(if (null? integrity1)
(if (null? integrity2)
'()
(cons 'integrity integrity2))
(if (null? integrity2)
(cons 'integrity integrity1)
(cons 'integrity
(min integrity1 integrity2)))))))
(define join-confidentiality
(lambda (l1 l2)
(let ([confidentiality1 (get-label-confidentiality l1)]
[confidentiality2 (get-label-confidentiality l2)])
(if (or (null? confidentiality1)
(null? confidentiality2))
'()
(cons 'confidentiality
(max confidentiality1 confidentiality2))))))
(define label-join
(lambda (l1 l2)
(if (is-lambda-label? l1)
(if (is-lambda-label? l2)
(list l1 l2)
`(lambda-label ,(lambda-label-begin l1)
,(lambda-label-params l1)
,(label-join (lambda-label-end l1) l2)))
(if (is-lambda-label? l2)
`(lambda-label ,(lambda-label-begin l2)
,(lambda-label-params l2)
,(label-join (lambda-label-end l2) l1))
`(label ,(join-integrity l1 l2) ,(join-confidentiality l1 l2))))))
(define label-flows-to
(lambda (l1 l2)
(if (and (is-value-label? l1)
(is-value-label? l2))
(and (check-integrity-flows-to l1 l2)
(check-confidentiality-flows-to l1 l2))
(errorf 'label-flows-to
"Both labels is not value labels ~s, ~s~n"
l1 l2))))
(define flow-anywhere-label
'(label () (confidentiality . 0)))
(define make-lambda-label
(lambda (b formals e)
`(lambda-label ,b
,formals
,e)))
;;;;;;;;;;;;;;;;;;;
;;; Predifined env
;;;;;;;;;;;;;;;;;;;
(define labels_of_predefined_functions
(list
'(+ . predefined)
'(- . predefined)
'(* . predefined)
'(/ . predefined)
'(= . predefined)
'(modulo . predefined)
'(mod . predefined)
'(random . predefined)
'(floor . predefined)
'(sqrt . predefined)
'(list . predefined)
'(car . predefined)
'(cdr . predefined)
'(cadr . predefined)
'(cons . predefined)
'(number->string . predefined)
'(string->list . predefined)
'(string-length . predefined)
'(null? . predefined)
'(equal? . predefined)
'(printf lambda-label (label () (confidentiality . 0))
((label (integrity . 0) (confidentiality . 0))
(label (integrity . 0) (confidentiality . 0))
(label (integrity . 0) (confidentiality . 0))
(label (integrity . 0) (confidentiality . 0))
(label (integrity . 0) (confidentiality . 0))
(label (integrity . 0) (confidentiality . 0))
(label (integrity . 0) (confidentiality . 0))
(label (integrity . 0) (confidentiality . 0))
(label (integrity . 0) (confidentiality . 0))
(label (integrity . 0) (confidentiality . 0))
(label (integrity . 0) (confidentiality . 0)))
(label () (confidentiality . 0)))
;; '(list lambda-label (label () (confidentiality . 0))
;; ((label (integrity . 0) (confidentiality . 0))
;; (label (integrity . 0) (confidentiality . 0))
;; (label (integrity . 0) (confidentiality . 0))
;; (label (integrity . 0) (confidentiality . 0))
;; (label (integrity . 0) (confidentiality . 0))
;; (label (integrity . 0) (confidentiality . 0))
;; (label (integrity . 0) (confidentiality . 0))
;; (label (integrity . 0) (confidentiality . 0))
;; (label (integrity . 0) (confidentiality . 0))
;; (label (integrity . 0) (confidentiality . 0))
;; (label (integrity . 0) (confidentiality . 0)))
;; (label () (confidentiality . 0)))
))
;;;;;;;;;;;;;;;;;;;
;;; Unit test
;;;;;;;;;;;;;;;;;;;
(define toptop
'(label () ()))
(define botbot
'(label (integrity . 0) (confidentiality . 0)))
(define topbot
'(label () (confidentiality . 0)))
(define bottop
'(label (integrity . 0) ()))
(define topone
'(label () (confidentiality . 1)))
(define onetop
'(label (integrity . 0) ()))
(define toptwo
'(label () (confidentiality . 2)))
(define twotop
'(label (integrity . 2) ()))
(define test-flows-to-equal
(lambda (p1 p2 expected)
(if (equal? (label-flows-to (eval p1) (eval p2)) expected)
#t
(errorf
'test-flows-to-equal
"~s flows to ~s was expected to be ~s~n"
p1 p2 expected))))
(define test-flows-to
(and (test-flows-to-equal 'toptop 'botbot #f)
(test-flows-to-equal 'toptop 'topbot #f)
(test-flows-to-equal 'toptop 'bottop #t)
(test-flows-to-equal 'toptop 'toptop #t)
(test-flows-to-equal 'botbot 'botbot #t)
(test-flows-to-equal 'botbot 'topbot #f)
(test-flows-to-equal 'botbot 'bottop #t)
(test-flows-to-equal 'botbot 'toptop #f)
(test-flows-to-equal 'bottop 'botbot #f)
(test-flows-to-equal 'bottop 'topbot #f)
(test-flows-to-equal 'bottop 'bottop #t)
(test-flows-to-equal 'bottop 'toptop #f)
(test-flows-to-equal 'topbot 'botbot #t)
(test-flows-to-equal 'topbot 'topbot #t)
(test-flows-to-equal 'topbot 'bottop #t)
(test-flows-to-equal 'topbot 'toptop #t)
(test-flows-to-equal 'topone 'botbot #f)
(test-flows-to-equal 'topone 'topbot #f)
(test-flows-to-equal 'topone 'bottop #t)
(test-flows-to-equal 'topone 'toptop #t)
(test-flows-to-equal 'onetop 'botbot #f)
(test-flows-to-equal 'onetop 'topbot #f)
(test-flows-to-equal 'onetop 'bottop #t)
(test-flows-to-equal 'onetop 'toptop #f)
(test-flows-to-equal 'onetop 'twotop #f)
(test-flows-to-equal 'topone 'toptwo #t)
(test-flows-to-equal 'twotop 'onetop #t)
(test-flows-to-equal 'toptwo 'topone #f)))
(define test-join-equal
(lambda (p1 p2 expected)
(let ([result (label-join (eval p1) (eval p2))])
(if (equal? result (eval expected))
#t
(errorf
'test-join-equal
"~s join ~s was expected to be ~s but was ~s ~n"
p1 p2 expected result)))))
(define test-join
(and (test-join-equal 'toptop 'botbot 'bottop)
(test-join-equal 'botbot 'toptop 'bottop)
(test-join-equal 'topbot 'toptop 'toptop)
(test-join-equal 'topbot 'topbot 'topbot)
(test-join-equal 'toptop ''(label) 'toptop)
(test-join-equal 'topbot ''(label (confidentiality . 0)) 'topbot)))
| false |
74be14d7c8c0dfacb34f6b147d573d1b8a90093a
|
e82d67e647096e56cb6bf1daef08552429284737
|
/ex1-32.scm
|
e793e50234be99b1d511dea5b2a2b08160f66024
|
[] |
no_license
|
ashishmax31/sicp-exercises
|
97dfe101dd5c91208763dcc4eaac2c17977d1dc1
|
097f76a5637ccb1fba055839d389541a1a103e0f
|
refs/heads/master
| 2020-03-28T11:16:28.197294 | 2019-06-30T20:25:18 | 2019-06-30T20:25:18 | 148,195,859 | 6 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 741 |
scm
|
ex1-32.scm
|
; Linear recursive process
(define (accumulate combiner null-value term a next b)
(if (> a b)
null-value
(combiner (term a) (accumulate combiner null-value term (next a) next b))))
; Iterative process
(define (accumulate combiner null-value term a next b)
(define (accumulate-iter combiner term a next b acc)
(if (> a b)
acc
(accumulate-iter combiner term (next a) next b (combiner acc (term a)))))
(accumulate-iter combiner term a next b null-value))
(define (cube x)
(* x x x))
(define (next-item x)
(+ x 1))
; Sum of cubes from 1 to 10
(accumulate + 0 cube 1 next-item 10)
; Product of cubes from 1 to 10
(accumulate * 1 cube 1 next-item 10)
| false |
841bf7f9fcc6b17b148b27ea2dd3643e8fa49ca7
|
432924338995770f121e1e8f6283702653dd1369
|
/2/p2.63-test.scm
|
eb94743af3b896f543091b6e7f41f8e3b7994267
|
[] |
no_license
|
punchdrunker/sicp-reading
|
dfaa3c12edf14a7f02b3b5f4e3a0f61541582180
|
4bcec0aa7c514b4ba48e677cc54b41d72c816b44
|
refs/heads/master
| 2021-01-22T06:53:45.096593 | 2014-06-23T09:51:27 | 2014-06-23T09:51:27 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 798 |
scm
|
p2.63-test.scm
|
(load "./p2.63.scm")
(define mytree
(make-tree 4
(make-tree 2
(make-tree 1 '() '())
(make-tree 3 '() '()))
(make-tree 6
(make-tree 5 '() '())
(make-tree 7 '() '()))))
;(trace tree->list-1)
;(trace tree->list-2)
(test-start "問題2.63")
(test-section "tree->list-1")
(test* "(tree->list-1 mytree)" '(1 2 3 4 5 6 7) (tree->list-1 mytree))
(test-section "tree->list-2")
(test* "(tree->list-2 mytree)" '(1 2 3 4 5 6 7) (tree->list-2 mytree))
(test-end)
; a.
; 再帰と反復で異なるだけで、出力は同じだと思います
;
; b.
; あまり変わらないように見えるが、
; appendがある分、tree->list1の方がステップ数が増えるのでは?
| false |
f1e0c2783fa0c6bfde4eda82a9680cd9cc3cb335
|
df0ba5a0dea3929f29358805fe8dcf4f97d89969
|
/exercises/software-engineering/08/iterate.scm
|
386aa6f91c0580a17837bfffe62fd84b2db66222
|
[
"MIT"
] |
permissive
|
triffon/fp-2019-20
|
1c397e4f0bf521bf5397f465bd1cc532011e8cf1
|
a74dcde683538be031186cf18367993e70dc1a1c
|
refs/heads/master
| 2021-12-15T00:32:28.583751 | 2021-12-03T13:57:04 | 2021-12-03T13:57:04 | 210,043,805 | 14 | 31 |
MIT
| 2019-12-23T23:39:09 | 2019-09-21T19:41:41 |
Racket
|
UTF-8
|
Scheme
| false | false | 555 |
scm
|
iterate.scm
|
(load "./stream.scm")
(define (iterate f x)
(cons-stream x (iterate f (f x))))
(load "../testing/check.scm")
(define (identity x) x)
(define (square x) (* x x))
(check (stream->list (take-stream 5 (iterate identity 42)))
=> '(42 42 42 42 42))
(check (stream->list (take-stream 4 (iterate square 2))) => '(2 4 16 256))
(check (stream->list (take-stream 3 (iterate list 6))) => '(6 (6) ((6))))
(check (stream->list (take-stream 6 (iterate list '())))
=> '(() (()) ((())) (((()))) ((((())))) (((((())))))))
(check-report)
(check-reset!)
| false |
5c9d0603923413ad41f40ac60316d587ee08a20b
|
ae0d7be8827e8983c926f48a5304c897dc32bbdc
|
/nekoie/misc/jwhois.cgi
|
038de24ba7628ec463c2d6948019a26feeb04f30
|
[] |
no_license
|
ayamada/copy-of-svn.tir.jp
|
96c2176a0295f60928d4911ce3daee0439d0e0f4
|
101cd00d595ee7bb96348df54f49707295e9e263
|
refs/heads/master
| 2020-04-04T01:03:07.637225 | 2015-05-28T07:00:18 | 2015-05-28T07:00:18 | 1,085,533 | 3 | 2 | null | 2015-05-28T07:00:18 | 2010-11-16T15:56:30 |
Scheme
|
UTF-8
|
Scheme
| false | false | 8,183 |
cgi
|
jwhois.cgi
|
#!/home/nekoie/bin/gosh
;#!/usr/local/gauche/bin/gosh
;#!/usr/local/gauche/bin/speedygosh
;; sakura.tir.jp に設置するセッティングにしてある
(define-module jwhois.cgi
(use www.cgi)
(use rfc.http)
(use text.html-lite)
(use text.tree)
(use srfi-1)
(use srfi-13)
(use rfc.uri)
(use rfc.cookie)
(use util.list)
(use gauche.charconv)
(use gauche.process)
(export
))
(select-module jwhois.cgi)
(define *jwhois-path* "/home/nekoie/bin/jwhois")
(define *option-list* '())
(define-macro (define-option option)
(set! *option-list* (cons option *option-list*))
'(values))
(define-option "")
(define-option "-h whois.jprs.jp")
(define (main args)
(set! (port-buffering (current-error-port)) :line)
(cgi-main
(lambda (params)
(emit-content params))
:on-error (lambda (e)
(list
(cgi-header)
(html:pre
(html-escape-string
(call-with-output-string
(cut with-error-to-port <> (cut report-error e))))))))
0)
(define (sanitize-query query)
;; 許可する文字は、ドメイン名、ip、JPNIC HANDLE、で利用可能な文字のみ
;; また、ハイフンはじまりはjwhoisコマンドのオプションとして認識される為、
;; 許可しない
(regexp-replace #/^\-+/
(regexp-replace-all #/[^\w\.\/\-]/ query "")
""))
(define (emit-content params)
(let ((query (cgi-get-parameter "q"
params
:default ""
;; サニタイズする
:convert sanitize-query))
(option (cgi-get-parameter "o"
params
:default ""
;; 規定のオプションのみを有効とする
:convert (lambda (o)
(or
(find
(cut equal? o <>)
*option-list*)
"")))))
(list
(cgi-header :content-type "text/html; charset=EUC-JP"
:pragma "no-cache"
:cache-control "no-cache"
)
(html:html
(html:head
(html:title "jwhois.cgi")
)
(html:body :id "the-body"
(the-form query option)
(html:hr)
(the-result query option)
)))))
(define (javascript . scripts)
(html:script
:type "text/javascript"
(intersperse
"\n"
`("<!--"
,@scripts
"// -->"))))
(define (the-form query option)
(define (selected? value)
(if (equal? option value)
"selected"
#f))
(define (make-option value)
(html:option :value value :selected (selected? value) value))
(html:form
:action (self-url)
:method "get"
:target "_self"
:name "send"
(html:div
"$ jwhois "
(html:select :name "o" (map make-option (reverse *option-list*)))
" "
(html:input :type "text" :name "q" :value query)
(html:input :type "submit" ;:name "submit"
:id "post-submit" :value "enter")
)
;(javascript "self.document.send.q.focus();")
))
(define (option->list option)
(if (equal? "" option)
'()
(string-split option #/\s+/)))
(define (hes/sp str)
(regexp-replace-all
#/\s/
(html-escape-string str)
" "))
(define (the-result query option)
;; queryが空の場合は、説明文を出す
(if (equal? "" query)
(the-help)
(let1 cmd `(,*jwhois-path* ,@(option->list option) ,query)
(html:div
(html:tt
(intersperse
(html:br)
(map
hes/sp
(cmd->result cmd))))))))
(define (cmd->result cmd)
(call-with-input-process
cmd
(lambda (p)
(reverse
(let next ((result '())
(str (read-line p #t)))
(if (eof-object? str)
result
(next
(cons
(ces-convert str "*JP")
result)
(read-line p #t))))))))
(define (the-help)
(list
(html:p
(html:a
:href "http://d.hatena.ne.jp/ranekov/20110217/1297877823"
"explanation(japanese)"))
(html:div
(html:tt
(intersperse
(html:br)
(map hes/sp (process-output->string-list
`(,*jwhois-path* --version :encoding "*JP"))))))))
(define (append-params-to-url url params)
(if (null? params)
url
(receive (url-without-fragment fragment) (let1 m (#/(\#.*)/ url)
(if m
(values (m 'before) (m 1))
(values url "")))
(call-with-output-string
(lambda (p)
(letrec ((delimitee (if (#/\?/ url-without-fragment)
(lambda () "&")
(lambda ()
(set! delimitee (lambda () "&"))
"?"))))
(display url-without-fragment p)
(let loop ((left-params params))
(if (null? left-params)
(display fragment p)
(let ((key-encoded (uri-encode-string (caar left-params)))
(vals (cdar left-params))
(next-left (cdr left-params))
)
(if (pair? vals)
(for-each
(lambda (val)
(display (delimitee) p) ; "?" or "&"
(display key-encoded p)
(display "=" p)
(display (uri-encode-string (if (string? val) val "")) p))
vals)
(begin
(display (delimitee) p)
(display key-encoded p)))
(loop next-left))))))))))
(define (completion-uri uri server-name server-port https)
(receive (uri-scheme
uri-userinfo
uri-hostname
uri-port
uri-path
uri-query
uri-fragment) (uri-parse uri)
;; uri-schemeが無い時にだけ補完する
;; 但し、server-nameが与えられていない場合は補完できないので、何もしない
(if (or uri-scheme (not server-name))
uri
(let* ((scheme (if https "https" "http"))
(default-port (if https 443 80))
)
(uri-compose
:scheme scheme
:userinfo uri-userinfo
:host server-name
:port (and
server-port
(not (eqv? default-port (x->number server-port)))
server-port)
:path uri-path
:query uri-query
:fragment uri-fragment)))))
(define (path->url path)
(if (#/^\// path)
(completion-uri
path
(cgi-get-metavariable "SERVER_NAME")
(cgi-get-metavariable "SERVER_PORT")
(cgi-get-metavariable "HTTPS"))
path))
(define (self-url)
(path->url (self-path)))
(define (self-url/path-info)
(path->url (self-path/path-info)))
(define (self-url/slash)
(string-append (self-url) "/"))
(define (self-path)
(or (cgi-get-metavariable "SCRIPT_NAME") "/"))
(define (self-path/path-info)
;; note: PATH_INFOは既にデコードされてしまっているので使わない事
(let* ((r (or (cgi-get-metavariable "REQUEST_URI") "/"))
(m (#/\?/ r))
)
(if m
(m 'before)
r)))
(define (self-path/slash)
(string-append (self-path) "/"))
;;;===================================================================
(select-module user)
(define main (with-module jwhois.cgi main))
;; Local variables:
;; mode: scheme
;; end:
;; vim: set ft=scheme:
| false |
ca4f01217afef61f7f70f707f6ab91ba5a065203
|
665da87f9fefd8678b0635e31df3f3ff28a1d48c
|
/tests/match-tests.scm
|
53fd4b7b5cd15445baa423b11e7fca965c5dff82
|
[
"MIT"
] |
permissive
|
justinethier/cyclone
|
eeb782c20a38f916138ac9a988dc53817eb56e79
|
cc24c6be6d2b7cc16d5e0ee91f0823d7a90a3273
|
refs/heads/master
| 2023-08-30T15:30:09.209833 | 2023-08-22T02:11:59 | 2023-08-22T02:11:59 | 31,150,535 | 862 | 64 |
MIT
| 2023-03-04T15:15:37 | 2015-02-22T03:08:21 |
Scheme
|
UTF-8
|
Scheme
| false | false | 3,350 |
scm
|
match-tests.scm
|
(import
(scheme base)
(scheme write)
)
(cond-expand
(cyclone
(import
(cyclone match)
(cyclone test)))
(chibi
(import
(chibi ast)
(chibi match)
(chibi test)))
)
(test-group
"Official tests"
(test 2 (match (list 1 2 3) ((a b c) b)) )
(test 2 (match (list 1 2 1) ((a a b) 1) ((a b a) 2)))
(test 1 (match (list 1 2 1) ((_ _ b) 1) ((a b a) 2)) )
(test 2 (match 'a ('b 1) ('a 2)) )
(test '(2 3) (match (list 1 2 3) (`(1 ,b ,c) (list b c))))
(test #t (match (list 1 2) ((1 2 3 ...) #t)) )
(test #t (match (list 1 2 3) ((1 2 3 ...) #t)) )
(test #t (match (list 1 2 3 3 3) ((1 2 3 ...) #t)) )
(test '() (match (list 1 2) ((a b c ...) c)) )
(test '(3) (match (list 1 2 3) ((a b c ...) c)) )
(test '(3 4 5) (match (list 1 2 3 4 5) ((a b c ...) c)) )
(test '() (match (list 1 2 3 4) ((a b c ... d e) c)) )
(test '(3) (match (list 1 2 3 4 5) ((a b c ... d e) c)) )
(test '(3 4 5) (match (list 1 2 3 4 5 6 7) ((a b c ... d e) c)) )
;; Next fails on cyclone and chibi, I believe intentionally
;;; Pattern not matched
;(display (match (list 1 2) ((a b c ..1) c)) )(newline)
(test '(3) (match (list 1 2 3) ((a b c ..1) c)))
(test #t (match 1 ((and) #t)))
(test 1 (match 1 ((and x) x)))
(test 1 (match 1 ((and x 1) x)))
(test #f (match 1 ((or) #t) (else #f)) )
(test 1 (match 1 ((or x) x)))
;; Next fails on cyclone but pass on chibi
;(display (match 1 ((or x 2) x)) )(newline)
(test #t (match 1 ((not 2) #t)) )
(test 1 (match 1 ((? odd? x) x)))
(test 1 (match '(1 . 2) ((= car x) x)) )
(test 16 (match 4 ((= square x) x)) )
(test '("Doctor" "Bob")
(let ()
(define-record-type employee
(make-employee name title)
employee?
(name get-name)
(title get-title))
(match (make-employee "Bob" "Doctor")
(($ employee n t) (list t n)))))
(test '("Doctor" "Bob")
(let ()
(define-record-type employee
(make-employee name title)
employee?
(name get-name)
(title get-title))
(match (make-employee "Bob" "Doctor")
((@ employee (title t) (name n)) (list t n)))))
(test '(1 . 3) (let ((x (cons 1 2))) (match x ((1 . (set! s)) (s 3) x))))
(test 2 (match '(1 . 2) ((1 . (get! g)) (g))))
(test '(a a a) (match '(a (a (a b))) ((x *** 'b) x)))
(test '(a c f) (match '(a (b) (c (d e) (f g))) ((x *** 'g) x)))
)
(test-group
"Predicates"
(test "test" (match "test" ((? string? s) s) (else #f)))
(test #(fromlist 1 2) (match '(1 2) ((a b) (vector 'fromlist a b))))
(test #f (match 42 (X #f)))
)
(define (calc-time lst)
(match
lst
;(() 0)
(((? number? n) (or 's 'seconds 'sec) . rest)
(+ 0 (* #e1 n) (calc-time rest)))
(((? number? n) (or 'm 'min 'minutes) . rest)
(+ (* #e60 n) (calc-time rest)))
(((? number? n) (or 'hours 'h) . rest)
(+ (* #e60 60 n) (calc-time rest)))
(((? number? n) (or 'd 'days 'day) . rest)
(+ (* #e60 60 24 n) (calc-time rest)))
(((? number? n) (or 'w 'week 'weeks) . rest)
(+ (* #e60 60 24 7 n) (calc-time rest)))
(else 0)
))
(test-group
"Demo"
(test (+ (* 5 60) 10) (calc-time '(5 min 10 sec)))
(test (+ (* 24 60 60) (* 60 5) 10) (calc-time '(1 day 5 min 10 sec)))
(test (+ (* 24 60 60) (* 60 60) (* 60 5) 10) (calc-time '(0 weeks 1 day 1 h 5 min 10 sec)))
)
(test-exit)
| false |
089a446381ed1d34f71e5525bdc86806dd25fcb6
|
4b5dddfd00099e79cff58fcc05465b2243161094
|
/chapter_5/exercise_5_49.scm
|
23cfa9205bb4da489b96e8f00214e24dd6bb3e45
|
[
"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 | 2,956 |
scm
|
exercise_5_49.scm
|
#lang sicp
;; P429 - [练习 5.49]
(#%require "ch5-compiler.scm")
(#%require "ch5-regsim.scm")
(#%require "ch5-eceval-support.scm")
(define (compile-scheme expression)
(assemble (statements
(compile expression 'val 'return))
eceval))
(define (user-print object)
(cond ((compound-procedure? object)
(display (list 'compound-procedure
(procedure-parameters object)
(procedure-body object)
'<procedure-env>)))
((compiled-procedure? object)
(display '<compiled-procedure>))
(else (display object))))
(define eceval-operations
(list
(list 'compile-scheme compile-scheme)
;;primitive Scheme operations
(list 'read read) ;used by eceval
;;used by compiled code
(list 'list list)
(list 'cons cons)
;;operations in eceval-support.scm
(list 'true? true?)
(list 'false? false?) ;for compiled code
(list 'make-procedure make-procedure)
(list 'compound-procedure? compound-procedure?)
(list 'procedure-parameters procedure-parameters)
(list 'procedure-body procedure-body)
(list 'procedure-environment procedure-environment)
(list 'extend-environment extend-environment)
(list 'lookup-variable-value lookup-variable-value)
(list 'set-variable-value! set-variable-value!)
(list 'define-variable! define-variable!)
(list 'primitive-procedure? primitive-procedure?)
(list 'apply-primitive-procedure apply-primitive-procedure)
(list 'prompt-for-input prompt-for-input)
(list 'announce-output announce-output)
(list 'user-print user-print)
(list 'empty-arglist empty-arglist)
(list 'adjoin-arg adjoin-arg)
(list 'last-operand? last-operand?)
(list 'no-more-exps? no-more-exps?) ;for non-tail-recursive machine
(list 'get-global-environment get-global-environment)
;;for compiled code (also in eceval-support.scm)
(list 'make-compiled-procedure make-compiled-procedure)
(list 'compiled-procedure? compiled-procedure?)
(list 'compiled-procedure-entry compiled-procedure-entry)
(list 'compiled-procedure-env compiled-procedure-env)
))
(define eceval
(make-machine
'(exp env val proc argl continue unev)
eceval-operations
'(
read-eval-print-loop
(perform (op initialize-stack))
(perform (op prompt-for-input) (const ";;; EC-Eval input:"))
(assign exp (op read))
(assign env (op get-global-environment))
(assign continue (label print-result))
(assign val (op compile-scheme) (reg exp))
(goto (reg val))
print-result
;;**following instruction optional -- if use it, need monitored stack
(perform (op print-stack-statistics))
(perform (op announce-output) (const ";;; EC-Eval value:"))
(perform (op user-print) (reg val))
(goto (label read-eval-print-loop))
)))
(#%require (only racket module*))
(module* main #f
(start eceval)
)
| false |
3a6afa924243e44ef1dbf66bc5eb23ab895a6588
|
0f59162925b625ec3daa4c120fa8d2ab9ad95a64
|
/frweb/examples/stress.ss
|
df2c91e4cf6d47dd1cc88f2b87fa9711df76e601
|
[] |
no_license
|
jeapostrophe/flowww
|
3a722802e2becab999a75d7db74ae0ad2d3220dc
|
78fd500e3b107739c82cc6b562da4bda3e303245
|
refs/heads/master
| 2021-01-13T01:37:22.604628 | 2013-10-31T01:17:17 | 2013-10-31T01:17:17 | 732,537 | 0 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,505 |
ss
|
stress.ss
|
#lang frtime
(require "../frfx.ss")
(define (start req)
`(html (head (title "FrWeb Time Test"))
(body (h2 "The current time is: "
,(number->string seconds))
(h2 ,(if (even? seconds)
`(span ([style "color: red"]) "That's even, by the way.")
`(i "Unfortunately, it's not even.")))
(ul (li "Top")
,@(map
(lambda (i)
`(li ,(number->string i)))
(build-list (modulo seconds 10) add1)))
(ul ,@(map
(lambda (i)
`(li ,(number->string i)))
(build-list (modulo seconds 10) add1)))
#;(,(if (even? seconds)
'h2
'h3)
"Some header")
#;(span ([style ,(if (even? seconds)
"color: red"
"color: blue")])
"Some text")
; XXX attr name behavior
#;(span (,(if (even? seconds)
'[style "color: red"]
'[style "color: blue"]))
"Some text")
#;(span ,(if (even? seconds)
'([style "color: red"])
'([style "color: blue"]))
"Some text"))))
(serve/frp start)
| false |
5d1ac65fe99de0fe708aa3374a373e0c926606e3
|
eaa28dbef6926d67307a4dc8bae385f78acf70f9
|
/lib/pikkukivi/command/sanoa/main.sld
|
0346607723746b2d26e32797aebfc6409a75d948
|
[
"Unlicense"
] |
permissive
|
mytoh/pikkukivi
|
d792a3c20db4738d99d5cee0530401a144027f1f
|
d3d77df71f4267b9629c3fc21a49be77940bf8ad
|
refs/heads/master
| 2016-09-01T18:42:53.979557 | 2015-09-04T08:32:08 | 2015-09-04T08:32:08 | 5,688,224 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 578 |
sld
|
main.sld
|
(define-library (pikkukivi command sanoa main)
(export sanoa)
(import
(scheme base)
(gauche process)
(srfi 13)
(kirjasto työkalu)
(kirjasto merkkijono)
(kirjasto komento))
(begin
(define (run lang word)
(let1 url (string-append
"http://translate.google.com/translate_tts?ie=UTF-8&tl="
(string-upcase lang)
"&q="
word)
(run-command `(mpv --really-quiet ,url))))
(define (sanoa args)
(run (car args)
(cadr args)))
)
)
| false |
3bf5b689006e9655c3691a37fb1e0fc10adf5bfb
|
f04768e1564b225dc8ffa58c37fe0213235efe5d
|
/Assignment11/11test.ss
|
3d1734d6d48137f26b6e5525f54f75edc58ee190
|
[] |
no_license
|
FrancisMengx/PLC
|
9b4e507092a94c636d784917ec5e994c322c9099
|
e3ca99cc25bd6d6ece85163705b321aa122f7305
|
refs/heads/master
| 2021-01-01T05:37:43.849357 | 2014-09-09T23:27:08 | 2014-09-09T23:27:08 | 23,853,636 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 8,421 |
ss
|
11test.ss
|
;; Test code for CSSE 304 Assignment 11
(define (test-lexical-address)
(let ([correct '(
(: free x)
((: free x) (: free y))
(lambda (x y) ((: free cons) (: 0 0) (: 0 1)))
(lambda (x y z) (if (: 0 1) (: 0 0) (: 0 2)))
(lambda (x y)
(lambda ()
((lambda (z)
(lambda (x w)
(lambda ()
((: 1 0) (: 4 1) (: 2 0) (: 1 1)))))
((: 1 0) (: 1 1) (: free z) (: free w)))))
(lambda (a b c)
(if ((: free eq?)(: 0 1) (: 0 2))
((lambda (c)
((: free cons) (: 1 0) (: 0 0)))
(: 0 0))
(: 0 1)))
((lambda (x y)
(((lambda (z)
(lambda (w y)
((: free +) (: 2 0) (: 1 0) (: 0 0) (: 0 1))))
((: free list) (: free w) (: 0 0) (: 0 1) (: free z)))
((: free +) (: 0 0) (: 0 1) (: free z))))
((: free y) (: free z)))
(if ((lambda (x)
((: free y) (: 0 0)))
(lambda (y)
((: 0 0) (: free x))))
(lambda (z)
(if (: free x)
(: free y)
((: free cons) (: 0 0) (: 0 0))))
((: free x) (: free y)))
)]
[answers
(list
(lexical-address (quote x))
(lexical-address (quote (x y)))
(lexical-address (quote (lambda (x y) (cons x y))))
(lexical-address (quote (lambda (x y z) (if y x z))))
(lexical-address
(quote (lambda (x y)
(lambda ()
((lambda (z)
(lambda (x w)
(lambda () (x y z w))))
(x y z w))))))
(lexical-address
(quote (lambda (a b c)
(if (eq? b c)
((lambda (c) (cons a c)) a)
b))))
(lexical-address
'((lambda (x y)
(((lambda (z)
(lambda (w y)
(+ x z w y)))
(list w x y z))
(+ x y z)))
(y z)))
(lexical-address
(quote (if ((lambda (x) (y x))
(lambda (y) (y x)))
(lambda (z)
(if x y (cons z z)))
(x y))))
)])
(display-results correct answers equal?)))
(define (test-un-lexical-address)
(let ([correct '(
(x y)
(if ((lambda (x) (y x))
(lambda (y)
(y x)))
(lambda (z)
(if x y (cons z z)))
(x y))
(lambda (x y)
(lambda ()
((lambda (z)
(lambda (x w)
(lambda ()
(x y z w))))
(x y z w))))
)]
[answers
(list
(un-lexical-address (lexical-address (quote (x y))))
(un-lexical-address
(lexical-address
(quote (if ((lambda (x) (y x))
(lambda (y) (y x)))
(lambda (z)
(if x y (cons z z)))
(x y)))))
(un-lexical-address
(lexical-address
(quote (lambda (x y)
(lambda ()
((lambda (z)
(lambda (x w)
(lambda ()
(x y z w))))
(x y z w)))))))
)])
(display-results correct answers equal?)))
(define (test-my-let)
(let ([correct '(
1
55
123
3
)]
[answers
(list
(my-let ((a 1)) a)
(my-let loop
((L (quote (1 2 3 4 5 6 7 8 9 10)))
(A 0))
(if (null? L)
A
(loop (cdr L)
(+ (car L) A))))
(my-let ((a 5))
(+ 3
(my-let fact ((n a))
(if (zero? n)
1
(* n (fact (- n 1)))))))
(my-let ((a (lambda () 3)))
(my-let ((a (lambda () 5))
(b a))
(b)))
)])
(display-results correct answers equal?)))
(define (test-my-or)
(let ([correct '(
#t
(#(2 s c) 5 2)
#t
#f
1
4
1
6
)]
[answers
(list
(begin (set! a #f)
(my-or #f
(begin
(set! a (not a))
a)
#f))
(let loop ((L (quote (a b 2 5 #f (a b c) #(2 s c) foo a)))
(A (quote ())))
(if (null? L)
A
(loop (cdr L)
(if (my-or (number? (car L))
(vector? (car L))
(char? (car L)))
(cons (car L) A)
A))))
(let loop ((L (quote (1 2 3 4 5 a 6))))
(if (null? L)
#f
(my-or (symbol? (car L))
(loop (cdr L)))))
(my-or)
(let ([x 0])
(if (my-or
#f
4
(begin (set! x 12)
#t))
(set! x (+ x 1))
(set! x (+ x 3)))
x)
(my-or #f 4 3)
(let ([x 0])
(my-or (begin (set! x (+ 1 x))
x)
#f))
(my-or 6)
)])
(display-results correct answers equal?)))
(define (test-+=)
(let ([correct '(
25
(41 31 41)
)]
[answers
(list
(let ([a 5])
(+= a 10)
(+ a 10))
(begin (let* ((a 10) (b 21) (c (+= a (+= b a)))) (list a b c)))
)])
(display-results correct answers equal?)))
(define (test-return-first)
(let ([correct '(
2
5
3
(5 3)
)]
[answers
(list
(return-first 2)
(begin (let ([a 3])
(return-first (+ a 2)
(set! a 7)
a)))
(return-first (return-first
3
4
5)
1
2)
(let ([a 4])
(let ([b (return-first 3
(set! a 5)
2)])
(list a b)))
)])
(display-results correct answers equal?)))
;-----------------------------------------------
(define display-results
(lambda (correct results test-procedure?)
(display ": ")
(pretty-print
(if (andmap test-procedure? correct results)
'All-correct
`(correct: ,correct yours: ,results)))))
(define sequal?-grading
(lambda (l1 l2)
(cond
((null? l1) (null? l2))
((null? l2) (null? l1))
((or (not (set?-grading l1))
(not (set?-grading l2)))
#f)
((member (car l1) l2) (sequal?-grading
(cdr l1)
(rember-grading
(car l1)
l2)))
(else #f))))
(define set?-grading
(lambda (s)
(cond [(null? s) #t]
[(not (list? s)) #f]
[(member (car s) (cdr s)) #f]
[else (set?-grading (cdr s))])))
(define rember-grading
(lambda (a ls)
(cond
((null? ls) ls)
((equal? a (car ls)) (cdr ls))
(else (cons (car ls) (rember-grading a (cdr ls)))))))
(define set-equals? sequal?-grading)
(define find-edges ; e know that this node is in the graph before we do the call
(lambda (graph node)
(let loop ([graph graph])
(if (eq? (caar graph) node)
(cadar graph)
(loop (cdr graph))))))
;; Problem 8 graph?
(define set? ;; Is this list a set? If not, it is not a graph.
(lambda (list)
(if (null? list) ;; it's an empty set.
#t
(if (member (car list) (cdr list))
#f
(set? (cdr list))))))
(define graph?
(lambda (obj)
(and (list? obj)
(let ([syms (map car obj)])
(and (set? syms)
(andmap symbol? syms)
(andmap (lambda (x)
(andmap (lambda (y) (member y (remove (car x) syms)))
(cadr x)))
obj))))))
(define graph-equal?
(lambda (a b)
(and
(graph? a)
(graph? b)
(let ([a-nodes (map car a)]
[b-nodes (map car b)])
(and
(set-equals? a-nodes b-nodes)
; Now See if the edges from each node are equivalent in the two graphs.
(let loop ([a-nodes a-nodes])
(if (null? a-nodes)
#t
(let ([a-edges (find-edges a (car a-nodes))]
[b-edges (find-edges b (car a-nodes))])
(and (set-equals? a-edges b-edges)
(loop (cdr a-nodes)))))))))))
(define (test-graph-equal)
(list
(graph-equal? '((a (b)) (b (a))) '((b (a)) (a (b))))
(graph-equal? '((a (b c d)) (b (a c d)) (c (a b d)) (d (a b c)))
'((b (a c d)) (c (a b d)) (a (b d c)) (d (b a c))))
(graph-equal? '((a ())) '((a ())))
(graph-equal? '((a (b c)) (b (a c)) (c (a b))) '((a (b c)) (b (a c)) (c (a b))))
(graph-equal? '() '())
))
(define g test-graph-equal)
;You can run the tests individually, or run them all
;#by loading this file (and your solution) and typing (r)
(define (run-all)
(display 'lexical-address)
(test-lexical-address)
(display 'un-lexical-address)
(test-un-lexical-address)
(display 'my-let)
(test-my-let)
(display 'my-or)
(test-my-or)
(display '+=)
(test-+=)
(display 'return-first)
(test-return-first)
)
(define r run-all)
| false |
450a05ebd73f83578f09109c00bda7909c4686b1
|
276acd6dd9e3fd2209c358b4c0d1bbe52153be49
|
/languages/Scheme/Scheme/compile-rm.ss
|
f9ce9fa82ae1320c30739f12b587e0ff69306efc
|
[] |
no_license
|
is44c/Calico
|
5ea488eb800289227980bdfa6042d7f35e416ccf
|
867aceee9b9b4d90207106ead70ed3247897e4db
|
refs/heads/master
| 2021-01-10T10:21:41.870239 | 2013-06-12T23:57:26 | 2013-06-12T23:57:26 | 53,207,319 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 142 |
ss
|
compile-rm.ss
|
(load "rm-transformer.ss")
(delete-file "pjscheme-rm.ss")
(compile-level-output)
(rm-transform-file "pjscheme-ds.ss" "pjscheme-rm.ss")
(exit)
| false |
f758e0a6d2cf06321c64aeb88737e29a76cb7b4f
|
f5083e14d7e451225c8590cc6aabe68fac63ffbd
|
/cs/01-Programming/cs61a/course/lectures/2.2/squares.scm
|
0209b57304de3e9b931197f1ffba88bd0b2d303a
|
[] |
no_license
|
Phantas0s/playground
|
a362653a8feb7acd68a7637334068cde0fe9d32e
|
c84ec0410a43c84a63dc5093e1c214a0f102edae
|
refs/heads/master
| 2022-05-09T06:33:25.625750 | 2022-04-19T14:57:28 | 2022-04-19T14:57:28 | 136,804,123 | 19 | 5 | null | 2021-03-04T14:21:07 | 2018-06-10T11:46:19 |
Racket
|
UTF-8
|
Scheme
| false | false | 1,309 |
scm
|
squares.scm
|
;; Tree ADT.
;;
;; Representation: a tree is a pair, whose car is the datum and whose
;; cdr is a list of the subtrees.
(define make-tree cons)
(define datum car)
(define children cdr)
(define empty-tree? null?)
(define (leaf? tree)
(null? (children tree)))
;; Example tree, using ADT, with data at nodes.
(define t1 (make-tree 6
(list (make-tree 2
(list (make-tree 1 '())
(make-tree 4 '())))
(make-tree 9
(list (make-tree 7 '())
(make-tree 12 '()))))))
;; review -- mapping over a sequence.
(define (SQUARES seq)
(if (null? seq)
'()
(cons (SQUARE (car seq))
(SQUARES (cdr seq)) )))
;; Mapping over a tree -- data at all nodes
(define (SQUARES tree)
(make-tree (SQUARE (datum tree))
(map SQUARES (children tree)) ))
;; mapping over tree -- data at leaves only
(define (SQUARES tree)
(cond ((empty-tree? tree) '())
((leaf? tree) (make-tree (SQUARE (datum tree)) '()))
(else (make-tree '() (map SQUARES (children tree)))) ))
;; Common alternative for mapping data at leaves only, no explicit ADT:
(define (SQUARES tree)
(cond ((null? tree) '())
((not (pair? tree)) (SQUARE tree))
(else (cons (SQUARES (car tree))
(SQUARES (cdr tree)) )) ))
;; Hallmark of tree recursion: recur for both car and cdr.
| false |
a5d25f576cf96911fffac99e1399506205aa2a91
|
f08220a13ec5095557a3132d563a152e718c412f
|
/logrotate/skel/usr/share/guile/2.0/srfi/srfi-9/gnu.scm
|
219bcdebb4103f4b0c09297c41dc36f93df75571
|
[
"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 | 6,471 |
scm
|
gnu.scm
|
;;; Extensions to SRFI-9
;; Copyright (C) 2010, 2012 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
;;; Commentary:
;; Extensions to SRFI-9. Fully documented in the Guile Reference Manual.
;;; Code:
(define-module (srfi srfi-9 gnu)
#:use-module (srfi srfi-1)
#:use-module (system base ck)
#:export (set-record-type-printer!
define-immutable-record-type
set-field
set-fields))
(define (set-record-type-printer! type proc)
"Set PROC as the custom printer for TYPE."
(struct-set! type vtable-index-printer proc))
(define-syntax-rule (define-immutable-record-type name ctor pred fields ...)
((@@ (srfi srfi-9) %define-record-type)
#t (define-immutable-record-type name ctor pred fields ...)
name ctor pred fields ...))
(define-syntax-rule (set-field s (getter ...) expr)
(%set-fields #t (set-field s (getter ...) expr) ()
s ((getter ...) expr)))
(define-syntax-rule (set-fields s . rest)
(%set-fields #t (set-fields s . rest) ()
s . rest))
;;
;; collate-set-field-specs is a helper for %set-fields
;; thats combines all specs with the same head together.
;;
;; For example:
;;
;; SPECS: (((a b c) expr1)
;; ((a d) expr2)
;; ((b c) expr3)
;; ((c) expr4))
;;
;; RESULT: ((a ((b c) expr1)
;; ((d) expr2))
;; (b ((c) expr3))
;; (c (() expr4)))
;;
(define (collate-set-field-specs specs)
(define (insert head tail expr result)
(cond ((find (lambda (tree)
(free-identifier=? head (car tree)))
result)
=> (lambda (tree)
`((,head (,tail ,expr)
,@(cdr tree))
,@(delq tree result))))
(else `((,head (,tail ,expr))
,@result))))
(with-syntax (((((head . tail) expr) ...) specs))
(fold insert '() #'(head ...) #'(tail ...) #'(expr ...))))
(define-syntax unknown-getter
(lambda (x)
(syntax-case x ()
((_ orig-form getter)
(syntax-violation 'set-fields "unknown getter" #'orig-form #'getter)))))
(define-syntax c-list
(lambda (x)
(syntax-case x (quote)
((_ s 'v ...)
#'(ck s '(v ...))))))
(define-syntax c-same-type-check
(lambda (x)
(syntax-case x (quote)
((_ s 'orig-form '(path ...)
'(getter0 getter ...)
'(type0 type ...)
'on-success)
(every (lambda (t g)
(or (free-identifier=? t #'type0)
(syntax-violation
'set-fields
(format #f
"\
field paths ~a and ~a require one object to belong to two different record types (~a and ~a)"
(syntax->datum #`(path ... #,g))
(syntax->datum #'(path ... getter0))
(syntax->datum t)
(syntax->datum #'type0))
#'orig-form)))
#'(type ...)
#'(getter ...))
#'(ck s 'on-success)))))
(define-syntax %set-fields
(lambda (x)
(with-syntax ((getter-type #'(@@ (srfi srfi-9) getter-type))
(getter-index #'(@@ (srfi srfi-9) getter-index))
(getter-copier #'(@@ (srfi srfi-9) getter-copier)))
(syntax-case x ()
((_ check? orig-form (path-so-far ...)
s)
#'s)
((_ check? orig-form (path-so-far ...)
s (() e))
#'e)
((_ check? orig-form (path-so-far ...)
struct-expr ((head . tail) expr) ...)
(let ((collated-specs (collate-set-field-specs
#'(((head . tail) expr) ...))))
(with-syntax (((getter0 getter ...)
(map car collated-specs)))
(with-syntax ((err #'(unknown-getter
orig-form getter0)))
#`(ck
()
(c-same-type-check
'orig-form
'(path-so-far ...)
'(getter0 getter ...)
(c-list (getter-type 'getter0 'err)
(getter-type 'getter 'err) ...)
'(let ((s struct-expr))
((ck () (getter-copier 'getter0 'err))
check?
s
#,@(map (lambda (spec)
(with-syntax (((head (tail expr) ...) spec))
(with-syntax ((err #'(unknown-getter
orig-form head)))
#'(head (%set-fields
check?
orig-form
(path-so-far ... head)
(struct-ref s (ck () (getter-index
'head 'err)))
(tail expr) ...)))))
collated-specs)))))))))
((_ check? orig-form (path-so-far ...)
s (() e) (() e*) ...)
(syntax-violation 'set-fields "duplicate field path"
#'orig-form #'(path-so-far ...)))
((_ check? orig-form (path-so-far ...)
s ((getter ...) expr) ...)
(syntax-violation 'set-fields "one field path is a prefix of another"
#'orig-form #'(path-so-far ...)))
((_ check? orig-form . rest)
(syntax-violation 'set-fields "invalid syntax" #'orig-form))))))
| true |
6776ff81282bd4dc03faff570275d9cc1005fda5
|
1e3480417b4da6395370dbe77c5f7e82e807f280
|
/mk-util.scm
|
0e399634212d066d6c0e557eb4a0615ee0a8031b
|
[] |
no_license
|
joshcox/send-more-money
|
dc3da6eb07ab83022df2773b41a23b187ca4849b
|
400f053dd1eae70d52ede55eab209477d558ed9a
|
refs/heads/master
| 2021-01-18T14:34:02.984733 | 2014-04-19T04:00:23 | 2014-04-19T04:00:23 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,155 |
scm
|
mk-util.scm
|
;;some nice utilities for miniKanren
(load "mk.scm")
(load "numbers.scm")
;;aps macro for pipelining a series of pluso operations
;;to a single variable
;;(pluso* x1 x2 x* ... o)
(define-syntax pluso*
(syntax-rules ()
((_ (uf* ...) (n0 n1) o (p* ...))
(fresh (uf* ...) p* ... (pluso n0 n1 o)))
((_ (uf* ...) (n0 n1 n* ...) o (p* ...))
(pluso* (f1 uf* ...) (f1 n* ...) o ((pluso n0 n1 f1) p* ...)))
((_ n0 n1 n* ... o)
(pluso* (f1) (f1 n* ...) o ((pluso n0 n1 f1))))))
;;=/=* (all-diff, unique, whatever) - written by Jason Hemann
(define-syntax =/=*
(syntax-rules (:)
((_ : (dt dt* ...) () (cl* ...)) (fresh () cl* ...))
((_ t1 t* ... : (ot ot* ...) (dt* ...) (cl* ...))
(=/=* t1 t* ... : (ot* ...) (ot dt* ...) ((=/= t1 ot) cl* ...)))
((_ t1 t* ... : () (dt dt* ...) (cl* ...))
(=/=* t* ... : (t1 dt dt* ...) () (cl* ...)))
((_ t0 t1 t* ...) (=/=* t1 t* ... : (t0) () ()))))
;;(withino n n* ... lbd ubd)
;;a constraint that restricts n,n* to fall within lbd and ubd
(define-syntax withino
(syntax-rules (:)
((_ lbd ubd : (c* ...))
(fresh () c* ...))
((_ n n* ... lbd ubd : (c* ...))
(withino n* ... lbd ubd : ((<=o n ubd) (<=o lbd n) c* ...)))
((_ n n* ... lbd ubd)
(withino n* ... lbd ubd : ((<=o n ubd) (<=o lbd n))))))
;;builds a list of Oleg numbers from lbd to ubd
(define (range lbd ubd)
(cond
((> lbd ubd) '())
(else (cons (build-num lbd) (range (add1 lbd) ubd)))))
;;similar to withino, this constrains a number appear within
;;a finite domain bounded by the provided list.
(define domain
(lambda (x y*)
(fresh (a d)
(== `(,a . ,d) y*)
(conde
((== x a))
((domain x d))))))
(define membero?
(lambda (x ls)
(conde
((== ls '()) (== #f #t))
((fresh (a d)
(== `(,a . ,d) ls)
(conde
((== x a) (== #f #f))
((=/= x a) (membero? x d))))))))
(define xor^o
(lambda (x y r)
(conde
((== x '()) (== y '()) (== r '()))
((== x '()) (== y '(1)) (== r '(1)))
((== x '(1)) (== y '()) (== r '(1)))
((== x '(1)) (== y '(1)) (== r '())))))
| true |
5cdfc89b31b0cd35adbf19836c1376fafa36ac70
|
f0747cba9d52d5e82772fd5a1caefbc074237e77
|
/pkg/python3.scm
|
f56d83368521b8bd828c0c63dddbc000f2844386
|
[] |
no_license
|
philhofer/distill
|
a3b024de260dca13d90e23ecbab4a8781fa47340
|
152cb447cf9eef3cabe18ccf7645eb597414f484
|
refs/heads/master
| 2023-08-27T21:44:28.214377 | 2023-04-20T03:20:55 | 2023-04-20T03:20:55 | 267,761,972 | 3 | 0 | null | 2021-10-13T19:06:55 | 2020-05-29T04:06:55 |
Scheme
|
UTF-8
|
Scheme
| false | false | 1,875 |
scm
|
python3.scm
|
(import
scheme
(only (chicken string) conc)
(distill plan)
(distill package)
(distill base)
(distill kvector)
(distill execline)
(pkg ncurses)
(pkg libexpat)
(pkg libffi)
(pkg tcl)
(pkg gdbm)
(pkg libreadline))
;; this py-setup arranges for just about
;; all of the modules to be built-in statically
(define python-config
(cdn-artifact "6iCCIatqDyPAUvIMW9CiVQG_vP-oBZxzL-RLAOuX050=" "/src/py-setup" #o644))
(define python3
(cmmi-package
"Python" "3.9.11"
"https://www.python.org/ftp/python/$version/$name-$version.tar.xz"
"NurkxI3wI4RAjLrFP81eU18EeZSDqdfM_23vEigNoKQ="
extra-src: (list python-config)
libs: (list ncurses libexpat libressl zlib libbz2 liblzma libffi
linux-headers gdbm libreadline)
cross: (list
(lambda (conf)
;; TODO: figure out precisely the conditions under which
;; the build script requires an external python3 program;
;; right now we're approximating it as 'build-triple != host-triple'
(if (eq? ($triple conf) ($build-triple conf)) '() (list python3))))
env: '((ac_cv_file__dev_ptmx . yes)
(ac_cv_file__dev_ptc . no))
prepare: '(cp /src/py-setup Modules/Setup)
cleanup: '(pipeline (find /out -type d -name __pycache__ -print0)
xargs "-0" rm -rf)
extra-configure: `(,(elconc '--with-openssl= $sysroot '/usr)
--enable-ipv6
--enable-optimizations=no
--with-computed-gotos
--with-dbmliborder=gdbm
--with-system-expat
--without-ensurepip)
override-make: (let (($py-cflags (lambda (conf)
(cons '-DTHREAD_STACK_SIZE=0x100000 ($CFLAGS conf)))))
`(,(el= 'EXTRA_CFLAGS= $py-cflags) ,$make-overrides))))
| false |
08db47a0ab8ace190d59a2f4d2a2d4d99d8aa69f
|
4f30ba37cfe5ec9f5defe52a29e879cf92f183ee
|
/src/sasm/tx/config.scm
|
c93979f92310a7707d7ce5d4dbdb1bde6cd6fac9
|
[
"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 | 795 |
scm
|
config.scm
|
;; sasm code-generator configuration ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; a symbol, identifying the target to the user
(define *machine-name* #f)
;; an association list of register symbols to actual register names
(define *machine-register-list* #f)
;; an association list of sys-register symbols to actual register names
(define *machine-sys-register-list* #f)
;; a table mapping SASM instruction patterns to actual assembly code
(define *machine-instructions* #f)
(define *sasm-assemble-class-in-data-segment* #f)
(define (sasm-set-target! name register-mapping sys-register-mapping machine)
(set! *machine-name* name)
(set! *machine-register-list* register-mapping)
(set! *machine-sys-register-list* sys-register-mapping)
(set! *machine-instructions* machine))
| false |
515c6b0c16baa0dd2a0ffc6762941cefb1a5f254
|
b9eb119317d72a6742dce6db5be8c1f78c7275ad
|
/praxis/isbn.rkt
|
8801b62dd2d26dc65acc02c6d71976df66139cdc
|
[] |
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,606 |
rkt
|
isbn.rkt
|
#! /bin/sh
#| Hey Emacs, this is -*-scheme-*- code!
exec racket --require "$0" --main -- ${1+"$@"}
|#
;; http://programmingpraxis.com/2011/05/20/isbn-validation/
#lang racket
(require rackunit rackunit/text-ui)
(define (digitchar->number d)
(if (char=? (char-downcase d) #\x)
10
(- (char->integer d)
(char->integer #\0))))
(define (groups str)
(regexp-split #rx"[- \t]+" str))
(define (->digits . strings)
(map digitchar->number (append* (map string->list strings))))
(define (->checksum constant digits)
(apply + (map * digits constant)))
(provide validate-ISBN/EAN)
(define (validate-ISBN/EAN str)
(match (groups str)
[(list region publisher title check)
(zero? (remainder
(->checksum (build-list 10 (curry - 10))
(->digits region publisher title check))
11))]
[(list "978" region publisher title check)
(zero? (remainder
(->checksum (build-list 10 (lambda (i) (if (even? i ) 1 3)))
(->digits region publisher title check))
10))]
[_ #f]))
(define-test-suite validate-ISBN/EAN-tests
(check-true (validate-ISBN/EAN "0-330-28987-X"))
(check-true (validate-ISBN/EAN "0- 330 -28987--X"))
(check-false (validate-ISBN/EAN "1-330-28987-X"))
(check-false (validate-ISBN/EAN "frotz plotz"))
(check-true (validate-ISBN/EAN "978-0-440-22378-8"))
(check-false (validate-ISBN/EAN "978-0-441-22378-8")))
(define-test-suite all-tests
validate-ISBN/EAN-tests)
(provide main)
(define (main . args)
(exit (run-tests all-tests 'verbose)))
| false |
0228677740d34025ce7ac38633df7b00a8a1dbcb
|
6138af219efc3a8f31060e30ebc532ffcbad1768
|
/experiments/norman/quaestor/src/main/scm/quaestor/sparql.scm
|
afd9bd792daabfae085937424a3fbf234286ad49
|
[
"AFL-3.0"
] |
permissive
|
Javastro/astrogrid-legacy
|
dd794b7867a4ac650d1a84bdef05dfcd135b8bb6
|
51bdbec04bacfc3bcc3af6a896e8c7f603059cd5
|
refs/heads/main
| 2023-06-26T10:23:01.083788 | 2021-07-30T11:17:12 | 2021-07-30T11:17:12 | 391,028,616 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 32,296 |
scm
|
sparql.scm
|
;; SISC library module for Quaestor
;; Support for SPARQL queries
(import s2j)
(require-library 'quaestor/utils)
(require-library 'quaestor/knowledgebase)
(require-library 'quaestor/jena)
(module sparql
(sparql:make-query-runner) ;the sole export from this module
(import* utils
jobject->list
is-java-type?)
(import* knowledgebase
kb:knowledgebase?
kb:get)
(import* jena
rdf:mime-type-list
rdf:mime-type->language
rdf:select-statements)
;; a few predicates for contracts
(define (jstring? x)
(define-java-class <java.lang.string>)
(is-java-type? x <java.lang.string>))
(define (jena-model? x)
(define-java-class <com.hp.hpl.jena.rdf.model.model>)
(is-java-type? x <com.hp.hpl.jena.rdf.model.model>))
(define (java-query? x)
(define-java-class <com.hp.hpl.jena.query.query>)
(is-java-type? x <com.hp.hpl.jena.query.query>))
(define (andf l) ; (and...) as a function
(cond ((null? l))
((car l)
(andf (cdr l)))
(else #f)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; SPARQL stuff
;; Following doesn't work, for reasons that I don't completely follow. See
;; http://sourceforge.net/mailarchive/forum.php?forum_id=7422&max_rows=25&style=nested&viewmonth=200412
;; for discussion and a workaround I definitely don't follow.
;; (define-syntax check-set-name!
;; (syntax-rules ()
;; ((_ procname)
;; (define :check-procedure-name (quote procname)))))
(define-syntax check
(syntax-rules ()
((_ test message ...)
(if (not test)
(error 'sparql:make-query-runner message ...)))))
;; Create an implementation of the ResultSet interface, which takes
;; a list of ResultSet instances, and returns results from each of
;; them in turn until all are exhausted.
;;
;; As well, this can be invoked with a null list of result-sets,
;; in which case it functions correctly as a (dummy?) result-set
;; with no results.
(define-java-classes <com.hp.hpl.jena.query.result-set>)
(define-java-proxy (multi-result-set result-sets)
(<com.hp.hpl.jena.query.result-set>)
(define (get-result-vars obj)
(define-generic-java-method get-result-vars)
(define-java-class <java.lang.string>)
(if (null? result-sets)
(java-array-new <java.lang.string> 0)
(get-result-vars (car result-sets))))
(define (get-row-number obj)
;; This doesn't respect multiplicity of result sets
;; ie, it resets the row number when starting on a new resultset
(define-generic-java-method get-row-number)
(if (null? result-sets)
(->jint 0)
(get-row-number (car result-sets))))
(define (has-next obj)
;; return true if the hasNext method of the car of the result-sets returns true;
;; if it doesn't, then try the succeeding elements of the list until one does,
;; or we run out of list
(define-generic-java-method has-next)
(if (null? result-sets)
(->jboolean #f)
(let loop ((current-has-next (has-next (car result-sets))))
(if (->boolean current-has-next) ;it does
current-has-next
(let ((new-result-sets (cdr result-sets)))
(set! result-sets new-result-sets)
(if (null? new-result-sets) ; no more results available from anywhere
(->jboolean #f)
(loop (has-next (car new-result-sets)))))))))
(define (distinct? obj)
;; All the results should be generated in response to the same query, so all should have
;; the same return for this method.
(define-generic-java-method distinct?)
(if (null? result-sets)
(->jboolean #t)
(distinct? (car result-sets))))
(define (ordered? obj)
;; as with DISTINCT?
(define-generic-java-method ordered?)
(if (null? result-sets)
(->jboolean #t)
(ordered? (car result-sets))))
(define (next obj)
(define-generic-java-method next)
(define-java-class <java.util.no-such-element-exception>)
(if (null? result-sets)
(error (java-new <java.util.no-such-element-exception>))
(next (car result-sets))))
(define (next-solution obj)
(define-generic-java-method next-solution)
(define-java-class <java.util.no-such-element-exception>)
(if (null? result-sets)
(error (java-new <java.util.no-such-element-exception>))
(next-solution (car result-sets))))
(define (remove obj)
(define-java-class <java.util.unsupported-operation-exception>)
(error (java-new <java.util.unsupported-operation-exception>
(->jstring "multi-result-set: Method 'remove' called unexpectedly")))))
;; PARSE-SPARQL-QUERY : string-or-jstring -> <Query>
(define (parse-sparql-query query-string)
(define-java-classes
(<query-factory> |com.hp.hpl.jena.query.QueryFactory|))
(define-generic-java-methods
create get-message)
(let ((query-jstring (cond ((and (is-java-type? query-string '|java.lang.String|)
(not (java-null? query-string)))
query-string)
((string? query-string)
(->jstring query-string))
(else
(error 'sparql:make-query-runner
"bad call: got query ~s, not string"
query-string)))))
(with/fc
(lambda (m e)
;; (error-message m) is the exception.
(report-exception 'sparql:make-query-runner
'|SC_BAD_REQUEST|
"SPARQL parse error: ~a" (->string (get-message (error-message m)))))
(lambda ()
(let ((q (create (java-null <query-factory>) query-jstring)))
(check q "can't happen: null query in sparql:make-query-runner")
q)))))
;; FIND-DELEGATES : knowledgebase -> listof knowledgebase-or-URIstring
;; Return the KB given as argument, at the head of a list of the KBs it delegates to
;; (ie, without delegation, this returns simply (k).
;; The return values in the list are knowledgebases if the knowledgebase is in this quaestor,
;; or a jstring containing a URI, if the delegated-to knowledgebase is at a different SPARQL endpoint
(define/contract (find-delegates (k kb:knowledgebase?) -> list?)
(define-generic-java-methods
(get-uri |getURI|))
(define (literal->string literal)
(define-generic-java-methods to-string)
(->string (to-string literal)))
(chatter "finding delegates of KB ~a" (if (procedure? k) (k 'get-name-as-uri) k))
(cons k
(let ((kb-uris (map get-uri (rdf:select-statements (k 'get-metadata)
(k 'get-name-as-resource)
"http://ns.eurovotech.org/quaestor#delegatesTo"
#f)))
(external? (member "externaldelegation"
(map literal->string
(rdf:select-statements (k 'get-metadata)
(k 'get-name-as-resource)
"http://ns.eurovotech.org/quaestor#debug"
#f)))))
(chatter "...KB ~s apparently delegates to ~s~a" (if (procedure? k) (k 'get-name-as-uri) k) kb-uris (if external? " (EXTERNALDELEGATION)" ""))
(apply append
(map (lambda (kb-uri)
(cond (external? ;forced external for debugging/unit-testing
(list kb-uri))
((kb:get (java-new <uri> kb-uri))
=> ;; this resource names a KB in this quaestor, so query that model directly
find-delegates)
(else ;; remote KB?, so evaluate to the string URI
(list kb-uri))))
kb-uris)))))
;; MAKE-EXECUTABLE-QUERY : model-or-url <com.hp.hpl.jena.query.Query> -> <...QueryExecution>
(define (make-executable-query x query)
(define-java-classes
(<query-execution-factory> |com.hp.hpl.jena.query.QueryExecutionFactory|))
(define-generic-java-methods create sparql-service)
(let ((qef (java-null <query-execution-factory>)))
(cond ((jena-model? x)
(create qef query x))
((jstring? x)
;; otherwise assume it names a SPARQL endpoint
;; (FIXME: the following might throw MalformedURL exceptions,
;; either because it is indeed malformed, or because the protocol is
;; unknown (for example, 'urn:'); we should trap these, and also make
;; ourselves more robust against the URL being simply wrong/dead, though
;; we won't find that out until the query is actually performed, later).
;;
;; The returned object is a
;; com.hp.hpl.jena.query.engineHTTP.QueryEngineHTTP object. It does not
;; appear possible to control the type of query being made, but it seems
;; from the ARQ source, and its behaviour, that it constructs a
;; 'GET foo?query=<query>' interaction, and that it switches to a POST
;; of the query if the GET URL would be too long.
(sparql-service qef x query))
(else
(error 'sparql-make-query-runner
"can't happen: expected model or jstring, but found ~s" x)))))
;; sparql:make-query-runner knowledgebase string-or-jstring list-of-strings -> procedure
;;
;; Given a knowledgebase KB, a SPARQL QUERY, and a (non-null) MIME-TYPE-LIST
;; of acceptable MIME types, return a procedure which has the signature
;;
;; (query-runner output-stream content-type-setter)
;;
;; where CONTENT-TYPE-SETTER is a procedure which takes a mime-type and
;; sets that as the content-type of the given OUTPUT-STREAM. This returned
;; procedure is all side-effect, and returns #f.
;;
;; All parsing and verification should be done before the procedure is returned,
;; so that when the procedure is finally called, it should run
;; successfully, barring unforseen changes in the environment.
;;
;; The procedure will either succeed or throw an error.
(define/contract (sparql:make-query-runner (kb (or (kb:knowledgebase? kb) (jena-model? kb)))
(query (or (string? query)
(jstring? query)))
(mime-type-list list?)
-> procedure?)
(with/fc (lambda (m error-continuation)
(if (pair? (error-message m))
(throw m) ;it came from report-exception; just pass it on
(report-exception 'sparql:make-query-runner
'|SC_INTERNAL_SERVER_ERROR|
"Something bad happened in sparql:make-query-runner: ~a"
(format-error-record m))))
(lambda ()
(cond ((null? mime-type-list)
(error "sparql:make-query-runner called with no MIME types"))
((kb:knowledgebase? kb)
(let ((query-model-list (map (lambda (one-kb)
(cond ((jstring? one-kb) one-kb)
((procedure? one-kb) (one-kb 'get-query-model))
(else (error "one-kb=~s (this shouldn't happen)" one-kb))))
(find-delegates kb))))
(if (andf query-model-list)
(sparql:make-query-runner* query-model-list query mime-type-list)
(report-exception 'sparql:make-query-runner '|SC_BAD_REQUEST| "I wasn't able to find a "))))
(else
(sparql:make-query-runner* (list kb) query mime-type-list))))))
;; worker procedure for sparql:make-query-runner
;; The elements of the QUERY-MODEL-LIST list are models if the model is held in this quaestor,
;; or a jstring if it is at a remote SPARQL endpoint.
;; The QUERY is the SPARQL query.
;; The MIME-TYPE-LIST is a non-null list of MIME types from the Accept header.
(define/contract (sparql:make-query-runner* (query-model-list (and (list? query-model-list)
(andf (map (lambda (x)
(or (jena-model? x)
(jstring? x))) ;url
query-model-list))))
(query (or (string? query) (jstring? query)))
(mime-type-list (and (list? mime-type-list)
(not (null? mime-type-list)))))
(define-generic-java-methods close to-string)
(let ((parsed-query (parse-sparql-query query)))
;; For each of the query models extracted above (in the simplest case, there will be only one,
;; but there will be multiple ones if there is delegation), create an executable query
(let ((executable-queries ;a list of QueryExecution objects
(map (lambda (one-model)
(make-executable-query one-model parsed-query))
query-model-list))
(query-executor (find-query-executor parsed-query))
(handler (make-result-set-handler 'sparql:make-query-runner
mime-type-list
(determine-query-type parsed-query))))
;; slightly paranoid: check everything looks as it should
(check (and (not (null? executable-queries))
(let loop ((l executable-queries))
(if (null? l)
#t
(and (not (java-null? (car l)))
(loop (cdr l))))))
"error creating ~a executable queries from query ~a"
(length executable-queries) (->string query-jstring))
;; check we have a query-executor and a non-null list of queries
(if (not (and query-executor (not (null? executable-queries))))
(begin (map close executable-queries)
(error 'sparql:make-query-runner
"can't find a way of executing query ~a"
(->string query-jstring))))
;; OK, we're fairly sure everything's OK
(chatter "Produced list of queries: ~s" executable-queries)
;; Return the function which will run all of these executable queries (in principle in parallel)
;; and print out a result set consisting of the union of the result-sets returned.
;; This doesn't attempt to deal with the case where the same result appears from multiple
;; queries -- perhaps it should.
(lambda (output-stream content-type-setter)
(if (= (length executable-queries) 1)
(handler (query-executor (car executable-queries))
output-stream
content-type-setter)
(handler (multi-result-set (map query-executor executable-queries))
output-stream
content-type-setter))
(map close executable-queries)
#f))))
;; The following is the simple case which doesn't handle delegation.
;; Perhaps it's useful as documentation...?
(define (sparql:make-query-runner-NO-DELEGATION kb
query
mime-type-list)
(define-java-classes
(<query-factory> |com.hp.hpl.jena.query.QueryFactory|)
(<query-execution-factory> |com.hp.hpl.jena.query.QueryExecutionFactory|))
(define-generic-java-methods
create
close)
(check kb
"cannot query null knowledgebase")
(check (kb:knowledgebase? kb)
"kb argument is not a knowledgebase!")
(check (not (null? mime-type-list))
"received null mime-type-list")
(let ((query-model (kb 'get-query-model))
(query-jstring (cond ((and (is-java-type? query '|java.lang.String|)
(not (java-null? query)))
query)
((string? query)
(->jstring query))
(else
(error 'sparql:make-query-runner
"bad call: got query ~s, not string"
query)))))
(check query-model
"failed to get query model from knowledgebase ~a"
(kb 'get-name-as-uri))
(let ((query (with/fc
(lambda (m e)
;; (print-exception (make-exception m e)) seems not to
;; work here. Don't know why. No matter: (error-message m) is the
;; exception.
(define-generic-java-method get-message)
(report-exception 'sparql:make-query-runner
'|SC_BAD_REQUEST|
"SPARQL parse error: ~a"
(->string
(get-message (error-message m)))))
(lambda ()
(create (java-null <query-factory>) query-jstring)))))
(or query
(error "can't happen: null query in sparql:make-query-runner"))
(let ((executable-query (create (java-null <query-execution-factory>)
query
query-model))
(query-executor (find-query-executor query))
(handler (make-result-set-handler 'sparql:make-query-runner
mime-type-list
(determine-query-type query))))
(check (not (java-null? executable-query))
"can't make executable query from ~a" (->string query-jstring))
(if (not (and query-executor executable-query))
(begin (or (java-null? executable-query)
(close executable-query))
(error 'sparql:make-query-runner
"can't find a way of executing query ~a"
(->string query-jstring))))
;; success!
(lambda (output-stream content-type-setter)
(let ((query-result (query-executor executable-query)))
(handler query-result output-stream content-type-setter)
(close executable-query)
#f))))))
;; make-result-set-handler symbol list symbol -> procedure
;; error: if none of the listed MIME types can be handled
;;
;; Return a procedure which will handle output of query results.
;; Given: CALLER-NAME: a symbol giving the location errors should
; be reported as coming from,
;; MIME-TYPES: a list of acceptable MIME-types,
;; QUERY-TYPE: one of the four symbols returned by DETERMINE-QUERY-TYPE,
;; Return: a procedure.
;;
;; The returned procedure has the following signature:
;;
;; (result-set-handler query-result output-stream content-type-setter)
;;
;; The procedure should write the query-result to the given output stream,
;; after first calling the CONTENT-TYPE-SETTER procedure with the appropriate
;; MIME type.
;;
;; When outputting XML, results should have the MIME type application/xml.
;; See <http://www.w3.org/2001/sw/DataAccess/prot26>, which refers to schema
;; spec at <http://www.w3.org/TR/rdf-sparql-XMLres/>
(define (make-result-set-handler caller-name
mime-types
query-type)
(define-generic-java-methods
out
(output-as-xml |outputAsXML|)
write
println)
(define-java-classes
<java.io.print-stream>
(<result-set-formatter> |com.hp.hpl.jena.query.ResultSetFormatter|))
;; Returns the first string in POSSIBILITIES which is one of the strings
;; in WANT, or #f if there are none. If one of the entries in POSSIBILITIES
;; is */*, return the first element of WANT.
(define (find-in-list want possibilities)
(chatter "find-in-list: want=~s poss=~s" want possibilities)
(cond ((null? possibilities)
#f)
((string=? (car possibilities) "*/*")
(car want))
((member (car possibilities) want)
(car possibilities)) ;success!
(else
(find-in-list want (cdr possibilities)))))
(chatter "make-result-set-handler: caller-name=~s mime-types=~s query-type=~s"
caller-name mime-types query-type)
(case query-type
((select)
(let ((handlers `(("application/sparql-results+xml" . ;see http://www.w3.org/TR/rdf-sparql-XMLres/#mime
,(lambda (result stream set-type)
(set-type "application/sparql-results+xml")
(output-as-xml (java-null <result-set-formatter>)
stream
result)))
("application/xml" .
,(lambda (result stream set-type)
(set-type "application/xml")
(output-as-xml (java-null <result-set-formatter>)
stream
result)))
("text/plain" .
,(lambda (result stream set-type)
(set-type "text/plain")
(out (java-null <result-set-formatter>)
stream result)))
("text/csv" .
,(lambda (result stream set-type)
(set-type "text/csv;header=present")
(output-as-csv stream result)))
("text/tab-separated-values" .
,(lambda (result stream set-type)
;; we include the line of headers, but TSV
;; doesn't specify the header=present parameter
(set-type "text/tab-separated-values")
(output-as-tab-separated-values stream result))))))
(let ((best-type (find-in-list (map car handlers)
mime-types)))
(cond ((not best-type)
(report-exception caller-name
'|SC_NOT_ACCEPTABLE|
"can't handle any of the MIME types ~a for SELECT queries (only ~a)"
mime-types (map car handlers)))
((assoc best-type handlers)
=> (lambda (p)
(cdr p)))
(else
;; this shouldn't happen
(report-exception caller-name
'|SC_INTERNAL_SERVER_ERROR|
"this can't happen: mime-types ~s -> unrecognised best-type=~s"
mime-types best-type))))))
((ask)
(let ((handlers `(("application/sparql-results+xml" . ;see http://www.w3.org/TR/rdf-sparql-XMLres/#mime
,(lambda (result stream set-type)
(set-type "application/sparql-results+xml")
(output-as-xml (java-null <result-set-formatter>)
stream
result)))
("application/xml" .
,(lambda (result stream set-type)
(set-type "application/xml")
(output-as-xml (java-null <result-set-formatter>)
stream
result)))
("text/plain" .
,(lambda (result stream set-type)
(set-type "text/plain")
(println (java-new <java.io.print-stream> stream)
(->jstring (if (->boolean result)
"yes" "no"))))))))
(let ((best-type (find-in-list (map car handlers)
mime-types)))
(cond ((not best-type)
(report-exception caller-name
'|SC_NOT_ACCEPTABLE|
"can't handle any of the MIME types ~a for ASK queries (only ~a)"
mime-types (map car handlers)))
((assoc best-type handlers)
=> (lambda (p)
(cdr p)))
(else
;; this shouldn't happen
(report-exception caller-name
'|SC_INTERNAL_SERVER_ERROR|
"this can't happen: mime-types ~s -> unrecognised best-type=~s"
mime-types best-type))))))
((construct describe)
;; QUERY-RESULT is a Model
(let ((best-type (find-in-list (rdf:mime-type-list) mime-types)))
(if best-type
(let ((lang (rdf:mime-type->language best-type)))
(lambda (result stream set-type)
(set-type best-type)
(write result
stream
(->jstring lang))))
(report-exception caller-name
'|SC_NOT_ACCEPTABLE|
"can't handle any of the MIME types ~a for ~a queries"
mime-types query-type))))
(else
(error caller-name "Unrecognised query type ~a" query-type))))
;; output-as-csv java-stream java-resultset -> void
;; side-effect: write resultset to stream
;;
;; Given a ResultSet and an output stream, write the result as CSV, following
;; the spec in RFC 4180. Include a header.
(define (output-as-csv stream result)
(define (write-list-with-commas print-list pw)
(define-generic-java-methods print)
(let ((jcomma (->jstring ","))
(jcrlf (->jstring (list->string (list (integer->char 13)
(integer->char 10))))))
(if (null? print-list)
(error 'output-as-csv "asked to output null list"))
(let loop ((l print-list))
(print pw (car l))
(let ((next (cdr l)))
(if (null? next)
(print pw jcrlf)
(begin (print pw jcomma)
(loop next)))))))
(output-with-formatter stream result write-list-with-commas))
;; The format of TSV files is specified rather informally at
;; <http://www.iana.org/assignments/media-types/text/tab-separated-values>.
;; The MIME type is "text/tab-separated-values".
(define (output-as-tab-separated-values stream result)
(define (tsv-output print-list pw)
(define-generic-java-methods print println)
(let ((jtab (->jstring (list->string (list (integer->char 9))))))
(if (null? print-list)
(error 'output-as-tab-separated-values "can't output null list"))
(let loop ((l print-list))
(print pw (car l))
(let ((next (cdr l)))
(if (null? next)
(println pw)
(begin (print pw jtab)
(loop next)))))))
(output-with-formatter stream result tsv-output))
;; OUTPUT-WITH-FORMATTER java-stream java-result-set procedure -> void
;; side-effect: write the given result-set to the stream
;;
;; The formatter is a procedure with the prototype
;; (formatter output-list printwriter)
;; The output-list is a list of Java objects which are to be sent to the
;; given PrintStream.
(define (output-with-formatter stream result formatter)
(define-generic-java-methods
get-result-vars
has-next
next-solution
get
to-string
flush)
(define-java-classes
<java.io.print-writer>
<java.io.output-stream-writer>)
(let ((result-vars (jobject->list (get-result-vars result)))
(pw (java-new <java.io.print-writer>
(java-new <java.io.output-stream-writer>
stream
(->jstring "UTF-8"))))
(empty-string (->jstring "")))
(formatter result-vars pw)
(let loop ()
(if (->boolean (has-next result))
(let ((qs (next-solution result)))
(formatter (map (lambda (var)
(let ((res (get qs var)))
(if (java-null? res)
empty-string
(to-string res))))
result-vars)
pw)
(loop))))
(flush pw))) ; flush is necessary
;; FIND-QUERY-EXECUTOR : <Query> -> procedure-or-false
;;
;; Given a PARSED-QUERY, return one of the set QueryExecution.execSelect,
;; QueryExecution.execAsk, ..., based on the type of query returned by
;; Query.getQueryType. If none of them match for some reason, return #f.
(define find-query-executor
(let ((alist #f))
(define-generic-java-methods exec-ask exec-construct exec-describe exec-select)
(set! alist
`((select . ,exec-select)
(ask . ,exec-ask)
(construct . ,exec-construct)
(describe . ,exec-describe)))
(lambda/contract ((parsed-query java-query?)
-> (lambda (x) (or (not x) (procedure? x))))
(let ((result-pair (assq (determine-query-type parsed-query) alist)))
;; If we've found a suitable function to execute the query (in the cdr of this pair),
;; then return it, wrapped in a FC which means we don't fall over if the (remote?)
;; query fails.
(and result-pair
(lambda (executable-query)
(define-generic-java-method to-string)
(with/fc (lambda (m e)
;; There's been some error executing the query, possibly because a remote
;; service is down, or something like that. It's not completely clear what's
;; the best thing to do, here, but for now, let's just note the error
;; and return an empty result set.
(chatter "query execution failed: ~a" (->string (to-string (error-message m))))
(multi-result-set '()))
(lambda ()
((cdr result-pair) executable-query)))))))))
;; determine-query-type java-string -> symbol
;;
;; Given a query, return one of the symbols 'ask, 'select, 'construct or
;; 'describe depending on what type of query it is.
;; Return #f if none match (which shouldn't happen).
(define determine-query-type
(let ((alist #f))
(lambda (query)
(define-generic-java-method get-query-type)
(if (not alist)
(let ()
(define-generic-java-field-accessors
(query-ask |QueryTypeAsk|)
(query-construct |QueryTypeConstruct|)
(query-describe |QueryTypeDescribe|)
(query-select |QueryTypeSelect|))
(set! alist
`((,(->number (query-select query)) . select)
(,(->number (query-ask query)) . ask)
(,(->number (query-construct query)) . construct)
(,(->number (query-describe query)) . describe)))))
(let ((result-pair (assv (->number (get-query-type query))
alist)))
(and result-pair (cdr result-pair))))))
;; End SPARQL stuff
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
)
| true |
597aa5621b0b6807bcaa1e9369648018d51ccc97
|
ac587213fe223ddf6d60893b02b7b69a3783a38a
|
/compat/compat-gambit.scm
|
3d92dace9e9f18625a0ed2a1656c4ae6dade3315
|
[] |
no_license
|
BernardBeefheart/bbslib
|
eef90ca19d6a87f0588029e40be98f15029f2379
|
d4a199fe53a55bf43446804313b81f97ab637d83
|
refs/heads/master
| 2021-01-17T12:42:42.730263 | 2016-06-12T19:47:46 | 2016-06-12T19:47:46 | 20,342,080 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 306 |
scm
|
compat-gambit.scm
|
;; ======================================================================
;; compat-gambit.scm
;; ln -s .../bbslib/compat/compat-gambit.scm ~/.gambcini
;; ======================================================================
(include "~~/lib/syntax-case.scm")
(display "syntax-case incuded!")
(newline)
| false |
4fda14a0e8e83ce36326bab8a048930a04cceb2d
|
4fd95c081ccef6afc8845c94fedbe19699b115b6
|
/chapter_2/2.73.scm
|
8b8da6340004f78cc30eae31f8041fd648c0fc51
|
[
"MIT"
] |
permissive
|
ceoro9/sicp
|
61ff130e655e705bafb39b4d336057bd3996195d
|
7c0000f4ec4adc713f399dc12a0596c770bd2783
|
refs/heads/master
| 2020-05-03T09:41:04.531521 | 2019-08-08T12:14:35 | 2019-08-08T12:14:35 | 178,560,765 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 4,165 |
scm
|
2.73.scm
|
; ------------------------------------------------------------------
(define (=number? exp num) (and (number? exp) (= exp num)))
(define (variable? x) (symbol? x))
(define (same-variable? v1 v2)
(and (variable? v1) (variable? v2) (eq? v1 v2)))
; ------------------------------------------------------------------
(define (create-data-direct-map) '())
(define (make-data-direct-map-item operation type item) (list operation type item))
(define (select-operation dd-map-item) (car dd-map-item))
(define (select-type dd-map-item) (cadr dd-map-item))
(define (select-item dd-map-item) (caddr dd-map-item))
(define data-direct-map (create-data-direct-map))
(define (get-from-dd-map dd-map operation type)
(cond ((null? dd-map) #f)
((and (eq? (select-operation (car dd-map))
operation)
(eq? (select-type (car dd-map))
type)) (select-item (car dd-map)))
(else (get-from-dd-map (cdr dd-map) operation type))))
(define (put-to-dd-map dd-map operation type item)
(cons (make-data-direct-map-item operation
type
item)
dd-map))
(define (put operation type item)
(define new-dd-map (put-to-dd-map data-direct-map operation type item))
(set! data-direct-map new-dd-map))
(define (get operation type)
(get-from-dd-map data-direct-map
operation
type))
; ------------------------------------------------------------------
(define (deriv exp var)
(cond ((number? exp) 0)
((variable? exp) (if (same-variable? exp var) 1 0))
(else ((get (operator exp) 'deriv) (operands exp) var))))
; ------------------------------------------------------------------
(define (make-sum a1 a2)
(cond ((=number? a1 0) a2)
((=number? a2 0) a1)
((and (number? a1) (number? a2)) (+ a1 a2))
(else (list '+ a1 a2))))
(define (sum? x) (and (pair? x) (eq? (car x) '+)))
(define (addend s) (cadr s))
(define (augend s) (caddr s))
; ------------------------------------------------------------------
(define (make-product m1 m2)
(cond ((or (=number? m1 0) (=number? m2 0)) 0)
((=number? m1 1) m2)
((=number? m2 1) m1)
((and (number? m1) (number? m2)) (* m1 m2))
(else (list '* m1 m2))))
(define (product? x) (and (pair? x) (eq? (car x) '*)))
(define (multiplier p) (cadr p))
(define (multiplicand p) (caddr p))
; ------------------------------------------------------------------
(define (make-exponentation a n)
(cond ((= n 1) a)
((= n 0) 1)
((and (number? a) (number? n)) (pow a n))
(else (list '^ a n))))
(define (exponentation? x) (and (pair? x) (eq? (car x) '^)))
(define (base s) (cadr s))
(define (exponent s) (caddr s))
; ------------------------------------------------------------------
(define (install-sum-deriv)
(define (handle-exp operands var)
(make-sum (deriv (car operands) var)
(deriv (cadr operands) var)))
(put '+ 'deriv handle-exp))
(define (install-product-deriv)
(define (handle-exp operands var)
(make-sum (make-product (car operands)
(deriv (cadr operands) var))
(make-product (cadr operands)
(deriv (car operands) var))))
(put '* 'deriv handle-exp))
(define (install-exponentation)
(define (handle-exp operands var)
(make-product
(make-product (cadr operands)
(make-exponentation (car operands)
(make-sum (cadr operands)
-1)))
(deriv (car operands) var)))
(put '^ 'deriv handle-exp))
; ------------------------------------------------------------------
(define (operator exp) (car exp))
(define (operands exp) (cdr exp))
(install-sum-deriv)
(install-product-deriv)
(install-exponentation)
(display (deriv '(+ (* 5 (+ 3 x)) (^ x 3)) 'x))
| false |
af3c33e257cf9a2a294b297d7514b80fbda543a1
|
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
|
/ext/crypto/sagittarius/crypto/keys/operations/asymmetric/eddsa.scm
|
6fa06d3aa3d297a4d30486f9735536b47aecb5ee
|
[
"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 | 14,994 |
scm
|
eddsa.scm
|
;;; -*- mode:scheme; coding:utf-8; -*-
;;;
;;; sagittarius/crypto/keys/operations/asymmetric/eddsa.scm - EdDSA key op
;;;
;;; Copyright (c) 2022 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.
;;;
#!nounbound
(library (sagittarius crypto keys operations asymmetric eddsa)
(export generate-key-pair
generate-public-key
generate-private-key
import-public-key
import-private-key
export-public-key
export-private-key
*key:eddsa*
*key:ed25519*
*key:ed448*
eddsa-key? <eddsa-key>
eddsa-key-parameter
eddsa-public-key? <eddsa-public-key>
eddsa-public-key-data
eddsa-private-key? <eddsa-private-key>
eddsa-private-key-random
eddsa-private-key-public-key
ed25519-key?
ed25519-public-key?
ed25519-private-key?
ed448-key?
ed448-public-key?
ed448-private-key?
eddsa-clamp!
)
(import (rnrs)
(core misc)
(clos user)
(srfi :117 list-queues)
(sagittarius)
(sagittarius mop immutable)
(sagittarius crypto asn1)
(sagittarius crypto keys types)
(sagittarius crypto keys operations asymmetric apis)
(sagittarius crypto digests)
(sagittarius crypto random)
(sagittarius crypto math ed)
(sagittarius crypto math prime))
(define *key:eddsa* :eddsa)
(define *key:ed25519* :ed25519)
(define *key:ed448* :ed448)
(define-class <eddsa-key> (<immutable>)
((parameter :init-keyword :parameter :reader eddsa-key-parameter)))
(define (eddsa-key? o) (is-a? o <eddsa-key>))
(define-class <eddsa-public-key> (<public-key> <eddsa-key>)
((data :init-keyword :data :reader eddsa-public-key-data)))
(define (eddsa-public-key? o) (is-a? o <eddsa-public-key>))
(define-class <eddsa-private-key> (<private-key> <eddsa-key>)
((random :init-keyword :random :reader eddsa-private-key-random)
(public-key :init-keyword :public-key :reader eddsa-private-key-public-key)))
(define (eddsa-private-key? o) (is-a? o <eddsa-private-key>))
(define (ed25519-key? key)
(and (eddsa-key? key)
(eq? 'ed25519 (eddsa-parameter-name (eddsa-key-parameter key)))))
(define (ed448-key? key)
(and (eddsa-key? key)
(eq? 'ed448 (eddsa-parameter-name (eddsa-key-parameter key)))))
(define (ed25519-public-key? key)
(and (eddsa-public-key? key) (ed25519-key? key)))
(define (ed25519-private-key? key)
(and (eddsa-private-key? key) (ed25519-key? key)))
(define (ed448-public-key? key)
(and (eddsa-public-key? key) (ed448-key? key)))
(define (ed448-private-key? key)
(and (eddsa-private-key? key) (ed448-key? key)))
(define (generate-ed25519-key-pair prng)
(let* ((random (random-generator-read-random-bytes prng 32))
(private-key (generate-ed25519-private-key random)))
(make-key-pair private-key
(eddsa-private-key-public-key private-key))))
(define (generate-ed25519-public-key data)
(make <eddsa-public-key> :data data :parameter ed25519-parameter))
(define (generate-ed25519-private-key random)
#|
5.1.5. Key Generation
The private key is 32 octets (256 bits, corresponding to b) of
cryptographically secure random data. See [RFC4086] for a discussion
about randomness.
The 32-byte public key is generated by the following steps.
1. Hash the 32-byte private key using SHA-512, storing the digest in
a 64-octet large buffer, denoted h. Only the lower 32 bytes are
used for generating the public key.
2. Prune the buffer: The lowest three bits of the first octet are
cleared, the highest bit of the last octet is cleared, and the
second highest bit of the last octet is set.
3. Interpret the buffer as the little-endian integer, forming a
secret scalar s. Perform a fixed-base scalar multiplication
[s]B.
4. The public key A is the encoding of the point [s]B. First,
encode the y-coordinate (in the range 0 <= y < p) as a little-
endian string of 32 octets. The most significant bit of the
final octet is always zero. To form the encoding of the point
[s]B, copy the least significant bit of the x coordinate to the
most significant bit of the final octet. The result is the
public key.
|#
(define (generate-public-key random)
(let ((h (digest-message (make-message-digest *digest:sha-512*) random))
(l (make-bytevector 32)))
;; 1
(bytevector-copy! h 0 l 0 32)
;; 2
(eddsa-clamp! l 3 254 256)
;; 3
(let* ((s (bytevector->integer/endian l (endianness little)))
(sB (ed-point-mul ed25519-parameter
(eddsa-parameter-B ed25519-parameter)
s)))
;; 4
(ed-point-encode-base ed25519-parameter sB
(eddsa-parameter-b ed25519-parameter)))))
(unless (= (bytevector-length random) 32)
(assertion-violation 'generate-ed25519-private-key "Invalid key size"))
(let ((pub (generate-ed25519-public-key (generate-public-key random))))
(make <eddsa-private-key> :parameter ed25519-parameter
:random random :public-key pub)))
(define-method generate-public-key ((m (eql *key:ed25519*))
(data <bytevector>) . ignore)
(generate-ed25519-public-key data))
(define-method generate-private-key ((m (eql *key:ed25519*))
(random <bytevector>) . ignore)
(generate-ed25519-private-key random))
(define-method generate-key-pair ((m (eql *key:ed25519*))
:key (prng (secure-random-generator *prng:chacha20*))
:allow-other-keys)
(generate-ed25519-key-pair prng))
(define (generate-ed448-key-pair prng)
(let* ((random (random-generator-read-random-bytes prng 57))
(private-key (generate-ed448-private-key random)))
(make-key-pair private-key
(eddsa-private-key-public-key private-key))))
(define (generate-ed448-public-key data)
(make <eddsa-public-key> :data data :parameter ed448-parameter))
(define (generate-ed448-private-key random)
#|
5.2.5. Key Generation
The private key is 57 octets (456 bits, corresponding to b) of
cryptographically secure random data. See [RFC4086] for a discussion
about randomness.
The 57-byte public key is generated by the following steps:
1. Hash the 57-byte private key using SHAKE256(x, 114), storing the
digest in a 114-octet large buffer, denoted h. Only the lower 57
bytes are used for generating the public key.
2. Prune the buffer: The two least significant bits of the first
octet are cleared, all eight bits the last octet are cleared, and
the highest bit of the second to last octet is set.
3. Interpret the buffer as the little-endian integer, forming a
secret scalar s. Perform a known-base-point scalar
multiplication [s]B.
4. The public key A is the encoding of the point [s]B. First encode
the y-coordinate (in the range 0 <= y < p) as a little-endian
string of 57 octets. The most significant bit of the final octet
is always zero. To form the encoding of the point [s]B, copy the
least significant bit of the x coordinate to the most significant
bit of the final octet. The result is the public key.
|#
(define (generate-public-key random)
(let ((h (digest-message (make-message-digest *digest:shake-256*)
random 114))
(l (make-bytevector 57)))
;; 1
(bytevector-copy! h 0 l 0 57)
;; 2
(eddsa-clamp! l 2 447 456)
;; 3
(let* ((s (bytevector->integer/endian l (endianness little)))
(sB (ed-point-mul ed448-parameter
(eddsa-parameter-B ed448-parameter)
s)))
;; 4
(ed-point-encode-base ed448-parameter sB
(eddsa-parameter-b ed448-parameter)))))
(unless (= (bytevector-length random) 57)
(assertion-violation 'generate-ed448-private-key "Invalid key size"))
(let ((pub (generate-ed448-public-key (generate-public-key random))))
(make <eddsa-private-key> :parameter ed448-parameter
:random random :public-key pub)))
(define-method generate-public-key ((m (eql *key:ed448*))
(data <bytevector>) . ignore)
(generate-ed448-public-key data))
(define-method generate-private-key ((m (eql *key:ed448*))
(random <bytevector>) . ignore)
(generate-ed448-private-key random))
(define-method generate-key-pair ((m (eql *key:ed448*))
:key (prng (secure-random-generator *prng:chacha20*))
:allow-other-keys)
(generate-ed448-key-pair prng))
(define *ed25519-key-oid* "1.3.101.112")
(define-method oid->key-operation ((oid (equal *ed25519-key-oid*)))
*key:ed25519*)
(define *ed448-key-oid* "1.3.101.113")
(define-method oid->key-operation ((oid (equal *ed448-key-oid*)))
*key:ed448*)
(define-method key->oid ((key <eddsa-key>))
(if (ed25519-key? key)
*ed25519-key-oid*
*ed448-key-oid*))
(define-method export-public-key ((key <eddsa-public-key>) . opts)
(apply export-public-key *key:eddsa* key opts))
(define-method export-public-key ((m (eql *key:ed25519*))
(key <eddsa-public-key>) . opts)
(apply export-public-key *key:eddsa* key opts))
(define-method export-public-key ((m (eql *key:ed448*))
(key <eddsa-public-key>) . opts)
(apply export-public-key *key:eddsa* key opts))
(define-method export-public-key ((m (eql *key:eddsa*))
(key <eddsa-public-key>)
:optional (format (public-key-format raw)))
(define (eddsa-key->oid key)
(cond ((ed25519-key? key) *ed25519-key-oid*)
((ed448-key? key) *ed448-key-oid*)
(else (assertion-violation 'export-public-key
"Unknown EdDSA key type"))))
(case format
((raw) (eddsa-public-key-data key))
((subject-public-key-info)
(asn1-encodable->bytevector
(der-sequence
(der-sequence
(oid-string->der-object-identifier (eddsa-key->oid key)))
(bytevector->der-bit-string (eddsa-public-key-data key)))))
(else (assertion-violation 'export-public-key
"Unknown public key format" format))))
(define-method import-public-key ((m (eql *key:ed25519*))
(in <port>) . opts)
(apply import-public-key m (get-bytevector-all in) opts))
(define-method import-public-key ((m (eql *key:ed25519*))
(bv <bytevector>)
:optional (format (public-key-format raw)))
(if (eq? format 'raw)
(generate-ed25519-public-key bv)
(import-public-key *key:eddsa* bv format)))
(define-method import-public-key ((m (eql *key:ed25519*))
(key <der-sequence>)
. opts)
(apply import-public-key *key:eddsa* key opts))
(define-method import-public-key ((m (eql *key:ed448*))
(in <port>) . opts)
(apply import-public-key m (get-bytevector-all in) opts))
(define-method import-public-key ((m (eql *key:ed448*))
(bv <bytevector>)
:optional (format (public-key-format raw)))
(if (eq? format 'raw)
(generate-ed448-public-key bv)
(import-public-key *key:eddsa* bv format)))
(define-method import-public-key ((m (eql *key:ed448*))
(key <der-sequence>)
. opts)
(apply import-public-key *key:eddsa* key opts))
(define-method import-public-key ((m (eql *key:eddsa*))
(in <bytevector>) . opts)
(apply import-public-key m (open-bytevector-input-port in) opts))
(define-method import-public-key ((m (eql *key:eddsa*))
(in <port>) . opts)
(apply import-public-key m (read-asn1-object in) opts))
(define-method import-public-key ((m (eql *key:eddsa*))
(in <der-sequence>)
:optional (format (public-key-format subject-public-key-info)))
(unless (eq? format 'subject-public-key-info)
(assertion-violation 'import-public-key
"Bare EdDSA can't be imported with raw format"))
(let*-values (((aid key) (deconstruct-asn1-collection in))
((oid . rest) (deconstruct-asn1-collection aid)))
(let ((op (oid->key-operation (der-object-identifier->oid-string oid))))
;; ironically, specifying key type, e.g. *key:ed25519*, for SPKI
;; format is slower than just specifying *key:eddsa*...
;; life sucks, huh?
(import-public-key op (der-bit-string->bytevector key)))))
(define-method export-private-key ((key <eddsa-private-key>) . opts)
(apply export-private-key *key:eddsa* key opts))
(define-method export-private-key ((m (eql *key:ed25519*))
(key <eddsa-private-key>) . opts)
(apply export-private-key *key:eddsa* key opts))
(define-method export-private-key ((m (eql *key:ed448*))
(key <eddsa-private-key>) . opts)
(apply export-private-key *key:eddsa* key opts))
(define-method export-private-key ((m (eql *key:eddsa*))
(key <eddsa-private-key>) . ignore)
(eddsa-private-key-random key))
(define-method import-private-key ((m (eql *key:ed25519*))
(in <port>) . opts)
(apply import-private-key m (get-bytevector-all in) opts))
(define-method import-private-key ((m (eql *key:ed25519*))
(in <bytevector>) . ignore)
(generate-ed25519-private-key in))
(define-method import-private-key ((m (eql *key:ed448*))
(in <port>) . opts)
(apply import-private-key m (get-bytevector-all in) opts))
(define-method import-private-key ((m (eql *key:ed448*))
(in <bytevector>) . ignore)
(generate-ed448-private-key in))
(define (eddsa-clamp! a c n b)
(do ((i 0 (+ i 1)))
((= i c))
(bytevector-u8-set! a (div i 8)
(bitwise-and (bytevector-u8-ref a (div i 8))
(bitwise-not (bitwise-arithmetic-shift-left 1 (mod i 8))))))
(bytevector-u8-set! a (div n 8)
(bitwise-ior (bytevector-u8-ref a (div n 8))
(bitwise-arithmetic-shift-left 1 (mod n 8))))
(do ((i (+ n 1) (+ i 1)))
((= i b) a)
(bytevector-u8-set! a (div i 8)
(bitwise-and (bytevector-u8-ref a (div i 8))
(bitwise-not (bitwise-arithmetic-shift-left 1 (mod i 8)))))))
)
| false |
3d09da8e40360f39c91170690900843931a56794
|
0b1826093fb47c0a7293573d80f03a28e859640f
|
/chapter-3/ex-3.72.scm
|
4667cb63f8c18684a4b0a0f8f2bc76dfcf86ba5f
|
[
"MIT"
] |
permissive
|
yysaki/sicp
|
253ef8ef52a330af6c2107ca7063773e63f1a4aa
|
36d2964c980c58ba13a2687e0af773a5e12d770d
|
refs/heads/master
| 2021-01-20T11:50:20.648783 | 2017-12-10T03:43:38 | 2017-12-10T08:08:18 | 56,677,496 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,267 |
scm
|
ex-3.72.scm
|
(load "./3.5")
(define (merge-weighted s1 s2 weight)
(cond ((stream-null? s1) s2)
((stream-null? s2) s1)
(else
(let ((s1car (stream-car s1))
(s2car (stream-car s2)))
(if (< (weight s1car) (weight s2car))
(cons-stream s1car (merge-weighted (stream-cdr s1) s2 weight))
(cons-stream s2car (merge-weighted s1 (stream-cdr s2) weight)))))))
(define (weighted-pairs s t weight)
(cons-stream
(list (stream-car s) (stream-car t))
(merge-weighted
(stream-map (lambda (x) (list (stream-car s) x))
(stream-cdr t))
(weighted-pairs (stream-cdr s) (stream-cdr t) weight)
weight)))
(define (weight pair)
(define (square x) (* x x))
(+ (square (car pair))
(square (cadr pair))))
(define (three-count-stream s)
(let ((s0 (stream-car s))
(s1 (stream-car (stream-cdr s)))
(s2 (stream-car (stream-cdr (stream-cdr s)))))
(if (= (weight s0) (weight s1) (weight s2))
(cons-stream (list (weight s0) s0 s1 s2)
(three-count-stream (stream-cdr (stream-cdr (stream-cdr s)))))
(three-count-stream (stream-cdr s)))))
(display-stream-10 (three-count-stream (weighted-pairs integers integers weight)))
| false |
13673d67af847237bd0cf30f6f458185dc6dd128
|
4f17c70ae149426a60a9278c132d5be187329422
|
/scheme/r6rs/unicode.ss
|
f21efa03829a93f8ca7494c293f9b31591c1cbbb
|
[] |
no_license
|
okuoku/yuni-core
|
8da5e60b2538c79ae0f9d3836740c54d904e0da4
|
c709d7967bcf856bdbfa637f771652feb1d92625
|
refs/heads/master
| 2020-04-05T23:41:09.435685 | 2011-01-12T15:54:23 | 2011-01-12T15:54:23 | 889,749 | 2 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 550 |
ss
|
unicode.ss
|
(library (yuni scheme r6rs unicode)
(export
char-upcase char-downcase char-titlecase char-foldcase
char-ci=? char-ci<? char-ci>? char-ci<=? char-ci>=?
char-alphabetic? char-numeric? char-whitespace?
char-upper-case? char-lower-case? char-title-case?
char-general-category
string-upcase string-downcase string-titlecase string-foldcase
string-ci=? string-ci<? string-ci>? string-ci<=? string-ci>=?
string-normalize-nfd string-normalize-nfkd
string-normalize-nfc string-normalize-nfkc)
(import
(yuni scheme r6rs)))
| false |
111b24df47261611b3ff755f8a932109134a6b7c
|
fb9a1b8f80516373ac709e2328dd50621b18aa1a
|
/ch1/exercise1-30.scm
|
e617f5e87e09228b3121f1a4e85362f297921756
|
[] |
no_license
|
da1/sicp
|
a7eacd10d25e5a1a034c57247755d531335ff8c7
|
0c408ace7af48ef3256330c8965a2b23ba948007
|
refs/heads/master
| 2021-01-20T11:57:47.202301 | 2014-02-16T08:57:55 | 2014-02-16T08:57:55 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 343 |
scm
|
exercise1-30.scm
|
;; 問題1.30
;; 反復的にsumを計算できるように書きなおす.
(load "./ch1/1-3_Formulating_Abstractings_with_Higher-Order_Procedures.scm")
(define (sum term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (+ result (term a)))))
(iter a 0))
(sum cube 1 inc 10)
(sum identity 1 inc 10)
| false |
813fa09bfae5da9465c4f5c21c03214178c942eb
|
9998f6f6940dc91a99e0e2acb4bc4e918f49eef0
|
/src/test/sample-moby-programs/falling-ball.ss
|
04613df3de5040ec0af4007f889edb6f337c1a98
|
[] |
no_license
|
JessamynT/wescheme-compiler2012
|
326d66df382f3d2acbc2bbf70fdc6b6549beb514
|
a8587f9d316b3cb66d8a01bab3cf16f415d039e5
|
refs/heads/master
| 2020-05-30T07:16:45.185272 | 2016-03-19T07:14:34 | 2016-03-19T07:14:34 | 70,086,162 | 0 | 0 | null | 2016-10-05T18:09:51 | 2016-10-05T18:09:51 | null |
UTF-8
|
Scheme
| false | false | 957 |
ss
|
falling-ball.ss
|
;; The first three lines of this file were inserted by DrScheme. They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-reader.ss" "lang")((modname falling-ball) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ())))
;; Simple falling ball example. Red ball falls down.
;; A world is a number representing the y position of the red ball.
(define WIDTH 320)
(define HEIGHT 480)
(define RADIUS 5)
(define (tick y)
(+ y 5))
(define (hits-floor? y)
(>= y (- HEIGHT RADIUS)))
(check-expect (hits-floor? 0) false)
(check-expect (hits-floor? HEIGHT) true)
(define (draw-scene y)
(place-image (circle RADIUS "solid" "red") (/ WIDTH 2) y
(empty-scene WIDTH HEIGHT)))
(big-bang WIDTH HEIGHT
10
(on-tick 1/15 tick)
(on-redraw draw-scene)
(stop-when hits-floor?))
| false |
530ac61ab70660c89e755a164d9b2a7db5c079cc
|
03de0e9f261e97d98f70145045116d7d1a664345
|
/schemantic-web/rdf-simple-graph.sls
|
6749973ee24dd5206e135b367da47538bf6be7a2
|
[
"LicenseRef-scancode-public-domain"
] |
permissive
|
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 | 2,316 |
sls
|
rdf-simple-graph.sls
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; R6RS Wrapper for TRC Simple RDF Graphs
;;;
;;; 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 schemantic-web rdf-simple-graph)
(export
make-rdf-graph
rdf-graph?
rdf-graph/add-triple!
rdf-graph/all-objects
rdf-graph/all-predicates
rdf-graph/all-subjects
rdf-graph/all-triples
rdf-graph/for-each-matching-object
rdf-graph/for-each-matching-predicate
rdf-graph/for-each-matching-subject
rdf-graph/for-each-object
rdf-graph/for-each-predicate
rdf-graph/for-each-subject
rdf-graph/for-each-triple-by-object
rdf-graph/for-each-triple-by-predicate
rdf-graph/for-each-triple-by-subject
rdf-graph/for-each-triple
rdf-graph/matching-objects
rdf-graph/matching-predicates
rdf-graph/matching-subjects
;; rdf-graph/purge-matching-objects!
;; rdf-graph/purge-matching-predicates!
;; rdf-graph/purge-matching-subjects!
;; rdf-graph/purge-triples-by-object!
;; rdf-graph/purge-triples-by-predicate!
;; rdf-graph/purge-triples-by-subject!
rdf-graph/remove-triple!
rdf-graph/size
rdf-graph/triples-by-object
rdf-graph/triples-by-predicate
rdf-graph/triples-by-subject)
(import
(except (rnrs base) for-each map)
(srfi :1)
(srfi :9)
(riastradh schemantic-web rdf)
(riastradh schemantic-web rdf-map)
(riastradh foof-loop)
(srfi private include))
(include/resolve-ci ("riastradh" "schemantic-web") "rdf-simple-graph.scm")
)
| false |
836682237170735fb81a5bac4f35506708ca5cae
|
9b2eb10c34176f47f7f490a4ce8412b7dd42cce7
|
/lib/yunivm/util/basiclibs.sls
|
dfc94719d2cb4ccd05accfabd6e54628684ee1d4
|
[
"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 | 5,708 |
sls
|
basiclibs.sls
|
(library (yunivm util basiclibs)
(export
basiclibs-zero-values
basiclibs-proc-vector
basiclibs-name-vector)
(import (yuni scheme))
;;
(define basiclibs-zero-values
'(;; FIXME: This list is incomplete. e.g. for-each etc
write
write-shared write-simple
newline
display
write-char write-string write-u8 write-bytevector
flush-output-port
delete-file
exit
;; stdlib
vector-set!
))
(define basiclibs-proc-vector
(vector
* + - / < <= = > >= abs append apply assoc assq assv
binary-port? boolean=? boolean? bytevector bytevector-append bytevector-copy
bytevector-copy! bytevector-length bytevector-u8-ref bytevector-u8-set!
bytevector? caar cadr call-with-current-continuation call-with-port
call-with-values call/cc car cdar cddr cdr ceiling char->integer
char<=? char<? char=? char>=? char>? char? close-input-port
close-output-port close-port complex?
cons current-error-port
current-input-port current-output-port
dynamic-wind eof-object eof-object? eq?
equal? eqv? error error-object-irritants error-object-message error-object?
even? exact exact-integer-sqrt exact-integer? exact? expt
file-error?
floor floor-quotient floor-remainder floor/ flush-output-port for-each gcd
get-output-bytevector get-output-string
inexact inexact? input-port-open? input-port? integer->char integer? lcm
length
list list->string list->vector list-copy list-ref list-set! list-tail list?
make-bytevector make-list make-parameter make-string make-vector map max member
memq memv min modulo negative? newline not null? number->string number?
odd? open-input-bytevector open-input-string open-output-bytevector
open-output-string output-port-open? output-port? pair?
peek-char peek-u8 port? positive? procedure? quotient raise
raise-continuable
read-bytevector read-bytevector!
read-char read-error? read-line read-string read-u8 real? remainder reverse
round set-car! set-cdr! square string string->list string->number
string->symbol string->utf8 string->vector string-append string-copy
string-copy! string-fill! string-for-each string-length string-map string-ref
string-set! string<=? string<? string=? string>=? string>? string? substring
symbol->string symbol=? symbol? textual-port? truncate
truncate-quotient truncate-remainder truncate/
utf8->string values vector vector->list vector->string
vector-append vector-copy vector-copy! vector-fill! vector-for-each
vector-length vector-map vector-ref vector-set! vector?
with-exception-handler write-bytevector write-char write-string write-u8 zero?
caaaar caaadr caaar caadar caaddr caadr cadaar cadadr cadar caddar cadddr caddr
cdaaar cdaadr cdaar cdadar cdaddr cdadr cddaar cddadr cddar cdddar cddddr cdddr
call-with-input-file call-with-output-file delete-file file-exists?
open-binary-input-file open-binary-output-file open-input-file
open-output-file with-input-from-file with-output-to-file
acos asin atan cos exp finite? log nan? sin sqrt tan
command-line exit get-environment-variable
read
display write write-simple
)
)
(define basiclibs-name-vector
'#(
* + - / < <= = > >= abs append apply assoc assq assv
binary-port? boolean=? boolean? bytevector bytevector-append bytevector-copy
bytevector-copy! bytevector-length bytevector-u8-ref bytevector-u8-set!
bytevector? caar cadr call-with-current-continuation call-with-port
call-with-values call/cc car cdar cddr cdr ceiling char->integer
char<=? char<? char=? char>=? char>? char? close-input-port
close-output-port close-port complex?
cons current-error-port
current-input-port current-output-port
dynamic-wind eof-object eof-object? eq?
equal? eqv? error error-object-irritants error-object-message error-object?
even? exact exact-integer-sqrt exact-integer? exact? expt
file-error?
floor floor-quotient floor-remainder floor/ flush-output-port for-each gcd
get-output-bytevector get-output-string
inexact inexact? input-port-open? input-port? integer->char integer? lcm
length
list list->string list->vector list-copy list-ref list-set! list-tail list?
make-bytevector make-list make-parameter make-string make-vector map max member
memq memv min modulo negative? newline not null? number->string number?
odd? open-input-bytevector open-input-string open-output-bytevector
open-output-string output-port-open? output-port? pair?
peek-char peek-u8 port? positive? procedure? quotient raise
raise-continuable
read-bytevector read-bytevector!
read-char read-error? read-line read-string read-u8 real? remainder reverse
round set-car! set-cdr! square string string->list string->number
string->symbol string->utf8 string->vector string-append string-copy
string-copy! string-fill! string-for-each string-length string-map string-ref
string-set! string<=? string<? string=? string>=? string>? string? substring
symbol->string symbol=? symbol? textual-port? truncate
truncate-quotient truncate-remainder truncate/
utf8->string values vector vector->list vector->string
vector-append vector-copy vector-copy! vector-fill! vector-for-each
vector-length vector-map vector-ref vector-set! vector?
with-exception-handler write-bytevector write-char write-string write-u8 zero?
caaaar caaadr caaar caadar caaddr caadr cadaar cadadr cadar caddar cadddr caddr
cdaaar cdaadr cdaar cdadar cdaddr cdadr cddaar cddadr cddar cdddar cddddr cdddr
call-with-input-file call-with-output-file delete-file file-exists?
open-binary-input-file open-binary-output-file open-input-file
open-output-file with-input-from-file with-output-to-file
acos asin atan cos exp finite? log nan? sin sqrt tan
command-line exit get-environment-variable
read
display write write-simple
)
)
)
| false |
201828dcf8cc85e88265a54ed90576e201fc7e56
|
1d9792d06f4a2f1200317a340be9abc3e7ae5e8b
|
/swap.scm
|
564f1a7a89b25cf495b309632e41f756446646bd
|
[
"MIT"
] |
permissive
|
Wilfred/comparative_macrology
|
4caf8c2efafa8cda58a8626c2b33e22e136cbcc2
|
523fa1543a285a4af78a0276fb39d526fc723733
|
refs/heads/master
| 2016-09-06T18:34:43.757407 | 2014-09-27T15:00:43 | 2014-09-27T15:00:43 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 182 |
scm
|
swap.scm
|
(define-syntax swap!
(syntax-rules ()
((swap x y)
(let ((tmp x))
(set! x y)
(set! y tmp)))))
(define a 1)
(define b 2)
(swap! a b)
(display a)
(display b)
| true |
5c08a04150affa350bbe61f0f01ff57fabed7dca
|
3195f36520cf39e7bb2f3f4455f354ce327302c2
|
/s/fxmap.ss
|
d069a6ed377200cffd12ac23c61eadbecccd94a3
|
[
"Apache-2.0"
] |
permissive
|
racket/ChezScheme
|
d882355f22f91adbf2decfc0a39c9ce6fd2ac6c6
|
73b4ec3c21207a72d1e9cafee9cfb8e6c2e7d3e3
|
refs/heads/master
| 2023-09-04T21:08:27.269433 | 2023-09-01T23:33:53 | 2023-09-03T19:28:38 | 171,331,531 | 109 | 17 |
Apache-2.0
| 2023-08-22T22:35:31 | 2019-02-18T18:03:38 |
Scheme
|
UTF-8
|
Scheme
| false | false | 13,803 |
ss
|
fxmap.ss
|
;;; fxmap.ss
;;; Copyright 1984-2017 Cisco Systems, Inc.
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
;; Based on Okasaki and Gill's "Fast Mergeable Integer Maps" (1998).
(module fxmap
(fxmap?
empty-fxmap
fxmap-empty?
fxmap-count
fxmap-ref
fxmap-set
fxmap-remove
fxmap-remove/base
fxmap-reset/base
fxmap-advance/base
fxmap-for-each
fxmap-for-each/diff
fxmap-changes
;; internals
; $branch? make-$branch $branch-prefix $branch-mask $branch-left $branch-right
; $leaf? make-$leaf $leaf-key $leaf-val
;; We treat $empty as a singleton, so don't use these functions.
; $empty? make-$empty
)
;; record types
(define-record-type $branch
(fields prefix mask left right count changes)
(nongenerative #{$branch pfv8jpsat5jrk6vq7vclc3ntg-1})
(sealed #t))
(define-record-type $leaf
(fields key val changes)
(nongenerative #{$leaf pfv8jq2dzw50ox4f6vqm1ff5v-1})
(sealed #t))
(define-record-type $empty
(nongenerative #{$empty pfwk1nal7cs5dornqtzvda91m-0})
(sealed #t))
(define-syntax let-branch
(syntax-rules ()
[(_ ([(p m l r) d] ...) exp ...)
(let ([p ($branch-prefix d)] ...
[m ($branch-mask d)] ...
[l ($branch-left d)] ...
[r ($branch-right d)] ...)
exp ...)]))
;; constants & empty
(define empty-fxmap (make-$empty))
(define (fxmap-empty? x) (eq? empty-fxmap x))
;; predicate
(define (fxmap? x)
(or ($branch? x)
($leaf? x)
(eq? empty-fxmap x)))
;; count & changes
(define (fxmap-count d)
(cond
[($branch? d)
($branch-count d)]
[($leaf? d) 1]
[else 0]))
(define (fxmap-changes d)
(cond
[($branch? d)
($branch-changes d)]
[($leaf? d)
($leaf-changes d)]
[else 0]))
;; ref
(define (fxmap-ref/leaf d key)
(cond
[($branch? d)
(let-branch ([(p m l r) d])
(cond
[(fx<= key p)
(fxmap-ref/leaf l key)]
[else
(fxmap-ref/leaf r key)]))]
[($leaf? d)
(if (fx= key ($leaf-key d))
d
#f)]
[else
#f]))
(define (fxmap-ref d key default)
(let ([d (fxmap-ref/leaf d key)])
(if d
($leaf-val d)
default)))
(define (fxmap-ref/changes d key)
(let ([d (fxmap-ref/leaf d key)])
(if d
($leaf-changes d)
0)))
;; set
(define (fxmap-set/changes d key val changes)
(cond
[($branch? d)
(let-branch ([(p m l r) d])
(cond
[(nomatch? key p m)
(join key (make-$leaf key val (or changes 1)) p d)]
[(fx<= key p)
(br p m (fxmap-set/changes l key val changes) r)]
[else
(br p m l (fxmap-set/changes r key val changes))]))]
[($leaf? d)
(let ([k ($leaf-key d)])
(if (fx= key k)
(make-$leaf key val (or changes (fx+ ($leaf-changes d) 1)))
(join key (make-$leaf key val (or changes 1)) k d)))]
[else
(make-$leaf key val (or changes 1))]))
(define (fxmap-set d key val)
(fxmap-set/changes d key val #f))
;; remove
(define (fxmap-remove d key)
(cond
[($branch? d)
(let-branch ([(p m l r) d])
(cond
[(nomatch? key p m) d]
[(fx<= key p) (br* p m (fxmap-remove l key) r)]
[else (br* p m l (fxmap-remove r key))]))]
[($leaf? d)
(if (fx= key ($leaf-key d))
empty-fxmap
d)]
[else
empty-fxmap]))
(define (fxmap-remove/base d key base)
; Remove key from d, but try to reuse the branches from base when possible
; instead of creating new ones.
; TODO: This assumes that all the keys in base are in d too.
; Perhaps this restriction can be removed.
(cond
[($branch? base)
(cond
[($branch? d)
(let-branch ([(p0 m0 l0 r0) base]
[(p m l r) d])
(let ([sub-base (cond
[(fx< m0 m) base]
[(fx<= key p0) l0]
[else r0])])
(cond
[(nomatch? key p m)
d]
[(fx<= key p)
(br*/base p m (fxmap-remove/base l key sub-base) r base)]
[else
(br*/base p m l (fxmap-remove/base r key sub-base) base)])))]
[($leaf? d)
(if (fx= key ($leaf-key d))
empty-fxmap
d)]
[else
empty-fxmap])]
[else
(fxmap-remove d key)]))
;; reset and advance
(define (fxmap-reset/base d key base)
; Reset key in d to the value it has in base, but try to reuse the branches
; from base when possible instead of creating new ones.
; TODO: This assumes that all the keys in base are in d too.
; Perhaps this restriction can be removed.
(cond
[($branch? d)
(let-branch ([(p m l r) d])
(let ([sub-base (cond
[($branch? base)
(let-branch ([(p0 m0 l0 r0) base])
(cond
[(fx< m0 m) base]
[(fx<= key p0) l0]
[else r0]))]
[else base])])
(cond
[(nomatch? key p m)
d]
[(fx<= key p)
(br*/base p m (fxmap-reset/base l key sub-base) r base)]
[else
(br*/base p m l (fxmap-reset/base r key sub-base) base)])))]
[(and ($leaf? d)
(fx= key ($leaf-key d))
($leaf? base)
(fx= key ($leaf-key base)))
base]
[else
(error 'fxmap-reset/base "")]))
(define (fxmap-advance/base d key base)
(let ([changes (fx+ (fxmap-ref/changes base key) 1)]
[l (fxmap-ref/leaf d key)])
(if l
(if (fx= changes ($leaf-changes l))
d
(fxmap-set/changes d key ($leaf-val l) changes))
(error 'fxmap-advance/base ""))))
;; set and remove utilities
(define-syntax define-syntax-rule
(syntax-rules ()
[(_ (name arg ...) e ...)
(define-syntax name
(syntax-rules ()
[(_ arg ...) e ...]))]))
(define (br p m l r)
(make-$branch p m l r
(fx+ (fxmap-count l) (fxmap-count r))
(fx+ (fxmap-changes l) (fxmap-changes r))))
(define (br* p m l r)
(cond [(eq? empty-fxmap r) l]
[(eq? empty-fxmap l) r]
[else (br p m l r)]))
(define (br*/base p m l r base)
(cond [(eq? empty-fxmap r) l]
[(eq? empty-fxmap l) r]
[(and ($branch? base)
(eq? l ($branch-left base))
(eq? r ($branch-right base)))
base]
[else (br p m l r)]))
(define (join p0 d0 p1 d1)
(let ([m (branching-bit p0 p1)])
(if (fx<= p0 p1)
(br (mask p0 m) m d0 d1)
(br (mask p0 m) m d1 d0))))
(define (join* p1 d1 p2 d2)
(cond
[(eq? empty-fxmap d1) d2]
[(eq? empty-fxmap d2) d1]
[else (join p1 d1 p2 d2)]))
(define (branching-bit p m)
(highest-set-bit (fxxor p m)))
(define-syntax-rule (mask h m)
(fxand (fxior h (fx1- m)) (fxnot m)))
(define highest-set-bit
(if (fx= (fixnum-width) 61)
(lambda (x1)
(let* ([x2 (fxior x1 (fxsrl x1 1))]
[x3 (fxior x2 (fxsrl x2 2))]
[x4 (fxior x3 (fxsrl x3 4))]
[x5 (fxior x4 (fxsrl x4 8))]
[x6 (fxior x5 (fxsrl x5 16))]
[x7 (fxior x6 (fxsrl x6 32))])
(fxxor x7 (fxsrl x7 1))))
(lambda (x1)
(let* ([x2 (fxior x1 (fxsrl x1 1))]
[x3 (fxior x2 (fxsrl x2 2))]
[x4 (fxior x3 (fxsrl x3 4))]
[x5 (fxior x4 (fxsrl x4 8))]
[x6 (fxior x5 (fxsrl x5 16))])
(fxxor x6 (fxsrl x6 1))))))
(define-syntax-rule (nomatch? h p m)
(not (fx= (mask h m) p)))
;; merge
(define (fxmap-merge bin f id g1 g2 d1 d2)
(define-syntax go
(syntax-rules ()
[(_ d1 d2) (fxmap-merge bin f id g1 g2 d1 d2)]))
(cond
[(eq? d1 d2) (id d1)]
[($branch? d1)
(cond
[($branch? d2)
(let-branch ([(p1 m1 l1 r1) d1]
[(p2 m2 l2 r2) d2])
(cond
[(fx> m1 m2) (cond
[(nomatch? p2 p1 m1) (join* p1 (g1 d1) p2 (g2 d2))]
[(fx<= p2 p1) (bin p1 m1 (go l1 d2) (g1 r1))]
[else (bin p1 m1 (g1 l1) (go r1 d2))])]
[(fx> m2 m1) (cond
[(nomatch? p1 p2 m2) (join* p1 (g1 d1) p2 (g2 d2))]
[(fx<= p1 p2) (bin p2 m2 (go d1 l2) (g2 r2))]
[else (bin p2 m2 (g2 l2) (go d1 r2))])]
[(fx= p1 p2) (bin p1 m1 (go l1 l2) (go r1 r2))]
[else (join* p1 (g1 d1) p2 (g2 d2))]))]
[($leaf? d2)
(let ([k2 ($leaf-key d2)])
(let merge0 ([d1 d1])
(cond
[(eq? d1 d2)
(id d1)]
[($branch? d1)
(let-branch ([(p1 m1 l1 r1) d1])
(cond [(nomatch? k2 p1 m1) (join* p1 (g1 d1) k2 (g2 d2))]
[(fx<= k2 p1) (bin p1 m1 (merge0 l1) (g1 r1))]
[else (bin p1 m1 (g1 l1) (merge0 r1))]))]
[($leaf? d1)
(let ([k1 ($leaf-key d1)])
(cond [(fx= k1 k2) (f d1 d2)]
[else (join* k1 (g1 d1) k2 (g2 d2))]))]
[else ; (eq? empty-fxmap d1)
(g2 d2)])))]
[else ; (eq? empty-fxmap d2)
(g1 d1)])]
[($leaf? d1)
(let ([k1 ($leaf-key d1)])
(let merge0 ([d2 d2])
(cond
[(eq? d1 d2)
(id d1)]
[($branch? d2)
(let-branch ([(p2 m2 l2 r2) d2])
(cond [(nomatch? k1 p2 m2) (join* k1 (g1 d1) p2 (g2 d2))]
[(fx<= k1 p2) (bin p2 m2 (merge0 l2) (g2 r2))]
[else (bin p2 m2 (g2 l2) (merge0 r2))]))]
[($leaf? d2)
(let ([k2 ($leaf-key d2)])
(cond [(fx= k1 k2) (f d1 d2)]
[else (join* k1 (g1 d1) k2 (g2 d2))]))]
[else ; (eq? empty-fxmap d2)
(g1 d1)])))]
[else ; (eq? empty-fxmap d1)
(g2 d2)]))
;; merge*
; like merge, but the result is (void)
(define (fxmap-merge* f id g1 g2 d1 d2)
(define (merge* f id g1 g2 d1 d2)
(define-syntax go
(syntax-rules ()
[(_ d1 d2) (merge* f id g1 g2 d1 d2)]))
(cond
[(eq? d1 d2) (id d1)]
[($branch? d1)
(cond
[($branch? d2)
(let-branch ([(p1 m1 l1 r1) d1]
[(p2 m2 l2 r2) d2])
(cond
[(fx> m1 m2) (cond
[(nomatch? p2 p1 m1) (g1 d1) (g2 d2)]
[(fx<= p2 p1) (go l1 d2) (g1 r1)]
[else (g1 l1) (go r1 d2)])]
[(fx> m2 m1) (cond
[(nomatch? p1 p2 m2) (g1 d1) (g2 d2)]
[(fx<= p1 p2) (go d1 l2) (g2 r2)]
[else (g2 l2) (go d1 r2)])]
[(fx= p1 p2) (go l1 l2) (go r1 r2)]
[else (g1 d1) (g2 d2)]))]
[else ; ($leaf? d2)
(let ([k2 ($leaf-key d2)])
(let merge*0 ([d1 d1])
(cond
[(eq? d1 d2)
(id d1)]
[($branch? d1)
(let-branch ([(p1 m1 l1 r1) d1])
(cond [(nomatch? k2 p1 m1) (g1 d1) (g2 d2)]
[(fx<= k2 p1) (merge*0 l1) (g1 r1)]
[else (g1 l1) (merge*0 r1)]))]
[else ; ($leaf? d1)
(let ([k1 ($leaf-key d1)])
(cond [(fx= k1 k2) (f d1 d2)]
[else (g1 d1) (g2 d2)]))])))])]
[($leaf? d1)
(let ([k1 ($leaf-key d1)])
(let merge*0 ([d2 d2])
(cond
[(eq? d1 d2)
(id d1)]
[($branch? d2)
(let-branch ([(p2 m2 l2 r2) d2])
(cond [(nomatch? k1 p2 m2) (g1 d1) (g2 d2)]
[(fx<= k1 p2) (merge*0 l2) (g2 r2)]
[else (g2 l2) (merge*0 r2)]))]
[else ; ($leaf? d2)
(let ([k2 ($leaf-key d2)])
(cond [(fx= k1 k2) (f d1 d2)]
[else (g1 d1) (g2 d2)]))])))]))
(cond
[(eq? d1 d2)
(id d1)]
[(eq? empty-fxmap d1)
(g2 d2)]
[(eq? empty-fxmap d2)
(g1 d1)]
[else
(merge* f id g1 g2 d1 d2)])
(void))
;; for-each
(define (fxmap-for-each g1 d1)
(cond
[($branch? d1)
(fxmap-for-each g1 ($branch-left d1))
(fxmap-for-each g1 ($branch-right d1))]
[($leaf? d1)
(g1 ($leaf-key d1) ($leaf-val d1))]
[else ; (eq? empty-fxmap d1)
(void)])
(void))
(define (fxmap-for-each/diff f g1 g2 d1 d2)
(fxmap-merge* (lambda (x y) (f ($leaf-key x) ($leaf-val x) ($leaf-val y)))
(lambda (x) (void))
(lambda (x) (fxmap-for-each g1 x))
(lambda (x) (fxmap-for-each g2 x))
d1
d2)
(void))
)
| true |
7683b31d23a39d66680a0a811807842786d527c7
|
f5083e14d7e451225c8590cc6aabe68fac63ffbd
|
/cs/01-Programming/cs61a/course/library/resist.scm
|
42c0e6bed9a88a0fc0b3cb3b43af0b56f3caaeed
|
[] |
no_license
|
Phantas0s/playground
|
a362653a8feb7acd68a7637334068cde0fe9d32e
|
c84ec0410a43c84a63dc5093e1c214a0f102edae
|
refs/heads/master
| 2022-05-09T06:33:25.625750 | 2022-04-19T14:57:28 | 2022-04-19T14:57:28 | 136,804,123 | 19 | 5 | null | 2021-03-04T14:21:07 | 2018-06-10T11:46:19 |
Racket
|
UTF-8
|
Scheme
| false | false | 1,774 |
scm
|
resist.scm
|
(define (make-resistor resistance)
(attach-type 'resistor resistance))
(define (resistor? ckt)
(eq? (type ckt) 'resistor))
(define (make-series ckt1 ckt2)
(attach-type 'series (list ckt1 ckt2)))
(define (series? ckt)
(eq? (type ckt) 'series))
(define (make-parallel ckt1 ckt2)
(attach-type 'parallel (list ckt1 ckt2)))
(define (parallel? ckt)
(eq? (type ckt) 'parallel))
(define (resistance ckt)
(cond ((resistor? ckt)
(resistance-resistor (contents ckt)))
((parallel? ckt)
(resistance-parallel (contents ckt)))
((series? ckt)
(resistance-series (contents ckt)))))
(define (conductance ckt)
(cond ((resistor? ckt)
(conductance-resistor (contents ckt)))
((parallel? ckt)
(conductance-parallel (contents ckt)))
((series? ckt)
(conductance-series (contents ckt)))))
(define (resistance-resistor resistor)
resistor)
(define (conductance-resistor resistor)
(/ 1 (resistance-resistor resistor)))
(define (resistance-series ckt)
(+ (resistance (left-branch ckt))
(resistance (right-branch ckt))))
(define (conductance-series ckt)
(/ 1 (resistance-series ckt)))
(define (conductance-parallel ckt)
(+ (conductance (left-branch ckt))
(conductance (right-branch ckt))))
(define (resistance-parallel ckt)
(/ 1 (conductance-parallel ckt)))
(define left-branch car)
(define right-branch cadr)
(define attach-type cons)
(define type car)
(define contents cdr)
(define (repeated f n)
(lambda (x)
(if (= n 0)
x
((repeated f (-1+ n)) (f x)))))
(define (L-extend base series-part parallel-part)
(make-series series-part (make-parallel parallel-part base)))
(define (ladder-extension stages base series-part parallel-part)
((repeated (lambda (x) (L-extend x series-part parallel-part)) stages)
base))
| false |
a35883687d78e30836c3e825750f727f83848023
|
ee232691dcbaededacb0778247f895af992442dd
|
/kirjasto/lib/kaava/liferea.scm
|
3ac9d3c94dc1c715da313d2cb34965d975696d87
|
[] |
no_license
|
mytoh/panna
|
c68ac6c6ef6a6fe79559e568d7a8262a7d626f9f
|
c6a193085117d12a2ddf26090cacb1c434e3ebf9
|
refs/heads/master
| 2020-05-17T02:45:56.542815 | 2013-02-13T19:18:38 | 2013-02-13T19:18:38 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 340 |
scm
|
liferea.scm
|
(use panna.kaava)
(kaava "liferea")
(homepage "liferea.sourceforge.net")
(repository "git://liferea.git.sourceforge.net/gitroot/liferea/liferea")
(define (install tynnyri)
(system
'(gmake clean)
'(gmake distclean)
'(./autogen.sh)
`(./configure ,(string-append "--prefix=" tynnyri))
'(gmake)
'(gmake install)
))
| false |
52fe17ff0df16355994d07e772674301e5203844
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/System.Xml/system/xml/xpath/relational-expr.sls
|
effe87d604c4d7c9da73ec0b57b0264bd0520600
|
[] |
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,001 |
sls
|
relational-expr.sls
|
(library (system xml xpath relational-expr)
(export new
is?
relational-expr?
compare?
evaluate-boolean?
static-value-as-boolean?)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...) #'(clr-new System.Xml.XPath.RelationalExpr a ...)))))
(define (is? a) (clr-is System.Xml.XPath.RelationalExpr a))
(define (relational-expr? a)
(clr-is System.Xml.XPath.RelationalExpr a))
(define-method-port
compare?
System.Xml.XPath.RelationalExpr
Compare
(System.Boolean System.Double System.Double System.Boolean)
(System.Boolean System.Double System.Double))
(define-method-port
evaluate-boolean?
System.Xml.XPath.RelationalExpr
EvaluateBoolean
(System.Boolean System.Xml.XPath.BaseIterator))
(define-field-port
static-value-as-boolean?
#f
#f
(property:)
System.Xml.XPath.RelationalExpr
StaticValueAsBoolean
System.Boolean))
| true |
3beb394b466e394b6787e3798c924e45e854f854
|
91a185b4ddebe85dce2ff5d2eacac55704d8af4d
|
/Lab3/b17069-lab3/q2.scm
|
4fe72cb6c169a3f5479b9b5e4357158f6ddc1d16
|
[] |
no_license
|
vsvipul/CS302-PoP
|
1ca80c301a3618e72ace6263bb90609a8880de3e
|
7d8811dd536bae2f804d7b06c9308f0377bd18f5
|
refs/heads/main
| 2023-06-05T21:00:03.523078 | 2021-06-22T15:15:00 | 2021-06-22T15:15:00 | 379,312,189 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 325 |
scm
|
q2.scm
|
#lang sicp
(define (make-monitored f)
(define times 0)
(define (mf x)
(if (eq? x 'how-many-calls?) times
(begin (set! times (+ times 1))
(f x))))
mf)
;(define s (make-monitored sqrt))
;(s 100)
;(s 10)
;(s 5)
;(define p (make-monitored sqrt))
;(p 100)
;(p 10)
;(p 'how-many-calls?)
| false |
060dc1c3172573c03e299749bdf1dd33f794df41
|
6d875d9eb248e3faa5b805ec74e4ef0095542354
|
/Ex3_53.scm
|
9fc8c2b71b9fb72c3633f64e27e897ebf12f92d5
|
[] |
no_license
|
cuihz/sicp
|
095d6661109075581710f37c5ded7a4525cb41d2
|
0392da93897105ced52060baedb153266babe6ec
|
refs/heads/master
| 2016-08-04T18:01:13.515086 | 2015-07-09T13:30:04 | 2015-07-09T13:30:04 | 29,767,016 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,494 |
scm
|
Ex3_53.scm
|
(define stream-null? null?)
(define the-empty-stream '())
(define stream-car
(lambda (s)
(car (force s))))
(define stream-cdr
(lambda (s)
(cdr (force s))))
(define (stream-map proc . argstreams)
(if (stream-null? (car argstreams))
the-empty-stream
(delay (cons
(apply proc (map stream-car argstreams))
(apply stream-map
(cons proc (map stream-cdr argstreams)))))))
(define (stream-enumerate-interval low high)
(if (> low high)
the-empty-stream
(delay (cons
low
(stream-enumerate-interval (+ low 1) high)))))
(define (stream-ref s n)
(if (= n 0)
(stream-car s)
(stream-ref (stream-cdr s) (- n 1))))
(define (stream-filter pred stream)
(cond ((stream-null? stream) the-empty-stream)
((pred (stream-car))
(delay (cons (stream-car stream)
(stream-filter pred
(stream-cdr stream)))))
(else (stream-filter pred (stream-cdr stream)))))
(define (add-stream s1 s2)
(stream-map + s1 s2))
;;; 2的n次幂
(define s (delay (cons 1 (add-stream s s))))
(stream-ref s 4)
;; Ex3_54
(define (integer-starting-from n)
(delay (cons n (integer-starting-from (+ n 1)))))
(define integers (integer-starting-from 1))
(define (mul-stream s1 s2)
(stream-map * s1 s2))
(define factorials (delay (cons 1 (mul-stream factorials (stream-cdr integers)))))
(stream-ref factorials 3)
;; Ex3_55
(define (partial-sums s)
(delay
(cons (stream-car s)
(add-stream (stream-cdr s) (partial-sums s)))))
(stream-ref (partial-sums integers) 3)
;; Ex3_56
(define (scale-stream stream factor)
(stream-map (lambda (x) (* x factor)) stream))
(define (merge s1 s2)
(cond ((stream-null? s1) s2)
((stream-null? s2) s1)
(else
(let ((s1car (stream-car s1))
(s2car (stream-car s2)))
(cond ((< s1car s2car)
(delay (cons s1car
(merge (stream-cdr s1) s2))))
((> s1car s2car)
(delay (cons s2car
(merge s1 (stream-cdr s2)))))
(else
(delay (cons s1car
(merge (stream-cdr s1)
(stream-cdr s2))))))))))
(define S (delay (cons 1 (merge (merge (scale-stream S 2) (scale-stream S 3))
(scale-stream S 5)))))
;; Ex3_59
(define ones (delay (cons 1 ones)))
(define (integrate-series s)
(stream-map * (stream-map / ones integers) s))
(define sine-series (delay
(cons 0 (integrate-series cosine-series))))
(define cosine-series (delay
(cons 1 (integrate-series (scale-stream
sine-series
-1)))))
| false |
3196d09af152bcc9ade2d996c3a50d8d9bb2c7ac
|
ea9fdab491ca277959f7dc59004d1a30c4ee6be4
|
/gauche-pib/patches/patch-lib_pib.scm
|
2ef672699f74fc272792ea7cdd269327b26e7f26
|
[] |
no_license
|
NetBSD/pkgsrc-wip
|
99f40fb6f56e2a5a11840a810e9cf8b6097e7f21
|
c94e923855e9515400435b2437a1659fdb26d2fb
|
refs/heads/master
| 2023-08-30T14:27:26.946664 | 2023-08-30T12:09:15 | 2023-08-30T12:09:15 | 42,824,785 | 81 | 59 | null | 2021-01-28T20:10:38 | 2015-09-20T18:44:07 |
Makefile
|
EUC-JP
|
Scheme
| false | false | 6,346 |
scm
|
patch-lib_pib.scm
|
$NetBSD: patch-lib_pib.scm,v 1.2 2015/05/28 05:38:12 phonohawk Exp $
Fix a race-condition on the send queue:
https://github.com/ayamada/copy-of-svn.tir.jp/pull/1
--- lib/pib.scm.orig 2009-09-28 16:03:37.000000000 +0000
+++ lib/pib.scm
@@ -461,10 +461,6 @@
:accessor irc-recv-cv-of)
(irc-send-cv
:accessor irc-send-cv-of)
- (irc-recv-cv-mutex
- :accessor irc-recv-cv-mutex-of)
- (irc-send-cv-mutex
- :accessor irc-send-cv-mutex-of)
(irc-send-laststatus
:accessor irc-send-laststatus-of)
(irc-send-last-microsec
@@ -509,23 +505,23 @@
(define-method %irc-recv-event! ((self <pib>) . opts)
(let-optionals* opts ((timeout 0))
(let loop ()
- (mutex-lock! (irc-recv-cv-mutex-of self))
+ (mutex-lock! (irc-recv-queue-mutex-of self))
(let1 event (irc-recv-dequeue! self)
(if (or event (equal? timeout 0))
;; キューに値が入ってきた or timeoutが0だった。
;; 処理して普通にアンロックして終了
(begin
- (mutex-unlock! (irc-recv-cv-mutex-of self))
+ (mutex-unlock! (irc-recv-queue-mutex-of self))
event)
;; eventは#fだった。つまり、キューは空だった
(let1 start-usec (gettimeofday-usec)
;; 受信スレッドが既にeofを受け取って終了していたなら、
;; ここでエラー例外を投げる必要がある
(when (irc-finished?-of self)
- (mutex-unlock! (irc-recv-cv-mutex-of self))
+ (mutex-unlock! (irc-recv-queue-mutex-of self))
(error "irc socket already closed"))
;; キューが空なので、タイムアウト有りでcvシグナルを待つ
- (if (not (mutex-unlock! (irc-recv-cv-mutex-of self)
+ (if (not (mutex-unlock! (irc-recv-queue-mutex-of self)
(irc-recv-cv-of self)
timeout))
;; タイムアウトした
@@ -750,19 +746,19 @@
;; キューが空の時は#fを返す(キューに#fが入っている事は無いものとする)
(define-method irc-send-dequeue! ((self <pib>))
- (with-locking-mutex
- (irc-send-queue-mutex-of self)
- (lambda ()
- (if (queue-empty? (irc-send-queue-of self))
+ (let1 state (mutex-state (irc-send-queue-mutex-of self))
+ (unless (eq? state (current-thread))
+ (error "assertion failed: irc-send-queue-mutex is not locked by the caller:" state))
+ (if (queue-empty? (irc-send-queue-of self))
#f
- (dequeue! (irc-send-queue-of self))))))
+ (dequeue! (irc-send-queue-of self)))))
(define-method irc-recv-dequeue! ((self <pib>))
- (with-locking-mutex
- (irc-recv-queue-mutex-of self)
- (lambda ()
- (if (queue-empty? (irc-recv-queue-of self))
+ (let1 state (mutex-state (irc-recv-queue-mutex-of self))
+ (unless (eq? state (current-thread))
+ (error "assertion failed: irc-recv-queue-mutex is not locked by the caller:" state))
+ (if (queue-empty? (irc-recv-queue-of self))
#f
- (dequeue! (irc-recv-queue-of self))))))
+ (dequeue! (irc-recv-queue-of self)))))
(define-method irc-send-enqueue! ((self <pib>) event)
;; 送信キューは、この時点で一旦変換を行い、エラーが出ない事を確認する
@@ -855,7 +851,7 @@
(define-method %irc-send-thread ((self <pib>))
(let loop ()
- (mutex-lock! (irc-send-cv-mutex-of self))
+ (mutex-lock! (irc-send-queue-mutex-of self))
(let* ((event (and-let* ((e (irc-send-dequeue! self)))
(send-event-split-last-param e)))
(message (and
@@ -868,7 +864,7 @@
(cond
;((eq? message 'shutdown) #f) ; 終了(旧コード)
((not message) ; キューが空だった(cvシグナルを待つ)
- (mutex-unlock! (irc-send-cv-mutex-of self) (irc-send-cv-of self))
+ (mutex-unlock! (irc-send-queue-mutex-of self) (irc-send-cv-of self))
(loop)) ; cvシグナル受信。キューチェックの段階から再実行する
(else ; 通常messageだった
;; まず、(irc-send-last-microsec-of self)をチェックし、
@@ -883,7 +879,7 @@
(dynamic-wind
(lambda ()
;; 一旦アンロックする
- (mutex-unlock! (irc-send-cv-mutex-of self)))
+ (mutex-unlock! (irc-send-queue-mutex-of self)))
(lambda ()
;; 待つ
;; TODO: ここは将来、cthreadsに対応した際に、
@@ -892,7 +888,7 @@
(selector-select (make <selector>) remain))
(lambda ()
;; 再度ロックする
- (mutex-lock! (irc-send-cv-mutex-of self)))))))
+ (mutex-lock! (irc-send-queue-mutex-of self)))))))
;; 送信する
(guard (e (else
(set! (irc-send-laststatus-of self) 'error)
@@ -919,7 +915,7 @@
(cdddr event))
(logging self sent-event))
;; アンロックする
- (mutex-unlock! (irc-send-cv-mutex-of self))
+ (mutex-unlock! (irc-send-queue-mutex-of self))
(loop))))))
(define-method %irc-pong-thread ((self <pib>))
@@ -1100,10 +1096,6 @@
(make-condition-variable "recv"))
(set! (irc-send-cv-of pib)
(make-condition-variable "send"))
- (set! (irc-recv-cv-mutex-of pib)
- (make-mutex "recv-cv"))
- (set! (irc-send-cv-mutex-of pib)
- (make-mutex "send-cv"))
(set! (irc-send-laststatus-of pib) 'ok)
(set! (irc-send-last-microsec-of pib) 0)
(set! (irc-logger-mutex-of pib)
@@ -1177,8 +1169,6 @@
(set! (irc-send-queue-mutex-of pib) #f)
(set! (irc-recv-cv-of pib) #f)
(set! (irc-send-cv-of pib) #f)
- (set! (irc-recv-cv-mutex-of pib) #f)
- (set! (irc-send-cv-mutex-of pib) #f)
(set! (irc-send-laststatus-of pib) #f)
(set! (irc-send-last-microsec-of pib) #f)
(set! (irc-logger-mutex-of pib) #f)
| false |
d4fac4d873e022495e875d73f56f968d78aebcb5
|
ee232691dcbaededacb0778247f895af992442dd
|
/kirjasto/lib/kaava/chicken.scm
|
bd9c4931a98042c768b9cd847d28d23126f99406
|
[] |
no_license
|
mytoh/panna
|
c68ac6c6ef6a6fe79559e568d7a8262a7d626f9f
|
c6a193085117d12a2ddf26090cacb1c434e3ebf9
|
refs/heads/master
| 2020-05-17T02:45:56.542815 | 2013-02-13T19:18:38 | 2013-02-13T19:18:38 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 437 |
scm
|
chicken.scm
|
;;; -*- coding: utf-8 -*-
(use panna.kaava)
(kaava "chicken")
(homepage "code.call-cc.org")
(repository "git://code.call-cc.org/chicken-core")
(cond
((is-freebsd)
(define (install tynnyri)
(system
`(gmake PLATFORM=bsd spotless)
`(gmake PLATFORM=bsd ,(string-append "PREFIX=" tynnyri)
install)
`(gmake PLATFORM=bsd confclean)
)))
(else
(print "not supprted platform sorry")))
| false |
84a917e34b97f2d3a45f3590ea25d38a417f9fa5
|
df0ba5a0dea3929f29358805fe8dcf4f97d89969
|
/exercises/informatics-2/05-lists/length.scm
|
fa2c817c3dfee829aeff4a82656fd62b80e2f041
|
[
"MIT"
] |
permissive
|
triffon/fp-2019-20
|
1c397e4f0bf521bf5397f465bd1cc532011e8cf1
|
a74dcde683538be031186cf18367993e70dc1a1c
|
refs/heads/master
| 2021-12-15T00:32:28.583751 | 2021-12-03T13:57:04 | 2021-12-03T13:57:04 | 210,043,805 | 14 | 31 |
MIT
| 2019-12-23T23:39:09 | 2019-09-21T19:41:41 |
Racket
|
UTF-8
|
Scheme
| false | false | 411 |
scm
|
length.scm
|
(require rackunit rackunit/text-ui)
(define length-tests
(test-suite
"Tests for length"
(check = (length '()) 0)
(check = (length '(2)) 1)
(check = (length '(1 2)) 2)
(check = (length '(3 4 1)) 3)
(check = (length '(5 3 5 5)) 4)
(check = (length '(8 4 92 82 8)) 5)
(check = (length '(8 4 82 12 31 133)) 6)
(check = (length (range 0 42)) 42)))
(run-tests length-tests)
| false |
c93e6aa3c390bebd58da8125cf7cb32212ec055a
|
0011048749c119b688ec878ec47dad7cd8dd00ec
|
/src/013/solution.scm
|
705b754c55e3f394e84decf25cd8acbba2f29f8f
|
[
"0BSD"
] |
permissive
|
turquoise-hexagon/euler
|
e1fb355a44d9d5f9aef168afdf6d7cd72bd5bfa5
|
852ae494770d1c70cd2621d51d6f1b8bd249413c
|
refs/heads/master
| 2023-08-08T21:01:01.408876 | 2023-07-28T21:30:54 | 2023-07-28T21:30:54 | 240,263,031 | 8 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 319 |
scm
|
solution.scm
|
(import
(chicken io))
(define (import-input)
(apply + (map string->number (read-lines))))
(define (number-length n)
(inexact->exact (ceiling (log n 10))))
(define (solve input)
(quotient input (expt 10 (- (number-length input) 10))))
(let ((_ (solve (import-input))))
(print _) (assert (= _ 5537376230)))
| false |
2883ae3acfa02bea21a220d65aa55649e0fa64e7
|
15b3f9425594407e43dd57411a458daae76d56f6
|
/bin/compiler/test/variable.scm
|
b79cbd7a30aee5dfe914989f25b652ce2856b276
|
[] |
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 | 30 |
scm
|
variable.scm
|
(define foo 1)
(display foo)
| false |
ed2f8136b516797667a36bb90983b1f79a2b5fd9
|
9ade40b4c752285122bc184fbd02b2280684c19b
|
/srfi-181-192/srfi/181/generic.scm
|
00c46be71c60c622c51383134b22be0d033051e6
|
[
"MIT"
] |
permissive
|
scheme-requests-for-implementation/srfi-192
|
3aeea83718d5d178af8d8e3e2a586e355d75b38a
|
fcf61311582916a365ba4d81ca3c8af5a81814e0
|
refs/heads/master
| 2022-12-10T09:11:06.198672 | 2020-09-08T22:39:26 | 2020-09-08T22:39:26 | 255,795,036 | 0 | 3 | null | 2020-09-08T22:39:27 | 2020-04-15T03:31:17 |
Scheme
|
UTF-8
|
Scheme
| false | false | 7,370 |
scm
|
generic.scm
|
;;;
;;; Generic implementation of custom ports.
;;;
;;; MIT License. See COPYING
;;;
(define-record-type custom-port
;; constructor (internal)
(%make-custom-port id binary? prefetch prefetch-pos buf
read! write! get-position set-position!
closer flusher)
;; predicate
custom-port?
;; port name
(id custom-port-id)
;; boolean flag
(binary? custom-port-binary?)
;; prefeched byte / char, for peek-u8/peek-char
(prefetch custom-port-prefetch custom-port-prefetch-set!)
;; saved the current pos before peek-char
;; can be (pos) or #f
(prefetch-pos custom-port-prefetch-pos custom-port-prefetch-pos-set!)
;; one-element bytevector or vector
(buf custom-port-buf)
;; handlers
(read! custom-port-read!)
(write! custom-port-write!)
(get-position custom-port-get-position)
(set-position! custom-port-set-position!)
(closer custom-port-closer)
(flusher custom-port-flusher))
(define-record-type custom-port-file-error
(%make-custom-port-file-error objs)
custom-port-file-error?
(objs custom-port-file-error-objs))
(define (boolean x) (not (not x)))
;;
;; Custom port internal interface
;;
;; (srfi 181 adapter) dispatches R7RS file operations on custom ports to
;; these internal APIs.
;;
(define (custom-port-has-port-position? port)
(assume (custom-port? port))
(boolean (custom-port-get-position port)))
(define (custom-port-has-set-port-position!? port)
(assume (custom-port? port))
(boolean (custom-port-set-position! port)))
(define (%call-get-position port)
(if (custom-port-get-position port)
((custom-port-get-position port))
0))
(define (%call-set-position! port pos)
(when (custom-port-set-position! port)
((custom-port-set-position! port) pos)))
(define (custom-port-position port)
(assume (and (custom-port? port)
(custom-port-get-position port)))
(if (custom-port-binary? port)
(if (custom-port-prefetch port)
(- (%call-get-position port) 1)
(%call-get-position port))
(or (custom-port-prefetch-pos port)
(%call-get-position port))))
(define (custom-port-set-port-position! port pos)
(assume (and (custom-port? port)
(custom-port-set-position! port)))
(custom-port-prefetch-set! port #f)
(custom-port-prefetch-pos-set! port #f)
(%call-set-position! port pos))
(define (custom-input-port? port)
(boolean (and (custom-port? port)
(custom-port-read! port))))
(define (custom-output-port? port)
(boolean (and (custom-port? port)
(custom-port-write! port))))
(define (custom-port-textual? port)
(not (custom-port-binary? port)))
(define (custom-port-read-u8 port)
(assume (and (custom-input-port? port)
(custom-port-binary? port)))
(let ((pre (custom-port-prefetch port)))
(if pre
(begin (custom-port-prefetch-set! port #f)
pre)
(let* ((buf (custom-port-buf port))
(nbytes ((custom-port-read! port) buf 0 1)))
(if (zero? nbytes)
(eof-object)
(bytevector-u8-ref buf 0))))))
(define (custom-port-peek-u8 port)
(or (custom-port-prefetch port)
(let* ((buf (custom-port-buf port))
(nbytes ((custom-port-read! port) buf 0 1)))
(if (zero? nbytes)
(eof-object)
(begin
(custom-port-prefetch-set! port (bytevector-u8-ref buf 0))
(bytevector-u8-ref buf 0))))))
(define (custom-port-read-char port)
(assume (and (custom-input-port? port)
(custom-port-textual? port)))
(let ((pre (custom-port-prefetch port)))
(if pre
(begin (custom-port-prefetch-set! port #f)
pre)
(let* ((buf (custom-port-buf port))
(nchars ((custom-port-read! port) buf 0 1)))
(if (zero? nchars)
(eof-object)
(vector-ref buf 0))))))
(define (custom-port-peek-char port)
(or (custom-port-prefetch port)
(let* ((buf (custom-port-buf port))
(pos (%call-get-position port))
(nchars ((custom-port-read! port) buf 0 1)))
(if (zero? nchars)
(eof-object)
(begin
(custom-port-prefetch-set! port (vector-ref buf 0))
(custom-port-prefetch-pos-set! port pos)
(vector-ref buf 0))))))
(define (custom-port-write-u8 byte port)
(let ((buf (custom-port-buf port)))
(when (custom-port-prefetch port)
(custom-port-prefetch-set! port #f)
(custom-port-prefetch-pos-set! port #f)
(%call-set-position! port (- (%call-get-position port) 1)))
(bytevector-u8-set! buf 0 byte)
((custom-port-write! port) buf 0 1)))
(define (custom-port-write-char ch port)
(let ((buf (custom-port-buf port)))
(when (custom-port-prefetch port)
(custom-port-prefetch-set! port #f)
(%call-set-position! port (custom-port-prefetch-pos port)))
(vector-set! buf 0 ch)
((custom-port-write! port) buf 0 1)))
(define (custom-port-close port)
(let ((closer (custom-port-closer port)))
(and closer (closer))))
(define (custom-port-flush port)
(let ((flusher (custom-port-flusher port)))
(and flusher (flusher))))
;;
;; SRFI-181 public API
;;
(define (make-custom-binary-input-port id read!
get-position set-position!
close)
(%make-custom-port id #t #f #f (make-bytevector 1)
read! #f
get-position
set-position!
close
#f))
(define (make-custom-textual-input-port id read!
get-position set-position!
close)
(%make-custom-port id #f #f #f (make-vector 1)
read! #f
get-position
set-position!
close
#f))
(define (make-custom-binary-output-port id write!
get-position set-position!
close . opts)
(let ((flush (if (pair? opts) (car opts) #f)))
(%make-custom-port id #t #f #f (make-bytevector 1)
#f write!
get-position
set-position!
close
flush)))
(define (make-custom-textual-output-port id write!
get-position set-position!
close . opts)
(let ((flush (if (pair? opts) (car opts) #f)))
(%make-custom-port id #f #f #f (make-vector 1)
#f write!
get-position
set-position!
close
flush)))
(define (make-custom-binary-input/output-port id read! write!
get-position set-position!
close . opts)
(let ((flush (if (pair? opts) (car opts) #f)))
(%make-custom-port id #t #f #f (make-bytevector 1)
read! write!
get-position
set-position!
close
flush)))
(define (make-file-error . objs)
(%make-custom-port-file-error objs))
| false |
2d43773f3f8e7a1ed9dafa4e23ee760653bbe12c
|
dae624fc36a9d8f4df26f2f787ddce942b030139
|
/chapter-14/string.scm
|
1b8f9d8a44212a199d4dfcef6292a5ce57851e4f
|
[
"MIT"
] |
permissive
|
hshiozawa/gauche-book
|
67dcd238c2edeeacb1032ce4b7345560b959b243
|
2f899be8a68aee64b6a9844f9cbe83eef324abb5
|
refs/heads/master
| 2020-05-30T20:58:40.752116 | 2019-10-01T08:11:59 | 2019-10-01T08:11:59 | 189,961,787 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 300 |
scm
|
string.scm
|
(define in (open-input-string "aiueo"))
(read in)
(define out (open-output-string))
(write 123 out)
(get-output-string out)
(call-with-input-string "aiueo" (lambda (port) (read port)))
(call-with-output-string (lambda (port) (write 123 port)))
(close-input-port in)
(close-output-port out)
| false |
0641f9512a03b93be97994d6066bfc668f70e107
|
17a42034153044d635a3585d9f0c9ea18c565eee
|
/Chapter-2/exercise-2.6.2.ss
|
fd9a9bb55660f09044cca352d831ed54f71633ee
|
[] |
no_license
|
al002/my-tspl4-answers
|
2c15b0eb508553557fb0909fe1f46b5afa5b458e
|
4dac628055360fd9356ff32ec1b978b91942e895
|
refs/heads/master
| 2021-05-27T23:14:28.514102 | 2013-04-22T00:18:25 | 2013-04-22T00:18:25 | 9,439,289 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 84 |
ss
|
exercise-2.6.2.ss
|
(define compose
(lambda (p1 p2)
(lambda (x)
(p1 (p2 x)))))
| false |
f37920429575531cf8cba721b47be2319681c73a
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/mscorlib/system/reflection/emit/pointer-type.sls
|
b5f0d756f28de8db924994c8245f480d5d76e23b
|
[] |
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 | 398 |
sls
|
pointer-type.sls
|
(library (system reflection emit pointer-type)
(export is? pointer-type? base-type)
(import (ironscheme-clr-port))
(define (is? a) (clr-is System.Reflection.Emit.PointerType a))
(define (pointer-type? a)
(clr-is System.Reflection.Emit.PointerType a))
(define-field-port
base-type
#f
#f
(property:)
System.Reflection.Emit.PointerType
BaseType
System.Type))
| false |
18d54b457a04106e9941dcef02421a5756d20bcd
|
abc7bd420c9cc4dba4512b382baad54ba4d07aa8
|
/src/old/plt/simulator_nought.ss
|
95707a4bdab6dbfa73437121d1dbaf1cf9587960
|
[
"BSD-3-Clause"
] |
permissive
|
rrnewton/WaveScript
|
2f008f76bf63707761b9f7c95a68bd3e6b9c32ca
|
1c9eff60970aefd2177d53723383b533ce370a6e
|
refs/heads/master
| 2021-01-19T05:53:23.252626 | 2014-10-08T15:00:41 | 2014-10-08T15:00:41 | 1,297,872 | 10 | 2 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 3,943 |
ss
|
simulator_nought.ss
|
(module simulator_nought mzscheme
(require "iu-match.ss"
"critical_section.ss"
(lib "include.ss")
(lib "pretty.ss")
;; NO SLIB:
; (lib "load.ss" "slibinit")
(lib "compat.ss") ;; gives us reg:define-struct
)
(require
"../generic/constants.ss"
(all-except "helpers.ss" id flush-output-port (current-output-port))
(all-except "graphics_stub.ss" test-this these-tests) ;; gives us clear-buffer
; (lib "9.ss" "srfi")
; "engine.ss"
(all-except "flat_threads.ss" test-this these-tests)
(all-except "tsort.ss" test-this these-tests)
)
;; This exports a whole bunch, because the simulated programs need to access this
;; stuff once they are "eval"ed.
(provide (all-defined)
(all-from "../generic/constants.ss")
(all-from "helpers.ss")
(all-from "flat_threads.ss")
;; Some Extra stuff needed by our runtime eval of simulated programs.
; yield-thread last
(all-from (lib "compat.ss")) ;; simulator needs flush-output-port
)
(define (vector-copy v)
(let ((newv (make-vector (vector-length v))))
(let loop ((n (vector-length newv)))
(if (>= n 0)
(begin (vector-set! newv n (vector-ref v n))
(loop (sub1 n)))))))
;; These need to be defined for the module system to be happy.
(define soc-return 'not-bound-yet-in-plt)
(define soc-finished 'not-bound-yet-in-plt)
(include (build-path "generic" "simulator_nought.examples.ss"))
(include (build-path "generic" "simulator_nought.ss"))
;; RRN: This is a cludge!! But how do I copy a structure in mzscheme!!
(set! structure-copy
(lambda (s)
(cond
[(node? s)
(make-node (node-id s) (node-pos s))]
[(simobject? s)
(make-simobject (simobject-node s)
(simobject-incoming s)
(simobject-timed-tokens s)
(simobject-redraw s)
(simobject-gobj s)
(simobject-homepage s)
(simobject-token-cache s)
(simobject-local-sent-messages s)
(simobject-local-recv-messages s))]
[else (error 'structure-copy
"sorry this is lame, but can't handle structure: ~s" s)]))
)
;; <TODO> Make stream version for this:
;(define text-repl (repl-builder void void run-compiler run-simulation))
'(define precomp-repl (repl-builder
void ;; Startup
void ;; Cleanse
(lambda (x) x) ;; Compiler
run-simulation-stream))
;(define precomp-graphical-repl
; (repl-builder (lambda () (init-world) (init-graphics))
; cleanse-world
; (lambda (x) x) ;; Compiler ;run-compiler
; graphical-simulation))
(define graphical-repl
(repl-builder (lambda () (init-world) (init-graphics))
cleanse-world
(lambda (x)
(parameterize ([pass-list (list-remove-after deglobalize (pass-list))])
(match x
[(precomp ,exp) `(unknown-lang (quote ,exp))]
[,other (run-compiler other)])))
graphical-simulation))
(define precomp-graphical-repl
(repl-builder (lambda () (init-world) (init-graphics))
cleanse-world
(lambda (x)
(parameterize ([pass-list (cleanup-token-machine)])
(match x
[(precomp ,exp) `(unknown-lang (quote ,exp))]
[,other (run-compiler other)])))
graphical-simulation))
(define pgr precomp-graphical-repl) ;; shorthand
)
;(require simulator_nought);
;(define (g) (eval (cadadr these-tests)))
;(go)
;(define x (cadr (list-ref testssim 2)))
| false |
ad166e581eb939d8eee7d9828c402f3f4fd0f17f
|
382770f6aec95f307497cc958d4a5f24439988e6
|
/projecteuler/009/009.scm
|
f30d08c839c817b17d144a8a7e077bd4fe3eeda7
|
[
"Unlicense"
] |
permissive
|
include-yy/awesome-scheme
|
602a16bed2a1c94acbd4ade90729aecb04a8b656
|
ebdf3786e54c5654166f841ba0248b3bc72a7c80
|
refs/heads/master
| 2023-07-12T19:04:48.879227 | 2021-08-24T04:31:46 | 2021-08-24T04:31:46 | 227,835,211 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 370 |
scm
|
009.scm
|
(let pro ([i 1])
(let f ([j i])
(let* ((k (- 1000 i j))
(cmp (- (+ (* i i) (* j j)) (* k k))))
(cond
((< cmp 0)
(f (+ j 1)))
((= cmp 0)
(* i j k))
((> cmp 0)
(pro (+ i 1)))))))
#|
(time (let pro ...))
no collections
0.000000000s elapsed cpu time
0.000806304s elapsed real time
0 bytes allocated
31875000
|#
| false |
467adca83c6801d68ced2d551953d4c181450a29
|
c63772c43d0cda82479d8feec60123ee673cc070
|
/ch2/24.scm
|
a0ea8d1bed4298c6ca3a17b7a2c2ca9c8093bea4
|
[
"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 | 59 |
scm
|
24.scm
|
#lang racket
(define ans (list 1 (list 2 (list 3 4))))
ans
| false |
d984971fb7b1fbce59b33ba42ec7425580562cb4
|
98fd12cbf428dda4c673987ff64ace5e558874c4
|
/sicp/v3/2.1/j0ni.scm
|
fa1f0fa59f4cc6350442067336992e2afc022f02
|
[
"Unlicense"
] |
permissive
|
CompSciCabal/SMRTYPRTY
|
397645d909ff1c3d1517b44a1bb0173195b0616e
|
a8e2c5049199635fecce7b7f70a2225cda6558d8
|
refs/heads/master
| 2021-12-30T04:50:30.599471 | 2021-12-27T23:50:16 | 2021-12-27T23:50:16 | 13,666,108 | 66 | 11 |
Unlicense
| 2019-05-13T03:45:42 | 2013-10-18T01:26:44 |
Racket
|
UTF-8
|
Scheme
| false | false | 18,553 |
scm
|
j0ni.scm
|
(require-extension sicp)
(require-extension numbers)
;; Code from rational number math in 2.1
;; (define (make-rat n d) (cons n d))
(define (numer x) (car x))
(define (denom x) (cdr x))
(define (add-rat x y)
(make-rat (+ (* (numer x) (denom y))
(* (numer y) (denom x)))
(* (denom x) (denom y))))
(define (sub-rat x y)
(make-rat (- (* (numer x) (denom y))
(* (numer y) (denom x)))
(* (denom x) (denom y))))
(define (mul-rat x y)
(make-rat (* (numer x) (numer y))
(* (denom x) (denom y))))
(define (div-rat x y)
(make-rat (* (numer x) (denom y))
(* (denom x) (numer y))))
(define (equal-rat? x y)
(= (* (numer x) (denom y))
(* (numer y) (denom x))))
(define (print-rat x)
(newline)
(display (numer x))
(display "/")
(display (denom x)))
;; Improved make-rat
;; (define (make-rat n d)
;; (let ((g (gcd n d)))
;; (cons (/ n g)
;; (/ d g))))
;; from 1.2.5
(define (gcd a b)
(if (= b 0)
a
(gcd b (remainder a b))))
;; Exercise 2.1: Define a better version of make-rat that handles both positive
;; and negative arguments. Make-rat should normalize the sign so that if the
;; rational number is positive, both the numerator and denominator are positive,
;; and if the rational number is negative, only the numerator is negative.
(define (make-rat n d)
(let ((g (gcd n d)))
(let ((n (/ n g))
(d (/ d g)))
(let ((f (if (negative? d)
(lambda (x) (* -1 x))
identity)))
(cons (f n) (f d))))))
;; Exercise 2.2: Consider the problem of representing line segments in a plane.
;; Each segment is represented as a pair of points: a starting point and an
;; ending point. Define a constructor make-segment and selectors start-segment
;; and end-segment that define the representation of segments in terms of
;; points. Furthermore, a point can be represented as a pair of numbers: the x
;; coordinate and the y coordinate. Accordingly, specify a constructor
;; make-point and selectors x-point and y-point that define this representation.
;; Finally, using your selectors and constructors, define a procedure
;; midpoint-segment that takes a line segment as argument and returns its
;; midpoint (the point whose coordinates are the average of the coordinates of
;; the endpoints). To try your procedures, you’ll need a way to print points:
(define (print-point p)
(display "(")
(display (x-point p))
(display ",")
(display (y-point p))
(display ")")
(newline))
(define (make-segment p1 p2)
(cons p1 p2))
(define (start-segment s)
(car s))
(define (end-segment s)
(cdr s))
(define (make-point x y)
(cons x y))
(define (x-point p)
(car p))
(define (y-point p)
(cdr p))
(define (midpoint-segment s)
(let ((x (/ (+ (x-point (start-segment s))
(x-point (end-segment s)))
2))
(y (/ (+ (y-point (start-segment s))
(y-point (end-segment s)))
2)))
(make-point x y)))
;; Exercise 2.3: Implement a representation for rectangles in a plane. (Hint:
;; You may want to make use of Exercise 2.2.) In terms of your constructors and
;; selectors, create procedures that compute the perimeter and the area of a
;; given rectangle. Now implement a different representation for rectangles. Can
;; you design your system with suitable abstraction barriers, so that the same
;; perimeter and area procedures will work using either representation?
(define (make-rectangle bottom-left top-right)
(make-segment bottom-left top-right))
(define (height r)
(- (y-point (end-segment r))
(y-point (start-segment r))))
(define (width r)
(- (x-point (end-segment r))
(x-point (start-segment r))))
(define (perimeter r)
(+ (* 2 (height r))
(* 2 (width r))))
(define (area r)
(* (height r) (width r)))
(define (make-rectangle-1 bottom-left height width)
(let ((dims (cons height width)))
(cons bottom-left dims)))
(define (height r)
(car (cdr r)))
(define (width r)
(cdr (cdr r)))
;; 2.1.3 What is meant by data
(define (cons-1 x y)
(define (dispatch m)
(cond ((= m 0) x)
((= m 1) y)
(else
(error "Argument not 0 or 1:
CONS" m))))
dispatch)
(define (car-1 z) (z 0))
(define (cdr-1 z) (z 1))
;; Exercise 2.4: Here is an alternative procedural representation of pairs. For
;; this representation, verify that (car (cons x y)) yields x for any objects x
;; and y.
(define (cons-2 x y)
(lambda (m) (m x y)))
(define (car-2 z)
(z (lambda (p q) p)))
;; What is the corresponding definition of cdr? (Hint: To verify that this
;; works, make use of the substitution model of 1.1.5.)
(define (cdr-2 z)
(z (lambda (p q) q)))
;; Exercise 2.5: Show that we can represent pairs of nonnegative integers using
;; only numbers and arithmetic operations if we represent the pair a and b as
;; the integer that is the product 2^a3^b. Give the corresponding definitions of
;; the procedures cons, car, and cdr.
(define (pow a b)
(define (iter acc count)
(if (= count 0)
acc
(iter (* acc a) (- count 1))))
(iter 1 b))
(define (cons-3 a b)
(* (pow 2 a)
(pow 3 b)))
;; The property of this combination which allows us to extract a and b is known
;; as the fundamental theorem of arithmetic - 2 and 3 are prime and share no
;; common factors. This means that we can divide by 2 until all that is left is
;; a power of 3, or vice versa.
(define (power-reduce y x)
(if (= 0 (remainder x y))
(power-reduce y (/ x y))
x))
(define (power-count y x)
(define (iter acc n)
(if (= n y)
acc
(iter (inc acc) (/ n y))))
(iter 1 x))
(define (car-3 x)
(power-count 2 (power-reduce 3 x)))
(define (cdr-3 x)
(power-count 3 (power-reduce 2 x)))
;; Exercise 2.6: In case representing pairs as procedures wasn’t mind-boggling
;; enough, consider that, in a language that can manipulate procedures, we can
;; get by without numbers (at least insofar as nonnegative integers are
;; concerned) by implementing 0 and the operation of adding 1 as
(define zero (lambda (f) (lambda (x) x)))
(define (add-1 n)
(lambda (f) (lambda (x) (f ((n f) x)))))
;; This representation is known as Church numerals, after its inventor, Alonzo
;; Church, the logician who invented the λ-calculus.
;; Define one and two directly (not in terms of zero and add-1). (Hint: Use
;; substitution to evaluate (add-1 zero)). Give a direct definition of the
;; addition procedure + (not in terms of repeated application of add-1).
;; (add-1 zero)
;; (add-1 (lambda (f) (lambda (x) x)))
;; (lambda (f) (lambda (x) (f (((lambda (f1) (lambda (x) x)) f) x))))
;; (lambda (f) (lambda (x) (f ((lambda (x) x) x))))
(define one
(lambda (f) (lambda (x) (f x))))
;; (add-1 (add-1 zero))
;; (add-1 (lambda (f) (lambda (x) (f x))))
;; (lambda (f) (lambda (x) (f (((lambda (f1) (lambda (x) (f1 x))) f) x))))
;; (lambda (f) (lambda (x) (f ((lambda (x) (f x)) x))))
(define two
(lambda (f) (lambda (x) (f (f x)))))
;; We can make use of the repeated application of f, which corresponds with the
;; number represented, to apply add-1 enough times.
(define (church-add a b)
((a add-1) b))
;; this is useful for testing:
(define (church->int x)
((x inc) 0))
;; 2.1.4 Interval arithmetic
(define (add-interval x y)
(make-interval (+ (lower-bound x)
(lower-bound y))
(+ (upper-bound x)
(upper-bound y))))
(define (mul-interval x y)
(let ((p1 (* (lower-bound x)
(lower-bound y)))
(p2 (* (lower-bound x)
(upper-bound y)))
(p3 (* (upper-bound x)
(lower-bound y)))
(p4 (* (upper-bound x)
(upper-bound y))))
(make-interval (min p1 p2 p3 p4)
(max p1 p2 p3 p4))))
(define (div-interval x y)
(mul-interval x
(make-interval
(/ 1.0 (upper-bound y))
(/ 1.0 (lower-bound y)))))
;; Exercise 2.7: Alyssa’s program is incomplete because she has not specified
;; the implementation of the interval abstraction. Here is a definition of the
;; interval constructor:
(define (make-interval a b) (cons a b))
;; Define selectors upper-bound and lower-bound to complete the implementation.
(define (lower-bound x) (car x))
(define (upper-bound x) (cdr x))
;; Exercise 2.8: Using reasoning analogous to Alyssa’s, describe how the
;; difference of two intervals may be computed. Define a corresponding
;; subtraction procedure, called sub-interval.
(define (sub-interval x y)
(make-interval (- (lower-bound x)
(upper-bound y))
(- (upper-bound x)
(lower-bound y))))
;; Should represent the range of all possible values of y subtracted from all
;; possible values of x
;; Exercise 2.9: The width of an interval is half of the difference between its
;; upper and lower bounds. The width is a measure of the uncertainty of the
;; number specified by the interval. For some arithmetic operations the width of
;; the result of combining two intervals is a function only of the widths of the
;; argument intervals, whereas for others the width of the combination is not a
;; function of the widths of the argument intervals. Show that the width of the
;; sum (or difference) of two intervals is a function only of the widths of the
;; intervals being added (or subtracted). Give examples to show that this is not
;; true for multiplication or division.
(define (width x)
(/ (- (upper-bound x)
(lower-bound x))
2))
(define (test-width-math fun)
(let ((interval-1 (make-interval 7 9))
(interval-2 (make-interval 3 7))
(interval-3 (make-interval 7 10))
(interval-4 (make-interval 2 3))
(interval-5 (make-interval 7 10)))
(print "interval-1 op interval-2 "
(width interval-1) " "
(width interval-2) " "
(width (fun interval-1 interval-2)))
(print "interval-2 op interval-3 "
(width interval-2) " "
(width interval-3) " "
(width (fun interval-2 interval-3)))
(print "interval-3 op interval-4 "
(width interval-3) " "
(width interval-4) " "
(width (fun interval-3 interval-4)))
(print "interval-4 op interval-5 "
(width interval-4) " "
(width interval-5) " "
(width (fun interval-4 interval-5)))))
;; #;151> (test-width-math add-interval)
;; interval-1 op interval-2 1 2 3
;; interval-2 op interval-3 2 1.5 3.5
;; interval-3 op interval-4 1.5 0.5 2
;; interval-4 op interval-5 0.5 1.5 2
;; #;154> (test-width-math sub-interval)
;; interval-1 op interval-2 1 2 3
;; interval-2 op interval-3 2 1.5 3.5
;; interval-3 op interval-4 1.5 0.5 2
;; interval-4 op interval-5 0.5 1.5 2
;; for add-interval and sub-interval, (width (*-interval interval-1 interval-2))
;; is given by (+ (width interval-1) (width interval-2))
;; #;182> (test-width-math mul-interval)
;; interval-1 op interval-2 1 2 21
;; interval-2 op interval-3 2 3/2 49/2
;; interval-3 op interval-4 3/2 1/2 8
;; interval-4 op interval-5 1/2 3/2 8
;; #;186> (test-width-math div-interval)
;; interval-1 op interval-2 1 2 1.0
;; interval-2 op interval-3 2 3/2 0.35
;; interval-3 op interval-4 3/2 1/2 1.33333333333333
;; interval-4 op interval-5 1/2 3/2 0.114285714285714
;; Max figured these out algebraically. Hahaha. Too little too late.
;; Exercise 2.10: Ben Bitdiddle, an expert systems programmer, looks over
;; Alyssa’s shoulder and comments that it is not clear what it means to divide
;; by an interval that spans zero. Modify Alyssa’s code to check for this
;; condition and to signal an error if it occurs.
(define (spans-zero? a)
(negative? (* (upper-bound a)
(lower-bound a))))
(define (div-interval-safe x y)
(if (spans-zero? y)
(error "cannot divide by an interval spanning 0")
(mul-interval x
(make-interval
(/ 1.0 (upper-bound y))
(/ 1.0 (lower-bound y))))))
(define (test-divide-by-zero)
(let ((i-1 (make-interval 9 12))
(i-2 (make-interval -3 5)))
(div-interval-safe i-1 i-2)))
(define (test-divide-by-non-zero)
(let ((i-1 (make-interval 9 12))
(i-2 (make-interval 3 5)))
(div-interval-safe i-1 i-2)))
;; Exercise 2.11: In passing, Ben also cryptically comments: “By testing the
;; signs of the endpoints of the intervals, it is possible to break mul-interval
;; into nine cases, only one of which requires more than two multiplications.”
;; Rewrite this procedure using Ben’s suggestion.
;; cases:
;; both positive
;; both negative
;; x pos, y neg
;; y pos, x neg
;; x spans 0, y pos
;; x spans 0, y neg
;; y spans 0, x pos
;; y spans 0, x neg
;; both span 0
(define (mul-interval-cases x y)
(define (positive-interval? x)
(positive? (lower-bound x)))
(define (negative-interval? x)
(negative? (upper-bound x)))
(let ((xu (upper-bound x))
(xl (lower-bound x))
(yu (upper-bound y))
(yl (lower-bound y)))
(cond ((and (positive-interval? x)
(positive-interval? y))
(make-interval (* xl yl)
(* xu yu)))
((and (negative-interval? x)
(negative-interval? y))
(make-interval (* xu yu)
(* xl yl)))
((and (positive-interval? x)
(negative-interval? y))
(make-interval (* xu yl)
(* xl yu)))
((and (negative-interval? x)
(positive-interval? y))
(make-interval (* xl yu)
(* xu yl)))
((and (spans-zero? x)
(positive-interval? y))
(make-interval (* xl yu)
(* xu yu)))
((and (spans-zero? x)
(negative-interval? y))
(make-interval (* xu yl)
(* xl yu)))
((and (spans-zero? y)
(positive-interval? x))
(make-interval (* xu yl)
(* xu yu)))
((and (spans-zero? y)
(negative-interval? x))
(make-interval (* xl yu)
(* xl yl)))
((and (spans-zero? x)
(spans-zero? y))
(mul-interval x y))
(else
(error "unprecedented combination of intervals!")))))
;; After debugging her program, Alyssa shows it to a potential user, who
;; complains that her program solves the wrong problem. He wants a program that
;; can deal with numbers represented as a center value and an additive
;; tolerance; for example, he wants to work with intervals such as 3.5 ±± 0.15
;; rather than [3.35, 3.65]. Alyssa returns to her desk and fixes this problem
;; by supplying an alternate constructor and alternate selectors:
(define (make-center-width c w)
(make-interval (- c w) (+ c w)))
(define (center i)
(/ (+ (lower-bound i)
(upper-bound i))
2))
(define (width i)
(/ (- (upper-bound i)
(lower-bound i))
2))
;; Unfortunately, most of Alyssa’s users are engineers. Real engineering
;; situations usually involve measurements with only a small uncertainty,
;; measured as the ratio of the width of the interval to the midpoint of the
;; interval. Engineers usually specify percentage tolerances on the parameters
;; of devices, as in the resistor specifications given earlier.
;; Exercise 2.12: Define a constructor make-center-percent that takes a center
;; and a percentage tolerance and produces the desired interval. You must also
;; define a selector percent that produces the percentage tolerance for a given
;; interval. The center selector is the same as the one shown above.
(define (make-center-percent c t)
(make-center-width c (* c (/ t 100))))
(define (percent i)
(* 100 (/ (width i) (center i))))
;; Exercise 2.13: Show that under the assumption of small percentage tolerances
;; there is a simple formula for the approximate percentage tolerance of the
;; product of two intervals in terms of the tolerances of the factors. You may
;; simplify the problem by assuming that all numbers are positive.
;; Nope, I don't think I will.
(define (par1 r1 r2)
(div-interval
(mul-interval r1 r2)
(add-interval r1 r2)))
(define (par2 r1 r2)
(let ((one (make-interval 1 1)))
(div-interval
one
(add-interval
(div-interval one r1)
(div-interval one r2)))))
;; Lem complains that Alyssa’s program gives different answers for the two ways
;; of computing. This is a serious complaint.
;; Exercise 2.14: Demonstrate that Lem is right. Investigate the behavior of the
;; system on a variety of arithmetic expressions. Make some intervals A and B,
;; and use them in computing the expressions A/A and A/B. You will get the most
;; insight by using intervals whose width is a small percentage of the center
;; value. Examine the results of the computation in center-percent form (see
;; Exercise 2.12).
(define (verify-program-flaw)
(define a (make-interval 100 101))
(define b (make-interval 200 201))
(let ((r1 (par1 a b))
(r2 (par2 a b)))
(print (upper-bound r1) " " (upper-bound r2))
(print (lower-bound r1) " " (lower-bound r2))
(print (center r1) " " (width r1) " " (percent r1))
(print (center r2) " " (width r2) " " (percent r2))))
;; #;1763> (verify-program-flaw)
;; 67.67 67.2218543046358
;; 66.2251655629139 66.6666666666667
;; 66.947582781457 0.72241721854305 1.07907886816661
;; 66.9442604856512 0.277593818984542 0.414664105586828
;; Exercise 2.15: Eva Lu Ator, another user, has also noticed the different
;; intervals computed by different but algebraically equivalent expressions. She
;; says that a formula to compute with intervals using Alyssa’s system will
;; produce tighter error bounds if it can be written in such a form that no
;; variable that represents an uncertain number is repeated. Thus, she says,
;; par2 is a “better” program for parallel resistances than par1. Is she right?
;; Why?
;; lol
;; Exercise 2.16: Explain, in general, why equivalent algebraic expressions may
;; lead to different answers. Can you devise an interval-arithmetic package that
;; does not have this shortcoming, or is this task impossible? (Warning: This
;; problem is very difficult.)
| false |
c6509dbf6bb70ec5edc923083f53872ad9e9fcac
|
ac2a3544b88444eabf12b68a9bce08941cd62581
|
/lib/_test/quiet.scm
|
4f2497d5d661edf9f37fa88b016692a50620211c
|
[
"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 | 401 |
scm
|
quiet.scm
|
;;;============================================================================
;;; File: "quiet.scm"
;;; Copyright (c) 2013-2019 by Marc Feeley, All Rights Reserved.
;;;============================================================================
(##supply-module _test/quiet)
(import _test)
(test-quiet?-set! #t)
;;;============================================================================
| false |
2037b57d6a805307c3afb9add167f43f33e01130
|
a0298d460500bb2fbb5e079ee99f7f6699e44969
|
/pea/util.sls
|
c82a89ec6fa13d007c0d41128f5aff770f0e9b83
|
[] |
no_license
|
akce/pea
|
1d1c225c8e007aeb9b0b49c474f203167317b282
|
eb9a1e57776f56e061fe67f4414e07f0564bd1f3
|
refs/heads/master
| 2020-12-18T18:25:57.698040 | 2020-09-09T04:15:56 | 2020-09-09T04:16:06 | 235,483,730 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 7,971 |
sls
|
util.sls
|
(library (pea util)
(export
arg
command
condition->doh
define-enum
indexp list-slice
my
object->string
(rename (safe-input-port-ready? input-port-ready?))
read-trim-right
reverse-map
safe-substring
slurp
string-join string-startswith? string-trim-both
write-now
)
(import
(rnrs)
(irregex)
(only (chezscheme) datum display-condition input-port-ready? list-head))
;; [proc] arg: get first argument.
;; HMMM check return type is singleton?
(define arg
(lambda (input)
(cadr input)))
;; [proc] command: sanitise 1st arg (if any) of input.
(define command
(lambda (input)
(cond
[(null? input)
'EMPTY]
[(list? input)
(car input)]
[else
input])))
;; [proc] condition->doh: converts the display-condition message to a DOH message.
;; [return] DOH message object.
(define condition->doh
(lambda (e msg)
(let-values ([(port getter) (open-string-output-port)])
(display-condition e port)
`(DOH ,msg ,(getter)))))
;; [syntax] define-enum: generates a syntax transformer that evaluates the value of an enum at compile time.
;; eg, using trace-define-syntax:
;; > (define-enum e [a 1] [b 2] [c 3])
;; |(define-enum (define-enum e (a 1) (b 2) (c 3)))
;; |(define-syntax e
;; (lambda (x)
;; (syntax-case x ()
;; [(_ v) (eq? (datum v) (syntax->datum #'a)) #'1]
;; [(_ v) (eq? (datum v) (syntax->datum #'b)) #'2]
;; [(_ v) (eq? (datum v) (syntax->datum #'c)) #'3])))
;; > (e a)
;; 1
;; > (e b)
;; 2
;; > (e c)
;; 3
;; > (e d)
;; Exception: invalid syntax (e d)
;; Type (debug) to enter the debugger.
;; >
(define-syntax define-enum
(syntax-rules ()
[(_ group (var* val*) ...)
(define-syntax group
(lambda (x)
(syntax-case x ()
[(_ v)
(eq? (datum v) (syntax->datum #'var*))
#'val*] ...)))]))
;; Like 'find' but returns the 0-based index of the first match for predicate, #f otherwise.
(define indexp
(lambda (pred lst)
(let ([index 0])
(if (find
(lambda (x)
(cond
[(pred x) #t]
[else (set! index (fx+ index 1)) #f]))
lst)
index
#f))))
;; [proc] list-slice: return exact slice or as much as able.
(define list-slice
(lambda (lst offset len)
(let ([lst-len (length lst)])
(cond
[(<= (+ offset len) lst-len)
(list-head (list-tail lst offset) len)]
[(> offset lst-len)
'()]
[else
(list-tail lst offset)]))))
;; [syntax] my: short-hand for batch defines.
;; Name gratuitously taken from perl. I also like that it's nice and short.
(define-syntax my
(syntax-rules ()
[(_ (name val) ...)
(begin
(define name val) ...)]))
;; [proc] object->string: returns the scheme object in string form.
(define object->string
(lambda (obj)
(call-with-string-output-port
(lambda (p)
(write obj p)))))
;; Wraps input-port-ready? so that any raised exception is converted to false.
;; The custom port for the socket is raising &i/o-read-error occasionally.
;; See: chez s/io.ss ~= /cannot determine ready status/
;; It appears to trigger when port is empty and has not reached eof.
(define safe-input-port-ready?
(lambda (port)
(guard (e [else #f])
(input-port-ready? port))))
;; [proc] read-trim-right: performs a read and then trims trailing whitespace.
;; This function requires a whitespace character (ie, newline) to trail the scheme datum
;; which will always be the case when using (write-now).
;; (Except in the case of EOF which marks end of stream.)
;; Trailing a message with a newline ensures that client/server read/event-loops stay healthy.
(define read-trim-right
(case-lambda
[()
(read-trim-right (current-input-port))]
[(port)
(let ([ret (guard (e [else (eof-object)])
;; (read) can exception if it encounters a scheme object it doesn't know how to instantiate.
(read port))])
(cond
;; Nothing is expected past an EOF.
[(eof-object? ret)
ret]
[else
;; NB: this assumes that there'll always be one whitespace (newline) following the scheme datum.
;; If not, peek-char will block!
(let ([ch (peek-char port)])
(cond
;; NB char-whitespace? will exception if it sees an eof-object.
[(eof-object? ch)
ret]
[(char-whitespace? ch)
(read-char port) ; remove from port buffer.
ret]
[else
ret]))]))]))
;; [proc] reverse-map: like map, but list is returned in reverse.
;; TODO support multiple lists.
(define reverse-map
(lambda (proc lst)
(let loop ([ls lst] [acc '()])
(cond
[(null? ls)
acc]
[else
(loop (cdr ls) (cons (proc (car ls)) acc))]))))
;; [proc] safe-substring: as substring but returns #f on error rather than exception.
(define safe-substring
(lambda (str start end)
(guard (e [else str])
(substring str start end))))
;; [proc] slurp: Read all lines from a text file.
;; Name is akin to the perl function.
;; All lines of a file are returned as a list with newlines removed.
(define slurp
(lambda (path)
(let ([f (open-file-input-port
path
(file-options no-create)
(buffer-mode line)
(make-transcoder (utf-8-codec)))])
(let loop ([line (get-line f)] [lines '()])
(cond
[(eof-object? line)
(close-input-port f)
(reverse lines)]
[else
(loop (get-line f) (cons line lines))])))))
;; [proc] string-join: join all string parts together using separator.
;;
;; Note that the signature to this version of string-join differs to that found in SRFI-13.
;; The separator is the first arg and therefore always explicit which allows for the string
;; parts as regular arguments, rather than a list of strings.
;;
;; Naive implementation that uses (potentially) multiple calls to string-append.
;; TODO use alternate name to differentiate from SRFI-13?
(define string-join
(lambda (sep . str-parts)
(cond
[(null? str-parts)
""]
[else
(let loop ([acc (car str-parts)] [rest (cdr str-parts)])
(cond
[(null? rest)
acc]
[else
(loop (string-append acc sep (car rest)) (cdr rest))]))])))
;; [proc] string-startswith?: tests whether str starts with prefix.
;; This is a quick and dirty (read inefficient) version that uses irregex.
(define string-startswith?
(lambda (str prefix)
(irregex-match-data? (irregex-search `(w/case bos ,prefix) str))))
;; [proc] string-trim-both: kind of the same as that found in (srfi :152 strings)
;; Defined using irregex and only supports whitespace trimming.
(define string-trim-both
(let ([p (irregex '(w/nocase (* space ) (submatch (* nonl)) (* space)))])
(lambda (line)
(irregex-match-substring (irregex-search p line) 1))))
;; [proc] write-now: write message and flush port.
;; If I had a dollar for the number of times i've forgotten to flush after write....
(define write-now
(lambda (msg port)
(write msg port)
;; NB newline is very import here. Chez scheme reader (read) seems to require it.
;; Otherwise pea ends up with the reader in weird states waiting for more data.
(newline port)
(flush-output-port port)))
)
| true |
3601474dc845a9840c1c99081302884f174a46ee
|
2163cd08beac073044187423727f84510a1dbc34
|
/documentation/ch4_qeval.scm
|
48a8e46b8066aa18187ba50d6f7f56159592448d
|
[] |
no_license
|
radiganm/sicp
|
b40995ad4d681e2950698295df1bbe3a75565528
|
32a7dcdf5678bb54d07ee3ee8a824842907489f0
|
refs/heads/master
| 2021-01-19T10:48:52.579235 | 2016-12-12T10:47:18 | 2016-12-12T10:47:18 | 63,052,284 | 3 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 183 |
scm
|
ch4_qeval.scm
|
(define (qeval query frame-stream)
(let ((qproc (get (type query) 'qeval)))
(if qproc
(qproc (contents query) frame-stream)
(simple-query query frame-stream))))
| false |
d7f8f8cf5653e183164ccfd42a686be9a9f02839
|
d10590821cfa35282206cd32acf430746cfca02d
|
/libs/locations.scm
|
0e6ab44bd8fd73b6f1242e599fbf10546b58ea72
|
[] |
no_license
|
kdltr/ensemble
|
606349ff62916c97dfcee4bdce03418eca1d2112
|
82e09a20e646f59f055abdc3f8664339760b351f
|
refs/heads/master
| 2021-06-07T06:44:15.767523 | 2021-05-30T13:06:06 | 2021-05-30T13:06:06 | 100,152,678 | 4 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,037 |
scm
|
locations.scm
|
(module (ensemble libs locations) (config-home cache-home)
(import scheme (chicken base) (chicken pathname) (chicken process-context))
(define (xdg-config-home)
(cond ((get-environment-variable "XDG_CONFIG_HOME")
=> values)
((get-environment-variable "HOME")
=> (lambda (d) (make-pathname d ".config")))
(else
(error "Either the XDG_CONFIG_HOME or the HOME environment variables must be defined"))))
(define (xdg-cache-home)
(cond ((get-environment-variable "XDG_CACHE_HOME")
=> values)
((get-environment-variable "HOME")
=> (lambda (d) (make-pathname d ".cache")))
(else
(error "Either the XDG_CACHE_HOME or the HOME environment variable must be defined"))))
(define (config-home)
(or (get-environment-variable "ENSEMBLE_CONFIG_HOME")
(make-pathname (xdg-config-home) "ensemble")))
(define (cache-home)
(or (get-environment-variable "ENSEMBLE_CACHE_HOME")
(make-pathname (xdg-cache-home) "ensemble")))
) ;; locations module
| false |
325e349823ef34cf82dc83a1610adbaef1a79307
|
c63772c43d0cda82479d8feec60123ee673cc070
|
/ch2/base.scm
|
53d688ec44c9613d40a6c86fb47bc2fff29783bd
|
[
"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 | 613 |
scm
|
base.scm
|
#lang racket
(provide (all-defined-out))
; flatmap :: (a -> [b]) -> [a] -> [b]
(define (flatmap proc seq)
(accumulate append '() (map proc seq)))
(define (enumerate-interval low high)
(if (> low high) '()
(cons low (enumerate-interval (+ low 1) high))))
(define (accumulate-iter op init seq)
(define (helper seq ret)
(if (null? seq) ret
(helper (cdr seq) (op (car seq) ret))))
(helper seq init))
(define (accumulate-rec op initial sequence)
(if (null? sequence) initial
(op (car sequence)
(accumulate-rec op initial (cdr sequence)))))
(define accumulate accumulate-iter)
| false |
214f88aaa23ee92689d7cd17af4cad1d0e13a0f6
|
6b961ef37ff7018c8449d3fa05c04ffbda56582b
|
/bbn_cl/mach/cl/modules.scm
|
afaacf2698c717b5c88fa1143b2241dd3302ae39
|
[] |
no_license
|
tinysun212/bbn_cl
|
7589c5ac901fbec1b8a13f2bd60510b4b8a20263
|
89d88095fc2a71254e04e57cf499ae86abf98898
|
refs/heads/master
| 2021-01-10T02:35:18.357279 | 2015-05-26T02:44:00 | 2015-05-26T02:44:00 | 36,267,589 | 4 | 3 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,661 |
scm
|
modules.scm
|
;;; ********
;;;
;;; Copyright 1992 by BBN Systems and Technologies, A division of Bolt,
;;; Beranek and Newman Inc.
;;;
;;; Permission to use, copy, modify and distribute this software and its
;;; documentation is hereby granted without fee, provided that the above
;;; copyright notice and this permission appear in all copies and in
;;; supporting documentation, and that the name Bolt, Beranek and Newman
;;; Inc. not be used in advertising or publicity pertaining to distribution
;;; of the software without specific, written prior permission. In
;;; addition, BBN makes no respresentation about the suitability of this
;;; software for any purposes. It is provided "AS IS" without express or
;;; implied warranties including (but not limited to) all implied warranties
;;; of merchantability and fitness. In no event shall BBN be liable for any
;;; special, indirect or consequential damages whatsoever resulting from
;;; loss of use, data or profits, whether in an action of contract,
;;; negligence or other tortuous action, arising out of or in connection
;;; with the use or performance of this software.
;;;
;;; ********
;;;
;;;
(proclaim '(insert-touches nil))
(export '(*modules* provide require))
(defvar *modules* ()
"This is a list of module names that have been loaded into Lisp so far.
It is used by PROVIDE and REQUIRE.")
;;;; Provide and Require.
(defun provide (module-name)
"Adds a new module name to *modules* indicating that it has been loaded.
Module-name may be either a case-sensitive string or a symbol; if it is
a symbol, its print name is used (downcased if it is not escaped)."
(pushnew (module-name-string module-name) *modules* :test #'string=)
t)
(defun require (module-name &optional pathname)
"Loads a module when it has not been already. Pathname, if supplied,
is a single pathname or list of pathnames to be loaded if the module
needs to be. If pathname is not supplied, then a file will be loaded whose
name is formed by merging \"\\modules\\\" and module-name (downcased if it
is a symbol)."
(setf module-name (module-name-string module-name))
(if (not (member module-name *modules* :test #'string=))
(progn
(cond ((null pathname)
(setf pathname (list (merge-pathnames "modules/" module-name))))
((not (consp pathname))
(setf pathname (list pathname))))
(dolist (ele pathname t)
(load ele)))))
;;;; Misc.
(defun module-name-string (name)
(typecase name
(string name)
(symbol (symbol->filename-string name))
(t (error "Module name must be a string or symbol -- ~S."
name))))
| false |
ab26e50a67768333914bdcf25aae892330379457
|
2861d122d2f859f287a9c2414057b2768870b322
|
/tests/test-record.scm
|
feb3019918499d105b195c6c0aeb905cc1016bca
|
[
"BSD-3-Clause"
] |
permissive
|
ktakashi/aeolus
|
c13162e47404ad99c4834da6677fc31f5288e02e
|
2a431037ea53cb9dfb5b585ab5c3fbc25374ce8b
|
refs/heads/master
| 2016-08-10T08:14:20.628720 | 2015-10-13T11:18:13 | 2015-10-13T11:18:13 | 43,139,534 | 5 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 520 |
scm
|
test-record.scm
|
(import (except (scheme base) define-record-type)
(aeolus misc record)
(aeolus-test))
(test-begin "Simplified R6RS record")
(let ()
(define-record-type (<bar> make-bar bar?))
(define-record-type (<foo> make-foo foo?)
(parent <bar>)
(protocol (lambda (p) (lambda (v) ((p) v))))
(fields (immutable v foo-v)))
(test-assert "bar?" (bar? (make-bar)))
(test-assert "foo?" (foo? (make-foo 'a)))
(test-assert "bar?(2)" (bar? (make-foo 'a)))
(test-equal "foo-v" 'a (foo-v (make-foo 'a))))
(test-end)
| false |
6ef5254f19661aa9e9a450975636e39ab90a39b4
|
acc632afe0d8d8b94b781beb1442bbf3b1488d22
|
/deps/sdl2/lib/sdl2-internals/helpers/define-enum-mask-accessor.scm
|
b96e88295b4a98072d0472396bb05ee9bbe8168f
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
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 | 5,925 |
scm
|
define-enum-mask-accessor.scm
|
;;
;; chicken-sdl2: CHICKEN Scheme bindings to Simple DirectMedia Layer 2
;;
;; Copyright © 2013, 2015-2016 John Croisant.
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; - Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;;
;; - 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 HOLDER 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.
;;; Macro: define-enum-mask-accessor
;;;
;;; Defines a getter and (optionally) setter that automatically
;;; convert enums from integer to list of symbols when getting, and
;;; from list of symbols to integer when setting. This macro is
;;; usually used for struct fields that hold an enum bitfield.
;;;
;;; This macro works by wrapping an existing "raw" getter and setter
;;; that work with integer values. The integer values are converted
;;; to/from lists of symbols using enum mask packer/unpacker
;;; procedures.
;;;
;;; Usage (getter and setter):
;;;
;;; (define-enum-mask-accessor
;;; getter: (GETTER
;;; raw: GETTER-RAW
;;; unpack: UNPACKER
;;; exact: DEFAULT-EXACT?)
;;; setter: (SETTER
;;; raw: SETTER-RAW
;;; pack: PACKER))
;;;
;;; Usage (getter only):
;;;
;;; (define-enum-mask-accessor
;;; getter: (GETTER
;;; raw: GETTER-RAW
;;; unpack: UNPACKER
;;; exact: DEFAULT-EXACT?))
;;;
;;; GETTER is the name for a getter procedure that returns the field
;;; value as a list of symbols. The getter procedure accepts one
;;; required argument, an object that will be passed to GETTER-RAW,
;;; and one optional argument, which controls whether bitmasks must
;;; match exactly (see define-enum-mask-unpacker). The getter
;;; procedure will be defined by this macro. If a setter is also
;;; specified, the getter procedure will be enhanced to work with
;;; "generalized set!" (SRFI 17).
;;;
;;; GETTER-RAW is the name of an existing struct field getter that
;;; returns an integer value.
;;;
;;; UNPACKER is the name of an existing procedure that unpacks an
;;; integer value to a list of symbols. It is used to convert the
;;; value returned by GETTER-RAW. Usually UNPACKER is a procedure
;;; defined with define-enum-mask-unpacker.
;;;
;;; DEFAULT-EXACT? must be #t or #f, and determines the default value
;;; for the optional argument to the getter procedure, which controls
;;; whether bitmasks much match exactly or not.
;;;
;;; SETTER is the name for a setter procedure that accepts an object
;;; and a list of enum symbols. The setter procedure will also accept
;;; an integer, which is assumed to be an already-packed bitfield
;;; value. The setter will throw an error if given a list containing
;;; an unrecognized symbol, or invalid type. The setter procedure will
;;; be defined by this macro.
;;;
;;; SETTER-RAW is the name of an existing procedure which sets a
;;; struct field to an integer value.
;;;
;;; PACKER is the name of an existing procedure that packs a list of
;;; enum symbols to an integer value. It is used to convert a list of
;;; symbols before passing it to SETTER-RAW. Usually PACKER is a
;;; procedure defined with define-enum-mask-packer.
;;;
;;; Example:
;;;
;;; (define-enum-mask-accessor
;;; getter: (keysym-mod
;;; raw: keysym-mod-raw
;;; unpack: unpack-keymods
;;; exact: #f)
;;; setter: (keysym-mod-set!
;;; raw: keysym-mod-raw-set!
;;; pack: pack-keymods))
;;;
(define-syntax define-enum-mask-accessor
(syntax-rules (getter: raw: unpack: exact: setter: pack:)
;; Getter and setter
((define-enum-mask-accessor
getter: (getter-name
raw: getter-raw
unpack: unpacker
exact: default-exact?)
setter: (setter-name
raw: setter-raw
pack: packer))
(begin
(define (setter-name record new)
(setter-raw
record
(cond ((integer? new) new)
((list? new)
(packer
new
(lambda (x)
(error 'setter-name "unrecognized enum value" x))))
(else
(error 'setter-name
"invalid type (expected list of symbols, or integer)"
new)))))
(define (getter-name record #!optional (exact? default-exact?))
(unpacker (getter-raw record) exact?))
(set! (setter getter-name) setter-name)))
;; Only getter
((define-enum-mask-accessor
getter: (getter-name
raw: getter-raw
unpack: unpacker
exact: default-exact?))
(define (getter-name record #!optional (exact? default-exact?))
(unpacker (getter-raw record) exact?)))))
| true |
2226416a3947066339e7cf6a2947a03f5b8a20f4
|
ca3425fbd3bef3cd7adeb7b1f61f00afd097927f
|
/planet/galore.plt/2/2/examples/heap--heap-sort.scm
|
44f4e0ba6a9e4601973ec14d8e6641b953ca5c1a
|
[] |
no_license
|
soegaard/little-helper
|
b330ec4382b958cd83b65e93c27581f5dc941c97
|
26249c688e5adf1e2535c405c6289030eff561b4
|
refs/heads/master
| 2021-01-16T18:06:35.491073 | 2011-08-11T23:00:56 | 2011-08-11T23:00:56 | 2,187,791 | 10 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 723 |
scm
|
heap--heap-sort.scm
|
; heap-sort.scm -- Jens Axel Søgaard
(require (planet "heap.scm" ("soegaard" "galore.plt" 2 1)))
(define (heap-sort l)
(heap->list (list->heap l)))
(define (list->heap l)
(foldl insert (empty) l))
(define (heap->list H)
(define (loop H l)
(if (empty? H)
(reverse l)
(loop (delete-min H) (cons (find-min H) l))))
(loop H '()))
(heap-sort '(3 1 4 1 5 9))
;;; Alternative using srfi-42 (and srfi-67)
(require (lib "42.ss" "srfi")
(lib "67.ss" "srfi"))
(define (heap-sort l)
(heap->list (list->heap l)))
(define (list->heap l)
(heap-ec default-compare (: x l) x))
(define (heap->list H)
(list-ec (: x H) x))
(heap-sort '(3 1 4 1 5 9))
| false |
f088120ebd26c1fd1e16278275b60b2c5be46f35
|
a19495f48bfa93002aaad09c6967d7f77fc31ea8
|
/src/kanren/kanren/benchmarks/lips.scm
|
d0e93c780de68f5e472a8100298fc4efd2f00470
|
[
"Zlib"
] |
permissive
|
alvatar/sphere-logic
|
4d4496270f00a45ce7a8cb163b5f282f5473197c
|
ccfbfd00057dc03ff33a0fd4f9d758fae68ec21e
|
refs/heads/master
| 2020-04-06T04:38:41.994107 | 2014-02-02T16:43:15 | 2014-02-02T16:43:15 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 3,184 |
scm
|
lips.scm
|
; LIPS benchmark -- logical inferences per second
;
; Do the dumy inverse of a list of 30 elements
;
; nrev([],[]).
; nrev([X|Rest],Ans) :- nrev(Rest,L), extend(L,[X],Ans).
; extend([],L,L).
; extend([X|L1],L2,[X|L3]) :- extend(L1,L2,L3).
; data([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]).
; $Id: lips.scm,v 4.50 2005/02/12 00:04:35 oleg Exp $
(define nrev
(extend-relation (a1 a2)
(fact () '() '())
(relation (x rest ans)
(to-show `(,x . ,rest) ans)
(exists (ls)
(all
(nrev rest ls)
(concat ls `(,x) ans))))))
(let ((lst '(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)))
(test-check 'test-nrev
(time
(solution (x) (nrev lst x)))
`((x.0 ,(reverse lst)))))
(define get_cpu_time
(lambda ()
(vector-ref (statistics) 1)))
(define lots
(extend-relation ()
(relation ()
(to-show)
(exists (count)
(all
(predicate (newline))
(predicate (newline))
(eg_count count)
(bench count)
fail)))
(fact ())))
(define test-lots
(lambda ()
(solve 1000 () (lots))))
(define eg_count
(extend-relation (a1)
(fact () 10)
(fact () 20)
(fact () 50)
(fact () 100)
(fact () 200)
(fact () 500)
(fact () 1000)
(fact () 2000)
(fact () 5000)
(fact () 10000)))
(define bench
(relation (count)
(to-show count)
(let ([t0 (get_cpu_time)])
(dodummy count)
(let ([t1 (get_cpu_time)])
(dobench count)
(let ([t2 (get_cpu_time)])
(report count t0 t1 t2))))))
(define dobench
(extend-relation (a1)
(relation (count)
(to-show count)
(all
(repeat count)
(nrev '(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)
_)
fail))
(fact () _)))
(define dodummy
(extend-relation (a1)
(relation (count)
(to-show count)
(all
(repeat count)
(dummy _)
fail))
(fact () _)))
(define dummy
(relation ()
(to-show _)))
(define repeat
(extend-relation (a1)
(fact (n) n)
(relation (n)
(to-show n)
(project (n)
(all (> n 1) (repeat (- n 1)))))))
(define report
(relation (count t0 t1 t2)
(to-show count t0 t1 t2)
(exists (lips units)
(project (t0 t1 t2)
(let ([time1 (- t1 t0)]
[time2 (- t2 t1)])
(let ([time (- time2 time1)])
(all
(calculate_lips count time lips units)
(project (lips count)
(predicate (printf "~n~s lips for ~s" lips count)))
(project (units)
(predicate
(printf " Iterations taking ~s ~s ( ~s )~n " time units time))))))))))
(define calculate_lips
(extend-relation (a1 a2 a3 a4)
(relation (count time lips)
(to-show count time lips 'msecs)
(if-only (== time 0) (== lips 0)
(project (count time)
(let ([t1 (* 496 count 1000)]
[t2 (+ time 0.0)])
(== lips (/ t1 t2))))))))
;(test-lots)
| false |
15af99acc56abcf2fc7d5affbee3233bf2e3df83
|
df0ba5a0dea3929f29358805fe8dcf4f97d89969
|
/exercises/informatics-2/02-linear-iterative-process/count-digits.scm
|
23f30b7ab22759f41f576dd41bfac2c46e549fa6
|
[
"MIT"
] |
permissive
|
triffon/fp-2019-20
|
1c397e4f0bf521bf5397f465bd1cc532011e8cf1
|
a74dcde683538be031186cf18367993e70dc1a1c
|
refs/heads/master
| 2021-12-15T00:32:28.583751 | 2021-12-03T13:57:04 | 2021-12-03T13:57:04 | 210,043,805 | 14 | 31 |
MIT
| 2019-12-23T23:39:09 | 2019-09-21T19:41:41 |
Racket
|
UTF-8
|
Scheme
| false | false | 569 |
scm
|
count-digits.scm
|
(require rackunit rackunit/text-ui)
(define (count-digits n)
(define (helper counter result)
(if (= counter 0)
result
(helper (quotient counter 10)
(+ result 1))))
(helper n 0))
(define count-digits-tests
(test-suite
"Tests for count-digits"
(check = (count-digits 3) 1)
(check = (count-digits 12) 2)
(check = (count-digits 42) 2)
(check = (count-digits 666) 3)
(check = (count-digits 1337) 4)
(check = (count-digits 65510) 5)
(check = (count-digits 8833443388) 10)))
(run-tests count-digits-tests)
| false |
b0b0919a1eb5aa2d0e86785a9f3b9ea06e8e7f88
|
648776d3a0d9a8ca036acaf6f2f7a60dcdb45877
|
/queries/ini/folds.scm
|
911798f5ab77c61a58a7a5b59e4d76d0d6643349
|
[
"Apache-2.0"
] |
permissive
|
nvim-treesitter/nvim-treesitter
|
4c3c55cbe6ff73debcfaecb9b7a0d42d984be3e6
|
f8c2825220bff70919b527ee68fe44e7b1dae4b2
|
refs/heads/master
| 2023-08-31T20:04:23.790698 | 2023-08-31T09:28:16 | 2023-08-31T18:19:23 | 256,786,531 | 7,890 | 980 |
Apache-2.0
| 2023-09-14T18:07:03 | 2020-04-18T15:24:10 |
Scheme
|
UTF-8
|
Scheme
| false | false | 16 |
scm
|
folds.scm
|
(section) @fold
| false |
d09f6708d8b2d86ec1cf11d2b7ab3849bfa6e3aa
|
f04bd2aa263016ca71be253d24a1c3bd9ab5d972
|
/chapter1/exercises/1.1.scm
|
7b1d58d14f12c7664b08082d44c62d746309c6af
|
[] |
no_license
|
concreted/l-i-s-p
|
91a91e45456fc67e5764606d6b33233b96268405
|
e09d346705e9798bd4e30692db55d5545dece321
|
refs/heads/master
| 2016-09-05T10:47:26.712576 | 2014-08-08T19:45:53 | 2014-08-08T19:51:41 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 5,138 |
scm
|
1.1.scm
|
; L-I-S-P
; lisp in small pieces
; book by Christian Quennec, Kathleen Calloway
; reproduced by Aric Huang
; =========================================================================
(use-syntax (ice-9 syncase)) ;required for define-syntax
; Language definition/special forms
; =========================================================================
; evaluate: takes program expression (e) and environment (env) as input.
; Environment is a data structure associating variables and values.
(define (evaluate e env)
(define (eval)
(if (atom? e) ; (atom? e) == (not (pair? e))
(cond ((symbol? e) (lookup e env))
((or (number? e) (string? e) (char? e) (boolean? e) (vector? e))
e)
(else (wrong "Cannot evaluate" e)) )
(case (car e)
((quote) (cadr e))
((if) (if (evaluate (cadr e) env)
(evaluate (caddr e) env)
(evaluate (cadddr e) env) ))
((begin) (eprogn (cdr e) env))
((set!) (update! (cadr e) env (evaluate (caddr e) env)))
((lambda) (make-function (cadr e) (cddr e) env))
(else (invoke (evaluate (car e) env)
(evlis (cdr e) env) )) ) ) )
(define (trace)
(if (pair? e)
(let ((result (eval)))
(display e)
(display ": ")
(display result)
(newline)
result)
(eval)))
(trace))
; Helper functions for evaluate
(define (atom? e)
(not (pair? e)))
(define (wrong msg e)
(display msg)
(display ": ")
(display e)
(display "\n"))
(define (println msg)
(display msg)
(newline))
; eprogn: Evaluate expressions (exps) with environment (env) sequentially in order.
; Only executes if (exps) is a pair?
(define (eprogn exps env)
(if (pair? exps)
(if (pair? (cdr exps))
(begin (evaluate (car exps) env)
(eprogn (cdr exps) env) )
(evaluate (car exps) env) )
empty-begin) )
; evlis: Evaluate list of expressions (exps) and returns result values in a list.
; Evaluates right-to-left.
(define (evlis exps env)
(if (pair? exps)
(cons (evaluate (car exps) env)
(evlis (cdr exps) env) )
'() ) )
; lookup: Lookup variable (id) in the environment association list (env).
(define (lookup id env)
(if (pair? env)
(if (eq? (caar env) id)
(cdar env)
(lookup id (cdr env)) )
(wrong "No such binding" id) ))
; update!: Sets variable (id) in environment (env) to a value (value).
(define (update! id env value)
(if (pair? env)
(if (eq? (caar env) id)
(begin (set-cdr! (car env) value)
value)
(update! id (cdr env) value) )
(wrong "No such binding" id) ))
; extend: Adds list of variables (variables) and corresponding
; values (values) to environment (env)
(define (extend env variables values)
(cond ((pair? variables)
(if (pair? values)
(cons (cons (car variables) (car values))
(extend env (cdr variables) (cdr values)) )
(wrong "Too few values") ) )
((null? variables)
(if (null? values)
env
(wrong "Too many values") ) )
((symbol? variables) (cons (cons variables values) env)) ) )
; invoke: Call a function (fn) with arguments (args)
(define (invoke fn args)
(if (procedure? fn)
(fn args)
(wrong "Not a function" fn) ) )
; make-function: Creates a new environment used during function execution.
; Creates new environment by adding variables bound during function call
; (variables) to parent environment (env), and executes function body
; (body) in that environment.
(define (make-function variables body env)
(lambda (values)
(eprogn body (extend env variables values)) ) )
; Library functions/macros
; =========================================================================
(define env.init '())
(define empty-begin 813)
(define env.global env.init)
(define-syntax definitial
(syntax-rules ()
((definitial name)
(begin (set! env.global (cons (cons 'name 'void) env.global))
'name ) )
((definitial name value)
(begin (set! env.global (cons (cons 'name value) env.global))
'name ) ) ) )
(define-syntax defprimitive
(syntax-rules ()
((defprimitive name value arity)
(definitial name
(lambda (values)
(if (= arity (length values))
(apply value values)
(wrong "Incorrect arity"
(list 'name values) ) ) ) ) ) ) )
(definitial t #t)
(definitial f #f)
(definitial nil '())
(definitial foo)
(definitial bar)
(definitial fib)
(definitial fact)
(defprimitive cons cons 2)
(defprimitive car car 1)
(defprimitive set-cdr! set-cdr! 2)
(defprimitive + + 2)
(defprimitive eq? eq? 2)
(defprimitive < < 2)
; Interpreter
; =========================================================================
(define (chapter1-scheme)
(define (toplevel)
(display "l-i-s-p> ")
(display (evaluate (read) env.global))
(newline)
(toplevel) )
(toplevel) )
(chapter1-scheme)
; Other - unused, variants
; =========================================================================
#!
; evlis - defined with left-to-right evaluation.
(define (evlis exps env)
(if (pair? exps)
(let ((argument1 (evaluate (car exps) env)))
(cons argument1 (evlis (cdr exps) env)) )
'() ) )
!#
| true |
ef59279dc07874481adc903fb45ca9acbda74504
|
df0ba5a0dea3929f29358805fe8dcf4f97d89969
|
/exercises/software-engineering/05/next-look-and-say.scm
|
a1c7dbdfde513fb77a5c3231919707e67c392d03
|
[
"MIT"
] |
permissive
|
triffon/fp-2019-20
|
1c397e4f0bf521bf5397f465bd1cc532011e8cf1
|
a74dcde683538be031186cf18367993e70dc1a1c
|
refs/heads/master
| 2021-12-15T00:32:28.583751 | 2021-12-03T13:57:04 | 2021-12-03T13:57:04 | 210,043,805 | 14 | 31 |
MIT
| 2019-12-23T23:39:09 | 2019-09-21T19:41:41 |
Racket
|
UTF-8
|
Scheme
| false | false | 943 |
scm
|
next-look-and-say.scm
|
(define (take-while p l)
(if (or (null? l)
(not (p (car l))))
'()
(cons (car l)
(take-while p (cdr l)))))
(define (drop-while p l)
(if (or (null? l)
(not (p (car l))))
l
(drop-while p (cdr l))))
(define (next-look-and-say y)
(define (take-first-equals l)
(take-while (lambda (x)
(= x (car l)))
l))
(define (drop-first-equals l)
(drop-while (lambda (x)
(= x (car l)))
l))
(if (null? y)
'()
(cons (length (take-first-equals y))
(cons (car y)
(next-look-and-say (drop-first-equals y))))))
(load "../testing/check.scm")
(check (next-look-and-say '()) => '())
(check (next-look-and-say '(1)) => '(1 1))
(check (next-look-and-say '(1 1 2 3 3)) => '(2 1 1 2 2 3))
(check (next-look-and-say '(1 1 2 2 3 3 3 3)) => '(2 1 2 2 4 3))
(check-report)
(check-reset!)
| false |
8a05e29546429e7705fbacc2b0dda11f6d56535f
|
1ed47579ca9136f3f2b25bda1610c834ab12a386
|
/sec3/q3.02.scm
|
828bcbb31f3ee1d08891f86c52d509fd5e3f0c79
|
[] |
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 | 583 |
scm
|
q3.02.scm
|
(define (make-monitored f)
(let ((counter 0))
(define (how-many-calls?) counter)
(define (reset-count)
(begin (set! counter 0)
counter))
(define (dispatch m)
(cond ((eq? m 'how-many-calls?) (how-many-calls?))
((eq? m 'reset-count) (reset-count))
(else (begin (set! counter (+ counter 1))
(f m)))))
dispatch))
;; まずhow-many-calls?内部手続きをcounterを返すように定義し、
;; dispatch内で、how-many-calls?を()で囲うと手続き呼び出しになってokだった。
| false |
102cefff25965e4dd459620c7afae5c88b4afc9b
|
bcb10d60b55af6af2f5217b6338f9f2c99af8a14
|
/swat.sch
|
a301aa26b12d1580d3daf3308af5889c870ede68
|
[
"Apache-2.0"
] |
permissive
|
lars-t-hansen/swat
|
e3aaffdca6fe74208b51a1ffed6fc380a91296d7
|
f6c30bee2ceaa47a4fe0e6f7ac4e7c3257921c3a
|
refs/heads/master
| 2020-03-18T08:45:41.600093 | 2018-06-20T05:49:47 | 2018-06-20T05:49:47 | 134,526,524 | 8 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 158,122 |
sch
|
swat.sch
|
;;; -*- fill-column: 80; indent-tabs-mode: nil; show-trailing-whitespace: t -*-
;;;
;;; Copyright 2018 Lars T Hansen.
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
;;; This is R7RS Scheme.
;;;
;;; The program is known to work with Larceny 1.3 (http://larcenists.org).
;;;
;;; It does not work with Chibi-Scheme (https://github.com/ashinn/chibi-scheme),
;;; which crashes on startup.
;;; Swat is a mostly Scheme-syntaxed statically typed language that targets
;;; WebAssembly. See MANUAL.md for more information.
;;;
;;; This program translates Swat programs to the WebAssembly text format
;;; accepted by Firefox's wasmTextToBinary, plus supporting JS code.
;;;
;;; See the functions "swat" and "swat-noninteractive" for sundry ways to run
;;; this program, and see the shell script "swat" for a command line interface.
(import (scheme base)
(scheme char)
(scheme cxr)
(scheme file)
(scheme process-context)
(scheme read)
(scheme write))
(define-syntax assert
(syntax-rules ()
((assert expr)
(if (not expr)
(begin (error "Assertion failed" (quote expr))
#t)))))
(define-syntax canthappen
(syntax-rules ()
((canthappen)
(begin (error "Can't happen")
#t))))
;; Driver. This never returns, it always calls exit.
(define (main)
(define-values (files mode stdout-mode wizard? expect-success)
(parse-command-line (cdr (command-line))))
(define (process-input-file input-filename)
(let ((root (substring input-filename 0 (- (string-length input-filename) 5))))
(call-with-input-file input-filename
(lambda (in)
(cond (stdout-mode
(process-input mode wizard? input-filename in (current-output-port) root))
((not expect-success)
(process-input mode wizard? input-filename in (open-output-string) root))
((or (eq? mode 'js) (eq? mode 'js-bytes) (eq? mode 'js-wasm))
(let ((output-filename (string-append root ".js")))
(remove-file output-filename)
(call-with-output-file output-filename
(lambda (out)
(process-input mode wizard? input-filename in out root)))))
((eq? mode 'wast)
(let ((output-filename (string-append root ".wast")))
(remove-file output-filename)
(call-with-output-file output-filename
(lambda (out)
(process-input mode wizard? input-filename in out root)))))
(else
(canthappen)))))))
(if (null? files)
(fail "No input files"))
(let ((result (handle-failure
(lambda ()
(for-each process-input-file files)
#t))))
(exit (eq? result expect-success))))
(define (parse-command-line args)
(define js-mode #f)
(define js-bytes-mode #f)
(define js-wasm-mode #f)
(define stdout-mode #f)
(define wizard-mode #f)
(define expect-success #t)
(define files '())
(define (fail . irritants)
(display (apply splice irritants))
(newline)
(usage)
(exit #f))
(let loop ((args args))
(cond ((null? args)
(if (> (+ (if js-mode 1 0) (if js-bytes-mode 1 0) (if js-wasm-mode 1 0)) 1)
(fail "At most one of --js, --js+bytes, and --js+wasm may be specified"))
(if (and stdout-mode (or js-bytes-mode js-wasm-mode))
(fail "--stdout is not compatible with --js+bytes and --js+wasm"))
(if (and (not expect-success)
(or js-mode js-bytes-mode js-wasm-mode stdout-mode))
(fail "--fail is not compatible with other modes"))
(values (reverse files)
(cond (js-mode 'js)
(js-bytes-mode 'js-bytes)
(js-wasm-mode 'js-wasm)
(else 'wast))
stdout-mode
wizard-mode
expect-success))
(else
(let* ((arg (car args))
(len (string-length arg)))
(cond ((or (string=? arg "--js") (string=? arg "-j"))
(set! js-mode #t)
(loop (cdr args)))
((string=? arg "--js+bytes")
(set! js-bytes-mode #t)
(loop (cdr args)))
((string=? arg "--js+wasm")
(set! js-wasm-mode #t)
(loop (cdr args)))
((or (string=? arg "--stdout") (string=? arg "-s"))
(set! stdout-mode #t)
(loop (cdr args)))
((or (string=? arg "--fail") (string=? arg "-f"))
(set! expect-success #f)
(loop (cdr args)))
((string=? arg "--wizard")
(set! wizard-mode #t)
(loop (cdr args)))
((or (string=? arg "--help") (string=? arg "-h"))
(usage)
(exit #t))
((and (> len 0) (char=? (string-ref arg 0) #\-))
(fail "Bad option " arg))
((and (> len 5) (string=? (substring arg (- len 5) len) ".swat"))
(set! files (cons arg files))
(loop (cdr args)))
(else
(fail "Bad file name " arg))))))))
(define (usage)
(display
"Usage: swat options file ...
By default, generate fn.wast for each fn.swat, producing wasm text output for
swat code and ignoring all `js` clauses. However, this is usually not what
you want.
Options:
--js, -j For each input file fn.swat generate fn.js.
When fn.js is loaded it defines global objects corresponding to
all the modules in fn.swat, with each object's `module` property
holding a WebAssembly.Module instance.
The output cannot be loaded in browsers, as it contains
wasm text.
--js+bytes For each input file fn.swat generate fn.metabytes.js and fn.js.
The fn.metabytes.js file contains wasm text and must be executed
to produce fn.bytes.js; the latter file defines the byte
values for the module(s) in fn.swat (in the form of JS code).
fn.bytes.js must be loaded before fn.js. When they are loaded,
the effect is as for --js.
The output can only be loaded in browsers that do not limit the
size of modules that can be compiled synchronously with
`new WebAssembly.Module` and similar interfaces.
--js+wasm For each input file fn.swat generate fn.metawasm.js and fn.js.
The fn.metawasm.js file contains wasm text and must be executed
and postprocessed to produce fn.wasm; the latter file contains
a wasm encoding of a wasm module.
fn.swat must contain exactly one module.
fn.js does not depend on fn.wasm and can be loaded at any time
using any mechanism. The web page must itself load, compile,
and instantiate fn.wasm using streaming APIs.
--wizard Emit code for the wasm GC feature, using unlanded code.
--stdout, -s For testing: Print output to stdout.
If --js is not present it only prints wasm text output;
otherwise it prints JS clauses too.
Not compatible with options other than --js.
--fail, -f For testing: Expect failure, reverse the exit codes.
At most one of --js, --js+bytes, and --js+wasm must be specified.
For detailed usage instructions see MANUAL.md.
"))
;; Generic source->object file processor. The input and output ports may be
;; string ports, and names may reflect that.
(define (process-input mode wizard? input-filename in out root)
(define (defmodule? phrase)
(and (pair? phrase) (eq? (car phrase) 'defmodule)))
(define (literal-js? phrase)
(and (pair? phrase) (eq? (car phrase) 'js)))
(define (read-source filename in)
(with-exception-handler
(lambda (x)
(if (read-error? x)
(fail "Malformed input on" filename "\n" (error-object-message x))
(fail "Unknown input error on" filename "\n" x)))
(lambda ()
(read in))))
(assert (memq mode '(wast js js-bytes js-wasm)))
(let ((num-modules 0)
(wasm-name (string-append root ".wasm"))
(meta-name (string-append root ".metawasm.js"))
(bytes-name (string-append root ".metabytes.js")))
(do ((phrase (read-source input-filename in) (read-source input-filename in)))
((eof-object? phrase))
(cond ((defmodule? phrase)
(set! num-modules (+ num-modules 1))
(let*-values (((support) (make-js-support))
((module-name code) (expand-module phrase support wizard?)))
(case mode
((js js-bytes js-wasm)
(write-js-header out module-name)
(write-js-module out mode module-name wasm-name code)
(write-js-footer out support))
((wast)
(display (string-append ";; " module-name "\n") out)
(pretty-print out code)))
(case mode
((js-bytes)
(remove-file bytes-name)
(call-with-output-file bytes-name
(lambda (out2)
(write-js-wast-for-bytes out2 module-name code))))
((js-wasm)
(remove-file meta-name)
(call-with-output-file meta-name
(lambda (out2)
(write-js-wast-for-wasm out2 module-name code)))))))
((literal-js? phrase)
(case mode
((js js-bytes js-wasm)
(display (cadr phrase) out)
(newline out))))
(else
(fail "Bad toplevel phrase" phrase))))
(if (and (eq? mode 'js-wasm) (not (= num-modules 1)))
(fail "Exactly one defmodule required for --js-wasm"))))
;; Environments.
;;
;; These map names to the entities they denote in the program. There is a
;; single lexically scoped namespace for everything, including loop labels.
(define (make-env locals globals-cell)
(cons locals globals-cell))
(define env.locals car)
(define env.globals-cell cdr)
(define (make-globals-cell)
(vector '()))
(define (env.globals env)
(vector-ref (env.globals-cell env) 0))
(define (env.globals-set! env x)
(vector-set! (env.globals-cell env) 0 x))
(define (define-env-global! env name also-internal? denotation)
(env.globals-set! env (cons (cons name denotation) (env.globals env)))
(if also-internal?
(env.globals-set! env (cons (cons (splice '% name '%) denotation) (env.globals env)))))
(define (extend-env env assocs)
(make-env (append assocs (env.locals env))
(env.globals-cell env)))
(define (lookup env name)
(cond ((assq name (env.locals env)) => cdr)
((assq name (env.globals env)) => cdr)
(else #f)))
(define (lookup-predicated env name match? tag)
(let ((probe (lookup env name)))
(cond ((not probe)
(fail "No binding for" name))
((match? probe)
probe)
(else
(fail "Binding does not denote a" tag name probe)))))
(define (lookup-type env name)
(lookup-predicated env name type? "type"))
(define (lookup-func env name)
(lookup-predicated env name func? "function"))
(define (lookup-func-or-virtual env name)
(lookup-predicated env name (lambda (x) (or (func? x) (virtual? x))) "function"))
(define (lookup-virtual env name)
(lookup-predicated env name virtual? "virtual"))
(define (lookup-global env name)
(lookup-predicated env name global? "global"))
(define (lookup-loop env name)
(lookup-predicated env name loop? "loop"))
(define (lookup-variable env name)
(lookup-predicated env name (lambda (x)
(or (local? x) (global? x)))
"variable"))
(define (lookup-class env name)
(let ((probe (lookup-type env name)))
(if (not (type.class probe))
(fail "Not a class type" name))
(type.class probe)))
(define (virtuals env)
(reverse (filter virtual? (map cdr (env.globals env)))))
(define (classes env)
(map type.class (reverse (filter (lambda (x)
(and (type? x) (type.class x)))
(map cdr (env.globals env))))))
(define (make-standard-env)
(let ((env (make-env '() (make-globals-cell))))
(define-keywords! env)
(define-types! env)
(define-constructors! env)
(define-syntax! env)
(define-builtins! env)
env))
;; Translation context.
(define-record-type type/cx
(%make-cx% slots gensym-id vid support name table-index table-elements types strings string-id vector-id
functions globals memory data wizard?)
cx?
(slots cx.slots cx.slots-set!) ; Slots storage (during body expansion)
(gensym-id cx.gensym-id cx.gensym-id-set!) ; Gensym ID
(vid cx.vid cx.vid-set!) ; Next virtual function ID (for dispatch)
(support cx.support) ; Host support code (opaque structure)
(name cx.name) ; Module name
(table-index cx.table-index cx.table-index-set!) ; Next table index
(table-elements cx.table-elements cx.table-elements-set!) ; List of table entries, reversed
(types cx.types cx.types-set!) ; Function types ((type . id) ...) where
; id is some gensym name and type is a
; rendered func type, we use ids to refer
; to the type because wasmTextToBinary inserts
; additional types. We can search the list with assoc.
(strings cx.strings cx.strings-set!) ; String literals ((string . id) ...)
(string-id cx.string-id cx.string-id-set!) ; Next string literal id
(vector-id cx.vector-id cx.vector-id-set!) ; Next vector type id
(functions cx.functions cx.functions-set!) ; List of all functions in order encountered, reversed
(globals cx.globals cx.globals-set!) ; List of all globals in order encountered, reversed
(memory cx.memory cx.memory-set!) ; Number of flat-memory bytes allocated so far
(data cx.data cx.data-set!) ; List of i32 values for data, reversed
(wizard? cx.wizard?)) ; #t for wizard-mode output
(define (make-cx name support wizard?)
(%make-cx% #|slots|# #f #|gensym-id|# 0 #|vid|# 0 support name #|table-index|# 0 #|table-elements|# '()
#|types|# '() #|strings|# '() #|string-id|# 0 #|vector-id|# 0 #|functions|# '() #|globals|# '()
#|memory|# 0 #|data|# '() wizard?))
;; Gensym.
(define (new-name cx tag)
(let ((n (cx.gensym-id cx)))
(cx.gensym-id-set! cx (+ n 1))
(splice "$" tag "_" n)))
;; Cells for late binding of counters.
(define-record-type type/indirection
(%make-indirection% n)
indirection?
(n indirection-get indirection-set!))
(define (make-indirection)
(%make-indirection% -1))
;; Modules
;; Special forms that appear at the top level of the module are not handled by
;; standard expanders but mustn't be redefined at that level, so must be
;; defined as keywords.
;;
;; defvirtual- actually makes no sense - a virtual would always be imported as a
;; func - but we reserve it anyway.
(define (define-keywords! env)
(for-each (lambda (name)
(define-env-global! env name #f '*keyword*))
'(defun defun+ defun- defvar defvar+ defvar- defconst defconst+ defconst-
defclass defclass+ defclass- defvirtual defvirtual+ defvirtual-)))
;; To handle imports and mutual references we must perform several passes over
;; the module to define functions in the table. The first pass handles
;; imports, which are given the lowest indices. The second pass defines other
;; functions and globals. Then the third phase expands function bodies.
(define (expand-module m support wizard?)
(check-list-atleast m 2 "Bad module" m)
(check-symbol (cadr m) "Bad module name" m)
(let* ((env (make-standard-env))
(name (symbol->string (cadr m)))
(cx (make-cx name support wizard?))
(body (cddr m)))
(for-each (lambda (d)
(check-list-atleast d 1 "Bad top-level phrase" d)
(case (car d)
((defclass)
(expand-class-phase1 cx env d))
((defun- defun defun+
defconst- defconst defconst+
defvar- defvar defvar+
defvirtual defvirtual+)
#t)
(else
(fail "Unknown top-level phrase" d))))
body)
(resolve-classes cx env)
(label-classes cx env)
(synthesize-class-descriptors cx env)
(for-each (lambda (d)
(case (car d)
((defun defun+ defun-)
(expand-func-phase1 cx env d))
((defvirtual defvirtual+)
(expand-virtual-phase1 cx env d))
((defconst- defconst defconst+ defvar- defvar defvar+)
(expand-global-phase1 cx env d))))
body)
(for-each (lambda (d)
(case (car d)
((defun defun+)
(expand-func-phase2 cx env d))
((defvirtual defvirtual+)
(expand-virtual-phase2 cx env d))
((defconst defconst+ defvar defvar+)
(expand-global-phase2 cx env d))))
body)
(compute-dispatch-maps cx env)
(renumber-globals cx env)
(renumber-functions cx env)
(compute-class-descriptors cx env)
(emit-class-descriptors cx env)
(emit-string-literals cx env)
(values name
(cons 'module
(append
(generate-memory cx env)
(generate-class-types cx env)
(generate-function-types cx env)
(generate-tables cx env)
(generate-globals cx env)
(generate-functions cx env))))))
(define (generate-memory cx env)
(if (> (cx.memory cx) 0)
(let ((pages (ceiling (/ (cx.memory cx) 65536))))
(list `(memory ,pages ,pages)
`(data (i32.const 0)
,(apply string-append
(map (lambda (i)
(let ((s (number->string (+ #x100000000 (if (>= i 0) i (+ i #xFFFFFFFF))) 16)))
(string #\\ (string-ref s 7) (string-ref s 8)
#\\ (string-ref s 5) (string-ref s 6)
#\\ (string-ref s 3) (string-ref s 4)
#\\ (string-ref s 1) (string-ref s 2))))
(reverse (cx.data cx)))))))
'()))
(define (generate-class-types cx env)
(if (cx.wizard? cx)
(map (lambda (cls)
`(type ,(wast-class-name cls)
(struct (field i32)
,@(map (lambda (x) `(field ,(wast-type-name cx (cadr x))))
(class.fields cls)))))
(classes env))
'()))
(define (generate-function-types cx env)
(reverse (map (lambda (x)
`(type ,(cdr x) ,(car x)))
(cx.types cx))))
(define (generate-tables cx env)
(if (not (null? (cx.table-elements cx)))
`((table anyfunc (elem ,@(reverse (cx.table-elements cx)))))
'()))
(define (generate-globals cx env)
(map (lambda (g)
(let* ((t (wast-type-name cx (global.type g)))
(t (if (global.mut? g) `(mut ,t) t)))
(if (global.module g)
`(import ,(global.module g) ,(symbol->string (global.name g)) (global ,t))
`(global ,@(if (global.export? g) `((export ,(symbol->string (global.name g)))) '())
,t
,(global.init g)))))
(sort (cx.globals cx)
(lambda (x y)
(< (indirection-get (global.id x)) (indirection-get (global.id y)))))))
(define (generate-functions cx env)
(map (lambda (f)
(if (func.module f)
`(import ,(func.module f) ,(symbol->string (func.name f)) ,(assemble-function cx f '()))
(func.defn f)))
(sort (cx.functions cx)
(lambda (x y)
(< (indirection-get (func.id x)) (indirection-get (func.id y)))))))
(define (parse-toplevel-name n import? tag)
(check-symbol n (string-append "Bad " tag " name") n)
(let* ((name (symbol->string n))
(len (string-length name)))
(let loop ((i 0))
(cond ((= i len)
(values (if import? "" #f) n))
((char=? (string-ref name i) #\:)
(if (not import?)
(fail "Import name not allowed for " tag n))
(if (= i (- len 1))
(fail "Import name can't have empty name part" n))
(values (substring name 0 i)
(string->symbol (substring name (+ i 1) len))))
(else
(loop (+ i 1)))))))
;; Classes
(define-record-type type/class
(%make-class% name base fields resolved? type label virtuals subclasses depth desc-addr)
class?
(name class.name) ; Class name as symbol
(base class.base class.base-set!) ; Base class object, or #f in Object
(fields class.fields class.fields-set!) ; ((name type-object) ...)
(resolved? class.resolved? class.resolved-set!) ; #t iff class has been resolved
(type class.type class.type-set!) ; Type object referencing this class object
(label class.label class.label-set!) ; Integer ID for class, or #f
(virtuals class.virtuals class.virtuals-set!) ; Virtuals map: Map from virtual-function-id to
; function when function is called on instance of
; this class as list ((vid function) ...), the
; function stores its own table index.
(subclasses class.subclasses class.subclasses-set!) ; List of direct subclasses, unordered
(depth class.depth class.depth-set!) ; Depth in the hierarchy, Object==0
(desc-addr class.desc-addr)) ; Indirection cell holding descriptor address
(define (make-class name base fields)
(%make-class% name base fields
#|resolved?|# #f #|type|# #f #|label|# #f #|virtuals|# '() #|subclasses|# '() #|depth|# 0
#|desc-addr|# (make-indirection)))
(define (class=? a b)
(eq? a b))
(define (format-class cls)
(class.name cls))
(define (define-class! cx env name base fields)
(let ((cls (make-class name base fields)))
(define-env-global! env name #f (make-class-type cls))
cls))
(define-record-type type/accessor
(make-accessor name field-name)
accessor?
(name accessor.name)
(field-name accessor.field-name))
(define (define-accessor! cx env field-name)
(let* ((name (splice "*" field-name))
(probe (lookup env name)))
(cond ((not probe)
(define-env-global! env name #f (make-accessor name field-name)))
((accessor? probe) #t)
(else
(fail "Conflict between accessor and other global" name)))))
(define (accessor-expression? env x)
(and (list? x)
(= (length x) 2)
(symbol? (car x))
(accessor? (lookup env (car x)))))
(define (field-index cls field-name)
(let loop ((fields (class.fields cls)) (i 0))
(cond ((null? fields) (fail "Field not found: " field-name))
((eq? field-name (caar fields)) i)
(else (loop (cdr fields) (+ i 1))))))
;; Phase 1 records the names of base and field types, checks syntax, and records
;; the type; the types are resolved and checked by the resolution phase.
;;
;; After phase1, "base" is #f or a symbol and "fields" only has the local
;; fields, with unresolved types. After the resolution phase, "base" is #f or a
;; class, and "fields" has the fields for the class and its base classes, with
;; the base classes' fields first.
(define (expand-class-phase1 cx env d)
(check-list-atleast d 2 "Bad defclass" d)
(let ((name (cadr d)))
(check-symbol name "class name" name)
(if (not (char-upper-case? (string-ref (symbol->string name) 0)))
(fail "Class names should have an initial upper case letter"))
(check-unbound env name "already defined at global level")
(let-values (((base body)
(let ((rest (cddr d)))
(if (and (not (null? rest))
(let ((x (car rest)))
(and (list? x)
(= (length x) 2)
(eq? (car x) 'extends))))
(let ((base-name (cadr (car rest))))
(check-symbol base-name "base class name" base-name)
(values base-name (cdr rest)))
(values 'Object rest)))))
(let loop ((body body) (fields '()))
(if (null? body)
(define-class! cx env name base (reverse fields))
(let ((c (car body)))
(cond ((not (and (list? c) (not (null? c))))
(fail "Invalid clause in defclass" c d))
((eq? (car c) 'extends)
(fail "Invalid extends clause in defclass" c d))
((symbol? (car c))
(check-list c 2 "Bad field" c d)
(let* ((name (car c))
(_ (check-symbol name "Bad field name" name d))
(type (cadr c)))
(loop (cdr body) (cons (list name type) fields))))
(else
(fail "Bad clause in defclass" c d)))))))))
(define (resolve-classes cx env)
(for-each (lambda (cls)
(resolve-class cx env cls '()))
(classes env)))
(define (resolve-class cx env cls forbidden)
(if (not (class.resolved? cls))
(begin
(if (memq cls forbidden)
(fail "Recursive class hierarchy" cls))
(if (class.base cls)
(let ((base (lookup-class env (class.base cls))))
(resolve-class cx env base (cons cls forbidden))
(class.base-set! cls base)
(class.subclasses-set! base (cons cls (class.subclasses base)))
(class.depth-set! cls (+ (class.depth base) 1)))
(begin
(assert (= (class.depth cls) 0))))
(class.resolved-set! cls #t)
(let ((base-fields (if (class.base cls)
(class.fields (class.base cls))
'())))
(let ((fields (map (lambda (f)
(let ((name (car f))
(ty (parse-type cx env (cadr f))))
(if (class-type? ty)
(resolve-class cx env (type.class ty) (cons cls forbidden)))
(if (and (Vector-type? ty) (class? (type.vector-element ty)))
(resolve-class cx env (type.class (type.vector-element ty)) (cons (type.vector-element ty) forbidden)))
(if (assq name base-fields)
(fail "Duplicated field name" name))
(list name ty)))
(class.fields cls))))
(for-each (lambda (f)
(define-accessor! cx env (car f)))
fields)
(class.fields-set! cls (append base-fields fields)))))))
;; Functions
(define-record-type type/func
(%make-func% name module export? id rendered-params formals result slots env defn table-index specialization)
basefunc?
(name func.name) ; Function name as a symbol
(module func.module) ; Module name as a string, or #f if not imported
(export? func.export?) ; #t iff exported, otherwise #f
(id func.id) ; Function index in Wasm module
(rendered-params func.rendered-params) ; ((name type-name) ...)
(formals func.formals) ; ((name type) ...)
(result func.result) ; type
(slots func.slots) ; as returned by make-slots
(env func.env) ; Environment extended by parameters
(defn func.defn func.defn-set!) ; Generated wasm code as s-expression
(table-index func.table-index func.table-index-set!) ; Index in the default table, or #f
(specialization func.specialization)) ; #f for normal functions, virtual-specialization for virtuals
(define (format-func fn)
(func.name fn))
(define (make-func name module export? rendered-params formals result slots env)
(let ((defn #f)
(table-index #f))
(%make-func% name module export? (make-indirection) rendered-params formals result slots env defn table-index #f)))
(define (func? x)
(and (basefunc? x) (not (func.specialization x))))
(define (make-virtual name module export? rendered-params formals result slots env vid)
(let ((defn #f)
(table-index #f)
(uber-discriminator #f)
(discriminators #f))
(%make-func% name module export? (make-indirection) rendered-params formals result slots env defn table-index
(make-virtual-specialization vid uber-discriminator discriminators))))
(define-record-type type/virtual-specialization
(make-virtual-specialization vid uber-discriminator discriminators)
virtual-specialization?
;; Virtual function ID (a number)
(vid virtual-specialization.vid)
;; The class obj named in the virtual's signature
(uber-discriminator virtual-specialization.uber-discriminator virtual-specialization.uber-discriminator-set!)
;; ((class func) ...) computed from body, unsorted
(discriminators virtual-specialization.discriminators virtual-specialization.discriminators-set!))
(define (virtual? x)
(and (basefunc? x) (virtual-specialization? (func.specialization x))))
(define (virtual.vid x)
(virtual-specialization.vid (func.specialization x)))
(define (virtual.uber-discriminator x)
(virtual-specialization.uber-discriminator (func.specialization x)))
(define (virtual.uber-discriminator-set! x v)
(virtual-specialization.uber-discriminator-set! (func.specialization x) v))
(define (virtual.discriminators x)
(virtual-specialization.discriminators (func.specialization x)))
(define (virtual.discriminators-set! x v)
(virtual-specialization.discriminators-set! (func.specialization x) v))
(define (register-func! cx func)
(cx.functions-set! cx (cons func (cx.functions cx))))
;; formals is ((name type) ...)
(define (define-function! cx env name module export? params formals result-type slots)
(let ((func (make-func name module export? params formals result-type slots env)))
(define-env-global! env name #f func)
(register-func! cx func)
func))
(define (assemble-function cx func body)
(let ((f (prepend-signature cx
(func.name func)
(func.rendered-params func)
(func.result func)
(func.export? func)
body)))
(func.defn-set! func f)
f))
(define (expand-func-phase1 cx env f)
(expand-func-or-virtual-phase1
cx env f "function"
(lambda (cx env name module export? params formals result slots)
(define-function! cx env name module export? params formals result slots))))
(define (expand-func-phase2 cx env f)
(let* ((signature (cadr f))
(body (cddr f)))
(let-values (((_ name) (parse-toplevel-name (car signature) #t "")))
(let* ((func (lookup-func env name))
(env (func.env func))
(slots (func.slots func)))
(cx.slots-set! cx slots)
(assemble-function cx func (expand-func-body cx body (func.result func) env))))))
(define (expand-func-body cx body expected-type env)
(let-values (((expanded result-type) (expand-expr cx (cons 'begin body) env)))
(let ((drop? (and (void-type? expected-type)
(not (void-type? result-type)))))
(if (not drop?)
(let ((val+ty (widen-value cx env expanded result-type expected-type)))
(if val+ty
`(,@(get-slot-decls cx (cx.slots cx)) ,(car val+ty))
(fail "Return type mismatch" (pretty-type expected-type) (pretty-type result-type))))
`(,@(get-slot-decls cx (cx.slots cx)) ,expanded (drop))))))
(define (prepend-signature cx name rendered-params result-type export? body)
(let* ((f body)
(f (if (void-type? result-type)
f
(cons `(result ,(wast-type-name cx result-type)) f)))
(f (append rendered-params f))
(f (if export?
(cons `(export ,(symbol->string name)) f)
f))
(f (cons 'func f)))
f))
(define (expand-func-or-virtual-phase1 cx env f tag k)
(check-list-atleast f 2 (string-append "Bad " tag) f)
(let* ((import? (memq (car f) '(defun- defvirtual-)))
(signature (cadr f))
(_ (check-list-atleast signature 1 "Bad signature" signature))
(export? (memq (car f) '(defun+ defvirtual+)))
(body (cddr f))
(slots (make-slots)))
(if (and import? (not (null? body)))
(fail "Import function can't have a body" f))
(let-values (((module name) (parse-toplevel-name (car signature) import? tag)))
(check-unbound env name "already defined at global level")
(cx.slots-set! cx #f)
(let loop ((xs (cdr signature))
(bindings '())
(formals '())
(params '()))
(cond ((null? xs)
(k cx (extend-env env bindings) name module export?
(reverse params) (reverse formals) *void-type* slots))
((eq? (car xs) '->)
(check-list xs 2 "Bad signature" signature)
(let ((t (parse-type cx env (cadr xs))))
(k cx (extend-env env bindings) name module export?
(reverse params) (reverse formals) t slots)))
(else
(let ((first (car xs)))
(check-list first 2 "Bad parameter" first f)
(check-symbol (car first) "Bad parameter name" first)
(let ((t (parse-type cx env (cadr first)))
(name (car first)))
(if (assq name bindings)
(fail "Duplicate parameter" name))
(let-values (((slot _) (claim-param slots t)))
(loop (cdr xs)
(cons (cons name (make-local name slot t)) bindings)
(cons (list name t) formals)
(cons `(param ,(wast-type-name cx t)) params)))))))))))
(define (renumber-functions cx env)
(let ((functions (reverse (cx.functions cx)))
(id 0))
(for-each (lambda (fn)
(if (func.module fn)
(begin
(indirection-set! (func.id fn) id)
(set! id (+ id 1)))))
functions)
(for-each (lambda (fn)
(if (not (func.module fn))
(begin
(indirection-set! (func.id fn) id)
(set! id (+ id 1)))))
functions)))
;; Virtuals
;; See above for make-virtual and virtual? and additional accessors
(define (expand-virtual-phase1 cx env f)
(expand-func-or-virtual-phase1
cx env f "virtual"
(lambda (cx env name module export? params formals result-type slots)
(if (not (> (length formals) 0))
(fail "Virtual function requires at least one argument" f))
(let* ((first (car formals))
(name (car first))
(type (cadr first)))
(if (not (eq? name 'self))
(fail "Name of first argument to virtual must be 'self'" f))
(if (not (class-type? type))
(fail "Type of first argument to virtual must be a class" f)))
(let* ((vid (cx.vid cx))
(virt (make-virtual name module export? params formals result-type slots env vid)))
(cx.vid-set! cx (+ vid 1))
(define-env-global! env name #f virt)
(register-func! cx virt)))))
(define (expand-virtual-phase2 cx env f)
(let* ((signature (cadr f))
(name (car signature))
(disc-name (cadr (cadr signature)))
(body (cddr f))
(virt (lookup-virtual env name))
(v-formals (func.formals virt))
(v-result (func.result virt))
(disc-cls (lookup-class env disc-name))
(discs '()))
;; Check syntax and type relationships
(for-each
(lambda (clause)
(check-list clause 2 "Virtual dispatch clause" clause f)
(let ((clause-name (car clause))
(clause-fn (cadr clause)))
(check-symbol clause-name "Virtual dispatch clause" clause-name f)
(check-symbol clause-fn "Virtual dispatch clause" clause-fn f)
(let ((clause-cls (lookup-class env clause-name)))
(if (not (subclass? clause-cls disc-cls))
(fail "Virtual dispatch clause" clause-cls clause))
(let ((meth (lookup-func-or-virtual env clause-fn)))
(let ((fn-formals (func.formals meth))
(fn-result (func.result meth)))
(if (not (= (length fn-formals) (length v-formals)))
(fail "Virtual method mismatch: arguments" f meth))
(for-each (lambda (fn-arg v-arg)
(if (not (type=? (cadr fn-arg) (cadr v-arg)))
(fail "Virtual method mismatch: arguments" f meth)))
(cdr fn-formals) (cdr v-formals))
(if (not (subtype? fn-result v-result))
(fail "Virtual method mismatch: result" f clause))
(let* ((fn-first (car fn-formals))
(fn-first-ty (cadr fn-first)))
(if (not (class-type? fn-first-ty))
(fail "Method discriminator" clause))
(let ((fn-first-cls (type.class fn-first-ty)))
(if (not (subclass? clause-cls fn-first-cls))
(fail "Method discriminator" clause "\n" clause-cls "\n" fn-first-cls))
(set! discs (cons (list clause-cls meth) discs)))))))))
body)
;; Check for duplicated type discriminators
(do ((body body (cdr body)))
((null? body))
(let ((b (car body)))
(if (assq (car b) (cdr body))
(fail "Duplicate name in virtual dispatch" f))))
;; Save information about the types and functions
(virtual.uber-discriminator-set! virt disc-cls)
(virtual.discriminators-set! virt (reverse discs))
;; Assign table IDs to the functions or trampolines.
;; For virtuals there's a downcast along the call path of the reeiver
;; argument, from the discriminator type of the virtual to the discriminator
;; type of the method. The downcast will never fail, because computing the
;; dispatch ensures that it will not, but the wasm type system requires it.
;;
;; With swat's current virtual function design the method is just a normal
;; function and the discriminator type of the method need not be the exact
;; class that is used in dispatch; the former can be a supertype of the
;; latter. So we end up needing to insert an entire trampoline along the
;; call path to do the proper downcast during virtual dispatch. If we had a
;; defvirtual/defmethod split then we could just insert the cast in the
;; method.
(for-each (lambda (disc)
(let ((disc-cls (car disc))
(disc-meth (cadr disc)))
(if (and (cx.wizard? cx)
(not (class=? disc-cls (type.class (cadr (car v-formals))))))
(let ((trampoline (create-virtual-trampoline cx env virt disc-cls disc-meth)))
(set-car! (cdr disc) trampoline)
(set! disc-meth trampoline)))
(if (not (func.table-index disc-meth))
(let ((index (cx.table-index cx)))
(cx.table-index-set! cx (+ index 1))
(func.table-index-set! disc-meth index)
(cx.table-elements-set! cx (cons (func.id disc-meth) (cx.table-elements cx)))))))
(virtual.discriminators virt))
;; Hash-cons the signature
(let ((typeref
(let ((t `(func ,@(func.rendered-params virt)
,@(if (not (void-type? (func.result virt)))
`((result ,(wast-type-name cx (func.result virt))))
'()))))
(let ((probe (assoc t (cx.types cx))))
(if probe
(cdr probe)
(let ((name (new-name cx "ty")))
(cx.types-set! cx (cons (cons t name) (cx.types cx)))
name))))))
;; Create the body
;; TODO: The null check is redundant because resolve-nonnull-virtual will
;; expand to a struct.get that performs a null check anyway.
(assemble-virtual
cx
virt
`((if (ref.is_null (get_local 0))
(unreachable))
(call_indirect ,typeref
,@(forward-arguments v-formals)
,(let-values (((e0 t0)
(resolve-nonnull-virtual cx env
'(get_local 0) (class.type disc-cls)
(virtual.vid virt))))
e0)))))))
(define (forward-arguments formals)
(do ((i 0 (+ i 1))
(fs formals (cdr fs))
(xs '() (cons `(get_local ,i) xs)))
((null? fs) (reverse xs))))
(define (assemble-virtual cx virtual body)
(let ((f (prepend-signature cx
(func.name virtual)
(func.rendered-params virtual)
(func.result virtual)
(func.export? virtual)
body)))
(func.defn-set! virtual f)
f))
;; We want to generate a function that has the same signature as the virtual and
;; a body that calls the target function with a downcast of the descriminator
;; argument to the target type.
(define (create-virtual-trampoline cx env virtual clause-cls disc-meth)
(assert (cx.wizard? cx))
(let* ((name (new-name cx "trampoline"))
(module #f)
(export? #f)
(formals (func.formals virtual))
(params (func.rendered-params virtual))
(result-type (func.result virtual))
(slots (make-slots))
(func (define-function! cx env name module export? params formals result-type slots))
(virt-cls (virtual.uber-discriminator virtual)))
(assemble-function
cx func
`((call ,(func.id disc-meth)
(struct.narrow
,(wast-type-name cx (class.type virt-cls))
,(wast-type-name cx (class.type clause-cls))
(get_local 0))
,@(cdr (forward-arguments formals)))))
func))
(define (transitive-subclasses cls)
(cons cls (apply append (map transitive-subclasses (class.subclasses cls)))))
(define (closest-discriminator cls discs)
(let loop ((discs discs) (best #f))
(cond ((null? discs)
(assert best)
best)
((not (subclass? cls (caar discs)))
(loop (cdr discs) best))
((not best)
(loop (cdr discs) (car discs)))
((subclass? (car best) (caar discs))
(loop (cdr discs) best))
(else
(loop (cdr discs) (car discs))))))
(define (compute-dispatch-maps cx env)
(for-each (lambda (v)
(let ((uber (virtual.uber-discriminator v))
(discs (virtual.discriminators v))
(vid (virtual.vid v)))
;; Do we need an error function at the top discriminator?
;; If so, cons an entry onto discs with (uber fn)
;;
;; FIXME: not right, we need a true error function here.
;; FIXME: assq will probably work but assoc with class=? would be better?
(if (not (assq uber discs))
(let ((err (make-func 'error #f #f '() '() *void-type* #f #f)))
(assemble-function cx err '(unreachable))
(register-func! cx err)
(func.table-index-set! err 0)
(set! discs (cons (list uber err) discs))))
;; Add entries for v to the affected classes.
;;
;; TODO: This is slow, presumably we can precompute stuff to
;; make it faster.
(for-each (lambda (disc)
(for-each (lambda (cls)
(let* ((d (closest-discriminator cls discs))
(fn (cadr d)))
(class.virtuals-set! cls (cons (list vid fn)
(class.virtuals cls)))))
(transitive-subclasses (car disc))))
discs)))
(virtuals env)))
;; Globals
(define-record-type type/global
(%make-global% name module export? mut? id type init)
global?
(name global.name)
(module global.module) ; Either #f or a string naming the module
(export? global.export?)
(mut? global.mut?)
(id global.id)
(type global.type)
(init global.init global.init-set!))
(define (make-global name module export? mut? type)
(%make-global% name module export? mut? (make-indirection) type #f))
(define (define-global! cx env name module export? mut? type)
(let* ((glob (make-global name module export? mut? type)))
(define-env-global! env name #f glob)
(register-global! cx glob)
glob))
(define (register-global! cx glob)
(cx.globals-set! cx (cons glob (cx.globals cx))))
(define (expand-global-phase1 cx env g)
(check-list-oneof g '(3 4) "Bad global" g)
(let* ((import? (memq (car g) '(defconst- defvar-)))
(export? (memq (car g) '(defconst+ defvar+)))
(module (if import? "" #f))
(mut? (memq (car g) '(defvar defvar+ defvar-)))
(type (parse-type cx env (caddr g)))
(init (if (null? (cdddr g)) #f (cadddr g))))
(if (and import? init)
(fail "Import global can't have an initializer"))
(let-values (((module name) (parse-toplevel-name (cadr g) import? "global")))
(check-unbound env name "already defined at global level")
(define-global! cx env name module export? mut? type))))
;; We could expand the init during phase 1 but we'll want to broaden
;; inits to encompass global imports soon.
(define (expand-global-phase2 cx env g)
(if (not (null? (cdddr g)))
(let ((init (cadddr g)))
(let-values (((_ name) (parse-toplevel-name (cadr g) #t "")))
(let ((defn (lookup-global env name)))
(let-values (((v t) (expand-constant-expr cx init)))
(global.init-set! defn v)))))))
(define (renumber-globals cx env)
(let ((globals (reverse (cx.globals cx)))
(id 0))
(for-each (lambda (g)
(if (global.module g)
(begin
(indirection-set! (global.id g) id)
(set! id (+ id 1)))))
globals)
(for-each (lambda (g)
(if (not (global.module g))
(begin
(indirection-set! (global.id g) id)
(set! id (+ id 1)))))
globals)))
;; Locals
(define-record-type type/local
(make-local name slot type)
local?
(name local.name)
(slot local.slot)
(type local.type))
;; Local slots storage
(define-record-type type/slots
(%make-slots% tracker accessors)
slots?
(tracker slots.tracker)
(accessors slots.accessors slots.accessors-set!))
(define (make-slots)
(%make-slots% (make-tracker) '()))
(define (make-slot-accessors)
(let ((slots '()))
(cons (lambda (_) slots)
(lambda (_ x) (set! slots x)))))
(define (slot-accessors-for-type slots t)
(let loop ((accessors (slots.accessors slots)))
(cond ((null? accessors)
(let ((g+s (make-slot-accessors)))
(slots.accessors-set! slots (cons (cons t g+s) (slots.accessors slots)))
(values (car g+s) (cdr g+s))))
((type=? (caar accessors) t)
(let ((g+s (cdar accessors)))
(values (car g+s) (cdr g+s))))
(else
(loop (cdr accessors))))))
(define-record-type type/slot-undo
(make-undo getter setter slot)
slot-undo?
(getter undo.getter)
(setter undo.setter)
(slot undo.slot))
;; Tracks defined slot numbers and types. Used by the slots structure.
(define-record-type type/tracker
(%make-tracker% next defined)
tracker?
(next tracker.next tracker.next-set!) ; number of next local
(defined tracker.defined tracker.defined-set!)) ; list of type names for locals (not params), reverse order
(define (make-tracker)
(%make-tracker% 0 '()))
;; returns (slot-id garbage)
(define (claim-param slots t)
(do-claim-slot slots t #f))
;; returns (slot-id undo-info)
(define (claim-local slots t)
(do-claim-slot slots t #t))
(define (unclaim-locals slots undos)
(for-each (lambda (u)
(let ((getter (undo.getter u))
(setter (undo.setter u))
(slot (undo.slot u)))
(setter slots (cons slot (getter slots)))))
undos))
(define (get-slot-decls cx slots)
(map (lambda (t)
`(local ,(wast-type-name cx t)))
(reverse (tracker.defined (slots.tracker slots)))))
(define (do-claim-slot slots t record?)
(let-values (((getter setter) (slot-accessors-for-type slots t)))
(let* ((spare (getter slots))
(slot (if (not (null? spare))
(let ((number (car spare)))
(setter slots (cdr spare))
number)
(let* ((tracker (slots.tracker slots))
(number (tracker.next tracker)))
(tracker.next-set! tracker (+ number 1))
(if record?
(tracker.defined-set! tracker (cons t (tracker.defined tracker))))
number))))
(values slot (make-undo getter setter slot)))))
;; Type constructors
(define-record-type type/type-constructor
(make-type-constructor name)
type-constructor?
(name type-constructor.name))
(define *Vector-constructor* (make-type-constructor 'Vector))
(define (define-constructors! env)
(define-env-global! env 'Vector #f *Vector-constructor*))
;; Types
(define-record-type type/type
(make-type name primitive ref-base vector-element vector-id class vector)
type?
(name type.name) ; a symbol: the same as primitive, or one of "ref", "vector", "class"
(primitive type.primitive) ; #f or a symbol naming the primitive type
(ref-base type.ref-base) ; #f, or this is the type (Ref ref-base)
(vector-element type.vector-element) ; #f, or this is the type (Vector vector-element)
(vector-id type.vector-id) ; #f, or the global id of this vector type, set with vector-element
(class type.class) ; #f, or the class object
(vector type.vector-of type.vector-of-set!)) ; #f, or the type here is (Vector this)
(define (make-primitive-type name)
(make-type name name #f #f #f #f #f))
(define (make-ref-type base)
(make-type 'ref #f base #f #f #f #f))
(define (make-vector-type cx env element)
(let ((probe (type.vector-of element)))
(if probe
probe
(let* ((id (cx.vector-id cx))
(t (make-type 'vector #f #f element id #f #f)))
(cx.vector-id-set! cx (+ id 1))
(type.vector-of-set! element t)
t))))
(define (make-class-type cls)
(let ((t (make-type 'class #f #f #f #f cls #f)))
(class.type-set! cls t)
t))
(define *void-type* (make-type 'void #f #f #f #f #f #f))
(define *i32-type* (make-primitive-type 'i32))
(define *i64-type* (make-primitive-type 'i64))
(define *f32-type* (make-primitive-type 'f32))
(define *f64-type* (make-primitive-type 'f64))
(define *String-type* (make-primitive-type 'String))
(define *anyref-type* (make-primitive-type 'anyref))
(define *Object-type* (make-class-type (make-class 'Object #f '())))
(define (type=? a b)
(or (eq? a b)
(and (eq? (type.name a) (type.name b))
(case (type.name a)
((ref) (type=? (type.ref-base a) (type.ref-base b)))
((vector) (type=? (type.vector-element a) (type.vector-element b)))
((class) (class=? (type.class a) (type.class b)))
(else #f)))))
(define (void-type? x) (eq? x *void-type*))
(define (i32-type? x) (eq? x *i32-type*))
(define (i64-type? x) (eq? x *i64-type*))
(define (f32-type? x) (eq? x *f32-type*))
(define (f64-type? x) (eq? x *f64-type*))
(define (String-type? x) (eq? x *String-type*))
(define (anyref-type? x) (eq? x *anyref-type*))
(define (integer-type? x)
(case (type.primitive x)
((i32 i64) #t)
(else #f)))
(define (floating-type? x)
(case (type.primitive x)
((f32 f64) #t)
(else #f)))
(define (number-type? x)
(case (type.primitive x)
((i32 i64 f32 f64) #t)
(else #f)))
(define (subtype? a b)
(cond ((and (class-type? a) (class-type? b))
(subclass? (type.class a) (type.class b)))
(else
(type=? a b))))
(define (class-type? x)
(not (not (type.class x))))
(define (Vector-type? x)
(not (not (type.vector-element x))))
(define (reference-type? x)
(or (class-type? x) (String-type? x) (anyref-type? x) (Vector-type? x)))
(define (nullable-reference-type? x)
(or (class-type? x) (anyref-type? x) (Vector-type? x)))
(define (subclass? a b)
(or (eq? a b)
(let ((parent (class.base a)))
(and parent
(subclass? parent b)))))
(define (proper-subclass? a b)
(and (not (eq? a b))
(let ((parent (class.base a)))
(and parent
(subclass? parent b)))))
;; TODO: We need to reserve the name Object but we should only emit things for
;; it if it is actually used for anything. This way we avoid a memory segment
;; when it isn't needed.
;;
;; This could be part of a general DCE thing, every global name could carry a
;; referenced bit that we set when we look it up.
(define (define-types! env)
(define-env-global! env 'i32 #f *i32-type*)
(define-env-global! env 'i64 #f *i64-type*)
(define-env-global! env 'f32 #f *f32-type*)
(define-env-global! env 'f64 #f *f64-type*)
(define-env-global! env 'String #f *String-type*)
(define-env-global! env 'anyref #f *anyref-type*)
(define-env-global! env 'Object #f *Object-type*))
(define (parse-type cx env t)
(cond ((and (symbol? t) (lookup env t)) =>
(lambda (probe)
(if (type? probe)
probe
(fail "Does not denote a type" t probe))))
((and (list? t) (= (length t) 2) (symbol? (car t)) (lookup env (car t))) =>
(lambda (probe)
(if (type-constructor? probe)
(cond ((eq? probe *Vector-constructor*)
(let ((base (parse-type cx env (cadr t))))
(make-vector-type cx env base)))
(else
(fail "Does not denote a type constructor" t probe)))
(fail "Does not denote a type constructor" t probe))))
(else
(fail "Invalid type" t))))
(define (widen-value cx env value value-type target-type)
(cond ((type=? value-type target-type)
(list value value-type))
((and (class-type? value-type)
(class-type? target-type)
(proper-subclass? (type.class value-type) (type.class target-type)))
(list (wast-upcast-class-to-class cx env (type.class target-type) value)
target-type))
((and (class-type? value-type)
(anyref-type? target-type))
(list (wast-upcast-class-to-anyref cx env value)
target-type))
((and (Vector-type? value-type)
(anyref-type? target-type))
(list (render-upcast-maybenull-vector-to-anyref cx env (type.vector-element value-type) value)
target-type))
((and (String-type? value-type)
(anyref-type? target-type))
(list (render-upcast-string-to-anyref cx env value)
target-type))
(else
#f)))
;; Loop labels
(define-record-type type/loop
(make-loop id break continue type)
loop?
(id loop.id)
(break loop.break)
(continue loop.continue)
(type loop.type loop.type-set!))
(define (loop.set-type! x t)
(let ((current (loop.type x)))
(cond ((not current)
(loop.type-set! x t))
((eq? t current))
(else
(fail "Type mismatch for loop" (loop.id x))))))
;; Expressions
(define (expand-expr cx expr env)
(cond ((symbol? expr)
(expand-symbol cx expr env))
((number? expr)
(expand-number expr))
((char? expr)
(expand-char expr))
((boolean? expr)
(expand-boolean expr))
((string? expr)
(expand-string-literal cx expr env))
((and (list? expr) (not (null? expr)))
(if (symbol? (car expr))
(let ((probe (lookup env (car expr))))
(cond ((not probe)
(fail "Unbound name in form" (car expr) "\n" expr))
((or (func? probe) (virtual? probe))
(expand-func-call cx expr env probe))
((accessor? probe)
(expand-accessor cx expr env))
((expander? probe)
((expander.expander probe) cx expr env))
(else
(fail "Attempting to call non-function" expr))))
(fail "Not a call" expr)))
(else
(fail "Unknown expression" expr))))
;; Returns ((val type) ...)
(define (expand-expressions cx exprs env)
(map (lambda (e)
(let-values (((e0 t0) (expand-expr cx e env)))
(list e0 t0)))
exprs))
(define (expand-symbol cx expr env)
(cond ((numbery-symbol? expr)
(expand-numbery-symbol expr))
((lookup-variable env expr) =>
(lambda (x)
(cond ((local? x)
(values `(get_local ,(local.slot x)) (local.type x)))
((global? x)
(values `(get_global ,(global.id x)) (global.type x)))
(else
(canthappen)))))
(else
(fail "Symbol does not denote variable or number" expr))))
(define min-i32 (- (expt 2 31)))
(define max-i32 (- (expt 2 31) 1))
(define max-u32 (- (expt 2 32) 1))
(define min-i64 (- (expt 2 63)))
(define max-i64 (- (expt 2 63) 1))
(define (expand-constant-expr cx expr)
(cond ((numbery-symbol? expr)
(expand-numbery-symbol expr))
((or (number? expr) (char? expr) (boolean? expr))
(expand-number expr))
(else (canthappen))))
;; TODO: really want to check that the syntax won't blow up string->number
;; later.
(define (numbery-symbol? x)
(and (symbol? x)
(let ((name (symbol->string x)))
(and (> (string-length name) 2)
(char=? #\. (string-ref name 1))
(memv (string-ref name 0) '(#\I #\L #\F #\D))))))
(define (expand-numbery-symbol expr)
(let* ((name (symbol->string expr))
(val (string->number (substring name 2 (string-length name)))))
(case (string-ref name 0)
((#\I)
(check-i32-value val expr)
(values (wast-number val *i32-type*) *i32-type*))
((#\L)
(check-i64-value val expr)
(values (wast-number val *i64-type*) *i64-type*))
((#\F)
(check-f32-value val expr)
(values (wast-number val *f32-type*) *f32-type*))
((#\D)
(check-f64-value val expr)
(values (wast-number val *f64-type*) *f64-type*))
(else (canthappen)))))
(define (expand-number expr)
(cond ((and (integer? expr) (exact? expr))
(cond ((<= min-i32 expr max-i32)
(values (wast-number expr *i32-type*) *i32-type*))
(else
(check-i64-value expr)
(values (wast-number expr *i64-type*) *i64-type*))))
((number? expr)
(check-f64-value expr)
(values (wast-number expr *f64-type*) *f64-type*))
((char? expr)
(expand-char expr))
((boolean? expr)
(expand-boolean expr))
(else
(fail "Bad syntax" expr))))
(define (expand-char expr)
(values (wast-number (char->integer expr) *i32-type*) *i32-type*))
(define (expand-boolean expr)
(values (wast-number (if expr 1 0) *i32-type*) *i32-type*))
(define (string-literal->id cx lit)
(let ((probe (assoc lit (cx.strings cx))))
(if probe
(cdr probe)
(let ((id (cx.string-id cx)))
(cx.string-id-set! cx (+ id 1))
(cx.strings-set! cx (cons (cons lit id) (cx.strings cx)))
id))))
(define (expand-string-literal cx expr env)
(values (render-string-literal cx env (string-literal->id cx expr))
*String-type*))
(define-record-type type/expander
(%make-expander% name expander len)
expander?
(name expander.name)
(expander expander.expander)
(len expander.len))
(define (make-expander name expander len)
(let ((expander (case (car len)
((atleast)
(lambda (cx expr env)
(if (< (length expr) (cadr len))
(fail "Bad" name "expected more operands" expr)
(expander cx expr env))))
((oneof)
(lambda (cx expr env)
(if (not (memv (length expr) (cdr len)))
(fail "Bad" name "expected more operands" expr)
(expander cx expr env))))
((precisely)
(lambda (cx expr env)
(if (not (= (length expr) (cadr len)))
(fail "Bad" name "expected more operands" expr)
(expander cx expr env))))
(else
(canthappen)))))
(%make-expander% name expander len)))
(define (define-syntax! env)
(define-env-global! env 'begin #t (make-expander 'begin expand-begin '(atleast 1)))
(define-env-global! env 'if #t (make-expander 'if expand-if '(oneof 3 4)))
(define-env-global! env 'cond #f (make-expander 'cond expand-cond '(atleast 1)))
(define-env-global! env 'set! #t (make-expander 'set! expand-set! '(precisely 3)))
(define-env-global! env 'inc! #f (make-expander 'inc! expand-inc!+dec! '(precisely 2)))
(define-env-global! env 'dec! #f (make-expander 'dec! expand-inc!+dec! '(precisely 2)))
(define-env-global! env 'let #t (make-expander 'let expand-let+let* '(atleast 3)))
(define-env-global! env 'let* #t (make-expander 'let* expand-let+let* '(atleast 3)))
(define-env-global! env 'loop #t (make-expander 'loop expand-loop '(atleast 3)))
(define-env-global! env 'break #t (make-expander 'break expand-break '(oneof 2 3)))
(define-env-global! env 'continue #t (make-expander 'continue expand-continue '(precisely 2)))
(define-env-global! env 'while #f (make-expander 'while expand-while '(atleast 2)))
(define-env-global! env 'do #f (make-expander 'do expand-do '(atleast 3)))
(define-env-global! env 'case #f (make-expander 'case expand-case '(atleast 2)))
(define-env-global! env '%case% #f (make-expander '%case% expand-%case% '(atleast 2)))
(define-env-global! env 'and #t (make-expander 'and expand-and '(atleast 1)))
(define-env-global! env 'or #t (make-expander 'or expand-or '(atleast 1)))
(define-env-global! env 'trap #t (make-expander 'trap expand-trap '(oneof 1 2)))
(define-env-global! env 'new #f (make-expander 'new expand-new '(atleast 2)))
(define-env-global! env 'null #t (make-expander 'null expand-null '(precisely 2)))
(define-env-global! env 'is #f (make-expander 'is expand-is '(precisely 3)))
(define-env-global! env 'as #f (make-expander 'as expand-as '(precisely 3)))
(define-env-global! env '%wasm% #t (make-expander '%wasm% expand-wasm '(oneof 2 3))))
(define (define-builtins! env)
(define-env-global! env 'not #f (make-expander 'not expand-not '(precisely 2)))
(define-env-global! env 'select #f (make-expander 'select expand-select '(precisely 4)))
(define-env-global! env 'zero? #f (make-expander 'zero? expand-zero? '(precisely 2)))
(define-env-global! env 'nonzero? #f (make-expander 'zero? expand-nonzero? '(precisely 2)))
(define-env-global! env 'null? #t (make-expander 'null? expand-null? '(precisely 2)))
(define-env-global! env 'nonnull? #f (make-expander 'nonnull? expand-nonnull? '(precisely 2)))
(define-env-global! env 'bitnot #f (make-expander 'bitnot expand-bitnot '(precisely 2)))
(for-each (lambda (name)
(define-env-global! env name #f (make-expander name expand-unop '(precisely 2))))
'(clz ctz popcnt neg abs sqrt ceil floor nearest trunc extend8 extend16 extend32))
(for-each (lambda (name)
(define-env-global! env name #f (make-expander name expand-binop '(precisely 3))))
'(+ %+% - %-% * div divu rem remu bitand bitor bitxor shl shr shru rotl rotr max min copysign))
(for-each (lambda (name)
(define-env-global! env name #f (make-expander name expand-relop '(precisely 3))))
'(< <u <= <=u > >u >= >=u = %>u% %=%))
(for-each (lambda (name)
(define-env-global! env name #f (make-expander name expand-conversion '(precisely 2))))
'(i32->i64 u32->i64 i64->i32 f32->f64 f64->f32 f64->i32 f64->i64 i32->f64 i64->f64
f32->i32 f32->i64 i32->f32 i64->f32 f32->bits bits->f32 f64->bits bits->f64))
(define-env-global! env 'string #f (make-expander 'string expand-string '(atleast 1)))
(define-env-global! env 'string-length #f (make-expander 'string-length expand-string-length '(precisely 2)))
(define-env-global! env 'string-ref #f (make-expander 'string-ref expand-string-ref '(precisely 3)))
(define-env-global! env 'string-append #t (make-expander 'string-append expand-string-append '(atleast 1)))
(define-env-global! env 'substring #f (make-expander 'substring expand-substring '(precisely 4)))
(for-each (lambda (name)
(define-env-global! env name #f (make-expander name expand-string-relop '(precisely 3))))
'(string=? string<? string<=? string>? string>=?))
(define-env-global! env 'vector-length #f (make-expander 'vector-length expand-vector-length '(precisely 2)))
(define-env-global! env 'vector-ref #f (make-expander 'vector-ref expand-vector-ref '(precisely 3)))
(define-env-global! env 'vector-set! #f (make-expander 'vector-set! expand-vector-set! '(precisely 4)))
(define-env-global! env 'vector->string #f (make-expander 'vector->string expand-vector->string '(precisely 2)))
(define-env-global! env 'string->vector #f (make-expander 'string->vector expand-string->vector '(precisely 2)))
(define-env-global! env '%object-desc% #f (make-expander '%object-desc% expand-object-desc '(precisely 2)))
(define-env-global! env '%object-desc-id% #f (make-expander '%object-desc-id% expand-object-desc-id '(precisely 2)))
(define-env-global! env '%object-desc-length% #f (make-expander '%object-desc-length% expand-object-desc-length '(precisely 2)))
(define-env-global! env '%object-desc-ref% #f (make-expander '%object-desc-ref% expand-object-desc-ref '(precisely 3)))
(define-env-global! env '%object-desc-virtual% #f (make-expander '%object-desc-virtual% expand-object-desc-virtual '(precisely 3)))
(define-env-global! env '%vector-desc% #f (make-expander '%vector-desc% expand-vector-desc '(precisely 2)))
(define-env-global! env '%vector-desc-id% #f (make-expander '%vector-desc-id% expand-vector-desc-id '(precisely 2))))
;; Primitive syntax
(define (expand-begin cx expr env)
(if (null? (cdr expr))
(values (void-expr) *void-type*)
(let-values (((e0 t0) (expand-expr cx (cadr expr) env)))
(let loop ((exprs (cddr expr)) (body (list e0)) (ty t0))
(cond ((null? exprs)
(cond ((= (length body) 1)
(values (car body) ty))
(else
(values `(block ,@(wast-type-name-spliceable cx ty) ,@(reverse body)) ty))))
((not (void-type? ty))
(loop exprs (cons 'drop body) *void-type*))
(else
(let-values (((e1 t1) (expand-expr cx (car exprs) env)))
(loop (cdr exprs) (cons e1 body) t1))))))))
(define (expand-if cx expr env)
(let-values (((test t0) (expand-expr cx (cadr expr) env)))
(check-i32-type t0 "'if' condition" expr)
(case (length expr)
((3)
(let-values (((consequent t1) (expand-expr cx (caddr expr) env)))
(values `(if ,test ,consequent) *void-type*)))
((4)
(let*-values (((consequent t1) (expand-expr cx (caddr expr) env))
((alternate t2) (expand-expr cx (cadddr expr) env)))
(check-same-type t1 t2 "'if' arms" expr)
(values `(if ,@(wast-type-name-spliceable cx t1) ,test ,consequent ,alternate) t1)))
(else
(fail "Bad 'if'" expr)))))
(define (expand-set! cx expr env)
(let* ((name (cadr expr))
(val (caddr expr)))
(let-values (((e0 t0) (expand-expr cx val env)))
(cond ((symbol? name)
(let ((binding (lookup-variable env name)))
(cond ((local? binding)
(let ((val+ty (widen-value cx env e0 t0 (local.type binding))))
(if (not val+ty)
(check-same-type t0 (local.type binding) "'set!'" expr))
(values `(set_local ,(local.slot binding) ,(car val+ty)) *void-type*)))
((global? binding)
(let ((val+ty (widen-value cx env e0 t0 (global.type binding))))
(if (not val+ty)
(check-same-type t0 (global.type binding) "'set!'" expr))
(values `(set_global ,(global.id binding) ,(car val+ty)) *void-type*)))
(else
(canthappen)))))
((accessor-expression? env name)
(let-values (((base-expr cls field-name field-type)
(process-accessor-expression cx name env))
((ev tv)
(expand-expr cx val env)))
(let ((val+ty (widen-value cx env ev tv field-type)))
(if (not val+ty)
(check-same-type field-type tv "'set!' object field" expr))
(values (wast-maybenull-field-update cx env cls field-name base-expr (car val+ty) (cadr val+ty))
*void-type*))))
(else
(fail "Illegal lvalue" expr))))))
(define (expand-let+let* cx expr env)
(define is-let* (eq? (car expr) 'let*))
(define (process-bindings bindings env)
(let loop ((bindings bindings) (new-locals '()) (code '()) (undos '()) (env env))
(if (null? bindings)
(values (reverse new-locals)
(reverse code)
undos
(if is-let* env (extend-env env new-locals)))
(let ((binding (car bindings)))
(check-list binding 2 "Bad binding" binding)
(let* ((name (car binding))
(_ (check-symbol name "Bad local name" name))
(_ (if (and (not is-let*) (assq name new-locals))
(fail "Duplicate let binding" name)))
(init (cadr binding)))
(let*-values (((e0 t0) (expand-expr cx init env))
((slot undo) (claim-local (cx.slots cx) t0)))
(let ((new-binding (cons name (make-local name slot t0))))
(loop (cdr bindings)
(cons new-binding new-locals)
(cons `(set_local ,slot ,e0) code)
(cons undo undos)
(if is-let* (extend-env env (list new-binding)) env)))))))))
(let* ((bindings (cadr expr))
(body (cddr expr)))
(let*-values (((new-locals code undos new-env) (process-bindings bindings env))
((e0 t0) (expand-expr cx `(begin ,@body) new-env)))
(unclaim-locals (cx.slots cx) undos)
(let ((type (wast-type-name-spliceable cx t0)))
(if (not (null? code))
(if (and (pair? e0) (eq? (car e0) 'begin))
(values `(block ,@type ,@code ,@(cdr e0)) t0)
(values `(block ,@type ,@code ,e0) t0))
(values e0 t0))))))
(define (expand-loop cx expr env)
(let* ((id (cadr expr))
(_ (check-symbol id "Bad loop id" id))
(body (cddr expr))
(loop (make-loop id (new-name cx "brk") (new-name cx "cnt") #f))
(env (extend-env env (list (cons id loop))))
(body (map car (expand-expressions cx body env))))
(values `(block ,(loop.break loop)
,@(wast-type-name-spliceable cx (loop.type loop))
(loop ,(loop.continue loop)
,@body
(br ,(loop.continue loop)))
,@(if (void-type? (loop.type loop))
'()
(list (typed-constant (loop.type loop) 0))))
(loop.type loop))))
(define (expand-break cx expr env)
(let* ((id (cadr expr))
(_ (check-symbol id "Bad loop id" id))
(e (if (null? (cddr expr)) #f (caddr expr)))
(loop (lookup-loop env id)))
(if e
(let-values (((e0 t0) (expand-expr cx e env)))
(loop.set-type! loop t0)
(values `(br ,(loop.break loop) ,e0) *void-type*))
(begin
(loop.set-type! loop *void-type*)
(values `(br ,(loop.break loop)) *void-type*)))))
(define (expand-continue cx expr env)
(let* ((id (cadr expr))
(_ (check-symbol id "Bad loop id" id))
(loop (lookup-loop env id)))
(values `(br ,(loop.continue loop)) *void-type*)))
(define (expand-trap cx expr env)
(let ((t (if (null? (cdr expr))
*void-type*
(parse-type cx env (cadr expr)))))
(values '(unreachable) t)))
(define (expand-new cx expr env)
(let* ((tyexpr (cadr expr))
(type (parse-type cx env tyexpr)))
(cond ((class-type? type)
(let* ((cls (type.class type))
(fields (class.fields cls))
(actuals (expand-expressions cx (cddr expr) env))
(actuals (check-and-widen-arguments cx env fields actuals expr)))
(values (wast-new-class cx env cls actuals) type)))
((Vector-type? type)
(check-list expr 4 "Bad arguments to 'new'" expr)
(let*-values (((el tl) (expand-expr cx (caddr expr) env))
((ei ti) (expand-expr cx (cadddr expr) env)))
(check-i32-type tl "'new' vector length" expr)
(let ((base (type.vector-element type)))
(check-same-type base ti "'new' initial value" expr)
(values (render-new-vector cx env base el ei) type))))
(else
(fail "Invalid type to 'new'" tyexpr expr)))))
(define (expand-null cx expr env)
(let* ((tyexpr (cadr expr))
(type (parse-type cx env tyexpr)))
(values
(cond ((class-type? type) `(ref.null ,(wast-type-name cx type)))
((Vector-type? type) (render-vector-null cx env (type.vector-element type)))
((anyref-type? type) '(ref.null anyref))
(else (fail "Not a valid reference type for 'null'" tyexpr)))
type)))
(define (expand-is cx expr env)
(let* ((tyexpr (cadr expr))
(target-type (parse-type cx env tyexpr)))
(let-values (((e t) (expand-expr cx (caddr expr) env)))
(cond ((anyref-type? target-type)
(values `(i32.eqz (ref.is_null ,e)) *i32-type*))
((String-type? target-type)
(cond ((String-type? t)
`(block i32 ,e drop (i32.const 1)))
((anyref-type? t)
(values (render-maybenull-anyref-is-string cx env e) *i32-type*))
(else
(fail "Bad source type in 'is'" t expr))))
((class-type? target-type)
(let ((target-cls (type.class target-type)))
(cond ((class-type? t)
(let ((value-cls (type.class t)))
(cond ((subclass? value-cls target-cls)
(values `(i32.eqz (ref.is_null ,e)) *i32-type*))
((subclass? target-cls value-cls)
(maybenull-class-is-class cx env target-cls e t))
(else
(fail "Types in 'is' are unrelated" expr)))))
((anyref-type? t)
(maybenull-anyref-is-class cx env target-cls e t))
(else
(fail "Expression in 'is' is not of class type" expr)))))
((Vector-type? target-type)
(cond ((and (Vector-type? t) (type=? target-type t))
(values `(i32.eqz (ref.is_null ,e)) *i32-type*))
((anyref-type? t)
(maybenull-anyref-is-vector cx env target-type e t))
(else
(fail "Bad source type in 'is'" t expr))))
(else
(fail "Bad target type in 'is'" target-type expr))))))
(define (expand-as cx expr env)
(let* ((tyexpr (cadr expr))
(target-type (parse-type cx env tyexpr)))
(let-values (((e t) (expand-expr cx (caddr expr) env)))
(cond ((anyref-type? target-type)
(cond ((anyref-type? t)
(values e target-type))
((String-type? t)
(values (render-upcast-string-to-anyref cx env e) target-type))
((class-type? t)
(values (wast-upcast-class-to-anyref cx env e) target-type))
((Vector-type? t)
(values (render-upcast-maybenull-vector-to-anyref cx env (type.vector-element t) e) target-type))
(else
(canthappen))))
((String-type? target-type)
(cond ((String-type? t)
(values e target-type))
((anyref-type? t)
(downcast-maybenull-anyref-to-string cx env e))
(else
(fail "Bad source type in 'as'" t expr))))
((class-type? target-type)
(let ((target-cls (type.class target-type)))
(cond ((class-type? t)
(let ((value-cls (type.class t)))
(cond ((class=? value-cls target-cls)
(values e t))
((subclass? value-cls target-cls)
(values (wast-upcast-class-to-class cx env target-cls e)
(class.type target-cls)))
((subclass? target-cls value-cls)
(downcast-maybenull-class-to-class cx env target-cls e t))
(else
(fail "Types in 'as' are unrelated" expr)))))
((anyref-type? t)
(downcast-maybenull-anyref-to-class cx env target-cls e))
(else
(fail "Expression in 'as' is not of class type" expr)))))
((Vector-type? target-type)
(cond ((and (Vector-type? t) (type=? target-type t))
(values e target-type))
((anyref-type? t)
(downcast-maybenull-anyref-to-vector cx env target-type e t))
(else
(fail "Bad source type in 'as'" t expr))))
(else
(fail "Bad target type in 'is'" target-type expr))))))
;; Dynamic type testing and dynamic downcasts.
;;
;; A private field of each object accessed by (%object-desc% obj) holds an
;; address A in flat memory of the object's descriptor. The descriptor is laid
;; out in both directions from the address and looks like this:
;;
;; -m: virtual function table index
;; ...
;; -1: virtual function table index
;; A ---> 0: Class ID
;; 1: Length
;; 2: Class ID of Supetype 0
;; ...
;; k: Class ID of this type [same as slot #0]
;;
;; When a class instance is allocated, the address A is placed in this first,
;; private field.
;;
;; At the moment, each virtual function has its own index from a global index
;; space, and when it is invoked it uses its index to reference into the virtual
;; function table of the object to the index into the virtual function table in
;; the module. The vtable is sparse, but unused elements are filled with -1 (in
;; slots where the virtual function in question is not defined on the type).
;; The virtual function table in the module is dense.
;;
;; The supertype table for a class is a vector of nonnegative integers. It
;; holds the class ids (which are positive integers) for all the classes that
;; are supertypes of the class, including the ID of the class itself. To test
;; whether a class of A is a subtype of B, where A is not known at all, we grab
;; B's class ID and see if it appears in the list of A's supertypes. This is a
;; constant time operation: a length check and a lookup. We simply test whether
;; a known slot has a known value.
(define (label-classes cx env)
(for-each (lambda (cls)
(let* ((support (cx.support cx))
(id (support.class-id support)))
(support.class-id-set! support (+ id 1))
(class.label-set! cls id)))
(classes env)))
(define (compute-class-descriptors cx env)
(define (class-ids cls)
(if (not cls)
'()
(cons (class.label cls) (class-ids (class.base cls)))))
(define (class-dispatch-map cls)
(let ((vs (class.virtuals cls)))
(if (null? vs)
'()
(let* ((largest (apply max (map car vs)))
(vtbl (make-vector (+ largest 1) -1)))
(for-each (lambda (entry)
(vector-set! vtbl (car entry) (func.table-index (cadr entry))))
vs)
(vector->list vtbl)))))
(for-each (lambda (cls)
(let* ((virtuals (class-dispatch-map cls))
(bases (reverse (class-ids cls)))
(table (append (reverse virtuals) (list (class.label cls) (length bases)) bases))
(addr (cx.memory cx)))
(cx.memory-set! cx (+ addr (* 4 (length table))))
(for-each (lambda (d)
(cx.data-set! cx (cons d (cx.data cx))))
table)
(let ((desc-addr (+ addr (* 4 (length virtuals)))))
(indirection-set! (class.desc-addr cls) desc-addr))))
(classes env)))
;; `obj` is a wasm expression, `objty` its type object, and `vid` is the virtual index.
(define (resolve-nonnull-virtual cx env obj objty vid)
(expand-expr
cx
`(%object-desc-virtual% ,vid (%object-desc% (%wasm% ,objty ,obj)))
env))
;; Anyref unboxing:
;;
;; - anyref holds only pointers or null (ie it's a generic nullable pointer)
;; - there are primitive downcasts from anyref to Wasm object, string, or generic array
;; - those downcasts all allow for null values - null is propagated [clean this up]
;; - nonnull values of the wrong types cause a trap
;; - for array and object there must then be a subsequent test for the
;; correct type
;; - for string there must then be a subsequent test for null, since strings are
;; not nullable
;; `val` is a wasm expression and `valty` is its type object.
(define (maybenull-class-is-class cx env cls val valty)
(let ((obj (new-name cx "p"))
(desc (new-name cx "a")))
(expand-expr
cx
`(%let% ((,obj (%wasm% ,valty ,val)))
(%if% (%null?% ,obj)
#f
(%let% ((,desc (%object-desc% ,obj)))
(%and% (%>u% (%object-desc-length% ,desc) ,(class.depth cls))
(%=% (%object-desc-ref% ,(class.depth cls) ,desc) ,(class.label cls))))))
env)))
;; TODO: the render here could be a primitive? %nonnull-anyref-unbox-object%
(define (maybenull-anyref-is-class cx env cls val valty)
(if (cx.wizard? cx)
(downcast-maybenull-to-class cx env cls val valty (lambda (name) 1) #f #f)
(let ((obj (new-name cx "p"))
(desc (new-name cx "a"))
(tmp (new-name cx "t")))
(expand-expr
cx
`(%let% ((,obj (%wasm% ,valty ,val)))
(%if% (%null?% ,obj)
#f
(%let% ((,tmp (%wasm% ,*Object-type*
,(render-maybe-unbox-nonnull-anyref-as-object cx env `(get_local (%id% ,obj))))))
(%if% (%null?% ,tmp)
#f
(%let% ((,desc (%object-desc% ,tmp)))
(%and% (%>u% (%object-desc-length% ,desc) ,(class.depth cls))
(%=% (%object-desc-ref% ,(class.depth cls) ,desc) ,(class.label cls))))))))
env))))
;; `val` is a wasm expression and `valty` is its type object.
(define (downcast-maybenull-class-to-class cx env cls val valty)
(if (cx.wizard? cx)
(downcast-maybenull-to-class cx env cls val valty (lambda (name) name) `(%null% ,(class.name cls)) `(trap ,(class.name cls)))
(let ((obj (new-name cx "p"))
(desc (new-name cx "a")))
(expand-expr
cx
`(%let% ((,obj (%wasm% ,valty ,val)))
(%if% (%null?% ,obj)
(%wasm% ,(class.type cls) (get_local (%id% ,obj)))
(%let% ((,desc (%object-desc% ,obj)))
(%if% (%>u% (%object-desc-length% ,desc) ,(class.depth cls))
(%if% (%=% (%object-desc-ref% ,(class.depth cls) ,desc) ,(class.label cls))
(%wasm% ,(class.type cls) (get_local (%id% ,obj)))
(%wasm% ,(class.type cls) (unreachable)))
(%wasm% ,(class.type cls) (unreachable))))))
env))))
;; TODO: the render here could be a primitive? %maybenull-anyref-unbox-object%
(define (downcast-maybenull-anyref-to-class cx env cls val)
(if (cx.wizard? cx)
(downcast-maybenull-to-class cx env cls val *anyref-type* (lambda (name) name) `(%null% ,(class.name cls)) `(trap ,(class.name cls)))
(downcast-maybenull-class-to-class cx env cls
(render-unbox-maybenull-anyref-as-object cx env val)
*Object-type*)))
(define (downcast-maybenull-to-class cx env cls val valty succeed ifnull fail)
(assert (cx.wizard? cx))
(let ((obj (new-name cx "p"))
(nobj (new-name cx "p"))
(desc (new-name cx "a"))
(ty (class.type cls)))
(expand-expr
cx
`(%let% ((,obj (%wasm% ,valty ,val)))
(%if% (%null?% ,obj)
,ifnull
(%let% ((,nobj (%wasm% ,ty (struct.narrow ,(wast-type-name cx valty) ,(wast-type-name cx ty) (get_local (%id% ,obj))))))
(%if% (%null?% ,nobj)
,fail
(%let% ((,desc (%object-desc% ,nobj)))
(%if% (%>u% (%object-desc-length% ,desc) ,(class.depth cls))
(%if% (%=% (%object-desc-ref% ,(class.depth cls) ,desc) ,(class.label cls))
,(succeed nobj)
,fail)
,fail))))))
env)))
;; TODO: the render here could be a primitive? %maybenull-anyref-unbox-string%
(define (downcast-maybenull-anyref-to-string cx env expr)
(let ((obj (new-name cx "p")))
(expand-expr
cx
`(%let% ((,obj (%wasm% anyref ,(render-unbox-maybenull-anyref-as-string cx env expr))))
(%wasm% ,*String-type*
(if anyref (ref.is_null (get_local (%id% ,obj)))
(unreachable)
(get_local (%id% ,obj)))))
env)))
;; TODO: the render here could be a primitive? %nonnull-anyref-unbox-vector%
(define (maybenull-anyref-is-vector cx env target-type val valty)
(let ((obj (new-name cx "p"))
(desc (new-name cx "d"))
(tmp (new-name cx "t")))
(expand-expr
cx
`(%let% ((,obj (%wasm% ,valty ,val)))
(%if% (%null?% ,obj)
#f
(%let% ((,tmp (%wasm% anyref ,(render-maybe-unbox-nonnull-anyref-as-vector cx env `(get_local (%id% ,obj))))))
(%if% (%null?% ,tmp)
#f
(%let% ((,desc (%vector-desc% ,tmp)))
(%=% (%vector-desc-id% ,desc) ,(type.vector-id target-type)))))))
env)))
(define (downcast-maybenull-anyref-to-vector cx env target-type val valty)
(let ((obj (new-name cx "p"))
(desc (new-name cx "d"))
(tmp (new-name cx "t")))
(expand-expr
cx
`(%let% ((,obj (%wasm% ,valty ,val)))
(%if% (%null?% ,obj)
(%wasm% ,target-type (get_local (%id% ,obj)))
(%let% ((,tmp (%wasm% anyref ,(render-maybe-unbox-nonnull-anyref-as-vector cx env `(get_local (%id% ,obj))))))
(%if% (%null?% ,tmp)
(%wasm% ,target-type (unreachable))
(%let% ((,desc (%vector-desc% ,tmp)))
(%if% (%=% (%vector-desc-id% ,desc) ,(type.vector-id target-type))
(%wasm% ,target-type (get_local (%id% ,obj)))
(%wasm% ,target-type (unreachable))))))))
env)))
;; Inline wasm is not yet exposed to user code because it can be used to break
;; generated code. For example, the %id% form can be used to compute the slot
;; number of any local or global, and this knowledge can escape. Even if we did
;; not have %id%, unrestricted use of get/set_local and get/set_global is a
;; hazard.
;;
;; Wasm ::= (%wasm% WasmType Code)
;; WasmType ::= i32 | i64 | f32 | f64 | anyref | TypeObject | Empty
;; Code ::= (Code ...) | SchemeSymbol | SchemeNumber | (%id% Id)
;;
;; This is a primitive inline-wasm-code facility. `Code` is any Wasm code,
;; which is not checked for validity at all, and is spliced into the output
;; code at the point where it occurs. The compiler assumes the code generates
;; a value of the provided type. If the type is absent then no value should
;; be generated.
;;
;; If a subform (%id% Id) appears then Id must denote a local or global
;; variable, and the subform is replaced by the index of the variable in the
;; appropriate space. Hence, (set_local (%id% x) (i32.const 1)) expands to
;; (set_local 42 (i32.const 1)) if x is bound as a local or global variable
;; whose index is 42. Of course, if it is a global variable then this is
;; silly.
;;
;; Note %id% is an operator inside wasm code and any bindings of %id% are
;; simply ignored. (There should not be any - programs should not use names
;; of the form %...%.)
;;
;; Reference types will be supported eventually.
(define (expand-wasm cx expr env)
(define (descend e)
(cond ((not (and (list? e) (not (null? e))))
e)
((eq? (car e) '%id%)
(if (or (not (= (length e) 2))
(not (symbol? (cadr e)))
(numbery-symbol? (cadr e)))
(fail "Bad form" e))
(let ((binding (lookup-variable env (cadr e))))
(cond ((local? binding) (local.slot binding))
((global? binding) (global.id binding))
(else (canthappen)))))
(else
(map descend e))))
(values (descend (car (last-pair expr)))
(cond ((= (length expr) 2)
*void-type*)
((type? (cadr expr))
(cadr expr))
(else
(case (cadr expr)
((i32) *i32-type*)
((i64) *i64-type*)
((f32) *f32-type*)
((f64) *f64-type*)
((anyref) *anyref-type*)
(else (fail "Bad type in wasm form" expr)))))))
;; Derived syntax
(define (expand-cond cx expr env)
(define (collect-clauses-reverse clauses)
(let loop ((clauses clauses) (exprs '()))
(if (null? clauses)
exprs
(let ((c (car clauses)))
(check-list-atleast c 1 "'cond' clause" expr)
(if (eq? (car c) 'else)
(begin
(if (not (null? (cdr clauses)))
(fail "'else' clause must be last" expr))
(let-values (((e0 t0) (expand-expr cx `(begin ,@(cdr c)) env)))
(loop (cdr clauses)
(cons (list #t e0 t0) exprs))))
(let-values (((ec tc) (expand-expr cx (car c) env)))
(check-i32-type tc "'cond' condition" expr)
(let-values (((e0 t0) (expand-expr cx `(begin ,@(cdr c)) env)))
(loop (cdr clauses)
(cons (list ec e0 t0) exprs)))))))))
(define (else-clause? c)
(eq? (car c) #t))
(define (wrap-clauses clauses base t)
(if (null? clauses)
base
(let ((c (car clauses)))
(wrap-clauses (cdr clauses) `(if ,@t ,(car c) ,(cadr c) ,base) t))))
(define (expand-clauses-reverse clauses t)
(let ((last (car clauses)))
(if (else-clause? last)
(wrap-clauses (cdr clauses)
(cadr last)
(wast-type-name-spliceable cx t))
(wrap-clauses (cdr clauses)
`(if ,(car last) ,(cadr last))
'()))))
(if (null? (cdr expr))
(values (void-expr) *void-type*)
(let ((clauses (collect-clauses-reverse (cdr expr))))
(begin
(check-same-types (map caddr clauses) "'cond' arms" expr)
(let* ((last (car clauses))
(t (caddr last)))
(if (not (else-clause? last))
(check-same-type t *void-type* "'cond' type" expr))
(values (expand-clauses-reverse clauses t)
t))))))
(define (expand-inc!+dec! cx expr env)
(let* ((the-op (if (eq? (car expr) 'inc!) '%+% '%-%))
(name (cadr expr)))
(cond ((symbol? name)
(expand-expr cx `(%set!% ,name (,the-op ,name 1)) env))
((accessor-expression? env name)
(let ((temp (new-name cx "local"))
(accessor (car name))
(ptr (cadr name)))
(expand-expr cx
`(%let% ((,temp ,ptr))
(%set!% (,accessor ,temp) (,the-op (,accessor ,temp) 1)))
env)))
(else
(fail "Illegal lvalue" expr)))))
(define (expand-while cx expr env)
(let ((loop-name (new-name cx "while"))
(test (cadr expr))
(body (cddr expr)))
(expand-expr cx
`(%loop% ,loop-name
(%if% (not ,test) (%break% ,loop-name))
,@body)
env)))
(define (expand-do cx expr env)
(define (collect-variables clauses)
(check-list-atleast clauses 0 "Variable clauses in 'do'" expr)
(for-each (lambda (c)
(check-list c 3 "Variable clause in 'do'" c "\n" expr)
(check-symbol (car c) "Binding in 'do'" c "\n" expr))
clauses)
(values (map car clauses)
(map cadr clauses)
(map caddr clauses)))
(define (collect-exit clause)
(check-list-atleast clause 1 "Test clause in 'do'" expr)
(values (car clause)
(cdr clause)))
(let*-values (((ids inits updates) (collect-variables (cadr expr)))
((test results) (collect-exit (caddr expr))))
(let ((body (cdddr expr))
(loop-name (new-name cx "do"))
(temps (map (lambda (id) (new-name cx "tmp")) ids)))
(expand-expr cx
`(%let% ,(map list ids inits)
(%loop% ,loop-name
(%if% ,test (%break% ,loop-name (%begin% ,@results)))
,@body
(%let% ,(map list temps updates)
,@(map (lambda (id temp) `(set! ,id ,temp)) ids temps))))
env))))
(define (expand-case cx expr env)
(let ((temp (new-name cx "local")))
(expand-expr cx
`(%let% ((,temp ,(cadr expr)))
(%case% ,temp ,@(cddr expr)))
env)))
;; The dispatch expr is always effect-free, and we make use of this.
(define (expand-%case% cx expr env)
(define (check-case-types cases default-type)
(for-each (lambda (c)
(check-same-type (caddr c) default-type "'case' arm"))
cases))
;; found-values is a list of the discriminant integer values.
;;
;; e0 is the dispatch expression, known to be side-effect free and unaffected
;; by side effects in the cases.
;;
;; cases is a list of lists (((integer ...) code type) ...) where each code is
;; typically a block and all the integers are known to be distinct across the
;; full list. Note the block may not yield a value; it may be void, or it may
;; break or continue.
;;
;; default is just an expr, default-type is its type.
(define (finish-case found-values e0 cases default default-type)
(if (null? cases)
(begin
(assert default)
(values default default-type))
(let* ((_ (check-case-types cases default-type))
(ty (caddr (car cases)))
(bty (wast-type-name-spliceable cx ty))
(cases (map (lambda (c) (cons (new-name cx "case") c)) cases))
(default-label (new-name cx "default"))
(outer-label (new-name cx "outer"))
(default (if (not default) '() (list default)))
(found-values (sort found-values <))
(smallest (car found-values))
(largest (car (last-pair found-values)))
(size (+ (- largest smallest) 1))
(v (make-vector size (list default-label))))
(if (> size 10000)
(fail "Range of cases too large" (list smallest largest)))
(for-each (lambda (c)
(for-each (lambda (val)
(vector-set! v (- val smallest) c))
(cadr c)))
cases)
(values
`(block ,outer-label ,@bty
(block ,default-label
,(letrec ((loop (lambda (cases)
(if (null? cases)
`(br_table ,@(map car (vector->list v))
,default-label
,(if (zero? smallest)
e0
`(i32.sub ,e0 (i32.const ,smallest))))
(let* ((c (car cases))
(label (car c))
(code (caddr c)))
`(block
(block ,label
,(loop (cdr cases)))
,@(if (void-type? ty)
`(,code (br ,outer-label))
`((br ,outer-label ,code)))))))))
(loop cases)))
(br ,outer-label ,@default))
ty))))
;; This returns a list of integers, not expressions
(define (resolve-case-constants cs)
(let ((constants
(map (lambda (c)
(cond ((numbery-symbol? c)
(let-values (((v t) (expand-numbery-symbol c)))
(check-i32-type t "'case' constant")
v))
((or (number? c) (char? c) (boolean? c))
(let-values (((v t) (expand-number c)))
(check-i32-type t "'case' constant")
v))
((and (symbol? c) (lookup-global env c)) =>
(lambda (g)
(if (and (not (global.module g))
(not (global.mut? g))
(i32-type? (global.type g)))
(global.init g)
(fail "Reference to global that is not immutable with a known constant initializer" c))))
(else
(fail "Invalid case constant " c))))
cs)))
(map (lambda (c)
(assert (and (pair? c) (eq? (car c) 'i32.const)))
(cadr c))
constants)))
(define (incorporate-constants constants known)
(cond ((null? constants)
known)
((memv (car constants) known)
(fail "Duplicate constant in case" (car constants)))
(else
(incorporate-constants (cdr constants)
(cons (car constants) known)))))
(let-values (((e0 t0) (expand-expr cx (cadr expr) env)))
(check-i32-type t0 "'case' expression")
(let loop ((cases (cddr expr)) (case-info '()) (found-values '()))
(cond ((null? cases)
(finish-case found-values e0 case-info #f *void-type*))
((and (pair? (car cases)) (eq? (caar cases) 'else))
(let ((c (car cases)))
(check-list-atleast c 2 "Bad else in case" c)
(if (not (null? (cdr cases)))
(fail "Else clause in case must be last" expr))
(let-values (((de te) (expand-expr cx (cons 'begin (cdr c)) env)))
(finish-case found-values e0 case-info de te))))
(else
(let ((c (car cases)))
(check-list-atleast c 2 "Bad case in case" c)
(check-list-atleast (car c) 1 "Bad constant list in case" c)
(let* ((constants (resolve-case-constants (car c)))
(found-values (incorporate-constants constants found-values)))
(let-values (((be bt) (expand-expr cx (cons 'begin (cdr c)) env)))
(loop (cdr cases)
(cons (list constants be bt) case-info)
found-values)))))))))
(define (expand-and cx expr env)
(cond ((null? (cdr expr))
(expand-expr cx #t env))
((null? (cddr expr))
(let-values (((e0 t0) (expand-expr cx (cadr expr) env)))
(check-i32-type t0 "'and'" (cadr expr) expr)
(values e0 t0)))
(else
(expand-expr cx `(%if% ,(cadr expr) (%and% ,@(cddr expr)) #f) env))))
(define (expand-or cx expr env)
(cond ((null? (cdr expr))
(expand-expr cx #f env))
((null? (cddr expr))
(let-values (((e0 t0) (expand-expr cx (cadr expr) env)))
(check-i32-type t0 "'or'" (cadr expr) expr)
(values e0 t0)))
(else
(let ((temp (new-name cx "local")))
(expand-expr cx
`(%let% ((,temp ,(cadr expr)))
(%if% ,temp ,temp (%or% ,@(cddr expr))))
env)))))
(define (expand-null? cx expr env)
(let-values (((e t) (expand-expr cx (cadr expr) env)))
(check-nullable-ref-type t "'null?'" expr)
(values `(ref.is_null ,e) *i32-type*)))
(define (expand-nonnull? cx expr env)
(let-values (((e t) (expand-expr cx (cadr expr) env)))
(check-nullable-ref-type t "'nonnull?'" expr)
(values `(i32.eqz (ref.is_null ,e)) *i32-type*)))
(define (expand-zero? cx expr env)
(let-values (((op1 t1) (expand-expr cx (cadr expr) env)))
(check-number-type t1 "'zero?'" expr)
(values `(,(operatorize t1 '=) ,op1 ,(typed-constant t1 0)) *i32-type*)))
(define (expand-nonzero? cx expr env)
(let-values (((op1 t1) (expand-expr cx (cadr expr) env)))
(check-number-type t1 "'nonzero?'" expr)
(values `(,(operatorize t1 '%!=%) ,op1 ,(typed-constant t1 0)) *i32-type*)))
(define (expand-bitnot cx expr env)
(let-values (((op1 t1) (expand-expr cx (cadr expr) env)))
(check-integer-type t1 "'bitnot'" expr)
(values `(,(operatorize t1 'bitxor) ,op1 ,(typed-constant t1 -1)) t1)))
(define (expand-select cx expr env)
(let*-values (((op t) (expand-expr cx (cadr expr) env))
((op1 t1) (expand-expr cx (caddr expr) env))
((op2 t2) (expand-expr cx (cadddr expr) env)))
(check-i32-type t "'select' condition" expr)
(check-same-type t1 t2 "'select' arms" expr)
(values `(select ,op2 ,op1 ,op) t1)))
(define (expand-not cx expr env)
(let-values (((op1 t1) (expand-expr cx (cadr expr) env)))
(check-i32-type t1 "'not'")
(values `(i32.eqz ,op1) *i32-type*)))
(define (expand-unop cx expr env)
(let-values (((op1 t1) (expand-expr cx (cadr expr) env)))
(values `(,(operatorize t1 (car expr)) ,op1) t1)))
(define (expand-binop cx expr env)
(let*-values (((op1 t1) (expand-expr cx (cadr expr) env))
((op2 t2) (expand-expr cx (caddr expr) env)))
(check-same-type t1 t2 "binary operator" (car expr))
(values `(,(operatorize t1 (car expr)) ,op1 ,op2) t1)))
(define (expand-relop cx expr env)
(let*-values (((op1 t1) (expand-expr cx (cadr expr) env))
((op2 t2) (expand-expr cx (caddr expr) env)))
(check-same-type t1 t2 "relational operator" (car expr))
(values `(,(operatorize t1 (car expr)) ,op1 ,op2) *i32-type*)))
(define (expand-conversion cx expr env)
(let-values (((e0 t0) (expand-expr cx (cadr expr) env)))
(let ((probe (assq (car expr) *conv-op*)))
(if probe
(begin (check-same-type t0 (cadr probe) (car expr) expr)
(values `(,(cadddr probe) ,e0) (caddr probe)))
(canthappen)))))
(define *conv-op*
(list (list 'i32->i64 *i32-type* *i64-type* 'i64.extend_s/i32)
(list 'u32->i64 *i32-type* *i64-type* 'i64.extend_u/i32)
(list 'i64->i32 *i64-type* *i32-type* 'i32.wrap/i64)
(list 'f32->f64 *f32-type* *f64-type* 'f64.promote/f32)
(list 'f64->f32 *f64-type* *f32-type* 'f32.demote/f64)
(list 'f64->i32 *f64-type* *i32-type* 'i32.trunc_s/f64)
(list 'f64->i64 *f64-type* *i64-type* 'i64.trunc_s/f64)
(list 'i32->f64 *i32-type* *f64-type* 'f64.convert_s/i32)
(list 'i64->f64 *i64-type* *f64-type* 'f64.convert_s/i64)
(list 'f32->i32 *f32-type* *i32-type* 'i32.trunc_s/f32)
(list 'f32->i64 *f32-type* *i64-type* 'i64.trunc_s/f32)
(list 'i32->f32 *i32-type* *f32-type* 'f32.convert_s/i32)
(list 'i64->f32 *i64-type* *f32-type* 'f32.convert_s/i64)
(list 'f32->bits *f32-type* *i32-type* 'i32.reinterpret/f32)
(list 'bits->f32 *i32-type* *f32-type* 'f32.reinterpret/i32)
(list 'f64->bits *f64-type* *i64-type* 'i64.reinterpret/f64)
(list 'bits->f64 *i64-type* *f64-type* 'f64.reinterpret/i64)))
(define (expand-accessor cx expr env)
(check-list expr 2 "Bad accessor" expr)
(let-values (((base-expr cls field-name field-type)
(process-accessor-expression cx expr env)))
(values (wast-maybenull-field-access cx env cls field-name base-expr)
field-type)))
;; Returns rendered-base-expr class field-name field-type
(define (process-accessor-expression cx expr env)
(let* ((name (car expr))
(accessor (lookup env name))
(field-name (accessor.field-name accessor))
(base (cadr expr)))
(let-values (((e0 t0) (expand-expr cx base env)))
(if (not (type.class t0))
(fail "Not a class type" expr t0))
(let* ((cls (type.class t0))
(fields (class.fields cls))
(probe (assq field-name fields)))
(if (not probe)
(fail "Class does not have field" field-name cls))
(values e0 cls field-name (cadr probe))))))
(define (expand-func-call cx expr env func)
(let* ((args (cdr expr))
(formals (func.formals func))
(actuals (expand-expressions cx args env))
(actuals (check-and-widen-arguments cx env formals actuals expr)))
(values `(call ,(func.id func) ,@(map car actuals))
(func.result func))))
;; formals is ((name type) ...)
;; actuals is ((val type) ...)
(define (check-and-widen-arguments cx env formals actuals context)
(if (not (= (length formals) (length actuals)))
(fail "wrong number of arguments" context))
(map (lambda (formal actual)
(let ((want (cadr formal))
(have (cadr actual)))
(or (widen-value cx env (car actual) have want)
(fail "Not same type in" context "and widening not possible.\n"
(pretty-type have) (pretty-type want)))))
formals actuals))
(define (operatorize t op . context)
(let ((name (cond ((i32-type? t)
(let ((probe (or (assq op *int-ops*) (assq op *common-ops*))))
(and probe (memq 'i32 (cddr probe)) (cadr probe))))
((i64-type? t)
(let ((probe (or (assq op *int-ops*) (assq op *common-ops*))))
(and probe (memq 'i64 (cddr probe)) (cadr probe))))
((f32-type? t)
(let ((probe (or (assq op *float-ops*) (assq op *common-ops*))))
(and probe (memq 'f32 (cddr probe)) (cadr probe))))
((f64-type? t)
(let ((probe (or (assq op *float-ops*) (assq op *common-ops*))))
(and probe (memq 'f64 (cddr probe)) (cadr probe))))
(else
(canthappen)))))
(if (not name)
(apply fail `("Unexpected type for" ,op ,(pretty-type t))))
(splice (type.name t) name)))
(define *int-ops*
'((clz ".clz" i32 i64)
(ctz ".ctz" i32 i64)
(popcnt ".popcnt" i32 i64)
(div ".div_s" i32 i64)
(divu ".div_u" i32 i64)
(rem ".rem_s" i32 i64)
(remu ".rem_u" i32 i64)
(< ".lt_s" i32 i64)
(<u ".lt_u" i32 i64)
(<= ".le_s" i32 i64)
(<=u ".le_u" i32 i64)
(> ".gt_s" i32 i64)
(>u ".gt_u" i32 i64)
(%>u% ".gt_u" i32 i64)
(>= ".ge_s" i32 i64)
(>=u ".ge_u" i32 i64)
(bitand ".and" i32 i64)
(bitor ".or" i32 i64)
(bitxor ".xor" i32 i64)
(shl ".shl" i32 i64)
(shr ".shr_s" i32 i64)
(shru ".shr_u" i32 i64)
(rotl ".rotl" i32 i64)
(rotr ".rotr" i32 i64)
(extend8 ".extend8_s" i32 i64)
(extend16 ".extend16_s" i32 i64)
(extend32 ".extend32_s" i64)))
(define *float-ops*
'((div ".div" f32 f64)
(< ".lt" f32 f64)
(<= ".le" f32 f64)
(> ".gt" f32 f64)
(>= ".ge" f32 f64)
(neg ".neg" f32 f64)
(abs ".abs" f32 f64)
(min ".min" f32 f64)
(max ".max" f32 f64)
(sqrt ".sqrt" f32 f64)
(ceil ".ceil" f32 f64)
(floor ".floor" f32 f64)
(nearest ".nearest" f32 f64)
(trunc ".trunc" f32 f64)))
(define *common-ops*
'((+ ".add" i32 i64 f32 f64)
(%+% ".add" i32 i64 f32 f64)
(- ".sub" i32 i64 f32 f64)
(%-% ".sub" i32 i64 f32 f64)
(* ".mul" i32 i64 f32 f64)
(= ".eq" i32 i64 f32 f64)
(%=% ".eq" i32 i64 f32 f64)
(%!=% ".ne" i32 i64 f32 f64)))
(define (typed-constant t value)
`(,(splice (type.name t) ".const") ,value))
(define (void-expr)
'(block))
(define (expand-string cx expr env)
(let ((actuals (map (lambda (x)
(check-i32-type (cadr x) "Argument to 'string'" expr)
(car x))
(expand-expressions cx (cdr expr) env))))
(values (render-new-string cx env actuals) *String-type*)))
(define (expand-string-length cx expr env)
(let-values (((e0 t0) (expand-expr cx (cadr expr) env)))
(check-string-type t0 "'string-length'" expr)
(values (render-string-length cx env e0) *i32-type*)))
(define (expand-string-ref cx expr env)
(let*-values (((e0 t0) (expand-expr cx (cadr expr) env))
((e1 t1) (expand-expr cx (caddr expr) env)))
(check-string-type t0 "'string-ref'" expr)
(check-i32-type t1 "'string-ref'" expr)
(values (render-string-ref cx env e0 e1) *i32-type*)))
(define (expand-string-append cx expr env)
(let ((l (length expr)))
(values (case l
((1)
(render-string-literal cx env (string-literal->id cx "")))
((2)
(let*-values (((e0 t0) (expand-expr cx (cadr expr) env)))
(check-string-type t0 "'string-append'" expr)
e0))
((3)
(let*-values (((e0 t0) (expand-expr cx (cadr expr) env))
((e1 t1) (expand-expr cx (caddr expr) env)))
(check-string-type t0 "'string-append'" expr)
(check-string-type t1 "'string-append'" expr)
(render-string-append cx env e0 e1)))
(else
(let-values (((e0 t0)
(expand-expr cx
`(%string-append% (%string-append% ,(cadr expr) ,(caddr expr))
,@(cdddr expr))
env)))
e0)))
*String-type*)))
(define (expand-substring cx expr env)
(let*-values (((e0 t0) (expand-expr cx (cadr expr) env))
((e1 t1) (expand-expr cx (caddr expr) env))
((e2 t2) (expand-expr cx (cadddr expr) env)))
(check-string-type t0 "'substring'" expr)
(check-i32-type t1 "'substring'" expr)
(check-i32-type t2 "'substring'" expr)
(values (render-substring cx env e0 e1 e2) *String-type*)))
(define (expand-string-relop cx expr env)
(let*-values (((e0 t0) (expand-expr cx (cadr expr) env))
((e1 t1) (expand-expr cx (caddr expr) env)))
(let ((name (string-append "'" (symbol->string (car expr)) "'")))
(check-string-type t0 name expr)
(check-string-type t1 name expr))
(values `(,(case (car expr)
((string=?) 'i32.eq)
((string<?) 'i32.lt_s)
((string<=?) 'i32.le_s)
((string>?) 'i32.gt_s)
((string>=?) 'i32.ge_s)
(else (canthappen)))
,(render-string-compare cx env e0 e1)
(i32.const 0))
*i32-type*)))
(define (expand-vector-length cx expr env)
(let-values (((e0 t0) (expand-expr cx (cadr expr) env)))
(check-vector-type t0 "'vector-length'" expr)
(values (render-maybenull-vector-length cx env e0 (type.vector-element t0)) *i32-type*)))
(define (expand-vector-ref cx expr env)
(let*-values (((e0 t0) (expand-expr cx (cadr expr) env))
((e1 t1) (expand-expr cx (caddr expr) env)))
(check-vector-type t0 "'vector-ref'" expr)
(check-i32-type t1 "'vector-ref'" expr)
(let ((element-type (type.vector-element t0)))
(values (render-maybenull-vector-ref cx env e0 e1 element-type) element-type))))
(define (expand-vector-set! cx expr env)
(let*-values (((e0 t0) (expand-expr cx (cadr expr) env))
((e1 t1) (expand-expr cx (caddr expr) env))
((e2 t2) (expand-expr cx (cadddr expr) env)))
(check-vector-type t0 "'vector-set!'" expr)
(check-i32-type t1 "'vector-set!'" expr)
(check-same-type (type.vector-element t0) t2 "'vector-set!'" expr)
(let ((element-type (type.vector-element t0)))
(values (render-maybenull-vector-set! cx env e0 e1 e2 element-type) *void-type*))))
(define (expand-vector->string cx expr env)
(let-values (((e0 t0) (expand-expr cx (cadr expr) env)))
(check-vector-type t0 "'vector->string'" expr)
(check-i32-type (type.vector-element t0) "'vector->string'" expr)
(values (render-maybenull-vector->string cx env e0) *String-type*)))
(define (expand-string->vector cx expr env)
(let-values (((e0 t0) (expand-expr cx (cadr expr) env)))
(check-string-type t0 "'string->vector'" expr)
(values (render-string->vector cx env e0) (make-vector-type cx env *i32-type*))))
(define (expand-object-desc cx expr env)
(let-values (((e0 t0) (expand-expr cx (cadr expr) env)))
(check-class-type t0 "'%object-desc%'" expr)
(values (wast-get-descriptor-addr cx env e0 t0) *i32-type*)))
(define (expand-object-desc-id cx expr env)
(let-values (((e0 t0) (expand-expr cx (cadr expr) env)))
(check-i32-type t0 "'%object-desc-id%'" expr)
(values `(i32.load ,e0) *i32-type*)))
(define (expand-object-desc-length cx expr env)
(let-values (((e0 t0) (expand-expr cx (cadr expr) env)))
(check-i32-type t0 "'%object-desc-length%'" expr)
(values `(i32.load offset = 4 ,e0) *i32-type*)))
(define (expand-object-desc-ref cx expr env)
(check-u32-value (cadr expr) "'%object-desc-ref%'" expr)
(let-values (((e0 t0) (expand-expr cx (caddr expr) env)))
(check-i32-type t0 "'%object-desc-ref%'" expr)
(values `(i32.load offset = ,(+ 8 (* 4 (cadr expr))) ,e0) *i32-type*)))
(define (expand-object-desc-virtual cx expr env)
(let ((vid (cadr expr)))
(check-u32-value vid "'%object-desc-virtual%'" expr)
(let-values (((e0 t0) (expand-expr cx (caddr expr) env)))
(check-i32-type t0 "'%object-desc-virtual%'" expr)
(values `(i32.load (i32.sub ,e0 (i32.const ,(+ 4 (* 4 vid))))) *i32-type*))))
(define (expand-vector-desc cx expr env)
(let-values (((e0 t0) (expand-expr cx (cadr expr) env)))
(check-anyref-type t0 "'%vector-desc%'" expr)
(values (render-get-vector-descriptor-addr cx env e0) *i32-type*)))
;; At the moment, the desc id is the same as the desc. This will change.
(define (expand-vector-desc-id cx expr env)
(let-values (((e0 t0) (expand-expr cx (cadr expr) env)))
(check-i32-type t0 "'%vector-desc-id%'" expr)
(values e0 *i32-type*)))
;; Miscellaneous wasm support: functions named wast-whatever return literal wast code.
(define (wast-number n type)
(let ((v (cond ((= n +inf.0) (string->symbol "+infinity"))
((= n -inf.0) (string->symbol "-infinity"))
((not (= n n)) (string->symbol "+nan"))
(else n))))
(cond ((i32-type? type) `(i32.const ,v))
((i64-type? type) `(i64.const ,v))
((f32-type? type) `(f32.const ,v))
((f64-type? type) `(f64.const ,v))
(else (canthappen)))))
(define (wast-class-name cls)
(splice "$cls_" (class.name cls)))
(define (wast-type-name cx t)
(if (reference-type? t)
(if (cx.wizard? cx)
(cond ((class-type? t)
`(ref ,(wast-class-name (type.class t))))
(else
'anyref))
'anyref)
(type.name t)))
(define (wast-type-name-spliceable cx t)
(if (void-type? t)
'()
(list (wast-type-name cx t))))
(define (wast-new-class cx env cls actuals)
(if (cx.wizard? cx)
`(struct.new ,(wast-class-name cls) (i32.const ,(class.desc-addr cls)) ,@(map car actuals))
(render-new-class cx env cls actuals)))
(define (wast-get-descriptor-addr cx env p t)
(if (cx.wizard? cx)
`(struct.get ,(wast-class-name (type.class t)) 0 ,p)
(render-get-descriptor-addr cx env p)))
(define (wast-maybenull-field-access cx env cls field-name base-expr)
(if (cx.wizard? cx)
`(struct.get ,(wast-class-name cls) ,(+ 1 (field-index cls field-name)) ,base-expr)
(render-maybenull-field-access cx env cls field-name base-expr)))
(define (wast-maybenull-field-update cx env cls field-name base-expr val valty)
(if (cx.wizard? cx)
(let ((index (+ 1 (field-index cls field-name))))
(if (reference-type? valty)
(render-maybenull-ref-field-update cx env cls (splice "_" index) valty base-expr val)
`(struct.set ,(wast-class-name cls) ,index ,base-expr ,val)))
(render-maybenull-field-update cx env cls field-name base-expr val)))
(define (wast-upcast-class-to-class cx env target-cls value)
(if (cx.wizard? cx)
value
(render-upcast-class-to-class cx env target-cls value)))
(define (wast-upcast-class-to-anyref cx env value)
(if (cx.wizard? cx)
value
(render-upcast-class-to-anyref cx env value)))
;; Type checking.
(define (check-i32-value val . context)
(if (not (and (integer? val) (exact? val) (<= min-i32 val max-i32)))
(apply fail "Value outside i32 range" val context)))
(define (check-u32-value val . context)
(if (not (and (integer? val) (exact? val) (<= 0 val max-u32)))
(apply fail "Nonnegative constant integer slot required" val context)))
(define (check-i64-value val . context)
(if (not (and (integer? val) (exact? val) (<= min-i64 val max-i64)))
(apply fail "Value outside i64 range" val context)))
(define (check-f32-value val . context)
(if (not (number? val))
(apply fail "Value outside f32 range" val context)))
(define (check-f64-value val . context)
(if (not (number? val))
(apply fail "Value outside f64 range" val context)))
(define (check-unbound env name reason)
(if (lookup env name)
(fail "Name cannot be bound because" reason name)))
(define (check-number-type t context . rest)
(if (not (number-type? t))
(apply fail `("Not a number type in" ,context ,@rest "\n" ,(pretty-type t)))))
(define (check-i32-type t context . rest)
(if (not (i32-type? t))
(apply fail `("Not an i32 type in" ,context ,@rest "\n" ,(pretty-type t)))))
(define (check-integer-type t context . rest)
(if (not (integer-type? t))
(apply fail `("Not an integer type in" ,context ,@rest "\n" ,(pretty-type t)))))
(define (check-anyref-type t context . rest)
(if (not (anyref-type? t))
(apply fail `("Not an anyref type in" ,context ,@rest "\n" ,(pretty-type t)))))
(define (check-string-type t context . rest)
(if (not (String-type? t))
(apply fail `("Not a string type in" ,context ,@rest "\n" ,(pretty-type t)))))
(define (check-vector-type t context . rest)
(if (not (Vector-type? t))
(apply fail `("Not a vector type in" ,context ,@rest "\n" ,(pretty-type t)))))
(define (check-same-types types . context)
(if (not (null? types))
(let ((t (car types)))
(for-each (lambda (e)
(apply check-same-type e t context))
(cdr types)))))
(define (check-same-type t1 t2 context . rest)
(if (not (type=? t1 t2))
(apply fail `("Not same type in" ,context ,@rest "\nlhs = " ,(pretty-type t1) "\nrhs = " ,(pretty-type t2)))))
(define (check-class-type t context . rest)
(if (not (class-type? t))
(apply fail `("Not class type in" ,context ,@rest "\ntype = " ,(pretty-type t)))))
(define (check-ref-type t context . rest)
(if (not (reference-type? t))
(apply fail `("Not reference type in" ,context ,@rest "\ntype = " ,(pretty-type t)))))
(define (check-nullable-ref-type t context . rest)
(if (not (nullable-reference-type? t))
(apply fail `("Not reference type in" ,context ,@rest "\ntype = " ,(pretty-type t)))))
(define (check-head x k)
(if (not (eq? (car x) k))
(fail "Expected keyword" k "but saw" (car x))))
(define (check-list-atleast l n . rest)
(if (or (not (list? l)) (not (>= (length l) n)))
(if (not (null? rest))
(apply fail rest)
(fail "List of insufficient length, need at least" n " " l))))
(define (check-list l n . rest)
(if (or (not (list? l)) (not (= (length l) n)))
(if (not (null? rest))
(apply fail rest)
(fail "List of wrong length" l))))
(define (check-list-oneof l ns . rest)
(if (not (and (list? l) (memv (length l) ns)))
(if (not (null? rest))
(apply fail rest)
(fail "List of wrong length" l))))
(define (check-symbol x . rest)
(if (not (symbol? x))
(if (not (null? rest))
(apply fail rest)
(fail "Expected a symbol but got" x))))
(define (check-constant x . rest)
(if (not (or (number? x) (numbery-symbol? x) (char? x) (boolean? x)))
(if (not (null? rest))
(apply fail rest)
(fail "Expected a constant number but got" x))))
;; JavaScript support.
;;
;; Various aspects of rendering reference types and operations on them, subject
;; to change as we grow better support.
;;
;; Each of these could be generated lazily with a little bit of bookkeeping,
;; even for per-class functions; it's the initial lookup that would trigger the
;; generation.
;; Note, "instanceof" does not worked on TypedObject instances. So instead of
;; "x instanceof T" where T is some TO type, we use "x.hasOwnProperty('_desc_')"
;; to test for Object/Vector, and then wasm code must extract the type code and
;; check that.
(define-record-type type/js-support
(%make-js-support% type lib desc strings class-id)
js-support?
(type support.type)
(lib support.lib)
(desc support.desc)
(strings support.strings)
(class-id support.class-id support.class-id-set!))
(define (make-js-support)
(%make-js-support% (open-output-string) ; for type constructors
(open-output-string) ; for library code
(open-output-string) ; for descriptor code
(open-output-string) ; for strings
1)) ; next class ID
(define (format-lib cx name fmt . args)
(apply format (support.lib (cx.support cx)) (string-splice "'~a':" fmt ",\n") name args))
(define (format-type cx name fmt . args)
(apply format (support.type (cx.support cx)) (string-splice "'~a':" fmt ",\n") name args))
(define (format-desc cx name fmt . args)
(apply format (support.desc (cx.support cx)) (string-splice "'~a':" fmt ",\n") name args))
(define (js-lib cx env name formals result code . args)
(assert (symbol? name))
(assert (every? type? formals))
(assert (type? result))
(apply format-lib cx name code args)
(synthesize-func-import cx env name formals result))
(define (synthesize-func-import cx env name formal-types result)
(let ((rendered-params (map (lambda (f)
`(param ,(wast-type-name cx f)))
formal-types))
(formals (map (lambda (k f)
(list (splice "p" k) f))
(iota (length formal-types)) formal-types)))
(define-function! cx env name "lib" #f rendered-params formals result #f)))
(define (lookup-synthesized-func cx env name synthesizer . args)
(if (not (lookup env name))
(apply synthesizer cx env name args))
(lookup-func env name))
;; Types
(define (typed-object-name t)
(string-append "TO."
(case (type.name t)
((class) "Object")
((anyref) "Object")
((vector) "Object")
((String) "string")
((i32) "int32")
((i64) "int64")
((f32) "float32")
((f64) "float64")
(else (canthappen)))))
;; Class descriptors, vtables, and hierarchies
(define (synthesize-class-descriptors cx env)
(if (not (cx.wizard? cx))
(for-each (lambda (cls)
(format-type cx (class.name cls)
"new TO.StructType({~a})"
(comma-separate (cons "_desc_:TO.int32"
(map (lambda (f)
(string-splice "'" (car f) "':" (typed-object-name (cadr f))))
(class.fields cls))))))
(classes env))))
(define (emit-class-descriptors cx env)
(if (not (cx.wizard? cx))
(for-each (lambda (cls)
(let ((desc-addr (indirection-get (class.desc-addr cls))))
(format-desc cx (class.name cls) "~a" desc-addr)))
(classes env))))
;; Once we have field access in wasm the the 'get descriptor' operation will be
;; subtype-polymorphic, it takes an Object that has a _desc_ field and returns
;; an i32. (Presumably it actually takes an Object that has an i32 field at
;; offset 0.) It depends on some kind of subtyping resolution in Wasm.
(define (synthesize-get-descriptor-addr cx env name)
(js-lib cx env name `(,*Object-type*) *i32-type* "function (p) { return p._desc_ }"))
(define (render-get-descriptor-addr cx env base-expr)
(let ((func (lookup-synthesized-func cx env '_desc_ synthesize-get-descriptor-addr)))
`(call ,(func.id func) ,base-expr)))
(define (synthesize-get-vector-descriptor-addr cx env name)
(js-lib cx env name `(,*anyref-type*) *i32-type* "function (p) { return p._vdesc_ }"))
(define (render-get-vector-descriptor-addr cx env base-expr)
(let ((func (lookup-synthesized-func cx env '_vdesc_ synthesize-get-vector-descriptor-addr)))
`(call ,(func.id func) ,base-expr)))
;; Class operations
(define (synthesize-new-class cx env name cls)
(let* ((cls-name (class.name cls))
(fields (class.fields cls))
(fs (map (lambda (f) (symbol->string (car f))) fields))
(formals (comma-separate fs))
(as (cons (string-append "_desc_:self.desc." (symbol->string cls-name)) fs))
(actuals (comma-separate as)))
(js-lib cx env name (map cadr fields) (class.type cls)
"function (~a) { return new self.types.~a({~a}) }" formals cls-name actuals)))
(define (render-new-class cx env cls args)
(assert (not (cx.wizard? cx)))
(let ((func (lookup-synthesized-func cx env
(splice "_new_" (class.name cls))
synthesize-new-class
cls)))
`(call ,(func.id func) ,@(map car args))))
;; The compiler shall only insert an upcast operation if the expression being
;; widened is known to be of a proper subtype of the target type. In this case
;; the operation is a no-op but once the wasm type system goes beyond having
;; just anyref we may need an explicit upcast here.
(define (synthesize-upcast-class-to-anyref cx env name)
(js-lib cx env name `(,*Object-type*) *anyref-type* "function (p) { return p }"))
(define (render-upcast-class-to-anyref cx env expr)
(assert (not (cx.wizard? cx)))
(let ((func (lookup-synthesized-func cx env '_upcast_class_to_anyref synthesize-upcast-class-to-anyref)))
`(call ,(func.id func) ,expr)))
(define (synthesize-upcast-to-class cx env name cls)
(js-lib cx env name `(,*Object-type*) (class.type cls) "function (p) { return p }"))
(define (render-upcast-class-to-class cx env desired expr)
(assert (not (cx.wizard? cx)))
(let ((func (lookup-synthesized-func cx env
(splice "_upcast_class_to_" (class.name desired))
synthesize-upcast-to-class
desired)))
`(call ,(func.id func) ,expr)))
(define (synthesize-unbox-maybenull-anyref-as-object cx env name)
(js-lib cx env name `(,*anyref-type*) *Object-type*
"
function (p) {
if (p === null || p.hasOwnProperty('_desc_'))
return p;
throw new Error('Failed to unbox anyref as object');
}"))
(define (render-unbox-maybenull-anyref-as-object cx env val)
(assert (not (cx.wizard? cx)))
(let ((func (lookup-synthesized-func cx env
'_unbox_anyref_as_object
synthesize-unbox-maybenull-anyref-as-object)))
`(call ,(func.id func) ,val)))
(define (synthesize-maybe-unbox-nonnull-anyref-as-object cx env name)
(js-lib cx env name `(,*anyref-type*) *Object-type*
"
function (p) {
if (p.hasOwnProperty('_desc_'))
return p;
return null;
}"))
(define (render-maybe-unbox-nonnull-anyref-as-object cx env val)
(assert (not (cx.wizard? cx)))
(let ((func (lookup-synthesized-func cx env
'_maybe_unbox_nonnull_anyref_as_object
synthesize-maybe-unbox-nonnull-anyref-as-object)))
`(call ,(func.id func) ,val)))
;; TODO: here we assume JS syntax for the field-name. We can work around it for
;; the field access but not for the function name. We need some kind of
;; mangling. But really, the problem will go away as soon as we have native
;; field access.
(define (synthesize-maybenull-field-access cx env name cls field-name)
(let* ((field (assq field-name (class.fields cls)))
(field-type (cadr field)))
(js-lib cx env name `(,(class.type cls)) field-type "function (p) { return p.~a }" field-name)))
(define (render-maybenull-field-access cx env cls field-name base-expr)
(assert (not (cx.wizard? cx)))
(let ((func (lookup-synthesized-func cx env
(splice "_maybenull_get_" (class.name cls) "_" field-name)
synthesize-maybenull-field-access
cls field-name)))
`(call ,(func.id func) ,base-expr)))
(define (synthesize-maybenull-field-update cx env name cls field-name)
(let* ((field (assq field-name (class.fields cls)))
(field-type (cadr field)))
(js-lib cx env name `(,(class.type cls) ,field-type) *void-type* "function (p, v) { p.~a = v }" field-name)))
(define (render-maybenull-field-update cx env cls field-name base-expr val-expr)
(assert (not (cx.wizard? cx)))
(let ((func (lookup-synthesized-func cx env
(splice "_maybenull_set_" (class.name cls) "_" field-name)
synthesize-maybenull-field-update
cls field-name)))
`(call ,(func.id func) ,base-expr ,val-expr)))
(define (synthesize-maybenull-ref-field-update cx env name cls field-name field-type)
(js-lib cx env name `(,(class.type cls) ,field-type) *void-type* "function (p, v) { p.~a = v }" field-name))
(define (render-maybenull-ref-field-update cx env cls field-name field-type base-expr val-expr)
(assert (cx.wizard? cx))
(let ((func (lookup-synthesized-func cx env
(splice "_maybenull_set_" (class.name cls) "_" field-name)
synthesize-maybenull-ref-field-update
cls field-name field-type)))
`(call ,(func.id func) ,base-expr ,val-expr)))
;; Strings and string literals
(define (emit-string-literals cx env)
(let ((out (support.strings (cx.support cx))))
(for-each (lambda (s)
(write s out)
(display ",\n" out))
(map car (reverse (cx.strings cx))))))
(define (synthesize-string-literal cx env name)
(js-lib cx env name `(,*i32-type*) *String-type* "function (n) { return self.strings[n] }"))
(define (render-string-literal cx env n)
(let ((func (lookup-synthesized-func cx env '_string_literal synthesize-string-literal)))
`(call ,(func.id func) (i32.const ,n))))
(define (synthesize-new-string-and-string-10chars cx env name name2)
(js-lib cx env name (make-list 11 *i32-type*) *String-type*
"
function (n,x1,x2,x3,x4,x5,x6,x7,x8,x9,x10) {
self.buffer.push(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10);
let s = String.fromCharCode.apply(null, self.buffer.slice(0,self.buffer.length-10+n));
self.buffer.length = 0;
return s;
}")
(js-lib cx env name2 (make-list 10 *i32-type*) *void-type*
"
function (x1,x2,x3,x4,x5,x6,x7,x8,x9,x10) {
self.buffer.push(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10);
}"))
(define (render-new-string cx env args)
(let* ((new_string (lookup-synthesized-func cx env '_new_string synthesize-new-string-and-string-10chars '_string_10chars))
(string_10chars (lookup-func env '_string_10chars)))
(let loop ((n (length args)) (args args) (code '()))
(if (<= n 10)
(let ((args (append args (make-list (- 10 n) '(i32.const 0)))))
`(block ,(wast-type-name cx *String-type*)
,@(reverse code)
(call ,(func.id new_string) (i32.const ,n) ,@args)))
(loop (- n 10)
(list-tail args 10)
(cons `(call ,(func.id string_10chars) ,@(list-head args 10))
code))))))
(define (synthesize-string-length cx env name)
(js-lib cx env name `(,*String-type*) *i32-type* "function (p) { return p.length }"))
(define (render-string-length cx env expr)
(let ((func (lookup-synthesized-func cx env '_string_length synthesize-string-length)))
`(call ,(func.id func) ,expr)))
(define (synthesize-string-ref cx env name)
(js-lib cx env name `(,*String-type* ,*i32-type*) *i32-type*
"
function (str,idx) {
if ((idx >>> 0) >= str.length)
throw new RangeError('Out of range: ' + idx + ' for ' + str.length);
return str.charCodeAt(idx);
}"))
(define (render-string-ref cx env e0 e1)
(let ((func (lookup-synthesized-func cx env '_string_ref synthesize-string-ref)))
`(call ,(func.id func) ,e0 ,e1)))
(define (synthesize-string-append cx env name)
(js-lib cx env name `(,*String-type* ,*String-type*) *String-type* "function (p,q) { return p + q }"))
(define (render-string-append cx env e0 e1)
(let ((func (lookup-synthesized-func cx env '_string_append synthesize-string-append)))
`(call ,(func.id func) ,e0 ,e1)))
(define (synthesize-substring cx env name)
(js-lib cx env name `(,*String-type* ,*i32-type* ,*i32-type*) *String-type*
"
function (str,start,end) {
if ((start >>> 0) >= str.length || (end >>> 0) > str.length)
throw new RangeError('Out of range: ' + start + ',' + end + ' for ' + str.length);
return str.substring(start,end);
}"))
(define (render-substring cx env e0 e1 e2)
(let ((func (lookup-synthesized-func cx env '_substring synthesize-substring)))
`(call ,(func.id func) ,e0 ,e1 ,e2)))
(define (synthesize-string-compare cx env name)
(js-lib cx env name `(,*String-type* ,*String-type*) *i32-type*
"
function (p,q) {
let a = p.length;
let b = q.length;
let l = a < b ? a : b;
for ( let i=0; i < l; i++ ) {
let x = p.charCodeAt(i);
let y = q.charCodeAt(i);
if (x != y) return x - y;
}
return a - b;
}"))
(define (render-string-compare cx env e0 e1)
(let ((func (lookup-synthesized-func cx env '_string_compare synthesize-string-compare)))
`(call ,(func.id func) ,e0 ,e1)))
(define (synthesize-maybenull-vector->string cx env name)
(js-lib cx env name `(,(make-vector-type cx env *i32-type*)) *String-type*
"function (x) { return String.fromCharCode.apply(null, x._memory_) }"))
(define (render-maybenull-vector->string cx env e)
(let ((func (lookup-synthesized-func cx env '_maybenull_vector_to_string synthesize-maybenull-vector->string)))
`(call ,(func.id func) ,e)))
(define (synthesize-string->vector cx env name)
(let ((vt (make-vector-type cx env *i32-type*)))
(js-lib cx env name `(,*String-type*) vt
"
function (s) {
let len = s.length;
let mem = new Array(len);
for (let i = 0; i < len; i++)
mem[i] = s.charCodeAt(i);
return new self.types.Vector({_vdesc_: ~a, _length_: len, _memory_: mem});
}" (type.vector-id vt))))
(define (render-string->vector cx env e)
(let ((func (lookup-synthesized-func cx env '_string_to_vector synthesize-string->vector)))
`(call ,(func.id func) ,e)))
(define (synthesize-upcast-string-to-anyref cx env name)
(js-lib cx env name `(,*String-type*) *anyref-type* "function (p) { return p }"))
(define (render-upcast-string-to-anyref cx env expr)
(let ((func (lookup-synthesized-func cx env '_upcast_string_to_anyref synthesize-upcast-string-to-anyref)))
`(call ,(func.id func) ,expr)))
(define (synthesize-maybenull-anyref-is-string cx env name)
(js-lib cx env '_anyref_is_string `(,*anyref-type*) *i32-type*
"
function (p) { return p !== null && p instanceof String }"))
(define (render-maybenull-anyref-is-string cx env val)
(let ((func (lookup-synthesized-func cx env '_anyref_is_string synthesize-maybenull-anyref-is-string)))
`(call ,(func.id func) ,val)))
(define (synthesize-unbox-maybenull-anyref-as-string cx env name)
(js-lib cx env name `(,*anyref-type*) *String-type*
"
function (p) {
if (p !== null && !(p instanceof String))
throw new Error('Failed to narrow to string' + p);
return p;
}"))
(define (render-unbox-maybenull-anyref-as-string cx env val)
(let ((func (lookup-synthesized-func cx env
'_unbox_anyref_as_string
synthesize-unbox-maybenull-anyref-as-string)))
`(call ,(func.id func) ,val)))
;; Vectors
;;
;; Some of these are a little dodgy because they use anyref as the parameter,
;; yet that implies some kind of upcast.
(define (render-vector-null cx env element-type)
`(ref.null anyref))
(define (synthesize-new-vector cx env name element-type)
(let ((vt (type.vector-of element-type)))
(js-lib cx env name `(,*i32-type* ,element-type) vt
"
function (len, init) {
let mem = new Array(len);
for (let i = 0; i < len; i++)
mem[i] = init;
return new self.types.Vector({_vdesc_: ~a, _length_: len, _memory_: mem});
}" (type.vector-id vt))))
(define (render-new-vector cx env element-type len init)
(let ((func (lookup-synthesized-func cx env (splice "_new_vector_" (render-element-type element-type))
synthesize-new-vector
element-type)))
`(call ,(func.id func) ,len ,init)))
(define (synthesize-maybenull-vector-length cx env name element-type)
(js-lib cx env name `(,*anyref-type*) *i32-type* "function (p) { return p._length_ }"))
(define (render-maybenull-vector-length cx env expr element-type)
(let ((func (lookup-synthesized-func cx env (splice "_maybenull_vector_length_" (render-element-type element-type))
synthesize-maybenull-vector-length
element-type)))
`(call ,(func.id func) ,expr)))
(define (synthesize-maybenull-vector-ref cx env name element-type)
(js-lib cx env name `(,*anyref-type* ,*i32-type*) element-type
"
function (p,i) {
if ((i >>> 0) >= p._length_)
throw new RangeError('Out of range: ' + i + ' for ' + p._length_);
return p._memory_[i];
}"))
(define (render-maybenull-vector-ref cx env e0 e1 element-type)
(let ((func (lookup-synthesized-func cx env (splice "_maybenull_vector_ref_" (render-element-type element-type))
synthesize-maybenull-vector-ref
element-type)))
`(call ,(func.id func) ,e0 ,e1)))
(define (synthesize-maybenull-vector-set! cx env name element-type)
(js-lib cx env name `(,*anyref-type* ,*i32-type* ,element-type) *void-type*
"
function (p,i,v) {
if ((i >>> 0) >= p._length_)
throw new RangeError('Out of range: ' + i + ' for ' + p._length_);
p._memory_[i] = v;
}"))
(define (render-maybenull-vector-set! cx env e0 e1 e2 element-type)
(let ((func (lookup-synthesized-func cx env (splice "_maybenull_vector_set_" (render-element-type element-type))
synthesize-maybenull-vector-set!
element-type)))
`(call ,(func.id func) ,e0 ,e1 ,e2)))
(define (synthesize-upcast-maybenull-vector-to-anyref cx env name element-type)
(js-lib cx env name `(,*anyref-type*) *anyref-type* "function (p) { return p }"))
(define (render-upcast-maybenull-vector-to-anyref cx env element-type expr)
(let ((func (lookup-synthesized-func cx env (splice "_upcast_maybenull_vector_" (render-element-type element-type) "_to_anyref")
synthesize-upcast-maybenull-vector-to-anyref
element-type)))
`(call ,(func.id func) ,expr)))
(define (synthesize-maybe-unbox-nonnull-anyref-as-vector cx env name)
(js-lib cx env name `(,*anyref-type*) *anyref-type*
"
function (p) {
if (p.hasOwnProperty('_vdesc_'))
return p;
return null;
}"))
(define (render-maybe-unbox-nonnull-anyref-as-vector cx env val)
(let ((func (lookup-synthesized-func cx env '_maybe_unbox_nonnull_anyref_as_vector
synthesize-maybe-unbox-nonnull-anyref-as-vector)))
`(call ,(func.id func) ,val)))
(define (render-element-type element-type)
(cond ((Vector-type? element-type)
(string-append "@" (render-element-type (type.vector-element element-type))))
((class-type? element-type)
(symbol->string (class.name (type.class element-type))))
(else
(symbol->string (type.name element-type)))))
(define (write-js-header out module-name)
(fmt out
"var " module-name " =
(function () {
var TO=TypedObject;
var self = {
"))
(define (write-js-module out mode module-name wasm-name code)
(case mode
((js)
(fmt out
"_module: new WebAssembly.Module(wasmTextToBinary(`
" code "
`)),
compile: function () { return Promise.resolve(self._module) },
"))
((js-bytes)
(fmt out
"_module: new WebAssembly.Module(" (splice module-name "_bytes") "),
compile: function () { return Promise.resolve(self._module) },
"))
((js-wasm)
(fmt out
"compile: function () { return fetch('" wasm-name "').then(WebAssembly.compileStreaming) },
"))
(else
(canthappen))))
(define (write-js-footer out support)
(fmt
out
"
desc:
{
"
(get-output-string (support.desc support))
"},
types:
{
'Vector': new TO.StructType({_vdesc_:TO.int32, _length_:TO.int32, _memory_: TO.Object}),
"
(get-output-string (support.type support))
"},
strings:
[
"
(get-output-string (support.strings support))
"],
buffer:[],
lib:
{
"
(get-output-string (support.lib support))
"}
};
return self;
})();
"))
(define (write-js-wast-for-bytes out module-name code)
(let ((module-bytes (splice module-name "_bytes")))
(fmt out
"
// Run this program in a JS shell and capture the output in a .bytes.js file.
// The .bytes.js file must be loaded before the companion .js file.
var " module-bytes " = wasmTextToBinary(`
" code "
`);
// Make sure the output is sane
new WebAssembly.Module(" module-bytes ");
print('var " module-bytes " = new Uint8Array([' + new Uint8Array(" module-bytes ").join(',') + ']).buffer;');
")))
(define (write-js-wast-for-wasm out module-name code)
(let ((module-bytes (splice module-name "_bytes")))
(fmt out
"
// Run this program in a JS shell and capture the output in a temp file, which
// must then be postprocessed by `binarize` to produce a .wasm file.
var " module-bytes " = wasmTextToBinary(`
" code "
`);
// Make sure the output is sane
new WebAssembly.Module(" module-bytes ");
putstr(Array.prototype.join.call(new Uint8Array(" module-bytes "), ' '));
")))
;; Lists
(define (filter pred l)
(cond ((null? l) l)
((pred (car l))
(cons (car l) (filter pred (cdr l))))
(else
(filter pred (cdr l)))))
(define (list-head l n)
(if (zero? n)
'()
(cons (car l) (list-head (cdr l) (- n 1)))))
(define (last-pair l)
(if (not (pair? (cdr l)))
l
(last-pair (cdr l))))
(define (every? pred l)
(if (null? l)
#t
(and (pred (car l))
(every? pred (cdr l)))))
(define (iota n)
(let loop ((n n) (l '()))
(if (zero? n)
l
(loop (- n 1) (cons (- n 1) l)))))
(define (sort xs less?)
(define (distribute xs)
(map list xs))
(define (merge2 as bs)
(cond ((null? as) bs)
((null? bs) as)
((less? (car as) (car bs))
(cons (car as) (merge2 (cdr as) bs)))
(else
(cons (car bs) (merge2 as (cdr bs))))))
(define (merge inputs)
(if (null? (cdr inputs))
(car inputs)
(let loop ((inputs inputs) (outputs '()))
(cond ((null? inputs)
(merge outputs))
((null? (cdr inputs))
(merge (cons (car inputs) outputs)))
(else
(loop (cddr inputs)
(cons (merge2 (car inputs) (cadr inputs))
outputs)))))))
(if (null? xs)
xs
(merge (distribute xs))))
;; Strings
(define (string-join strings sep)
(if (null? strings)
""
(let loop ((xs (list (car strings))) (strings (cdr strings)))
(if (null? strings)
(apply string-append (reverse xs))
(loop (cons (car strings) (cons sep xs)) (cdr strings))))))
;; Formatting
(define (format out0 fmt . xs)
(let ((out (cond ((eq? out0 #t) (current-output-port))
((eq? out0 #f) (open-output-string))
(else out0)))
(len (string-length fmt)))
(let loop ((i 0) (xs xs))
(cond ((= i len))
((char=? (string-ref fmt i) #\~)
(cond ((< (+ i 1) len)
(case (string-ref fmt (+ i 1))
((#\a)
(display (car xs) out)
(loop (+ i 2) (cdr xs)))
((#\~)
(write-char #\~ out)
(loop (+ i 2) xs))
(else
(error "Bad format: " fmt))))
(else
(write-char #\~ out)
(loop (+ i 1) xs))))
(else
(write-char (string-ref fmt i) out)
(loop (+ i 1) xs)))
(if (eq? #f out0)
(get-output-string out)))))
(define (pretty-type x)
(case (type.name x)
((i32 i64 f32 f64 void)
(type.name x))
((class)
`(class ,(class.name (type.class x))))
(else
x)))
(define (splice . xs)
(string->symbol (apply string-splice xs)))
(define (string-splice . xs)
(apply string-append (map (lambda (x)
(cond ((string? x) x)
((symbol? x) (symbol->string x))
((number? x) (number->string x))
(else (canthappen))))
xs)))
(define (fmt out . args)
(for-each (lambda (x)
(cond ((string? x) (display x out))
((symbol? x) (display x out))
((number? x) (display x out))
(else (pretty-print out x))))
args))
(define (pretty-print out x)
(define indented #f)
(define pending-nl #f)
(define in 0)
(define (nl)
(set! pending-nl #t)
(set! indented #f))
(define (flush)
(if pending-nl
(begin
(set! pending-nl #f)
(newline out)))
(if (not indented)
(begin
(set! indented #t)
(pr (make-string in #\space)))))
(define (prq x)
(flush)
(write x out))
(define (pr x)
(flush)
(display x out))
(define (type? x)
(or (symbol? x)
(and (list? x) (= (length x) 2) (eq? (car x) 'ref))))
(define (print-indented x on-initial-line? exprs indents)
(pr #\()
(print (car x))
(let ((xs
(let loop ((xs (cdr x)) (exprs exprs))
(cond ((null? xs) xs)
((on-initial-line? (car xs))
(pr #\space)
(print (car xs))
(loop (cdr xs) exprs))
((> exprs 0)
(pr #\space)
(print (car xs))
(loop (cdr xs) (- exprs 1)))
(else xs)))))
(if (not (null? xs))
(begin
(nl)
(set! in (+ in (* 2 indents)))
(for-each (lambda (x) (print x) (nl)) xs)
(set! in (- in (* 2 indents)))))
(display #\) out)))
(define (print-module x)
(print-indented x (lambda (x) #f) 0 1))
(define (print-func x)
(print-indented x
(lambda (x)
(and (pair? x) (memq (car x) '(param result export))))
0 1))
(define (print-if x)
(print-indented x type? 1 2))
(define (print-block x)
(print-indented x type? 0 1))
(define (print-list x)
(print-indented x (lambda (x) #t) 0 0))
(define (print x)
(cond ((or (string? x) (number? x))
(prq x))
((symbol? x)
(pr x))
((null? x)
(pr "()"))
((pair? x)
(case (car x)
((module) (print-module x))
((func) (print-func x))
((if) (print-if x))
((block loop) (print-block x))
(else (print-list x))))
((indirection? x)
(prq (indirection-get x)))
(else
(write x)
(error "Don't know what this is: " x))))
(print x))
(define (comma-separate strings)
(string-join strings ","))
;; Files
(define (remove-file fn)
(guard (exn (else #t))
(delete-file fn)))
;; Error reporting
(define (handle-failure thunk)
(call-with-current-continuation
(lambda (k)
(set! *leave* k)
(let ((result (thunk)))
(set! *leave* #f)
result))))
(define *leave* #f)
(define (fail msg . irritants)
(display "FAIL: ")
(display msg)
(for-each (lambda (x)
(display " ")
(display x))
irritants)
(newline)
(if *leave*
(*leave* #f)
(exit #f)))
;; Do it
(main)
| true |
836a7274aa47fda8a343f6caad4389c1c6c2e9af
|
5fe14ef1ced9caa3b7d1fc3248ba86155e9628f5
|
/tests/srfi-39.scm
|
1e3444b43cb8d5172c646588216ea3924b9b4379
|
[] |
no_license
|
mario-goulart/chicken-tests
|
95720ed5b29e7a7c209d4431b9558f21916752f1
|
04b8e059aaacaea308aac40082d346e884cb901c
|
refs/heads/master
| 2020-06-02T08:18:08.888442 | 2012-07-12T14:02:29 | 2012-07-12T14:02:29 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 611 |
scm
|
srfi-39.scm
|
; Test suite for SRFI-39
; 2004-01-02 / lth
;(cond-expand (srfi-39))
(define (writeln . xs)
(for-each display xs)
(newline))
(define (fail token . more)
(writeln "Error: test failed: " token)
#f)
(define radix
(make-parameter "10" (lambda (x)
(if (number? x)
x
(string->number x)))))
(or (equal? 10 (radix))
(fail 'get:1))
(parameterize ((radix 16))
(or (equal? 16 (radix))
(fail 'get:2)))
(or (equal? 10 (radix))
(fail 'get:3))
(radix 2)
(or (equal? 2 (radix))
(fail 'set:1))
(radix "20")
(or (equal? 20 (radix))
(fail 'set:2))
(writeln "Done.")
| false |
d411c54b121d07a0fef43e51c917db8b71cf47fa
|
a1adfbe57cbf00f380b6da4666c6f467f13ca531
|
/pnkfelix/objects-lecture/queue2.sls
|
cfbde744ced6b038de2c8e3a3cd4223943c3eebd
|
[] |
no_license
|
pnkfelix/pnkfelix.github.com
|
b9856c6ff4fcb63fa450744d396b7d5cf4785cbe
|
2da02366dc0af520d79f3cb862bcfde2290a2f2b
|
refs/heads/master
| 2023-01-24T12:26:54.931482 | 2023-01-18T04:56:37 | 2023-01-18T04:56:37 | 7,489,545 | 5 | 2 | null | 2020-12-23T00:20:15 | 2013-01-07T20:45:18 |
HTML
|
UTF-8
|
Scheme
| false | false | 1,015 |
sls
|
queue2.sls
|
#!r6rs
(library (obj-lecture queue2)
(export empty snoc isEmpty head tail)
(import (rnrs base))
;; A LoV is one of: [[ LoV is also written Listof[SchemeValue] ]]
;; - '()
;; - (cons SchemeValue LoV)
;; A Queue is a (list LoV LoV)
;;
;; interpretation:
;; A Queue (F R) is the sequence (append F (reverse R))
;;
;; INVARIANT: for any Queue (F R), F is null only if R is null.
;; empty : -> Queue
(define (empty)
(list '() '()))
;; snoc : Queue SchemeValue -> Queue
(define (snoc q v)
(cond ;; (why do we know the first clause below is okay?)
((null? (car q)) (list (list v) '()))
(else (list (car q) (cons v (cadr q))))))
;; isEmpty: Queue -> Boolean
(define (isEmpty q)
(and (null? (car q)) (null? (cadr q))))
;; head : Queue -> SchemeValue
(define (head q)
(car (car q)))
;; tail : Queue -> Queue
(define (tail q)
(cond
((null? (cdr (car q))) (list (reverse (cadr q)) '()))
(else (list (cdr (car q)) (cadr q))))))
| false |
d80c670b72966f396bf37b4de44d752ab4601636
|
92b8d8f6274941543cf41c19bc40d0a41be44fe6
|
/testsuite/reflect2.scm
|
e26ad6d05251b4229755adb7a77cd6b907e825f0
|
[
"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 | 360 |
scm
|
reflect2.scm
|
;; Kawa-options: --diagnostic-strip-directories --script %F
(define sb (java.lang.StringBuilder))
(sb:append "abcdefg")
(sb:setLength 3)
(display (sb:toString))(newline)
;; Diagnostic: reflect2.scm:3:2: warning - no known slot 'append' in java.lang.Object
;; Diagnostic: reflect2.scm:4:2: warning - no known slot 'setLength' in java.lang.Object
;; Output: abc
| false |
3c13702a095ebd4fcbf212377330c6ea1ddecdb2
|
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
|
/sitelib/util/treemap.scm
|
7f73fa14ddffc28a1618cbaca94ab681058103e2
|
[
"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 | 3,824 |
scm
|
treemap.scm
|
;;; -*- mode: scheme; coding: utf-8 -*-
;;;
;;; treemap.scm - treemap utilities
;;;
;;; Copyright (c) 2010-2019 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.
;;;
(library (util treemap)
(export make-rb-treemap
make-rb-treemap/comparator
treemap?
treemap-ref
treemap-set!
treemap-adjoin!
treemap-replace!
treemap-delete!
treemap-update!
treemap-clear!
treemap-copy
treemap-contains?
treemap-size
treemap-entries treemap-entries-list
treemap-keys treemap-keys-list
treemap-values treemap-values-list
treemap-higher-entry treemap-lower-entry
treemap-first-entry treemap-last-entry
treemap-pop-first-entry! treemap-pop-last-entry!
treemap-for-each treemap-map treemap-fold
treemap-for-each-reverse treemap-map-reverse treemap-fold-reverse
treemap-find/index treemap-reverse-find/index
treemap-find treemap-reverse-find
treemap-seek
treemap->alist alist->treemap
)
(import (rnrs)
(only (core base) wrong-type-argument-message)
(clos user)
(sagittarius)
(sagittarius treemap)
(sagittarius object))
;; should we move this to lib_treemap.stub?
(define %unique (list #t))
(define (treemap-adjoin! tree k v)
(treemap-update! tree k (lambda (old) (if (eq? old %unique) v old)) %unique))
;; TODO not efficient
(define (treemap-replace! tree k v)
(when (treemap-contains? tree k) (treemap-set! tree k v)))
;; from Gauche
(define (treemap-seek tm pred succ fail)
(let ((itr (treemap-iterator tm)) (eof (cons #t #t)))
(let loop ()
(let-values (((k v) (itr eof)))
(cond ((eq? k eof) (fail))
((pred k v) => (lambda (r) (succ r k v)))
(else (loop)))))))
;; end
(define (treemap-pop-first-entry! tm)
(let ((itr (treemap-iterator tm)) (eof (cons #t #t)))
(let-values (((k v) (itr eof)))
(and (not (eq? k eof))
(treemap-delete! tm k)
(cons k v)))))
(define (treemap-pop-last-entry! tm :optional (fallback #f))
(let ((itr (treemap-reverse-iterator tm)) (eof (cons #t #t)))
(let-values (((k v) (itr eof)))
(and (not (eq? k eof))
(treemap-delete! tm k)
(cons k v)))))
;; for generic ref
(define-method ref ((tm <tree-map>) key)
(treemap-ref tm key #f))
(define-method ref ((tm <tree-map>) key fallback)
(treemap-ref tm key fallback))
(define-method (setter ref) ((tm <tree-map>) key value)
(treemap-set! tm key value))
)
| false |
afe953e51b4a37a7ef73a4131a93ffaa45e517c0
|
120324bbbf63c54de0b7f1ca48d5dcbbc5cfb193
|
/packages/nanopass/tests/compiler.ss
|
b2f35ac49aa76cdb3d3304dee9be37cc03677c8b
|
[
"MIT"
] |
permissive
|
evilbinary/scheme-lib
|
a6d42c7c4f37e684c123bff574816544132cb957
|
690352c118748413f9730838b001a03be9a6f18e
|
refs/heads/master
| 2022-06-22T06:16:56.203827 | 2022-06-16T05:54:54 | 2022-06-16T05:54:54 | 76,329,726 | 609 | 71 |
MIT
| 2022-06-16T05:54:55 | 2016-12-13T06:27:36 |
Scheme
|
UTF-8
|
Scheme
| false | false | 59,311 |
ss
|
compiler.ss
|
;;; Copyright (c) 2000-2015 Dipanwita Sarkar, Andrew W. Keep, R. Kent Dybvig, Oscar Waddell
;;; See the accompanying file Copyright for details
(library (tests compiler)
(export
;; languages
LP L0 L1 L2 L3 L4 L5 L6 L7 L8 L9 L10 L11 L12 L13 L14 L15 L16 L17 L18
;; parsers
parse-LP parse-L0 parse-L1 parse-L2 parse-L3 parse-L4 parse-L5 parse-L6
parse-L7 parse-L8 parse-L9 parse-L10 parse-L11 parse-L13 parse-L14
parse-L15 parse-L16 parse-L17 parse-L18
;; unparsers
unparse-LP unparse-L0 unparse-L1 unparse-L2 unparse-L3 unparse-L4
unparse-L5 unparse-L6 unparse-L7 unparse-L8 unparse-L9 unparse-L10
unparse-L11 unparse-L12 unparse-L13 unparse-L14 unparse-L15 unparse-L16
unparse-L17 unparse-L18
;; passes
verify-scheme remove-implicit-begin remove-unquoted-constant
remove-one-armed-if uncover-settable remove-impure-letrec remove-set!
sanitize-binding remove-anonymous-lambda uncover-free convert-closure
lift-letrec explicit-closure normalize-context remove-complex-opera*
remove-anonymous-call introduce-dummy-rp remove-nonunary-let
return-of-set! explicit-labels
;; preprocessor
rename-vars/verify-legal)
(import (rnrs) (nanopass) (tests helpers) (tests synforms) (nanopass nano-syntax-dispatch))
(define-language LP
(terminals
(variable (x))
(datum (d))
(user-primitive (pr)))
(Expr (e body)
d
x
pr
(set! x e)
(if e1 e2)
(if e1 e2 e3)
(begin e1 ... e2)
(lambda (x ...) body1 ... body2)
(let ((x e) ...) body1 ... body2)
(letrec ((x e) ...) body1 ... body2)
(e0 e1 ...)))
(define-parser parse-LP LP)
(define-language L0 (extends LP)
(Expr (e body)
(- d
x
pr
(e0 e1 ...))
(+ (datum d)
(var x)
(primapp pr e ...)
(app e0 e1 ...))))
(define-parser parse-L0 L0)
(define-who rename-vars/verify-legal
(lambda (expr)
(define keywords '(quote set! if begin let letrec lambda))
(define extend-env*
(lambda (x* env)
(let f ([x* x*] [rx* '()] [env env])
(if (null? x*)
(values (reverse rx*) env)
(let ([x (car x*)])
(let ([rx (gen-symbol x)])
(f (cdr x*) (cons rx rx*) (cons (cons x rx) env))))))))
(let f ([expr expr] [env '()])
(define f* (lambda (e* env) (map (lambda (e) (f e env)) e*)))
(with-output-language (L0 Expr)
(syncase expr
[,const (guard (constant? const)) `(datum ,const)]
[(quote ,lit) (guard (not (assq 'quote env))) `(datum ,lit)]
[,var
(guard (symbol? var))
(cond
[(assq var env) => (lambda (a) `(var ,(cdr a)))]
[(memq var keywords) (error who "invalid reference to keyword" var)]
[else (error who "reference to unbound var" var)])]
[(set! ,var ,rhs)
(guard (not (assq 'set! env)) (symbol? var))
(cond
[(assq var env) => (lambda (a) `(set! ,(cdr a) ,(f rhs env)))]
[(memq var keywords) (error who "set! of keyword" expr)]
[else (error who "set! of unbound var" expr)])]
[(if ,e0 ,e1)
(guard (not (assq 'if env)))
`(if ,(f e0 env) ,(f e1 env))]
[(if ,e0 ,e1 ,e2)
(guard (not (assq 'if env)))
`(if ,(f e0 env) ,(f e1 env) ,(f e2 env))]
[(begin ,e* ... ,e)
(guard (not (assq 'begin env)))
`(begin ,(f* e* env) ... ,(f e env))]
[(let ([,x* ,rhs*] ...) ,e* ... ,e)
(guard (for-all symbol? x*) (set? x*))
(let-values ([(x* new-env) (extend-env* x* env)])
`(let ([,x* ,(f* rhs* env)] ...)
,(f* e* new-env) ... ,(f e new-env)))]
[(letrec ([,x* ,rhs*] ...) ,e* ... ,e)
(guard (for-all symbol? x*) (set? x*))
(let-values ([(x* env) (extend-env* x* env)])
`(letrec ([,x* ,(f* rhs* env)] ...)
,(f* e* env) ... ,(f e env)))]
[(lambda (,x* ...) ,e* ... ,e)
(guard (not (assq 'lambda env)) (for-all symbol? x*) (set? x*))
(let-values ([(x* env) (extend-env* x* env)])
`(lambda (,x* ...) ,(f* e* env) ... ,(f e env)))]
[(,prim ,rand* ...)
(guard (not (assq prim env)) (user-primitive? prim)
(= (cadr (assq prim list-of-user-primitives)) (length rand*)))
`(primapp ,prim ,(f* rand* env) ...)]
[(,rator ,rand* ...) `(app ,(f rator env) ,(f* rand* env) ...)]
[else (error who "invalid expression" expr)])))))
(define-pass verify-scheme : LP (ir) -> L0 ()
(definitions
(define invalid-var?
(lambda (x env)
(cond
[(memq x env) #f]
[(keyword? x) "keyword"]
[(user-primitive? x) "user-primitive"]
[else "unbound variable"])))
(define valid-bindings?
(lambda (ls)
(for-all variable? ls)))
(define duplicate-names?
(lambda (var*)
(let f ([ls var*] [dups '()])
(cond
[(null? ls) (if (null? dups) #f dups)]
[(and (memq (car ls) (cdr ls)) (not (memq (car ls) dups)))
(f (cdr ls) (cons (car ls) dups))]
[else (f (cdr ls) dups)]))))
(define format-list
(lambda (ls)
(case (length ls)
[(0) ""]
[(1) (format "~s" (car ls))]
[(2) (format "~s and ~s" (car ls) (cadr ls))]
[else (let f ([a (car ls)] [ls (cdr ls)])
(if (null? ls)
(format "and ~s" a)
(format "~s, ~a" a (f (car ls) (cdr ls)))))]))))
(Expr : Expr (ir [env '()]) -> Expr ()
[,d `(datum ,d)]
[,x (let ([invalid? (invalid-var? x env)])
(if invalid?
(error 'verify-scheme (format "reference to ~a ~s" invalid? x))
`(var ,x)))]
[(set! ,x ,e)
(let ([invalid? (invalid-var? x env)])
(if invalid?
(error 'verify-scheme (format "assignment to ~a ~s" invalid? x))
(let ([e (Expr e env)])
`(set! ,x ,e))))]
[(lambda (,x ...) ,body1 ... ,body2)
(cond
[(not (valid-bindings? x))
(error 'verify-scheme
(format "invalid binding list ~a in lambda form" x))]
[(duplicate-names? x)
=>
(lambda (x)
(error 'verify-scheme
(format "duplicate bindings ~a in lambda form"
(format-list x))))]
[else
(let ([env (append env x)])
(let ([body1 (map (lambda (x) (Expr x env)) body1)]
[body2 (Expr body2 env)])
`(lambda (,x ...) ,body1 ... ,body2)))])]
[(let ((,x ,e) ...) ,body1 ... ,body2) ;; track variables
(cond
[(not (valid-bindings? x))
(error 'verify-scheme
(format "invalid binding list ~a in let form" x))]
[(duplicate-names? x)
=>
(lambda (x)
(error 'verify-scheme
(format "duplicate bindings ~a in let form"
(format-list x))))]
[else
(let ([e (map (lambda (x) (Expr x env)) e)])
(let ([env (append env x)])
(let ([body1 (map (lambda (x) (Expr x env)) body1)]
[body2 (Expr body2 env)])
`(let ((,x ,e) ...) ,body1 ... ,body2))))])]
[(letrec ((,x ,e) ...) ,body1 ... ,body2) ;; track variables
(cond
[(not (valid-bindings? x))
(error 'verify-scheme
(format "invalid binding list ~a in letrec form" x))]
[(duplicate-names? x)
=>
(lambda (x)
(error 'verify-scheme
(format "duplicate bindings ~a in letrec form"
(format-list x))))]
[else
(let ([env (append env x)])
(let ([e (map (lambda (x) (Expr x env)) e)])
(let ([body1 (map (lambda (x) (Expr x env)) body1)]
[body2 (Expr body2 env)])
`(letrec ((,x ,e) ...) ,body1 ... ,body2))))])]
[(,e0 ,e1 ...)
(let ([e1 (map (lambda (x) (Expr x env)) e1)])
(if (and (symbol? e0) (user-primitive? e0))
`(primapp ,e0 ,e1 ...)
`(app ,(Expr e0 env) ,e1 ...)))]))
(define-language L1 (extends L0)
(Expr (e body)
(- (lambda (x ...) body1 ... body2)
(let ((x e) ...) body1 ... body2)
(letrec ((x e) ...) body1 ... body2))
(+ (lambda (x ...) body)
(let ((x e) ...) body)
(letrec ((x e) ...) body))))
(define-parser parse-L1 L1)
(define-pass remove-implicit-begin : L0 (ir) -> L1 ()
(process-expr-expr : Expr (ir) -> Expr ()
[(lambda (,x ...) ,[body1] ... ,[body2])
`(lambda (,x ...) (begin ,body1 ... ,body2))]
[(let ((,x ,[e]) ...) ,[body1] ... ,[body2])
`(let ((,x ,e) ...) (begin ,body1 ... ,body2))]
[(letrec ((,x ,[e]) ...) ,[body1] ... ,[body2])
`(letrec ((,x ,e) ...) (begin ,body1 ... ,body2))]))
(define-language L2 (extends L1)
(Expr (e body)
(- (datum d))
(+ (quoted-const d))))
(define-parser parse-L2 L2)
(define-pass remove-unquoted-constant : L1 (ir) -> L2 ()
(process-expr-expr : Expr (ir) -> Expr ()
[(datum ,d) `(quoted-const ,d)]))
(define-language L3 (extends L2) (Expr (e body) (- (if e1 e2))))
(define-parser parse-L3 L3)
(define-pass remove-one-armed-if : L2 (ir) -> L3 ()
(process-expr-expr : Expr (ir) -> Expr ()
[(if ,[e1] ,[e2]) `(if ,e1 ,e2 (primapp void))]))
(define-language L4 (extends L3)
(Expr (e body)
(- (lambda (x ...) body)
(let ((x e) ...) body)
(letrec ((x e) ...) body))
(+ (lambda (x ...) sbody)
(let ((x e) ...) sbody)
(letrec ((x e) ...) sbody)))
(SetBody (sbody) (+ (settable (x ...) body) => body)))
(define-parser parse-L4 L4)
(define-pass uncover-settable : L3 (ir) -> L4 ()
(definitions
(define Expr*
(lambda (e* asgn-var*)
(if (null? e*)
(values '() asgn-var*)
(let-values ([(e asgn-var*) (Expr (car e*) asgn-var*)])
(let-values ([(e* asgn-var*) (Expr* (cdr e*) asgn-var*)])
(values (cons e e*) asgn-var*)))))))
(Expr : Expr (ir asgn-var*) -> Expr (asgn-var*)
[(set! ,x ,[e asgn-var*]) (values `(set! ,x ,e) (set-cons x asgn-var*))]
[(lambda (,x* ...) ,[body asgn-var*])
(let ([set-x* (intersection asgn-var* x*)])
(values `(lambda (,x* ...) (settable (,set-x* ...) ,body))
(difference asgn-var* set-x*)))]
[(let ([,x* ,e*]...) ,[body asgn-var*])
(let ([set-x* (intersection asgn-var* x*)])
(let-values ([(e* asgn-var*) (Expr* e* (difference asgn-var* set-x*))])
(values `(let ([,x* ,e*] ...) (settable (,set-x* ...) ,body)) asgn-var*)))]
[(letrec ([,x* ,e*]...) ,[body asgn-var*])
(let-values ([(e* asgn-var*) (Expr* e* asgn-var*)])
(let ([set-x* (intersection asgn-var* x*)])
(values `(letrec ((,x* ,e*) ...) (settable (,set-x* ...) ,body))
(difference asgn-var* set-x*))))]
; TODO: this code used to be supported by the automatic combiners, we've
; abandoned this in favor of threading, but we've not added threading yet
[(app ,[e asgn-var*] ,e* ...)
(let-values ([(e* asgn-var*) (Expr* e* asgn-var*)])
(values `(app ,e ,e* ...) asgn-var*))]
[(primapp ,pr ,e* ...)
(let-values ([(e* asgn-var*) (Expr* e* asgn-var*)])
(values `(primapp ,pr ,e* ...) asgn-var*))]
[(if ,[e0 asgn-var*] ,e1 ,e2)
(let-values ([(e1 asgn-var*) (Expr e1 asgn-var*)])
(let-values ([(e2 asgn-var*) (Expr e2 asgn-var*)])
(values `(if ,e0 ,e1 ,e2) asgn-var*)))]
[(begin ,e* ... ,[e asgn-var*])
(let-values ([(e* asgn-var*) (Expr* e* asgn-var*)])
(values `(begin ,e* ... ,e) asgn-var*))])
(let-values ([(e asgn-var*) (Expr ir '())]) e))
(define-language L5 (extends L4)
(Expr (e body)
(+ lexpr
(letrec ((x lexpr) ...) body))
(- (lambda (x ...) sbody)
(letrec ((x e) ...) sbody)))
(LambdaExpr (lexpr) (+ (lambda (x ...) sbody))))
(define-parser parse-L5 L5)
(define-pass remove-impure-letrec : L4 (ir) -> L5 ()
(process-expr-expr : Expr (ir) -> Expr ()
[(lambda (,x ...) ,[sbody])
(in-context LambdaExpr `(lambda (,x ...) ,sbody))]
[(letrec ((,x1 (lambda (,x2 ...) ,[sbody1])) ...) (settable () ,[body2]))
(let ([lambdabody (map
(lambda (x sbody)
(in-context LambdaExpr `(lambda (,x ...) ,sbody)))
x2 sbody1)])
`(letrec ((,x1 ,lambdabody) ...) ,body2))]
[(letrec ((,x1 ,[e]) ...) (settable (,x2 ...) ,[body]))
(let ()
(define void-maker
(lambda (ids)
(letrec ((helper (lambda (ls)
(if (null? (cdr ls))
(list (in-context Expr `(primapp void)))
(cons (in-context Expr `(primapp void))
(helper (cdr ls)))))))
(helper (iota (length ids))))))
(let* ([new-ids (map gen-symbol x1)]
[voids (void-maker x1)]
[bodies (map (lambda (lhs id)
`(set! ,lhs (var ,id))) x1 new-ids)]
[rbodies (reverse bodies)]
[new-body (cdr rbodies)]
[rest-bodies (car rbodies)])
`(let ([,x1 ,voids] ...)
(settable (,x1 ...)
(begin
(primapp void)
(let ([,new-ids ,e] ...)
;;**** this need not be from the output nonterminal ****
(settable ()
(begin ,new-body ... ,rest-bodies)))
,body)))))])
(process-setbody-setbody : SetBody (ir) -> SetBody ()
[(settable (,x ...) ,[body]) `(settable (,x ...) ,body)])
(process-expr-lexpr : Expr (ir) -> LambdaExpr ()
[(lambda (,x ...) ,[sbody]) `(lambda (,x ...) ,sbody)])
(process-setbody-expr : SetBody (ir) -> Expr ()
[(settable (,x ...) ,[body]) `,body]))
(define-language L6 (extends L5)
(Expr (e body)
(- (let ((x e) ...) sbody)
(set! x e))
(+ (let ((x e) ...) body)))
(LambdaExpr (lexpr)
(- (lambda (x ...) sbody))
(+ (lambda (x ...) body)))
(SetBody (sbody) (- (settable (x ...) body))))
(define-parser parse-L6 L6)
(define-pass remove-set! : L5 (ir) -> L6 ()
(Expr : Expr (ir [set* '()]) -> Expr ()
[(var ,x) (if (memq x set*) `(primapp car (var ,x)) `(var ,x))]
[(set! ,x ,[e set* -> e]) `(primapp set-car! (var ,x) ,e)]
[(let ((,x ,[e set* -> e]) ...) ,sbody)
(let ([body (SetBody sbody x e set*)])
`,body)])
(LambdaExpr : LambdaExpr (ir set*) -> LambdaExpr ()
[(lambda (,x ...) ,[sbody x '() set* -> body]) `,body])
(SetBody : SetBody (ir x* e* set*) -> Expr ()
[(settable () ,[body set* -> body])
(if (null? e*)
`(lambda (,x* ...) ,body)
`(let ([,x* ,e*] ...) ,body))]
[(settable (,x ...) ,[body (append x set*) -> body])
(let ()
(define settable-bindings
(lambda (var* set*)
(if (null? var*) (values '() '() '())
(let ([var (car var*)])
(let-values ([(var* lhs* rhs*)
(settable-bindings (cdr var*) set*)])
(if (memq var set*)
(let ([tmp (gen-symbol var)])
(values (cons tmp var*)
(cons var lhs*)
(cons (in-context
Expr
`(primapp cons (var ,tmp)
(primapp void))) rhs*)))
;; **** (primapp void) is still a problem here ****
(values (cons var var*) lhs* rhs*)))))))
(let-values ([(x* lhs* rhs*) (settable-bindings x* x)])
;; **** cannot have (let (,(apply append bindings*)) ---) or
;; some such, due to nano-syntax-dispatch
;; the problem is not that we don't allow ,(arbitrary
;; function call) in the metaparser
(if (null? e*)
`(lambda (,x* ...) (let ([,lhs* ,rhs*] ...) ,body))
`(let ([,x* ,e*] ...) (let ([,lhs* ,rhs*] ...) ,body)))))]))
(define-pass sanitize-binding : L6 (ir) -> L6 ()
(Expr : Expr (ir [rhs? #f]) -> Expr (#f)
[(var ,x) (values `(var ,x) #f)]
[(if ,[e1 #f -> e1 ig1] ,[e2 #f -> e2 ig2] ,[e3 #f -> e3 ig3])
(values `(if ,e1 ,e2 ,e3) #f)]
[(begin ,[e1 #f -> e1 ig1] ... ,[e2 #f -> e2 ig2])
(values `(begin ,e1 ... ,e2) #f)]
[(primapp ,pr ,[e #f -> e ig] ...) (values `(primapp ,pr ,e ...) #f)]
[(app ,[e0 #f -> e0 ig0] ,[e1 #f -> e1 ig1] ...)
(values `(app ,e0 ,e1 ...) #f)]
[(quoted-const ,d) (values `(quoted-const ,d) #f)]
[(let ([,x ,[e #t -> e lambda?]] ...) ,[body #f -> body ig])
(let-values ([(let-x* let-e* letrec-x* letrec-e*)
(let f ([x x] [e e] [lambda? lambda?])
(if (null? x)
(values '() '() '() '())
(let-values ([(let-x let-e letrec-x letrec-e)
(f (cdr x) (cdr e) (cdr lambda?))])
(let ([lhs (car x)]
[rhs (car e)]
[rhs-lambda? (car lambda?)])
(if rhs-lambda?
(values let-x let-e (cons lhs letrec-x)
(cons rhs letrec-e))
(values (cons lhs let-x) (cons rhs let-e)
letrec-x letrec-e))))))])
(if (null? letrec-x*)
(values `(let ([,let-x* ,let-e*] ...) ,body) #f)
(if (null? let-x*)
(values `(letrec ([,letrec-x* ,letrec-e*] ...) ,body) #f)
(values `(letrec ([,letrec-x* ,letrec-e*] ...)
(let ([,let-x* ,let-e*] ...) ,body)) #f))))]
[(letrec ([,x1 (lambda (,x2 ...) ,[body1 #f -> body1 ig1])] ...)
,[body2 #f -> body2 ig2])
(values `(letrec ([,x1 (lambda (,x2 ...) ,body1)] ...) ,body2) #f)])
(LambdaExpr : LambdaExpr (ir [rhs? #f]) -> LambdaExpr (dummy)
[(lambda (,x ...) ,[body #f -> body ig])
(values `(lambda (,x ...) ,body) #t)]))
(define-language L7 (extends L6) (Expr (e body) (- lexpr)))
(define-parser parse-L7 L7)
(define-pass remove-anonymous-lambda : L6 (ir) -> L7 ()
(Expr : Expr (ir) -> Expr ()
[(lambda (,x ...) ,[body])
(let ([anon (gen-symbol 'anon)])
`(letrec ([,anon (lambda (,x ...) ,body)]) (var ,anon)))]))
#;
(define-pass remove-anonymous-lambda : L6 (ir) -> L7 ()
(Expr : Expr (ir) -> Expr ()
[(lambda (,x ...) ,[body])
(let ([anon (gen-symbol 'anon)])
`(letrec ([,anon (lambda (,x ...) ,body)]) (var ,anon)))]
[(var ,x) `(var ,x)]
[(quoted-const ,d) `(quoted-const ,d)]
[(if ,[e1] ,[e2] ,[e3]) `(if ,e1 ,e2 ,e3)]
[(begin ,[e1] ... ,[e2]) `(begin ,e1 ... ,e2)]
[(let ([,x ,[e]] ...) ,[body]) `(let ([,x ,e] ...) ,body)]
[(letrec ([,x ,[lexpr]] ...) ,[body])
`(letrec ([,x ,lexpr] ...) ,body)]
[(primapp ,pr ,[e] ...) `(primapp ,pr ,e ...)]
[(app ,[e0] ,[e1] ...) `(app ,e0 ,e1 ...)])
(LambdaExpr : LambdaExpr (ir) -> LambdaExpr ()
[(lambda (,x ...) ,[body]) `(lambda (,x ...) ,body)]))
(define-language L8 (extends L7)
(entry Expr)
(LambdaExpr (lexpr) (- (lambda (x ...) body)))
(FreeExp (free-body) (+ (free (x ...) body) => body))
(LambdaExpr (lexpr) (+ (lambda (x ...) free-body))))
(define-parser parse-L8 L8)
(define-pass uncover-free : L7 (ir) -> L8 ()
(definitions
(define LambdaExpr*
(lambda (lexpr* free*)
(if (null? lexpr*)
(values '() free*)
(let-values ([(lexpr free*) (LambdaExpr (car lexpr*) free*)])
(let-values ([(lexpr* free*) (LambdaExpr* (cdr lexpr*) free*)])
(values (cons lexpr lexpr*) free*))))))
(define Expr*
(lambda (e* free*)
(if (null? e*)
(values '() free*)
(let-values ([(e free*) (Expr (car e*) free*)])
(let-values ([(e* free*) (Expr* (cdr e*) free*)])
(values (cons e e*) free*)))))))
(Expr : Expr (ir free*) -> Expr (free*)
[(letrec ([,x* ,lexpr*] ...) ,[body free*])
(let-values ([(e* free*) (LambdaExpr* lexpr* free*)])
(values `(letrec ([,x* ,e*] ...) ,body) (difference free* x*)))]
[(let ([,x* ,e*] ...) ,[body free*])
(let-values ([(e* free*) (Expr* e* (difference free* x*))])
(values `(let ([,x* ,e*] ...) ,body) free*))]
[(var ,x) (values `(var ,x) (cons x free*))]
; TODO: get threaded variables working so we don't need to do this by hand
[(app ,[e free*] ,e* ...)
(let-values ([(e* free*) (Expr* e* free*)])
(values `(app ,e ,e* ...) free*))]
[(primapp ,pr ,e* ...)
(let-values ([(e* free*) (Expr* e* free*)])
(values `(primapp ,pr ,e* ...) free*))]
[(if ,[e1 free*] ,e2 ,e3)
(let-values ([(e2 free*) (Expr e2 free*)])
(let-values ([(e3 free*) (Expr e3 free*)])
(values `(if ,e1 ,e2 ,e3) free*)))]
[(begin ,e* ... ,[e free*])
(let-values ([(e* free*) (Expr* e* free*)])
(values `(begin ,e* ... ,e) free*))])
(LambdaExpr : LambdaExpr (ir free*) -> LambdaExpr (free*)
[(lambda (,x* ...) ,[body free*])
(let ([free* (difference free* x*)])
(values `(lambda (,x* ...) (free (,free* ...) ,body)) free*))])
(let-values ([(e free*) (Expr ir '())]) e))
(define-language L9
(terminals
(variable (x))
(datum (d))
(user-primitive (pr)))
(Expr (e body)
(var x)
(quoted-const d)
(if e1 e2 e3)
(begin e1 ... e2)
(let ((x e) ...) body)
(letrec ((x lexpr) ...) c-letrec)
(primapp pr e ...)
(app e0 e1 ...)
(anonymous-call e0 e1 ...))
(LambdaExpr (lexpr)
(lambda (x ...) bf-body))
(BindFree (bf-body)
(bind-free (x1 x2 ...) body))
(Closure (c-exp)
(closure x1 x2 ...))
(ClosureLetrec (c-letrec)
(closure-letrec ((x c-exp) ...) body)))
(define-parser parse-L9 L9)
(define-pass convert-closure : L8 (ir) -> L9 ()
(Expr : Expr (ir [direct '()]) -> Expr ()
[(app (var ,x) ,[e1 direct -> e1] ...)
(guard (assq x direct))
`(app (var ,(cdr (assq x direct))) (var ,x) ,e1 ...)]
[(app ,[e0 direct -> e0] ,[e1 direct -> e1] ...)
`(anonymous-call ,e0 ,e1 ...)]
[(letrec ([,x1 (lambda (,x2 ...) (free (,x3 ...) ,body1))] ...) ,body2)
(let ([code-name* (map gen-label x1)]
[cp* (map (lambda (x) (gen-symbol 'cp)) x1)])
(let* ([direct (append (map cons x1 code-name*) direct)]
[body1 (map (lambda (exp)(Expr exp direct)) body1)]
[bind-free* (map (lambda (cp formal* free* lbody)
(in-context LambdaExpr
`(lambda (,cp ,formal* ...)
(bind-free (,cp ,free* ...)
,lbody))))
cp* x2 x3 body1)]
[closure* (map (lambda (code-name free*)
(in-context Closure
`(closure ,code-name ,free* ...)))
code-name* x3)])
`(letrec ([,code-name* ,bind-free*] ...)
(closure-letrec ([,x1 ,closure*] ...)
,(Expr body2 direct)))))]))
(define-language L10 (extends L9)
(entry LetrecExpr)
(LetrecExpr (lrexpr) (+ (letrec ((x lexpr) ...) e)))
(Expr (e body)
(- (letrec ((x lexpr) ...) c-letrec))
(+ (closure-letrec ((x c-exp) ...) body)))
(ClosureLetrec (c-letrec) (- (closure-letrec ((x c-exp) ...) body))))
(define-parser parse-L10 L10)
(define-pass lift-letrec : L9 (ir) -> L10 ()
(definitions
(define Expr*
(lambda (e* binding*)
(if (null? e*)
(values '() binding*)
(let-values ([(e binding*) (Expr (car e*) binding*)])
(let-values ([(e* binding*) (Expr* (cdr e*) binding*)])
(values (cons e e*) binding*))))))
(define LambdaExpr*
(lambda (lexpr* binding*)
(if (null? lexpr*)
(values '() binding*)
(let-values ([(lexpr binding*) (LambdaExpr (car lexpr*) binding*)])
(let-values ([(lexpr* binding*) (LambdaExpr* (cdr lexpr*) binding*)])
(values (cons lexpr lexpr*) binding*)))))))
(Expr : Expr (ir binding*) -> Expr (binding*)
; TODO: we'd like to do this using variable threading!
[(var ,x) (values `(var ,x) binding*)]
[(quoted-const ,d) (values `(quoted-const ,d) binding*)]
[(if ,e1 ,e2 ,[e3 binding*])
(let-values ([(e1 binding*) (Expr e1 binding*)])
(let-values ([(e2 binding*) (Expr e2 binding*)])
(values `(if ,e1 ,e2 ,e3) binding*)))]
[(begin ,e1 ... ,[e2 binding*])
(let-values ([(e1 binding*) (Expr* e1 binding*)])
(values `(begin ,e1 ... ,e2) binding*))]
[(let ([,x* ,e*] ...) ,[body binding*])
(let-values ([(e* binding*) (Expr* e* binding*)])
(values `(let ([,x* ,e*] ...) ,body) binding*))]
[(primapp ,pr ,e* ...)
(let-values ([(e* binding*) (Expr* e* binding*)])
(values `(primapp ,pr ,e* ...) binding*))]
[(app ,[e binding*] ,e* ...)
(let-values ([(e* binding*) (Expr* e* binding*)])
(values `(app ,e ,e* ...) binding*))]
[(anonymous-call ,[e binding*] ,e* ...)
(let-values ([(e* binding*) (Expr* e* binding*)])
(values `(anonymous-call ,e ,e* ...) binding*))]
[(letrec ((,x* ,lexpr*) ...) ,[e binding*])
(let-values ([(lexpr* binding*) (LambdaExpr* lexpr* binding*)])
(values e (append (map cons x* lexpr*) binding*)))])
(LambdaExpr : LambdaExpr (ir binding*) -> LambdaExpr (binding*)
[(lambda (,x* ...) ,[bf-body binding*])
(values `(lambda (,x* ...) ,bf-body) binding*)])
(BindFree : BindFree (ir binding*) -> BindFree (binding*)
[(bind-free (,x ,x* ...) ,[body binding*])
(values `(bind-free (,x ,x* ...) ,body) binding*)])
(ClosureLetrec : ClosureLetrec (ir binding*) -> Expr (binding*)
[(closure-letrec ([,x* ,[c-exp*]] ...) ,[body binding*])
(values `(closure-letrec ([,x* ,c-exp*] ...) ,body) binding*)])
(let-values ([(e binding*) (Expr ir '())])
(let ([x* (map car binding*)] [e* (map cdr binding*)])
`(letrec ([,x* ,e*] ...) ,e))))
(define-language L11 (extends L10)
(entry LetrecExpr)
(terminals
(+ (system-primitive (spr))))
(Expr (e body)
(- (closure-letrec ((x c-exp) ...) body))
(+ (sys-primapp spr e ...)))
(BindFree (bf-body) (- (bind-free (x1 x2 ...) body)))
(Closure (c-exp) (- (closure x1 x2 ...)))
(LambdaExpr (lexpr)
(- (lambda (x ...) bf-body))
(+ (lambda (x ...) body))))
(define-parser parse-L11 L11)
(define-pass explicit-closure : L10 (ir) -> L11 ()
(LetrecExpr : LetrecExpr (ir) -> LetrecExpr ()
[(letrec ((,x ,[lexpr]) ...) ,e)
(let ([e (Expr e '() '())]) `(letrec ((,x ,lexpr) ...) ,e))])
(Expr : Expr (ir [cp '()] [env '()]) -> Expr ()
[(var ,x)
(let ([i (list-index x env)])
(if (>= i 0)
`(sys-primapp closure-ref (var ,cp) (quoted-const ,i))
`(var ,x)))]
[(closure-letrec ((,x ,[c-exp -> e free**]) ...)
,[body cp env -> body])
(let* ([e* (append (apply append
(map
(lambda (lhs free*)
(map
(lambda (i free)
`(sys-primapp
closure-set!
(var ,lhs)
(quoted-const ,i)
,(let ([ind (list-index free env)])
(if (>= ind 0)
`(sys-primapp
closure-ref
(var ,cp)
(quoted-const ,ind))
`(var ,free)))))
(iota (length free*)) free*))
x free**))
(list body))])
(let* ([re* (reverse e*)] [e1 (cdr re*)] [e2 (car re*)])
`(let ([,x ,e] ...) (begin ,e1 ... ,e2))))])
(BindFree : BindFree (ir) -> Expr ()
[(bind-free (,x1 ,x2 ...) ,[body x1 x2 -> body]) `,body])
(Closure : Closure (ir) -> Expr (dummy)
[(closure ,x1 ,x2 ...)
(values `(sys-primapp make-closure (var ,x1)
(quoted-const ,(length x2))) x2)])
(LambdaExpr : LambdaExpr (ir) -> LambdaExpr ()
[(lambda (,x ...) ,[bf-body -> body]) `(lambda (,x ...) ,body)]))
(define-language L12
(terminals
(variable (x))
(datum (d))
(value-primitive (vp))
(predicate-primitive (pp))
(effect-primitive (ep))
(system-primitive (spr)))
(LetrecExpr (lrexpr)
(letrec ((x lexpr) ...) v))
(LambdaExpr (lexpr)
(lambda (x ...) v))
(Value (v)
(var x)
(quoted-const d)
(if p1 v2 v3)
(begin f0 ... v1)
(let ((x v1) ...) v2)
(primapp vp v ...)
(sys-primapp spr v ...)
(anonymous-call v0 v1 ...)
(app v0 v1 ...))
(Predicate (p)
(true)
(false)
(if p1 p2 p3)
(begin f0 ... p1)
(let ((x v) ...) p)
(primapp pp v ...)
(sys-primapp spr v ...)
(anonymous-call v0 v1 ...)
(app v0 v1 ...))
(Effect (f)
(nop)
(if p1 f2 f3)
(begin f0 ... f1)
(let ((x v) ...) f)
(primapp ep v ...)
(sys-primapp spr v ...)
(anonymous-call v0 v1 ...)
(app v0 v1 ...)))
(define-parser parse-L12 L12)
(define-pass normalize-context : L11 (ir) -> L12 ()
(LetrecExpr : LetrecExpr (ir) -> LetrecExpr ()
[(letrec ((,x ,[lexpr]) ...) ,[v]) `(letrec ((,x ,lexpr) ...) ,v)])
(LambdaExpr : LambdaExpr (ir) -> LambdaExpr ()
[(lambda (,x ...) ,[v]) `(lambda (,x ...) ,v)])
(Value : Expr (ir) -> Value ()
[(var ,x) `(var ,x)]
[(quoted-const ,d) `(quoted-const ,d)]
[(if ,[p0] ,[v1] ,[v2]) `(if ,p0 ,v1 ,v2)]
[(begin ,[f0] ... ,[v1]) `(begin ,f0 ... ,v1)]
[(let ((,x ,[v1]) ...) ,[v2]) `(let ((,x ,v1) ...) ,v2)]
[(primapp ,pr ,[p])
(guard (equal? pr 'not))
`(if ,p (quoted-const #f) (quoted-const #t))]
[(primapp ,pr ,[v0] ...)
(guard (predicate-primitive? pr))
`(if (primapp ,pr ,v0 ...) (quoted-const #t) (quoted-const #f))]
[(primapp ,pr ,[v0] ...)
(guard (value-primitive? pr))
`(primapp ,pr ,v0 ...)]
[(primapp ,pr ,[v0] ...)
(guard (effect-primitive? pr))
`(begin (primapp ,pr ,v0 ...) (primapp void))]
[(sys-primapp ,spr ,[v0] ...)
(guard (predicate-primitive? spr))
`(if (sys-primapp ,spr ,v0 ...) (quoted-const #t) (quoted-const #f))]
[(sys-primapp ,spr ,[v0] ...)
(guard (value-primitive? spr))
`(sys-primapp ,spr ,v0 ...)]
[(sys-primapp ,spr ,[v0] ...)
(guard (effect-primitive? spr))
`(begin (primapp ,spr ,v0 ...) (primapp void))]
[(anonymous-call ,[v0] ,[v1] ...) `(anonymous-call ,v0 ,v1 ...)]
[(app ,[v0] ,[v1] ...) `(app ,v0 ,v1 ...)])
(Predicate : Expr (ir) -> Predicate ()
[(var ,x)
`(if (primapp eq? (var ,x) (quoted-const #f)) (false) (true))]
[(quoted-const ,d) (if d `(true) `(false))]
[(if ,[p0] ,[p1] ,[p2]) `(if ,p0 ,p1 ,p2)]
[(begin ,[f0] ... ,[p1]) `(begin ,f0 ... ,p1)]
[(let ((,x ,[v]) ...) ,[p]) `(let ((,x ,v) ...) ,p)]
[(primapp ,pr ,[p]) (guard (equal? pr 'not)) `(if ,p (false) (true))]
[(primapp ,pr ,[v0] ...)
(guard (predicate-primitive? pr))
`(primapp ,pr ,v0 ...)]
[(primapp ,pr ,[v0] ...)
(guard (value-primitive? pr))
`(if (primapp eq? (primapp ,pr ,v0 ...) (quoted-const #f))
(false) (true))]
[(primapp ,pr ,[v0] ...)
(guard (effect-primitive? pr))
`(begin (primapp ,pr ,v0 ...)(true))]
[(sys-primapp ,spr ,[v0] ...)
(guard (predicate-primitive? spr))
`(sys-primapp ,spr ,v0 ...)]
[(sys-primapp ,spr ,[v0] ...)
(guard (value-primitive? spr))
`(if (primapp eq? (sys-primapp ,spr ,v0 ...) (quoted-const #f))
(false) (true))]
[(sys-primapp ,spr ,[v0] ...)
(guard (effect-primitive? spr))
`(begin (sys-primapp ,spr ,v0 ...)(true))]
[(anonymous-call ,[v0] ,[v1] ...)
`(if (primapp eq? (anonymous-call ,v0 ,v1 ...) (quoted-const #f))
(false) (true))]
[(app ,[v0] ,[v1] ...)
`(if (primapp eq? (app ,v0 ,v1 ...) (quoted-const #f))
(false) (true))])
(Effect : Expr (ir) -> Effect ()
[(var ,x) `(nop)]
[(quoted-const ,d) `(nop)]
[(if ,[p0] ,[f1] ,[f2]) `(if ,p0 ,f1 ,f2)]
[(begin ,[f0] ... ,[f1]) `(begin ,f0 ... ,f1)]
[(let ((,x ,[v]) ...) ,[f]) `(let ((,x ,v) ...) ,f)]
[(primapp ,pr ,[f]) (guard (equal? pr 'not)) f]
[(primapp ,pr ,[f0] ...)
(guard (or (predicate-primitive? pr) (value-primitive? pr)))
(if (null? f0) `(nop) `(begin ,f0 ... (nop)))]
[(primapp ,pr ,[v0] ...)
(guard (effect-primitive? pr))
`(primapp ,pr ,v0 ...)]
[(sys-primapp ,spr ,[f0] ...)
(guard (or (predicate-primitive? spr) (value-primitive? spr)))
(if (null? f0) `(nop) `(begin ,f0 ... (nop)))]
[(sys-primapp ,spr ,[v0] ...)
(guard (effect-primitive? spr))
`(sys-primapp ,spr ,v0 ...)]
[(anonymous-call ,[v0] ,[v1] ...) `(anonymous-call ,v0 ,v1 ...)]
[(app ,[v0] ,[v1] ...) `(app ,v0 ,v1 ...)]))
(define-language L13
(terminals
(variable (x))
(datum (d))
(value-primitive (vp))
(predicate-primitive (pp))
(effect-primitive (ep))
(system-primitive (spr)))
(LetrecExpr (lrexpr)
(letrec ((x lexpr) ...) v))
(LambdaExpr (lexpr)
(lambda (x ...) v))
(Triv (t)
(var x)
(quoted-const d))
(Value (v)
t
(if p1 v2 v3)
(begin f0 ... v1)
(let ((x v1) ...) v2)
(primapp vp t ...)
(sys-primapp spr t ...)
(anonymous-call t0 t1 ...)
(app t0 t1 ...))
(Predicate (p)
(true)
(false)
(if p1 p2 p3)
(begin f0 ... p1)
(let ((x v) ...) p)
(primapp pp t ...)
(sys-primapp spr t ...)
(anonymous-call t0 t1 ...)
(app t0 t1 ...))
(Effect (f)
(nop)
(if p1 f2 f3)
(begin f0 ... f1)
(let ((x v) ...) f)
(primapp ep t ...)
(sys-primapp spr t ...)
(anonymous-call t0 t1 ...)
(app t0 t1 ...)))
(define-parser parse-L13 L13)
(define-pass remove-complex-opera* : L12 (ir) -> L13 ()
(definitions
(define remove-nulls
(lambda (ls)
(if (null? ls)
'()
(if (null? (car ls))
(remove-nulls (cdr ls))
(cons (car ls) (remove-nulls (cdr ls))))))))
(LetrecExpr : LetrecExpr (ir) -> LetrecExpr ()
[(letrec ((,x ,[lexpr]) ...) ,[v]) `(letrec ((,x ,lexpr) ...) ,v)])
(LambdaExpr : LambdaExpr (ir) -> LambdaExpr ()
[(lambda (,x ...) ,[v]) `(lambda (,x ...) ,v)])
(Opera : Value (ir) -> Triv (dummy)
[(var ,x) (values `(var ,x) '())]
[(quoted-const ,d) (values `(quoted-const ,d) '())]
; [,[v] (let ([tmp (gen-symbol 'tmp)])
; (values `(var ,tmp)
; (list tmp (in-context Value `,v))))])
[(if ,[p1] ,[v2] ,[v3])
(let ([tmp (gen-symbol 'tmp)])
(values `(var ,tmp)
(list tmp (in-context Value `(if ,p1 ,v2 ,v3)))))]
[(begin ,[f0] ... ,[v1])
(let ([tmp (gen-symbol 'tmp)])
(values `(var ,tmp)
(list tmp (in-context Value `(begin ,f0 ... ,v1)))))]
[(let ((,x ,[v1]) ...) ,[v2])
(let ([tmp (gen-symbol 'tmp)])
(values `(var ,tmp)
(list tmp (in-context Value `(let ((,x ,v1) ...) ,v2)))))]
[(primapp ,vp ,[t* binding*] ...)
(let ([binding* (remove-nulls binding*)])
(let ([tmp (gen-symbol 'tmp)])
(if (null? binding*)
(values `(var ,tmp)
(list tmp (in-context Value `(primapp ,vp ,t* ...))))
(let ([x (map car binding*)] [v (map cadr binding*)])
(values `(var ,tmp)
(list tmp
(in-context
Value `(let ((,x ,v) ...)
(primapp ,vp ,t* ...)))))))))]
[(sys-primapp ,spr ,[t* binding*]...)
(let ([binding* (remove-nulls binding*)])
(let ([tmp (gen-symbol 'tmp)])
(if (null? binding*)
(values `(var ,tmp)
(list tmp (in-context
Value `(sys-primapp ,spr ,t* ...))))
(let ([x (map car binding*)][v (map cadr binding*)])
(values
`(var ,tmp)
(list
tmp (in-context
Value `(let ((,x ,v) ...)
(sys-primapp ,spr ,t* ...)))))))))]
[(anonymous-call ,[v0 binding] ,[v1 binding*] ...)
(let ([binding* (remove-nulls (cons binding binding*))]
[tmp (gen-symbol 'tmp)])
(if (null? binding*)
(values `(var ,tmp)
(list tmp (in-context Value
`(anonymous-call ,v0 ,v1 ...))))
(let ([x (map car binding*)] [v (map cadr binding*)])
(values `(var ,tmp)
(list tmp (in-context
Value
`(let ((,x ,v) ...)
(anonymous-call ,v0 ,v1 ...))))))))]
[(app ,[v0] ,[t* binding*] ...)
(let ([binding* (remove-nulls binding*)])
(let ([tmp (gen-symbol 'tmp)])
(if (null? binding*)
(values `(var ,tmp)
(list tmp (in-context Value `(app ,v0 ,t* ...))))
(let ([x (map car binding*)] [v (map cadr binding*)])
(values `(var ,tmp)
(list tmp
(in-context Value
`(let ((,x ,v) ...)
(app ,v0 ,t* ...)))))))))])
(Value : Value (ir) -> Value ()
[(var ,x) (in-context Triv `(var ,x))]
[(quoted-const ,d) (in-context Triv `(quoted-const ,d))]
[(if ,[p1] ,[v2] ,[v3]) `(if ,p1 ,v2 ,v3)]
[(begin ,[f0] ... ,[v1]) `(begin ,f0 ... ,v1)]
[(let ((,x ,[v1]) ...) ,[v2]) `(let ((,x ,v1) ...) ,v2)]
[(primapp ,vp ,[t* binding*] ...)
(let ([binding* (remove-nulls binding*)])
(if (null? binding*)
`(primapp ,vp ,t* ...)
(let ([x (map car binding*)] [v (map cadr binding*)])
`(let ((,x ,v) ...)
(primapp ,vp ,t* ...)))))]
[(sys-primapp ,spr ,[t* binding*] ...)
(let ([binding* (remove-nulls binding*)])
(if (null? binding*)
`(sys-primapp ,spr ,t* ...)
(let ([x (map car binding*)][v (map cadr binding*)])
`(let ((,x ,v) ...)
(sys-primapp ,spr ,t* ...)))))]
[(anonymous-call ,[t0 binding] ,[t1 binding*] ...)
(let ([binding* (remove-nulls (cons binding binding*))])
(if (null? binding*)
`(anonymous-call ,t0 ,t1 ...)
(let ([x (map car binding*)] [v (map cadr binding*)])
`(let ((,x ,v) ...)
(anonymous-call ,t0 ,t1 ...)))))]
[(app ,[v0] ,[t* binding*] ...)
(let ([binding* (remove-nulls binding*)])
(if (null? binding*)
`(app ,v0 ,t* ...)
(let ([x (map car binding*)] [v (map cadr binding*)])
`(let ((,x ,v) ...) (app ,v0 ,t* ...)))))])
(Predicate : Predicate (ir) -> Predicate ()
[(let ((,x ,[v]) ...) ,[p]) `(let ((,x ,v) ...) ,p)]
[(primapp ,pp ,[t* binding*] ...)
(let ([binding* (remove-nulls binding*)])
(if (null? binding*)
`(primapp ,pp ,t* ...)
(let ([x (map car binding*)] [v (map cadr binding*)])
`(let ((,x ,v) ...)
(primapp ,pp ,t* ...)))))]
[(sys-primapp ,spr ,[t* binding*] ...)
(let ([binding* (remove-nulls binding*)])
(if (null? binding*)
`(sys-primapp ,spr ,t* ...)
(let ([x (map car binding*)] [v (map cadr binding*)])
`(let ((,x ,v) ...)
(sys-primapp ,spr ,t* ...)))))]
[(anonymous-call ,[t0 binding] ,[t1 binding*]...)
(let ([binding* (remove-nulls (cons binding binding*))])
(if (null? binding*)
`(anonymous-call ,t0 ,t1 ...)
(let ([x (map car binding*)] [v (map cadr binding*)])
`(let ((,x ,v) ...)
(anonymous-call ,t0 ,t1 ...)))))]
[(app ,[v0] ,[t* binding*] ...)
(let ([binding* (remove-nulls binding*)])
(if (null? binding*)
`(app ,v0 ,t* ...)
(let ([x (map car binding*)] [v (map cadr binding*)])
`(let ((,x ,v) ...) (app ,v0 ,t* ...)))))])
(Effect : Effect (ir) -> Effect ()
[(let ((,x ,[v]) ...) ,[f]) `(let ((,x ,v) ...) ,f)]
[(primapp ,ep ,[t* binding*] ...)
(let ([binding* (remove-nulls binding*)])
(if (null? binding*)
`(primapp ,ep ,t* ...)
(let ([x (map car binding*)] [v (map cadr binding*)])
`(let ((,x ,v) ...)
(primapp ,ep ,t* ...)))))]
[(sys-primapp ,spr ,[t* binding*] ...)
(let ([binding* (remove-nulls binding*)])
(if (null? binding*)
`(sys-primapp ,spr ,t* ...)
(let ([x (map car binding*)] [v (map cadr binding*)])
`(let ((,x ,v) ...)
(sys-primapp ,spr ,t* ...)))))]
[(anonymous-call ,[t0 binding] ,[t1 binding*] ...)
(let ([binding* (remove-nulls (cons binding binding*))])
(if (null? binding*)
`(anonymous-call ,t0 ,t1 ...)
(let ([x (map car binding*)] [v (map cadr binding*)])
`(let ((,x ,v) ...) (anonymous-call ,t0 ,t1 ...)))))]
[(app ,[v0] ,[t* binding*] ...)
(let ([binding* (remove-nulls binding*)])
(if (null? binding*)
`(app ,v0 ,t* ...)
(let ([x (map car binding*)] [v (map cadr binding*)])
`(let ((,x ,v) ...) (app ,v0 ,t* ...)))))]))
(define-language L14 (extends L13)
(entry LetrecExpr)
(Value (v) (- (anonymous-call t0 t1 ...)))
(Predicate (p) (- (anonymous-call t0 t1 ...)))
(Effect (f) (- (anonymous-call t0 t1 ...))))
(define-pass remove-anonymous-call : L13 (ir) -> L14 ()
(Value : Value (ir) -> Value ()
[(anonymous-call ,[t0] ,[t1] ...)
(let ([tmp (gen-symbol 'tmp)])
`(let ([,tmp (sys-primapp procedure-code ,t0)])
(app (var ,tmp) ,t0 ,t1 ...)))])
(Predicate : Predicate (ir) -> Predicate ()
[(anonymous-call ,[t0] ,[t1] ...)
(let ([tmp (gen-symbol 'tmp)])
`(let ([,tmp (sys-primapp procedure-code ,t0)])
(app (var ,tmp) ,t0 ,t1 ...)))])
(Effect : Effect (ir) -> Effect ()
[(anonymous-call ,[t0] ,[t1] ...)
(let ([tmp (gen-symbol 'tmp)])
`(let ([,tmp (sys-primapp procedure-code ,t0)])
(app (var ,tmp) ,t0 ,t1 ...)))]))
(define-parser parse-L14 L14)
(define-language L15
(terminals
(variable (x))
(datum (d))
(value-primitive (vp))
(predicate-primitive (pp))
(effect-primitive (ep))
(system-primitive (spr)))
(LetrecExpr (lrexpr)
(letrec ((x1 lexpr) ...) rnexpr))
(RunExpr (rnexpr)
(run (x) tl))
(LambdaExpr (lexpr)
(lambda (x ...) tl))
(Triv (t)
(var x)
(quoted-const d))
(Application (a)
(app t0 t1 ...))
(Tail (tl)
(return t1 t2)
(if p1 tl2 tl3)
(begin f0 ... tl1)
(let ((x ntl1) ...) tl2)
(app t0 t1 ...))
(Nontail (ntl)
t
(if p1 ntl2 ntl3)
(begin f0 ... ntl1)
(let ((x ntl1) ...) ntl2)
(primapp vp t ...)
(sys-primapp spr t ...)
(return-point x a))
(Predicate (p)
(true)
(false)
(if p1 p2 p3)
(begin f0 ... p1)
(let ((x ntl) ...) p)
(primapp pp t ...)
(sys-primapp spr t ...))
(Effect (f)
(nop)
(if p1 f2 f3)
(begin f0 ... f1)
(let ((x ntl) ...) f)
(primapp ep t ...)
(sys-primapp spr t ...)
(return-point x a)))
(define-parser parse-L15 L15)
; (define process-tail
; (lambda (expr rp)
; (match expr
; [(quote ,datum) `(return ,rp (quote ,datum))]
; [,var (guard (symbol? var)) `(return ,rp ,var)]
; [(if ,test ,[conseq] ,[altern])
; `(if ,(process-nontail test) ,conseq ,altern)]
; [(begin ,expr* ...)
; `(begin
; ,@((foldl '())
; (lambda (expr)
; (lambda (expr*)
; (if (null? expr*)
; (cons (process-tail expr rp) expr*)
; (cons (process-nontail expr) expr*))))
; expr*))]
; [(let ([,lhs* ,rhs*] ...) ,[body])
; (let ([rhs* (map process-nontail rhs*)])
; `(let ([,lhs* ,rhs*] ...)
; ,body))]
; [(,prim ,rand* ...)
; (guard (primitive? prim))
; (let ([rand* (map process-nontail rand*)])
; (let ([tmp (gen-symbol 'tmp)])
; `(let ([,tmp (,prim ,rand* ...)])
; (return ,rp ,tmp))))]
; [(,rator ,rand* ...)
; (let ([rator (process-nontail rator)]
; [rand* (map process-nontail rand*)])
; `(,rator ,rp ,rand* ...))]
; [,expr (error 'insert-dummy-rp "Invalid expression: ~s" expr)])))
; (define process-nontail
; (lambda (expr)
; (match expr
; [(quote ,datum) `(quote ,datum)]
; [,var (guard (symbol? var)) `,var]
; [(if ,[test] ,[conseq] ,[altern])
; `(if ,test ,conseq ,altern)]
; [(begin ,[expr*] ...) `(begin ,expr* ...)]
; [(let ([,lhs* ,[rhs*]] ...) ,[body])
; `(let ([,lhs* ,rhs*] ...) ,body)]
; [(,prim ,[rand*] ...)
; (guard (primitive? prim))
; `(,prim ,rand* ...)]
; [(,[rator] ,[rand*] ...)
; (let ([label (gen-label (gen-symbol 'lab))])
; `(return-point ,label
; (,rator ,label ,rand* ...)))]
; [,expr (error 'insert-dummy-rp "Invalid expression: ~s" expr)])))
; (define process-lambda
; (lambda (expr)
; (match expr
; [(lambda (,formal* ...) ,body)
; (let ([rp (gen-symbol 'rp)])
; `(lambda (,rp ,formal* ...)
; ,(process-tail body rp)))])))
; (define process-letrec
; (lambda (expr)
; (match expr
; [(letrec ([,lhs* ,rhs*] ...) ,body)
; (let ([rhs* (map process-lambda rhs*)])
; (let ([rp (gen-symbol 'rp)])
; `(letrec ([,lhs* ,rhs*] ...)
; (run (,rp)
; ,(process-tail body rp)))))])))
(define-pass introduce-dummy-rp : L14 (ir) -> L15 ()
(LetrecExpr : LetrecExpr (ir) -> LetrecExpr ()
[(letrec ((,x ,[lexpr]) ...) ,[rnexpr])
`(letrec ((,x ,lexpr) ...) ,rnexpr)])
(LambdaExpr : LambdaExpr (ir) -> LambdaExpr ()
[(lambda (,x ...) ,v)
(let ([rp (gen-symbol 'rp)])
(let ([tl (ValueTail v rp)])
`(lambda (,rp ,x ...) ,tl)))])
(ValueRun : Value (ir) -> RunExpr ()
[(var ,x) (let ([rp (gen-symbol 'rp)])
`(run (,rp) (return (var ,rp) (var ,x))))]
[(quoted-const ,d)
(let ([rp (gen-symbol 'rp)])
`(run (,rp) (return (var ,rp) (quoted-const ,d))))]
[(if ,[p1] ,v2 ,v3)
(let ([rp (gen-symbol 'rp)])
(let ([tl2 (ValueTail v2 rp)]
[tl3 (ValueTail v3 rp)])
`(run (,rp) (if ,p1 ,tl2 ,tl3))))]
[(begin ,[f0] ... ,v1)
(let ([rp (gen-symbol 'rp)])
(let ([tl1 (ValueTail v1 rp)])
`(run (,rp) (begin ,f0 ... ,tl1))))]
[(let ((,x ,[ntl1]) ...) ,v2)
(let ([rp (gen-symbol 'rp)])
(let ([tl2 (ValueTail v2 rp)])
`(run (,rp) (let ((,x ,ntl1) ...) ,tl2))))]
[(primapp ,vp ,[t] ...)
(let ([rp (gen-symbol 'rp)])
(let ([tmp (gen-symbol 'tmp)])
`(run (,rp) (let ([,tmp (primapp ,vp ,t ...)])
(return (var ,rp) (var ,tmp))))))]
[(sys-primapp ,spr ,[t] ...)
(let ([rp (gen-symbol 'rp)])
(let ([tmp (gen-symbol 'tmp)])
`(run (,rp) (let ([,tmp (primapp ,spr ,t ...)])
(return (var ,rp) (var ,tmp))))))]
[(app ,[t0] ,[t1] ...)
(let ([rp (gen-symbol 'rp)])
`(run (,rp)(app ,t0 (var ,rp) ,t1 ...)))])
(ValueTail : Value (ir rp) -> Tail ()
[(var ,x) `(return (var ,rp) (var ,x))]
[(quoted-const ,d) `(return (var ,rp) (quoted-const ,d))]
[(if ,[p1] ,[ValueTail : v2 rp -> tl2] ,[ValueTail : v3 rp -> tl3])
`(if ,p1 ,tl2 ,tl3)]
[(begin ,[f0] ... ,[ValueTail : v1 rp -> tl1]) `(begin ,f0 ... ,tl1)]
[(let ((,x ,[ntl1]) ...) ,[ValueTail : v2 rp -> tl2])
`(let ((,x ,ntl1) ...) ,tl2)]
[(primapp ,vp ,[t] ...)
(let ([tmp (gen-symbol 'tmp)])
`(let ([,tmp (primapp ,vp ,t ...)])
(return (var ,rp) (var ,tmp))))]
[(sys-primapp ,spr ,[t] ...)
(let ([tmp (gen-symbol 'tmp)])
`(let ([,tmp (primapp ,spr ,t ...)])
(return (var ,rp) (var ,tmp))))]
[(app ,[t0] ,[t1] ...) `(app ,t0 (var ,rp) ,t1 ...)])
(ValueNTail : Value (ir) -> Nontail ()
[(if ,[p1] ,[ntl2] ,[ntl3]) `(if ,p1 ,ntl2 ,ntl3)]
[(begin ,[f0] ... ,[ntl1]) `(begin ,f0 ... ,ntl1)]
[(let ((,x ,[ntl1]) ...) ,[ntl2]) `(let ((,x ,ntl1) ...) ,ntl2)]
[(app ,[t0] ,[t1] ...)
(let ([label (gen-label (gen-symbol 'lab))])
`(return-point ,label (app ,t0 (var ,label) ,t1 ...)))])
(Predicate : Predicate (ir) -> Predicate ()
[(let ((,x ,[ntl1]) ...) ,[p]) `(let ((,x ,ntl1) ...) ,p)])
(Effect : Effect (ir) -> Effect ()
[(let ((,x ,[ntl1]) ...) ,[f]) `(let ((,x ,ntl1) ...) ,f)]
[(app ,[t0] ,[t1] ...)
(let ([label (gen-label (gen-symbol 'lab))])
`(return-point ,label (app ,t0 (var ,label) ,t1 ...)))]))
(define-language L16 (extends L15)
(entry LetrecExpr)
(Tail (tl)
(- (let ((x ntl1) ...) tl2))
(+ (let ((x ntl1)) tl2)))
(Nontail (ntl)
(- (let ((x ntl1) ...) ntl2))
(+ (let ((x ntl1)) ntl2)))
(Predicate (p)
(- (let ((x ntl) ...) p))
(+ (let ((x ntl)) p)))
(Effect (f)
(- (let ((x ntl) ...) f))
(+ (let ((x ntl)) f))))
(define-parser parse-L16 L16)
(define-pass remove-nonunary-let : L15 (ir) -> L16 ()
(Tail : Tail (ir) -> Tail ()
[(let ((,x ,[ntl]) ...) ,[tl])
(let loop ([lhs* x] [rhs* ntl])
(if (null? lhs*)
tl
(let ([x (car lhs*)]
[ntl (car rhs*)]
[tl (loop (cdr lhs*) (cdr rhs*))])
`(let ((,x ,ntl)) ,tl))))])
(Nontail : Nontail (ir) -> Nontail ()
[(let ((,x ,[ntl1]) ...) ,[ntl2])
(let loop ([lhs* x] [rhs* ntl1])
(if (null? lhs*)
ntl2
(let ([x (car lhs*)]
[ntl1 (car rhs*)]
[ntl2 (loop (cdr lhs*) (cdr rhs*))])
`(let ((,x ,ntl1)) ,ntl2))))])
(Predicate : Predicate (ir) -> Predicate ()
[(let ((,x ,[ntl]) ...) ,[p])
(let loop ([lhs* x] [rhs* ntl])
(if (null? lhs*)
p
(let ([x (car lhs*)]
[ntl (car rhs*)]
[p (loop (cdr lhs*) (cdr rhs*))])
`(let ((,x ,ntl)) ,p))))])
(Effect : Effect (ir) -> Effect ()
[(let ((,x ,[ntl]) ...) ,[f])
(let loop ([lhs* x] [rhs* ntl])
(if (null? lhs*)
f
(let ([x (car lhs*)]
[ntl (car rhs*)]
[f (loop (cdr lhs*) (cdr rhs*))])
`(let ((,x ,ntl)) ,f))))]))
(define-language L17 (extends L16)
(entry LetrecExpr)
(RunExpr (rnexpr)
(- (run (x) tl))
(+ (run (x) dec)))
(LambdaExpr (lexpr)
(- (lambda (x ...) tl))
(+ (lambda (x ...) dec)))
(DeclareExpr (dec) (+ (declare (x ...) tl)))
(Tail (tl) (- (let ((x ntl1)) tl2)))
(Nontail (ntl)
(- t
(if p1 ntl2 ntl3)
(begin f0 ... ntl1)
(let ((x ntl1)) ntl2)
(primapp vp t ...)
(sys-primapp spr t ...)
(return-point x a)))
(RhsExpr (rhs)
(+ t
(if p1 rhs2 rhs3)
(begin f0 ... rhs1)
(primapp vp t ...)
(sys-primapp spr t ...)
(return-point x a)))
(Predicate (p) (- (let ((x ntl)) p)))
(Effect (f)
(- (let ((x ntl)) f))
(+ (set! x rhs))))
(define-parser parse-L17 L17)
(define-pass return-of-set! : L16 (ir) -> L17 ()
(definitions
(define Effect*
(lambda (f* var*)
(if (null? f*)
(values '() var*)
(let-values ([(f var*) (Effect (car f*) var*)])
(let-values ([(f* var*) (Effect* (cdr f*) var*)])
(values (cons f f*) var*)))))))
(RunExpr : RunExpr (ir) -> RunExpr ()
[(run (,x) ,[tl '() -> tl var*]) `(run (,x) (declare (,var* ...) ,tl))])
(LambdaExpr : LambdaExpr (ir) -> LambdaExpr ()
[(lambda (,x* ...) ,[tl '() -> tl var*]) `(lambda (,x* ...) (declare (,var* ...) ,tl))])
(Tail : Tail (ir var*) -> Tail (var*)
[(let ([,x ,ntl]) ,[tl var*])
(let-values ([(rhs var*) (Nontail ntl var*)])
(values `(begin (set! ,x ,rhs) ,tl) (cons x var*)))]
[(if ,[p1 var*] ,tl2 ,tl3)
(let-values ([(tl2 var*) (Tail tl2 var*)])
(let-values ([(tl3 var*) (Tail tl3 var*)])
(values `(if ,p1 ,tl2 ,tl3) var*)))]
[(begin ,f* ... ,[tl var*])
(let-values ([(f* var*) (Effect* f* var*)])
(values `(begin ,f* ... ,tl) var*))])
(Nontail : Nontail (ir var*) -> RhsExpr (var*)
[(let ((,x ,ntl1)) ,[rhs2 var*])
(let-values ([(rhs1 var*) (Nontail ntl1 var*)])
(values `(begin (set! ,x ,rhs1) ,rhs2) (cons x var*)))]
[(if ,[p1 var*] ,ntl2 ,ntl3)
(let-values ([(rhs2 var*) (Nontail ntl2 var*)])
(let-values ([(rhs3 var*) (Nontail ntl3 var*)])
(values `(if ,p1 ,rhs2 ,rhs3) var*)))]
[(begin ,f* ... ,[rhs var*])
(let-values ([(f* var*) (Effect* f* var*)])
(values `(begin ,f* ... ,rhs) var*))]
; TODO: something we could do better here? Triv->Rhs is effectively just this code
[(quoted-const ,d) (values `(quoted-const ,d) var*)]
[(var ,x) (values `(var ,x) var*)])
(Effect : Effect (ir var*) -> Effect (var*)
[(let ([,x ,ntl]) ,[f var*])
(let-values ([(rhs var*) (Nontail ntl var*)])
(values `(begin (set! ,x ,rhs) ,f) var*))]
[(if ,[p1 var*] ,f2 ,f3)
(let-values ([(f2 var*) (Effect f2 var*)])
(let-values ([(f3 var*) (Effect f3 var*)])
(values `(if ,p1 ,f2 ,f3) var*)))]
[(begin ,f* ... ,[f var*])
(let-values ([(f* var*) (Effect* f* var*)])
(values `(begin ,f* ... ,f) var*))])
(Predicate : Predicate (ir var*) -> Predicate (var*)
[(let ([,x ,ntl]) ,[p var*])
(let-values ([(rhs var*) (Nontail ntl var*)])
(values `(begin (set! ,x ,rhs) ,p) (cons x var*)))]
[(if ,[p1 var*] ,p2 ,p3)
(let-values ([(p2 var*) (Predicate p2 var*)])
(let-values ([(p3 var*) (Predicate p3 var*)])
(values `(if ,p1 ,p2 ,p3) var*)))]
[(begin ,f* ... ,[p var*])
(let-values ([(f* var*) (Effect* f* var*)])
(values `(begin ,f* ... ,p) var*))]))
(define-language L18 (extends L17)
(entry LetrecExpr)
(Triv (t) (+ (label x))))
(define-parser parse-L18 L18)
(define-pass explicit-labels : L17 (ir) -> L18 ()
(LetrecExpr : LetrecExpr (ir [labs '()]) -> LetrecExpr ()
[(letrec ((,x ,[lexpr x -> lexpr]) ...) ,[rnexpr x -> rnexpr])
`(letrec ((,x ,lexpr) ...) ,rnexpr)])
(LambdaExpr : LambdaExpr (ir labs) -> LambdaExpr ())
(Triv : Triv (ir labs) -> Triv ()
[(var ,x) (if (memq x labs) `(label ,x) `(var ,x))])
(Application : Application (ir labs) -> Application ())
(DeclareExpr : DeclareExpr (ir labs) -> DeclareExpr ())
(RunExpr : RunExpr (ir labs) -> RunExpr ())
(Tail : Tail (ir labs) -> Tail ())
(RhsExpr : RhsExpr (ir labs) -> RhsExpr ()
[(return-point ,x ,a) (let ([a (Application a (cons x labs))])
`(return-point ,x ,a))])
(Predicate : Predicate (ir labs) -> Predicate ())
(Effect : Effect (ir labs) -> Effect ()
[(return-point ,x ,a) (let ([a (Application a (cons x labs))])
`(return-point ,x ,a))])))
| false |
51ecb3ba507eae88afab49a3b2ec7c4ed74df49b
|
ac2a3544b88444eabf12b68a9bce08941cd62581
|
/lib/srfi/0/test.scm
|
7c849d4d08dc1edd0a8b56325ca96ab5f076c54b
|
[
"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 | 579 |
scm
|
test.scm
|
;;;============================================================================
;;; File: "test.scm"
;;; Copyright (c) 1994-2019 by Marc Feeley, All Rights Reserved.
;;;============================================================================
;;; SRFI 0, Feature-based conditional expansion construct
(import (srfi 0))
(import (_test))
;;;============================================================================
(cond-expand
(gambit
(check-true #t))
(else
(check-true #f)))
;;;============================================================================
| false |
ef44838eb1f739f9f69cfb149908c26c0684f034
|
0fb129f0bb28f55cb148d0e7fb1b8ca439c23e95
|
/example/basic-min.scm
|
c6479ba71fd136e4a71b7c2867036bd75009cccf
|
[] |
no_license
|
xieyuheng/sequent0
|
b3b61f8554ae8dbb352ad157531309a68cebbc0e
|
c64986ad5e6eabfbf5dd2d4a4f9aaa8978df5f48
|
refs/heads/master
| 2020-09-28T10:52:24.191893 | 2017-07-30T17:05:17 | 2017-07-30T17:05:17 | 67,279,174 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 3,244 |
scm
|
basic-min.scm
|
(+ nat (-> [] [type])
zero (-> [] [nat])
succ (-> [nat] [nat]))
(~ add (-> [nat nat] [nat])
(-> [:m zero] [:m])
(-> [:m :n succ] [:m :n add succ]))
(~ mul (-> [nat nat] [nat])
(-> [:m zero] [zero])
(-> [:m :n succ] [:m :n mul :m add]))
(~ factorial (-> [nat] [nat])
(-> [zero] [zero succ])
(-> [:n succ] [:n factorial :n succ mul]))
(run zero succ
zero succ succ
add)
(run zero succ succ
zero succ succ
mul)
(run zero succ succ succ
factorial)
(~ nat-induction (-> [(: :p (-> [nat] [type]))
zero :p @
(-> [(: :k nat) :k :p @]
[:k succ :p @])
(: :x nat)]
[[:x :p @]])
(-> [:q :q/z :q/s zero] [:q/z])
(-> [:q :q/z :q/s :n succ]
[:n
:q :q/z :q/s :n nat-induction
:q/s @]))
(~ drop (-> [:t] [])
(-> [:d]
[]))
(~ dup (-> [:t] [:t :t])
(-> [:d]
[:d :d]))
(~ over (-> [:t1 :t2] [:t1 :t2 :t1])
(-> [:d1 :d2]
[:d1 :d2 :d1]))
(~ tuck (-> [:t1 :t2] [:t2 :t1 :t2])
(-> [:d1 :d2]
[:d2 :d1 :d2]))
(~ swap (-> [:t1 :t2] [:t2 :t1])
(-> [:d1 :d2]
[:d2 :d1]))
(run zero
zero succ
swap
drop
dup)
(+ list (-> [type] [type])
null (-> [] [:t list])
cons (-> [:t list :t] [:t list]))
(~ append (-> [:t list :t list] [:t list])
(-> [:l null] [:l])
(-> [:l :r :e cons] [:l :r append :e cons]))
(~ length (-> [:t list] [nat])
(-> [null] [zero])
(-> [:l :e cons] [:l length succ]))
(run null
zero cons
null
zero cons
append)
(run null
zero cons
zero cons
null
zero cons
zero cons
append
length)
(~ map (-> [:t1 list (-> [:t1] [:t2])]
[:t2 list])
(-> [null :f] [null])
(-> [:l :e cons :f] [:l :f map :e :f @ cons]))
(run null
zero cons
zero cons
zero cons
null
zero cons
zero cons
zero cons
append
(-> [zero] [zero succ])
map)
(run null
zero cons
zero cons
(~ (-> [nat] [nat])
(-> [zero] [zero succ]))
map)
(+ has-length (-> [:t list nat] [type])
null/has-length (-> [] [null zero has-length])
cons/has-length (-> [:l :n has-length]
[:l :a cons :n succ has-length]))
(~ map/has-length (-> [:l :n has-length]
[:l :f map :n has-length])
(-> [null/has-length] [null/has-length])
(-> [:h cons/has-length] [:h map/has-length cons/has-length]))
(+ vector (-> [nat type] [type])
null (-> [] [zero :t vector])
cons (-> [:n :t vector :t]
[:n succ :t vector]))
(~ append (-> [:m :t vector :n :t vector]
[:m :n add :t vector])
(-> [:l null] [:l])
(-> [:l :r :e cons]
[:l :r append :e cons]))
(run null
zero cons
zero cons
zero cons
null
zero cons
zero cons
zero cons
append)
(~ map (-> [:n :t1 vector (-> [:t1] [:t2])]
[:n :t2 vector])
(-> [null :f] [null])
(-> [:l :e cons :f] [:l :f map :e :f @ cons]))
(run null
zero cons
zero cons
zero cons
null
zero cons
zero cons
zero cons
append
(-> [zero] [zero succ])
map)
| false |
36b088634e9a8dcc2671f2b9024f99d64fc739e5
|
4b480cab3426c89e3e49554d05d1b36aad8aeef4
|
/chapter-02/ex2.54-falsetru-test.scm
|
2a833ab0e071026ae3703e740ffec15e60954ae2
|
[] |
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 | 412 |
scm
|
ex2.54-falsetru-test.scm
|
(require (planet schematics/schemeunit:3))
(require (planet schematics/schemeunit:3/text-ui))
(load "ex2.54-falsetru.scm")
(define ex2.54-falsetru-tests
(test-suite
"Test for ex2.54-falsetru"
(check-true (my-equal? '(this is a list) '(this is a list)))
(check-false (my-equal? '(this is a list) '(this (is a) list)))
))
(exit
(cond
((= (run-tests ex2.54-falsetru-tests) 0))
(else 1)))
| false |
a226935d4e9b2407ff2460334e32ebcb3deaeb71
|
0768e217ef0b48b149e5c9b87f41d772cd9917f1
|
/sitelib/ypsilon/glut.scm
|
be11ba6d030db26d7a6950b862ac90bbc65f133b
|
[
"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 | 25,977 |
scm
|
glut.scm
|
#!nobacktrace
;;; Copyright (c) 2004-2022 Yoshikatsu Fujita / LittleWing Company Limited.
;;; See LICENSE file for terms and conditions of use.
(library (ypsilon glut)
(export glutInit
glutInitWindowPosition
glutInitWindowSize
glutInitDisplayMode
glutInitDisplayString
glutMainLoop
glutCreateWindow
glutCreateSubWindow
glutDestroyWindow
glutSetWindow
glutGetWindow
glutSetWindowTitle
glutSetIconTitle
glutReshapeWindow
glutPositionWindow
glutShowWindow
glutHideWindow
glutIconifyWindow
glutPushWindow
glutPopWindow
glutFullScreen
glutPostWindowRedisplay
glutPostRedisplay
glutSwapBuffers
glutWarpPointer
glutSetCursor
glutEstablishOverlay
glutRemoveOverlay
glutUseLayer
glutPostOverlayRedisplay
glutPostWindowOverlayRedisplay
glutShowOverlay
glutHideOverlay
glutCreateMenu
glutDestroyMenu
glutGetMenu
glutSetMenu
glutAddMenuEntry
glutAddSubMenu
glutChangeToMenuEntry
glutChangeToSubMenu
glutRemoveMenuItem
glutAttachMenu
glutDetachMenu
glutTimerFunc
glutIdleFunc
glutKeyboardFunc
glutSpecialFunc
glutReshapeFunc
glutVisibilityFunc
glutDisplayFunc
glutMouseFunc
glutMotionFunc
glutPassiveMotionFunc
glutEntryFunc
glutKeyboardUpFunc
glutSpecialUpFunc
glutJoystickFunc
glutMenuStateFunc
glutMenuStatusFunc
glutOverlayDisplayFunc
glutWindowStatusFunc
glutSpaceballMotionFunc
glutSpaceballRotateFunc
glutSpaceballButtonFunc
glutButtonBoxFunc
glutDialsFunc
glutTabletMotionFunc
glutTabletButtonFunc
glutGet
glutDeviceGet
glutGetModifiers
glutLayerGet
glutBitmapCharacter
glutBitmapWidth
glutStrokeCharacter
glutStrokeWidth
glutBitmapLength
glutStrokeLength
glutWireCube
glutSolidCube
glutWireSphere
glutSolidSphere
glutWireCone
glutSolidCone
glutWireTorus
glutSolidTorus
glutWireDodecahedron
glutSolidDodecahedron
glutWireOctahedron
glutSolidOctahedron
glutWireTetrahedron
glutSolidTetrahedron
glutWireIcosahedron
glutSolidIcosahedron
glutWireTeapot
glutSolidTeapot
glutGameModeString
glutEnterGameMode
glutLeaveGameMode
glutGameModeGet
glutVideoResizeGet
glutSetupVideoResizing
glutStopVideoResizing
glutVideoResize
glutVideoPan
glutSetColor
glutGetColor
glutCopyColormap
glutIgnoreKeyRepeat
glutSetKeyRepeat
glutForceJoystickFunc
glutExtensionSupported
glutReportErrors
GLUT_API_VERSION
GLUT_XLIB_IMPLEMENTATION
GLUT_KEY_F1
GLUT_KEY_F2
GLUT_KEY_F3
GLUT_KEY_F4
GLUT_KEY_F5
GLUT_KEY_F6
GLUT_KEY_F7
GLUT_KEY_F8
GLUT_KEY_F9
GLUT_KEY_F10
GLUT_KEY_F11
GLUT_KEY_F12
GLUT_KEY_LEFT
GLUT_KEY_UP
GLUT_KEY_RIGHT
GLUT_KEY_DOWN
GLUT_KEY_PAGE_UP
GLUT_KEY_PAGE_DOWN
GLUT_KEY_HOME
GLUT_KEY_END
GLUT_KEY_INSERT
GLUT_LEFT_BUTTON
GLUT_MIDDLE_BUTTON
GLUT_RIGHT_BUTTON
GLUT_DOWN
GLUT_UP
GLUT_LEFT
GLUT_ENTERED
GLUT_RGB
GLUT_RGBA
GLUT_INDEX
GLUT_SINGLE
GLUT_DOUBLE
GLUT_ACCUM
GLUT_ALPHA
GLUT_DEPTH
GLUT_STENCIL
GLUT_MULTISAMPLE
GLUT_STEREO
GLUT_LUMINANCE
GLUT_MENU_NOT_IN_USE
GLUT_MENU_IN_USE
GLUT_NOT_VISIBLE
GLUT_VISIBLE
GLUT_HIDDEN
GLUT_FULLY_RETAINED
GLUT_PARTIALLY_RETAINED
GLUT_FULLY_COVERED
GLUT_WINDOW_X
GLUT_WINDOW_Y
GLUT_WINDOW_WIDTH
GLUT_WINDOW_HEIGHT
GLUT_WINDOW_BUFFER_SIZE
GLUT_WINDOW_STENCIL_SIZE
GLUT_WINDOW_DEPTH_SIZE
GLUT_WINDOW_RED_SIZE
GLUT_WINDOW_GREEN_SIZE
GLUT_WINDOW_BLUE_SIZE
GLUT_WINDOW_ALPHA_SIZE
GLUT_WINDOW_ACCUM_RED_SIZE
GLUT_WINDOW_ACCUM_GREEN_SIZE
GLUT_WINDOW_ACCUM_BLUE_SIZE
GLUT_WINDOW_ACCUM_ALPHA_SIZE
GLUT_WINDOW_DOUBLEBUFFER
GLUT_WINDOW_RGBA
GLUT_WINDOW_PARENT
GLUT_WINDOW_NUM_CHILDREN
GLUT_WINDOW_COLORMAP_SIZE
GLUT_WINDOW_NUM_SAMPLES
GLUT_WINDOW_STEREO
GLUT_WINDOW_CURSOR
GLUT_SCREEN_WIDTH
GLUT_SCREEN_HEIGHT
GLUT_SCREEN_WIDTH_MM
GLUT_SCREEN_HEIGHT_MM
GLUT_MENU_NUM_ITEMS
GLUT_DISPLAY_MODE_POSSIBLE
GLUT_INIT_WINDOW_X
GLUT_INIT_WINDOW_Y
GLUT_INIT_WINDOW_WIDTH
GLUT_INIT_WINDOW_HEIGHT
GLUT_INIT_DISPLAY_MODE
GLUT_ELAPSED_TIME
GLUT_WINDOW_FORMAT_ID
GLUT_HAS_KEYBOARD
GLUT_HAS_MOUSE
GLUT_HAS_SPACEBALL
GLUT_HAS_DIAL_AND_BUTTON_BOX
GLUT_HAS_TABLET
GLUT_NUM_MOUSE_BUTTONS
GLUT_NUM_SPACEBALL_BUTTONS
GLUT_NUM_BUTTON_BOX_BUTTONS
GLUT_NUM_DIALS
GLUT_NUM_TABLET_BUTTONS
GLUT_DEVICE_IGNORE_KEY_REPEAT
GLUT_DEVICE_KEY_REPEAT
GLUT_HAS_JOYSTICK
GLUT_OWNS_JOYSTICK
GLUT_JOYSTICK_BUTTONS
GLUT_JOYSTICK_AXES
GLUT_JOYSTICK_POLL_RATE
GLUT_OVERLAY_POSSIBLE
GLUT_LAYER_IN_USE
GLUT_HAS_OVERLAY
GLUT_TRANSPARENT_INDEX
GLUT_NORMAL_DAMAGED
GLUT_OVERLAY_DAMAGED
GLUT_VIDEO_RESIZE_POSSIBLE
GLUT_VIDEO_RESIZE_IN_USE
GLUT_VIDEO_RESIZE_X_DELTA
GLUT_VIDEO_RESIZE_Y_DELTA
GLUT_VIDEO_RESIZE_WIDTH_DELTA
GLUT_VIDEO_RESIZE_HEIGHT_DELTA
GLUT_VIDEO_RESIZE_X
GLUT_VIDEO_RESIZE_Y
GLUT_VIDEO_RESIZE_WIDTH
GLUT_VIDEO_RESIZE_HEIGHT
GLUT_NORMAL
GLUT_OVERLAY
GLUT_ACTIVE_SHIFT
GLUT_ACTIVE_CTRL
GLUT_ACTIVE_ALT
GLUT_CURSOR_RIGHT_ARROW
GLUT_CURSOR_LEFT_ARROW
GLUT_CURSOR_INFO
GLUT_CURSOR_DESTROY
GLUT_CURSOR_HELP
GLUT_CURSOR_CYCLE
GLUT_CURSOR_SPRAY
GLUT_CURSOR_WAIT
GLUT_CURSOR_TEXT
GLUT_CURSOR_CROSSHAIR
GLUT_CURSOR_UP_DOWN
GLUT_CURSOR_LEFT_RIGHT
GLUT_CURSOR_TOP_SIDE
GLUT_CURSOR_BOTTOM_SIDE
GLUT_CURSOR_LEFT_SIDE
GLUT_CURSOR_RIGHT_SIDE
GLUT_CURSOR_TOP_LEFT_CORNER
GLUT_CURSOR_TOP_RIGHT_CORNER
GLUT_CURSOR_BOTTOM_RIGHT_CORNER
GLUT_CURSOR_BOTTOM_LEFT_CORNER
GLUT_CURSOR_INHERIT
GLUT_CURSOR_NONE
GLUT_CURSOR_FULL_CROSSHAIR
GLUT_RED
GLUT_GREEN
GLUT_BLUE
GLUT_KEY_REPEAT_OFF
GLUT_KEY_REPEAT_ON
GLUT_KEY_REPEAT_DEFAULT
GLUT_JOYSTICK_BUTTON_A
GLUT_JOYSTICK_BUTTON_B
GLUT_JOYSTICK_BUTTON_C
GLUT_JOYSTICK_BUTTON_D
GLUT_GAME_MODE_ACTIVE
GLUT_GAME_MODE_POSSIBLE
GLUT_GAME_MODE_WIDTH
GLUT_GAME_MODE_HEIGHT
GLUT_GAME_MODE_PIXEL_DEPTH
GLUT_GAME_MODE_REFRESH_RATE
GLUT_GAME_MODE_DISPLAY_CHANGED)
(import (core) (ypsilon c-ffi))
(define libGLUT
(let ((sysname (architecture-feature 'sysname)))
(cond ((string-contains sysname "darwin")
(load-shared-object "GLUT.framework/GLUT"))
((string-contains sysname "linux")
(load-shared-object "libglut.so.3"))
(else
(assertion-violation 'load-shared-object "can not load GLUT library, unknown operating system")))))
(define-syntax define-cdecl
(syntax-rules ()
((_ ret name args)
(define name (c-function/weak ret name args)))))
(define GLUT_API_VERSION 4)
(define GLUT_XLIB_IMPLEMENTATION 13)
(define GLUT_KEY_F1 #x0001)
(define GLUT_KEY_F2 #x0002)
(define GLUT_KEY_F3 #x0003)
(define GLUT_KEY_F4 #x0004)
(define GLUT_KEY_F5 #x0005)
(define GLUT_KEY_F6 #x0006)
(define GLUT_KEY_F7 #x0007)
(define GLUT_KEY_F8 #x0008)
(define GLUT_KEY_F9 #x0009)
(define GLUT_KEY_F10 #x000A)
(define GLUT_KEY_F11 #x000B)
(define GLUT_KEY_F12 #x000C)
(define GLUT_KEY_LEFT #x0064)
(define GLUT_KEY_UP #x0065)
(define GLUT_KEY_RIGHT #x0066)
(define GLUT_KEY_DOWN #x0067)
(define GLUT_KEY_PAGE_UP #x0068)
(define GLUT_KEY_PAGE_DOWN #x0069)
(define GLUT_KEY_HOME #x006A)
(define GLUT_KEY_END #x006B)
(define GLUT_KEY_INSERT #x006C)
(define GLUT_LEFT_BUTTON #x0000)
(define GLUT_MIDDLE_BUTTON #x0001)
(define GLUT_RIGHT_BUTTON #x0002)
(define GLUT_DOWN #x0000)
(define GLUT_UP #x0001)
(define GLUT_LEFT #x0000)
(define GLUT_ENTERED #x0001)
(define GLUT_RGB #x0000)
(define GLUT_RGBA #x0000)
(define GLUT_INDEX #x0001)
(define GLUT_SINGLE #x0000)
(define GLUT_DOUBLE #x0002)
(define GLUT_ACCUM #x0004)
(define GLUT_ALPHA #x0008)
(define GLUT_DEPTH #x0010)
(define GLUT_STENCIL #x0020)
(define GLUT_MULTISAMPLE #x0080)
(define GLUT_STEREO #x0100)
(define GLUT_LUMINANCE #x0200)
(define GLUT_MENU_NOT_IN_USE #x0000)
(define GLUT_MENU_IN_USE #x0001)
(define GLUT_NOT_VISIBLE #x0000)
(define GLUT_VISIBLE #x0001)
(define GLUT_HIDDEN #x0000)
(define GLUT_FULLY_RETAINED #x0001)
(define GLUT_PARTIALLY_RETAINED #x0002)
(define GLUT_FULLY_COVERED #x0003)
(define GLUT_WINDOW_X #x0064)
(define GLUT_WINDOW_Y #x0065)
(define GLUT_WINDOW_WIDTH #x0066)
(define GLUT_WINDOW_HEIGHT #x0067)
(define GLUT_WINDOW_BUFFER_SIZE #x0068)
(define GLUT_WINDOW_STENCIL_SIZE #x0069)
(define GLUT_WINDOW_DEPTH_SIZE #x006A)
(define GLUT_WINDOW_RED_SIZE #x006B)
(define GLUT_WINDOW_GREEN_SIZE #x006C)
(define GLUT_WINDOW_BLUE_SIZE #x006D)
(define GLUT_WINDOW_ALPHA_SIZE #x006E)
(define GLUT_WINDOW_ACCUM_RED_SIZE #x006F)
(define GLUT_WINDOW_ACCUM_GREEN_SIZE #x0070)
(define GLUT_WINDOW_ACCUM_BLUE_SIZE #x0071)
(define GLUT_WINDOW_ACCUM_ALPHA_SIZE #x0072)
(define GLUT_WINDOW_DOUBLEBUFFER #x0073)
(define GLUT_WINDOW_RGBA #x0074)
(define GLUT_WINDOW_PARENT #x0075)
(define GLUT_WINDOW_NUM_CHILDREN #x0076)
(define GLUT_WINDOW_COLORMAP_SIZE #x0077)
(define GLUT_WINDOW_NUM_SAMPLES #x0078)
(define GLUT_WINDOW_STEREO #x0079)
(define GLUT_WINDOW_CURSOR #x007A)
(define GLUT_SCREEN_WIDTH #x00C8)
(define GLUT_SCREEN_HEIGHT #x00C9)
(define GLUT_SCREEN_WIDTH_MM #x00CA)
(define GLUT_SCREEN_HEIGHT_MM #x00CB)
(define GLUT_MENU_NUM_ITEMS #x012C)
(define GLUT_DISPLAY_MODE_POSSIBLE #x0190)
(define GLUT_INIT_WINDOW_X #x01F4)
(define GLUT_INIT_WINDOW_Y #x01F5)
(define GLUT_INIT_WINDOW_WIDTH #x01F6)
(define GLUT_INIT_WINDOW_HEIGHT #x01F7)
(define GLUT_INIT_DISPLAY_MODE #x01F8)
(define GLUT_ELAPSED_TIME #x02BC)
(define GLUT_WINDOW_FORMAT_ID #x007B)
(define GLUT_HAS_KEYBOARD #x0258)
(define GLUT_HAS_MOUSE #x0259)
(define GLUT_HAS_SPACEBALL #x025A)
(define GLUT_HAS_DIAL_AND_BUTTON_BOX #x025B)
(define GLUT_HAS_TABLET #x025C)
(define GLUT_NUM_MOUSE_BUTTONS #x025D)
(define GLUT_NUM_SPACEBALL_BUTTONS #x025E)
(define GLUT_NUM_BUTTON_BOX_BUTTONS #x025F)
(define GLUT_NUM_DIALS #x0260)
(define GLUT_NUM_TABLET_BUTTONS #x0261)
(define GLUT_DEVICE_IGNORE_KEY_REPEAT #x0262)
(define GLUT_DEVICE_KEY_REPEAT #x0263)
(define GLUT_HAS_JOYSTICK #x0264)
(define GLUT_OWNS_JOYSTICK #x0265)
(define GLUT_JOYSTICK_BUTTONS #x0266)
(define GLUT_JOYSTICK_AXES #x0267)
(define GLUT_JOYSTICK_POLL_RATE #x0268)
(define GLUT_OVERLAY_POSSIBLE #x0320)
(define GLUT_LAYER_IN_USE #x0321)
(define GLUT_HAS_OVERLAY #x0322)
(define GLUT_TRANSPARENT_INDEX #x0323)
(define GLUT_NORMAL_DAMAGED #x0324)
(define GLUT_OVERLAY_DAMAGED #x0325)
(define GLUT_VIDEO_RESIZE_POSSIBLE #x0384)
(define GLUT_VIDEO_RESIZE_IN_USE #x0385)
(define GLUT_VIDEO_RESIZE_X_DELTA #x0386)
(define GLUT_VIDEO_RESIZE_Y_DELTA #x0387)
(define GLUT_VIDEO_RESIZE_WIDTH_DELTA #x0388)
(define GLUT_VIDEO_RESIZE_HEIGHT_DELTA #x0389)
(define GLUT_VIDEO_RESIZE_X #x038A)
(define GLUT_VIDEO_RESIZE_Y #x038B)
(define GLUT_VIDEO_RESIZE_WIDTH #x038C)
(define GLUT_VIDEO_RESIZE_HEIGHT #x038D)
(define GLUT_NORMAL #x0000)
(define GLUT_OVERLAY #x0001)
(define GLUT_ACTIVE_SHIFT #x0001)
(define GLUT_ACTIVE_CTRL #x0002)
(define GLUT_ACTIVE_ALT #x0004)
(define GLUT_CURSOR_RIGHT_ARROW #x0000)
(define GLUT_CURSOR_LEFT_ARROW #x0001)
(define GLUT_CURSOR_INFO #x0002)
(define GLUT_CURSOR_DESTROY #x0003)
(define GLUT_CURSOR_HELP #x0004)
(define GLUT_CURSOR_CYCLE #x0005)
(define GLUT_CURSOR_SPRAY #x0006)
(define GLUT_CURSOR_WAIT #x0007)
(define GLUT_CURSOR_TEXT #x0008)
(define GLUT_CURSOR_CROSSHAIR #x0009)
(define GLUT_CURSOR_UP_DOWN #x000A)
(define GLUT_CURSOR_LEFT_RIGHT #x000B)
(define GLUT_CURSOR_TOP_SIDE #x000C)
(define GLUT_CURSOR_BOTTOM_SIDE #x000D)
(define GLUT_CURSOR_LEFT_SIDE #x000E)
(define GLUT_CURSOR_RIGHT_SIDE #x000F)
(define GLUT_CURSOR_TOP_LEFT_CORNER #x0010)
(define GLUT_CURSOR_TOP_RIGHT_CORNER #x0011)
(define GLUT_CURSOR_BOTTOM_RIGHT_CORNER #x0012)
(define GLUT_CURSOR_BOTTOM_LEFT_CORNER #x0013)
(define GLUT_CURSOR_INHERIT #x0064)
(define GLUT_CURSOR_NONE #x0065)
(define GLUT_CURSOR_FULL_CROSSHAIR #x0066)
(define GLUT_RED #x0000)
(define GLUT_GREEN #x0001)
(define GLUT_BLUE #x0002)
(define GLUT_KEY_REPEAT_OFF #x0000)
(define GLUT_KEY_REPEAT_ON #x0001)
(define GLUT_KEY_REPEAT_DEFAULT #x0002)
(define GLUT_JOYSTICK_BUTTON_A #x0001)
(define GLUT_JOYSTICK_BUTTON_B #x0002)
(define GLUT_JOYSTICK_BUTTON_C #x0004)
(define GLUT_JOYSTICK_BUTTON_D #x0008)
(define GLUT_GAME_MODE_ACTIVE #x0000)
(define GLUT_GAME_MODE_POSSIBLE #x0001)
(define GLUT_GAME_MODE_WIDTH #x0002)
(define GLUT_GAME_MODE_HEIGHT #x0003)
(define GLUT_GAME_MODE_PIXEL_DEPTH #x0004)
(define GLUT_GAME_MODE_REFRESH_RATE #x0005)
(define GLUT_GAME_MODE_DISPLAY_CHANGED #x0006)
;; void glutInit(int* pargc, char** argv)
(define-cdecl void glutInit (void* void*))
;; void glutInitWindowPosition(int x, int y)
(define-cdecl void glutInitWindowPosition (int int))
;; void glutInitWindowSize(int width, int height)
(define-cdecl void glutInitWindowSize (int int))
;; void glutInitDisplayMode(unsigned int displayMode)
(define-cdecl void glutInitDisplayMode (unsigned-int))
;; void glutInitDisplayString(const char* displayMode)
(define-cdecl void glutInitDisplayString (void*))
;; void glutMainLoop(void)
(define-cdecl void glutMainLoop ())
;; int glutCreateWindow(const char* title)
(define-cdecl int glutCreateWindow (void*))
;; int glutCreateSubWindow(int window, int x, int y, int width, int height)
(define-cdecl int glutCreateSubWindow (int int int int int))
;; void glutDestroyWindow(int window)
(define-cdecl void glutDestroyWindow (int))
;; void glutSetWindow(int window)
(define-cdecl void glutSetWindow (int))
;; int glutGetWindow(void)
(define-cdecl int glutGetWindow ())
;; void glutSetWindowTitle(const char* title)
(define-cdecl void glutSetWindowTitle (void*))
;; void glutSetIconTitle(const char* title)
(define-cdecl void glutSetIconTitle (void*))
;; void glutReshapeWindow(int width, int height)
(define-cdecl void glutReshapeWindow (int int))
;; void glutPositionWindow(int x, int y)
(define-cdecl void glutPositionWindow (int int))
;; void glutShowWindow(void)
(define-cdecl void glutShowWindow ())
;; void glutHideWindow(void)
(define-cdecl void glutHideWindow ())
;; void glutIconifyWindow(void)
(define-cdecl void glutIconifyWindow ())
;; void glutPushWindow(void)
(define-cdecl void glutPushWindow ())
;; void glutPopWindow(void)
(define-cdecl void glutPopWindow ())
;; void glutFullScreen(void)
(define-cdecl void glutFullScreen ())
;; void glutPostWindowRedisplay(int window)
(define-cdecl void glutPostWindowRedisplay (int))
;; void glutPostRedisplay(void)
(define-cdecl void glutPostRedisplay ())
;; void glutSwapBuffers(void)
(define-cdecl void glutSwapBuffers ())
;; void glutWarpPointer(int x, int y)
(define-cdecl void glutWarpPointer (int int))
;; void glutSetCursor(int cursor)
(define-cdecl void glutSetCursor (int))
;; void glutEstablishOverlay(void)
(define-cdecl void glutEstablishOverlay ())
;; void glutRemoveOverlay(void)
(define-cdecl void glutRemoveOverlay ())
;; void glutUseLayer(GLenum layer)
(define-cdecl void glutUseLayer (unsigned-int))
;; void glutPostOverlayRedisplay(void)
(define-cdecl void glutPostOverlayRedisplay ())
;; void glutPostWindowOverlayRedisplay(int window)
(define-cdecl void glutPostWindowOverlayRedisplay (int))
;; void glutShowOverlay(void)
(define-cdecl void glutShowOverlay ())
;; void glutHideOverlay(void)
(define-cdecl void glutHideOverlay ())
;; int glutCreateMenu(void (* callback)( int menu ))
(define-cdecl int glutCreateMenu (void*))
;; void glutDestroyMenu(int menu)
(define-cdecl void glutDestroyMenu (int))
;; int glutGetMenu(void)
(define-cdecl int glutGetMenu ())
;; void glutSetMenu(int menu)
(define-cdecl void glutSetMenu (int))
;; void glutAddMenuEntry(const char* label, int value)
(define-cdecl void glutAddMenuEntry (void* int))
;; void glutAddSubMenu(const char* label, int subMenu)
(define-cdecl void glutAddSubMenu (void* int))
;; void glutChangeToMenuEntry(int item, const char* label, int value)
(define-cdecl void glutChangeToMenuEntry (int void* int))
;; void glutChangeToSubMenu(int item, const char* label, int value)
(define-cdecl void glutChangeToSubMenu (int void* int))
;; void glutRemoveMenuItem(int item)
(define-cdecl void glutRemoveMenuItem (int))
;; void glutAttachMenu(int button)
(define-cdecl void glutAttachMenu (int))
;; void glutDetachMenu(int button)
(define-cdecl void glutDetachMenu (int))
;; void glutTimerFunc(unsigned int time, void (* callback)( int ), int value)
(define-cdecl void glutTimerFunc (unsigned-int void* int))
;; void glutIdleFunc(void (* callback)( void ))
(define-cdecl void glutIdleFunc (void*))
;; void glutKeyboardFunc(void (* callback)( unsigned char, int, int ))
(define-cdecl void glutKeyboardFunc (void*))
;; void glutSpecialFunc(void (* callback)( int, int, int ))
(define-cdecl void glutSpecialFunc (void*))
;; void glutReshapeFunc(void (* callback)( int, int ))
(define-cdecl void glutReshapeFunc (void*))
;; void glutVisibilityFunc(void (* callback)( int ))
(define-cdecl void glutVisibilityFunc (void*))
;; void glutDisplayFunc(void (* callback)( void ))
(define-cdecl void glutDisplayFunc (void*))
;; void glutMouseFunc(void (* callback)( int, int, int, int ))
(define-cdecl void glutMouseFunc (void*))
;; void glutMotionFunc(void (* callback)( int, int ))
(define-cdecl void glutMotionFunc (void*))
;; void glutPassiveMotionFunc(void (* callback)( int, int ))
(define-cdecl void glutPassiveMotionFunc (void*))
;; void glutEntryFunc(void (* callback)( int ))
(define-cdecl void glutEntryFunc (void*))
;; void glutKeyboardUpFunc(void (* callback)( unsigned char, int, int ))
(define-cdecl void glutKeyboardUpFunc (void*))
;; void glutSpecialUpFunc(void (* callback)( int, int, int ))
(define-cdecl void glutSpecialUpFunc (void*))
;; void glutJoystickFunc(void (* callback)( unsigned int, int, int, int ), int pollInterval)
(define-cdecl void glutJoystickFunc (void* int))
;; void glutMenuStateFunc(void (* callback)( int ))
(define-cdecl void glutMenuStateFunc (void*))
;; void glutMenuStatusFunc(void (* callback)( int, int, int ))
(define-cdecl void glutMenuStatusFunc (void*))
;; void glutOverlayDisplayFunc(void (* callback)( void ))
(define-cdecl void glutOverlayDisplayFunc (void*))
;; void glutWindowStatusFunc(void (* callback)( int ))
(define-cdecl void glutWindowStatusFunc (void*))
;; void glutSpaceballMotionFunc(void (* callback)( int, int, int ))
(define-cdecl void glutSpaceballMotionFunc (void*))
;; void glutSpaceballRotateFunc(void (* callback)( int, int, int ))
(define-cdecl void glutSpaceballRotateFunc (void*))
;; void glutSpaceballButtonFunc(void (* callback)( int, int ))
(define-cdecl void glutSpaceballButtonFunc (void*))
;; void glutButtonBoxFunc(void (* callback)( int, int ))
(define-cdecl void glutButtonBoxFunc (void*))
;; void glutDialsFunc(void (* callback)( int, int ))
(define-cdecl void glutDialsFunc (void*))
;; void glutTabletMotionFunc(void (* callback)( int, int ))
(define-cdecl void glutTabletMotionFunc (void*))
;; void glutTabletButtonFunc(void (* callback)( int, int, int, int ))
(define-cdecl void glutTabletButtonFunc (void*))
;; int glutGet(GLenum query)
(define-cdecl int glutGet (unsigned-int))
;; int glutDeviceGet(GLenum query)
(define-cdecl int glutDeviceGet (unsigned-int))
;; int glutGetModifiers(void)
(define-cdecl int glutGetModifiers ())
;; int glutLayerGet(GLenum query)
(define-cdecl int glutLayerGet (unsigned-int))
;; void glutBitmapCharacter(void* font, int character)
(define-cdecl void glutBitmapCharacter (void* int))
;; int glutBitmapWidth(void* font, int character)
(define-cdecl int glutBitmapWidth (void* int))
;; void glutStrokeCharacter(void* font, int character)
(define-cdecl void glutStrokeCharacter (void* int))
;; int glutStrokeWidth(void* font, int character)
(define-cdecl int glutStrokeWidth (void* int))
;; int glutBitmapLength(void* font, const unsigned char* string)
(define-cdecl int glutBitmapLength (void* void*))
;; int glutStrokeLength(void* font, const unsigned char* string)
(define-cdecl int glutStrokeLength (void* void*))
;; void glutWireCube(GLdouble size)
(define-cdecl void glutWireCube (double))
;; void glutSolidCube(GLdouble size)
(define-cdecl void glutSolidCube (double))
;; void glutWireSphere(GLdouble radius, GLint slices, GLint stacks)
(define-cdecl void glutWireSphere (double int int))
;; void glutSolidSphere(GLdouble radius, GLint slices, GLint stacks)
(define-cdecl void glutSolidSphere (double int int))
;; void glutWireCone(GLdouble base, GLdouble height, GLint slices, GLint stacks)
(define-cdecl void glutWireCone (double double int int))
;; void glutSolidCone(GLdouble base, GLdouble height, GLint slices, GLint stacks)
(define-cdecl void glutSolidCone (double double int int))
;; void glutWireTorus(GLdouble innerRadius, GLdouble outerRadius, GLint sides, GLint rings)
(define-cdecl void glutWireTorus (double double int int))
;; void glutSolidTorus(GLdouble innerRadius, GLdouble outerRadius, GLint sides, GLint rings)
(define-cdecl void glutSolidTorus (double double int int))
;; void glutWireDodecahedron(void)
(define-cdecl void glutWireDodecahedron ())
;; void glutSolidDodecahedron(void)
(define-cdecl void glutSolidDodecahedron ())
;; void glutWireOctahedron(void)
(define-cdecl void glutWireOctahedron ())
;; void glutSolidOctahedron(void)
(define-cdecl void glutSolidOctahedron ())
;; void glutWireTetrahedron(void)
(define-cdecl void glutWireTetrahedron ())
;; void glutSolidTetrahedron(void)
(define-cdecl void glutSolidTetrahedron ())
;; void glutWireIcosahedron(void)
(define-cdecl void glutWireIcosahedron ())
;; void glutSolidIcosahedron(void)
(define-cdecl void glutSolidIcosahedron ())
;; void glutWireTeapot(GLdouble size)
(define-cdecl void glutWireTeapot (double))
;; void glutSolidTeapot(GLdouble size)
(define-cdecl void glutSolidTeapot (double))
;; void glutGameModeString(const char* string)
(define-cdecl void glutGameModeString (void*))
;; int glutEnterGameMode(void)
(define-cdecl int glutEnterGameMode ())
;; void glutLeaveGameMode(void)
(define-cdecl void glutLeaveGameMode ())
;; int glutGameModeGet(GLenum query)
(define-cdecl int glutGameModeGet (unsigned-int))
;; int glutVideoResizeGet(GLenum query)
(define-cdecl int glutVideoResizeGet (unsigned-int))
;; void glutSetupVideoResizing(void)
(define-cdecl void glutSetupVideoResizing ())
;; void glutStopVideoResizing(void)
(define-cdecl void glutStopVideoResizing ())
;; void glutVideoResize(int x, int y, int width, int height)
(define-cdecl void glutVideoResize (int int int int))
;; void glutVideoPan(int x, int y, int width, int height)
(define-cdecl void glutVideoPan (int int int int))
;; void glutSetColor(int color, GLfloat red, GLfloat green, GLfloat blue)
(define-cdecl void glutSetColor (int float float float))
;; GLfloat glutGetColor(int color, int component)
(define-cdecl float glutGetColor (int int))
;; void glutCopyColormap(int window)
(define-cdecl void glutCopyColormap (int))
;; void glutIgnoreKeyRepeat(int ignore)
(define-cdecl void glutIgnoreKeyRepeat (int))
;; void glutSetKeyRepeat(int repeatMode)
(define-cdecl void glutSetKeyRepeat (int))
;; void glutForceJoystickFunc(void)
(define-cdecl void glutForceJoystickFunc ())
;; int glutExtensionSupported(const char* extension)
(define-cdecl int glutExtensionSupported (void*))
;; void glutReportErrors(void)
(define-cdecl void glutReportErrors ())
) ;[end]
| true |
cefa5d662a7101d4dd7fe3fc4050a641d572ad8e
|
c2603f0d6c6e523342deaa1e284b7855a450a6f7
|
/autoload/vgen/compiler.scm
|
d692c1f38ad9f1f23db0303ce6ced78ca457403c
|
[] |
no_license
|
aharisu/vise
|
5d35a085e6b1070920e9a4e035339050091b2be0
|
6d0f54b0fe28e7d2c3b2b91cb3ef5ff847a11484
|
refs/heads/master
| 2020-06-02T10:48:42.822204 | 2013-02-21T09:42:59 | 2013-02-21T09:42:59 | 7,975,231 | 1 | 1 | null | 2013-02-20T12:26:45 | 2013-02-02T11:53:18 | null |
UTF-8
|
Scheme
| false | false | 4,090 |
scm
|
compiler.scm
|
(define-module vgen.compiler
(use gauche.parameter)
(use vgen.util)
(use vgen.common)
(use vgen.compiler.read)
(use vgen.compiler.include)
(use vgen.compiler.expand)
(use vgen.compiler.check)
(use vgen.compiler.add-return)
(use vgen.compiler.render)
(use vgen.compiler.lambda-expand)
(use vgen.compiler.self-recursion)
(use vgen.compiler.erase)
(use vgen.compiler.add-repl-eval)
(export vise-compile-from-string vise-compile
vise-repl
)
)
(select-module vgen.compiler)
(define (vise-compile-from-string str)
(vise-compile (open-input-string str)))
(define (get-file-path in-port)
(if (eq? (port-type in-port) 'file)
(sys-dirname (port-name in-port))
(sys-normalize-pathname "." :absolute #t :expand #t :canonicalize #t)))
(define (make-global-env)
(rlet1 env (make-env #f)
(hash-table-for-each
renderer-table
(lambda (k v) (env-add-symbol&exp env k 'syntax v)))
(for-each
(lambda (sym) (env-add-symbol env sym 'syntax))
vim-symbol-list)))
(define (make-vise-macro-module)
(rlet1 m (make-module #f)
(eval '(begin
(use util.match)
(use srfi-1) ;list
(use util.list)
(use srfi-13) ;string
(use vgen.common :only (vise-error))
)
m)))
(define (vise-compile in-port
:key (out-port (current-output-port))
(load-path '())
(prologue "")
(epilogue ""))
(let1 global-env (make-global-env)
(parameterize ([toplevel-env global-env]
[vise-macro-module (make-vise-macro-module)])
(let1 exp-list ((.$
vise-phase-render
vise-phase-erase
vise-phase-lambda-expand
vise-phase-self-recursion
vise-phase-add-return
(pa$ vise-phase-check global-env)
(pa$ vise-phase-expand global-env)
(pa$ vise-phase-include load-path (get-file-path in-port))
vise-phase-read)
in-port)
(with-output-to-port
out-port
(lambda ()
(display prologue)
(for-each print exp-list)
(display epilogue)))))))
(define (vise-repl in-port
:key (script-output-port (current-output-port))
(prompt-output-port (current-output-port))
(load-path '())
)
(let* ([global-env (make-global-env)]
[translator (.$
vise-phase-render
vise-phase-lambda-expand
vise-phase-self-recursion
vise-phase-add-return
(pa$ vise-phase-check global-env)
vise-phase-add-repl-eval
(pa$ vise-phase-expand global-env)
(pa$ vise-phase-include load-path (get-file-path in-port)))])
(parameterize ([toplevel-env global-env]
[vise-macro-module (make-vise-macro-module)]
[script-prefix "b:"])
(letrec ((repl (lambda ()
(guard (e [(<vise-error> e)
(display (@ e.message) prompt-output-port)
(newline prompt-output-port)
(repl)])
(port-for-each
(lambda (e)
(for-each
(lambda (exp)
(display exp script-output-port)
(flush script-output-port))
(translator (list e))))
(lambda ()
(display "vise> " prompt-output-port)
(flush prompt-output-port)
(vise-phase-read-repl in-port)))))))
(repl)))))
| false |
4f3a091c2c8d13043edd957081c136c591564282
|
2861d122d2f859f287a9c2414057b2768870b322
|
/tests/test-aes.scm
|
c51047ff912de9e5f3d6193f4d183053c0e4fd5d
|
[
"BSD-3-Clause"
] |
permissive
|
ktakashi/aeolus
|
c13162e47404ad99c4834da6677fc31f5288e02e
|
2a431037ea53cb9dfb5b585ab5c3fbc25374ce8b
|
refs/heads/master
| 2016-08-10T08:14:20.628720 | 2015-10-13T11:18:13 | 2015-10-13T11:18:13 | 43,139,534 | 5 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 11,003 |
scm
|
test-aes.scm
|
(import (scheme base)
(scheme cxr)
(aeolus cipher)
(aeolus cipher aes)
(aeolus modes ecb)
(aeolus modes cbc)
(aeolus modes ctr)
(aeolus modes parameters)
(aeolus-test)
(extra-aes-vectors))
(test-begin "AES")
(test-assert "cipher?"
(cipher?
(make-cipher AES #u8(1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6) mode-ecb)))
;; from
;; http://www.inconteam.com/software-development/41-encryption/55-aes-test-vectors
(define test-aes-vectors
'(
;; ken-len key plain cipher
#(16 #x2b7e151628aed2a6abf7158809cf4f3c #x6bc1bee22e409f96e93d7e117393172a #x3ad77bb40d7a3660a89ecaf32466ef97)
#(16 #x2b7e151628aed2a6abf7158809cf4f3c #xae2d8a571e03ac9c9eb76fac45af8e51 #xf5d3d58503b9699de785895a96fdbaaf)
#(16 #x2b7e151628aed2a6abf7158809cf4f3c #x30c81c46a35ce411e5fbc1191a0a52ef #x43b1cd7f598ece23881b00e3ed030688)
#(16 #x2b7e151628aed2a6abf7158809cf4f3c #xf69f2445df4f9b17ad2b417be66c3710 #x7b0c785e27e8ad3f8223207104725dd4)
#(24 #x8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b #x6bc1bee22e409f96e93d7e117393172a #xbd334f1d6e45f25ff712a214571fa5cc)
#(24 #x8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b #xae2d8a571e03ac9c9eb76fac45af8e51 #x974104846d0ad3ad7734ecb3ecee4eef)
#(24 #x8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b #x30c81c46a35ce411e5fbc1191a0a52ef #xef7afd2270e2e60adce0ba2face6444e)
#(24 #x8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b #xf69f2445df4f9b17ad2b417be66c3710 #x9a4b41ba738d6c72fb16691603c18e0e)
#(32 #x603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4 #x6bc1bee22e409f96e93d7e117393172a #xf3eed1bdb5d2a03c064b5a7e3db181f8)
#(32 #x603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4 #xae2d8a571e03ac9c9eb76fac45af8e51 #x591ccb10d410ed26dc5ba74a31362870)
#(32 #x603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4 #x30c81c46a35ce411e5fbc1191a0a52ef #xb6ed21b99ca6f4f9f153e7b1beafed1d)
#(32 #x603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4 #xf69f2445df4f9b17ad2b417be66c3710 #x23304b7a39f9f3ff067d8d8f9e24ecc7)
))
(define (test-aes-ecb vec)
(let ((key (integer->bytevector (vector-ref vec 1) (vector-ref vec 0)))
(pt (integer->bytevector (vector-ref vec 2) 16))
(ct (integer->bytevector (vector-ref vec 3) 16)))
(define cipher (make-cipher AES key mode-ecb))
(cipher-encrypt cipher pt)
(test-equal (string-append "encrypt: ("
(number->string (vector-ref vec 0))
") "
(number->string (vector-ref vec 2) 16)
" -> "
(number->string (vector-ref vec 3) 16))
ct
(cipher-encrypt cipher pt))
(cipher-decrypt cipher ct)
(test-equal (string-append "decrypt: ("
(number->string (vector-ref vec 0))
") "
(number->string (vector-ref vec 3) 16)
" -> "
(number->string (vector-ref vec 2) 16))
pt
(cipher-decrypt cipher ct))))
(for-each test-aes-ecb test-aes-vectors)
(for-each test-aes-ecb extra-aes-ecb-vectors)
(define test-aes-ctr-vectors
'(;; key-len key iv plain cipher1 ... plainn ciphern
(16
#x2b7e151628aed2a6abf7158809cf4f3c
#xf0f1f2f3f4f5f6f7f8f9fafbfcfdfeff
(#x6bc1bee22e409f96e93d7e117393172a #x874d6191b620e3261bef6864990db6ce)
(#xae2d8a571e03ac9c9eb76fac45af8e51 #x9806f66b7970fdff8617187bb9fffdff)
(#x30c81c46a35ce411e5fbc1191a0a52ef #x5ae4df3edbd5d35e5b4f09020db03eab)
(#xf69f2445df4f9b17ad2b417be66c3710 #x1e031dda2fbe03d1792170a0f3009cee))
(24
#x8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b
#xf0f1f2f3f4f5f6f7f8f9fafbfcfdfeff
(#x6bc1bee22e409f96e93d7e117393172a #x1abc932417521ca24f2b0459fe7e6e0b)
(#xae2d8a571e03ac9c9eb76fac45af8e51 #x090339ec0aa6faefd5ccc2c6f4ce8e94)
(#x30c81c46a35ce411e5fbc1191a0a52ef #x1e36b26bd1ebc670d1bd1d665620abf7)
(#xf69f2445df4f9b17ad2b417be66c3710 #x4f78a7f6d29809585a97daec58c6b050))
(32
#x603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4
#xf0f1f2f3f4f5f6f7f8f9fafbfcfdfeff
(#x6bc1bee22e409f96e93d7e117393172a #x601ec313775789a5b7a7f504bbf3d228)
(#xae2d8a571e03ac9c9eb76fac45af8e51 #xf443e3ca4d62b59aca84e990cacaf5c5)
(#x30c81c46a35ce411e5fbc1191a0a52ef #x2b0930daa23de94ce87017ba2d84988d)
(#xf69f2445df4f9b17ad2b417be66c3710 #xdfc9c58db67aada613c2dd08457941a6))
))
(define (test-aes-ctr lis)
(let ((key (integer->bytevector (cadr lis) (car lis)))
(iv (integer->bytevector (caddr lis) 16))
(v* (cdddr lis)))
(define enc-cipher
(make-cipher AES key mode-ctr (make-iv-paramater iv)))
(define dec-cipher
(make-cipher AES key mode-ctr (make-iv-paramater iv)))
(for-each (lambda (pt&ct)
(let ((pt (integer->bytevector (car pt&ct) 16))
(ct (integer->bytevector (cadr pt&ct) 16)))
(test-equal (string-append "CTR encrypt: ("
(number->string (car lis))
") "
(number->string (car pt&ct) 16)
" -> "
(number->string (cadr pt&ct) 16))
ct
(cipher-encrypt enc-cipher pt))
(test-equal (string-append "CTR decrypt: ("
(number->string (car lis))
") "
(number->string (car pt&ct) 16)
" -> "
(number->string (cadr pt&ct) 16))
pt
(cipher-decrypt dec-cipher ct))))
v*)))
(for-each test-aes-ctr test-aes-ctr-vectors)
(define (test-rfc3686 i vec)
(let ((key (vector-ref vec 0))
(iv (vector-ref vec 1))
(nonce (vector-ref vec 2))
(plain (vector-ref vec 3))
(cipher (vector-ref vec 4)))
(define enc-c (make-cipher AES key mode-ctr
(make-composite-parameter
(make-rfc3686-parameter iv nonce))))
(define dec-c (make-cipher AES key mode-ctr
(make-composite-parameter
(make-rfc3686-parameter iv nonce))))
(test-equal (string-append "AES-CTR encrypt (" (number->string i) ")")
cipher (cipher-encrypt enc-c plain))
(test-equal (string-append "AES-CTR decrypt (" (number->string i) ")")
plain (cipher-encrypt dec-c cipher))))
(define test-rfc3686-vector
'(;; key iv nonce plain cipher
#(#u8(#xAE #x68 #x52 #xF8 #x12 #x10 #x67 #xCC #x4B #xF7 #xA5 #x76 #x55 #x77 #xF3 #x9E)
#u8(#x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00)
#u8(#x00 #x00 #x00 #x30)
#u8(#x53 #x69 #x6E #x67 #x6C #x65 #x20 #x62 #x6C #x6F #x63 #x6B #x20 #x6D #x73 #x67)
#u8(#xE4 #x09 #x5D #x4F #xB7 #xA7 #xB3 #x79 #x2D #x61 #x75 #xA3 #x26 #x13 #x11 #xB8))
#(#u8(#x7E #x24 #x06 #x78 #x17 #xFA #xE0 #xD7 #x43 #xD6 #xCE #x1F #x32 #x53 #x91 #x63)
#u8(#xC0 #x54 #x3B #x59 #xDA #x48 #xD9 #x0B)
#u8(#x00 #x6C #xB6 #xDB)
#u8(#x00 #x01 #x02 #x03 #x04 #x05 #x06 #x07 #x08 #x09 #x0A #x0B #x0C #x0D #x0E #x0F
#x10 #x11 #x12 #x13 #x14 #x15 #x16 #x17 #x18 #x19 #x1A #x1B #x1C #x1D #x1E #x1F)
#u8(#x51 #x04 #xA1 #x06 #x16 #x8A #x72 #xD9 #x79 #x0D #x41 #xEE #x8E #xDA #xD3 #x88
#xEB #x2E #x1E #xFC #x46 #xDA #x57 #xC8 #xFC #xE6 #x30 #xDF #x91 #x41 #xBE #x28))
#(#u8(#x76 #x91 #xBE #x03 #x5E #x50 #x20 #xA8 #xAC #x6E #x61 #x85 #x29 #xF9 #xA0 #xDC)
#u8(#x27 #x77 #x7F #x3F #x4A #x17 #x86 #xF0)
#u8(#x00 #xE0 #x01 #x7B)
#u8(#x00 #x01 #x02 #x03 #x04 #x05 #x06 #x07 #x08 #x09 #x0A #x0B #x0C #x0D #x0E #x0F
#x10 #x11 #x12 #x13 #x14 #x15 #x16 #x17 #x18 #x19 #x1A #x1B #x1C #x1D #x1E #x1F
#x20 #x21 #x22 #x23)
#u8(#xC1 #xCF #x48 #xA8 #x9F #x2F #xFD #xD9 #xCF #x46 #x52 #xE9 #xEF #xDB #x72 #xD7
#x45 #x40 #xA4 #x2B #xDE #x6D #x78 #x36 #xD5 #x9A #x5C #xEA #xAE #xF3 #x10 #x53
#x25 #xB2 #x07 #x2F))
#(#u8(#x16 #xAF #x5B #x14 #x5F #xC9 #xF5 #x79 #xC1 #x75 #xF9 #x3E #x3B #xFB #x0E #xED
#x86 #x3D #x06 #xCC #xFD #xB7 #x85 #x15)
#u8(#x36 #x73 #x3C #x14 #x7D #x6D #x93 #xCB)
#u8(#x00 #x00 #x00 #x48)
#u8(#x53 #x69 #x6E #x67 #x6C #x65 #x20 #x62 #x6C #x6F #x63 #x6B #x20 #x6D #x73 #x67)
#u8(#x4B #x55 #x38 #x4F #xE2 #x59 #xC9 #xC8 #x4E #x79 #x35 #xA0 #x03 #xCB #xE9 #x28))
#(#u8(#x7C #x5C #xB2 #x40 #x1B #x3D #xC3 #x3C #x19 #xE7 #x34 #x08 #x19 #xE0 #xF6 #x9C
#x67 #x8C #x3D #xB8 #xE6 #xF6 #xA9 #x1A)
#u8(#x02 #x0C #x6E #xAD #xC2 #xCB #x50 #x0D)
#u8(#x00 #x96 #xB0 #x3B)
#u8(#x00 #x01 #x02 #x03 #x04 #x05 #x06 #x07 #x08 #x09 #x0A #x0B #x0C #x0D #x0E #x0F
#x10 #x11 #x12 #x13 #x14 #x15 #x16 #x17 #x18 #x19 #x1A #x1B #x1C #x1D #x1E #x1F)
#u8(#x45 #x32 #x43 #xFC #x60 #x9B #x23 #x32 #x7E #xDF #xAA #xFA #x71 #x31 #xCD #x9F
#x84 #x90 #x70 #x1C #x5A #xD4 #xA7 #x9C #xFC #x1F #xE0 #xFF #x42 #xF4 #xFB #x00))
#(#u8(#x02 #xBF #x39 #x1E #xE8 #xEC #xB1 #x59 #xB9 #x59 #x61 #x7B #x09 #x65 #x27 #x9B
#xF5 #x9B #x60 #xA7 #x86 #xD3 #xE0 #xFE)
#u8(#x5C #xBD #x60 #x27 #x8D #xCC #x09 #x12)
#u8(#x00 #x07 #xBD #xFD)
#u8(#x00 #x01 #x02 #x03 #x04 #x05 #x06 #x07 #x08 #x09 #x0A #x0B #x0C #x0D #x0E #x0F
#x10 #x11 #x12 #x13 #x14 #x15 #x16 #x17 #x18 #x19 #x1A #x1B #x1C #x1D #x1E #x1F
#x20 #x21 #x22 #x23)
#u8(#x96 #x89 #x3F #xC5 #x5E #x5C #x72 #x2F #x54 #x0B #x7D #xD1 #xDD #xF7 #xE7 #x58
#xD2 #x88 #xBC #x95 #xC6 #x91 #x65 #x88 #x45 #x36 #xC8 #x11 #x66 #x2F #x21 #x88
#xAB #xEE #x09 #x35))
#(#u8(#x77 #x6B #xEF #xF2 #x85 #x1D #xB0 #x6F #x4C #x8A #x05 #x42 #xC8 #x69 #x6F #x6C
#x6A #x81 #xAF #x1E #xEC #x96 #xB4 #xD3 #x7F #xC1 #xD6 #x89 #xE6 #xC1 #xC1 #x04)
#u8(#xDB #x56 #x72 #xC9 #x7A #xA8 #xF0 #xB2)
#u8(#x00 #x00 #x00 #x60)
#u8(#x53 #x69 #x6E #x67 #x6C #x65 #x20 #x62 #x6C #x6F #x63 #x6B #x20 #x6D #x73 #x67)
#u8(#x14 #x5A #xD0 #x1D #xBF #x82 #x4E #xC7 #x56 #x08 #x63 #xDC #x71 #xE3 #xE0 #xC0))
#(#u8(#xF6 #xD6 #x6D #x6B #xD5 #x2D #x59 #xBB #x07 #x96 #x36 #x58 #x79 #xEF #xF8 #x86
#xC6 #x6D #xD5 #x1A #x5B #x6A #x99 #x74 #x4B #x50 #x59 #x0C #x87 #xA2 #x38 #x84)
#u8(#xC1 #x58 #x5E #xF1 #x5A #x43 #xD8 #x75)
#u8(#x00 #xFA #xAC #x24)
#u8(#x00 #x01 #x02 #x03 #x04 #x05 #x06 #x07 #x08 #x09 #x0A #x0B #x0C #x0D #x0E #x0F
#x10 #x11 #x12 #x13 #x14 #x15 #x16 #x17 #x18 #x19 #x1A #x1B #x1C #x1D #x1E #x1F)
#u8(#xF0 #x5E #x23 #x1B #x38 #x94 #x61 #x2C #x49 #xEE #x00 #x0B #x80 #x4E #xB2 #xA9
#xB8 #x30 #x6B #x50 #x8F #x83 #x9D #x6A #x55 #x30 #x83 #x1D #x93 #x44 #xAF #x1C))
#(#u8(#xFF #x7A #x61 #x7C #xE6 #x91 #x48 #xE4 #xF1 #x72 #x6E #x2F #x43 #x58 #x1D #xE2
#xAA #x62 #xD9 #xF8 #x05 #x53 #x2E #xDF #xF1 #xEE #xD6 #x87 #xFB #x54 #x15 #x3D)
#u8(#x51 #xA5 #x1D #x70 #xA1 #xC1 #x11 #x48)
#u8(#x00 #x1C #xC5 #xB7)
#u8(#x00 #x01 #x02 #x03 #x04 #x05 #x06 #x07 #x08 #x09 #x0A #x0B #x0C #x0D #x0E #x0F
#x10 #x11 #x12 #x13 #x14 #x15 #x16 #x17 #x18 #x19 #x1A #x1B #x1C #x1D #x1E #x1F
#x20 #x21 #x22 #x23)
#u8(#xEB #x6C #x52 #x82 #x1D #x0B #xBB #xF7 #xCE #x75 #x94 #x46 #x2A #xCA #x4F #xAA
#xB4 #x07 #xDF #x86 #x65 #x69 #xFD #x07 #xF4 #x8C #xC0 #xB5 #x83 #xD6 #x07 #x1F
#x1E #xC0 #xE6 #xB8))
))
(let loop ((i 1) (v test-rfc3686-vector))
(unless (null? v)
(test-rfc3686 i (car v))
(loop (+ i 1) (cdr v))))
(test-end)
| false |
ed3ec0761f157abedbda4ada818bce3587b20ae8
|
958488bc7f3c2044206e0358e56d7690b6ae696c
|
/scheme/guile/hash-custom.scm
|
9edbd20bda7f611badf4e215b7d256ab99003709
|
[] |
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 | 411 |
scm
|
hash-custom.scm
|
(use-modules (srfi srfi-1) (srfi srfi-13))
(define (my-hash str size)
(remainder (string-hash-ci str) size))
(define (my-assoc str alist)
(find (lambda (pair) (string-ci=? str (car pair))) alist))
(define my-table (make-hash-table)) ; suitable for any hash , hashq, hashv and custom hash
(hashx-set! my-hash my-assoc my-table "foo" 123)
(display (hashx-ref my-hash my-assoc my-table "FOO"))(newline)
| false |
38edfff42baa253971a69a24e606ce5ca5e07f6a
|
309e1d67d6ad76d213811bf1c99b5f82fa2f4ee2
|
/A08b.ss
|
cf7e66997b607f3865ad1c9b6fc852a184fd49e2
|
[] |
no_license
|
lix4/CSSE304-Programming-Language-Concept-Code
|
d8c14c18a1baa61ab5d3df0b1ac650bdebc59526
|
dd94262865d880a357e85f6def697661e11c8e7a
|
refs/heads/master
| 2020-08-06T02:50:53.307301 | 2016-11-12T03:03:56 | 2016-11-12T03:03:56 | 73,528,000 | 1 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,130 |
ss
|
A08b.ss
|
(define group-by-n
(lambda (ls n)
(group-by-n-rec ls n 0 '() '())))
(define group-by-n-rec
(lambda (ls n index current current-element)
(cond [(null? ls) '()]
[(null? (cdr ls)) (append current (list (append current-element (list (car ls)))))]
[(= index (- n 1))
(if (null? current)
(group-by-n-rec (cdr ls) n 0 (list (append current-element (list (car ls)))) '())
(group-by-n-rec (cdr ls) n 0 (append current (list (append current-element (list (car ls))))) '()))]
[else (group-by-n-rec (cdr ls) n (+ index 1) current (append current-element (list (car ls))))])))
(define symmetric?
(lambda (rel)
(cond [(null? rel) #t]
[(equal? (caar rel)
(cadar rel))
(symmetric? (cdr rel))]
[else (member? (list (cadar rel) (caar rel)) rel)])))
(define member?
(lambda (target ls)
(cond [(null? ls) #f]
[(equal? (car ls) target) #t]
[else (member? target (cdr ls))])))
(define subst-leftmost
(lambda (new old slist equality-pred?)
(car (subst-leftmost-rec new old slist equality-pred? #f '() '()))))
(trace-define subst-leftmost-rec
(lambda (new old slist equality-pred? switched? current)
(cond [(null? slist) (list current switched?)]
[(symbol? (car slist))
(if (and (equality-pred? (car slist) old)
(not switched?))
(append current (list new) (cdr slist))
; (subst-leftmost-rec new old (cdr slist) equality-pred? #t (append current (list new)))
(subst-leftmost-rec new old (cdr slist) equality-pred? switched? (append current (list (car slist))) (cddr slist)))]
[else
(let ([rec (subst-leftmost-rec new old (car slist) equality-pred? switched? '() )])
(if switched?
(subst-leftmost-rec new old (cdr slist) equality-pred? switched? (append current (list (car slist))))
(subst-leftmost-rec new old (cdr slist)
equality-pred?
(cadr rec)
(append current
(list (car rec))))))])))
| false |
866f717cd5e3203174c3bc4c1de88e4c3e99f763
|
222b42ba803bfecd4ec31166dd2be107a840f2bd
|
/undone/unsorted/stringutil.scm
|
c5d98d3438f6f2c18ac189218f8a5614eae37008
|
[] |
no_license
|
ab3250/ablib
|
83512c2c2cadd0eb49ad534548c058e3ed119d4c
|
887c8661ce99e8edfe89bcf707400e55c3943dd4
|
refs/heads/master
| 2023-06-12T13:36:49.487467 | 2021-07-11T13:29:45 | 2021-07-11T13:29:45 | 384,955,137 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 5,861 |
scm
|
stringutil.scm
|
;;;
;;; auxiliary string utilities. to be autoloaded.
;;;
;;; Copyright (c) 2000-2019 Shiro Kawai <[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.
;;;
;;; 3. Neither the name of the authors nor the names of its contributors
;;; may be used to endorse or promote products derived from this
;;; software without specific prior written permission.
;;;
;;; 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.
;;;
(define-module gauche.stringutil
(export string-split)
)
(select-module gauche.stringutil)
;; trick to delay loading of srfi-13 until needed
(autoload srfi-13 string-tokenize)
(define %string-split-by-char
(with-module gauche.internal %string-split-by-char))
;; Generic string-split
;; splitter can be a character, a char-set, a string, or a regexp.
;; NB: To adapt to srfi-152, we changed the optional argument - now the
;; 'grammar' argument comes before 'limit'. For the bacward compatibility,
;; we recognize an integer argument in 'grammar' as 'limit'.
(define (string-split string splitter :optional (grammar 'infix) (limit #f) start end)
(if (or (not grammar) (integer? grammar))
(%string-split string splitter 'infix grammar limit start)
(%string-split string splitter grammar limit start end)))
(define (%string-split string splitter grammar limit start end)
(unless (memq grammar '(infix strict-infix prefix suffix))
(error "grammar argument must be one of (infix strict-infix prefix suffix), but got" grammar))
(unless (or (not limit) (and (integer? limit) (>= limit 0)))
(error "limit argument must be a nonnegative integer or #f, but got" limit))
(let1 s ((with-module gauche.internal %maybe-substring) string start end)
(if (equal? s "")
(if (eq? grammar 'strict-infix)
(error "string must not be empty with strict-infix grammar")
'())
(let1 r (if (char? splitter)
(%string-split-by-char s splitter (or limit -1))
(%string-split-by-scanner s (%string-split-scanner splitter)
(or limit -1)))
(case grammar
[(prefix) (if (and (pair? r) (equal? (car r) ""))
(cdr r)
r)]
[(suffix) (if (and (pair? r) (equal? (car (last-pair r)) ""))
(drop-right r 1)
r)]
[else r])))))
;; aux fns
(define (%string-split-scanner splitter)
(cond [(string? splitter)
(if (string=? splitter "")
(^s (if (<= (string-length s) 1)
(values s #f)
(values (string-copy s 0 1) (string-copy s 1))))
(^s (receive (before after) (string-scan s splitter 'both)
(if before (values before after) (values s #f)))))]
[(char-set? splitter)
(%string-split-scanner-each-char
(cut char-set-contains? splitter <>))]
[(regexp? splitter)
(^s (cond [(rxmatch splitter s)
=> (^m (let ([before (m 'before)]
[after (m 'after)])
(if (string=? s after)
(if (<= (string-length s) 1)
(values s #f)
(values (string-copy s 0 1)
(string-copy s 1)))
(values before after))))]
[else (values s #f)]))]
[else ;; assume splitter is a predicate
(%string-split-scanner-each-char splitter)]))
(define (%string-split-scanner-each-char pred)
(define (scan-in p)
(let1 c (string-pointer-ref p)
(cond [(eof-object? c) (values (string-pointer-substring p) #f)]
[(pred c) (let1 before (string-pointer-substring p)
(string-pointer-next! p)
(scan-out p before))]
[else (string-pointer-next! p) (scan-in p)])))
(define (scan-out p before)
(let1 c (string-pointer-ref p)
(cond [(eof-object? c) (values before "")]
[(pred c) (string-pointer-next! p) (scan-out p before)]
[else (values before (string-pointer-substring p :after #t))])))
(^s (scan-in (make-string-pointer s))))
(define (%string-split-by-scanner string scanner limit)
(let loop ([s string]
[r '()]
[limit limit])
(if (zero? limit)
(reverse! (cons s r))
(receive (before after) (scanner s)
(if after
(loop after (cons before r) (- limit 1))
(reverse! (cons before r)))))))
| false |
638f17fa6a6b5b779ee6dfa3fa00b26d762ee23b
|
5fa722a5991bfeacffb1d13458efe15082c1ee78
|
/src/c3_43.scm
|
0192a7604398805ebdcf9f4fdca7b44bdca2e860
|
[] |
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 | 69 |
scm
|
c3_43.scm
|
; My answer is on http://sicp.readthedocs.org/en/latest/chp3/43.html
| false |
15f3b05e4a0947773f2038e7ff64a2048f86ed86
|
f848bf700fa92fd97e10b65159f79a7b46565824
|
/test/util.scm
|
fb952234ba3081dcf1a8b5e59030741ab2d89cc7
|
[
"MIT"
] |
permissive
|
her01n/hdt
|
75e1158dda6e6f846b50ac0f72f5f9dd40d0eecb
|
8d65000180ddddde94485e4a50c1c2e36a539e5f
|
refs/heads/master
| 2023-02-13T05:40:38.668744 | 2023-01-27T15:21:27 | 2023-01-27T15:21:27 | 132,890,317 | 2 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 343 |
scm
|
util.scm
|
(define-module (test util)
#:export-syntax (execute-tests-with-output-to-string))
(use-modules (hdt hdt))
(define-syntax execute-tests-with-output-to-string
(syntax-rules ()
((execute-tests-with-output-to-string tests ...)
(with-output-to-string
(lambda ()
(execute-tests
(lambda () tests ...)))))))
| true |
9d597632c24161eca4a029727f2070fca14707ff
|
4478a6db6f759add823da6436842ff0b1bf82aa8
|
/final/lds/dof.ss
|
1ce46deaeac4f88136fbfe95763195006b7a4d3e
|
[] |
no_license
|
gaborpapp/LDS-fluxus
|
2c06508f9191d52f784c2743c4a92e8cadf116ea
|
44d90d9f1e3217b3879c496b2ddd4d34237935d1
|
refs/heads/master
| 2016-09-05T13:29:09.695559 | 2013-04-05T05:33:10 | 2013-04-05T05:33:10 | 7,058,302 | 1 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 6,258 |
ss
|
dof.ss
|
#lang racket
(require fluxus-018/fluxus)
(provide dof)
(define dof-vert "
void main()
{
gl_FrontColor = gl_Color;
gl_Position = ftransform();
gl_TexCoord[ 0 ] = gl_MultiTexCoord0;
}")
; based on http://artmartinsh.blogspot.com/2010/02/glsl-lens-blur-filter-with-bokeh.html by Martins Upitis
(define dof-frag "
uniform sampler2D tColor;
uniform sampler2D tDepth;
uniform float maxblur; // max blur amount
uniform float aperture; // aperture - bigger values for shallower depth of field
uniform float focus;
uniform vec2 size;
uniform float bloomStrength;
float zfar = 100.;
float znear = 1.;
float linearizeDepth( float z )
{
return ( 2.0 * znear ) / ( zfar + znear - z * ( zfar - znear ) );
}
void main()
{
vec2 uv = gl_TexCoord[ 0 ].st;
vec2 aspectcorrect = vec2( 1.0, size.x / size.y );
vec4 depth1 = texture2D( tDepth, uv );
float factor = linearizeDepth( depth1.x ) - focus;
vec2 dofblur = vec2 ( clamp( factor * aperture, -maxblur, maxblur ) );
vec2 dofblur9 = dofblur * 0.9;
vec2 dofblur7 = dofblur * 0.7;
vec2 dofblur4 = dofblur * 0.4;
vec4 col = vec4( 0.0 );
col += texture2D( tColor, uv );
col += texture2D( tColor, uv + ( vec2( 0.0, 0.4 ) * aspectcorrect ) * dofblur );
col += texture2D( tColor, uv + ( vec2( 0.15, 0.37 ) * aspectcorrect ) * dofblur );
col += texture2D( tColor, uv + ( vec2( 0.29, 0.29 ) * aspectcorrect ) * dofblur );
col += texture2D( tColor, uv + ( vec2( -0.37, 0.15 ) * aspectcorrect ) * dofblur );
col += texture2D( tColor, uv + ( vec2( 0.40, 0.0 ) * aspectcorrect ) * dofblur );
col += texture2D( tColor, uv + ( vec2( 0.37, -0.15 ) * aspectcorrect ) * dofblur );
col += texture2D( tColor, uv + ( vec2( 0.29, -0.29 ) * aspectcorrect ) * dofblur );
col += texture2D( tColor, uv + ( vec2( -0.15, -0.37 ) * aspectcorrect ) * dofblur );
col += texture2D( tColor, uv + ( vec2( 0.0, -0.4 ) * aspectcorrect ) * dofblur );
col += texture2D( tColor, uv + ( vec2( -0.15, 0.37 ) * aspectcorrect ) * dofblur );
col += texture2D( tColor, uv + ( vec2( -0.29, 0.29 ) * aspectcorrect ) * dofblur );
col += texture2D( tColor, uv + ( vec2( 0.37, 0.15 ) * aspectcorrect ) * dofblur );
col += texture2D( tColor, uv + ( vec2( -0.4, 0.0 ) * aspectcorrect ) * dofblur );
col += texture2D( tColor, uv + ( vec2( -0.37, -0.15 ) * aspectcorrect ) * dofblur );
col += texture2D( tColor, uv + ( vec2( -0.29, -0.29 ) * aspectcorrect ) * dofblur );
col += texture2D( tColor, uv + ( vec2( 0.15, -0.37 ) * aspectcorrect ) * dofblur );
col += texture2D( tColor, uv + ( vec2( 0.15, 0.37 ) * aspectcorrect ) * dofblur9 );
col += texture2D( tColor, uv + ( vec2( -0.37, 0.15 ) * aspectcorrect ) * dofblur9 );
col += texture2D( tColor, uv + ( vec2( 0.37, -0.15 ) * aspectcorrect ) * dofblur9 );
col += texture2D( tColor, uv + ( vec2( -0.15, -0.37 ) * aspectcorrect ) * dofblur9 );
col += texture2D( tColor, uv + ( vec2( -0.15, 0.37 ) * aspectcorrect ) * dofblur9 );
col += texture2D( tColor, uv + ( vec2( 0.37, 0.15 ) * aspectcorrect ) * dofblur9 );
col += texture2D( tColor, uv + ( vec2( -0.37, -0.15 ) * aspectcorrect ) * dofblur9 );
col += texture2D( tColor, uv + ( vec2( 0.15, -0.37 ) * aspectcorrect ) * dofblur9 );
col += texture2D( tColor, uv + ( vec2( 0.29, 0.29 ) * aspectcorrect ) * dofblur7 );
col += texture2D( tColor, uv + ( vec2( 0.40, 0.0 ) * aspectcorrect ) * dofblur7 );
col += texture2D( tColor, uv + ( vec2( 0.29, -0.29 ) * aspectcorrect ) * dofblur7 );
col += texture2D( tColor, uv + ( vec2( 0.0, -0.4 ) * aspectcorrect ) * dofblur7 );
col += texture2D( tColor, uv + ( vec2( -0.29, 0.29 ) * aspectcorrect ) * dofblur7 );
col += texture2D( tColor, uv + ( vec2( -0.4, 0.0 ) * aspectcorrect ) * dofblur7 );
col += texture2D( tColor, uv + ( vec2( -0.29, -0.29 ) * aspectcorrect ) * dofblur7 );
col += texture2D( tColor, uv + ( vec2( 0.0, 0.4 ) * aspectcorrect ) * dofblur7 );
col += texture2D( tColor, uv + ( vec2( 0.29, 0.29 ) * aspectcorrect ) * dofblur4 );
col += texture2D( tColor, uv + ( vec2( 0.4, 0.0 ) * aspectcorrect ) * dofblur4 );
col += texture2D( tColor, uv + ( vec2( 0.29, -0.29 ) * aspectcorrect ) * dofblur4 );
col += texture2D( tColor, uv + ( vec2( 0.0, -0.4 ) * aspectcorrect ) * dofblur4 );
col += texture2D( tColor, uv + ( vec2( -0.29, 0.29 ) * aspectcorrect ) * dofblur4 );
col += texture2D( tColor, uv + ( vec2( -0.4, 0.0 ) * aspectcorrect ) * dofblur4 );
col += texture2D( tColor, uv + ( vec2( -0.29, -0.29 ) * aspectcorrect ) * dofblur4 );
col += texture2D( tColor, uv + ( vec2( 0.0, 0.4 ) * aspectcorrect ) * dofblur4 );
col /= 41.0;
// bloom
vec4 sum = vec4( 0 );
for ( int i = -4; i < 4; i++ )
{
for ( int j = -3; j < 3; j++ )
{
sum += texture2D( tColor, uv + vec2( j, i ) * 0.004 ) * bloomStrength;
}
}
if ( col.r < 0.3 )
{
gl_FragColor = sum * sum * 0.012 + col;
}
else
if ( col.r < 0.5 )
{
gl_FragColor = sum * sum * 0.009 + col;
}
else
{
gl_FragColor = sum * sum * 0.0075 + col;
}
gl_FragColor.a = 1.0;
}")
(define (dof pprim #:aperture aperture #:focus focus #:maxblur maxblur #:bloom bloom)
(texture-params 0 '(min linear mag linear))
(texture-params 1 '(min linear mag linear))
(multitexture 0 (pixels->texture pprim))
(multitexture 1 (pixels->depth pprim))
(shader-source dof-vert dof-frag)
(shader-set! #:tColor 0 #:tDepth 1
#:size (with-primitive pprim (vector (pixels-width) (pixels-height)))
#:maxblur maxblur #:aperture aperture #:focus focus
#:bloomStrength bloom))
| false |
7a32276c8e4cbcb6a206990f3deee8a6f0ea08bf
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/System.Xml/system/xml/xpath/expr-union.sls
|
c602152a9efd9eb9b2c0e63f713eca7f11613bc2
|
[] |
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 | 728 |
sls
|
expr-union.sls
|
(library (system xml xpath expr-union)
(export new is? expr-union? optimize evaluate to-string)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...) #'(clr-new System.Xml.XPath.ExprUNION a ...)))))
(define (is? a) (clr-is System.Xml.XPath.ExprUNION a))
(define (expr-union? a) (clr-is System.Xml.XPath.ExprUNION a))
(define-method-port
optimize
System.Xml.XPath.ExprUNION
Optimize
(System.Xml.XPath.Expression))
(define-method-port
evaluate
System.Xml.XPath.ExprUNION
Evaluate
(System.Object System.Xml.XPath.BaseIterator))
(define-method-port
to-string
System.Xml.XPath.ExprUNION
ToString
(System.String)))
| true |
8dde50bdd441898231ed8b010a5f03020a4bd23e
|
ab2b756cdeb5aa94b8586eeb8dd5948b7f0bba27
|
/old/lisp/car.scm
|
fb37f8a20d3342618b118a9dc9a3ed5e25927d20
|
[] |
no_license
|
stjordanis/chalang
|
48ff69d8bc31da1696eae043e66c628f41035b5a
|
a728e6bb9a60ac6eca189ee7d6873a891825fa9a
|
refs/heads/master
| 2021-07-31T22:26:45.299432 | 2021-03-09T13:06:56 | 2021-03-09T13:06:56 | 142,876,387 | 0 | 0 | null | 2018-07-30T13:03:00 | 2018-07-30T13:03:00 | null |
UTF-8
|
Scheme
| false | false | 61 |
scm
|
car.scm
|
(= (cons (car (list 4 5))
(cdr (list 4 5)))
(list 4 5))
| false |
42d1b1acc2c897c8edc6d2e01b234f1f79f4f8c8
|
abc7bd420c9cc4dba4512b382baad54ba4d07aa8
|
/src/ws/langs/lang20_deglobalize.ss
|
c0a2e6d8715c8f59271567d4105e1c1fb7b6ce07
|
[
"BSD-3-Clause"
] |
permissive
|
rrnewton/WaveScript
|
2f008f76bf63707761b9f7c95a68bd3e6b9c32ca
|
1c9eff60970aefd2177d53723383b533ce370a6e
|
refs/heads/master
| 2021-01-19T05:53:23.252626 | 2014-10-08T15:00:41 | 2014-10-08T15:00:41 | 1,297,872 | 10 | 2 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 317 |
ss
|
lang20_deglobalize.ss
|
;; [2004.06.09]
;; This is the "language definition" for the output of deglobalize.
;; REQUIRES: on simulator_nought.ss and maybe simulator_nought_grpahics.ss
(define (deglobalize-lang prog)
; (run-simulation
; (build-simulation
; (compile-simulate-nought prog))
(compile-simulate-alpha prog))
; 2.0))
| false |
ede06148653d131ee0bcc85c4a2916bbcef30e8f
|
0ffe5235b0cdac3846e15237c2232d8b44995421
|
/src/scheme/Section_1.3/1.38.scm
|
b4e0e7657d9827aa571eb2e22e64e1631ae188cb
|
[] |
no_license
|
dawiedotcom/SICP
|
4d05014ac2b075b7de5906ff9a846e42298fa425
|
fa6ccac0dad8bdad0645aa01197098c296c470e0
|
refs/heads/master
| 2020-06-05T12:36:41.098263 | 2013-05-16T19:41:38 | 2013-05-16T19:41:38 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 508 |
scm
|
1.38.scm
|
; SICP Exercise 1.38
; Dawie de Klerk
; 2012-08-12
(load "../utils.scm")
(load "1.37.scm")
(define (d i)
;; Calculate the denomitator terms needed for
;; calculating the Euler's number by continued
;; fraction
(let ((i+1 (inc i)))
(if (zero? (remainder i+1 3))
(* (/ i+1 3) 2)
1)))
(define e
(+ 2 (cont-frac (lambda (i) 1.0)
d
100)))
(println "Euler's number calculated by continued fraction with 100 terms" e)
| false |
76dc550eaacae4e77248a19da1cfb53e2274df7a
|
26d55c57aff7d872227c276ba869535af537a81c
|
/api/scm/iup-web.scm
|
7aa6d2f1fc129b783b434d1ee53068b24d403ce4
|
[
"BSD-3-Clause"
] |
permissive
|
caelia/iup.jl
|
56f266d133d884d52061dd9874590c118e72c776
|
b401da82f534abd8786139578e0dee084eff1231
|
refs/heads/master
| 2021-01-19T05:42:55.097872 | 2016-06-04T21:13:05 | 2016-06-04T21:13:05 | 60,310,558 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 373 |
scm
|
iup-web.scm
|
;; -*- mode: Scheme; tab-width: 2; -*- ;;
;; {{{ Data types
(foreign-declare
"#include <iup.h>\n"
"#include <iupweb.h>\n")
(include "iup-types.scm")
;; }}}
;; {{{ Web browser control
(define web-browser
(make-constructor-procedure
(foreign-lambda nonnull-ihandle "IupWebBrowser")))
;; }}}
;; {{{ Library setup
(foreign-code "IupWebBrowserOpen();")
;; }}}
| false |
d7d9cc2e043a2a092a88e0853fad46a862402990
|
7666204be35fcbc664e29fd0742a18841a7b601d
|
/code/accumulate.scm
|
d94d5ab8e8c8f95c356d4d8e93da8be17ab7011e
|
[] |
no_license
|
cosail/sicp
|
b8a78932e40bd1a54415e50312e911d558f893eb
|
3ff79fd94eda81c315a1cee0165cec3c4dbcc43c
|
refs/heads/master
| 2021-01-18T04:47:30.692237 | 2014-01-06T13:32:54 | 2014-01-06T13:32:54 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 847 |
scm
|
accumulate.scm
|
#lang racket
(provide
accumulate
enumerate-tree
)
(define (accumulate op init lst)
(if (null? lst)
init
(accumulate op (op init (car lst)) (cdr lst))))
;(accumulate + 0 '(1 2 3 4 5))
(define (enumerate-tree tree)
(cond
((null? tree) '())
((not (pair? tree)) (list tree))
(else
(append (enumerate-tree (car tree))
(enumerate-tree (cdr tree))))))
(require "felix.scm")
(accumulate + 0
(map square
(filter odd?
(enumerate-tree '(1 (2 3) (4 5 (6 7 8) 9 (10 11)) 12)))))
(define (range start stop)
(define (iter answer i)
(if (= i stop)
answer
(iter (append answer (list i)) (inc i))))
(iter '() start))
(require "fast-fibo.scm")
(filter even?
(map fast-fibo
(range 0 20)))
| false |
c84483b3e9ece63092c3bbde2a461e135bfef03e
|
b62560d3387ed544da2bbe9b011ec5cd6403d440
|
/crates/steel-core/src/tests/success/closure_value_capture.scm
|
f410b3e77f0e6b6233c65dabaac6463090bc1b5c
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Apache-2.0"
] |
permissive
|
mattwparas/steel
|
c6fb91b20c4e613e6a8db9d9310d1e1c72313df2
|
700144a5a1aeb33cbdb2f66440bbe38cf4152458
|
refs/heads/master
| 2023-09-04T03:41:35.352916 | 2023-09-01T03:26:01 | 2023-09-01T03:26:01 | 241,949,362 | 207 | 10 |
Apache-2.0
| 2023-09-06T04:31:21 | 2020-02-20T17:39:28 |
Rust
|
UTF-8
|
Scheme
| false | false | 403 |
scm
|
closure_value_capture.scm
|
(define (build-list-of-functions n i list)
(if (< i n)
(build-list-of-functions n (+ i 1) (cons (lambda () (* (- n i) (- n i))) list))
list))
(define list-of-functions (build-list-of-functions 10 1 '()))
(assert! (equal?
(map (lambda (f) (f)) list-of-functions)
'(1 4 9 16 25 36 49 64 81)))
(assert! (equal? ((list-ref list-of-functions 8))
81))
| false |
50a4b3b65e1b8cdc5cc96a0e731d40606bcad7d2
|
26aaec3506b19559a353c3d316eb68f32f29458e
|
/modules/ln_glgui/glgui_keypad_return.scm
|
54ed9b863bc5f7c42d58d24370c15878ce214d34
|
[
"BSD-3-Clause"
] |
permissive
|
mdtsandman/lambdanative
|
f5dc42372bc8a37e4229556b55c9b605287270cd
|
584739cb50e7f1c944cb5253966c6d02cd718736
|
refs/heads/master
| 2022-12-18T06:24:29.877728 | 2020-09-20T18:47:22 | 2020-09-20T18:47:22 | 295,607,831 | 1 | 0 |
NOASSERTION
| 2020-09-15T03:48:04 | 2020-09-15T03:48:03 | null |
UTF-8
|
Scheme
| false | false | 4,154 |
scm
|
glgui_keypad_return.scm
|
#|
LambdaNative - a cross-platform Scheme framework
Copyright (c) 2009-2013, University of British Columbia
All rights reserved.
Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* 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.
* Neither the name of the University of British Columbia nor
the names of its contributors may be used to endorse or
promote products derived from this software without specific
prior written permission.
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 HOLDER 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.
|#
(define glgui_keypad_return.raw (glCoreTextureCreate 32 32 '#u8(
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
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
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
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
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
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
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
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
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
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
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
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
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
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
0 0 0 0 0 0 0 0 0 76 249 255 253 255 255 0 0
0 0 0 0 0 0 0 255 246 255 215 0 0 0 0
0 0 0 0 0 0 0 0 98 249 243 254 254 196 0 0 0
0 0 0 0 0 0 0 250 254 255 187 0 0 0 0
0 0 0 0 0 0 0 76 235 255 250 255 250 0 0 0 0
0 0 0 0 0 0 0 255 255 255 201 0 0 0 0
0 0 0 0 0 0 102 251 250 255 255 165 0 0 0 0 0
0 0 0 0 0 0 0 244 245 255 188 0 0 0 0
0 0 0 0 0 163 254 255 251 246 182 0 0 0 0 0 0
0 0 0 0 0 0 0 255 255 245 205 0 0 0 0
0 0 0 0 149 255 245 255 253 255 79 93 89 94 85 92 98
89 90 94 84 95 83 109 253 255 255 196 0 0 0 0
0 0 0 139 255 250 255 245 255 250 255 248 251 248 255 255 248
255 255 251 255 255 249 251 255 251 248 204 0 0 0 0
0 0 95 253 246 249 255 255 246 249 255 243 255 251 251 251 255
255 240 255 250 246 255 255 246 250 255 192 0 0 0 0
0 0 0 93 255 255 255 238 250 255 240 255 235 255 255 255 250
255 255 251 255 248 255 249 255 254 253 141 0 0 0 0
0 0 0 0 97 255 244 255 255 255 30 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 76 255 248 255 239 212 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 255 245 255 255 254 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 244 255 240 255 248 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 255 254 255 251 255 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 255 227 236 248 243 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 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 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 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
)))
(define glgui_keypad_return.img (list 30 21 glgui_keypad_return.raw 0. 1. .93750000000000000000 .34375000000000000000))
| false |
88268c526fb51be855cde7b312a3dff0e6647696
|
2fc7c18108fb060ad1f8d31f710bcfdd3abc27dc
|
/lib/sublist.scm
|
864f10da6f3bb7b5e92473f2b5798f493edb587f
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-warranty-disclaimer",
"CC0-1.0"
] |
permissive
|
bakul/s9fes
|
97a529363f9a1614a85937a5ef9ed6685556507d
|
1d258c18dedaeb06ce33be24366932143002c89f
|
refs/heads/master
| 2023-01-24T09:40:47.434051 | 2022-10-08T02:11:12 | 2022-10-08T02:11:12 | 154,886,651 | 68 | 10 |
NOASSERTION
| 2023-01-25T17:32:54 | 2018-10-26T19:49:40 |
Scheme
|
UTF-8
|
Scheme
| false | false | 738 |
scm
|
sublist.scm
|
; Scheme 9 from Empty Space, Function Library
; By Nils M Holm, 2010
; Placed in the Public Domain
;
; (sublist list integer1 integer2) ==> list
;
; Return a fresh list formed from the members of LIST beginning with
; index INTEGER1 (inclusive) and ending with index INTEGER2 (exclusive).
;
; Example: (sublist '(a b c d e) 2 4) ==> (c d)
; (sublist '(a b c d e) 2 2) ==> ()
(define (sublist x p0 pn)
(let ((k (length x)))
(cond ((<= 0 p0 pn k)
(do ((i p0 (+ 1 i))
(in (list-tail x p0) (cdr in))
(out '() (cons (car in) out)))
((= i pn)
(reverse! out))))
(else
(error "sublist: bad range" (list p0 pn))))))
| false |
aff00339487e09f28eb07c452835b92155035184
|
d17943098180a308ae17ad96208402e49364708f
|
/platforms/js-vm/private/tests/benchmarks/common/nestedloop.rkt
|
5d7594bcddaf363135e076ea683606314ff353d9
|
[] |
no_license
|
dyoo/benchmark
|
b3f4f39714cc51e1f0bc176bc2fa973240cd09c0
|
5576fda204529e5754f6e1cc8ec8eee073e2952c
|
refs/heads/master
| 2020-12-24T14:54:11.354541 | 2012-03-02T19:40:48 | 2012-03-02T19:40:48 | 1,483,546 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 31 |
rkt
|
nestedloop.rkt
|
(module nestedloop "wrap.ss")
| false |
9a6e34e1e7caf746ba22b8fb11d1bc7a3a518b06
|
5355071004ad420028a218457c14cb8f7aa52fe4
|
/3.5/e-3.58.scm
|
f1e5954b086ee3ad3230a4baf2296e413fe6693b
|
[] |
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 | 640 |
scm
|
e-3.58.scm
|
(load "../helpers.scm")
(load "3.5.scm")
; Exercise 3.58. Give an interpretation of the stream computed by the
; following procedure:
(define (expand num den radix)
(cons-stream
(quotient (* num radix) den)
(expand (remainder (* num radix) den) den radix)))
; (Quotient is a primitive that returns the integer quotient of two
; integers.) What are the successive elements produced by (expand 1 7
; 10) ? What is produced by (expand 3 8 10) ?
; ------------------------------------------------------------
; (display-stream (expand 1 7 10)) ; 1 4 2 8 5 7 1 4 2 8 ..
; (display-stream (expand 3 8 10)) ; 3 7 5 0 0 0 0 0 0 0 ...
| false |
6edbb809e66bd61fe1cb392f7e68b821fd30123a
|
b25f541b0768197fc819f1bb01688808b4a60b30
|
/s9/lib/subvector.scm
|
3dbc64d44b9dd5916d5f1a23c2c5bf126a8cb722
|
[
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain"
] |
permissive
|
public-domain/s9fes
|
327c95115c2ecb7fab976307ae7cbb1d4672f843
|
f3c3f783da7fd74daa8be7e15f1c31f827426985
|
refs/heads/master
| 2021-02-09T01:22:30.573860 | 2020-03-01T20:50:48 | 2020-03-01T20:50:48 | 244,221,631 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,052 |
scm
|
subvector.scm
|
; Scheme 9 from Empty Space, Function Library
; By Nils M Holm, 2010
; Placed in the Public Domain
;
; (subvector vector integer1 integer2) ==> vector
; (vector-copy vector) ==> vector
;
; SUBVECTOR returns a fresh vector formed from the members of VECTOR
; beginning with index INTEGER1 (inclusive) and ending with index
; INTEGER2 (exclusive).
;
; (Vector-copy v) is shorthand for (subvector v 0 (vector-length v)).
;
; Example: (subvector '#(a b c d e) 2 4) ==> #(c d)
; (subvector '#(a b c d e) 2 2) ==> #()
; (vector-copy '#(a b c)) ==> #(a b c)
(define (subvector v p0 pn)
(let ((k (vector-length v)))
(cond ((<= 0 p0 pn k)
(let ((n (make-vector (- pn p0))))
(do ((i p0 (+ 1 i))
(j 0 (+ 1 j)))
((= i pn)
n)
(vector-set! n j (vector-ref v i)))))
(else
(error "subvector: bad range" (list p0 pn))))))
(define (vector-copy v)
(subvector v 0 (vector-length v)))
| false |
be6678af8e0caf7dece9a652456ef75354394dec
|
d6ba773f1c822a5003692c47a6d2b645e47c0907
|
/lib/postgresql/misc/socket.sld
|
b8daab17dad6cf1fceec478865522ac6aa932b92
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
ktakashi/r7rs-postgresql
|
a2d93e39cd95c0cf659e8336f5aaf62ad61f4f75
|
94fdaeccee6caa5e9562a8f231329e59ce15aae7
|
refs/heads/master
| 2020-04-06T13:13:50.481891 | 2017-12-11T20:09:43 | 2017-12-11T20:09:43 | 26,015,242 | 23 | 3 | null | 2015-02-04T19:40:18 | 2014-10-31T12:26:02 |
Scheme
|
UTF-8
|
Scheme
| false | false | 2,611 |
sld
|
socket.sld
|
;;; -*- mode:scheme; coding:utf-8; -*-
;;;
;;; postgresql/misc/socket.sld - socket utilities
;;;
;;; Copyright (c) 2014-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.
;;;
(define-library (postgresql misc socket)
(cond-expand
((library (srfi 106)) (import (srfi 106)))
(chibi
;; only support what we need.
(import (scheme base) (chibi net) (scheme cxr) (chibi filesystem)
(chibi process))
(begin
;; well...
(define socket? list?)
(define (make-client-socket host port . opt)
(let ((r (open-net-io host port)))
(unless r (error "make-client-socket: failed to create a socket"))
r))
(define (socket-input-port sock) (cadr sock))
(define (socket-output-port sock) (caddr sock))
(define (socket-close sock) (close-file-descriptor (car sock)))
;; do nothing for now
(define (socket-shutdown sock how) #t)
(define hope-one-shot-execution
(begin
(set-signal-action! signal/pipe
(lambda (signum) (error "received SIGPIPE")))))))
(gauche (import (gauche base))
(begin (define socket? (with-module srfi-106 socket?))))
(else))
(export socket? make-client-socket socket-input-port socket-output-port
socket-close socket-shutdown))
| false |
69dd024aae0a785f214a644f3a6ca95c1dd3fe38
|
d9cb7af1bdc28925fd749260d5d643925185b084
|
/test/1.05.scm
|
1cefd7112428d59054911aa16aef78791d3cbe21
|
[] |
no_license
|
akerber47/sicp
|
19e0629df360e40fd2ea9ba34bf7bd92be562c3e
|
9e3d72b3923777e2a66091d4d3f3bfa96f1536e0
|
refs/heads/master
| 2021-07-16T19:36:31.635537 | 2020-07-19T21:10:54 | 2020-07-19T21:10:54 | 14,405,303 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 284 |
scm
|
1.05.scm
|
(define (eps-eq? a b)
(and (< (- a b) 0.0001)
(< (- b a) 0.0001)))
(define (run)
(assert (eps-eq? (new-sqrt 4.0) 2.0))
(assert (eps-eq? (new-sqrt 1.0) 1.0))
(assert (eps-eq? (new-sqrt 100.0) 10.0))
(assert (eps-eq? (new-sqrt 10000.0) 100.0))
"All tests passed!"
)
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.