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
193eadcae598fbedaf68e2dcd0744b7064120b8e
43612e5ed60c14068da312fd9d7081c1b2b7220d
/tools/benchtimes/num-itersx10.scm
80057ffb107be673344377ba09b98f3e39daac57
[ "BSD-3-Clause" ]
permissive
bsaleil/lc
b1794065183b8f5fca018d3ece2dffabda6dd9a8
ee7867fd2bdbbe88924300e10b14ea717ee6434b
refs/heads/master
2021-03-19T09:44:18.905063
2019-05-11T01:36:38
2019-05-11T01:36:38
41,703,251
27
1
BSD-3-Clause
2018-08-29T19:13:33
2015-08-31T22:13:05
Scheme
UTF-8
Scheme
false
false
1,917
scm
num-itersx10.scm
; Gabriel benchmarks (define boyer-iters 200) (define browse-iters 6000) (define cpstak-iters 10000) (define ctak-iters 1000) (define dderiv-iters 20000000) (define deriv-iters 20000000) (define destruc-iters 5000) (define diviter-iters 10000000) (define divrec-iters 10000000) (define puzzle-iters 1000) (define tak-iters 20000) (define takl-iters 3000) (define trav1-iters 1000) (define trav2-iters 200) (define triangl-iters 100) ; Kernighan and Van Wyk benchmarks (define ack-iters 100) (define array1-iters 10) (define cat-iters 10) (define string-iters 100) (define sum1-iters 100) (define sumloop-iters 100) (define tail-iters 10) (define wc-iters 10) ; C benchmarks (define fft-iters 20000) (define fib-iters 50) (define fibfp-iters 20) (define mbrot-iters 1000) (define nucleic-iters 50) (define pnpoly-iters 1000000) (define sum-iters 200000) (define sumfp-iters 200000) (define tfib-iters 200) ; Other benchmarks (define conform-iters 400) (define dynamic-iters 200) (define earley-iters 2000) (define fibc-iters 5000) (define graphs-iters 3000) (define lattice-iters 10) (define matrix-iters 4000) (define maze-iters 40000) (define mazefun-iters 10000) (define nqueens-iters 20000) (define paraffins-iters 10000) (define peval-iters 2000) (define pi-iters 20) (define primes-iters 1000000) (define ray-iters 50) (define scheme-iters 200000) (define simplex-iters 1000000) (define slatex-iters 200) (define perm9-iters 100) (define nboyer-iters 1000) (define sboyer-iters 1000) (define gcbench-iters 10) (define compiler-iters 3000) (define nbody-iters 10) (define fftrad4-iters 40)
false
38da0c413cc15ee973dd9ca58b091f3657fd4222
5090d98da30eebff560edb892f4ff139f775019b
/tests/run.scm
4722ac0c5973d8f811caab475e81eb7b6264546b
[]
no_license
mario-goulart/fakefile
baf8d40594b8f1aed4c62abe5bb24d200f6863d5
4f53dbffed79cd069031e07c3c0f321bb09e2995
refs/heads/master
2020-04-28T07:21:20.649886
2012-12-05T14:55:27
2012-12-05T14:55:27
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,860
scm
run.scm
(use fakefile files simple-sha1 test) (define csc-options '(-d0 -O3)) ;; Extensions we want to build (extension.so and extension.import.so) (define extensions '(foo bar baz quux)) ;; Helper procedures (define (extension.scm ext) (make-pathname #f (->string ext) "scm")) (define (extension.so ext) (make-pathname #f (->string ext) "so")) (define (extension.import.so ext) (make-pathname #f (->string ext) "import.so")) (define (extension.import.scm ext) (make-pathname #f (->string ext) "import.scm")) (define (make-extension-rules ext) (let* ((ext-so (extension.so ext)) (ext-scm (extension.scm ext)) (mod-scm (extension.import.scm ext))) `((,(extension.so ext) (,ext-scm) (csc -s -J ,@csc-options ,ext-scm)) (,(extension.import.so ext) (,mod-scm) (csc -s ,@csc-options ,mod-scm))))) (define extensions-rules (let loop ((extensions extensions)) (if (null? extensions) '() (append (make-extension-rules (car extensions)) (loop (cdr extensions)))))) (define cleanup-command (let ((files-to-remove (let loop ((extensions extensions)) (if (null? extensions) '() (let ((ext (car extensions))) (append (list (extension.so ext) (extension.import.so ext) (extension.import.scm ext)) (loop (cdr extensions)))))))) `(rm -f ,@files-to-remove *~))) ;;; Write the Makefile (write-makefile "Makefile" (append (list "SOME_VAR ?= value") `((all ,(map car extensions-rules))) extensions-rules `((clean () ,cleanup-command)) `((.PHONY (all clean))))) ;;; Test (test-begin "fakefile") (test-assert (equal? (sha1sum "Makefile") (sha1sum "Makefile.orig"))) (test-end "fakefile") (delete-file* "Makefile")
false
9b0c34e85f30ee01780ec13022f735bc38de1228
a8216d80b80e4cb429086f0f9ac62f91e09498d3
/tests/snow/repo3/takakazu/bernoulli-includes.sld
1190aac8d472dde67daffbebed67e690d2ea2158
[ "BSD-3-Clause" ]
permissive
ashinn/chibi-scheme
3e03ee86c0af611f081a38edb12902e4245fb102
67fdb283b667c8f340a5dc7259eaf44825bc90bc
refs/heads/master
2023-08-24T11:16:42.175821
2023-06-20T13:19:19
2023-06-20T13:19:19
32,322,244
1,290
223
NOASSERTION
2023-08-29T11:54:14
2015-03-16T12:05:57
Scheme
UTF-8
Scheme
false
false
68
sld
bernoulli-includes.sld
(import (scheme base) (pingala binomial)) (include "bernoulli.scm")
false
687ec2c3d2f8c25090b41e3def2ac47ed2dbeeed
40f36bb0b41c6a27b2e4802ddb128f7354ea38a3
/self/schemeR6RS/lib/string.sld
7c5193d51082824e591b0d8b8ca8b3a124d18862
[]
no_license
simalaia/modules
b5d2d4c015646b0ea9edc17576a31493f520197c
45f58e17b1faab48c6f0c46cb17cc010f30872fe
refs/heads/main
2023-04-05T19:42:12.407065
2021-04-22T22:05:04
2021-04-22T22:05:04
343,354,627
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,565
sld
string.sld
;; -*- mode:scheme -*- ;; I need to review the code here since I left it in a terrible state. While I' at it I should check the standards to see whether these aren't already implemented. (library (lib string) (export str string->char string-reverse) (import (rnrs)) ;; Stuff to string (define (str . l) (with-output-to-string (lambda () (for-each display l)))) ;; The inverse of char->string (define (string->char s) (if (and (string? s) (= (string-length s) 1)) (car (string->list c)) (error `meh "string->char hates you")) ) (define (string-reverse s) (list->string (reverse (string->list s))) ) (define (string-empty? s) (string=? s "") ) (define (string-prefix? s p) (and (<= (string-length p) (string-length s)) (string=? p (substring s 0 (string-length p)))) ) (define (string-take s n) (substring s 0 n) ) (define (string-drop s n) (substring s n (string-length s))) (define (string-trim s p) (if (prefix? p s) (right (string-length p) s) s)) (define (string-mirt p s) (string-reverse (trim (string-reverse p) (string-reverse s)))) (define (chop p s) (string-reverse (trim (string-reverse p) (string-reverse (trim p s)))) ) ;; What are collect about again? (define (collect p l r) (let ( (n (string-length p)) ) (cond ((string=? r "") `(,l . "") ) ((prefix? p r) `(,l . ,(right n r))) (else (collect p (string-append l (left n r)) (right n r)) )) )) (define (split p s) (cond ((string=? s "") `() ) (else (let ( (n (collect p "" s)) ) (cons (car n) (split p (cdr n))) ) )) ) )
false
e4a825604ed1e1e28a85f7c8b17d940d401ec534
dd4cc30a2e4368c0d350ced7218295819e102fba
/vendored_parsers/vendor/highlights/cmake.scm
d118992f84e7a9a7405f61c6e31b099bacf4c6ee
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "Apache-2.0" ]
permissive
Wilfred/difftastic
49c87b4feea6ef1b5ab97abdfa823aff6aa7f354
a4ee2cf99e760562c3ffbd016a996ff50ef99442
refs/heads/master
2023-08-28T17:28:55.097192
2023-08-27T04:41:41
2023-08-27T04:41:41
162,276,894
14,748
287
MIT
2023-08-26T15:44:44
2018-12-18T11:19:45
Rust
UTF-8
Scheme
false
false
3,260
scm
cmake.scm
;; Based on the nvim-treesitter highlighting, which is under the Apache license. ;; https://github.com/nvim-treesitter/nvim-treesitter/blob/d76b0de6536c2461f97cfeca0550f8cb89793935/queries/cmake/highlights.scm [ (quoted_argument) (bracket_argument) ] @string (variable_ref) @none (variable) @variable [ (bracket_comment) (line_comment) ] @comment (normal_command (identifier) @function) ["ENV" "CACHE"] @symbol ["$" "{" "}" "<" ">"] @punctuation.special ["(" ")"] @punctuation.bracket [ (function) (endfunction) (macro) (endmacro) ] @keyword.function [ (if) (elseif) (else) (endif) ] @conditional [ (foreach) (endforeach) (while) (endwhile) ] @repeat (function_command (function) . (argument) @function (argument)* @parameter ) (macro_command (macro) . (argument) @function.macro (argument)* @parameter ) ;; (normal_command ;; (identifier) @function.builtin ;; . (argument) @variable ;; (#match? @function.builtin "\\c^(set)$") ;; ) ;; (normal_command ;; (identifier) @function.builtin ;; (#match? @function.builtin "\\c^(set)$") ;; ( ;; (argument) @constant ;; (#any-of? @constant "PARENT_SCOPE") ;; ) . ;; ) ;; (normal_command ;; (identifier) @function.builtin ;; (#match? @function.builtin "\\c^(set)$") ;; . (argument) ;; ( ;; (argument) @_cache @constant ;; . ;; (argument) @_type @constant ;; (#any-of? @_cache "CACHE") ;; (#any-of? @_type "BOOL" "FILEPATH" "PATH" "STRING" "INTERNAL") ;; ) ;; ) ;; (normal_command ;; (identifier) @function.builtin ;; (#match? @function.builtin "\\c^(set)$") ;; . (argument) ;; (argument) @_cache ;; (#any-of? @_cache "CACHE") ;; ( ;; (argument) @_force @constant ;; (#any-of? @_force "FORCE") ;; ) . ;; ) ;; ((argument) @boolean ;; (#match? @boolean "\\c^(1|on|yes|true|y|0|off|no|false|n|ignore|notfound|.*-notfound)$") ;; ) (if_command (if) (argument) @keyword.operator (#any-of? @keyword.operator "NOT" "AND" "OR" "COMMAND" "POLICY" "TARGET" "TEST" "DEFINED" "IN_LIST" "EXISTS" "IS_NEWER_THAN" "IS_DIRECTORY" "IS_SYMLINK" "IS_ABSOLUTE" "MATCHES" "LESS" "GREATER" "EQUAL" "LESS_EQUAL" "GREATER_EQUAL" "STRLESS" "STRGREATER" "STREQUAL" "STRLESS_EQUAL" "STRGREATER_EQUAL" "VERSION_LESS" "VERSION_GREATER" "VERSION_EQUAL" "VERSION_LESS_EQUAL" "VERSION_GREATER_EQUAL" ) ) ;; (normal_command ;; (identifier) @function.builtin ;; . (argument) ;; (argument) @constant ;; (#any-of? @constant "ALL" "COMMAND" "DEPENDS" "BYPRODUCTS" "WORKING_DIRECTORY" "COMMENT" ;; "JOB_POOL" "VERBATIM" "USES_TERMINAL" "COMMAND_EXPAND_LISTS" "SOURCES") ;; (#match? @function.builtin "\\c^(add_custom_target)$") ;; ) ;; (normal_command ;; (identifier) @function.builtin ;; (argument) @constant ;; (#any-of? @constant "OUTPUT" "COMMAND" "MAIN_DEPENDENCY" "DEPENDS" "BYPRODUCTS" "IMPLICIT_DEPENDS" "WORKING_DIRECTORY" ;; "COMMENT" "DEPFILE" "JOB_POOL" "VERBATIM" "APPEND" "USES_TERMINAL" "COMMAND_EXPAND_LISTS") ;; (#match? @function.builtin "\\c^(add_custom_command)$") ;; )
false
c636d10e14aa2fb64df280ccad46d8e77d1e19b1
b63601b5d27a014d9258eb736eefa6b17c4ecc31
/LLLdocs/src/Fibonacci.scm
0f97be8966b06985a3fbacd3203395321bb181a6
[]
no_license
hitokey/wasCm
953d3c9e6a768b940cac0b765e0c2177fe2d0646
32c7f0f25964200441f52852763ce31f725ef2e7
refs/heads/master
2023-08-17T00:56:06.969797
2021-02-10T02:20:43
2021-02-10T02:20:43
266,668,959
1
0
null
2020-06-23T22:28:59
2020-05-25T02:53:02
TeX
UTF-8
Scheme
false
false
181
scm
Fibonacci.scm
(define (fibo i) (let fn+1 [ (n i) (fn 1) (fn-1 1) ] (if (< n 2) fn (fn+1 (- n 1) (+ fn fn-1) fn)) )) #| 1:=> (load "Fibonacci.scm") Fibonacci.scm 1:=> (fibo 5) 8 |#
false
dc1ed00abff797857f1fac82857c09768d553b84
f2a89a6c62c60082aeec115c2d4b5a1c947a4bd8
/scheme/gauche/dict.scm
ed35afe91e3ce687cb49a04ea24e85085ba69f80
[]
no_license
offby1/anagrams
13b83343d8f1ca8a0ab1cbc65aedac39c47ee1a9
0a7fbcff49a7dee6ed28333ecd354dd1fcff4bd6
refs/heads/master
2021-06-05T00:51:33.057068
2017-11-20T05:16:37
2017-11-20T05:16:37
89,620
9
5
null
2017-11-20T05:16:38
2008-12-12T17:57:46
Scheme
UTF-8
Scheme
false
false
2,019
scm
dict.scm
(define-module dict (use bag) (use srfi-1) (export dictionary-for)) (select-module dict) (define word-acceptable? (let ((has-vowel-regexp #/[aeiouy]/i) (has-non-letter-regexp #/[^a-z]/i)) (lambda (word) (let ((l (string-length word))) (and (not (zero? l)) ;; it appears that word will be "incomplete" if and only ;; if it contains non-ASCII characters. (not (string-incomplete? word)) ;; it's gotta have a vowel. (rxmatch has-vowel-regexp word) ;; it's gotta be all ASCII, all the time. (not (rxmatch has-non-letter-regexp word)) ;; it's gotta be two letters long, unless it's `i' or `a'. (or (string=? "i" word) (string=? "a" word) (< 1 l))))))) (define *ht* (make-hash-table 'eqv?)) (define (adjoin-word! dict word) (let ((bag (bag word))) (define (! thing) (hash-table-put! dict bag thing)) (let ((probe (hash-table-get dict bag #f))) (if (not probe) (! (list word)) (if (not (member word probe)) (! (cons word probe))))))) (call-with-input-file "/usr/share/dict/words" (lambda (p) (let loop ((words-saved 0)) (let ((line (read-line p #t))) (if (eof-object? line) (begin (display "Dictionary has ") (display words-saved) (display " entries") (newline) ) (if (word-acceptable? line) (begin (adjoin-word! *ht* (list->string (map char-downcase (string->list line)))) (loop (+ 1 words-saved))) (loop words-saved)) ))))) ;; now convert the hash table to a list (define (dictionary-for criterion-bag) (filter (lambda (pair) (subtract-bags criterion-bag (car pair))) (hash-table-map *ht* cons))) (provide "dict")
false
28cd63b9a6b557631c954ab53ea30a85ef9de9c4
1384f71796ddb9d11c34c6d988c09a442b2fc8b2
/scheme/xmms2/client.scm
46d42c66053713153a18cf6fd29214b35317b95b
[]
no_license
ft/xmms2-guile
94c2479eec427a370603425fc9e757611a796254
29670e586bf440c20366478462f425d5252b953c
refs/heads/master
2021-07-08T07:58:15.066996
2020-10-12T01:24:04
2020-10-12T01:24:04
74,858,831
1
2
null
null
null
null
UTF-8
Scheme
false
false
1,891
scm
client.scm
;; Copyright (c) 2017 xmms2-guile workers, All rights reserved. ;; ;; Terms for redistribution and use can be found in LICENCE. (define-module (xmms2 client) #:use-module (ice-9 optargs) #:use-module (xmms2 constants meta) #:use-module (xmms2 header) #:use-module (xmms2 io) #:use-module (xmms2 ipc main) #:use-module (xmms2 payload) #:export (default-uri reply->header reply->payload reply->value with-xmms2-connection)) (define (default-uri) "Returns the default IPC uri used by xmms2 servers." (string-concatenate `("unix:///tmp/xmms-ipc-" ,(passwd:name (getpwuid (geteuid)))))) (define (default-failure-handler exception arguments) (format (current-error-port) "xmms2-connection failed: ~s (~s)~%" exception arguments) (quit 1)) (define* (with-xmms2-connection #:key (handler (lambda (cl id co) #t)) (server (default-uri)) (client "xmms2-guile") (failure default-failure-handler)) (define (disconnect-and-return co rv) (xmms2-disconnect co) rv) (catch #t (lambda () (let ((connection (make-xmms2-connection server))) (xmms2-connect connection) (xmms2-send connection (ipc-hello PROTOCOL-VERSION client)) (let* ((reply (xmms2-recv connection)) (cookie (header->cookie (car reply))) (client-id (payload->value (caddr reply)))) (disconnect-and-return connection (handler connection client-id cookie))))) (lambda (key . rest) (failure key rest)))) (define (reply->header reply) (car reply)) (define (reply->payload reply) (caddr reply)) (define (reply->value reply) (payload->value (reply->payload reply)))
false
925e2cd93f4dd19b3601c5ab8f5cc1b36b0f327c
222b42ba803bfecd4ec31166dd2be107a840f2bd
/undone/unsorted/src/src/skew-heap1.scm
c9af33fa4cc89d6da64477b62e4cdeee63d56126
[]
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
2,511
scm
skew-heap1.scm
;; Skew heap. ;; Copyright Juha Heinanen 1988 ;; This code may be freely distributed. ;; (define (make-skew-heap lt? value-list) ; explicit vector version (define heap (heapify value-list)) (define (heapify value-list) ; heapifies value-list by a two-way merge (define (merge heap-list new-heap-list) (if (null? heap-list) new-heap-list (if (null? (cdr heap-list)) (cons (car heap-list) new-heap-list) (merge (cddr heap-list) (cons (meld! (car heap-list) (cadr heap-list)) new-heap-list))))) (if (null? value-list) '() (let loop ((heap-list (merge (map (lambda (x) (vector '() x '())) value-list) '()))) (if (null? (cdr heap-list)) (car heap-list) (loop (merge heap-list '())))))) (define (left h) (vector-ref h 0)) (define (info h) (vector-ref h 1)) (define (right h) (vector-ref h 2)) (define (set-left! h v) (vector-set! h 0 v)) (define (set-right! h v) (vector-set! h 2 v)) (define (insert! x) (set! heap (meld! (heapify (list x)) heap))) (define (find-min) (if (null? heap) '() (info heap))) (define (delete-min!) (if (null? heap) '() (let ((result (info heap))) (set! heap (meld! (left heap) (right heap))) result))) (define (meld! h1 h2) (define (meld1! h1 h2 parent) (if (null? h1) (set-left! parent h2) (if (lt? (info h1) (info h2)) (let ((t (right h1))) (set-left! parent h1) (set-right! h1 (left h1)) (meld1! t h2 h1)) (let ((t (right h2))) (set-left! parent h2) (set-right! h2 (left h2)) (meld1! t h1 h2))))) (if (null? h2) h1 (let ((result (vector '() '() '()))) (meld1! h1 h2 result) (left result)))) (define (select op . args) (case op (insert! (apply insert! args)) (find-min (find-min)) (delete-min! (delete-min!)) (else (error "Unknown operation MAKE-SKEW-HEAP" op)))) select) (define (heap-sort1 list) (define heap (make-skew-heap < '())) (for-each (lambda (x) (heap 'insert! x)) list) (let loop ((result '()) (next (heap 'delete-min!))) (if (null? next) result (loop (cons next result) (heap 'delete-min!)))))
false
6195181f9b0ca45c35d7e8e4bde3e6421b67d8bf
ebf028b3a35ae1544bba1a1f9aa635135486ee6c
/sitelib/lunula/mysql.scm
26f7c6bd02c2ad9661604cb39bbe876a71a28c2a
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
tabe/lunula
b4b666151874271211744cce1346e58e3a56fa79
b7699a850b9c9a64c1d3a52d50ce20050bd17475
refs/heads/master
2021-01-01T20:04:43.571993
2010-05-06T15:39:31
2010-05-06T15:39:31
334,916
2
0
null
null
null
null
UTF-8
Scheme
false
false
13,528
scm
mysql.scm
(library (lunula mysql) (export *mysql* call-with-mysql close connect count destroy execute lookup lookup-all save) (import (rnrs) (only (srfi :1) iota) (only (srfi :48) format) (only (ypsilon concurrent) make-mailbox recv send) (ypsilon ffi) (ypsilon mysql) (only (lunula string)) (prefix (only (lunula log) info) log:) (only (lunula persistent-record) created-at-set! id-of id-set! maybe-id updated-at-set!) (lunula sql)) (define NULL 0) (define *mysql* (make-mailbox)) (define (connect host user passwd database) (let ((mysql (mysql_init NULL))) (cond ((zero? (mysql_real_connect mysql host user passwd database 0 NULL 0)) (mysql_error mysql)) (else (send *mysql* mysql) #t)))) (define (close) (mysql_close (recv *mysql*))) (define (escape/mysql mysql x) (cond ((integer? x) x) ((string? x) (let* ((bv (string->utf8 x)) (len (bytevector-length bv)) (dst (make-bytevector (+ (* 2 len) 1)))) (mysql_real_escape_string mysql dst x len) (utf8->string dst))) (else (escape/mysql mysql (format "~a" x))))) (define (row->fields names result row) (let ((num (mysql_num_fields result)) (lengths (mysql_fetch_lengths result))) (and (= num (+ 3 (vector-length names))) (let lp ((i 0) (fields '())) (if (= i num) (reverse fields) (let* ((f (c-void*-ref (+ row (* i sizeof:void*)))) (v (if (zero? f) #f (utf8->string (make-bytevector-mapping f (c-unsigned-int-ref (+ lengths (* i sizeof:int)))))))) (lp (+ i 1) (cons v fields)))))))) (define-syntax call-with-mysql (syntax-rules () ((_ proc) (let ((mysql (recv *mysql*))) (dynamic-wind (lambda () #f) (lambda () (proc mysql)) (lambda () (send *mysql* mysql))))))) (define-syntax execute (syntax-rules () ((_ mysql query) (begin (log:info "MySQL> ~a" query) (let ((r (mysql_query mysql query))) (unless (zero? r) (log:info "MySQL! ~a" (mysql_error mysql))) r))) ((_ query) (call-with-mysql (lambda (mysql) (execute mysql query)))))) (define (fields->persistent-record constructor fields) (let ((record (apply constructor (cdddr fields)))) (id-set! record (maybe-id (car fields))) (created-at-set! record (cadr fields)) (updated-at-set! record (caddr fields)) record)) (define (row->field-tuple c-tuple result row) (let ((num (mysql_num_fields result)) (lengths (mysql_fetch_lengths result))) (and (= num (apply + (map length c-tuple))) (let ((len (length c-tuple))) (let loop ((k 0) (n 0) (f-tuple '())) (if (= k len) (reverse f-tuple) (let ((l (length (list-ref c-tuple k)))) (let lp ((i 0) (fields '())) (if (= i l) (loop (+ k 1) (+ n i) (cons (reverse fields) f-tuple)) (let* ((f (c-void*-ref (+ row (* (+ n i) sizeof:void*)))) (v (if (zero? f) #f (utf8->string (make-bytevector-mapping f (c-unsigned-int-ref (+ lengths (* (+ n i) sizeof:int)))))))) (lp (+ i 1) (cons v fields)))))))))))) (define-syntax field-tuple->persistent-record-tuple (syntax-rules () ((_ (record-name0 record-name1 ...) field-tuple) (map (lambda (record-name fields) (fields->persistent-record (record-constructor (record-constructor-descriptor record-name)) fields)) (list record-name0 record-name1 ...) field-tuple)))) (define-syntax count (syntax-rules () ((_ (record-name (reference foreign) ...) param) (call-with-mysql (lambda (mysql) (call-with-count (lambda (x) (escape/mysql mysql x)) (record-name (reference foreign) ...) param () (lambda (query) (and (zero? (execute mysql query)) (let ((result (mysql_store_result mysql))) (and (not (zero? result)) (dynamic-wind (lambda () #f) (lambda () (let ((row (mysql_fetch_row result))) (and (not (zero? row)) (let ((lengths (mysql_fetch_lengths result)) (f (c-void*-ref row))) (and (not (zero? f)) (string->number (utf8->string (make-bytevector-mapping f (c-unsigned-int-ref lengths))))))))) (lambda () (mysql_free_result result))))))))))) ((_ record-name param) (count (record-name) param)))) (define-syntax lookup (syntax-rules () ((_ (record-name (reference foreign) ...) param rest) (call-with-mysql (lambda (mysql) (call-with-tuple (lambda (x) (escape/mysql mysql x)) (record-name (reference foreign) ...) param () (lambda (c-tuple query) (if (not (zero? (execute mysql query))) #f (let ((result (mysql_store_result mysql))) (if (zero? result) #f (let ((row (mysql_fetch_row result))) (and (not (zero? row)) (let ((ft (row->field-tuple c-tuple result row))) (mysql_free_result result) (and ft (field-tuple->persistent-record-tuple (record-name reference ...) ft))))))))))))) ((_ (record-name (reference foreign) ...) param) (lookup (record-name (reference foreign) ...) param ())) ((_ record-name param rest) (call-with-mysql (lambda (mysql) (let* ((escape (lambda (x) (escape/mysql mysql x))) (rtd (record-type-descriptor record-name)) (c (record-constructor (record-constructor-descriptor record-name))) (names (record-type-field-names rtd)) (table (record-name->table-name (record-type-name rtd))) (query (string-append (lookup-query escape names table param) rest))) (if (not (zero? (execute mysql query))) #f (let ((result (mysql_store_result mysql))) (if (zero? result) #f (let ((row (mysql_fetch_row result))) (and (not (zero? row)) (let ((fields (row->fields names result row))) (mysql_free_result result) (and fields (fields->persistent-record c fields)))))))))))) ((_ record-name param) (lookup record-name param "")))) (define-syntax lookup-all (syntax-rules () ((_ (record-name (reference foreign) ...) param rest) (call-with-mysql (lambda (mysql) (call-with-tuple (lambda (x) (escape/mysql mysql x)) (record-name (reference foreign) ...) param rest (lambda (c-tuple query) (if (not (zero? (execute mysql query))) #f (let ((result (mysql_store_result mysql))) (if (zero? result) '() (let loop ((ls '()) (row (mysql_fetch_row result))) (cond ((zero? row) (mysql_free_result result) (reverse ls)) ((row->field-tuple c-tuple result row) => (lambda (ft) (let ((rt (field-tuple->persistent-record-tuple (record-name reference ...) ft))) (loop (cons rt ls) (mysql_fetch_row result))))) (else (loop (cons #f ls) (mysql_fetch_row result))))))))))))) ((_ (record-name (reference foreign) ...) param) (lookup-all (record-name (reference foreign) ...) param ())) ((_ record-name param rest) (call-with-mysql (lambda (mysql) (let* ((escape (lambda (x) (escape/mysql mysql x))) (rtd (record-type-descriptor record-name)) (c (record-constructor (record-constructor-descriptor record-name))) (names (record-type-field-names rtd)) (table (record-name->table-name (record-type-name rtd))) (query (string-append (lookup-query escape names table param) rest))) (if (not (zero? (execute mysql query))) #f (let ((result (mysql_store_result mysql))) (if (zero? result) '() (let loop ((ls '()) (row (mysql_fetch_row result))) (cond ((zero? row) (mysql_free_result result) (reverse ls)) (else (let ((fields (row->fields names result row))) (loop (cons (and fields (fields->persistent-record c fields)) ls) (mysql_fetch_row result))))))))))))) ((_ record-name param) (lookup-all record-name param "")))) (define-syntax save (syntax-rules () ((_ mysql record) (let* ((escape (lambda (x) (escape/mysql mysql x))) (rtd (record-rtd record)) (names (record-type-field-names rtd)) (table (record-name->table-name (record-type-name rtd))) (id (id-of record))) (if (integer? id) (let ((query (string-append (lookup-query escape names table id) " FOR UPDATE"))) (and (zero? (execute mysql query)) (let ((result (mysql_store_result mysql))) (if (zero? result) #f (call/cc (lambda (cont) (if (dynamic-wind (lambda () #f) (lambda () (let ((row (mysql_fetch_row result))) (or (zero? row) (let ((fields (row->fields names result row))) (cond ((list? fields) (and (for-all equal? (cdddr fields) (map (lambda (i) ((record-accessor rtd i) record)) (iota (vector-length names)))) (cont 0))) (else (cont #f))))))) (lambda () (mysql_free_result result))) (let ((query (insert-query escape rtd names table record))) (and (zero? (execute mysql query)) (< 0 (mysql_affected_rows mysql)))) (let ((query (update-query escape rtd names table record))) (and (zero? (execute mysql query)) (mysql_affected_rows mysql)))))))))) (let ((query (insert-query escape rtd names table record))) (cond ((and (zero? (execute mysql query)) (< 0 (mysql_affected_rows mysql))) (id-set! record (mysql_insert_id mysql)) #t) (else #f)))))) ((_ record) (call-with-mysql (lambda (mysql) (save mysql record)))))) (define-syntax destroy (syntax-rules () ((_ mysql record) (let* ((table (record-name->table-name (record-type-name (record-rtd record)))) (query (delete-query table record))) (and (zero? (execute mysql query)) (mysql_affected_rows mysql)))) ((_ record) (call-with-mysql (lambda (mysql) (destroy mysql record)))))) )
true
dcc670896596514b64876a49ca020c6ac73a6d24
59d5121573c9397e5da52d630558f4187f80b25e
/P2-1.ss
56bd3d84d0f831a4628b93b174e74e7ee1510a76
[ "MIT" ]
permissive
haskellstudio/CSSE304
dc900af2102b6e8bffca38f7be7d5236007c1a5d
698ceabf026cb847754fc2bc01c16641b2f2c2af
refs/heads/master
2021-04-03T05:16:05.177891
2018-02-13T21:35:01
2018-02-13T21:35:01
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,346
ss
P2-1.ss
;;Yifei Li ;;P01 (load "pmatch.ss") ;;lex (define lex (lambda (e acc) (pmatch e [,y (guard (symbol? y)) (list 'var (list-index-of-eqv? y acc)) ] [,y (guard (number? y)) (list 'const y) ] [(lambda (,x) ,body) `(lambda ,(lex body (cons x acc)))] [(zero? ,nexp) `(zero ,(lex nexp acc))] [(sub1 ,a) `(sub1 ,(lex a acc))] [(* ,nexp1 ,nexp2) `(mult ,(lex nexp1 acc) ,(lex nexp2 acc))] [(if ,cond ,t ,f) `(if ,(lex cond acc) ,(lex t acc) ,(lex f acc))] [(let ((,x ,e)) ,body) `( let ,(lex e (cons x acc)) ,(lex body (cons x acc)))] [(let/cc ,x ,b) `(letcc ,(lex b (cons x acc)))] [(throw ,kexp ,nexp) `(throw ,(lex kexp acc) ,(lex nexp acc)) ] [(,rator ,rand) `(app ,(lex rator acc) ,(lex rand acc))] ))) (define list-index-of-eqv? (lambda (x acc) (cond ((eqv? x (car acc)) 0) (else (add1 (list-index-of-eqv? x (cdr acc))) )))) ;;interpreter-cps (define value-of-cps (lambda (expr env k) (pmatch expr [(const ,expr) (apply-k k expr)] [(mult ,x1 ,x2) (value-of-cps x1 env (lambda (v) (value-of-cps x2 env (lambda(w) (apply-k k (* v w))))))] [(sub1 ,x) (value-of-cps x env (lambda (v) (apply-k k (sub1 v))))] [(zero ,x) (value-of-cps x env (lambda (v) (apply-k k (zero? v))))] [(if ,test ,conseq ,alt) (value-of-cps test env (lambda (v) (if v (value-of-cps conseq env k) (value-of-cps alt env k) )))] [(letcc ,body) (value-of-cps body (lambda (y k^) (if (zero? y) (apply-k k^ k) (apply-env env y k^)))k) ] [(throw ,k-exp ,v-exp) (value-of-cps k-exp env (lambda (k) (value-of-cps v-exp env k)))] [(let ,e ,body) (value-of-cps e env (lambda (a) (value-of-cps body (lambda (y k) (if (zero? y) (apply-k k a) (apply-env env (sub1 y) k))) k)))] [(var ,expr) (apply-env env expr k)] [(lambda ,body) (apply-k k (lambda (a k) (value-of-cps body (lambda (y k) (if (zero? y) (apply-k k a) (apply-env env (sub1 y) k) )) k)))] [(app ,rator ,rand) (value-of-cps rator env (lambda (v) (value-of-cps rand env (lambda (w) (apply-closure v w k))))) ] ))) (define empty-env (lambda () (lambda (y) (error 'value-of "unbound identifier")))) (define empty-k (lambda () (lambda (v) v))) (define apply-env (lambda (env y k) (env y k))) (define apply-closure (lambda (c a k) (c a k))) (define apply-k (lambda (k v) (k v)))
false
045ce2cfb0931a1a8f772f548870858ef8484db5
0ffe5235b0cdac3846e15237c2232d8b44995421
/src/scheme/Section_3.3/3.21.scm
845e6d276aedf6ed8da3d0913139f3aee92a97e9
[]
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
666
scm
3.21.scm
; SICP Exercise 3.21 ; Dawie de Klerk ; 2012-11-24 (load "queue.scm") (load "../utils.scm") (define (print-queue queue) ;; Prints the content of a queue. The queue object is ;; a pair of pointers to the front and rear of a queue. ;; For it te be printed correctly only the list that ;; the front is pointing to is printed. (display (front-ptr queue)) (newline)) (define (do-example) (let ((q1 (make-queue))) (print-eval (insert-queue! q1 'a)) (print-queue q1) (print-eval (insert-queue! q1 'b)) (print-queue q1) (print-eval (delete-queue! q1)) (print-queue q1) (print-eval (delete-queue! q1)) (print-queue q1)))
false
2614a1c50285d9151a7aa6d449c0f81eb6701974
6f7df1f0361204fb0ca039ccbff8f26335a45cd2
/scheme/named-search-trees.ss
971af2fc9c114fc022827e739919a210aa42c614
[]
no_license
LFY/bpm
f63c050d8a2080793cf270b03e6cf5661bf3599e
a3bce19d6258ad42dce6ffd4746570f0644a51b9
refs/heads/master
2021-01-18T13:04:03.191094
2012-09-25T10:31:25
2012-09-25T10:31:25
2,099,550
2
0
null
null
null
null
UTF-8
Scheme
false
false
9,985
ss
named-search-trees.ss
;; Library for converting unfold program into SCFG over trees ;; The resulting SCFG can be considered a "stochastic search tree" in the sense ;; of HANSEI, except with names, so we can get recursion and sharing of ;; definitions. Hence "named search tree." (library (named-search-trees) (export define-nondet-prog define-nondet nondet-choice nondet-program->named-search-tree ;; debug make-root reify-choice-context make-choice-NT) (import (except (rnrs) string-hash string-ci-hash) (printing) (util) (_srfi :69) (_srfi :1) (delimcc-simple-ikarus) ) (define (make-root name thunk) (reset ((lambda () `(define-NT ,name ,(thunk)))))) (define (mk-choice-context name counter term) `(Choice-Context ,name ,counter ,term)) ;; name, 0 essentially act as a form of dynamically-scoped local ;; storage, we throw these away when the function returns (define (reify-choice-context name thunk) (choice-context->term (reset (mk-choice-context name 0 (thunk))))) (define choice-context->name cadr) (define choice-context->counter caddr) (define choice-context->term cadddr) (define (increment-choice-context cc) (mk-choice-context (choice-context->name cc) (+ 1 (choice-context->counter cc)) (choice-context->term cc))) (define (appname-counter->choice-symbol name counter) (list 'C counter name)) (define (choice-context->hash cc) (appname-counter->choice-symbol (choice-context->name cc) (choice-context->counter cc))) (define nt-defs (make-hash-table equal?)) (define symbol-store (make-hash-table equal?)) (define choice-symbol-count 0) (define (choice-symbol) (begin (set! choice-symbol-count (+ 1 choice-symbol-count)) (string->symbol (string-append "choice" (number->string choice-symbol-count))))) (define (gen-or-retrieve-symbol store context-name) (if (hash-table-exists? store context-name) (hash-table-ref store context-name) (begin (hash-table-set! store context-name (choice-symbol)) (hash-table-ref store context-name)))) (define (store-get-def context-name gen-context-def) (if (hash-table-exists? nt-defs context-name) (hash-table-ref nt-defs context-name) (begin (hash-table-set! nt-defs context-name 'PRIMED) ;; Yes, this line is necessary. (hash-table-set! nt-defs context-name (gen-context-def)) (hash-table-ref nt-defs context-name)))) ;; make-choice-NT: stores the definition of the nonterminal corresponding to this choice, ;; and returns the name (as the context + abstraction in question). (define (construct-NT name body . vars) `(define ,(cons name vars) ,body)) (define h-counter 0) (define (sym) (let ([answer (string->symbol (string-append "H" (number->string h-counter)))]) (begin (set! h-counter (+ 1 h-counter)) answer))) (define (choice-context->vars cc) (define (sample-name? t) (and (symbol? t) (equal? "H" (substring (symbol->string t) 0 1)))) (filter sample-name? (cdr (choice-context->name cc)))) (define (make-choice-NT . choices) (shift k ;; k: the reified partial continuation: (Choice-Context hash counter term[]) (let* ( [sample-name (sym)] ;; increment choice context is for the different choices occuring in same context. or something. ;; [choice-context (increment-choice-context (k sample-name))] [choice-context (increment-choice-context (k sample-name))] ;; in general we won't be able to recover the ;; structure ; not every ADT allows us to a 'H there. ;; however, it may be possible under a symbolic ;; execution of the program, where context is the program trace. ;; rule: if we see H on the LHS, that means a random ;; choice flowed into this function, so we will have ;; to 'delay' the final definition---or use the ;; sample name in the definition of the "nonterminal" [context-name (gen-or-retrieve-symbol symbol-store (choice-context->hash choice-context))] [context-vars (choice-context->vars choice-context)] [gen-context-def (lambda () (apply (curry construct-NT context-name `(choose ,@(map (lambda (f) (f)) choices))) (choice-context->vars choice-context)))] ;; `(define ,context-name ;; (choose ,@(map (lambda (f) (f)) choices))))] ;; [answer (increment-choice-context (k `(,context-name)))] [context-app `(,context-name ,@context-vars)] ;; version taking sharing into account: ;; [answer (let* ([final-context (increment-choice-context (k sample-name))]) ;; (mk-choice-context (choice-context->name final-context) ;; (choice-context->counter final-context) ;; `(let ([,sample-name ,context-app]) ;; ,(choice-context->term final-context))))] ;; old version [answer (increment-choice-context (k context-app))] ;; [answer (increment-choice-context ;; `(let ([,sample-name ,context-app]) ;; ,(k sample-name)))] ;; [answer `(let ([,sample-name ,context-app]) ;; ,(increment-choice-context (k sample-name)))] ) (begin (store-get-def context-name gen-context-def) ;(begin (print "in make-choice-NT:======================") ; (print "my choice context:") ; (pretty-print choice-context) ; (print "my context name:") ; (pretty-print context-name) ; (newline) ; (print "current symbol store:") ; (pretty-print (hash-table->alist symbol-store)) ; (print "current definition store:") ; (pretty-print (hash-table->alist nt-defs)) ; (newline) ; (print "final choice context:") ; (pretty-print answer) ; (print "end make-choice-NT=====================") ; (newline) ; (newline)) answer )))) ;; we can define "direct-style" programs that transform to SCFGs (define-syntax define-nondet-prog (syntax-rules () ((define-nondet-prog (name . vars) body) (define (name . vars) (make-root 'start (lambda () body)))))) (define-syntax define-nondet (syntax-rules () ((define-nondet (name . vars) body) (define (name . vars) (reify-choice-context (list 'name . vars) (lambda () body)))))) (define-syntax process-choices (syntax-rules () [(process-choices) '()] [(process-choices e1 e2 ...) (cons (lambda () e1) (process-choices e2 ...))] ;; ((process-choices e) (lambda () e)) )) (define-syntax nondet-choice (syntax-rules () ((nondet-choice . xs) (apply make-choice-NT (process-choices . xs))) ;; ((nondet-choice e1) (make-choice-NT (lambda () e1))) ;; ((nondet-choice e1 e2 ...) (make-choice-NT (process-choices e1 e2 ...))) )) ;; Converting a program to named search tree, i.e., stochastic context free tree grammar ;; there is one nonterminal per random choice (modulo naming) (define (nondet-program->named-search-tree thunk) (begin ;; clear the store (set! nt-defs (make-hash-table equal?)) ;; run the program, return the results (let* ([start-tree (thunk)] [definitions (map cdr (hash-table->alist nt-defs))]) (list (construct-NT 'start start-tree) definitions)) )) )
true
c99fc1a149c2f45ec845e325d1d3b776805185c0
fb9a1b8f80516373ac709e2328dd50621b18aa1a
/ch1/exercise1-6.scm
e92389a4b93100202f3a1279da822f087ec05e1a
[]
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
935
scm
exercise1-6.scm
;; 問題1.6 ;; Alyssa P. Hackerはifが特殊形式である理由がわからない. ;; condを使って普通の手続きとして提議してはいけないのか? ;; Eva Lu ator は,ifの新版を提議した. ;; then-clause, else-clause共に評価してから判定をしてしまう (define (new-if predicate then-clause else-clause) (cond (predicate then-clause) (else else-clause))) (new-if (= 2 3) 0 5) (new-if (= 1 1) 0 5) ;; else-clauseに再帰があるため無限ループに陥る ;; 特殊形式でないと,ifの評価前に引数の評価をするために無限ループになる (define (sqrt-iter guess x) (new-if (good-enough? guess x) guess (sqrt-iter (improve guess x) x))) ;; 参考にした ;; http://g000001.cddddr.org/1177591058 (define (foo x) (if (= x 0) "zero" (print "foo"))) (define (bar x) (new-if (= x 0) "zero" (print "foo"))) (foo 0) (bar 0)
false
739f80f7a29363b5b30716a6f92a4ad520b5fc8c
1de3d2f5aea84e4d19825c290980a3b4f7815f32
/monarchy/prototyping/agent-single.scm
4878140624a1db4feb10458ce9d28ccbe95f9d64
[]
no_license
certainty/lisp-misc
37798607ca0275552c39683bad3080a42ba931fe
d5ee799f3ab0f2cc74bf3b2a83604dace160a649
refs/heads/master
2017-12-30T03:02:25.789701
2016-11-12T09:27:43
2016-11-12T09:27:43
69,743,925
0
0
null
null
null
null
UTF-8
Scheme
false
false
292
scm
agent-single.scm
;; =license= ;; =/license= (use zmq posix) (let ((socket (make-socket 'push))) (connect-socket socket "tcp://127.0.0.1:5555") (connect-socket socket "tcp://127.0.0.1:5557") (send-message socket (sprintf "Agent-Message")) ;(receive-message* socket) (close-socket socket))
false
2c0bef65c0a85c93a23dbb33495e9c3c385b63a8
a8216d80b80e4cb429086f0f9ac62f91e09498d3
/lib/srfi/158.sld
897a43d933111ff84742fbc891699c2290fb0464
[ "BSD-3-Clause" ]
permissive
ashinn/chibi-scheme
3e03ee86c0af611f081a38edb12902e4245fb102
67fdb283b667c8f340a5dc7259eaf44825bc90bc
refs/heads/master
2023-08-24T11:16:42.175821
2023-06-20T13:19:19
2023-06-20T13:19:19
32,322,244
1,290
223
NOASSERTION
2023-08-29T11:54:14
2015-03-16T12:05:57
Scheme
UTF-8
Scheme
false
false
1,169
sld
158.sld
(define-library (srfi 158) (import (scheme base)) (import (scheme case-lambda)) (export generator circular-generator make-iota-generator make-range-generator make-coroutine-generator list->generator vector->generator reverse-vector->generator string->generator bytevector->generator make-for-each-generator make-unfold-generator) (export gcons* gappend gcombine gfilter gremove gtake gdrop gtake-while gdrop-while gflatten ggroup gmerge gmap gstate-filter gdelete gdelete-neighbor-dups gindex gselect) (export generator->list generator->reverse-list generator->vector generator->vector! generator->string generator-fold generator-map->list generator-for-each generator-find generator-count generator-any generator-every generator-unfold) (export make-accumulator count-accumulator list-accumulator reverse-list-accumulator vector-accumulator reverse-vector-accumulator vector-accumulator! string-accumulator bytevector-accumulator bytevector-accumulator! sum-accumulator product-accumulator) (include "158.scm") )
false
133433da026a76718a374a688f3d6a9cff026aa9
6b961ef37ff7018c8449d3fa05c04ffbda56582b
/bbn_cl/mach/cl/build-load.scm
6e93357a969266c9c42965704302963ffb360e45
[]
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,985
scm
build-load.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. ;;; ;;; ******** ;;; ;;; (define *common-lisp-filenames* '()) (define *load-compiled-commonlisp?* #f) (define *build-code* (vector-cons 512 '())) (define *build-index* 0) ;;; ;;; filename is just the root. ;;; (define prim-file-write-date (make-primitive-procedure 'cl-file-write-date)) (define (build-load filename environment) (set! *common-lisp-filenames* (cons filename *common-lisp-filenames*)) (let ((bin (string-append filename ".bin")) (com (string-append filename ".com"))) (define (inform file) (newline) (princ ";;; Loading ") (prin1 file) file) (call-with-fasl-input-file (if *load-compiled-commonlisp?* (if (> (prim-file-write-date bin) (prim-file-write-date com)) (begin (newline) (princ ";;; Build Warning: ") (prin1 bin) (princ " is more recent than ") (prin1 com) (inform bin)) (inform com)) (inform bin)) (lambda (fd) (let load-loop ((scode (fasload-fd fd *package*))) (if (eq? scode eof-error-code) 'DONE (begin (vector-set! *build-code* *build-index* scode) (set! *build-index* (1+ *build-index*)) (scode-eval scode environment) (load-loop (fasload-fd fd *package*))))))))) (define (write-build-info) (let ((f (open-output-file "build-info.scm"))) (write `("Date:" ,(date) "Time:" ,(time)) f) (pp *common-lisp-filenames* f) (close-output-port f)) 'BUILD-INFORMATION-WRITTEN) (define (cl-cf input . options) (if *load-compiled-commonlisp?* (apply (access cf compiler-package) `(,input ,@options ,@'(touch #f))) (apply sf `(,input ,@options)))) (define (tcf input . options) (if *load-compiled-commonlisp?* (apply (access cf compiler-package) `(,input ,@options ,@'(touch #t))) (apply sf `(,input ,@options))))
false
361a633c0b4098f9c07acb44f2fb99899063316f
ee672a7d0e1e833a369316f5d0441f38b7fb7efb
/Implementation/metrics.scm
bb81336e9b0c7798808a25976ae2ddb140757123
[]
no_license
mvdcamme/WODA15
f2c558567519c1a5d6df3c50810e368c554a2b88
54f6258a7db73b8d3b96faff6fb70cf774924744
refs/heads/master
2021-01-16T21:23:14.456335
2015-11-05T10:08:43
2015-11-05T10:08:43
42,398,539
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,719
scm
metrics.scm
(module metrics racket (require "tracing.scm") (provide calculate-average-trace-length calculate-total-number-of-traces calculate-total-traces-length get-trace-executions) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; ; Metrics ; ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; Auxiliary functions ; (define (map-over-trace-tree tracer-context f) (define (2-ary-f id trace-node) (f trace-node)) (for-each f (tracer-context-trace-nodes tracer-context))) ; ; Total nr of traces ; (define (calculate-total-number-of-traces tracer-context) (let ((sum 0)) (define (inc-sum!) (set! sum (+ sum 1))) (map-over-trace-tree tracer-context (lambda (ignored) (inc-sum!))) sum)) ; ; Total trace length ; (define (calculate-total-traces-length tracer-context) (let ((sum 0)) (define (add-trace-length! trace-node) (set! sum (+ sum (length (get-instruction-list (trace-node-trace trace-node)))))) (define (get-instruction-list s-expression) (cddadr (caadr s-expression))) (map-over-trace-tree tracer-context add-trace-length!) (table-for-each (lambda (ignored mp-tail-trace-node) (add-trace-length! mp-tail-trace-node)) (tracer-context-mp-tails-dictionary tracer-context)) sum)) ; ; Average trace length ; (define (calculate-average-trace-length tracer-context) (let ((total-number-of-traces (calculate-total-number-of-traces tracer-context))) (if (= total-number-of-traces 0) "No traces were formed" (/ (calculate-total-traces-length tracer-context) total-number-of-traces)))) ; ; Trace executions ; (define (get-trace-executions tracer-context) (let ((label-traces '())) (define (add-trace-node-execution-info trace-node) (let ((binding (cons (trace-key-label (trace-node-trace-key trace-node)) (trace-node-executions trace-node)))) (set! label-traces (cons binding label-traces)))) (map-over-trace-tree tracer-context add-trace-node-execution-info) (list label-traces))) ; ; Resetting metrics ; (define (reset-metrics!) (reset-trace-duplication-metric!)))
false
7a81c409fc739cedf1eb13a48ac1c454a7f6fb88
68c4bab1f5d5228078d603066b6c6cea87fdbc7a
/lab/frozen/just-born/rifle/src/mzscheme/util/conditionals.ss
e6ae7e5d115a3dbe28f0be07fd4ed98d1d01255b
[]
no_license
felipelalli/micaroni
afab919dab304e21ba916aa6310dca102b1a04a5
741b628754b7c7085d3e68009a621242c2a1534e
refs/heads/master
2023-08-03T06:25:15.405861
2023-07-25T14:44:56
2023-07-25T14:44:56
537,536
2
1
null
null
null
null
UTF-8
Scheme
false
false
1,065
ss
conditionals.ss
(load "../little-error-control/little-error-control.ss") ; Verifica se n está entre a e b: ; (between n a b) ; ; Exemplos: ; (between 2 1 3) => #t ; (between 4 1 3) => #f ; (between 3 1 3) => #t (define-syntax between? (syntax-rules () ((between? n a b) (and (>= n a) (<= n b))))) ; Verifica se um número está dentro de um intervalo e, se sim, executa o corpo: ; (validate-range n a b corpo ...) ; a <= n <= b ; ; (validate-range 0 1 10 (display "oi") (display " tchau!")) ; => (erro fora-do-intervalo "0 deveria estar entre 1 e 10") ; ; (validate-range 2 1 10 (display "oi") (display " tchau!")) ; => oi tchau! (define-syntax validate-range (syntax-rules () ((valida-intervalo n a b) (between? n a b)) ((valida-intervalo n a b body ...) (if (not (between? n a b)) (make-error 'out-of-range (string-append (number->string n) " must be between " (number->string a) " and " (number->string b))) ;else (begin body ...)))))
true
c0905fc88611548a87e6790a3e513e7fd268c73d
a74932f6308722180c9b89c35fda4139333703b8
/edwin48/scsh/macros-helpers.scm
fb99b30104e598215a162f6a28a99f47cbfd4770
[]
no_license
scheme/edwin48
16b5d865492db5e406085e8e78330dd029f1c269
fbe3c7ca14f1418eafddebd35f78ad12e42ea851
refs/heads/master
2021-01-19T17:59:16.986415
2014-12-21T17:50:27
2014-12-21T17:50:27
1,035,285
39
10
null
2022-02-15T23:21:14
2010-10-29T16:08:55
Scheme
UTF-8
Scheme
false
false
1,437
scm
macros-helpers.scm
(define (command-name->scheme-name name) (symbol-append 'edwin-command$ name)) (define (variable-name->scheme-name name) (symbol-append 'edwin-variable$ name)) (define (mode-name->scheme-name name) (symbol-append 'edwin-mode$ name)) (define (list-ref/default list index default-value) (if (> (length list) index) (list-ref list index) default-value)) (define (expand-variable-definition buffer-local?) (lambda (form rename compare) (if (not (<= (length form) 6)) (syntax-error "DEFINE-VARIABLE name description value test normalization")) (let* ((%define (rename 'define)) (%make-variable (rename 'make-variable)) (name (list-ref form 1)) (scheme-name (variable-name->scheme-name name)) (description (list-ref/default form 2 #f)) (value (list-ref/default form 3 #f)) (test (list-ref/default form 4 #f)) (normalization (list-ref/default form 5 #f))) `(,%define ,scheme-name (,%make-variable ',name ,description ,value ,buffer-local? ,test ,normalization))))) (define (expand-variable-assignment form generator) (if (not (<= (length form) 4)) (syntax-error "ill-formed syntax" form) (generator (list-ref form 1) (list-ref/default form 2 #f) (list-ref/default form 3 #f))))
false
8894f2937fc3adb5753aaede1aa1b9e77255ac28
f08220a13ec5095557a3132d563a152e718c412f
/logrotate/skel/usr/share/guile/2.0/srfi/srfi-4.scm
b2e6f492865611bd4bf9a345814b735f61980f1f
[ "Apache-2.0" ]
permissive
sroettger/35c3ctf_chals
f9808c060da8bf2731e98b559babd4bf698244ac
3d64486e6adddb3a3f3d2c041242b88b50abdb8d
refs/heads/master
2020-04-16T07:02:50.739155
2020-01-15T13:50:29
2020-01-15T13:50:29
165,371,623
15
5
Apache-2.0
2020-01-18T11:19:05
2019-01-12T09:47:33
Python
UTF-8
Scheme
false
false
5,107
scm
srfi-4.scm
;;; srfi-4.scm --- Homogeneous Numeric Vector Datatypes ;; Copyright (C) 2001, 2002, 2004, 2006, 2009, 2010, ;; 2012, 2014 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 ;;; Author: Martin Grabmueller <[email protected]> ;;; Commentary: ;; This module exports the homogeneous numeric vector procedures as ;; defined in SRFI-4. They are fully documented in the Guile ;; Reference Manual. ;;; Code: (define-module (srfi srfi-4) #:use-module (rnrs bytevectors) #:export (;; Unsigned 8-bit vectors. u8vector? make-u8vector u8vector u8vector-length u8vector-ref u8vector-set! u8vector->list list->u8vector ;; Signed 8-bit vectors. s8vector? make-s8vector s8vector s8vector-length s8vector-ref s8vector-set! s8vector->list list->s8vector ;; Unsigned 16-bit vectors. u16vector? make-u16vector u16vector u16vector-length u16vector-ref u16vector-set! u16vector->list list->u16vector ;; Signed 16-bit vectors. s16vector? make-s16vector s16vector s16vector-length s16vector-ref s16vector-set! s16vector->list list->s16vector ;; Unsigned 32-bit vectors. u32vector? make-u32vector u32vector u32vector-length u32vector-ref u32vector-set! u32vector->list list->u32vector ;; Signed 32-bit vectors. s32vector? make-s32vector s32vector s32vector-length s32vector-ref s32vector-set! s32vector->list list->s32vector ;; Unsigned 64-bit vectors. u64vector? make-u64vector u64vector u64vector-length u64vector-ref u64vector-set! u64vector->list list->u64vector ;; Signed 64-bit vectors. s64vector? make-s64vector s64vector s64vector-length s64vector-ref s64vector-set! s64vector->list list->s64vector ;; 32-bit floating point vectors. f32vector? make-f32vector f32vector f32vector-length f32vector-ref f32vector-set! f32vector->list list->f32vector ;; 64-bit floating point vectors. f64vector? make-f64vector f64vector f64vector-length f64vector-ref f64vector-set! f64vector->list list->f64vector)) (cond-expand-provide (current-module) '(srfi-4)) ;; Need quasisyntax to do this effectively using syntax-case (define-macro (define-bytevector-type tag infix size) `(begin (define (,(symbol-append tag 'vector?) obj) (and (bytevector? obj) (eq? (array-type obj) ',tag))) (define (,(symbol-append 'make- tag 'vector) len . fill) (apply make-srfi-4-vector ',tag len fill)) (define (,(symbol-append tag 'vector-length) v) (let ((len (/ (bytevector-length v) ,size))) (if (integer? len) len (error "fractional length" v ',tag ,size)))) (define (,(symbol-append tag 'vector) . elts) (,(symbol-append 'list-> tag 'vector) elts)) (define (,(symbol-append 'list-> tag 'vector) elts) (let* ((len (length elts)) (v (,(symbol-append 'make- tag 'vector) len))) (let lp ((i 0) (elts elts)) (if (and (< i len) (pair? elts)) (begin (,(symbol-append tag 'vector-set!) v i (car elts)) (lp (1+ i) (cdr elts))) v)))) (define (,(symbol-append tag 'vector->list) v) (let lp ((i (1- (,(symbol-append tag 'vector-length) v))) (elts '())) (if (< i 0) elts (lp (1- i) (cons (,(symbol-append tag 'vector-ref) v i) elts))))) (define (,(symbol-append tag 'vector-ref) v i) (,(symbol-append 'bytevector- infix '-ref) v (* i ,size))) (define (,(symbol-append tag 'vector-set!) v i x) (,(symbol-append 'bytevector- infix '-set!) v (* i ,size) x)) (define (,(symbol-append tag 'vector-set!) v i x) (,(symbol-append 'bytevector- infix '-set!) v (* i ,size) x)))) (define-bytevector-type u8 u8 1) (define-bytevector-type s8 s8 1) (define-bytevector-type u16 u16-native 2) (define-bytevector-type s16 s16-native 2) (define-bytevector-type u32 u32-native 4) (define-bytevector-type s32 s32-native 4) (define-bytevector-type u64 u64-native 8) (define-bytevector-type s64 s64-native 8) (define-bytevector-type f32 ieee-single-native 4) (define-bytevector-type f64 ieee-double-native 8)
false
b60fb625a4c83c5218cee7e38cf43c1ac4ae9ded
a2c4df92ef1d8877d7476ee40a73f8b3da08cf81
/ch06-1-test.scm
7a9adfc8d0ad626afb063f0a8c21d4f88f27457e
[]
no_license
naoyat/reading-paip
959d0ec42b86bc01fe81dcc3589e3182e92a05d9
739fde75073af36567fcbdf3ee97e221b0f87c8a
refs/heads/master
2020-05-20T04:56:17.375890
2009-04-21T20:01:01
2009-04-21T20:01:01
176,530
1
0
null
null
null
null
UTF-8
Scheme
false
false
131
scm
ch06-1-test.scm
(require "./ch05-4") ; flatten (require "./ch06-1") (interactive-interpreter (prompt-generator) (compose flatten use-eliza-rules))
false
16ce11ec2cb154bda527946d6a58a23a0c54aae4
abc7bd420c9cc4dba4512b382baad54ba4d07aa8
/src/ws/testing/old_scheme_tests/tests_obj.ss
3d629d27bb1a7a427fbbe5f9f8208a3a1f1c8aa6
[ "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
1,556
ss
tests_obj.ss
;=============================================================================== (define tests_obj_basic '( '() (program '()) (program (define-class MyClass object (lambda () (void)) (fields public x y) (fields private a) (methods public (f1 (lambda (x) x)))) '()) ;(open-package System (System.WriteLine 1)) (open-package System (System.Console.WriteLine 1)) (program (define-class MyClass object (lambda () (void)) (fields public x)) (let ([a (new MyClass)]) (open-instance a MyClass '()))) (program (define-class MyClass object (lambda () (void)) (fields public x)) (let ([a (new MyClass)]) (open-instance a MyClass a.x))) (program (define-class MyClass object (lambda () (void)) (fields public x) (methods public (f1 (lambda () 1)))) (let ([a (new MyClass)]) (open-instance a MyClass (a.f1)))) )) ;=============================================================================== ;=============================================================================== ;=============================================================================== #!eof (program (define-class MyClass object (lambda () (void)) (fields public x y) (fields private a) (methods public (f1 (lambda (x) x)))) (let ([f (lambda (x) (add1 x))]) (f 3)))
false
7f4c8f06b581f08ba50de3ec700c4d513813f15a
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
/lib/rnrs/arithmetic/bitwise.scm
f9ee85e62cbb77c168299593f83b42f0141f4a71
[ "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
595
scm
bitwise.scm
;; -*- scheme -*- (library (rnrs arithmetic bitwise (6)) (export bitwise-not bitwise-and bitwise-ior bitwise-xor bitwise-if bitwise-bit-count bitwise-length bitwise-first-bit-set bitwise-bit-set? bitwise-copy-bit bitwise-bit-field bitwise-copy-bit-field bitwise-arithmetic-shift bitwise-arithmetic-shift-left bitwise-arithmetic-shift-right bitwise-rotate-bit-field bitwise-reverse-bit-field) (import (core) (core arithmetic)) ) ; [end] ;; end of file ;; Local Variables: ;; coding: utf-8-unix ;; End:
false
9b1dabfa3065e7c5c6dc013e3d2c9d59433232a2
f07bc117302b8959f25449863c6fdabdda510c48
/full-interp-extended-memo-lambda.scm
8d01c948e01998e10e009f09c7960ca1d6034a74
[ "MIT" ]
permissive
namin/clpsmt-miniKanren
3a1165a20dc1c50e4d568e2e493b701fb9f5caea
d2270aa14410805fa7068150bc2ab2f3bf9391b4
refs/heads/master
2022-03-10T07:05:21.950751
2022-02-26T23:54:05
2022-02-26T23:54:05
129,262,229
33
9
MIT
2021-08-03T16:02:50
2018-04-12T14:14:59
Scheme
UTF-8
Scheme
false
false
23,369
scm
full-interp-extended-memo-lambda.scm
;; Add memo-lambda form, and pass around a list of memo tables (which themselves are association lists) as an argument ;; ;; match is currently commented out, since threading through the table appears tedious and error prone ;; The definition of 'letrec' is based based on Dan Friedman's code, ;; using the "half-closure" approach from Reynold's definitional ;; interpreters. (define (evalo expr val) (fresh (tables-out) (eval-expo expr initial-env initial-tables tables-out val))) (define (eval-expo expr env tables-in tables-out val) (conde ((== `(quote ,val) expr) (== tables-in tables-out) (absento 'closure val) (absento 'prim val) (not-in-envo 'quote env)) ((numbero expr) (== tables-in tables-out) (== expr val)) ((symbolo expr) (== tables-in tables-out) (lookupo expr env val)) ((fresh (x body) (== `(lambda ,x ,body) expr) (== `(closure (lambda ,x ,body) ,env) val) (== tables-in tables-out) (paramso x) #| (conde ;; Variadic ((symbolo x)) ;; Multi-argument ((list-of-symbolso x))) |# (not-in-envo 'lambda env))) ;; McCarthy's 'amb' operator, with 'require' ;; See http://community.schemewiki.org/?amb ;; ;; (let ((a (amb 1 2)) ;; (b (amb 1 2))) ;; (require (< a b)) ;; (list a b)) ((fresh (e v) (== `(require ,e) expr) (== 'void val) (=/= #f v) (eval-expo e env tables-in tables-out v) (not-in-envo 'require env))) ;; McCarthy's 'amb' operator ;; See http://community.schemewiki.org/?amb ;; ;; (let ((a (amb 1 2)) ;; (b (amb 1 2))) ;; (require (< a b)) ;; (list a b)) ((fresh (e*) (== `(amb . ,e*) expr) (evaluate-oneo e* env tables-in tables-out val) (not-in-envo 'amb env))) ((fresh (x body name) ;; should memo-lambda take a user-defined name? ;; if not, how to lookup the right table for the resulting closure? (== `(memo-lambda ,name ,x ,body) expr) (== `(closure (memo-lambda ,name ,x ,body) ,env) val) ;; add a new, empty memo table for the new memo'd closure (== `((,name . ()) . ,tables-in) tables-out) (conde ;; Variadic ((symbolo x)) ;; Multi-argument ((list-of-symbolso x))) (not-in-envo 'memo-lambda env))) ((fresh (rator x rands body env^ a* env^^ tables^ tables^^) (== `(,rator . ,rands) expr) ;; variadic (symbolo x) (== `((val . (,x . ,a*)) . ,env^) env^^) ;; (== `((,x . (val . ,a*)) . ,env^) env^^) (eval-expo rator env tables-in tables^ `(closure (lambda ,x ,body) ,env^)) (eval-expo body env^^ tables^ tables^^ val) (eval-listo rands env tables^^ tables-out a*))) ((fresh (rator x* rands body env^ a* env^^ tables^ tables^^) (== `(,rator . ,rands) expr) ;; Multi-argument (eval-expo rator env tables-in tables^ `(closure (lambda ,x* ,body) ,env^)) (eval-listo rands env tables^ tables^^ a*) (ext-env*o x* a* env^ env^^) (eval-expo body env^^ tables^^ tables-out val))) ((fresh (rator x* rands body env^ a* tables^ tables^^ name) (== `(,rator . ,rands) expr) ;; Multi-argument memo-lambda closure (eval-expo rator env tables-in tables^ `(closure (memo-lambda ,name ,x* ,body) ,env^)) (eval-listo rands env tables^ tables^^ a*) (fresh (table entry) ;; look up the memo table in 'tables^^' corresponding to 'name'. ;; there should be a table, since 'memo-lambda' adds an association of the name mapped to the empty table (find-tableo tables^^ name table) ;; needed for SMT?? ;; purge-M-inc-models z/purge ;; z/check ;; look up the arguments to the memo'd closure, 'a*', in the resulting table: (table-lookupo a* table entry) (conde ((== 'in-progress entry) ;; fail, since the recursive function has been called ;; again with the same arguments, before the original call ;; has finished (divergent computation) ;; fail! (== #f #t)) ((== `(memo-value ,val) entry) ;; if 'a*' is associated with '(memo-value val)', then the value of the call is 'val' (== tables^^ tables-out) ) ((== 'no-entry entry) ;; if 'a*' does not yet have an entry in the table, (fresh (env^^ in-progress-table table^ final-value-table new-tables new-tables^) ;; associate 'a*' with 'in-progress' in an extended table, and update a new tables to use the "in-progress" table (== `((,a* in-progress) . ,table) in-progress-table) (== `((,name . ,in-progress-table) . ,tables^^) new-tables) ;; associate 'a*' with '(memo-value val)', (== `((,a* (memo-value ,val)) . ,table^) final-value-table) ;; unify the updated table with 'tables-out' (== `((,name . ,final-value-table) . ,new-tables^) tables-out) ;; let the result of evaluating the body of the memo-closure be 'val', as usual (this is just the normal evaluation of a procedure call) (ext-env*o x* a* env^ env^^) (eval-expo body env^^ new-tables new-tables^ val) ;; look up the memo table for name, (find-tableo new-tables^ name table^) )))))) ((fresh (rator x* rands a* prim-id tables^ tables^^) (== `(,rator . ,rands) expr) (eval-expo rator env tables-in tables^ `(prim . ,prim-id)) (eval-primo prim-id a* val) (eval-listo rands env tables^ tables-out a*))) #| ((handle-matcho expr env tables-in tables-out val)) |# ((fresh (b* letrec-body) (== `(letrec ,b* ,letrec-body) expr) (not-in-envo 'letrec env) (eval-letreco b* letrec-body env tables-in tables-out val))) #| ((fresh (p-name x body letrec-body) ;; single-function variadic letrec version (== `(letrec ((,p-name (lambda ,x ,body))) ,letrec-body) expr) (conde ; Variadic ((symbolo x)) ; Multiple argument ((list-of-symbolso x))) (not-in-envo 'letrec env) (eval-expo letrec-body `((,p-name . (rec . (lambda ,x ,body))) . ,env) tables-in tables-out val))) |# ((fresh (begin-body) (== `(begin . ,begin-body) expr) (eval-begino begin-body env tables-in tables-out val) (not-in-envo 'begin env))) ((fresh (x e body a env^ tables^) (== `(let ((,x ,e)) ,body) expr) (symbolo x) (ext-envo x a env env^) (eval-expo e env tables-in tables^ a) (eval-expo body env^ tables^ tables-out val))) ((prim-expo expr env tables-in tables-out val)) )) (define empty-env '()) (define (evaluate-oneo e* env tables-in tables-out val) (fresh (e e-rest) (== `(,e . ,e-rest) e*) (conde ((eval-expo e env tables-in tables-out val)) ((evaluate-oneo e-rest env tables-in tables-out val))))) (define (eval-begino begin-body env tables-in tables-out val) (conde ((fresh (e) (== `(,e) begin-body) (== tables-in tables-out) (eval-expo e env tables-in tables-out val))) ((fresh (e e1 e-rest tables^ ignore-val) (== `(,e ,e1 . ,e-rest) begin-body) (eval-expo e env tables-in tables^ ignore-val) (eval-begino `(,e1 . ,e-rest) env tables^ tables-out val))))) (define (lookup-reco k renv x b* t) (conde ((== '() b*) (k)) ((fresh (b*-rest p-name lam-expr) (== `((,p-name . ,lam-expr) . ,b*-rest) b*) (conde ((== p-name x) (== `(closure ,lam-expr ,renv) t)) ((=/= p-name x) (lookup-reco k renv x b*-rest t))))))) (define (lookupo x env t) (conde ((fresh (y b rest) (== `((val . (,y . ,b)) . ,rest) env) (conde ((== x y) (== b t)) ((=/= x y) (lookupo x rest t))))) ((fresh (b* rest) (== `((rec . ,b*) . ,rest) env) (lookup-reco (lambda () (lookupo x rest t)) env x b* t))))) #| (define (lookupo x env t) (fresh (y b rest) (== `((,y . ,b) . ,rest) env) (conde ((== x y) (conde ((== `(val . ,t) b)) ((fresh (lam-expr) (== `(rec . ,lam-expr) b) (== `(closure ,lam-expr ,env) t))))) ((=/= x y) (lookupo x rest t))))) |# (define (not-in-envo x env) (conde ((== empty-env env)) ((fresh (y b rest) (== `((val . (,y . ,b)) . ,rest) env) (=/= x y) (not-in-envo x rest))) ((fresh (b* rest) (== `((rec . ,b*) . ,rest) env) (not-in-env-reco x b* rest))))) (define (not-in-env-reco x b* env) (conde ((== '() b*) (not-in-envo x env)) ((fresh (p-name lam-expr b*-rest) (== `((,p-name . ,lam-expr) . ,b*-rest) b*) (=/= p-name x) (not-in-env-reco x b*-rest env))))) #| (define (not-in-envo x env) (conde ((== empty-env env)) ((fresh (y b rest) (== `((,y . ,b) . ,rest) env) (=/= y x) (not-in-envo x rest))))) |# (define (eval-letreco b* letrec-body env tables-in tables-out val) (let loop ((b* b*) (rb* '()) (tables tables-in)) (conde ((== '() b*) (eval-expo letrec-body `((rec . ,rb*) . ,env) tables tables-out val)) ((fresh (p-name x body b*-rest) (== `((,p-name (lambda ,x ,body)) . ,b*-rest) b*) (symbolo p-name) (paramso x) (loop b*-rest `((,p-name . (lambda ,x ,body)) . ,rb*) tables))) ((fresh (p-name name x body b*-rest tables^) (== `((,p-name (memo-lambda ,name ,x ,body)) . ,b*-rest) b*) (symbolo p-name) (paramso x) (== `((,name . ()) . ,tables) tables^) (loop b*-rest `((,p-name . (memo-lambda ,name ,x ,body)) . ,rb*) tables^)))))) (define (paramso params) (conde ; Multiple argument ((list-of-paramso params)) ; Variadic ((symbolo params)))) (define (not-in-paramso x params) (conde ((== '() params)) ((fresh (a d) (== `(,a . ,d) params) (=/= a x) (not-in-paramso x d))))) (define (list-of-paramso los) (conde ((== '() los)) ((fresh (a d) (== `(,a . ,d) los) (symbolo a) (list-of-paramso d) (not-in-paramso a d))))) (define (find-tableo tables table-name table) (fresh (tn t rest) (== `((,tn . ,t) . ,rest) tables) (conde ((== tn table-name) (== t table)) ((=/= tn table-name) (find-tableo rest table-name table))))) (define (table-lookupo x table entry) (conde ((== '() table) (== 'no-entry entry)) ((fresh (y v rest) (== `((,y ,v) . ,rest) table) (conde ((== x y) (== v entry)) ((=/= x y) (table-lookupo x rest entry))))))) (define (eval-listo expr env tables-in tables-out val) (conde ((== '() expr) (== tables-in tables-out) (== '() val)) ((fresh (a d v-a v-d tables^) (== `(,a . ,d) expr) (== `(,v-a . ,v-d) val) (eval-expo a env tables-in tables^ v-a) (eval-listo d env tables^ tables-out v-d))))) ;; need to make sure lambdas are well formed. ;; grammar constraints would be useful here!!! (define (list-of-symbolso los) (conde ((== '() los)) ((fresh (a d) (== `(,a . ,d) los) (symbolo a) (list-of-symbolso d))))) (define (ext-envo x a env out) (fresh () (== `((val . (,x . ,a)) . ,env) out) (symbolo x))) #| (define (ext-envo x a env out) (fresh () (== `((,x . (val . ,a)) . ,env) out) (symbolo x))) |# (define (ext-env*o x* a* env out) (conde ((== '() x*) (== '() a*) (== env out)) ((fresh (x a dx* da* env2) (== `(,x . ,dx*) x*) (== `(,a . ,da*) a*) (== `((val . (,x . ,a)) . ,env) env2) (symbolo x) (ext-env*o dx* da* env2 out))))) #| (define (ext-env*o x* a* env out) (conde ((== '() x*) (== '() a*) (== env out)) ((fresh (x a dx* da* env2) (== `(,x . ,dx*) x*) (== `(,a . ,da*) a*) (== `((,x . (val . ,a)) . ,env) env2) (symbolo x) (ext-env*o dx* da* env2 out))))) |# (define (eval-primo prim-id a* val) (conde [(== prim-id 'cons) (fresh (a d) (== `(,a ,d) a*) (== `(,a . ,d) val))] [(== prim-id 'car) (fresh (d) (== `((,val . ,d)) a*) (=/= 'closure val))] [(== prim-id 'cdr) (fresh (a) (== `((,a . ,val)) a*) (=/= 'closure a))] [(== prim-id 'not) (fresh (b) (== `(,b) a*) (conde ((=/= #f b) (== #f val)) ((== #f b) (== #t val))))] [(== prim-id 'equal?) (fresh (v1 v2) (== `(,v1 ,v2) a*) (conde ((== v1 v2) (== #t val)) ((=/= v1 v2) (== #f val))))] ;; FIXME (webyrd) -- symbol?, and perhaps other type predicates, doesn't handle booleans (fails) [(== prim-id 'symbol?) (fresh (v) (== `(,v) a*) (conde ((symbolo v) (== #t val)) ((numbero v) (== #f val)) ((fresh (a d) (== `(,a . ,d) v) (== #f val)))))] [(== prim-id 'null?) (fresh (v) (== `(,v) a*) (conde ((== '() v) (== #t val)) ((=/= '() v) (== #f val))))] [(conde [(== prim-id '+)] [(== prim-id '-)] [(== prim-id '*)] [(== prim-id '/)]) (fresh (a1 a2) (== `(,a1 ,a2) a*) ;; we could use list-of-numbero instead ;; but it causes more divergence with run* ;; (list-of-numbero a*) (numbero a1) (numbero a2) (numbero val) (z/assert `(= ,val (,prim-id ,a1 ,a2))))] [(== prim-id '!=) (fresh (a1 a2) (== `(,a1 ,a2) a*) (numbero a1) (numbero a2) (conde [(== #t val) (z/assert `(not (= ,a1 ,a2)))] [(== #f val) (z/assert `(= ,a1 ,a2))]))] [(conde [(== prim-id '=)] [(== prim-id '>)] [(== prim-id '>=)] [(== prim-id '<)] [(== prim-id '<=)]) (fresh (a1 a2) (== `(,a1 ,a2) a*) ;; we could use list-of-numbero instead ;; but it causes more divergence with run* ;; (list-of-numbero a*) (numbero a1) (numbero a2) (conde [(== #t val) (z/assert `(,prim-id ,a1 ,a2))] [(== #f val) (z/assert `(not (,prim-id ,a1 ,a2)))]))] )) (define (prim-expo expr env tables-in tables-out val) (conde ((boolean-primo expr env tables-in tables-out val)) ((and-primo expr env tables-in tables-out val)) ((or-primo expr env tables-in tables-out val)) ((if-primo expr env tables-in tables-out val)))) (define (boolean-primo expr env tables-in tables-out val) (fresh () (== tables-in tables-out) (conde ((== #t expr) (== #t val)) ((== #f expr) (== #f val))))) (define (and-primo expr env tables-in tables-out val) (fresh (e*) (== `(and . ,e*) expr) (not-in-envo 'and env) (ando e* env tables-in tables-out val))) (define (ando e* env tables-in tables-out val) (conde ((== '() e*) (== #t val) (== tables-in tables-out)) ((fresh (e) (== `(,e) e*) (eval-expo e env tables-in tables-out val))) ((fresh (e1 e2 e-rest v) (== `(,e1 ,e2 . ,e-rest) e*) (conde ((== #f v) (== #f val) (eval-expo e1 env tables-in tables-out v)) ((=/= #f v) (fresh (tables^) (eval-expo e1 env tables-in tables^ v) (ando `(,e2 . ,e-rest) env tables^ tables-out val)))))))) (define (or-primo expr env tables-in tables-out val) (fresh (e*) (== `(or . ,e*) expr) (not-in-envo 'or env) (oro e* env tables-in tables-out val))) (define (oro e* env tables-in tables-out val) (conde ((== '() e*) (== #f val) (== tables-in tables-out)) ((fresh (e) (== `(,e) e*) (eval-expo e env tables-in tables-out val))) ((fresh (e1 e2 e-rest v) (== `(,e1 ,e2 . ,e-rest) e*) (conde ((=/= #f v) (== v val) (eval-expo e1 env tables-in tables-out v)) ((== #f v) (fresh (tables^) (eval-expo e1 env tables-in tables^ v) (oro `(,e2 . ,e-rest) env tables^ tables-out val)))))))) (define (if-primo expr env tables-in tables-out val) (fresh (e1 e2 e3 t tables^) (== `(if ,e1 ,e2 ,e3) expr) (not-in-envo 'if env) (eval-expo e1 env tables-in tables^ t) (conde ((=/= #f t) (eval-expo e2 env tables^ tables-out val)) ((== #f t) (eval-expo e3 env tables^ tables-out val))))) (define initial-env `((val . (list . (closure (lambda x x) ,empty-env))) (val . (not . (prim . not))) (val . (equal? . (prim . equal?))) (val . (symbol? . (prim . symbol?))) (val . (cons . (prim . cons))) (val . (null? . (prim . null?))) (val . (car . (prim . car))) (val . (cdr . (prim . cdr))) (val . (+ . (prim . +))) (val . (- . (prim . -))) (val . (* . (prim . *))) (val . (/ . (prim . /))) (val . (= . (prim . =))) (val . (!= . (prim . !=))) (val . (> . (prim . >))) (val . (>= . (prim . >=))) (val . (< . (prim . <))) (val . (<= . (prim . <=))) . ,empty-env)) #| (define initial-env `((list . (val . (closure (lambda x x) ,empty-env))) (not . (val . (prim . not))) (equal? . (val . (prim . equal?))) (symbol? . (val . (prim . symbol?))) (cons . (val . (prim . cons))) (null? . (val . (prim . null?))) (car . (val . (prim . car))) (cdr . (val . (prim . cdr))) (+ . (val . (prim . +))) (- . (val . (prim . -))) (* . (val . (prim . *))) (/ . (val . (prim . /))) (= . (val . (prim . =))) (!= . (val . (prim . !=))) (> . (val . (prim . >))) (>= . (val . (prim . >=))) (< . (val . (prim . <))) (<= . (val . (prim . <=))) . ,empty-env)) |# (define initial-tables '()) #| (define handle-matcho (lambda (expr env tables-in tables-out val tables^) (fresh (against-expr mval clause clauses) (== `(match ,against-expr ,clause . ,clauses) expr) (not-in-envo 'match env) (eval-expo against-expr env tables-in tables^ mval) (match-clauses mval `(,clause . ,clauses) env tables^ tables-out val)))) |# (define (not-symbolo t) (conde ((== #f t)) ((== #t t)) ((== '() t)) ((numbero t)) ((fresh (a d) (== `(,a . ,d) t))))) (define (not-numbero t) (conde ((== #f t)) ((== #t t)) ((== '() t)) ((symbolo t)) ((fresh (a d) (== `(,a . ,d) t))))) (define (self-eval-literalo t) (conde ((numbero t)) ((booleano t)))) (define (literalo t) (conde ((numbero t)) ((symbolo t) (=/= 'closure t)) ((booleano t)) ((== '() t)))) (define (booleano t) (conde ((== #f t)) ((== #t t)))) #| (define (regular-env-appendo env1 env2 env-out) (conde ((== empty-env env1) (== env2 env-out)) ((fresh (y v rest res) (== `((,y . (val . ,v)) . ,rest) env1) (== `((,y . (val . ,v)) . ,res) env-out) (regular-env-appendo rest env2 res))))) (define (match-clauses mval clauses env tables-in tables-out val) (fresh (p result-expr d penv) (== `((,p ,result-expr) . ,d) clauses) (conde ((fresh (env^) (p-match p mval '() penv) (regular-env-appendo penv env env^) (eval-expo result-expr env^ tables-in tables-out val))) ((p-no-match p mval '() penv) (match-clauses mval d env val))))) (define (var-p-match var mval penv penv-out) (fresh (val) (symbolo var) (=/= 'closure mval) (conde ((== mval val) (== penv penv-out) (lookupo var penv val)) ((== `((,var . (val . ,mval)) . ,penv) penv-out) (not-in-envo var penv))))) (define (var-p-no-match var mval penv penv-out) (fresh (val) (symbolo var) (=/= mval val) (== penv penv-out) (lookupo var penv val))) (define (p-match p mval penv penv-out) (conde ((self-eval-literalo p) (== p mval) (== penv penv-out)) ((var-p-match p mval penv penv-out)) ((fresh (var pred val) (== `(? ,pred ,var) p) (conde ((== 'symbol? pred) (symbolo mval)) ((== 'number? pred) (numbero mval))) (var-p-match var mval penv penv-out))) ((fresh (quasi-p) (== (list 'quasiquote quasi-p) p) (quasi-p-match quasi-p mval penv penv-out))))) (define (p-no-match p mval penv penv-out) (conde ((self-eval-literalo p) (=/= p mval) (== penv penv-out)) ((var-p-no-match p mval penv penv-out)) ((fresh (var pred val) (== `(? ,pred ,var) p) (== penv penv-out) (symbolo var) (conde ((== 'symbol? pred) (conde ((not-symbolo mval)) ((symbolo mval) (var-p-no-match var mval penv penv-out)))) ((== 'number? pred) (conde ((not-numbero mval)) ((numbero mval) (var-p-no-match var mval penv penv-out))))))) ((fresh (quasi-p) (== (list 'quasiquote quasi-p) p) (quasi-p-no-match quasi-p mval penv penv-out))))) (define (quasi-p-match quasi-p mval penv penv-out) (conde ((== quasi-p mval) (== penv penv-out) (literalo quasi-p)) ((fresh (p) (== (list 'unquote p) quasi-p) (p-match p mval penv penv-out))) ((fresh (a d v1 v2 penv^) (== `(,a . ,d) quasi-p) (== `(,v1 . ,v2) mval) (=/= 'unquote a) (quasi-p-match a v1 penv penv^) (quasi-p-match d v2 penv^ penv-out))))) (define (quasi-p-no-match quasi-p mval penv penv-out) (conde ((=/= quasi-p mval) (== penv penv-out) (literalo quasi-p)) ((fresh (p) (== (list 'unquote p) quasi-p) (=/= 'closure mval) (p-no-match p mval penv penv-out))) ((fresh (a d) (== `(,a . ,d) quasi-p) (=/= 'unquote a) (== penv penv-out) (literalo mval))) ((fresh (a d v1 v2 penv^) (== `(,a . ,d) quasi-p) (=/= 'unquote a) (== `(,v1 . ,v2) mval) (conde ((quasi-p-no-match a v1 penv penv^)) ((quasi-p-match a v1 penv penv^) (quasi-p-no-match d v2 penv^ penv-out))))))) |#
false
223d65081a15fcac974ae96b31039111f0d100c9
018a7ce673c5be3cf3df61bd5c5036581d6646a7
/spec/libcapture.scm
f601bdbee2922b223ea6a1f9e3a842e1c04cfa11
[ "MIT" ]
permissive
iwillspeak/feersum
e857deec2b8683960f9ac6d1f395fb5f625204a8
1602e8333aa11c0335c9775c0ab49bf01389ba98
refs/heads/main
2023-08-07T17:15:19.843607
2023-06-20T06:28:28
2023-06-20T06:28:28
223,348,583
31
2
MIT
2023-06-10T21:29:11
2019-11-22T07:33:04
F#
UTF-8
Scheme
false
false
238
scm
libcapture.scm
(define-library (lib capture) (export testit) (begin (define testit "broken") (let ((replacement "pass")) (set! testit replacement)))) (import (lib capture) (scheme write)) (display testit)(newline)
false
2b1a9fd8bfe04b093317f8b3897b2d3b3b64a8cf
b8034221175e02a02307ef3efef129badecda527
/tests/merge-rich-string.scm
4a7b773f6dcb0f54dddd74c49da203620b1d828d
[]
no_license
nobody246/xlsxWriterScm
ded2410db122dfbe8bbb5e9059239704ee9a5b32
d02ed10c3e8c514cc1b6a9eaf793a2cde34c4c47
refs/heads/master
2022-04-27T23:29:45.258892
2022-04-15T22:04:02
2022-04-15T22:04:02
153,357,109
0
1
null
null
null
null
UTF-8
Scheme
false
false
1,060
scm
merge-rich-string.scm
(use xlsxwriterscm) (create-workbook "merge-rich-string.xlsx") (define-formats '((red ((set-font-color #xFF0000) (set-align ($align 'center)) (set-align ($align 'vertical-center)))) (blue ((set-font-color #x0000FF) (set-align ($align 'center)) (set-align ($align 'vertical-center)))) (merge-format ((set-bold) (set-border ($border 'thin)) (set-align ($align 'center)) (set-align ($align 'vertical-center)))) (none ()))) (add-worksheet "") (set-pos 1 1) (set-format 'merge-format) (worksheet-merge-range "" 1 1 4 3) (worksheet-write-rich-string `((,($formats 'none) "This is ") (,($formats 'red) "red ") (,($formats 'none) "and this is ") (,($formats 'blue) "blue."))) (set-format 'none) (close-workbook) (exit)
false
4236f97fd0c5a8bba371519fa929282e88427ab8
2f17124e3438460e41d3f6242b2bf047ed80fbee
/lab2/aufgabe8.scm
3a20a02f5a9fa5d35f20d224d4bc6535154023a0
[]
no_license
truenicfel/scheme
e5b2dbd532038c45eba464c35c33c0d4f06efe55
babbf5d895c0817b180fb2da3c8ce0d46434cda9
refs/heads/master
2020-03-23T07:29:56.483376
2018-07-29T11:08:15
2018-07-29T11:08:15
141,275,259
0
0
null
null
null
null
UTF-8
Scheme
false
false
400
scm
aufgabe8.scm
;;; Aufgabe 8 ;;; (define (union-set set1 set2) (cond ((null? set1) set2) ((null? set2) set1) (else (cond ((< (car set1) (car set2)) (cons (car set1) (union-set (cdr set1) set2))) ((> (car set1) (car set2)) (cons (car set2) (union-set set1 (cdr set2)))) (else (union-set set1 (cdr set2))) ) ) ) ) (union-set (list 1 2 3 4 5) (list 1 2 3 12))
false
1777a1c96dc84699ed583da7dea9d0c1a1ce60de
66ee0dd65a25484c064b09edb360a9b2a0217883
/fib.ss
8e503d16b9f251eff8299a0dfc73c2fbe41201c8
[]
no_license
Liudx1985/Lisp-Scheme-Haskell
337c1faceed9318905a7235379163bbe258d0bd0
f874b92b86cabc09ead4f6c711e7550561a9d628
refs/heads/master
2016-09-06T03:37:02.977060
2015-02-02T02:17:53
2015-02-02T02:17:53
18,743,986
2
0
null
null
null
null
UTF-8
Scheme
false
false
1,093
ss
fib.ss
;;; simple function ;;; uses trace-lambda to show the nesting (define sign (lambda (x) (cond [(> x 0) x] [(= x 0) 0] [else (- x)]))) (define sum_int (trace-lambda sum_int (x) (if (= x 0) 0 (+ x (sum_int (- x 1)))))) ;tail-recursive fibonacci (define fib-iter (trace-lambda fib-iter (a b n) (if (<= n 0) b (fib-iter b (+ a b) (- n 1) )))) (define (fib n) (fib-iter '1 '1 n)) ;; Same as \map\ procedure (define fmap (lambda (f ls) (if (null? ls) '() (cons (f (car ls)) (fmap f (cdr ls)))))) (define (sum a term next b) (define (iter it result) (if (> it b) result (iter (next it) (+ (term it) result)))) (iter a 0)) (require racket/trace) (define/match (fact n) [(0) 1] [(n) (* n (fact (sub1 n)))]) (trace fact) ; start to trace (fact 10) (untrace fact); stop tract. (fact 4) #| #lang lazy ;; An infinite list: (define fibs (list* 1 1 (map + fibs (cdr fibs)))) |#
false
853ad5c321261861031dbf1584695c300e329031
ecfd9ed1908bdc4b099f034b121f6e1fff7d7e22
/old1/sicp/3/p71.scm
4996bfed1dcae37b2a43a9f045500a72d9385933
[ "MIT" ]
permissive
sKabYY/palestra
36d36fc3a03e69b411cba0bc2336c43b3550841c
06587df3c4d51961d928bd8dd64810c9da56abf4
refs/heads/master
2021-12-14T04:45:20.661697
2021-11-25T08:29:30
2021-11-25T08:29:30
12,856,067
6
3
null
null
null
null
UTF-8
Scheme
false
false
834
scm
p71.scm
(load "weighted-pairs.scm") ; failed! TODO (define (sumofexpt3 i j) (+ (expt i 3) (expt j 3))) (define ipairs (weighted-sorted-pairs integers integers sumofexpt3)) (define (filter-the-same stream) (define (iter prev prev-count s) (cond ((= prev (stream-car s)) (iter prev (+ prev-count 1) (stream-cdr s))) ((= prev-count 1) (iter (stream-car s) 1 (stream-cdr s))) (else (cons prev (delay (iter (stream-car s) 1 (stream-cdr s))))))) (iter (stream-car stream) 1 (stream-cdr stream))) ;(define ramanujan (filter-the-same sums)) (stream-for-n (lambda (x) (if (> (car x) 1) (println x) (void))) ipairs 20) ;(stream-for-n println ramanujan 6)
false
8ef0fc5e01705002bf7bc8ebfabb8f3738d37956
7d9eccbe82e84e7e965133bb70caee2c7ba35f71
/scheme/sequent1.scm
b1304a62813b2745c19e7efdebec3a9ec9977b94
[]
no_license
xieyuheng/sequent1
15975abfdf332d44d0494230226695e0099a967a
9aa8b843881414d8c0eb129783902a37c0aeb2dd
refs/heads/master
2021-01-21T04:55:44.285279
2016-04-24T07:44:23
2016-04-24T07:44:23
54,508,452
6
1
null
null
null
null
UTF-8
Scheme
false
false
8,707
scm
sequent1.scm
;; module system of guile ;; using http://synthcode.com/scheme/match.scm (use-modules (ice-9 match)) (define-syntax cat (syntax-rules () [(cat (str . args)) (format #t str . args)] [(cat (str . args) (str2 . args2) ...) (string-append (cat (str . args)) (cat (str2 . args2) ...))])) (define-syntax orz (syntax-rules () [(orz . body) (error (cat . body))])) (define-syntax note (syntax-rules () [(note . body) '()])) (use-modules (ice-9 pretty-print)) (define-syntax test (syntax-rules () [(test b1 b2) (if (equal? b1 b2) #t (let () (cat ("\n")) (cat ("<test-fail-report-begin>\n")) (cat ("<actual-form> :\n")) (pretty-print (quote b1)) (cat ("<actual-value> :\n")) (pretty-print b1) (cat ("<expect-form> :\n")) (pretty-print (quote b2)) (cat ("<expect-value> :\n")) (pretty-print b2) (orz ("<test-fail-report-end>\n"))))])) (define (left-of s l) ;; sexp, list -> list (cond [(equal? s (car l)) '()] [else (cons (car l) (left-of s (cdr l)))])) (define (right-of s l) ;; sexp, list -> list (cond [(equal? s (car l)) (cdr l)] [else (right-of s (cdr l))])) (define (find-char c s) ;; char, string -> curser or #f (find-char/curser c s 0)) (define (find-char/curser c s curser) ;; char, string, curser -> curser or #f (if (>= curser (string-length s)) #f (let ([c0 (substring s curser (+ 1 curser))]) (if (equal? c c0) curser (find-char/curser c s (+ 1 curser)))))) (define (parse/arrow s) ;; sexp-arrow -> formal-arrow (list (parse/cedent 0 (left-of '-> s)) (parse/cedent 0 (right-of '-> s)))) (define (parse/cedent default-level s) ;; default-level, sexp-cedent -> formal-cedent (match s ['() '()] [(h . r) (cons (parse/dispatch default-level h) (parse/cedent default-level r))])) (define (parse/dispatch default-level v) ;; default-level, sexp-form -> formal-form (let ([var? (lambda (v) (and (symbol? v) (equal? ":" (substring (symbol->string v) 0 1))))] [name? (lambda (v) (and (symbol? v) (not (eq? ":" (substring (symbol->string v) 0 1)))))] [arrow? (lambda (v) (and (list? v) (member '-> v)))] [im-bind? (lambda (v) (and (list? v) (member ': v)))] [ex-bind? (lambda (v) (and (list? v) (member '@ v)))]) (cond [(var? v) (list 'v (parse/var default-level v))] [(name? v) (list 'n v)] [(arrow? v) (list 'a (parse/arrow v))] [(im-bind? v) (list 'b (list (parse/cedent 1 (left-of ': v)) (parse/cedent 0 (right-of ': v)) #f))] [(ex-bind? v) (list 'b (list (parse/cedent 1 (left-of '@ v)) (parse/cedent 0 (right-of '@ v)) #t))] [else (orz ("parse/dispatch can not handle sexp-form:~a" v))]))) (define (parse/var default-level v) ;; default-level, symbol -> formal-var (let* ([str (symbol->string v)] [cursor (find-char "^" str)]) (if cursor (list (string->symbol (substring str 0 cursor)) (string->number (substring str (+ 1 cursor)))) (list v default-level)))) (test (list (parse/arrow '(natural natural -> natural)) (parse/arrow '(natural natural -> (natural natural -> natural) natural)) (parse/arrow '(:m zero -> :m)) (parse/arrow '(:m :n succ -> :m :n recur succ)) (parse/arrow '((:t : type) :t -> type)) (parse/arrow '((:t @ type) :t -> type)) (parse/arrow '((:t^2 : type) :t -> type)) (parse/arrow '((:t1 :t2^2 :t3^0 : j k) :t -> type)) (parse/arrow '((:t^2 @ type) :t -> type))) '((((n natural) (n natural)) ((n natural))) (((n natural) (n natural)) ((a (((n natural) (n natural)) ((n natural)))) (n natural))) (((v (:m 0)) (n zero)) ((v (:m 0)))) (((v (:m 0)) (v (:n 0)) (n succ)) ((v (:m 0)) (v (:n 0)) (n recur) (n succ))) (((b (((v (:t 1))) ((n type)) #f)) (v (:t 0))) ((n type))) (((b (((v (:t 1))) ((n type)) #t)) (v (:t 0))) ((n type))) (((b (((v (:t 2))) ((n type)) #f)) (v (:t 0))) ((n type))) (((b (((v (:t1 1)) (v (:t2 2)) (v (:t3 0))) ((n j) (n k)) #f)) (v (:t 0))) ((n type))) (((b (((v (:t 2))) ((n type)) #t)) (v (:t 0))) ((n type))))) (define (pass1/arrow f s) ;; formal-arrow, scope -> arrow (match f [(fac fsc) (match (pass1/cedent fac s) [(ac s0) (match (pass1/cedent fsc s0) [(sc s1) (list ac sc)])])])) (define (pass1/cedent f s) ;; formal-cedent, scope -> (cedent scope) (match f ['() (list '() s)] [(h . r) (match (pass1/dispatch h s) [(v s0) (match (pass1/cedent r s0) [(c s1) (list (cons v c) s1)])])])) (define (pass1/dispatch f s) ;; formal-form, scope -> (form scope) (match f [('v v) (pass1/var v s)] [('n n) (list (list 'name n) s)] [('a a) (list (list 'arrow (pass1/arrow a s)) s)] [('b b) (pass1/bind b s)])) (define (pass1/var v s) ;; formal-var, scope -> (var scope) (match v [(symbol level) (let ([found (assq symbol s)]) (if found (let ([old (cdr found)]) (list (list 'var (list old level)) s)) (let ([new (vector symbol '())]) (list (list 'var (list new level)) (cons (cons symbol new) s)))))])) (define (pass1/bind b s) ;; formal-bind, scope -> (bind scope) (match b [(fvs fc leave?) (match (pass1/cedent fvs s) [(vs s0) (match (pass1/cedent fc s0) ;; this means vars in fvs can occur in fc [(c s1) (list (list 'bind (list vs c leave?)) s1)])])])) (test (map (lambda (x) (pass1/arrow x '())) (list (parse/arrow '(natural natural -> natural)) (parse/arrow '(natural natural -> (natural natural -> natural) natural)) (parse/arrow '(:m zero -> :m)) (parse/arrow '(:m :n succ -> :m :n recur succ)) (parse/arrow '((:t : type) :t -> type)) (parse/arrow '((:t @ type) :t -> type)) (parse/arrow '((:t^2 : type) :t -> type)) (parse/arrow '((:t1 :t2^2 :t3^0 : j k) :t -> type)) (parse/arrow '((:t^2 @ type) :t -> type)))) '((((name natural) (name natural)) ((name natural))) (((name natural) (name natural)) ((arrow (((name natural) (name natural)) ((name natural)))) (name natural))) (((var (#(:m ()) 0)) (name zero)) ((var (#(:m ()) 0)))) (((var (#(:m ()) 0)) (var (#(:n ()) 0)) (name succ)) ((var (#(:m ()) 0)) (var (#(:n ()) 0)) (name recur) (name succ))) (((bind (((var (#(:t ()) 1))) ((name type)) #f)) (var (#(:t ()) 0))) ((name type))) (((bind (((var (#(:t ()) 1))) ((name type)) #t)) (var (#(:t ()) 0))) ((name type))) (((bind (((var (#(:t ()) 2))) ((name type)) #f)) (var (#(:t ()) 0))) ((name type))) (((bind (((var (#(:t1 ()) 1)) (var (#(:t2 ()) 2)) (var (#(:t3 ()) 0))) ((name j) (name k)) #f)) (var (#(:t ()) 0))) ((name type))) (((bind (((var (#(:t ()) 2))) ((name type)) #t)) (var (#(:t ()) 0))) ((name type))))) (define (apply/arrow a e) ;; arrow, env -> report (match e [(ds bs ns) (match a [(ac sc) (match (unify (lambda (e) (apply/cedent ac e)) (list ds (cons '(commit-point) bs) ns)) [('fail info-list) ('fail info-list)] [('success info-list e1) (match (apply/cedent sc e1) [(ds2 bs2 ns2) (list 'success info-list (list ds2 (bs/commit! bs2) ns2))])])])])) (define (bs/commit! bs) ;; bs -> bs ;; effect on part of bs (cond [(equal? '(commit-point) (car bs)) (cdr bs)] [else (let* ([pair (car bs)] [id (car pair)] [ls (cdr pair)]) (id/commit! id ls) (bs/commit! (cdr bs)))])) (define (id/commit! id ls) ;; id, ls -> id ;; effect on id (let () (vector-set! id (append ls (vector-ref id 1))) id)) (define (apply/cedent c e) ;; cedent, env -> env (match c ['() e] [(h . r) (apply/cedent r (apply/dispatch h e))])) (define (apply/dispatch f e) ;; form, env -> env (match f [('var v) (apply/var v e)] [('name n) (apply/name n e)] [('arrow a) (apply/literal-arrow a e)] [('bind b) (apply/bind b e)])) (define (id->ls id) (vector-ref id 1)) (define (unify e) ;; (env -> env), env -> unify-report )
true
98e0b66b12e04843efde955bdea80c1172a74e9e
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
/ext/ffi/win32/gui/tab.scm
f6dfcb7570072d2a87795e98649cb88cf25d4acb
[ "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
17,582
scm
tab.scm
;;; -*- mode: scheme; coding: utf-8; -*- ;;; ;;; win32/gui/tab.scm - Win32 Tab component ;;; ;;; Copyright (c) 2021 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 (win32 gui tab) (export make-win32-tab-container <win32-tab-container> win32-tab-container? win32-tab-container-set-image-list! make-win32-tab-panel <win32-tab-panel> win32-tab-panel? win32-tab-panel-set-tab-name! <win32-closable-tab-panel> win32-closable-tab-panel? make-win32-closable-tab-panel *win32-tab-panel-default-close-button-width* *win32-tab-panel-default-close-button-height* ) (import (rnrs) (sagittarius) (sagittarius ffi) (win32 kernel) (win32 user) (win32 defs) (win32 common-control) (win32 gdi) (win32 gui api) (win32 gui image) (clos user) (sagittarius control) (sagittarius object) (srfi :39 parameters)) (define *win32-tab-panel-default-close-button-width* (make-parameter 15)) (define *win32-tab-panel-default-close-button-height* (make-parameter 15)) (define *win32-default-tab-panel-class-name* "sagittarius-default-tab-panel-class") (define-class <win32-tab-panel> (<win32-container>) ((tab-name :init-keyword :tab-name) (tab-image :init-keyword :tab-image :init-value #f) (tab-color :init-keyword :tab-color :init-value #f))) (define (win32-tab-panel? o) (is-a? o <win32-tab-panel>)) (define (make-win32-tab-panel . args) (apply make <win32-tab-panel> args)) (define-method initialize ((o <win32-tab-panel>) initargs) (call-next-method) (unless (slot-bound? o 'class-name) (set! (~ o 'class-name) *win32-default-tab-panel-class-name*)) (unless (slot-bound? o 'tab-name) (set! (~ o 'tab-name) (~ o 'name))) (set! (~ o 'name) "") o) (define-class <win32-closable-tab-panel> (<win32-tab-panel>) ((close-button :init-keyword :close-button :init-value #f) (image-list :init-value #f))) (define (make-win32-closable-tab-panel . args) (apply make <win32-closable-tab-panel> args)) (define (win32-closable-tab-panel? o) (is-a? o <win32-closable-tab-panel>)) (define-method initialize ((o <win32-closable-tab-panel>) initargs) (call-next-method) (when (win32-image? (~ o 'close-button)) (set! (~ o 'image-list) (make <win32-image-list> :images (list (~ o 'close-button)) :width 16 :height 16)))) (define-method win32-create ((ct <win32-closable-tab-panel>)) (call-next-method) (when (~ ct 'image-list) (win32-create (~ ct 'image-list)))) (define-method win32-destroy ((ct <win32-closable-tab-panel>)) (when (~ ct 'image-list) (win32-destroy (~ ct 'image-list))) (call-next-method)) (define (win32-tab-panel-set-tab-name! tab name) (set! (~ tab 'tab-name) name) ;; if owner isn't there, then just slot set is fine (cond ((~ tab 'owner) => (lambda (c) (let ((pos (win32-get-tab-position c tab))) (when (>= pos 0) (win32-set-tab! c tab pos))))))) (define *win32-default-tab-control-class-name* "sagittarius-default-tab-control-class") (inherit-window-class WC_STATIC *win32-default-tab-panel-class-name* WM_NCCREATE) (define-class <win32-tab-container> (<win32-container>) ((tabs :init-value '()) (fixed-width? :init-keyword :fixed-width? :init-value #f) (image-list :init-keyword :image-list :init-value #f))) (define (win32-tab-container? o) (is-a? o <win32-tab-container>)) (define (make-win32-tab-container . args) (apply make <win32-tab-container> args)) (define-method initialize ((o <win32-tab-container>) initargs) (call-next-method) ;; maybe custom window proc? (unless (slot-bound? o 'class-name) (set! (~ o 'class-name) *win32-default-tab-control-class-name*)) ;; if user didn't specify (when (zero? (~ o 'window-style)) (set! (~ o 'window-style) WS_EX_APPWINDOW)) (let ((s (~ o 'style)) (fx? (~ o 'fixed-width?))) (set! (~ o 'style) (bitwise-ior s (if fx? TCS_FIXEDWIDTH 0) WS_CHILD WS_CLIPSIBLINGS WS_VISIBLE))) o) (define (tab-container-dispatch hwnd imsg wparam lparam) (define (close-tab tc tab index) (set! (~ tc 'tabs) (remq tab (~ tc 'tabs))) (tab-ctrl-delete-item (~ tc 'hwnd) index) (resize-tab-panel tc 0 0) (win32-destroy tab)) (define (maybe-close? tc tab x y) (define index (win32-get-tab-position tc tab)) (define rc (allocate-c-struct RECT)) (tab-ctrl-get-item-rect hwnd index rc) (inflate-rect rc 2 2) (let* ((selected? (= index (pointer->integer (tab-ctrl-get-cur-sel hwnd)))) (b-rc (win32-tab-get-close-button-rect tc index tab rc selected?))) (and (position-in-rect b-rc x y) (close-tab tc tab index)))) (define (cont) ;; let the common one handle it (win32-common-dispatch hwnd imsg wparam lparam)) (cond ((= imsg WM_LBUTTONUP) (let* ((w (win32-get-component hwnd)) (p (pointer->integer lparam)) (x (win32-loword p)) (y (win32-hiword p))) (cond ((get-tab-under-point w x y) => (lambda (tab) (if (need-close-button? tab) (or (maybe-close? w tab x y) (cont)) (cont)))) (else (cont))))) (else (cont)))) (inherit-window-class WC_TABCONTROL *win32-default-tab-control-class-name* WM_NCCREATE tab-container-dispatch) (define-method win32-create ((o <win32-tab-container>)) (when (~ o 'image-list) (win32-create (~ o 'image-list))) (call-next-method)) (define-method win32-destroy ((ct <win32-closable-tab-panel>)) (when (and (~ ct 'image-list) (~ ct 'destroy-children?)) (win32-destroy (~ ct 'image-list))) (call-next-method)) (define (win32-tab-container-set-image-list! w il) (unless (and (win32-tab-container? w) (win32-image-list? il)) (assertion-violation 'win32-tab-container-set-image-list! "Tab container and image list required" w il)) (set! (~ w 'image-list) il) (win32-require-hwnd w (send-message (~ w 'hwnd) TCM_SETIMAGELIST 0 (~ il 'himl)))) (define-method win32-handle-notify ((w <win32-tab-container>) wparam lparam) (define code (c-struct-ref lparam NMHDR 'code)) (cond ((= code TCN_SELCHANGE) (resize-tab-panel w 0 0)) ;; for now ;; get-message-pos returns global position, so it's rather ;; difficult to adjust... #;((= code NM_CLICK) (let* ((p (get-message-pos)) (x (win32-loword p)) (y (win32-hiword p))) (cond ((get-tab-under-point w x y) => (lambda (tab) (display tab) (newline))))))) ;; return #f to let Windows handle the rest #f) (define-method win32-handle-draw-item ((w <win32-tab-container>) lparam) (define pos (c-struct-ref lparam DRAWITEMSTRUCT 'itemID)) (let ((tab (list-ref (~ w 'tabs) pos))) (win32-draw-tab w tab lparam)) #t) (define (position-in-rect rc x y) (and (< (c-struct-ref rc RECT 'left) x (c-struct-ref rc RECT 'right)) (< (c-struct-ref rc RECT 'top) y (c-struct-ref rc RECT 'bottom)))) (define (get-tab-under-point tc x y) (define rc (allocate-c-struct RECT)) ;; reuse... (define (in-position tab pos) (tab-ctrl-get-item-rect (~ tc 'hwnd) pos rc) (inflate-rect rc 2 2) (position-in-rect rc x y)) (do ((i 0 (+ i 1)) (tabs (~ tc 'tabs) (cdr tabs))) ((or (null? tabs) (in-position (car tabs) i)) (if (null? tabs) #f (car tabs))))) (define (resize-tab-panel w width height) ;; get currently selected one (let ((index (pointer->integer (tab-ctrl-get-cur-sel (~ w 'hwnd)))) (rect (allocate-c-struct RECT))) (get-window-rect (~ w 'hwnd) rect) (c-struct-set! rect RECT 'left 0) (c-struct-set! rect RECT 'top 0) (tab-ctrl-adjust-rect (~ w 'hwnd) 0 rect) ;; get adjusted size here (do ((i 0 (+ i 1)) (tabs (~ w 'tabs) (cdr tabs)) (selected (if (negative? index) 0 index))) ((null? tabs)) (let ((tab (car tabs))) (win32-require-hwnd tab (cond ((= i selected) (show-window (~ tab 'hwnd) SW_SHOW) (move-window (~ tab 'hwnd) (c-struct-ref rect RECT 'left) (c-struct-ref rect RECT 'top) (- (c-struct-ref rect RECT 'right) (c-struct-ref rect RECT 'left)) (- (c-struct-ref rect RECT 'bottom) (c-struct-ref rect RECT 'top)) #t)) (else (show-window (~ tab 'hwnd) SW_HIDE)))))))) (define-method win32-handle-size ((w <win32-tab-container>) width height) (when (win32-auto-resize? w) (move-window (~ w 'hwnd) (~ w 'x) (~ w 'y) width height (~ w 'repaint?))) (resize-tab-panel w width height)) (define-method win32-add-component! ((o <win32-tab-container>) (t <win32-tab-panel>)) (call-next-method) ;; it's bit costly... (set! (~ o 'tabs) (append (~ o 'tabs) (list t))) (win32-insert-tab! o t (length (~ o 'tabs)))) (define-method win32-add-component! ((o <win32-tab-container>) (t <win32-closable-tab-panel>)) (call-next-method) (when (zero? (bitwise-and (~ o 'style) TCS_OWNERDRAWFIXED)) (win32-require-hwnd o (let ((l (pointer->integer (get-window-long-ptr (~ o 'hwnd) GWL_STYLE)))) (set-window-long-ptr (~ o 'hwnd) GWL_STYLE (integer->pointer (bitwise-ior l TCS_OWNERDRAWFIXED))) (set! (~ o 'style) (bitwise-ior l TCS_OWNERDRAWFIXED)))))) ;; make sure (define (find-image tab il) (if il (let ((image (~ tab 'tab-image))) (do ((i 0 (+ i 1)) (images (~ il 'images) (cdr images))) ((or (null? images) (eq? (car images) image)) (if (null? images) -1 i)))) -1)) (define (need-close-button? p) (win32-closable-tab-panel? p)) (define (make-tc-item c tab) (let ((ti (allocate-c-struct TC_ITEM)) (hwnd (~ c 'hwnd)) (name (if (need-close-button? tab) (string-append (~ tab 'tab-name) " ") (~ tab 'tab-name))) (image (find-image tab (~ c 'image-list)))) (c-struct-set! ti TC_ITEM 'mask (bitwise-ior TCIF_TEXT TCIF_IMAGE)) (c-struct-set! ti TC_ITEM 'pszText name) (c-struct-set! ti TC_ITEM 'cchTextMax (string-length name)) (c-struct-set! ti TC_ITEM 'iImage image) ti)) (define (win32-insert-tab! c tab pos) (win32-require-hwnd c (let ((ti (make-tc-item c tab))) (unless (~ tab 'hwnd) (win32-create tab)) (let ((index (pointer->integer (tab-ctrl-insert-item (~ c 'hwnd) pos ti)))) (tab-ctrl-set-cur-sel (~ c 'hwnd) index) (resize-tab-panel c 0 0))))) (define (win32-get-tab-position c tab) (do ((i 0 (+ i 1)) (tabs (~ c 'tabs) (cdr tabs))) ((or (null? tabs) (eq? tab (car tabs))) (if (null? tabs) -1 i)))) (define (win32-set-tab! c tab pos) (win32-require-hwnd c (let ((ti (make-tc-item c tab))) (tab-ctrl-set-item (~ c 'hwnd) pos ti) (let ((index (pointer->integer (tab-ctrl-get-cur-sel (~ c 'hwnd))))) (when (= pos index) (win32-show tab))) ;; we need to re-render the tab to make the components ;; be rendered properly... no idea why... (let ((rect (allocate-c-struct RECT))) (get-window-rect (~ c 'hwnd) rect) (tab-ctrl-adjust-rect (~ c 'hwnd) 0 rect) (move-window (~ c 'hwnd) (c-struct-ref rect RECT 'left) (c-struct-ref rect RECT 'top) (- (c-struct-ref rect RECT 'right) (c-struct-ref rect RECT 'left)) (- (c-struct-ref rect RECT 'bottom) (c-struct-ref rect RECT 'top)) #t)) ))) (define (win32-tab-get-close-button-rect tc index p rect selected?) (define rc (allocate-c-struct RECT)) (define pad 3) (if (~ p 'image-list) (let ((ii (allocate-c-struct IMAGEINFO))) (image-list-get-image-info (~ p 'image-list 'himl) 0 ii) (let ((rcImage (c-struct-ref ii IMAGEINFO 'rcImage))) (c-struct-set! rc RECT 'top (+ (c-struct-ref rect RECT 'top) pad)) (c-struct-set! rc RECT 'bottom (+ (c-struct-ref rc RECT 'top) (- (c-struct-ref rcImage RECT 'bottom) (c-struct-ref rcImage RECT 'top)))) (c-struct-set! rc RECT 'right (- (c-struct-ref rect RECT 'right) pad)) (c-struct-set! rc RECT 'left (- (c-struct-ref rc RECT 'right) (- (c-struct-ref rcImage RECT 'right) (c-struct-ref rcImage RECT 'left)))))) ;; okay just return a fixed range (let ((width (*win32-tab-panel-default-close-button-width*)) (height (*win32-tab-panel-default-close-button-height*))) (c-struct-set! rc RECT 'top (c-struct-ref rect RECT 'top)) (c-struct-set! rc RECT 'bottom (+ (c-struct-ref rc RECT 'top) height)) (c-struct-set! rc RECT 'right (- (c-struct-ref rect RECT 'right) pad)) (c-struct-set! rc RECT 'left (- (c-struct-ref rc RECT 'right) width)))) (when selected? (c-struct-set! rc RECT 'left (- (c-struct-ref rc RECT 'left) 1)) (c-struct-set! rc RECT 'right (- (c-struct-ref rc RECT 'right) 1))) rc) (define (draw-default-close-button hdc rc) (define (create-pen) (define brush (allocate-c-struct LOGBRUSH)) (c-struct-set! brush LOGBRUSH 'lbStyle BS_SOLID) (c-struct-set! brush LOGBRUSH 'lbColor (rgb #xff #xff #xff)) (ext-create-pen PS_COSMETIC 1 brush 0 null-pointer)) (define hpen (create-pen)) (define old-hpen (select-object hdc hpen)) (define pad 2) (define brush (create-solid-brush (rgb #xff 0 0))) (fill-rect hdc rc brush) (delete-object brush) (inflate-rect rc (- pad) (- pad)) ;; draw left diagonal line (move-to-ex hdc (c-struct-ref rc RECT 'left) (c-struct-ref rc RECT 'top) null-pointer) (line-to hdc (c-struct-ref rc RECT 'right) (c-struct-ref rc RECT 'bottom)) ;; draw right diagonal line (move-to-ex hdc (c-struct-ref rc RECT 'right) (c-struct-ref rc RECT 'top) null-pointer) (line-to hdc (c-struct-ref rc RECT 'left) (c-struct-ref rc RECT 'bottom)) (inflate-rect rc pad pad) (select-object hdc old-hpen) (delete-object hpen)) (define-method win32-draw-tab ((t <win32-tab-container>) (p <win32-tab-panel>) lparam) (define rect (c-struct-ref lparam DRAWITEMSTRUCT 'rcItem)) (define item-id (c-struct-ref lparam DRAWITEMSTRUCT 'itemID)) (define hdc (c-struct-ref lparam DRAWITEMSTRUCT 'hDC)) (define selected? (= (pointer->integer (tab-ctrl-get-cur-sel (~ t 'hwnd))) item-id)) (define image-list (tab-ctrl-get-image-list (~ t 'hwnd))) (define padding 3) ;; maybe get from panel? (define bottom (c-struct-ref rect RECT 'bottom)) (define left (c-struct-ref rect RECT 'left)) (define top(c-struct-ref rect RECT 'top)) (define right (c-struct-ref rect RECT 'right)) (c-struct-set! rect RECT 'bottom (+ bottom (if selected? -1 2))) (let ((brush (create-solid-brush (cond ((~ p 'tab-color)) (else (get-sys-color COLOR_BTNFACE)))))) (fill-rect hdc rect brush) (delete-object brush)) (c-struct-set! rect RECT 'left (+ left padding)) (c-struct-set! rect RECT 'top (+ top padding (if selected? 1 0))) (let ((oldbk (set-bk-mode hdc TRANSPARENT))) ;; Draw image left side (icon) (let ((ti (allocate-c-struct TC_ITEM))) (c-struct-set! ti TC_ITEM 'mask TCIF_IMAGE) (tab-ctrl-get-item (~ t 'hwnd) item-id ti) (when (and (not (null-pointer? image-list)) (>= (c-struct-ref ti TC_ITEM 'iImage) 0)) (let ((ii (allocate-c-struct IMAGEINFO)) (pos (c-struct-ref ti TC_ITEM 'iImage))) (image-list-get-image-info image-list pos ii) (image-list-draw image-list pos hdc (c-struct-ref rect RECT 'left) (c-struct-ref rect RECT 'top) ILD_TRANSPARENT) (let ((rc (c-struct-ref ii IMAGEINFO 'rcImage))) (c-struct-set! rect RECT 'left (+ (c-struct-ref rect RECT 'left) (- (c-struct-ref rc RECT 'right) (c-struct-ref rc RECT 'left)) padding)))))) ;; Draw close button (when (need-close-button? p) (let ((rc (win32-tab-get-close-button-rect t item-id p rect selected?))) (if (~ p 'image-list) (image-list-draw (~ p 'image-list 'himl) 0 hdc (c-struct-ref rc RECT 'left) (c-struct-ref rc RECT 'top) ILD_TRANSPARENT) (draw-default-close-button hdc rc)) (set! right (- (c-struct-ref rc RECT 'left) padding)) ;; TODO need padding? )) ;; Draw text (c-struct-set! rect RECT 'right (- right padding)) (let ((oldtx (set-text-color hdc (rgb 0 0 0)))) (draw-text hdc (~ p 'tab-name) (string-length (~ p 'tab-name)) rect (bitwise-ior DT_CENTER DT_SINGLELINE DT_VCENTER)) (set-text-color hdc oldtx) (set-bk-mode hdc oldbk)))) )
false
b540ffd305fb473638a86f9b9d00d71e5bfc9cea
ca3425fbd3bef3cd7adeb7b1f61f00afd097927f
/planet/galore.plt/2/2/leftist-heap.scm
dcb1da1350d6cdc754fe200cbf921dbff1c1047d
[]
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
7,998
scm
leftist-heap.scm
;;; leftist-heap.scm -- Jens Axel Søgaard -- 28th dec 2005 ;;; LEFTIST HEAP [Okasaki, p.17-20] ; A *Leftist heap* is a heap-ordered binary tree with the /leftist property/: ; The rank of any left child is at least as large as the rank of its right sibling. ; The *rank* of a node is the length of the its *right spine*, which is the ; rightmost path from the node to an empty node. ;;; Time worst case ; delete-min O(log n) ; empty O(1) ; empty? O(1) ; find-min O(1) ; insert O(log n) ; union O(log n) (module leftist-heap mzscheme (require (lib "67.ss" "srfi") (lib "42.ss" "srfi") (only (lib "list.ss") foldl)) ;;; DATA DEFINITION ; A HEAP is either ; (make-heap-empty cmp) ; or ; (make-heap-node cmp rank elm left right) ; where ; cmp is a compare function, ; rank is an integer, and ; left and right are heaps. (define-struct heap (compare)) (define-struct (heap-empty heap) ()) (define-struct (heap-node heap) (rank elm left right)) ;;; CORE HEAP OPERATIONS (define empty (case-lambda [() (make-heap-empty (current-compare))] [(cmp) (make-heap-empty cmp)])) (define empty? heap-empty?) (define (rank h) (if (empty? h) 0 (heap-node-rank h))) (define (make x a b) (let ([ra (rank a)] [rb (rank b)] [cmp (heap-compare a)]) (if (>= ra rb) (make-heap-node cmp (add1 rb) x a b) (make-heap-node cmp (add1 ra) x b a)))) (define (union h1 h2) (cond [(empty? h1) h2] [(empty? h2) h1] [else (let ([x (heap-node-elm h1)] [y (heap-node-elm h2)]) (if<=? ((heap-compare h1) x y) (make x (heap-node-left h1) (union (heap-node-right h1) h2)) (make y (heap-node-left h2) (union h1 (heap-node-right h2)))))])) (define (insert x h) (let ([cmp (heap-compare h)]) (union (make-heap-node cmp 1 x (make-heap-empty cmp) (make-heap-empty cmp)) h))) (define (delete x h) (define (delete/sf x h s f) (cond [(empty? h) (s h)] [(=? (heap-compare h) x (heap-node-elm h)) (s (union (heap-node-left h) (heap-node-right h)))] [(<? (heap-compare h) x (heap-node-elm h)) (f)] [else (let ([cmp (heap-compare h)]) (let ([y (heap-node-elm h)] [l (heap-node-left h)] [r (heap-node-right h)]) (delete/sf x l (lambda (h1) (s (make y h1 r))) (lambda () (delete/sf x r (lambda (h1) (s (make y l h1))) (lambda () (f)))))))])) (delete/sf x h (lambda (h1) h1) (lambda () h))) (define (delete-all x h) (define (delete-all/sf x h s f) (cond [(empty? h) (s h)] [(=? (heap-compare h) x (heap-node-elm h)) (s (union (delete-all x (heap-node-left h)) (delete-all x (heap-node-right h))))] [(<? (heap-compare h) x (heap-node-elm h)) (f)] [else (let ([cmp (heap-compare h)]) (let ([y (heap-node-elm h)] [l (heap-node-left h)] [r (heap-node-right h)]) (delete-all/sf x l (lambda (l1) (s (delete-all/sf x r (lambda (r1) (make y l1 r1)) (lambda () (make y l1 r))))) (lambda () (delete-all/sf x r (lambda (r1) (s (make y l r1))) (lambda () (f)))))))])) (delete-all/sf x h (lambda (h1) h1) (lambda () h))) (define (find-min h) (heap-node-elm h)) (define (delete-min h) (union (heap-node-left h) (heap-node-right h))) (define (get x h) (let ([cmp (heap-compare h)]) (define (inner-get h s f) (if (empty? h) (f) (if=? (cmp x (heap-node-elm h)) (s (heap-node-elm h)) (inner-get (heap-node-left h) s (lambda () (inner-get (heap-node-right h) s f)))))) (inner-get h (lambda (x) x) (lambda () #f)))) ;;; ;;; EXTRA OPERATIONS ;;; (define (delete* xs h) (foldl delete h xs)) (define (elements h) (fold cons '() h)) (define (fold f b h) (if (empty? h) b (fold f (fold f (f (heap-node-elm h) b) (heap-node-left h)) (heap-node-right h)))) (define (count x h) (let ([cmp (heap-compare h)]) (fold (lambda (y s) (if=? (cmp x y) (add1 s) s)) 0 h))) (define (-heap . xs) (list->heap xs)) (define (insert* xs h) (union (list->heap (heap-compare h) xs) h)) (define list->heap ; time: O(n) (case-lambda [(l) (list->heap (current-compare) l)] [(cmp l) (let* ([e (empty cmp)] [hs (map (lambda (x) (insert x e)) l)]) ; (list heap) -> (list heap) ; merge adjacent pairs of heaps (define (merge-pairs hs) (cond [(or (null? hs) (null? (cdr hs))) hs] [else (cons (union (car hs) (cadr hs)) (merge-pairs (cddr hs)))])) (if (null? hs) e (let loop ([hs hs]) ; merge adjacent pairs of heaps until one is left (cond [(null? hs) '()] [(null? (cdr hs)) (car hs)] [else (loop (merge-pairs hs))]))))])) ; select : set -> element (define (select s) (if (empty? s) (error 'select "can't select an element from an empty heap") (find-min s))) (define singleton (case-lambda [(x) (insert x (empty))] [(cmp x) (insert x (make-heap-empty cmp))])) (define (size h) ; NOTE: T(size)=O(n) (cond [(heap-empty? h) 0] [else (+ (size (heap-node-left h)) 1 (size (heap-node-right h)))])) ;;; ;;; support for srfi-42 ;;; (define-syntax heap-ec (syntax-rules () [(heap-ec cmp etc1 etc ...) (fold-ec (empty cmp) etc1 etc ... insert)])) (define-syntax :heap (syntax-rules (index) ((:heap cc var (index i) arg) (:parallel cc (:stack var arg) (:integers i)) ) ((:heap cc var arg) (:do cc (let ()) ((t arg)) (not (empty? t)) (let ((var (find-min t)))) #t ((delete-min t)) )))) (define (:heap-dispatch args) (cond [(null? args) 'heap] [(and (heap? (car args))) (:generator-proc (:heap (car args)))] [else #f])) (:-dispatch-set! (dispatch-union (:-dispatch-ref) :heap-dispatch)) (require "signatures/heap-signature.scm") (provide-heap) )
true
b2ad97910fec17f94bde59168e66d5d73754109b
00a6616bb1f09bd79678366f29b89bb25eb42c39
/Scheme/Scheme/diff-0.scm
18ad4b2594590fa719539efd82358839bd8d919e
[]
no_license
JeppeJonHolt/PP
8e34392d392e20057f22eec7c3347142efa68da3
1c56d913c1a3e6e9635e855fbf9103efcc6c0038
refs/heads/main
2023-09-04T08:08:37.852260
2021-10-26T10:16:41
2021-10-26T10:16:41
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
361
scm
diff-0.scm
#lang scheme (define (func x) (* x 3)) (define derivative (lambda(f) (lambda (x) (/ (- (f (+ x 0.0005)) (f x)) 0.0005 ))) ) (define (compare-2 f1 f2 numerical-input-list) (if (null? numerical-input-list) '() (cons (- (f1 (car numerical-input-list)) (f2 (car numerical-input-list))) (compare-2 f1 f2 (cdr numerical-input-list)))))
false
630d88ac4414d21fdfe5d16fe8d43883225e5575
0011048749c119b688ec878ec47dad7cd8dd00ec
/src/034/solution.scm
54ffd4479f9c2e017b100e7dd709a6306c37523e
[ "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
629
scm
solution.scm
(import (chicken fixnum) (euler)) (define factorials (list->vector (map factorial (range 0 9)))) (define limit (let ((_ (vector-ref factorials 9))) (let loop ((a 1) (b 1)) (if (fx> a b) a (loop (fx* a 10) (fx+ b _)))))) (define (valid? n) (let loop ((i n) (acc 0)) (if (fx= i 0) (fx= acc n) (loop (fx/ i 10) (fx+ acc (vector-ref factorials (fxmod i 10))))))) (define (solve) (let loop ((i 3) (acc 0)) (if (fx> i limit) acc (loop (fx+ i 1) (if (valid? i) (fx+ acc i) acc))))) (let ((_ (solve))) (print _) (assert (= _ 40730)))
false
0faa73ed01a7e5e1d212b1f3500f6e43e37745df
6e9c9cefc78bdeaa3902ebfdd7d3a3367db26ef5
/match.ss
178d147f7966e8dc99f420e0bbfe848f3542036e
[]
no_license
liumingc/frac
39971c055dea4e6130862501a7cd6bd0f9790ac4
655734946338ac041fffea472a1eca304c52832a
refs/heads/master
2021-01-20T13:48:04.089112
2019-10-08T13:54:02
2019-10-08T13:54:02
18,410,646
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,768
ss
match.ss
#| (match '(+ a b) [(,op ,x ,y) (list x y)] [(,op ,x) (list x 0)]) -> (let ([x '(+ a b)]) (let ([ls/fail (sexp-dispatch x '(any any any))]) (if ls/fail (apply (lambda (op x y) (list x y)) ls/fail) (let ([ls/fail2 (sexp-dispatch x '(any any))]) (if ls/fail2 (apply (lambda (op x) (list x 0)) ls/fail2) (error 'match "~s~%" x)))))) ;;; TODO: support ellipse |# (define-syntax match (lambda (x) (syntax-case x () [(_ x clause ...) #'(let ([t x]) (match1 t clause ...))]))) (define-syntax match1 (lambda (x) (syntax-case x () [(_ x) #'(syntax-error x)] [(_ x cls rest ...) (with-syntax ([rest #'(match1 x rest ...)]) (syntax-case #'cls () [(pat expr) (let-values ([(p pvars) (convert-pattern #'pat)]) ;(printf "convert pattern output: pattern->~s pvars->~s~%" p pvars) #`(let ([ls/fail (sexp-dispatch x '#,p)]) (if ls/fail (apply (lambda #,pvars expr) ls/fail) rest)))]))]))) (define convert-pattern (lambda (pat) (define cvt (lambda (pat ids) (syntax-case pat (unquote) [,x (values #'any (cons #'x ids))] [() (values '() ids)] [(x . y) (let-values ([(ypat yvars) (cvt #'y ids)]) (let-values ([(xpat xvars) (cvt #'x yvars)]) (values (cons xpat ypat) xvars)))] [x (values (vector #'atom #'x) ids)]))) (cvt pat '()))) (define sexp-dispatch (lambda (x pat) (define disp (lambda (x pat r) (cond [(not r) #f] [(null? pat) (and (null? x) r)] [(eq? pat 'any) (cons x r)] [(vector? pat) (and (equal? (vector-ref pat 1) x) r)] [(pair? pat) (and (pair? x) (disp (car x) (car pat) (disp (cdr x) (cdr pat) r)))]))) (disp x pat '()))) #!eof
true
67acc01f987366ddb42f9c3e89f6ad789210f37c
7f4f8ff05f0d36d9c92e03565efd45e70483880a
/erik.ss
1f06c912cda99a67a1822cd40b7651289ef73659
[]
no_license
hansenrl/plcAssignments
1c29a7033b5857ad44822b180255dede7ce3e89a
cada30b7ffd24a4a846c7bc38f88396c0d6ffb43
refs/heads/master
2018-12-29T00:29:48.539259
2013-05-11T19:44:59
2013-05-11T19:44:59
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
56
ss
erik.ss
(define erik (lambda () 5)) (define ross (lambda () 7))
false
22bbcf247d034b9e20267ce568e439c009e24c31
defeada37d39bca09ef76f66f38683754c0a6aa0
/mscorlib/system/security/access-control/authorization-rule-collection.sls
8833c0f9dd6487e91a68b5c8d658c4b6b2e89734
[]
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
785
sls
authorization-rule-collection.sls
(library (system security access-control authorization-rule-collection) (export is? authorization-rule-collection? copy-to item) (import (ironscheme-clr-port)) (define (is? a) (clr-is System.Security.AccessControl.AuthorizationRuleCollection a)) (define (authorization-rule-collection? a) (clr-is System.Security.AccessControl.AuthorizationRuleCollection a)) (define-method-port copy-to System.Security.AccessControl.AuthorizationRuleCollection CopyTo (System.Void System.Security.AccessControl.AuthorizationRule[] System.Int32)) (define-field-port item #f #f (property:) System.Security.AccessControl.AuthorizationRuleCollection Item System.Security.AccessControl.AuthorizationRule))
false
be788aa5a7b26b257aa25e1d3843f9044933f94a
43612e5ed60c14068da312fd9d7081c1b2b7220d
/unit-tests/IFT3065/2/etape2-stringeq.scm
fc77e01de363b19880f090f874d65e62a0e685e3
[ "BSD-3-Clause" ]
permissive
bsaleil/lc
b1794065183b8f5fca018d3ece2dffabda6dd9a8
ee7867fd2bdbbe88924300e10b14ea717ee6434b
refs/heads/master
2021-03-19T09:44:18.905063
2019-05-11T01:36:38
2019-05-11T01:36:38
41,703,251
27
1
BSD-3-Clause
2018-08-29T19:13:33
2015-08-31T22:13:05
Scheme
UTF-8
Scheme
false
false
225
scm
etape2-stringeq.scm
(define a "a") (define b "b") (define c "ab") (define (try p1 p2) (println (string=? p1 p2))) (try a a) (try a b) (try a c) (try b a) (try b b) (try b c) (try c a) (try c b) (try c c) ;#t ;#f ;#f ;#f ;#t ;#f ;#f ;#f ;#t
false
3ed0a03b42319bcfcb39aaf749470dab8edaa1f3
7aeb920de21547a1d9c714b029bbf3a9e7df449e
/tests/unit/type-register-scm.t
5dec63c7e9bc5b68297621dbc5d5bc7626fc8b71
[ "BSD-2-Clause" ]
permissive
ft/chip-remote
f8ac5a2d7597d24f44ac287836be3422a32283d4
2a64df611214f7e3eb55d4ead76e270351158cdb
refs/heads/master
2023-04-30T08:38:16.483240
2023-01-05T04:01:44
2023-01-05T04:01:44
117,028,633
2
1
null
null
null
null
UTF-8
Scheme
false
false
6,053
t
type-register-scm.t
;; -*- scheme -*- ;; Copyright (c) 2017-2018 chip-remote workers, All rights reserved. ;; ;; Terms for redistribution and use can be found in LICENCE. (use-modules (test tap) (test setup) (chip-remote item) (chip-remote register)) (init-test-tap!) (define (address default) (generate-item #:name 'address #:offset 14 #:width 2 #:access read-only #:default default)) (define (fnct-that-returns-an-item name) (generate-item #:name name #:offset 3 #:width 2)) (with-fs-test-bundle (plan 33) (define-test "generate-register, call structure works" (pass-if-true (register? (generate-register #:default #x12 #:contents (foo 0 3) (bar 3 5))))) (let* ((reg (generate-register #:default #x12 #:contents (foo 0 3) (bar 5 3) #:contents* (fnct-that-returns-an-item 'thing) #:contents (foo 8 6) (=> (address 0)))) (meta (register-meta reg)) (items (register-items reg)) (foo (car items)) (bar (cadr items))) (define-test "canon: Negative indices are rejected" (pass-if-false (register-canonical reg -1))) (define-test "canon: Exceedingly large indices are rejected" (pass-if-false (register-canonical reg 5))) (define-test "canon: 0 is (0)" (pass-if-equal? '(0) (register-canonical reg 0))) (define-test "canon: foo is 0" (pass-if-equal? '(0) (register-canonical reg 'foo))) (define-test "canon: foo:0 is 0" (pass-if-equal? '(0) (register-canonical reg 'foo 0))) (define-test "canon: thing is 1" (pass-if-equal? '(1) (register-canonical reg 'thing))) (define-test "canon: thing:0 is 1" (pass-if-equal? '(1) (register-canonical reg 'thing 0))) (define-test "canon: bar is 2" (pass-if-equal? '(2) (register-canonical reg 'bar))) (define-test "canon: bar:0 is 2" (pass-if-equal? '(2) (register-canonical reg 'bar 0))) (define-test "canon: foo:1 is 3" (pass-if-equal? '(3) (register-canonical reg 'foo 1))) (define-test "reg: meta looks good" (pass-if-equal? meta '((#:default . #x12)))) (define-test "reg: first item is an <item>" (pass-if-true (item? foo))) (define-test "reg: its name is foo" (pass-if-eq? (item-name foo) 'foo)) (define-test "reg: second item is an <item>, too" (pass-if-true (item? bar))) (define-test "reg: its name is bar" (pass-if-eq? (item-name bar) 'bar)) (define-test "reg: item names are as expected" (pass-if-equal? (register-item-names reg) '(foo bar thing foo address))) (define-test "reg: the register's width is correct" (pass-if-= (register-width reg) 16)) (define-test "reg: the regsiter has an item foo" (pass-if-true (register-contains? reg 'foo))) (define-test "reg: and another item called bar" (pass-if-true (register-contains? reg 'foo))) (define-test "reg: addressing foo yields the correct item" (pass-if-equal? (register-address reg 'foo) foo)) (define-test "reg: addressing bar works as well" (pass-if-equal? (register-address reg 'bar) bar)) (define-test "reg: register-ref works #1" (pass-if-eq? (item-name (register-ref reg 0)) 'foo)) (define-test "reg: register-ref works #2" (pass-if-eq? (item-name (register-ref reg 1)) 'thing)) (define-test "reg: register-ref works #3" (pass-if-eq? (item-name (register-ref reg 2)) 'bar)) (define-test "reg: register-address/name+cnt works #1" (pass-if-eq? (item-name (register-address reg 'foo 0)) 'foo)) (define-test "reg: register-address/name+cnt works #2" (pass-if-= (item-offset (register-address reg 'foo 0)) 0)) (define-test "reg: register-address/name+cnt works #3" (pass-if-= (item-offset (register-address reg 'foo 1)) 8)) (define-test "register-default works" (pass-if-= (register-default reg) #x12))) (let ((reg (generate-register #:contents (address 0 4 #:default 10) (foo 4 4) (bar 8 4) (baz? 12 1) (reserved 13 3) (thing? 16 1) (fish? 17 1) (reserved 18 24))) (moar (generate-item moar 8 4)) (at-the-end (generate-item at-the-end 32 4))) (define-test "Removing an item works (bar)" (pass-if-equal? (register->alist (derive-register-from reg #:remove 'bar)) '((address 0 4) (foo 4 4) (baz? 12 1) (reserved 13 3) (thing? 16 1) (fish? 17 1) (reserved 18 24)))) (define-test "Inserting an item works (moar)" (pass-if-equal? (register->alist (derive-register-from reg #:insert moar)) '((address 0 4) (foo 4 4) (moar 8 4) (bar 8 4) (baz? 12 1) (reserved 13 3) (thing? 16 1) (fish? 17 1) (reserved 18 24)))) (define-test "Removing and inserting an item works (moar for bar)" (pass-if-equal? (register->alist (derive-register-from reg #:insert moar #:remove 'bar)) '((address 0 4) (foo 4 4) (moar 8 4) (baz? 12 1) (reserved 13 3) (thing? 16 1) (fish? 17 1) (reserved 18 24)))) (define-test "Inserting at the end works" (pass-if-equal? (register->alist (derive-register-from reg #:insert at-the-end)) '((address 0 4) (foo 4 4) (bar 8 4) (baz? 12 1) (reserved 13 3) (thing? 16 1) (fish? 17 1) (reserved 18 24) (at-the-end 32 4))))))
false
c91fb376dfc0c9f59fb8a43e5814599786404389
b14c18fa7a4067706bd19df10f846fce5a24c169
/Chapter2/2.31.scm
fa94aae75a24411f33f1445859e23a1cbc833f0f
[]
no_license
silvesthu/LearningSICP
eceed6267c349ff143506b28cf27c8be07e28ee9
b5738f7a22c9e7967a1c8f0b1b9a180210051397
refs/heads/master
2021-01-17T00:30:29.035210
2016-11-29T17:57:16
2016-11-29T17:57:16
19,287,764
3
0
null
null
null
null
UTF-8
Scheme
false
false
360
scm
2.31.scm
#lang scheme (define (tree-map action tree) (map ; map on each element -> skip null implicitly (lambda (sub-tree) (if (pair? sub-tree) (square-tree-map sub-tree) (action sub-tree) ) ) tree ) ) (define (square x) (* x x)) (define (square-tree tree) (tree-map square tree)) (square-tree (list 1 (list 2 (list 3 4) 5) (list 6 7) ) )
false
bea4f1a0586e705c932adabd9b9caa9906b2cff5
08b21a94e7d29f08ca6452b148fcc873d71e2bae
/src/scheme/file.sld
ed5fb759d79d3d7e40536ded1d77f45ec3dc0e1b
[ "MIT" ]
permissive
rickbutton/loki
cbdd7ad13b27e275bb6e160e7380847d7fcf3b3a
7addd2985de5cee206010043aaf112c77e21f475
refs/heads/master
2021-12-23T09:05:06.552835
2021-06-13T08:38:23
2021-06-13T08:38:23
200,152,485
21
1
NOASSERTION
2020-07-16T06:51:33
2019-08-02T02:42:39
Scheme
UTF-8
Scheme
false
false
348
sld
file.sld
(define-library (scheme file) (import (loki core io)) (export call-with-input-file delete-file open-binary-input-file open-input-file with-input-from-file call-with-output-file file-exists? open-binary-output-file open-output-file with-output-to-file))
false
3d72aa5356393b4c4d9516ee2ca0ee3b8a0322aa
961ccc58c2ed4ed1d84a78614bedf0d57a2f2174
/scheme/chapter1/fixed-point.scm
528dd7843221a78136f58c04b4ff3cf5cf5d433c
[]
no_license
huangjs/mostly-lisp-code
96483b566b8fa72ab0b73bf0e21f48cdb80dab0d
9fe862dbb64f2a28be62bb1bd996238de018f549
refs/heads/master
2021-01-10T10:11:50.121705
2015-11-01T08:53:22
2015-11-01T08:53:22
45,328,850
0
0
null
null
null
null
UTF-8
Scheme
false
false
827
scm
fixed-point.scm
;:*======================= ;:* finding fixed point of a function (define tolerance 0.0001) (define (fixed-point f first-guess) (define (close-enough? a b) (< (abs (- a b)) tolerance)) (define (try guess) (let ((next (f guess))) ; (display guess) ; (newline) (if (close-enough? next guess) next (try next)))) (try first-guess)) ;:*======================= ;:* application ;:* y^2 = x => y = x/y, which means we are trying to find a fixed point of function y -> x/y (define (sqrt x) (fixed-point (lambda (y) (average y (/ x y))) ;otherwise it won't converge 1.0)) (define golden-ratio (fixed-point (lambda (x) (+ 1 (/ 1 x))) 1.0)) (define root-of-x^x=1000 (fixed-point (lambda (x) (/ (+ x (/ (log 1000) (log x))) 2)) 2.0))
false
fe0fa613b15312efbd9dbe5f3b00dd666141b898
41cef4c35c07d1c023318e9870b9c7d83a102ff9
/ooff/src/ooff.scm
479c43281dbf66780290308cb6ced712e20ea704
[ "MIT" ]
permissive
michae2/michae2.xyz
10579705ec9ddf6e7d8cbb757986f117fadbdc76
83412bf5d45c76f71c84a387109f097188363412
refs/heads/main
2022-05-06T02:54:48.248346
2022-03-31T04:16:56
2022-03-31T04:16:56
106,938,693
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,143
scm
ooff.scm
#!r6rs (library (ooff) (export ooff->html5) (import (rnrs base) (expand)) (define ooff->html5-rules (list (expand-rule (n title body) '(opus n title body) `((!DOCTYPE ((html))) (html ((lang . "en")) (head () (meta ((charset . "UTF-8"))) (title () ,title)) (body () (header () (nav ())) (main () (article () (header () (h1 () ,title)) ,body)) (footer ()))))) (expand-rule (time place body) '(© time place body) `(section () (h2 () ,time (br ()) ,place) ,body)) (expand-rule (body) '(§ . body) `(section () . ,body)) (expand-rule (body) '(¶ . body) `(p () . ,body)) (expand-rule (text) '(· . text) `(! () . ,text)))) (define (ooff->html5 ooff) (expand ooff ooff->html5-rules)))
false
662f37cb6c583148c4b5ac506865b7d36f577d2b
a2d8b4843847507b02085bb8adabd818f57dd09f
/scheme/little-schemer/test-test.scm
d827f97451bf18e6b5e143bc9a57fc5b950092b6
[]
no_license
tcharding/self_learning
df911b018fc86bd5f918394b79d2456bf51f35a8
f6bb5c6f74092177aa1b71da2ce87ca1bfc5ef3c
refs/heads/master
2022-05-13T05:09:32.284093
2022-05-02T08:25:18
2022-05-02T08:25:18
41,029,057
13
2
null
null
null
null
UTF-8
Scheme
false
false
1,312
scm
test-test.scm
(load "test-manager/load.scm") ; This is a test group named simple-stuff (in-test-group simple-stuff ; This is one test named arithmetic (define-test (arithmetic) "Checking that set! and arithmetic work" (define foo 5) (check (= 5 foo) "Foo should start as five.") (set! foo 6) (check (= 36 (* foo foo)))) ; Each of these will become a separate anonymous one-form test (define-each-test (check (= 4 (+ 2 2)) "Two and two should make four.") (check (= 2147483648 (+ 2147483647 1)) "Addition shouldn't overflow.")) ; Each of these will become a separate anonymous one-form test using check (define-each-check (= 6 (+ 2 2 2)) (equal? '(1 2 3) (cons 1 '(2 3)))) ; This is a test that looks like a REPL interaction (define-test (interactive) (interaction (define foo 5) foo (produces 5) ; This compares against the value of the last form (set! foo 6) (* foo foo) (produces 36)))) (run-registered-tests) ; Can run individual groups or tests with (run-test '(simple-stuff)) (run-test '(simple-stuff arithmetic))
false
f335dce6889c0e4b104801c9c9d28d0259de46ee
ac2a3544b88444eabf12b68a9bce08941cd62581
/examples/tcltk/fig17-9.scm
e4156d349acc24a6887dccd9011eafed7fb99289
[ "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
1,488
scm
fig17-9.scm
#!/usr/bin/env gsi-script ; File: "fig17-9.scm" ; Copyright (c) 1997-2007 by Marc Feeley, All Rights Reserved. ; Translation into Scheme of Figure 17.9 from Chapter 17 of John ; Ousterhout's "Tcl and the Tk Toolkit". (include "tcltk#.scm") ; import Tcl/Tk procedures and variables (load "tcltk") (define pts "pts") (define bold "bold") (define italic "italic") (define underline "underline") (frame ".f1") (frame ".f2") (define rbuttons (map (lambda (size) (let* ((size-str (number->string size)) (rb (string-append ".f1." size-str))) (radiobutton rb text: (string-append size-str " points") relief: 'flat variable: pts value: size-str) rb)) '(8 10 12 18 24))) (checkbutton ".f2.bold" text: "Bold" relief: 'flat variable: bold) (checkbutton ".f2.italic" text: "Italic" relief: 'flat variable: italic) (checkbutton ".f2.underline" text: "Underline" relief: 'flat variable: underline) (define cbuttons '(".f2.bold" ".f2.italic" ".f2.underline")) (set-variable! pts "10") (pack ".f1" side: 'left padx: "3m" pady: "3m") (pack ".f2" side: 'right padx: "3m" pady: "3m") (apply pack (append rbuttons '(in: ".f1" side: top anchor: w))) (apply pack (append cbuttons '(in: ".f2" side: top anchor: w)))
false
174764578af4a479fea9f73c9b281a0ff9e190b0
2d868c9428b8f4772d2ede375a3492b3b6885e1d
/Logic Programming, Part 1/4.58.scm
ecd55c308e6e94d79768a0fae3f01d38aa28d0a9
[]
no_license
transducer/sicp
2428223945da87836fa2a82c02d965061717ae95
2cec377aa7805edfd7760c643c14127e344ee962
refs/heads/master
2021-06-06T20:06:47.156461
2016-09-16T22:05:02
2016-09-16T22:05:02
25,219,798
1
0
null
null
null
null
UTF-8
Scheme
false
false
324
scm
4.58.scm
;; Define a rule that says that a person is a ``big shot'' in a division if the person ;; works in the division but does not have a supervisor who works in the division. ; From lecture: (rule (bigshot ?x ?dept) (and (job ?x (?dept . ?y)) (not (and (supervisor ?x ?z) (job ?z (?dept . ?w))))))
false
2cdc994ae3cfa41c361146aeefc44d5db3985958
2b0dc0760baad4405f64b424345381f688173281
/compiler/src/test/scheme/functional/SymbolSuite.scm
3697a75ca0ad96cdf1f29b7c0c502e1a3f5cc7f4
[ "Apache-2.0" ]
permissive
abduld/llambda
f2e7daf0c9a302dafa29a2d4067bfae6d1ec8317
17e53a5ec15f2b09f2eb3304151af3dbbcfd7f32
refs/heads/master
2023-04-12T23:59:17.462698
2015-10-24T04:51:25
2015-10-24T04:51:25
45,697,748
0
0
NOASSERTION
2023-04-04T01:11:51
2015-11-06T17:50:04
Scala
UTF-8
Scheme
false
false
2,151
scm
SymbolSuite.scm
; This test assumes the inline -> heap transition happens after 12 bytes (define-test "symbol constant is a symbol" (expect #t (symbol? 'test))) (define-test "symbol constant of maximum inline size" (expect crash-length 'crash-length)) (define-test "empty list is not a symbol" (expect #f (string? '()))) (define-test "(symbol=?)" (expect-success (assert-true (symbol=? 'test 'test)) (assert-false (symbol=? 'test 'nottest)) (assert-false (symbol=? 'test 'test 'nottest)) ; Inline symbols (assert-true (symbol=? 'test 'test 'test)) ; Heap symbols (assert-true (symbol=? 'very-long-test-symbol 'very-long-test-symbol 'very-long-test-symbol)))) (define-test "(symbol=?) with one arg fails" (expect-compile-error arity-error? (symbol=? 'test))) (define-test "(symbol=?) with non-symbol fails" (expect-compile-error type-error? (symbol=? 'test 'test "test"))) (define-test "(symbol->string)" (expect-static-success ; Inline symbol (assert-equal "flying-cat" (symbol->string 'flying-cat)) ; Heap symbol (assert-equal "flying-hippopotamus" (symbol->string 'flying-hippopotamus)) (define non-bmp-string (symbol->string '|Hell🏂!|)) (assert-equal "Hell🏂!" non-bmp-string) (assert-equal 6 (string-length non-bmp-string)))) (define-test "(string->symbol)" (expect-static-success ; Inline symbol; inline string (assert-equal 'mISSISSIppi (string->symbol "mISSISSIppi")) ; Inline symbol; heap string (assert-equal 'MassaCHUsetts (string->symbol "MassaCHUsetts")) ; Heap symbol; heap string (assert-equal 'Yamagawaokachiyogamizu (string->symbol "Yamagawaokachiyogamizu")))) (define-test "(string->symbol (symbol->string))" (expect-static-success ; Inline symbol; inline string (assert-equal 'LollyPop (string->symbol (symbol->string 'LollyPop))) ; Inline symbol; heap string (assert-equal 'SourPatchKids (string->symbol (symbol->string 'SourPatchKids))) ; Heap symbol; heap string (assert-equal '|Reese's Peanut Butter Cup| (string->symbol (symbol->string '|Reese's Peanut Butter Cup|))) ; Non-BMP symbol (assert-equal '|Hell🏂!| (string->symbol (symbol->string '|Hell🏂!|)))))
false
900aded4a5c0596d044c19315eb195dde0ec7a0a
f905d699ac1de9d5919e9ad890a71613a3561a5c
/srfi-60/srfi/60.sld
e80b614e567d7788e91effeb1106f9fc4d9e6f1f
[ "BSD-3-Clause" ]
permissive
ilammy/srfi-60
d75401f9b4513c78252297e2e07019e7473165fe
69c7ac24564fae1c336c39f94d4199f24cd4946f
refs/heads/master
2020-05-30T17:09:09.399003
2015-04-16T20:44:41
2015-04-16T20:44:41
32,548,181
0
0
null
2015-04-16T20:47:53
2015-03-19T21:53:35
Scheme
UTF-8
Scheme
false
false
737
sld
60.sld
(define-library (srfi 60) (export bitwise-and bitwise-ior bitwise-xor bitwise-not bitwise-if arithmetic-shift bit-count bit-set? first-set-bit any-bits-set? copy-bit integer-length bit-field copy-bit-field rotate-bit-field reverse-bit-field integer->list list->integer booleans->integer (rename bitwise-and logand) (rename any-bits-set? logtest) (rename bitwise-ior logior) (rename bit-count logcount) (rename bitwise-xor logxor) (rename bit-set? logbit?) (rename bitwise-not lognot) (rename bitwise-if bitwise-merge) (rename arithmetic-shift ash) (rename first-set-bit log2-binary-factors)) (import (scheme base) (scheme case-lambda)) (include "60/portable-implementation.scm"))
false
dbc6c3ecdfe089743a52ca65443cf005b59acf12
f033ff2c78c89e2d7d24d7b8e711fa6d1b230142
/ccc/sequential/benchmarks/tel/telephone-catalogue.ss
3d31120faf29e7d7706cfdaf6d35b8d70a716ce1
[]
no_license
zane/research
3cb47d47bb2708f6e83ee16cef89647a47db139d
8b4ecfe6035fe30c9113f3add380c91598f7262a
refs/heads/master
2021-01-01T19:09:58.166662
2009-12-16T16:53:57
2009-12-16T16:53:57
62,193
1
0
null
null
null
null
UTF-8
Scheme
false
false
9,162
ss
telephone-catalogue.ss
(module telephone-catalogue scheme (require "../../contract.ss") (provide valid-telephone-entry? valid-telephone-catalogue? spine-telephone-entry? gtq-telephone-entry eq-telephone-entry create-telephone-entry) ;;+ create-telephone-entry, telephone-entry->string ;;a name-string is a String that consists of alphabetic chars ;name-string?: string? -> boolean? (define name-string? (lambda (s) (and (string? s) (andmap char-alphabetic? (string->list s))))) (define-struct telephone-number (description tel-no)) ;;a telephone-number is (make-telephone-number string? number?) ;;where 10000000 <= tel-no <= 9999999999 ;;valid-telephone-no?: number? -> boolean? (define valid-telephone-no? (lambda (no) (and (<= 1000000000 no) (<= no 9999999999)))) ;;valid-telephone-nuber?:telephone-number? -> bookean? (define valid-telephone-number? (lambda (tn) (and (string? (telephone-number-description tn)) (number? (telephone-number-tel-no tn)) (valid-telephone-no? (telephone-number-tel-no tn))))) (define-struct email (description address)) ;;an email is (make-email string? string?) ;;where address has form [email protected] where x,y,z ;;are nane-string ;;valid-address: string? -> boolean? ;;returns #t if str is in the form [email protected] where ;;x,y,y are name-string (define (valid-address? str) (letrec ((valid-address?-aux (lambda (s level) (cond ((null? s) (= level 3)) (else (cond ((= level 1) (cond ((char-alphabetic? (car s)) (valid-address?-aux (cdr s) level)) ((char=? (car s) #\@) (valid-address?-aux (cdr s) (+ 1 level))) (else #f))) ((= level 2) (cond ((char-alphabetic? (car s)) (valid-address?-aux (cdr s) level)) ((char=? (car s) #\.) (valid-address?-aux (cdr s) (+ 1 level))) (else #f))) ((= level 3) (cond ((char-alphabetic? (car s)) (valid-address?-aux (cdr s) level)) (else #f))))))))) (valid-address?-aux (string->list str) 1))) ;;valid-email?: email? -> boolean? (define valid-email? (lambda (e) (and (email? e) (string? (email-description e)) (string? (email-address e)) (valid-address? (email-address e))))) (define-struct telephone-entry (last-name first-name telephone-numbers emails)) ;; a telephone-entry is a (make-telephone-entry ;; name-string? ;; name-string? ;; (listof valid-telephone-number?) ;; (listof valid-emails?)) ;;valid-telephone-entry?: telephone-entry? -> boolean? (define valid-telephone-entry? (lambda (te) (and (name-string? (telephone-entry-last-name te)) (name-string? (telephone-entry-first-name te)) (andmap (lambda (x) (valid-telephone-number? x)) (telephone-entry-telephone-numbers te)) (andmap (lambda (x) (valid-email? x)) (telephone-entry-emails te))))) (define (gtq-telephone-entry te1 te2) (or (string<? (telephone-entry-last-name te1) (telephone-entry-last-name te2)) (and (string=? (telephone-entry-last-name te1) (telephone-entry-last-name te2)) (string<=? (telephone-entry-first-name te1) (telephone-entry-first-name te2))))) (define (eq-telephone-entry te1 te2) (and (string=? (telephone-entry-last-name te1) (telephone-entry-last-name te2)) (string=? (telephone-entry-first-name te1) (telephone-entry-first-name te2)))) (define (merge-telephone-entry te1 te2) (make-telephone-entry (telephone-entry-last-name te1) (telephone-entry-first-name te1) (append (telephone-entry-telephone-numbers te1) (telephone-entry-telephone-numbers te2)) (append (telephone-entry-emails te1) (telephone-entry-emails te2)))) ;spine-telephone-entry: telephone-entry? -> boolean? (define (spine-telephone-entry? te) (and (null? (telephone-entry-telephone-numbers te)) (null? (telephone-entry-emails te)))) ;;sorted-and-assoc-telephone-entry-list?: ;; [listof telephone-entry?] -> boolean? (define sorted-and-assoc-telephone-entry-list? (lambda (tel) (cond ((null? tel) #t) ((null? (cdr tel)) #t) (else (if (gtq-telephone-entry (car tel) (cadr tel)) (sorted-and-assoc-telephone-entry-list? (cdr tel)) #f))))) ;;a telephone-catalogue is an assoc [listof telephone-entry?] ;;sorted in descending order by the last and first name of the ;;telephone entries ;;valid-telephone-catalogue?: ;; [listof valid-telephone-entry?] -> boolean (define valid-telephone-catalogue? (lambda (tc) (and (andmap valid-telephone-entry? tc) (sorted-and-assoc-telephone-entry-list? tc)))) ;;create-telephone-numbers: ;; [listof (string? x number?)] -> [listof telephone-number?] (define (create-telephone-numbers tel-nos) (map (lambda (tn) (make-telephone-number (car tn) (cdr tn))) tel-nos)) ;;create-emails: ;; [listof (string? x string?)] -> [listof email?] (define (create-emails emails) (map (lambda (e) (make-email (car e) (cdr e))) emails)) (define (create-telephone-entry last-name first-name tel-nos emails) (make-telephone-entry last-name first-name (create-telephone-numbers tel-nos) (create-emails emails))) ;;telephone-numbers->string: ;; [listof telephone-number?] -> string? (define (telephone-numbers->string tel-nums) (foldr string-append "" (map (lambda (tn) (string-append (telephone-number-description tn) "~n" (number->string (telephone-number-tel-no tn)) "~n")) tel-nums))) ;;emails->string: ;; [listof telephone-number?] -> string? (define (emails->string emails) (foldr string-append "" (map (lambda (e) (string-append (email-description e) "~n" (email-address e) "~n")) emails))) (provide telephone-entry->string) ;;(provide/contract ;; (telephone-entry->string (-> valid-telephone-entry? string?))) (define (telephone-entry->string te) (string-append "Telephone-entry:~n" "last name:~n" (telephone-entry-last-name te) "first name:~n" (telephone-entry-last-name te) "telephone numbers:~n" (telephone-numbers->string (telephone-entry-telephone-numbers te)) "emails:~n" (emails->string (telephone-entry-emails te)))) )
false
2b21ac2bb1ae63e30ddde42241a877094ce17c2c
784dc416df1855cfc41e9efb69637c19a08dca68
/src/bootstrap/gerbil/core__8.scm
890914c68955732acf3f49ad3d0569c29d8f0066
[ "LGPL-2.1-only", "Apache-2.0", "LGPL-2.1-or-later" ]
permissive
danielsz/gerbil
3597284aa0905b35fe17f105cde04cbb79f1eec1
e20e839e22746175f0473e7414135cec927e10b2
refs/heads/master
2021-01-25T09:44:28.876814
2018-03-26T21:59:32
2018-03-26T21:59:32
123,315,616
0
0
Apache-2.0
2018-02-28T17:02:28
2018-02-28T17:02:28
null
UTF-8
Scheme
false
false
1,316
scm
core__8.scm
(declare (block) (standard-bindings) (extended-bindings) (inlining-limit 200)) (begin (define |gerbil/core$<MOP>$<MOP:3>[1]#macro-object::t| (make-class-type 'gerbil.core#macro-object::t '() '(macro) 'macro-object '() '#f)) (define |gerbil/core$<MOP>$<MOP:3>[1]#macro-object?| (make-class-predicate |gerbil/core$<MOP>$<MOP:3>[1]#macro-object::t|)) (define |gerbil/core$<MOP>$<MOP:3>[1]#make-macro-object| (lambda _$args21978_ (apply make-class-instance |gerbil/core$<MOP>$<MOP:3>[1]#macro-object::t| _$args21978_))) (define |gerbil/core$<MOP>$<MOP:3>[1]#macro-object-macro| (make-class-slot-accessor |gerbil/core$<MOP>$<MOP:3>[1]#macro-object::t| 'macro)) (define |gerbil/core$<MOP>$<MOP:3>[1]#macro-object-macro-set!| (make-class-slot-mutator |gerbil/core$<MOP>$<MOP:3>[1]#macro-object::t| 'macro)) (define |gerbil/core$<MOP>$<MOP:3>[1]#macro-object::apply-macro-expander| (lambda (_self21974_ _stx21976_) (gx#core-apply-expander (|gerbil/core$<MOP>$<MOP:3>[1]#macro-object-macro| _self21974_) _stx21976_))) (bind-method! |gerbil/core$<MOP>$<MOP:3>[1]#macro-object::t| 'apply-macro-expander |gerbil/core$<MOP>$<MOP:3>[1]#macro-object::apply-macro-expander| '#f))
false
625233a59bc2e2cdaccc9de5d29fe1891fde85db
784dc416df1855cfc41e9efb69637c19a08dca68
/src/lang/scheme/stubs.ss
ed9622765a2802bda871e5ff53955d1a612d4dc2
[ "LGPL-2.1-only", "Apache-2.0", "LGPL-2.1-or-later" ]
permissive
danielsz/gerbil
3597284aa0905b35fe17f105cde04cbb79f1eec1
e20e839e22746175f0473e7414135cec927e10b2
refs/heads/master
2021-01-25T09:44:28.876814
2018-03-26T21:59:32
2018-03-26T21:59:32
123,315,616
0
0
Apache-2.0
2018-02-28T17:02:28
2018-02-28T17:02:28
null
UTF-8
Scheme
false
false
399
ss
stubs.ss
;;; -*- Gerbil -*- ;;; (C) vyzo at hackzen.org ;;; R7RS stub macros for missing features package: scheme (export #t) (defrules defstub () ((_ id) (identifier? #'id) (defsyntax (id stx) (raise-syntax-error #f "R7RS procedure NOT IMPLEMENTED" stx 'id)))) (defrules defsyntax-stub () ((_ id) (defsyntax (id stx) (raise-syntax-error #f "R7RS macro NOT IMPLEMENTED" stx 'id))))
false
015c533b26925cf786e39707a436df9b0779cdf5
7499eaf0e102a9f0cabeee40a7d1f9b44d0374ad
/nbody.scm
5fff6f0930fc72eff36736ced7f80ec2b642a835
[]
no_license
lv-gh/clbg-scheme
09bb85c421d116a633399428d4e789efea7b95e1
86bd045490c87ec11b5b18c0e58062ec3b14e8f3
refs/heads/master
2021-01-01T05:06:21.022893
2016-04-18T23:31:15
2016-04-18T23:31:15
56,554,069
0
0
null
null
null
null
UTF-8
Scheme
false
false
5,607
scm
nbody.scm
#!r6rs ;; The Computer Language Benchmarks Game ;; http://benchmarksgame.alioth.debian.org/ ;; ;; Unoptimized although Scheme'ish and r6rs compatible implementation. ;; ;; Author: Laimonas Vėbra (import (rnrs base) (rnrs lists) (rnrs control) (rnrs programs) (rnrs io simple) (rnrs syntax-case) (rnrs records syntactic)) (define *dt* 0.01) (define *year-days* 365.24) (define *sun-mass* (* 4 (expt 3.141592653589793 2))) (define (round* number count) ;; Round number to a fraction scale (count of decimal places). (let ((scale (expt 10 count))) (/ (round (* scale number)) scale))) (define (print* energy) (display (round* energy 9)) (newline)) (define-syntax Λ ;; Syntactic sugar; lambda alias. (syntax-rules () ([_ <formals> <body> ...] (lambda <formals> <body> ...)))) (define (a•x⃗ a x⃗) ;; Multiplies vector by a number (vector-map * x⃗ (make-vector (vector-length x⃗) a))) (define-record-type body (fields (mutable x⃗ x⃗ x⃗!) ; position vector (x y z) (mutable v⃗ v⃗ v⃗!) ; velocity vecor (vx vy vz) (immutable mass mass)) ; mass ;; Custom constructor (mass and velocity values are normalized) (protocol (Λ (p) (Λ (x⃗ v⃗ mass) (let ([v⃗ (a•x⃗ *year-days* v⃗)] [mass (* mass *sun-mass*)]) (p x⃗ v⃗ mass)))))) ;; Velocity and position change (advance) (define (v⃗+ body v⃗ᵥ) (v⃗! body (vector-map + (v⃗ body) v⃗ᵥ))) (define (x⃗+ body x⃗ᵥ) (x⃗! body (vector-map + (x⃗ body) x⃗ᵥ))) (define (x⃗•x⃗ x⃗) ;; Dot product of a vector (apply + (vector->list (vector-map * x⃗ x⃗)))) (define (d⃗ bᵢ bⱼ) ;; Distance vector '(dx dy dz) between two bodies (vector-map - (x⃗ bᵢ) (x⃗ bⱼ))) (define *sun* (make-body '#(0.0 0.0 0.0) ;; x⃗ (x y z) '#(0.0 0.0 0.0) ;; v⃗ (vx vy vz) 1.0)) ;; mass (define *jupiter* (make-body '#(4.84143144246472090 -1.16032004402742839 -1.03622044471123109e-1) '#(1.66007664274403694e-3 7.69901118419740425e-3 -6.90460016972063023e-5) 9.54791938424326609e-4)) (define *saturn* (make-body '#(8.34336671824457987 4.12479856412430479 -4.03523417114321381e-1) '#(-2.76742510726862411e-3 4.99852801234917238e-3 2.30417297573763929e-5) 2.85885980666130812e-4)) (define *uranus* (make-body '#(1.28943695621391310e1 -1.51111514016986312e1 -2.23307578892655734e-1) '#(2.96460137564761618e-03 2.37847173959480950e-03 -2.96589568540237556e-05) 4.36624404335156298e-05)) (define *neptune* (make-body '#(1.53796971148509165e+01 -2.59193146099879641e+01 1.79258772950371181e-01) '#(2.68067772490389322e-03 1.62824170038242295e-03 -9.51592254519715870e-05) 5.15138902046611451e-05)) (define *system* (list *sun* *jupiter* *saturn* *uranus* *neptune*)) ;; ;; Distance: ;; d⃗ᵢⱼ = '(dx dy dz) = '(xᵢ-xⱼ yᵢ-yⱼ zᵢ-zⱼ) ;; r = sqrt(d⃗•d⃗) = sqrt(dx² + dy² + dz²) ;; ;; Momentum: ;; p⃗ = mᵢ•v⃗ᵢ, v⃗ᵢ = '(vxᵢ vyᵢ vzᵢ) ;; ;; Kinetic energy: ;; Eₖ = 1/2 • mᵢ • (v⃗ᵢ•v⃗ᵢ) ;; ;; Gravitational potencial energy between two bodies: ;; Uᵢⱼ = -1 • mᵢmⱼ/rᵢⱼ ;; ;; Velocity change (advance step) ;; dv⃗ᵢ = -1 • a⃗ᵢ [F/mᵢ = (1/mᵢ • d⃗ᵢⱼ (dx dy dz)/r • mᵢmⱼ/r²] • dt ;; dv⃗ⱼ = -1 • dv⃗ᵢ • mᵢ/mⱼ ;; (define (offset-momentum) (let* ([p⃗ (Λ (body) (a•x⃗ (mass body) (v⃗ body)))] [Σp⃗ (Λ (bodies) (fold-left (Λ (a bᵢ) (vector-map + a (p⃗ bᵢ))) '#(0.0 0.0 0.0) bodies))]) (v⃗! *sun* ;; update sun velocity (a•x⃗ (/ -1.0 (mass *sun*)) (Σp⃗ *system*))))) (define (energy) (letrec* ([Eₖ (Λ (bᵢ) (* 0.5 (mass bᵢ) (x⃗•x⃗ (v⃗ bᵢ))))] [U (Λ (bᵢ bⱼ) (/ (* (mass bᵢ) (mass bⱼ) -1.0) (sqrt (x⃗•x⃗ (d⃗ bᵢ bⱼ)))))] [ΣE (Λ (bodies) ;; kinetic and gravitational potencial energy sum (let ([bᵢ (car bodies)] [b_ (cdr bodies)]) (+ (fold-left (Λ (a bⱼ) (+ a (U bᵢ bⱼ))) (Eₖ bᵢ) b_) (if (null? b_) 0.0 (ΣE b_)))))]) (ΣE *system*))) (define (advance) (letrec ([v⃗← (Λ (bᵢ bⱼ) ;; Velocity advance/update (let* ([d⃗ᵢⱼ (d⃗ bᵢ bⱼ)] [dv⃗ᵢ (a•x⃗ (/ (* -1.0 (mass bⱼ) *dt*) (expt (x⃗•x⃗ d⃗ᵢⱼ) 3/2)) d⃗ᵢⱼ)]) (v⃗+ bᵢ dv⃗ᵢ) (v⃗+ bⱼ (a•x⃗ (/ (mass bᵢ) (mass bⱼ) -1.0) dv⃗ᵢ))))] [x⃗← (Λ (bᵢ) ;; Position advance/update (x⃗+ bᵢ (a•x⃗ *dt* (v⃗ bᵢ))))] [loop (Λ (bodies) (let ([bᵢ (car bodies)] [b_ (cdr bodies)]) (for-each (Λ (bⱼ) (v⃗← bᵢ bⱼ)) b_) (x⃗← bᵢ) (if (not (null? b_)) (loop b_))))]) (loop *system*))) (let* ([arg (cdr (command-line))] [num (if (null? arg) 500000 (string->number (car arg)))]) (offset-momentum) (print* (energy)) (do ([i 0 (+ i 1)]) ((= i num)) (advance)) (print* (energy)))
true
be1664562765bdc2a8559d9166e197d5c4a4cf3d
b8c57f31ad241eb9ce17678725921cb0fba65db9
/test/r7rs-6.6-character.scm
7b9a170f63af3470d31232cb5df408bb79a38002
[]
no_license
AtsukiYokota/meevax
130ab5cb892ae7399970a7d421c4cc96df1e8388
2781b4277b436fdbf85174830b477a07688c1ce1
refs/heads/master
2020-12-09T23:43:20.633092
2019-11-22T23:34:07
2019-11-22T23:34:07
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
243
scm
r7rs-6.6-character.scm
; 6.6 Character #\alarm #\backspace #\delete #\escape #\newline #\null #\return #\space #\tab #\a #\A #\( ; #\ #\x03BB #\iota (digit-value #\3); -> 3 (digit-value #\x0664); -> 4 (digit-value #\x0AE6); -> 0 (digit-value #\x0EA6); -> #false
false
5ac11b03a9502e871d90b81397992272d464de66
ae8b793a4edd1818c3c8b14a48ba0053ac5d160f
/primit.scm
d53d7872740d10d219ba2a15efedc50126a635f4
[]
no_license
experimentsin/telosis
e820d0752f1b20e2913f6f49c0e2a4023f5eda97
4b55140efa8fc732291d251f18f1056dc700442f
refs/heads/master
2020-04-19T08:32:05.037165
2013-07-13T18:59:36
2013-07-13T18:59:36
11,391,770
1
0
null
null
null
null
UTF-8
Scheme
false
false
2,736
scm
primit.scm
; ;; TelosiS module (adapted from Eutopia) Copyright (C) Keith Playford 1992 ; ; ;; $Id: primit.scm,v 1.1 1992/08/09 21:25:26 kjp Exp kjp $ ;; ;; $Log: primit.scm,v $ ;; Revision 1.1 1992/08/09 21:25:26 kjp ;; Initial revision ;; ;; Primitive object allocation. ;; ;; Primitive interface to object allocation and slot access. ;; ; ;; Primitives: (define *unbound-slot-value* (list 'slot-unbound)) ;; rebound later (define (slot-unbound-value) *unbound-slot-value*) (define (slot-unbound-value? o) (eq? *unbound-slot-value* o)) (define *primitive-tag* (list 'telos)) (define (primitive-object? o) (and (vector? o) (= (vector-length o) 2) (eq? (vector-ref o 0) *primitive-tag*))) ; ;; Gripe: ;; ;; So, here we are again tripping over Scheme's most appalling shortcoming - ;; no support for the definition of new disjoint types. Everytime I see ;; an otherwise rational champion of Scheme post code such as that below ;; and claim that Scheme doesn't need that facility, I cringe more ;; violently. They are WRONG!!! You can almost, almost, *almost* do it ;; but, in the end, whatever perverse disguise you've come up with for the ;; object, it will still answer true to one of the internal predicates and ;; submit to direct manipulation by the operations on that type. Even ;; common code is effected by this - in a type switch for example, I must ;; always make sure I test for new types before primitive types to avoid ;; error. This is unacceptable in a modern language. ;; ;; Fingers crossed that they stop hedging and do something about it. ;; ; ;; This particular wacky rep was chosen because Telos objects tend to ;; be viciously circular - almost everything references everything else ;; through some chain - so it's beneficial to wrap these things up in ;; such a way that the standard Scheme output routines won't freak-out. (define (make-primitive-object class slots) (vector *primitive-tag* (lambda (op index value) (case op ((class-ref) class) ((class-set) (set! class value) value) ((ref) (vector-ref slots index)) ((set) (vector-set! slots index value) value) (else 'inconcievable!))))) (define (primitive-allocate class size) (make-primitive-object class (make-vector size *unbound-slot-value*))) (define (primitive-allocate-initialized class . values) (make-primitive-object class (apply vector values))) (define (primitive-ref object index) ((vector-ref object 1) 'ref index #f)) (define (primitive-set! object index value) ((vector-ref object 1) 'set index value)) (define (primitive-class-ref object) ((vector-ref object 1) 'class-ref #f #f)) (define (primitive-class-set! object class) ((vector-ref object 1) 'class-set #f class)) ;; eof
false
7994ad8c3397d919787229a5ab1232f1afc0c2fb
de7bd741808e14126905d922ee4fbc4c661dbda1
/0.2.1/scm/gambit/flat-domain.scm
e3fbccc4239f04bba299e4ba64135a52a3b94380
[ "Apache-2.0" ]
permissive
mikelevins/categories
023bec294f51f769c054191746a88965a874eca5
66e3861071e4d88b7b27421a78ab497e1fb5fa0c
refs/heads/master
2016-09-05T21:31:58.879869
2013-02-05T10:38:25
2013-02-05T10:38:25
5,856,317
5
0
null
null
null
null
UTF-8
Scheme
false
false
1,328
scm
flat-domain.scm
;;;; *********************************************************************** ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: flat-domain.scm ;;;; Project: Categories ;;;; Purpose: The -flat- domain ;;;; Author: mikel evins ;;;; Copyright: Copyright 2009 by mikel evins, all rights reserved ;;;; License: Licensed under the Apache License, version 2.0 ;;;; See the accompanying file "License" for more information ;;;; ;;;; *********************************************************************** ;;; ---------------------------------------------------------------------- ;;; auxiliary functions ;;; ---------------------------------------------------------------------- (define (flat:find-method fun vals) (let* ((vsig (map type vals)) (mtable (get-method-table fun)) (entries (fun:get-method-entries mtable))) (utils:get entries vsig equal? #f))) ;;; ---------------------------------------------------------------------- ;;; imoplementation of the domain API ;;; ---------------------------------------------------------------------- (define (flat:select-methods fun vals) (let ((meth (flat:find-method fun vals))) (if meth (values meth #f #f) (values #f #f #f)))) (define =flat= (domain 'method-selector flat:select-methods))
false
f0b97605b36b8b2b36c2f37da8d8fcb1cc779d70
354ae3428451a81e5a6e07d282edb9bd79ff0e3f
/scribblings/utils.ss
f4c281c26736a84fe55c3b9b6a73224f5ec54cac
[]
no_license
jeapostrophe/datalog
385a478dc18a904a35cbe36ebc7b1a7ec0a26478
a5d59e455b49d091f3c5348e4c1f0071a1bc0134
refs/heads/master
2021-01-18T13:42:51.827415
2013-10-31T01:32:07
2013-10-31T01:32:07
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
237
ss
utils.ss
#lang scheme/base (require scribble/eval (planet cce/scheme:6/planet)) (provide the-eval) (define the-eval (let ([the-eval (make-base-eval)]) (the-eval `(require (planet ,(this-package-version-symbol)))) the-eval))
false
c6253016f9fae9cde821aa76bdac4da5306ed1a1
bcfa2397f02d5afa93f4f53c0b0a98c204caafc1
/scheme/chapter2/ex2_32.scm
5ee663dbbb913cad052677fa47fe29029da2dd95
[]
no_license
rahulkumar96/sicp-study
ec4aa6e1076b46c47dbc7a678ac88e757191c209
4dcd1e1eb607aa1e32277e1c232a321c5de9c0f0
refs/heads/master
2020-12-03T00:37:39.576611
2017-07-05T12:58:48
2017-07-05T12:58:48
96,050,670
0
0
null
2017-07-02T21:46:09
2017-07-02T21:46:09
null
UTF-8
Scheme
false
false
1,082
scm
ex2_32.scm
;; SICP 2.32 ;; Exercise 2.32. We can represent a set as a list of distinct ;; elements, and we can represent the set of all subsets of the set as ;; a list of lists. For example, if the set is (1 2 3), then the set ;; of all subsets is (() (3) (2) (2 3) (1) (1 3) (1 2) (1 2 ;; 3)). Complete the following definition of a procedure that ;; generates the set of subsets of a set and give a clear explanation ;; of why it works: ;; (define (subsets s) ;; (if (null? s) ;; (list nil) ;; (let ((rest (subsets (cdr s)))) ;; (append rest (map <??> rest))))) ;; ANSWER ------------------------------------------------------------ (define (subsets s) (if (null? s) (list ()) (let ((rest (subsets (cdr s)))) (append rest (map (lambda (x) (cons (car s) x)) rest))))) ;; The value assigned to rest is all subsets the constructed from the ;; remaining items in the set. So, remember that list of subsets, and ;; construct additional subsets that include the current element. By ;; induction, this works for sets of any size.
false
fcd3158f34148c169cb296f62de1393881ff1dbb
c3523080a63c7e131d8b6e0994f82a3b9ed901ce
/hertfordstreet/sicp/chapter4/macrotutorial.ss
fe7f31bcb376e4d47a090d92d17c6a586876e9b8
[]
no_license
johnlawrenceaspden/hobby-code
2c77ffdc796e9fe863ae66e84d1e14851bf33d37
d411d21aa19fa889add9f32454915d9b68a61c03
refs/heads/master
2023-08-25T08:41:18.130545
2023-08-06T12:27:29
2023-08-06T12:27:29
377,510
6
4
null
2023-02-22T00:57:49
2009-11-18T19:57:01
Clojure
UTF-8
Scheme
false
false
5,841
ss
macrotutorial.ss
#lang scheme ;macro tutorial ;www.cs.utah.edu/classes/cs6520-mflatt/s04/macro-tutorial.pdf (define-syntax swap (syntax-rules () ((swap a b) (let ((tmp b)) (set! b a) (set! a tmp))))) ;lexical scope! (let ((tmp 5) (other 6)) (swap tmp other) (list tmp other)) ;lexical scope means that we can use local macros too (define (f x) (define-syntax swap-with-arg (syntax-rules () ((swap-with-arg y) (swap x y)))) (list x (let ((z 12) (x 10)) (swap-with-arg z) (list x z)))) (f 5) ;ok, how about rotate? (define-syntax rotate (syntax-rules () ((rotate a) (void)) ((rotate a b c ...) (begin (swap a b) (rotate b c ...))))) (let ((a 1)(b 2)(c 3)) (rotate a b c) (list a b c)) ;works at repl but not in code, don't know why ;(syntax->datum (expand-once '(rotate a b c))) ;that rotate is a bit mangy. We can do better (define-syntax better-rotate (syntax-rules () ((better-rotate a c ...) (shift-to (c ... a) (a c ...))))) ;to define the sub-macro ;we take advantage of the fact that the pattern matching is too good to be true. (define-syntax shift-to (syntax-rules () ((shift-to (from0 from ...) (to0 to ...)) (let ((tmp from0)) (set! to from) ... (set! to0 tmp))))) (let ((a 1)(b 2)(c 3)) (better-rotate a b c) (list a b c)) ;(syntax->datum (expand-once '(better-rotate a b c))) ;identifier macros (utterly contrived and useless example?) (define clocktime "17:00") (define (get-clock) clocktime) (define (put-clock! a) (set! clocktime a)) (define-syntax clock (syntax-id-rules (set!) ((set! clock e) (put-clock! e)) ((clock a ...) (print "na")) (clock (get-clock)))) ;;got bored here as he goes on to do call-by-reference using syntax-rules ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;http://c2.com/cgi-bin/wiki?DefineSyntax (fixed up by me because it was broken) (define-syntax aif (lambda (expr) (syntax-case expr () ((aif test then) (with-syntax ((it-id (datum->syntax (syntax aif) 'it))) (syntax (let ((tmp test)) (if tmp (let ((it-id tmp)) then)))))) ((aif test then else) (with-syntax ((it-id (datum->syntax (syntax aif) 'it))) (syntax (let ((tmp test)) (if tmp (let ((it-id tmp)) then) (let ((it-id tmp)) else) )))))))) (let ((x 1)) (aif (> x 2) (cons it it) (cons it '()))) (let ((x 3)) (aif (> x 2) (cons it it) (cons it '()))) ; a cut down anaphoric when (define-syntax awhen (lambda (expr) (syntax-case expr () ((awhen test then) (with-syntax ((it-id (datum->syntax (syntax awhen) 'it))) (syntax (let ((tmp test)) (if tmp (let ((it-id tmp)) then) (void))))))))) (awhen (assq 1 '((1 . hello) (2 . bye))) (print (cdr it))) ;of course you can sort of do that with cond anyway (cond ((assq 1 '((1 . hello) (2 . bye))) => (λ(x)(print (cdr x))))) ;my first syntax-case macro (define-syntax fluffy (lambda (expr) (syntax-case expr () ((fluffy a b) (syntax (printf "~a ~a~n" a b)))))) ;behold its glory (fluffy 'hello 'world) ;http://www.scheme.com/tspl2d/syntax.html ;Hang on, I see how it must work. Syntax objects are just list structure with lexical data attached. ;they have their own quote unquote quasiquote operators, called syntax unsyntax quasisyntax, whose ;abbreviations are #' #, #` (define syntaxobjectlist (list (syntax a) #'a #'(a b c) (let ((x 'a)) #'(a b c x)) (let ((x 'a)) #'(a b c ,x)) (let ((x 'a)) #'(a b c #,x)) (let ((x 'a)) #`(a b c #,x)))) ; syntax->datum strips the syntactic information, just leaving the code without its context. (map syntax->datum syntaxobjectlist) ;I'm conjecturing here, but I think syntax-case is just a function which does pattern matching ;usually it's used to return syntax objects (syntax-case '(random expression) () (_ (syntax (b a)))) ;but it doesn't have to: (syntax-case '(random expression with literal) (literal) (_ 2)) ;no, backtracking here. It must be a macro to do this substitution (syntax-case '(random expression with literal) (literal) ((random a b literal) (syntax (a b)))) ;it appears that it can substitute pattern matching variables into syntax expressions (syntax-case '(random expression with literal) (literal) ((random a b literal) (syntax (a b)))) ;the pattern matching is pretty powerful (syntax->datum (syntax-case '(cleantests evaltests (test1 result1) (test2 result2) (test3 result3)) () ((_ name (a b) ...) (syntax (testsuite name (cleantest a b) ...))))) ;enabling me to write test macros beyond my wildest dreams (syntax->datum (syntax-case '(cleantests evaltests (1 -> 1) (((λ(x)2) 1) -> 2)) (->) ((_ name (t -> r) ...) (syntax (testsuite name (cleantest t r) ...))))) ;here's that wrapped up into a usable macro (relies on testsuite and cleantest already being defined though) (define-syntax paralleltestsincleanenvironment (lambda (stx) (syntax-case stx (->) ((_ name (a -> b) ...) (syntax (testsuite name (cleantest a b) ...)))))) ;of course it's slightly vexing to realize that after all that I could have done it with define-syntax-rule (define-syntax-rule (ptce1 name (a -> b) ...) (testsuite name (cleantest a b) ...)) ;although actually that doesn't work because -> is a variable, so it matches (a b c) as well as (a -> b) (define-syntax ptce (syntax-rules (->) (_ (a -> b) ...) (testsuite name (cleantest a b) ...)))
true
d529e087980baf79ef1cb4e68346c66fece642d2
9686fd1d8c004ec241c14bbbfd8e4dfc06452a9c
/modules/stay-alive/armor.scm
f6f939d174c63e7f65e48dec1272bf9acb09b9ed
[]
no_license
mwitmer/StayAlive
edd5e5cb55cc698d033eafca1df7bbd379410d80
137b15ac06414adaeca0ff01750a779c89d871e0
refs/heads/master
2021-01-23T03:54:04.289089
2012-11-09T17:22:02
2012-11-09T17:22:02
5,642,903
7
1
null
null
null
null
UTF-8
Scheme
false
false
1,266
scm
armor.scm
(define-module (stay-alive armor) #:use-module (shelf shelf) #:use-module (stay-alive item) #:export (Armor Buckler LeatherArmor Gauntlets)) (define-objects Armor ((symbol 'armor) (armor #t) (use (method (level agent) (if (this 'worn? #:def #f) (this 'take-off level agent) (this 'put-on level agent)))) (can-wear? #t)) ((Shield ((wear-requires (h (also-wield? 'hand) (quantity 1) (pred (method (part) (eq? (part 'name) 'arm)))))) ((Buckler ((name "buckler") (describe-long "A handy little shield that can block a sword blow but won't do you much good versus slings and arrows."))))) (BodyArmor ((wear-requires (h (quantity 1) (pred (method (part) (eq? (part 'name) 'torso)))))) ((LeatherArmor ((name '("suit of leather armor" "suits of leather armor")) (describe-long "A thing layer of animal skin that doesn't seem to protect you from much."))))) (BaseGloves ((wear-requires (h (quantity 2) (pred (method (part) (eq? (part 'name) 'hand)))))) ((Gauntlets ((name '("pair of gauntlets" "pairs of gauntlets")) (describe-long "A shiny pair of metal gloves with a cold, snug fit."))))))) (extend Item (list Armor))
false
8540dd7e5b90bf3a5768ade23716b0ad480ed680
bfff08ec416296ebf11ed9181789608f0836419c
/first-edition/chapter 5/5.5.4.scm
00bd0ca2e64cf7aba481ef26af5f46288e01979a
[]
no_license
kesava/eopl
8c54bb024ee50478ce6f7835fa1f511236a64175
9c6cf32e9bdc6ff659ecb45feabaa38550e732a5
refs/heads/master
2022-01-24T15:21:30.826989
2021-12-27T02:23:36
2021-12-27T02:23:36
170,910,305
3
0
null
null
null
null
UTF-8
Scheme
false
false
4,787
scm
5.5.4.scm
#lang eopl (require "../define-record.rkt") (require "../string-parser.rkt") (require readline/readline) (require "../util.rkt") (require "../cell.rkt") (define-record lit (datum)) (define-record varref (var)) (define-record lambda (formal body)) (define-record app (rator rand)) (define-record if (test-exp then-exp else-exp)) (define-record let (decls body)) (define-record decl (var exp)) (define-record proc (formals body)) (define-record closure (formals body env)) (define-record varassign (var expr)) (define-record begin (exp1 exp2)) (define true-value? (lambda (x) (not (zero? x)))) (define eval-exp (lambda (exp env) (displayln "---------") (displayln "eval-exp: " exp) (displayln "---------") (variant-case exp (lit (datum) datum) (varref (var) (begin ;(displayln "var: " var) (cell-ref (apply-env env var)))) (if (test-exp then-exp else-exp) (if (true-value? (eval-exp test-exp env)) (eval-exp then-exp env) (eval-exp else-exp env))) (app (rator rands) (let ((proc (eval-exp rator env)) (args (eval-rands rands env))) (apply-proc proc args))) (varassign (var exp) (cell-set! (apply-env env var) (eval-exp exp env))) (proc (formals body) (make-closure formals body env)) (begin (exp1 exp2) (eval-exp exp1 env) (eval-exp exp2 env)) (else (eopl:error "Invalid AST: " exp))))) (define denoted->expressed cell-ref) (define eval-rands (lambda (rands env) ;(displayln "-----eval-rands: rands: " rands "; env: " env " -----") (map (lambda (rand) (make-cell (eval-exp rand env))) rands))) (define-record prim-proc (prim-op)) (define apply-proc (lambda (proc args) ;(displayln "invoking apply-proc") (variant-case proc (prim-proc (prim-op) (begin (displayln prim-op "->" args) (apply-prim-op prim-op (map denoted->expressed args)))) (closure (formals body env) (eval-exp body (extend-env formals args env))) (else (eopl:error "Invalid procedure: " proc))))) (define ft->01 (lambda (x) (if x 1 0))) ; Exercise 5.4.4 (define syntax-expand (lambda (exp) (displayln "syntax-expand exp: " exp) (variant-case exp (lit (datum) exp) (varref (var) exp) (if (test-exp then-exp else-exp) exp) (let (decls body) (let ((vars (map decl->var decls)) (exps (map decl->exp decls))) (make-app (make-proc vars body) exps))) (proc (formals body) exp) (app (rator rands) exp) (begin (exp1 exp2) exp) (varassign (var expr) exp) (else (eopl:error "Invalid AST: " exp))))) (define apply-prim-op (lambda (prim-op args) (displayln "prim-op: " prim-op args) (case prim-op ((+) (+ (car args) (cadr args))) ((-) (- (car args) (cadr args))) ((*) (* (car args) (cadr args))) ((add1) (+ (car args) 1)) ((sub1) (- (car args) 1)) ((minus) (- 0 (car args))) ; Exercise 5.1.3 ((list) args) ; Exercise 5.1.4 ((car) (caar args)) ; Exercise 5.1.4 ((cdr) (cdar args)) ; exercise 5.1.4 ((null) (ft->01 (null? (car args)))) ; Exercise 5.2.3 ((cons) (cons (car args) (cadr args))) ; Exercise 5.1.4 ((eq) (eq? (car args) (cadr args))) ; Exercise 5.3.2 ((equal) (ft->01 (= (car args) (cadr args)))) ; Exercise 5.2.2 ((greater) (ft->01 (> (car args) (cadr args)))) ; Exercise 5.2.2 ((less) (ft->01 (< (car args) (cadr args)))) ; Exercise 5.2.2 ((zero) (ft->01 (= (car args) 0))) ; Exercise 5.2.2 (else (eopl:error "Invalid prim-op name: " prim-op))))) (define prim-op-names '(+ - * add1 sub1 minus list car cdr cons equal greater less zero null eq)) (define init-env (extend-env prim-op-names (map make-cell (map make-prim-proc prim-op-names)) (extend-ff 'emptylist '() the-empty-env))) (define run (lambda (x) (eval-exp (parse x)))) (define parse character-string-parser) (write (eval-exp (syntax-expand (parse "let x = 3 in begin x := add1(x); x := +(x, x); +(x, 2) end")) init-env)) ; 10 ;; lang eopl doesnt support standard scheme read-line. So using a different package readline. ;(define repl ; (lambda () ; (define x (readline "-->")) ; (write (length x)) ; ;(write (parse (readline "-->"))) ; ; (write (eval-exp (syntax-expand (parse (readline "-->"))) init-env)) ; (newline) ; (repl)))
false
5ad82b11108a912a630a21a028d04ae5cf311496
ac2a3544b88444eabf12b68a9bce08941cd62581
/lib/guide/_guide#.scm
2d11dcc0ec25b3c39e763b06027c9d35936bf7fc
[ "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
657
scm
_guide#.scm
;============================================================================== ; File: "_guide#.scm", Time-stamp: <2007-04-04 11:32:46 feeley> ; Copyright (c) 1994-2007 by Marc Feeley, All Rights Reserved. ;============================================================================== (define-type-of-repl-channel repl-channel-guide id: e188675f-7d4e-4e1f-8eb0-01a25aae640b extender: define-type-of-repl-channel-guide implementer: implement-type-repl-channel-guide macros: prefix: macro- opaque: equality-skip: unprintable: far-port GuideUiScheme ) ;==============================================================================
false
e7400b19c6c22718fcfaa1d2f01dabf927e22d40
87f1e27952a387ff6a7d0625169d9a4f6cd960b2
/guix/scripts/process.scm
0d489f61a366c431ea3632dd8a84bbf5dff13716
[]
no_license
guixwl/gwl
f5d21ca3563eed71e5cabb076f783fab63309cd1
036a6e043b9ee010b0ca7eaa5bd1381555385808
refs/heads/master
2020-03-17T23:42:10.633451
2018-03-11T11:22:16
2018-05-17T10:11:40
134,056,393
0
0
null
null
null
null
UTF-8
Scheme
false
false
7,033
scm
process.scm
;;; Copyright © 2016, 2017, 2018 Roel Janssen <[email protected]> ;;; Copyright © 2018 Ricardo Wurmus <[email protected]> ;;; ;;; 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 3 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, see <http://www.gnu.org/licenses/>. (define-module (guix scripts process) #:use-module (guix ui) #:use-module (guix scripts) #:use-module (guix utils) #:use-module (guix processes) #:use-module (guix process-engines) #:use-module (gnu processes) #:use-module (ice-9 match) #:use-module (ice-9 vlist) #:use-module (srfi srfi-37) #:use-module (srfi srfi-1) #:export (guix-process)) (define (show-help) (for-each (lambda (line) (display line) (newline)) '("Usage: guix process [OPTION]..." "Run a predefined computational process." "" " -i, --input=LOCATION set LOCATION as input for a workflow" " -o, --output=LOCATION set LOCATION as output for a workflow" " -e, --engine=ENGINE set ENGINE for offloading to a cluster" " -l, --list-available list available processes" " -p, --prepare=PROCESS Prepare the running of a PROCESS" " -r, --run=PROCESS Run PROCESS" " -s, --search=REGEXP search in synopsis and description using REGEXP" " -h, --help display this help and exit" " -V, --version display version information and exit" ""))) (define (show-available-processes args) "Display available processes." (format #t "Available processes:~%") (let ((processes (fold-processes (lambda (p r) (if (string= (process-version p) "") (vhash-cons (format #f "~a" (process-name p)) p r) (vhash-cons (format #f "~a (~a)" (process-name p) (process-version p)) p r))) vlist-null))) (vlist-for-each (lambda (pair) (format #t " * ~a~%" (car pair))) processes)) (newline)) (define %options ;; List of command-line options. (list (option '(#\h "help") #f #f (lambda args (show-help) (exit 0))) (option '(#\V "version") #f #f (lambda args (show-version-and-exit "guix process"))) (option '(#\e "engine") #t #f (lambda (opt name arg result) (alist-cons 'engine arg (alist-delete 'engine result)))) (option '(#\i "input") #t #f (lambda (opt name arg result) (alist-cons 'input arg (alist-delete 'input result)))) (option '(#\o "output") #t #f (lambda (opt name arg result) (alist-cons 'output arg (alist-delete 'output result)))) (option '(#\p "prepare") #t #f (lambda (opt name arg result) (alist-cons 'query 'prepare (alist-cons 'value arg (alist-delete 'prepare result))))) (option '(#\r "run") #t #f (lambda (opt name arg result) (alist-cons 'query 'run (alist-cons 'value arg (alist-delete 'run result))))) (option '(#\s "search") #t #f (lambda (opt name arg result) (alist-cons 'query 'search (alist-cons 'value arg (alist-delete 'search result))))) (option '(#\l "list-available") #f #f (lambda args (show-available-processes args))))) (define %default-options `((engine . "bash-engine"))) ;;; ;;; Entry point. ;;; (define (guix-process . args) (define (parse-options) ;; Return the alist of option values. (args-fold* args %options (lambda (opt name arg result) (leave (G_ "~A: unrecognized option~%") name)) (lambda (arg result) (when (assq 'argument result) (leave (G_ "~A: extraneous argument~%") arg)) (alist-cons 'argument arg result)) %default-options)) (let ((opts (parse-options))) (match (assoc-ref opts 'query) ;; Handle searching for a process. ;; ---------------------------------------------------------------------- ('search (let* ((procs (find-processes (assoc-ref opts 'value)))) (unless (null? procs) (vlist-for-each (lambda (proc) (print-process-record (cdr proc) #t)) procs))) #t) ;; Handle running a process. ;; ---------------------------------------------------------------------- ('prepare ;; TODO: Deal with the situation wherein multiple processes ;; with the same name are defined. (let* ((procs (find-process-by-name (assoc-ref opts 'value))) (proc (if (null? procs) '() (car procs))) (engine-name (assoc-ref opts 'engine)) (proc-name (assoc-ref opts 'value))) (when (not proc-name) (leave (G_ "Please provide --engine and --run arguments.~%"))) (when (not (process? proc)) (leave (G_ "Cannot find a process with name ~s.~%") proc-name)) (let ((engine (find-engine-by-name engine-name))) (when (not engine) (leave (G_ "The engine ~s is not available.~%") engine-name)) (process->script proc engine))) #t) ('run (let* ((procs (find-process-by-name (assoc-ref opts 'value))) (proc (if (null? procs) '() (car procs))) (engine-name (assoc-ref opts 'engine)) (proc-name (assoc-ref opts 'value))) (when (not proc-name) (leave (G_ "Please provide --engine and --run arguments.~%"))) (when (not (process? proc)) (leave (G_ "Cannot find a process with name ~s.~%") proc-name)) (let ((engine (find-engine-by-name engine-name))) (when (not engine) (leave (G_ "The engine ~s is not available.~%") engine-name)) (process->script->run proc engine))) #t) ;; Handle (or don't handle) anything else. ;; ---------------------------------------------------------------------- (_ #t))))
false
938512464b03cbf8ed5aa33b56e4deca0a2c4a6b
f4cf5bf3fb3c06b127dda5b5d479c74cecec9ce9
/Sources/LispKit/Resources/Examples/VisualizePointSets.scm
e2b49fe7b89419317ce04dcc67314223cd2eedce
[ "Apache-2.0" ]
permissive
objecthub/swift-lispkit
62b907d35fe4f20ecbe022da70075b70a1d86881
90d78a4de3a20447db7fc33bdbeb544efea05dda
refs/heads/master
2023-08-16T21:09:24.735239
2023-08-12T21:37:39
2023-08-12T21:37:39
57,930,217
356
17
Apache-2.0
2023-06-04T12:11:51
2016-05-03T00:37:22
Scheme
UTF-8
Scheme
false
false
17,150
scm
VisualizePointSets.scm
;;; Visualize points, lines and planes ;;; ;;; This program visualizes points, lines and planes in a 3-dimensional cartesian coordinate ;;; system using an oblique projection as described in http://zenger.org/papers/fa.pdf (in ;;; German). ;;; ;;; The oblique projection used to map 3-dimensional vectors into 2-dimensional screen ;;; coordinates is described in terms of the following parameters: ;;; ;;; - _bounds_ : a vector of ranges describing the space that is visualized (as a cube) ;;; - _root_ : screen coordinates specifying the center of the visualized space ;;; - _angles_ : a vector of angles (radian) describing the drawing angle of the axis ;;; for all three dimensions ;;; - _factors_: a vector of factors specifying the size of the visualized space on ;;; the screen ;;; ;;; The record `projection` implements such oblique projections. Function `make-projection` ;;; is used to create a new projection object consisting of the parameters listed above. ;;; ;;; 3-dimensional point sets such as points, lines, and planes, are created using the ;;; following constructor functions: ;;; ;;; - `(point x)` creates a point; `x` is a vector of length 3 of floating-point ;;; numbers describing the location of the point. ;;; - `(line x u)` creates a line from a location vector `x` and a direction vector `u`. ;;; - `(plane x u v)` creates a plane from a location vector `x` and two direction ;;; vectors `u` and `v`. ;;; ;;; A number of drawing functions can be used to create drawings containing visualizations ;;; of axis, the bounds of the displayed space (in form of a cube), as well as point sets: ;;; ;;; - `(draw-projection-axis proj d)` draws the three axis using projection `proj` ;;; into the drawing `d`. ;;; - `(draw-projection-cube proj d)` draws a cube depicting the boundaries of ;;; projection `proj` into drawing `d`. ;;; - `(draw-point-set proj ps lcol fcol d)` draws the point set `ps` into drawing ;;; `d` using projection `proj`. `lcol` specifies the line color, `fcol` specifies ;;; the surface/fill color used for planes. ;;; - `(draw-projection proj pss d)` draws axis, the boundary cube, as well as the ;;; point sets in list `pss` into drawing `d`. Elements of `pss` are either ;;; point sets or lists of the form `(ps lcol fcol)` where `ps` is a point set, and ;;; `lcol` and `fcol` are colors. ;;; ;;; Invoking the following procedure will save two demo projections into a PDF file at the ;;; given path: ;;; (save-demo-drawings "~/Desktop/ProjectionDemo.pdf") ;;; ;;; ;;; Author: Matthias Zenger ;;; Copyright © 2021 Matthias Zenger. All rights reserved. ;;; ;;; 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. (import (lispkit base) (rename (lispkit draw) (point coord) (point-x coord-x) (point-y coord-y) (move-point move-coord) (point? coord?))) ;; Utilities (define (sqr x) (* x x)) (define (deg->rad w) (/ (* w pi) 180.0)) (define (rad->deg w) (/ (* w 180.0) pi)) ;; Ranges (define-values (range-type-tag new-range range? range-ref make-range-subtype) (make-type 'range)) (define (range min max) (assert (real? min) (real? max)) (new-range (list (real->flonum min) (real->flonum max)))) (define (range-min rng) (car (range-ref rng))) (define (range-max rng) (cadr (range-ref rng))) (define (range-size rng) (- (range-max rng) (range-min rng))) (define (fraction-in-range x rng) (/ (- x (range-min rng)) (range-size rng))) (define (range-contains? rng x) (and (>= x (range-min rng)) (<= x (range-max rng)))) ;; Coordinates (define (add-coord p . ps) (if (null? ps) p (apply add-coord (coord (+ (coord-x p) (coord-x (car ps))) (+ (coord-y p) (coord-y (car ps)))) (cdr ps)))) (define (magnitude+angle->coord mag angle) (coord (* mag (cos angle)) (- (* mag (sin angle))))) ;; Vectors with three elements (define (vector-predicate f) (lambda (v) (and (vector? v) (= (vector-length v) 3) (f (vector-ref v 0)) (f (vector-ref v 1)) (f (vector-ref v 2))))) (define real-vector? (vector-predicate real?)) (define range-vector? (vector-predicate range?)) (define (zero-vector? v) (and (zero? (vector-ref v 0)) (zero? (vector-ref v 1)) (zero? (vector-ref v 2)))) (define (round-number n) (/ (truncate (* (real->flonum n) 10000.0)) 10000.0)) (define (round-vector v) (vector-set! v 0 (round-number (vector-ref v 0))) (vector-set! v 1 (round-number (vector-ref v 1))) (vector-set! v 2 (round-number (vector-ref v 2))) v) ;; Oblique projection (define-record-type projection (new-projection bounds root angles factors) projection? (bounds projection-bounds) (root projection-root set-projection-root!) (angles projection-angles) (factors projection-factors)) (define (make-projection bounds root angles factors) (assert (range-vector? bounds) (coord? root) (real-vector? angles) (real-vector? factors)) (new-projection bounds root angles factors)) (define (copy-projection proj . args) (let-optionals args ((bounds #f) (root #f) (angles #f) (factors #f)) (make-projection (if bounds bounds (projection-bounds proj)) (if root root (projection-root proj)) (if angles angles (projection-angles proj)) (if factors factors (projection-factors proj))))) (define current-projection (make-parameter (make-projection (vector (range -10 10) (range -10 10) (range -10 10)) (coord 200 200) (vector (deg->rad 0) (deg->rad 90) (deg->rad 225)) (vector 200.0 200.0 100.0)))) (define (projection-includes? proj v) (let ((bounds (projection-bounds proj))) (and (range-contains? (vector-ref bounds 0) (vector-ref v 0)) (range-contains? (vector-ref bounds 1) (vector-ref v 1)) (range-contains? (vector-ref bounds 2) (vector-ref v 2))))) (define (projection-includes-zero? proj) (projection-includes? proj #(0 0 0))) (define (projection-corners proj) (let* ((bounds (projection-bounds proj)) (xbounds (vector-ref bounds 0)) (ybounds (vector-ref bounds 1)) (zbounds (vector-ref bounds 2))) (vector (vector (range-min xbounds) (range-min ybounds) (range-min zbounds)) (vector (range-max xbounds) (range-min ybounds) (range-min zbounds)) (vector (range-min xbounds) (range-max ybounds) (range-min zbounds)) (vector (range-max xbounds) (range-max ybounds) (range-min zbounds)) (vector (range-min xbounds) (range-min ybounds) (range-max zbounds)) (vector (range-max xbounds) (range-min ybounds) (range-max zbounds)) (vector (range-min xbounds) (range-max ybounds) (range-max zbounds)) (vector (range-max xbounds) (range-max ybounds) (range-max zbounds))))) ;; Transform vectors into points (define (projected-coord proj v i) (magnitude+angle->coord (* (- (fraction-in-range (vector-ref v i) (vector-ref (projection-bounds proj) i)) 0.5) (vector-ref (projection-factors proj) i)) (vector-ref (projection-angles proj) i))) (define (vector->coord proj v) (add-coord (projection-root proj) (projected-coord proj v 0) (projected-coord proj v 1) (projected-coord proj v 2))) ;; Point sets in a 3-dimensional space (define-values (point-set-type new-point-set point-set? point-set-ref make-point-set-subtype) (make-type 'point-set)) (define (point a) (assert (real-vector? a)) (new-point-set (list a #(0 0 0) #(0 0 0)))) (define (line a u) (assert (real-vector? a) (real-vector? u)) (new-point-set (list a u #(0 0 0)))) (define (plane a u v) (assert (real-vector? a) (real-vector? u) (real-vector? v)) (new-point-set (list a u v))) (define (point-set-location ps) (car (point-set-ref ps))) (define (point-set-vectors ps) (apply values (point-set-ref ps))) (define (point-set-point? ps) (let-values (((a u v) (point-set-vectors ps))) (and (zero-vector? u) (zero-vector? v)))) (define (point-set-line? ps) (let-values (((a u v) (point-set-vectors ps))) (not (boolean=? (zero-vector? u) (zero-vector? v))))) (define (point-set-plane? ps) (let-values (((a u v) (point-set-vectors ps))) (and (not (zero-vector? u)) (not (zero-vector? v))))) ;; Polygons (lists of vectors) (define (polygon? vs) (every? real-vector? vs)) (define (polygon-points-for-bound proj a u v i bound) (if (not (zero? (vector-ref u i))) (let ((j (remainder (+ i 1) 3)) (k (remainder (+ i 2) 3)) (p (/ (- bound (vector-ref a i)) (vector-ref u i))) (q (/ (vector-ref v i) (vector-ref u i))) (sa (vector 0.0 0.0 0.0)) (su (vector 0.0 0.0 0.0))) (vector-set! sa i bound) (vector-set! sa j (+ (vector-ref a j) (* (vector-ref u j) p))) (vector-set! sa k (+ (vector-ref a k) (* (vector-ref u k) p))) (vector-set! su j (- (vector-ref v j) (* (vector-ref u j) q))) (vector-set! su k (- (vector-ref v k) (* (vector-ref u k) q))) (point-set->polygon proj (line sa su))) '())) (define (polygon-points-for-dimension proj a u v i) (let ((bounds (vector-ref (projection-bounds proj) i))) (append (polygon-points-for-bound proj a u v i (range-min bounds)) (polygon-points-for-bound proj a u v i (range-max bounds))))) (define (polygon-points proj ps i) (let-values (((a u v) (point-set-vectors ps))) (if (zero? (vector-ref u i)) (polygon-points-for-dimension proj a v u i)) (polygon-points-for-dimension proj a u v i))) (define (point-set->polygon proj ps) (if (point-set-point? ps) (let ((v (round-vector (point-set-location ps)))) (if (projection-includes? proj v) (list v) '())) (append (polygon-points proj ps 0) (polygon-points proj ps 1) (polygon-points proj ps 2)))) (define (dimension-match n1 n2 rng) (and (= n1 n2) (or (= n1 (range-min rng)) (= n1 (range-max rng))))) (define (adjacent-vectors? proj v1 v2) (let ((bounds (projection-bounds proj))) (or (dimension-match (vector-ref v1 0) (vector-ref v2 0) (vector-ref bounds 0)) (dimension-match (vector-ref v1 1) (vector-ref v2 1) (vector-ref bounds 1)) (dimension-match (vector-ref v1 2) (vector-ref v2 2) (vector-ref bounds 2))))) (define (sort-polygon proj v vs nvs) (if (pair? vs) (if (equal? v (car vs)) (sort-polygon proj v (cdr vs) nvs) (if (adjacent-vectors? proj v (car vs)) (cons (car vs) (sort-polygon proj (car vs) (append (delete v (cdr vs)) nvs) '())) (sort-polygon proj v (cdr vs) (cons (car vs) nvs)))) '())) (define (normalize-polygon proj vs) (if (pair? vs) (cons (car vs) (sort-polygon proj (car vs) (cdr vs) '())) '())) ;;; Drawing procedures (define (draw-solid-line proj v1 v2 d) (draw-line (vector->coord proj v1) (vector->coord proj v2) d)) (define (draw-line-with-angle c mag angle) (line-to (add-coord c (magnitude+angle->coord mag angle)))) (define (draw-outlined-text s c col d) (let ((fnt (font "Times" 14)) (boldfnt (font "Times" 14 extrablack))) (for-each (lambda (dx) (for-each (lambda (dy) (draw-text s (move-coord c dx dy) boldfnt white d)) '(-2.0 -1.0 0.0 1.0 2.0))) '(-1.0 -0.5 0.0 0.5 1.0)) (draw-text s c fnt col d))) (define (draw-vector proj v1 v2 s col d) (let* ((c1 (vector->coord proj v1)) (c2 (vector->coord proj v2)) (dx (- (coord-x c2) (coord-x c1))) (dy (- (coord-y c1) (coord-y c2))) (adj (coord -6 -13)) (w (if (= dx 0) (if (>= dy 0) 90.0 180.0) (+ (rad->deg (atan (/ dy dx))) (if (>= dx 0.0) 0.0 180.0))))) (set-color (color 0.0 0.0 0.5) d) (draw-dashed (shape (move-to c1) (line-to c2) (draw-line-with-angle c2 10 (deg->rad (+ w 150))) (move-to c2) (draw-line-with-angle c2 10 (deg->rad (- w 150)))) '(2.0 1.0) 0 1.0 d) (draw-outlined-text s (add-coord c2 (magnitude+angle->coord 11 (deg->rad w)) adj) col d))) (define (draw-axis proj i s d) (let ((from (vector 0.0 0.0 0.0)) (to (vector 0.0 0.0 0.0)) (rng (vector-ref (projection-bounds proj) i)) (col (color 0.0 0.0 0.7))) (vector-set! from i (range-min rng)) (vector-set! to i (+ (* 1.3 (range-size rng)) (range-min rng))) (draw-vector proj from to s col d))) (define (draw-projection-axis proj . args) (if (projection-includes-zero? proj) (let-optionals args ((d (current-drawing))) (draw-axis proj 0 "x₁" d) (draw-axis proj 1 "x₂" d) (draw-axis proj 2 "x₃" d)))) (define (draw-projection-cube proj . args) (let-optionals args ((d (current-drawing))) (do ((cns (projection-corners proj)) (x 0 (+ x 1))) ((> x 3)) (set-line-width 2.5 d) (draw-solid-line proj (vector-ref cns (* 2 x)) (vector-ref cns (+ (* 2 x) 1)) d) (draw-solid-line proj (vector-ref cns (* 2 x)) (vector-ref cns (+ (* 2 x) 1)) d) (draw-solid-line proj (vector-ref cns (+ x (if (> x 1) 2 0))) (vector-ref cns (+ x (if (> x 1) 4 2))) d) (draw-solid-line proj (vector-ref cns x) (vector-ref cns (+ x 4)) d) (set-line-width 1 d)))) (define (point-set-shape proj ps) (let* ((vs (point-set->polygon proj ps)) (nvs (normalize-polygon proj vs)) (s (make-shape))) (case (length nvs) ((0 1) s) ((2) (move-to (vector->coord proj (car nvs)) s) (line-to (vector->coord proj (cadr nvs)) s) s) (else (move-to (vector->coord proj (car nvs)) s) (for-each (lambda (v) (line-to (vector->coord proj v) s)) (cdr nvs)) (line-to (vector->coord proj (car nvs)) s) s)))) (define (draw-point-set proj ps . args) (let-optionals args ((lcol #f) (fcol #f) (d (current-drawing))) (let ((sh (point-set-shape proj ps))) (if lcol (set-color lcol d)) (if fcol (set-fill-color fcol d)) (fill sh d) (draw sh 1.0 d)))) (define (draw-projection proj pss . args) (let-optionals args ((d (current-drawing))) (draw-projection-cube proj d) (draw-projection-axis proj d) (for-each (lambda (ps) (if (point-set? ps) (draw-point-set proj ps black (color 1 1 1 0) d) (let-optionals ps ((qs #f) (lcol black) (fcol (color 1 1 1 0))) (draw-point-set proj qs lcol fcol d)))) pss))) ;; Procedures for saving drawings (define (page-drawing spec) (assert (pair? spec) (projection? (car spec))) (let* ((d (make-drawing)) (proj (car spec)) (root (projection-root proj))) (draw-projection proj (cdr spec) d) (list d (size (* 2.0 (coord-x root)) (* 2.0 (coord-y root)))))) (define (save-projection-drawings path . args) (save-drawings path (map page-drawing args))) (define (save-demo-drawings path) (let ((gray (color 0.5 0.5 0.5 0.15))) (save-projection-drawings path (list (current-projection) (list (plane #(0 0 0) #(1.0 0.1 -0.5) #(0.0 0.8 0.8)) (color 0.6 0.6 0.6) (color 0 0 1 0.15)) (list (plane #(0 -7.5 0) #(1.0 0.0 0.0) #(0.0 0.0 1.0)) (color 0.6 0.6 0.6) (color 1 0 0 0.15))) (list (make-projection (vector (range -10 10) (range -10 10) (range -10 10)) (coord 200 200) (vector (deg->rad 350) (deg->rad 90) (deg->rad 215)) (vector 180.0 200.0 130.0)) (list (plane #(0 0 0) #(0.0 0.0 1.0) #(1.0 0.0 0.0)) black gray) (list (plane #(0 0 0) #(0.0 0.0 1.0) #(1.7 1.0 0.0)) black gray) (list (plane #(0 0 0) #(0.0 0.0 1.0) #(1.0 1.7 0.0)) black gray) (list (plane #(0 0 0) #(0.0 0.0 1.0) #(0.0 1.0 0.0)) black gray) (list (plane #(0 0 0) #(0.0 0.0 1.0) #(-1.0 1.7 0.0)) black gray) (list (plane #(0 0 0) #(0.0 0.0 1.0) #(1.7 -1.0 0.0)) black gray)))))
false
4727851989ab6da98974e19f896aace4b55dd88b
ebf028b3a35ae1544bba1a1f9aa635135486ee6c
/sitelib/lunula/log.scm
9d432052f929173992d0c788f0fded7e58d91b47
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
tabe/lunula
b4b666151874271211744cce1346e58e3a56fa79
b7699a850b9c9a64c1d3a52d50ce20050bd17475
refs/heads/master
2021-01-01T20:04:43.571993
2010-05-06T15:39:31
2010-05-06T15:39:31
334,916
2
0
null
null
null
null
UTF-8
Scheme
false
false
551
scm
log.scm
(library (lunula log) (export drain info) (import (rnrs) (only (core) make-parameter format lookup-process-environment)) (define drain (make-parameter (cond ((lookup-process-environment "LUNULA_LOG_DRAIN") => (lambda (path) (open-file-output-port path (file-options no-fail)))) (else #t)))) (define (info msg . args) (assert (string? msg)) (let ((port (drain))) (apply format port (string-append msg "~%") args) (when (output-port? port) (flush-output-port port)))) )
false
1a06cd77e2b4fe2e34ab12233fb5205b6bb244c9
86a7d9ada5a7978cc6b3dc51c73a61abf82a6023
/src/parse-tree.ss
19bc75c0ed74d5c06f7e30b7486cfdfbb583296b
[]
no_license
themetaschemer/rackscad
6b249559ae9dbced4c12d3562284a41ab0265fe4
8915919c24bb93a63d13546610871bd11a823411
refs/heads/master
2021-06-26T07:31:04.723127
2017-09-15T15:32:41
2017-09-15T15:32:41
103,672,527
0
0
null
null
null
null
UTF-8
Scheme
false
false
5,151
ss
parse-tree.ss
#lang racket (require "utils.ss") (require racket/include) (require rackunit) ;;------------------------------------------------------------------------------------------- ;; Fundamental objects ;;------------------------------------------------------------------------------------------- (struct/provide point (x y z) #:transparent) (struct/provide edge (from to) #:transparent) (struct/provide face (points) #:transparent) (define/provide (2d-point x y) (point x y 0)) ;;------------------------------------------------------------------------------------------- ;; 2d objects ;;------------------------------------------------------------------------------------------- (struct/provide circle-object (diameter) #:transparent) (struct/provide rectangle-object (x y center) #:transparent) (struct/provide polygon-object (points paths) #:transparent) (struct/provide text-object (string size font halign valign spacing direction language script) #:transparent) (define/provide (2d-object? x) (ormap (λ (f) (f x)) (list circle-object? rectangle-object? polygon-object? text-object?))) ;;------------------------------------------------------------------------------------------- ;; 3d objects ;;------------------------------------------------------------------------------------------- (struct/provide sphere-object (diameter) #:transparent) (struct/provide cuboid-object (width depth height center) #:transparent) (struct/provide conic-object (height base-diameter top-diameter center) #:transparent) (struct/provide polyhedron-object (points faces convexity) #:transparent) (define/provide (3d-object? x) (ormap (λ (f) (f x)) (list sphere-object? cuboid-object? conic-object? polyhedron-object?))) ;;------------------------------------------------------------------------------------------- ;; File ops ;;------------------------------------------------------------------------------------------- (struct/provide import-object (file) #:transparent) (struct/provide height-map-transform (file objects center convexity) #:transparent) (define/provide (height-map-with-args file objects #:center [center #f] #:convexity [convexity 10]) (height-map-transform file objects center convexity)) (define/provide import? import-object?) (define/provide height-map? height-map-transform?) ;;------------------------------------------------------------------------------------------- ;; Global parameter modifications $fa, $fs and $fn ;;------------------------------------------------------------------------------------------- (struct/provide parameters-transform (params objs) #:transparent) (define/provide parameters? parameters-transform?) ;;------------------------------------------------------------------------------------------- ;; 3d->2d ;;------------------------------------------------------------------------------------------- (struct/provide project-transform (cut objects) #:transparent) (define/provide projection? project-transform?) ;;------------------------------------------------------------------------------------------- ;; 2d->3d ;;------------------------------------------------------------------------------------------- (struct/provide linear-extrude-transform (objects height center convexity twist slices scale) #:transparent) (struct/provide rotate-extrude-transform (objects angle convexity) #:transparent) (define/provide (linear-extrude-with-args objs #:height height #:center center #:convexity convexity #:twist twist #:slices slices #:scale scale) (linear-extrude-transform objs height center convexity twist slices scale)) (define/provide (rotate-extrude-with-args objs #:angle angle #:convexity convexity) (rotate-extrude-transform objs angle convexity)) (define/provide (extrude? x) (or (linear-extrude-transform? x) (rotate-extrude-transform? x))) ;;------------------------------------------------------------------------------------------- ;; 3d->3d transformations ;;------------------------------------------------------------------------------------------- (struct/provide basic-transform (name x y z objects) #:transparent) (struct/provide basic-color-transform (r g b alpha objects) #:transparent) (struct/provide offset-transform (radius depth chamfer objects) #:transparent) (struct/provide affine-transform (matrix objects) #:transparent) (define/provide (transform? x) (ormap (λ (f) (f x)) (list basic-transform? basic-color-transform? offset-transform? affine-transform?))) ;;------------------------------------------------------------------------------------------- ;; Set operations ;;------------------------------------------------------------------------------------------- (struct/provide set-operation-object (op objects) #:transparent) (define/provide set-operation? set-operation-object?) (include "parse-tree-test.ss")
false
af67309055866e9b62a99d351ed7a58990c88750
18fb2e9f5ce1a5c876d9e0694ed001d8932b2fde
/racr-meta/core.scm
c9435e4e1be09033e900db36bcfa66b379fb398f
[ "MIT", "X11" ]
permissive
christoff-buerger/racr
0669a0ba537c6b6d7e4379dbb453c42ff8456d25
b83e18d751bb11f844e8face7a81770819f1a3a9
refs/heads/master
2023-09-04T05:25:04.113295
2023-08-19T22:29:23
2023-08-19T22:29:23
32,183,687
33
10
null
2017-02-13T20:38:03
2015-03-13T22:19:59
Scheme
UTF-8
Scheme
false
false
162,315
scm
core.scm
; This program and the accompanying materials are made available under the ; terms of the MIT license (X11 license) which accompanies this distribution. ; Author: C. Bürger #!r6rs (library (racr-meta core) (export ; Specification interface: (rename (make-racr-specification create-specification)) ; Specification query interface: specification->phase specification->start-symbol specification->ast-rules specification->find-ast-rule ast-rule->symbolic-representation ast-rule->supertype? ast-rule->production symbol->name symbol->non-terminal? symbol->kleene? symbol->context-name symbol->attributes attribute->name attribute->circular? attribute->synthesized? attribute->inherited? attribute->cached? ; ASTs: Specification (rename (specify-ast-rule ast-rule)) compile-ast-specifications ; ASTs: Construction create-ast create-ast-list create-ast-bud create-ast-mockup ; ASTs: Traversal ast-parent ast-child ast-sibling ast-children ast-for-each-child ast-find-child ast-find-child* ; ASTs: Node Information ast-node? ast-specification ast-has-parent? ast-child-index ast-has-child? ast-num-children ast-has-sibling? ast-node-type ast-node-rule ast-list-node? ast-bud-node? ast-subtype? ; Attribution: Specification specify-attribute (rename (specify-ag-rule ag-rule)) compile-ag-specifications ; Attribution: Querying att-in-evaluation? att-value ; Rewriting: Primitive Rewrite Functions rewrite-terminal rewrite-refine rewrite-abstract rewrite-subtree rewrite-add rewrite-insert rewrite-delete ; Rewriting: Rewrite Strategies perform-rewrites ; Support with-specification ; RACR Exceptions: throw-exception racr-exception? make-atom ; TODO Delete following exports when properly integrated: (rename (make-racr-specification-2 create-specification-2)) racr-specification-2-ast-scheme (rename (specify-ast-rule-2 ast-rule-2)) specify-start-symbol-2 specify-attribute-2 compile-specification-2 create-ast-2 create-ast-list-2) (import (rnrs) (rnrs mutable-pairs)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Internal Data Structures ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-record-type atom ; Unique key entities, each instance is only equal to itself. (nongenerative atom:4eac95849d0fb73142c398c35979fa20a71b9d02) (sealed #t)(opaque #t)(fields (mutable dummy-value)) (protocol (lambda (new) (lambda () (new #t))))) (define racr-nil (make-atom)) ; Unique value indicating undefined RACR entities ; Record type representing RACR compiler specifications. A compiler specification consists of arbitrary ; many AST rule, attribute and rewrite specifications, all aggregated into a set of rules stored in a ; non-terminal-symbol -> ast-rule hashtable, an actual compiler specification phase and a distinguished ; start symbol. The specification phase is an internal flag indicating the RACR system the compiler's ; specification progress. Possible phases are: ; 1 : AST specification ; 2 : AG specification ; 3 : Rewrite specification ; 4 : Specification finished (define-record-type racr-specification (nongenerative racr-specification:4eac95849d0fb73142c398c35979fa20a71b9d02) (fields (mutable specification-phase) rules-table (mutable start-symbol)) (opaque #t)(sealed #t) (protocol (lambda (new) (lambda () (new 1 (make-eq-hashtable 50) racr-nil))))) ; INTERNAL FUNCTION: Given a RACR specification and a non-terminal, return the ; non-terminal's AST rule or #f if it is undefined. (define racr-specification-find-rule (lambda (spec non-terminal) (hashtable-ref (racr-specification-rules-table spec) non-terminal #f))) ; INTERNAL FUNCTION: Given a RACR specification return a list of its AST rules. (define racr-specification-rules-list (lambda (spec) (call-with-values (lambda () (hashtable-entries (racr-specification-rules-table spec))) (lambda (key-vector value-vector) (vector->list value-vector))))) ; Record type for AST rules; An AST rule has a reference to the RACR specification it belongs to and consist ; of its symbolic encoding, a production (i.e., a list of production-symbols) and an optional supertype. (define-record-type ast-rule (nongenerative ast-rule:4eac95849d0fb73142c398c35979fa20a71b9d02) (fields specification as-symbol (mutable production) (mutable supertype?)) (opaque #t)(sealed #t)) ; INTERNAL FUNCTION: Given an AST rule find a certain child context by name. If the rule defines no such ; context, return #f, otherwise the production symbol defining the respective context. (define ast-rule-find-child-context (lambda (r context-name) (find (lambda (symbol) (eq? (symbol-context-name symbol) context-name)) (cdr (ast-rule-production r))))) ; INTERNAL FUNCTION: Given two rules r1 and r2, return whether r1 is a subtype of r2 or not. The subtype ; relationship is reflexive, i.e., every type is a subtype of itself. ; BEWARE: Only works correct if supertypes are resolved, otherwise an exception can be thrown! (define ast-rule-subtype? (lambda (r1 r2) (and (eq? (ast-rule-specification r1) (ast-rule-specification r2)) (let loop ((r1 r1)) (cond ((eq? r1 r2) #t) ((ast-rule-supertype? r1) (loop (ast-rule-supertype? r1))) (else #f)))))) ; INTERNAL FUNCTION: Given a rule, return a list containing all its subtypes except the rule itself. ; BEWARE: Only works correct if supertypes are resolved, otherwise an exception can be thrown! (define ast-rule-subtypes (lambda (rule1) (filter (lambda (rule2) (and (not (eq? rule2 rule1)) (ast-rule-subtype? rule2 rule1))) (racr-specification-rules-list (ast-rule-specification rule1))))) ; Record type for production symbols; A production symbol is part of a certain ast rule and has name, ; a flag indicating whether it is a non-terminal or not (later resolved to the actual AST rule representing ; the respective non-terminal), a flag indicating whether it represents a Kleene closure (i.e., is a list ; of certain type) or not, a context-name unambiguously referencing it within the production it is part of ; and a list of attributes defined for it. (define-record-type (symbol make-production-symbol production-symbol?) (nongenerative symbol:4eac95849d0fb73142c398c35979fa20a71b9d02) (fields name ast-rule (mutable non-terminal?) kleene? context-name (mutable attributes)) (opaque #t)(sealed #t)) ; Record type for attribute definitions. An attribute definition has a certain name, a definition context ; (i.e., a symbol of an AST rule), an equation and an optional circularity-definition used for fix-point ; computations. Further, attribute definitions specify whether the value of instances of the defined ; attribute are cached. Circularity-definitions are (bottom-value equivalence-function) pairs, whereby ; bottom-value is the value fix-point computations start with and equivalence-functions are used to decide ; whether a fix-point is reached or not (i.e., equivalence-functions are arbitrary functions of arity two ; computing whether two given arguments are equal or not). (define-record-type attribute-definition (nongenerative attribute-definition:4eac95849d0fb73142c398c35979fa20a71b9d02) (fields name context equation circularity-definition cached?) (opaque #t)(sealed #t)) ; INTERNAL FUNCTION: Given an attribute definition, check if instances can depend on ; themself (i.e., be circular) or not. (define attribute-definition-circular? (lambda (att) (if (attribute-definition-circularity-definition att) #t #f))) ; INTERNAL FUNCTION: Given an attribute definition, return whether it specifies ; a synthesized attribute or not. (define attribute-definition-synthesized? (lambda (att-def) (let ((symbol (attribute-definition-context att-def))) (eq? (car (ast-rule-production (symbol-ast-rule symbol))) symbol)))) ; INTERNAL FUNCTION: Given an attribute definition, return whether it specifies ; an inherited attribute or not. (define attribute-definition-inherited? (lambda (att-def) (not (attribute-definition-synthesized? att-def)))) ; Record type for AST nodes. AST nodes have a reference to the evaluator state used for evaluating their ; attributes and rewrites, the AST rule they represent a context of, their parent, children, attribute ; instances and the attribute cache entries they influence. (define-record-type node (nongenerative node:4eac95849d0fb73142c398c35979fa20a71b9d02) (fields (mutable evaluator-state) (mutable ast-rule) (mutable parent) (mutable children) (mutable attributes) (mutable cache-influences)) (opaque #t)(sealed #t) (protocol (lambda (new) (lambda (ast-rule parent children) (new #f ast-rule parent children (list) (list)))))) ; INTERNAL FUNCTION: Is the AST node of a certain type or subtype thereof (must be no terminal, bud or list node)? (define node-instance-of?-2 (lambda (node rule) (or (eq? (node-ast-rule node) rule) (memq (node-ast-rule node) (=subtypes rule))))) ; INTERNAL FUNCTION: Given a node, return whether it is a terminal or not. (define node-terminal? (lambda (n) (eq? (node-ast-rule n) 'terminal))) ; INTERNAL FUNCTION: Given a node, return whether it is a non-terminal or not. (define node-non-terminal? (lambda (n) (not (node-terminal? n)))) ; INTERNAL FUNCTION: Given a node, return whether it is a list node or not. (define node-list-node? (lambda (n) (eq? (node-ast-rule n) 'list-node))) ; INTERNAL FUNCTION: Given a node, return whether it is a bud node or not. (define node-bud-node? (lambda (n) (eq? (node-ast-rule n) 'bud-node))) ; INTERNAL FUNCTION: Given a node, return its child-index if it has a parent, otherwise return #f. (define node-child-index? (lambda (n) (if (node-parent n) (let loop ((children (node-children (node-parent n))) (pos 1)) (if (eq? (car children) n) pos (loop (cdr children) (+ pos 1)))) #f))) ; INTERNAL FUNCTION: Given a node find a certain child by name. If the node has ; no such child, return #f, otherwise the child. (define node-find-child (lambda (n context-name) (and (not (node-list-node? n)) (not (node-bud-node? n)) (not (node-terminal? n)) (let loop ((contexts (cdr (ast-rule-production (node-ast-rule n)))) (children (node-children n))) (if (null? contexts) #f (if (eq? (symbol-context-name (car contexts)) context-name) (car children) (loop (cdr contexts) (cdr children)))))))) ; INTERNAL FUNCTION: Given a node find a certain attribute associated with it. If the node ; has no such attribute, return #f, otherwise the attribute. TODO: delte (define node-find-attribute (lambda (n name) (find (lambda (att) (eq? (attribute-definition-name (attribute-instance-definition att)) name)) (node-attributes n)))) ; INTERNAL FUNCTION: Given a node return a certain of its attributes if it exists otherwise #f. (define node-find-attribute-2 (lambda (n name) (find (lambda (attribute-instance) (eq? (->name (attribute-instance-definition attribute-instance)) name)) (node-attributes n)))) ; INTERNAL FUNCTION: Given two nodes n1 and n2, return whether n1 is within the subtree spaned by n2 or not. (define node-inside-of? (lambda (n1 n2) (cond ((eq? n1 n2) #t) ((node-parent n1) (node-inside-of? (node-parent n1) n2)) (else #f)))) ; Record type for attribute instances of a certain attribute definition, associated with ; a certain node (context) and a cache. (define-record-type attribute-instance (nongenerative attribute-instance:4eac95849d0fb73142c398c35979fa20a71b9d02) (fields (mutable definition) (mutable context) cache) (opaque #t)(sealed #t) (protocol (lambda (new) (lambda (definition context) (new definition context (make-hashtable equal-hash equal? 1)))))) ; Record type for attribute cache entries. Attribute cache entries represent the values of ; and dependencies between attribute instances evaluated for certain arguments. The attribute ; instance of which an entry represents a value is called its context. If an entry already ; is evaluated, it caches the result of its context evaluated for its arguments. If an entry is ; not evaluated but its context is circular it stores an intermediate result of its fixpoint ; computation, called cycle value. Entries also track whether they are already in evaluation or ; not, such that the attribute evaluator can detect unexpected cycles. (define-record-type attribute-cache-entry (nongenerative attribute-cache-entry:4eac95849d0fb73142c398c35979fa20a71b9d02) (fields (mutable context) (mutable arguments) (mutable value) (mutable cycle-value) (mutable entered?) (mutable node-dependencies) (mutable cache-dependencies) (mutable cache-influences)) (opaque #t)(sealed #t) (protocol (lambda (new) (lambda (att arguments) ; att: The attribute instance for which to construct a cache entry (new att arguments racr-nil (let ((circular? (attribute-definition-circularity-definition (attribute-instance-definition att)))) (if circular? (car circular?) racr-nil)) #f (list) (list) (list)))))) ; Record type representing the internal state of RACR systems throughout their execution, i.e., while ; evaluating attributes and rewriting ASTs. An evaluator state consists of a flag indicating if the AG ; currently performs a fix-point evaluation, a flag indicating if throughout a fix-point iteration the ; value of an attribute changed and an attribute evaluation stack used for dependency tracking. (define-record-type evaluator-state (nongenerative evaluator-state:4eac95849d0fb73142c398c35979fa20a71b9d02) (fields (mutable ag-in-cycle?) (mutable ag-cycle-change?) (mutable evaluation-stack)) (opaque #t)(sealed #t) (protocol (lambda (new) (lambda () (new #f #f (list)))))) ; INTERNAL FUNCTION: Given an evaluator state, return whether it represents an evaluation in progress or ; not. If it represents an evaluation in progress return the current attribute in evaluation, otherwise #f. (define evaluator-state-in-evaluation? (lambda (state) (and (not (null? (evaluator-state-evaluation-stack state))) (car (evaluator-state-evaluation-stack state))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Support API ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; INTERNAL FUNCTION: Given an arbitrary Scheme entity, construct a string ; representation of it using display. (define object->string (lambda (x) (call-with-string-output-port (lambda (port) (display x port))))) (define-condition-type racr-exception &violation make-racr-exception racr-exception?) ; INTERNAL FUNCTION: Given an arbitrary sequence of strings and other Scheme entities, concatenate them to ; form an error message and throw a special RACR exception with the constructed message. Any entity that is ; not a string is treated as error information embedded in the error message between '[' and ']' characters, ; whereby the actual string representation of the entity is obtained using object->string. (define-syntax throw-exception (syntax-rules () ((_ m-part ...) (raise-continuable (condition (make-racr-exception) (make-message-condition (string-append "RACR exception: " (let ((m-part* m-part)) (if (string? m-part*) m-part* (string-append "[" (object->string m-part*) "]"))) ...))))))) ; INTERNAL FUNCTION: Procedure sequentially applying a function on all the AST rules of a set of rules which ; inherit, whereby supertypes are processed before their subtypes. (define apply-wrt-ast-inheritance (lambda (func rules) (let loop ((resolved ; The set of all AST rules that are already processed.... (filter ; ...Initially it consists of all the rules that have no supertypes. (lambda (rule) (not (ast-rule-supertype? rule))) rules)) (to-check ; The set of all AST rules that still must be processed.... (filter ; ...Initially it consists of all the rules that have supertypes. (lambda (rule) (ast-rule-supertype? rule)) rules))) (let ((to-resolve ; ...Find a rule that still must be processed and... (find (lambda (rule) (memq (ast-rule-supertype? rule) resolved)) ; ...whose supertype already has been processed.... to-check))) (when to-resolve ; ...If such a rule exists,... (func to-resolve) ; ...process it and... (loop (cons to-resolve resolved) (remq to-resolve to-check))))))) ; ...recur. (define-syntax with-specification (lambda (x) (syntax-case x () ((k spec body ...) #`(let* ((spec* spec) (#,(datum->syntax #'k 'ast-rule) (lambda (rule) (specify-ast-rule spec* rule))) (#,(datum->syntax #'k 'compile-ast-specifications) (lambda (start-symbol) (compile-ast-specifications spec* start-symbol))) (#,(datum->syntax #'k 'compile-ag-specifications) (lambda () (compile-ag-specifications spec*))) (#,(datum->syntax #'k 'create-ast) (lambda (rule children) (create-ast spec* rule children))) (#,(datum->syntax #'k 'specification->phase) (lambda () (specification->phase spec*))) (#,(datum->syntax #'k 'specify-attribute) (lambda (att-name non-terminal index cached? equation circ-def) (specify-attribute spec* att-name non-terminal index cached? equation circ-def)))) (let-syntax ((#,(datum->syntax #'k 'ag-rule) (syntax-rules () ((_ attribute-name definition (... ...)) (specify-ag-rule spec* attribute-name definition (... ...)))))) body ...)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Abstract Syntax Tree Specification ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define specify-ast-rule (lambda (spec rule) ;;; Ensure, that the RACR system is in the correct specification phase: (when (> (racr-specification-specification-phase spec) 1) (throw-exception "Unexpected AST rule " rule "; " "AST rules can only be defined in the AST specification phase.")) (letrec* ((ast-rule ; The parsed AST rule that will be added to the given specification. (make-ast-rule spec rule racr-nil racr-nil)) (rule-string (symbol->string rule)) ; String representation of the encoded rule (used for parsing) (pos 0) ; The current parsing position ; Support function returning, whether the end of the parsing string is reached or not: (eos? (lambda () (= pos (string-length rule-string)))) ; Support function returning the current character to parse: (my-peek-char (lambda () (string-ref rule-string pos))) ; Support function returning the current character to parse and incrementing the parsing position: (my-read-char (lambda () (let ((c (my-peek-char))) (set! pos (+ pos 1)) c))) ; Support function matching a certain character: (match-char! (lambda (c) (if (eos?) (throw-exception "Unexpected end of AST rule " rule ";" "Expected " c " character.") (if (char=? (my-peek-char) c) (set! pos (+ pos 1)) (throw-exception "Invalid AST rule " rule "; " "Unexpected " (my-peek-char) " character."))))) ; Support function parsing a symbol, i.e., retrieving its name, type, if it is a list and optional context name. (parse-symbol (lambda (location) ; location: l-hand, r-hand (let ((symbol-type (if (eq? location 'l-hand) "non-terminal" "terminal"))) (when (eos?) (throw-exception "Unexpected end of AST rule " rule "; " "Expected " symbol-type ".")) (let* ((parse-name (lambda (terminal?) (let ((name (append (let loop ((chars (list))) (if (and (not (eos?)) (char-alphabetic? (my-peek-char))) (begin (when (and terminal? (not (char-lower-case? (my-peek-char)))) (throw-exception "Invalid AST rule " rule "; " "Unexpected " (my-peek-char) " character.")) (loop (cons (my-read-char) chars))) (reverse chars))) (let loop ((chars (list))) (if (and (not (eos?)) (char-numeric? (my-peek-char))) (loop (cons (my-read-char) chars)) (reverse chars)))))) (when (null? name) (throw-exception "Unexpected " (my-peek-char) " character in AST rule " rule "; " "Expected " symbol-type ".")) (unless (char-alphabetic? (car name)) (throw-exception "Malformed name in AST rule " rule "; " "Names must start with a letter.")) name))) (terminal? (char-lower-case? (my-peek-char))) (name (parse-name terminal?)) (kleene? (and (not terminal?) (eq? location 'r-hand) (not (eos?)) (char=? (my-peek-char) #\*) (my-read-char))) (context-name? (and (not terminal?) (eq? location 'r-hand) (not (eos?)) (char=? (my-peek-char) #\<) (my-read-char) (parse-name #f))) (name-string (list->string name)) (name-symbol (string->symbol name-string))) (when (and terminal? (eq? location 'l-hand)) (throw-exception "Unexpected " name " terminal in AST rule " rule "; " "Left hand side symbols must be non-terminals.")) (make-production-symbol name-symbol ast-rule (not terminal?) kleene? (if context-name? (string->symbol (list->string context-name?)) (if kleene? (string->symbol (string-append name-string "*")) name-symbol)) (list)))))) (l-hand (parse-symbol 'l-hand)); The rule's l-hand (supertype ; The rule's super-type (and (not (eos?)) (char=? (my-peek-char) #\:) (my-read-char) (symbol-name (parse-symbol 'l-hand))))) (match-char! #\-) (match-char! #\>) (ast-rule-production-set! ast-rule (append (list l-hand) (let loop ((r-hand (if (not (eos?)) (list (parse-symbol 'r-hand)) (list)))) (if (eos?) (reverse r-hand) (begin (match-char! #\-) (loop (cons (parse-symbol 'r-hand) r-hand))))))) (ast-rule-supertype?-set! ast-rule supertype) ; Check, that the rule's l-hand is not already defined: (when (racr-specification-find-rule spec (symbol-name l-hand)) (throw-exception "Invalid AST rule " rule "; " "Redefinition of " (symbol-name l-hand) ".")) (hashtable-set! ; Add the rule to the RACR specification. (racr-specification-rules-table spec) (symbol-name l-hand) ast-rule)))) (define (specify-ast-rule-2 spec rule) (define rule-string (symbol->string rule)) ; The characters to parse. (define rule-string-length (string-length rule-string)) ; The number of characters to parse. (define pos 0) ; The current parsing position. (define peek-char ; Return the next character if it satisfies optional constraints and exists. (lambda constraints (define char-read? (and (< pos rule-string-length) (string-ref rule-string pos))) (and char-read? (for-all (lambda (f) (f char-read?)) constraints) char-read?))) (define read-char ; Similar to peek-char but additionally increments the parsing position. (lambda constraints (define char-read? (apply peek-char constraints)) (unless char-read? (throw-exception "Invalid AST rule " rule ";")) (set! pos (+ pos 1)) char-read?)) (define (char= to-read) ; Construct filter for certain character that can be used by peek- and read-char. (lambda (char-read) (char=? char-read to-read))) (define (parse-rule) ; Parse complete rule. (define name #f) (define supertype? #f) (define rhand #f) (unless (peek-char char-upper-case?) (throw-exception "Invalid AST rule " rule ";")) (set! name (parse-identifier)) (when (peek-char (char= #\:)) (read-char) (unless (peek-char char-upper-case?) (throw-exception "Invalid AST rule " rule ";")) (set! supertype? (parse-identifier))) (read-char (char= #\-)) (read-char (char= #\>)) (set! rhand (if (peek-char char-alphabetic?) (let loop () (let ((symbol (parse-symbol))) (if (peek-char (char= #\-)) (begin (read-char) (cons symbol (loop))) (list symbol)))) (list))) (when (peek-char) (throw-exception "Invalid AST rule " rule ";")) (create-ast ast-language 'AstRule (list name supertype? (create-ast-list rhand)))) (define (parse-symbol) ; Parse right hand symbol including optional klenee closure and context name. (define non-terminal? (peek-char char-upper-case?)) (define name (parse-identifier)) (define klenee? (and non-terminal? (peek-char (char= #\*)) (read-char))) (define contextname? (and non-terminal? (peek-char (char= #\<)) (read-char) (parse-identifier))) (create-ast ast-language 'Symbol (list name klenee? contextname?))) (define (parse-identifier) ; Parse ordinary identifier, i.e., [a-zA-Z][a-zA-Z0-9]* (let loop ((id (list (read-char char-alphabetic?)))) (let ((next-char? (peek-char))) (if (and next-char? (or (char-alphabetic? next-char?) (char-numeric? next-char?))) (loop (cons (read-char) id)) (string->symbol (apply string (reverse id))))))) ;;; Before adding the AST rule, ensure that... (unless (symbol? rule) ; ...the given argument is of the expected type and... (throw-exception "Invalid AST rule definition;" "Wrong argument type (expected symbol encoding rule, but the argument was " rule ".")) (when (> (racr-specification-2-specification-phase spec) 1) ; ...the language is in the correct specification phase. (throw-exception "Unexpected AST rule " rule ";" "AST rules can only be defined in the specification phase.")) ;;; Parse the rule, add it to the RACR specification and return it: (let ((rule (parse-rule))) (rewrite-add (->astrules (racr-specification-2-ast-scheme spec)) rule) rule)) (define (specify-start-symbol-2 spec start-symbol) ;;; Before changing the start symbol, ensure that... (unless (symbol? start-symbol) ; ...the given argument is of the expected type and... (throw-exception "Invalid start symbol definition;" "Wrong argument type (expected symbol encoding non-terminal, but the argument was " start-symbol ").")) (when (> (racr-specification-2-specification-phase spec) 1) ; ...the language is in the correct specification phase. (throw-exception "Unexpected " start-symbol " start symbol definition;" "The start symbol can only be defined in the specification phase.")) ;;; Set the start symbol: (rewrite-terminal 'startsymbol (racr-specification-2-ast-scheme spec) start-symbol)) (define (specify-attribute-2 spec name rule position cached? equation circularity-definition) ;;; Before adding the attribute definition, ensure that... (define wrong-argument-type ; ...the given arguments are of the expected type and... (or (and (not (symbol? name)) (cons "symbol encoding attribute name" name)) (and (not (symbol? rule)) (cons "symbol denoting AST rule" rule)) (and (not (symbol? position)) (cons "symbol denoting AST rule context" position)) (and (not (procedure? equation)) (cons "function encoding attribute equation" equation)) (and circularity-definition (or (not (pair? circularity-definition)) (not (procedure? (cdr circularity-definition)))) (cons "#f or (bottom-value equivalence-function) pair encoding circularity definition" circularity-definition)))) (when wrong-argument-type (throw-exception "Invalid attribute definition; " "Wrong argument type (expected " (car wrong-argument-type) ", but the argument was " (cdr wrong-argument-type) ").")) (when (> (racr-specification-2-specification-phase spec) 1) ; ...the language is in the correct specification phase. (throw-exception "Unexpected " name " attribute definition; " "Attributes can only be defined in the specification phase.")) ;;; Add the attribute to the RACR specification and return it: (let ((attribute (create-ast ast-language 'Attribute (list name (cons rule position) equation circularity-definition cached?)))) (rewrite-add (->attribution (racr-specification-2-ast-scheme spec)) attribute) attribute)) (define (compile-specification-2 spec) (define ast-scheme (racr-specification-2-ast-scheme spec)) ;;; Before compiling the specification, ensure that... (when (> (racr-specification-2-specification-phase spec) 1) ; ...it is in the correct specification phase and... (throw-exception "Unexpected RACR specification compilation;" "The specification already has been compiled.")) (unless (=well-formed? ast-scheme) ; ...well-formed. (throw-exception "Cannot compile RACR specification;" "The specification is not well-formed.")) ;;; Compile the specification, i.e.,... (racr-specification-2-specification-phase-set! spec 2) ; ...proceed to the next specifcation phase and... (for-each ; ...precompute the attribution factories of all possible context switches. The attribution for... (lambda (rule) (define abstracted-context (list #f #f (->name rule))) (=attribution-factory ast-scheme #f abstracted-context) ; ...new nodes and... (for-each ; ...all their... (lambda (sub) (define refined-context (list #f #f (->name sub))) (=attribution-factory ast-scheme abstracted-context refined-context) ; ...refinements and... (=attribution-factory ast-scheme refined-context abstracted-context)) ; ...abstractions and... (=subtypes rule)) (for-each ; ...all their children,... (lambda (symbol) (for-each ; ...of all permitted kind, whether... (lambda (child-rule) (define without-parent-context (list #f #f (->name child-rule))) (define with-parent-context (list (->name rule) (=contextname symbol) (->name child-rule))) (=attribution-factory ast-scheme without-parent-context with-parent-context) ; ...added,... (=attribution-factory ast-scheme with-parent-context without-parent-context) ; ...removed,... (for-each (lambda (child-sub) (define refined-child-context (list (->name rule) (=contextname symbol) (->name child-sub))) (=attribution-factory ast-scheme with-parent-context refined-child-context); ...refined or... (=attribution-factory ast-scheme refined-child-context with-parent-context)); ...abstracted. (=subtypes child-rule))) (let ((child-rule (=non-terminal? symbol))) (cons child-rule (=subtypes child-rule))))) (=rhand-non-terminal-symbols rule))) (=ast-rules ast-scheme))) (define-record-type racr-specification-2 (nongenerative racr-specification-2:4eac95849d0fb73142c398c35979fa20a71b9d02) (fields (mutable specification-phase) ast-scheme) (opaque #t)(sealed #t) (protocol (lambda (new) (lambda () (new 1 (with-specification ast-language (create-ast 'AstScheme ; The initial AST scheme just consists of... (list (create-ast-list (list (create-ast 'AstRule ; ...the error rule with... (list racr-nil #f (create-ast-list (list (create-ast 'Symbol (list 'error-symbol #f 'error-symbol)))))))) ; ...the error symbol. #f (create-ast-list (list)))))))))) (define ast-language (make-racr-specification)) ; AST Accessors: (define (->astrules n) (ast-child 'astrules n)) (define (->attribution n) (ast-child 'attribution n)) (define (->rhand n) (ast-child 'rhand n)) (define (->startsymbol n) (ast-child 'startsymbol n)) (define (->name n) (ast-child 'name n)) (define (->supertype n) (ast-child 'supertype n)) (define (->klenee n) (ast-child 'klenee n)) (define (->contextname n) (ast-child 'contextname n)) (define (->context n) (ast-child 'context n)) (define (->equation n) (ast-child 'equation n)) (define (->circularitydefinition n) (ast-child 'circularitydefinition n)) (define (->cached n) (ast-child 'cached n)) (define (->* n) (ast-children n)) ; Attribute Accessors: (define (=error-rule n) (att-value 'error-rule n)) (define (=error-symbol n) (att-value 'error-symbol n)) (define (=error-node? n) (att-value 'error-node? n)) (define (=attribute-definitions n) (att-value 'attribute-definitions n)) (define (=ast-rules n) (att-value 'ast-rules n)) (define (=containing-rule n) (att-value 'containing-rule n)) (define (=terminal? n) (att-value 'terminal? n)) (define (=contextname n) (att-value 'contextname n)) (define (=lookup-rule n name) (att-value 'lookup-rule n name)) (define (=startsymbol n) (att-value 'startsymbol n)) (define (=supertype? n) (att-value 'supertype? n)) (define (=non-terminal? n) (att-value 'non-terminal? n)) (define (=lookup-contextname n name) (att-value 'lookup-contextname n name)) (define (=supertypes n) (att-value 'supertypes n)) (define (=subtypes n) (att-value 'subtypes n)) (define (=expanded-rhand n) (att-value 'expanded-rhand n)) (define (=rhand-non-terminal-symbols n) (att-value 'rhand-non-terminal-symbols n)) (define (=productive? n) (att-value 'productive? n)) (define (=direct-derivable n) (att-value 'direct-derivable n)) (define (=derivable n) (att-value 'derivable n)) (define (=synthesised? n) (att-value 'synthesised? n)) (define (=inherited? n) (att-value 'inherited? n)) (define (=circular? n) (att-value 'circular? n)) (define (=bottom-value n) (att-value 'bottom-value n)) (define (=equality-function n) (att-value 'equality-function n)) (define (=context-rule n) (att-value 'context-rule n)) (define (=context n) (att-value 'context n)) (define (=attributes-for-rule/symbol n) (att-value 'attributes-for-rule/symbol n)) (define =attributes (case-lambda ((n) (att-value 'attributes n)) ((n context-name) (att-value 'attributes n context-name)))) (define (=attributes-for-context n parent-type? context-name? child-type) (att-value 'attributes-for-context n parent-type? context-name? child-type)) (define (=well-formed? n) (att-value 'well-formed? n)) (define (=local-correct? n) (att-value 'local-correct? n)) (define =ast-node-factory (case-lambda ((n) (att-value 'ast-node-factory n)) ((n name) (att-value 'ast-node-factory n name)))) (define (=context-checker n) (att-value 'context-checker n)) (define (=context-factory n) (att-value 'context-factory n)) (define (=attribution-factory n old-context new-context) (att-value 'attribution-factory n old-context new-context)) (define (load-ast-language) (define set-union (case-lambda ((s1 s2 f) ; Given two sets s1 and s2 and an equality function f, return the set union of s1 and s2 w.r.t. f. (fold-left (lambda (result e2) (if (find (lambda (e1) (f e1 e2)) s1) result (cons e2 result))) s1 s2)) ((s1 s2) ; Given two sets s1 and s2, return the set union of s1 and s2 (use eq? to compare elements). (set-union s1 s2 eq?)))) (define-record-type attribute-instance-2 (nongenerative attribute-instance-2:4eac95849d0fb73142c398c35979fa20a71b9d02) (fields name cached? (mutable definition) (mutable context) cache) (opaque #t)(sealed #t) (protocol (lambda (new) (lambda (name cached? definition context) (new name cached? definition context (make-hashtable equal-hash equal? 1)))))) ; Meta-instantiation contract: AST rule specification, attribute specification, ; start symbol specification and specification compilation only query attributes ; and no further AST information. All such queries are cache hits. (let* ((% racr-nil) ; Never queried information. (dummy-attribute-instance (lambda (name . entries) (let* ((instance (make-attribute-instance-2 name #t % %)) (cache (attribute-instance-2-cache instance))) (for-each (lambda (entry) (hashtable-set! cache (car entry) (cdr entry))) entries) instance))) (dummy-node (lambda () (make-node % % %))) (AstScheme (dummy-node)) (AstScheme-astrules (dummy-node)) (AstScheme-startsymbol (dummy-node)) (AstScheme-attribution (dummy-node)) (AstRule (dummy-node)) (AstRule-name (dummy-node)) (AstRule-supertype (dummy-node)) (AstRule-rhand (dummy-node)) (Symbol (dummy-node)) (Symbol-name (dummy-node)) (Symbol-klenee (dummy-node)) (Symbol-contextname (dummy-node)) (Attribute (dummy-node)) (Attribute-name (dummy-node)) (Attribute-context (dummy-node)) (Attribute-equation (dummy-node)) (Attribute-circularitydefinition (dummy-node)) (Attribute-cached (dummy-node)) (error-node?->f (dummy-attribute-instance 'error-node? (cons (list) #f))) (klenee?->t (dummy-attribute-instance 'klenee? (cons (list) #t))) (klenee?->f (dummy-attribute-instance 'klenee? (cons (list) #f))) (contextname->name (dummy-attribute-instance 'contextname (cons (list) 'name))) (contextname->astrules (dummy-attribute-instance 'contextname (cons (list) 'astrules))) (contextname->startsymbol (dummy-attribute-instance 'contextname (cons (list) 'startsymbol))) (contextname->attribution (dummy-attribute-instance 'contextname (cons (list) 'attribution))) (contextname->astrules (dummy-attribute-instance 'contextname (cons (list) 'astrules))) (contextname->supertype (dummy-attribute-instance 'contextname (cons (list) 'supertype))) (contextname->rhand (dummy-attribute-instance 'contextname (cons (list) 'rhand))) (contextname->klenee (dummy-attribute-instance 'contextname (cons (list) 'klenee))) (contextname->contextname (dummy-attribute-instance 'contextname (cons (list) 'contextname))) (contextname->context (dummy-attribute-instance 'contextname (cons (list) 'context))) (contextname->equation (dummy-attribute-instance 'contextname (cons (list) 'equation))) (contextname->circularitydefinition (dummy-attribute-instance 'contextname (cons (list) 'circularitydefinition))) (contextname->cached (dummy-attribute-instance 'contextname (cons (list) 'cached))) (terminal?->t (dummy-attribute-instance 'terminal? (cons (list) #t))) (terminal?->f (dummy-attribute-instance 'terminal? (cons (list) #f))) (non-terminal?->AstRule (dummy-attribute-instance 'non-terminal? (cons (list) AstRule))) (non-terminal?->Attribute (dummy-attribute-instance 'non-terminal? (cons (list) Attribute))) (non-terminal?->Symbol (dummy-attribute-instance 'non-terminal? (cons (list) Symbol))) (name->AstScheme (dummy-attribute-instance 'name (cons (list) 'AstScheme))) (name->AstRule (dummy-attribute-instance 'name (cons (list) 'AstRule))) (name->Symbol (dummy-attribute-instance 'name (cons (list) 'Symbol))) (name->Attribute (dummy-attribute-instance 'name (cons (list) 'Attribute))) (lookup-rule (dummy-attribute-instance 'lookup-rule (cons (list 'AstScheme) AstScheme) (cons (list 'AstRule) AstRule) (cons (list 'Symbol) Symbol) (cons (list 'Attribute) Attribute))) (AstScheme:attributes (dummy-attribute-instance 'attributes (cons (list) (list)))) (AstRule:attributes (dummy-attribute-instance 'attributes (cons (list) (list)))) (Symbol:attributes (dummy-attribute-instance 'attributes (cons (list) (list)))) (Attribute:attributes (dummy-attribute-instance 'attributes (cons (list) (list)))) (AstScheme:expanded-rhand '(dummy-attribute-instance 'expanded-rhand (cons (list) (list AstScheme-astrules AstScheme-startsymbol AstScheme-attribution)))) (AstRule:expanded-rhand '(dummy-attribute-instance 'expanded-rhand (cons (list) (list AstRule-name AstRule-supertype AstRule-rhand)))) (Symbol:expanded-rhand '(dummy-attribute-instance 'expanded-rhand (cons (list) (list Symbol-name Symbol-klenee Symbol-contextname)))) (Attribute:expanded-rhand '(dummy-attribute-instance 'expanded-rhand (cons (list) (list Attribute-name Attribute-context Attribute-equation Attribute-circularitydefinition Attribute-cached)))) (attributes-for-context (dummy-attribute-instance 'attributes-for-context (cons (list 'AstScheme 'astrules 'AstRule) (list)) (cons (list 'AstScheme 'attribution 'Attribute) (list)) (cons (list 'AstRule 'rhand 'Symbol) (list)))) ) (node-attributes-set! AstScheme (list error-node?->f name->AstScheme AstScheme:expanded-rhand lookup-rule attributes-for-context)) (node-attributes-set! AstRule (list error-node?->f name->AstRule AstRule:expanded-rhand)) (node-attributes-set! Symbol (list error-node?->f name->Symbol Symbol:expanded-rhand)) (node-attributes-set! Attribute (list error-node?->f name->Attribute Attribute:expanded-rhand)) (node-attributes-set! AstScheme-astrules (list terminal?->f klenee?->t contextname->astrules non-terminal?->AstRule)) (node-attributes-set! AstScheme-startsymbol (list terminal?->t klenee?->f contextname->startsymbol)) (node-attributes-set! AstScheme-attribution (list terminal?->f klenee?->t contextname->attribution non-terminal?->Attribute)) (node-attributes-set! AstRule-name (list terminal?->t klenee?->f contextname->name)) (node-attributes-set! AstRule-supertype (list terminal?->t klenee?->f contextname->supertype)) (node-attributes-set! AstRule-rhand (list terminal?->f klenee?->t contextname->rhand non-terminal?->Symbol)) (node-attributes-set! Symbol-name (list terminal?->t klenee?->f contextname->name)) (node-attributes-set! Symbol-klenee (list terminal?->t klenee?->f contextname->klenee)) (node-attributes-set! Symbol-contextname (list terminal?->t klenee?->f contextname->contextname)) (node-attributes-set! Attribute-name (list terminal?->t klenee?->f contextname->name)) (node-attributes-set! Attribute-context (list terminal?->t klenee?->f contextname->context)) (node-attributes-set! Attribute-equation (list terminal?->t klenee?->f contextname->equation)) (node-attributes-set! Attribute-circularitydefinition (list terminal?->t klenee?->f contextname->circularitydefinition)) (node-attributes-set! Attribute-cached (list terminal?->t klenee?->f contextname->cached)) ) (with-specification ast-language ;;; AST Scheme: (ast-rule 'AstScheme->AstRule*<astrules-startsymbol-Attribute*<attribution) (ast-rule 'AstRule->name-supertype-Symbol*<rhand) (ast-rule 'Symbol->name-klenee-contextname) (ast-rule 'Attribute->name-context-equation-circularitydefinition-cached) (compile-ast-specifications 'AstScheme) ;;; AST Query Support: (ag-rule error-rule ; Childless, non-inheriting rule with invalid name referd to by undeclared rule references. (AstScheme (lambda (n) (=lookup-rule n racr-nil)))) (ag-rule error-symbol ; Terminal symbol with invalid context name refered to by undeclared symbol references. (AstScheme (lambda (n) (=lookup-contextname (=error-rule n) 'error-symbol)))) (ag-rule error-node? ; Is the rule/symbol the error rule/symbol? (AstRule (lambda (n) (eq? n (=error-rule n)))) (Symbol (lambda (n) (eq? n (=error-symbol n))))) (ag-rule attribute-definitions ; List of all attribute definitions. (AstScheme (lambda (n) (->* (->attribution n))))) (ag-rule ast-rules ; List of all AST rules. (AstScheme (lambda (n) (->* (->astrules n))))) (ag-rule containing-rule ; Broadcast the AST rule containing a symbol. (AstRule (lambda (n) n))) (ag-rule terminal? ; Is the symbol a terminal? (Symbol (lambda (n) (char-lower-case? (string-ref (symbol->string (->name n)) 0))))) (ag-rule contextname ; User-specified, and otherwise implicit, context name of the symbol. (Symbol (lambda (n) (or (->contextname n) (if (->klenee n) (string->symbol (string-append (symbol->string (->name n)) "*")) (->name n)))))) ;;; Name Analysis: (ag-rule lookup-rule ; Given a symbolic name, find the respective AST rule (error rule if not defined). (AstScheme (lambda (n name) (or (ast-find-child (lambda (i n) (eq? (->name n) name)) (->astrules n)) (=error-rule n))))) (ag-rule startsymbol ; The grammar's start rule (error rule if not defined). (AstScheme (lambda (n) (=lookup-rule n (->startsymbol n))))) (ag-rule supertype? ; The rule's supertype (error rule if not defined) or #f if the rule does not inherite. (AstRule (lambda (n) (and (->supertype n) (=lookup-rule n (->supertype n)))))) (ag-rule non-terminal? ; The symbol's defining rule (error rule if not defined) or #f if the symbol is a terminal. (Symbol (lambda (n) (and (not (=terminal? n)) (=lookup-rule n (->name n)))))) (ag-rule lookup-contextname ; Given a symbolic name, find the respective child (error symbol if not defined). (AstRule (lambda (n name) (if (eq? name '*) n (or (find (lambda (n) (eq? (=contextname n) name)) (=expanded-rhand n)) (=error-symbol n)))))) ;;; Inheritance Analysis: (ag-rule supertypes ; List of all supertypes ordered w.r.t. inheritance (supertypes before their subtypes). (AstRule (lambda (n) (reverse (let loop ((current-rule n)) (let ((supertype? (=supertype? current-rule))) (cond ((or (not supertype?) (=error-node? supertype?)) (list)) ((eq? supertype? n) (list supertype?)) (else (cons supertype? (loop supertype?)))))))))) (ag-rule subtypes ; List of all subtypes (transitive but, if well-formed, not reflexive). (AstRule (lambda (n) (filter (lambda (rule) (memq n (=supertypes rule))) (=ast-rules n))))) (ag-rule expanded-rhand ; List of right-hand symbols including inherited ones. (AstRule (lambda (n) (fold-right (lambda (n result) (append (->* (->rhand n)) result)) (->* (->rhand n)) (=supertypes n))))) (ag-rule rhand-non-terminal-symbols ; List of right-hand symbols that are non-terminals. (AstRule (lambda (n) (filter (lambda (n) (not (=terminal? n))) (=expanded-rhand n))))) ;;; Derivability Analysis: (ag-rule productive? ; Does there exist a finite AST whose root is typed with the rule? (AstRule (lambda (n) (for-all (lambda (n) (or (->klenee n) (=productive? (=non-terminal? n)))) (=rhand-non-terminal-symbols n))) #f (lambda (r1 r2) (if r1 r2 (not r2))))) (ag-rule direct-derivable ; List of AST rules that are non-transitive applicable. (AstRule (lambda (n) (fold-left (lambda (result symbol) (let ((rule (=non-terminal? symbol))) (set-union (set-union (set-union result (=supertypes rule)) (list rule)) (=subtypes rule)))) (list) (=rhand-non-terminal-symbols n))))) (ag-rule derivable ; List of AST rules that are transitive applicable. (AstRule (lambda (n) (fold-left (lambda (result rule) (set-union result (=derivable rule))) (=direct-derivable n) (=direct-derivable n))) (list) (lambda (r1 r2) (= (length r1) (length r2))))) ;;; Attribution Analysis: (ag-rule synthesised? ; Is the attribute synthesised? (Attribute (lambda (n) ;(ast-subtype? (=context n) 'AstRule) (eq? (cdr (->context n)) '*)))) (ag-rule inherited? ; Is the attribute inherited? (Attribute (lambda (n) (not (=synthesised? n))))) (ag-rule circular? ; Is the attribute circular? (Attribute (lambda (n) (->circularitydefinition n)))) (ag-rule bottom-value ; The attribute's bottom value if it is circular, exception otherwise. (Attribute (lambda (n) (car (->circularitydefinition n))))) (ag-rule equality-function ; The attribute's equality function if it is circular, exception otherwise. (Attribute (lambda (n) (cdr (->circularitydefinition n))))) (ag-rule context-rule ; AST rule in whose context the attribute is defined. (Attribute (lambda (n) (=lookup-rule n (car (->context n)))))) (ag-rule context ; AST rule/symbol the attribute is defined for (AST rule if synthesised, symbol if inherited). (Attribute (lambda (n) (=lookup-contextname (=context-rule n) (cdr (->context n)))))) (let ((attributes-for-node ; List of attribute definitions for AST node. (lambda (n) (filter (lambda (attribute) (eq? (=context attribute) n)) (=attribute-definitions n))))) (ag-rule attributes-for-rule/symbol ; List of attribute definitions for the rule/symbol. (AstRule attributes-for-node) (Symbol attributes-for-node))) (ag-rule attributes ; List of attributes of AST rules and their right hand symbols considering inheritance. (AstRule (case-lambda ((n) ; List of synthesised attributes of the rule. (fold-right ; Process all ancestor AST rules in order of inheritance and... (lambda (n result) (set-union ; ...add the definitions of all synthesised attributes... result (=attributes-for-rule/symbol n) (lambda (a1 a2) ; ...that are not already defined. (eq? (->name a1) (->name a2))))) (=attributes-for-rule/symbol n) (=supertypes n))) ((n context-name) ; List of inherited attributes of a symbol of the rule. (let ((symbol (=lookup-contextname n context-name))) (fold-right ; Process each AST rule that has the symbol in order of inheritance and... (lambda (n result) (set-union ; ...add the definitions of all inherited attributes... result (filter (lambda (attribute) (eq? (=context-rule attribute) n)) (=attributes-for-rule/symbol symbol)) (lambda (a1 a2) ; ...that are not already defined for the symbol. (eq? (->name a1) (->name a2))))) (list) (memq (=containing-rule symbol) (append (=supertypes n) (list n))))))))) (ag-rule attributes-for-context ; Sorted list of all attributes of a node of a certain type if it is in a certain context. (AstScheme (lambda (n parent-type? context-name? child-type) (list-sort (lambda (a1 a2) (string<? (symbol->string (->name a1)) (symbol->string (->name a2)))) (if parent-type? (set-union (=attributes (=lookup-rule n child-type)) (=attributes (=lookup-rule n parent-type?) context-name?) (lambda (a1 a2) (eq? (->name a1) (->name a2)))) (=attributes (=lookup-rule n child-type))))))) ;;; Well-formedness Analysis: (let ((well-formed?-visitor ; Is an AST node, and are all ASTs of certain children of it, local correct? (lambda (n . to-visit) (and (=local-correct? n) (for-all (lambda (to-visit) (not (ast-find-child (lambda (i n) (not (=well-formed? n))) to-visit))) to-visit))))) (ag-rule well-formed? ; Is the specification valid, such that attributed AST instances can be constructed? (AstScheme (lambda (n) (well-formed?-visitor n (->astrules n) (->attribution n)))) (AstRule (lambda (n) (well-formed?-visitor n (->rhand n)))) (Symbol well-formed?-visitor) (Attribute well-formed?-visitor))) (ag-rule local-correct? ; Is a certain part of the specification valid? (AstScheme (lambda (n) (not (=error-node? (=startsymbol n))))) ; The start rule is defined. (AstRule (lambda (n) (or ; Either,... (=error-node? n) ; ...the rule is the error rule or... (and (eq? (=lookup-rule n (->name n)) n) ; ...(1) its name is unique,... (let ((supertype? (=supertype? n))) ; ...(2) if it has a supertype it exists,... (or (not supertype?) (not (=error-node? supertype?)))) (not (memq n (=subtypes n))) ; ...(3) if it inherits inheritance is cycle free,... (=productive? n) ; ...(4) it is productive and... (let ((s (=startsymbol n))) ; ...(4) either,... (or (memq n (cons s (=subtypes s))) ; ...the startsymbol, a subtype of the startsymbol or... (memq n (=derivable s)))))))) ; ...reachable from the startsymbol. (Symbol (lambda (n) (or ; Either,... (=error-node? n) ; ...the symbol is the error symbol or,... (let ((rule? (=non-terminal? n))) (and (not (and (->klenee n) (not rule?))) ; ...in case of Klenee closure, the symbol is a non-terminal,... (or (not rule?) (not (=error-node? rule?))) ; ...it is a terminal or a defined non-terminal and... (eq? (=lookup-contextname n (=contextname n)) n)))))) ; its context name is unique. (Attribute (lambda (n) (let ((context (=context n))) (and (not (=error-node? context)) ; The attribute's definition context exists and,... (not ; ...in case the attribute is inherited, is not a terminal and... (and (=inherited? n) (=terminal? context))) (eq? ; ...the definition is unique for it. (find (lambda (attribute) (eq? (->name attribute) (->name n))) (if (=synthesised? n) (=attributes context) (=attributes (=context-rule n) (cdr (->context n))))) n)))))) ;;; AST Construction: (ag-rule ast-node-factory ; Function that can be used to instantiate new AST nodes of certain type. (AstScheme (lambda (n name) (lambda children (let ((rule (=lookup-rule n name))) (when (=error-node? rule) (throw-exception ; BEWARE: Prolonged check ensures the rule exists at construction time! "Cannot construct " name " fragment;" "Unknown node type.")) (apply (=ast-node-factory rule) children))))) (AstRule (lambda (n) (define new-parent-type (->name n)) ; TODO: Delete ;(define children-fit? ; Do the given children fit in context? ; (let loop ((rhand (=expanded-rhand n))) ; (if (null? rhand) ; (lambda (children) (null? children)) ; (let ((fits? (=context-checker (car rhand))) ; (loop (loop (cdr rhand)))) ; (lambda (children) ; (and (not (null? children)) (fits? (car children)) (loop (cdr children)))))))) ;(define prepare-children ; Prepare the given children for new context. ; (let loop ((rhand (=expanded-rhand n))) ; (if (null? rhand) ; (lambda x (list)) ; (let ((prepare (=context-factory (car rhand))) ; (loop (loop (cdr rhand)))) ; (lambda (new-parent children) ; (cons (prepare new-parent-type new-parent (car children)) (loop new-parent (cdr children)))))))) ;(define rhand (=expanded-rhand n)) (define checkers (map =context-checker (=expanded-rhand n))) (define factories (map =context-factory (=expanded-rhand n))) (when (< (racr-specification-specification-phase (ast-specification n)) 2) (throw-exception ; BEWARE: Immediate check ensures the language specification is immutable! "Cannot construct fragment;" "The RACR specification is not compiled yet. It still is in the specification phase.")) (lambda children (let ((new-fragment (make-node n #f (list)))) ;;; Before constructing the fragment ensure, that... (unless (and ; ...the given children fit. (= (length children) (length checkers)) (for-all (lambda (f c) (f c)) checkers children)) (throw-exception "Cannot construct " n " fragment;" "The given children do not fit.")) ;;; When all constraints are satisfied, construct the fragment, i.e.,... (node-children-set! new-fragment (map (lambda (f c) (f new-parent-type new-fragment c)) factories children)) ; ...add its children,... (distribute-evaluator-state (make-evaluator-state) new-fragment) ; ...distribute the fragment's evaluator state and... (node-attributes-set! ; ...initialize its synthesized attributes. new-fragment (map (lambda (attribute) (make-attribute-instance attribute new-fragment)) (=attributes n))) new-fragment))))) ; Finally, return the constructed fragment. (ag-rule context-checker ; Function deciding if a given Scheme entity can become child in certain context. (Symbol (lambda (n) (define expected-type? (=non-terminal? n)) (define (satisfies-type? node) (or (node-bud-node? node) (node-instance-of?-2 node expected-type?))) (cond ((not expected-type?) ; Context is terminal? (lambda (node) #t)) ((->klenee n) ; Context is list? (lambda (node) (and (can-be-non-terminal-child? node) (or (node-bud-node? node) (and (node-list-node? node) (for-all satisfies-type? (->* node))))))) (else ; Context is ordinary non-terminal! (lambda (node) (and (can-be-non-terminal-child? node) (not (node-list-node? node)) (satisfies-type? node)))))))) (ag-rule context-factory ; Internal function preparing a given Scheme entity to become child in certain context. (Symbol (lambda (n) ; TODO: Delete unnecessary new-parent-type (define context-name (=contextname n)) (if (=terminal? n) (lambda (new-parent-type new-parent child) (make-node 'terminal new-parent child)) (lambda (new-parent-type new-parent child) (for-each ; Flush all attribute cache entries depending on the child being a root,... (lambda (influence) (flush-attribute-cache-entry (car influence))) (filter (lambda (influence) (vector-ref (cdr influence) 1)) (node-cache-influences child))) (node-parent-set! child new-parent) ; ...set its parent and... (update-attributes-2 new-parent-type context-name child) ; ...update its inherited attributes. child))))) (ag-rule attribution-factory ; Internal function updating the attribution of a node w.r.t. certain old and new context. (AstScheme (lambda (n old-context new-context) (define (equal-semantics a1 a2) ; Evaluate two attribute definitions always the same? (or ; Attribute definitions are semantically equivalent, if either... (eq? a1 a2) ; ...they are the same or... (and (eq? (->equation a1) (->equation a2)) ; ...have the same equation and... (if (=circular? a1) ; ...circularity definition. (and (=circular? a2) (equal? (=bottom-value a1) (=bottom-value a2)) (eq? (=equality-function a1) (=equality-function a2))) (not (=circular? a2)))))) (let loop ((old-attribution (if old-context (apply =attributes-for-context n old-context) (list))) (new-attribution (apply =attributes-for-context n new-context))) (cond ((and (null? old-attribution) (null? new-attribution)) ; No attributes to process left: (lambda (n old-instances) (list))) ((null? new-attribution) ; Only old attributes to delete left: (let ((loop (loop (cdr old-attribution) new-attribution))) (lambda (n old-instances) (flush-attribute-instance (car old-instances)) (attribute-instance-context-set! (car old-instances) racr-nil) (loop n (cdr old-instances))))) ((null? old-attribution) ; Only new attributes to add left: (let ((new-attribute (car new-attribution)) (loop (loop old-attribution (cdr new-attribution)))) (lambda (n old-instances) (cons (make-attribute-instance new-attribute n) (loop n #f))))) (else ; New and old attributes left: (let ((a1 (car old-attribution)) (a2 (car new-attribution))) (cond ((eq? (->name a1) (->name a2)) ; Definitions for the same attribute, either... (let ((loop (loop (cdr old-attribution) (cdr new-attribution)))) (if (equal-semantics a1 a2) (lambda (n old-instances) ; ...semantic equivalent or... (attribute-instance-definition-set! (car old-instances) a2) (cons (car old-instances) (loop n (cdr old-instances)))) (lambda (n old-instances) ; ...not semantic equivalent. (flush-attribute-instance (car old-instances)) (attribute-instance-definition-set! (car old-instances) a2) (cons (car old-instances) (loop n (cdr old-instances))))))) ((string<? (symbol->string (->name a1)) ; Old attribute deleted from lexical sorted list. (symbol->string (->name a2))) (let ((loop (loop (cdr old-attribution) new-attribution))) (lambda (n old-instances) (flush-attribute-instance (car old-instances)) (attribute-instance-context-set! (car old-instances) racr-nil) (loop n (cdr old-instances))))) (else ; New attribute inserted into lexical sorted list. (let ((loop (loop old-attribution (cdr new-attribution)))) (lambda (n old-instances) (cons (make-attribute-instance a2 n) (loop n old-instances))))))))))))) (compile-ag-specifications))) (define compile-ast-specifications (lambda (spec start-symbol) ;;; Ensure, that the RACR system is in the correct specification phase and... (let ((current-phase (racr-specification-specification-phase spec))) (if (> current-phase 1) (throw-exception "Unexpected AST compilation; " "The AST specifications already have been compiled.") ; ...iff so proceed to the next specification phase: (racr-specification-specification-phase-set! spec (+ current-phase 1)))) (racr-specification-start-symbol-set! spec start-symbol) (let* ((rules-list (racr-specification-rules-list spec)) ; Support function, that given a rule R returns a list of all rules directly derivable from R: (derivable-rules (lambda (rule*) (fold-left (lambda (result symb*) (if (symbol-non-terminal? symb*) (append result (list (symbol-non-terminal? symb*)) (ast-rule-subtypes (symbol-non-terminal? symb*))) result)) (list) (cdr (ast-rule-production rule*)))))) ;;; Resolve supertypes and non-terminals occuring in productions and ensure all non-terminals are defined: (for-each (lambda (rule*) (when (ast-rule-supertype? rule*) (let ((supertype-entry (racr-specification-find-rule spec (ast-rule-supertype? rule*)))) (if (not supertype-entry) (throw-exception "Invalid AST rule " (ast-rule-as-symbol rule*) "; " "The supertype " (ast-rule-supertype? rule*) " is not defined.") (ast-rule-supertype?-set! rule* supertype-entry)))) (for-each (lambda (symb*) (when (symbol-non-terminal? symb*) (let ((symb-definition (racr-specification-find-rule spec (symbol-name symb*)))) (when (not symb-definition) (throw-exception "Invalid AST rule " (ast-rule-as-symbol rule*) "; " "Non-terminal " (symbol-name symb*) " is not defined.")) (symbol-non-terminal?-set! symb* symb-definition)))) (cdr (ast-rule-production rule*)))) rules-list) ;;; Ensure, that inheritance is cycle-free: (for-each (lambda (rule*) (when (memq rule* (ast-rule-subtypes rule*)) (throw-exception "Invalid AST grammar; " "The definition of " (ast-rule-as-symbol rule*) " depends on itself (cyclic inheritance)."))) rules-list) ;;; Ensure, that the start symbol is defined: (unless (racr-specification-find-rule spec start-symbol) (throw-exception "Invalid AST grammar; " "The start symbol " start-symbol " is not defined.")) ;;; Resolve inherited production symbols: (apply-wrt-ast-inheritance (lambda (rule) (ast-rule-production-set! rule (append (list (car (ast-rule-production rule))) (map (lambda (symbol) (make-production-symbol (symbol-name symbol) rule (symbol-non-terminal? symbol) (symbol-kleene? symbol) (symbol-context-name symbol) (list))) (cdr (ast-rule-production (ast-rule-supertype? rule)))) (cdr (ast-rule-production rule))))) rules-list) ;;; Ensure context-names are unique: (for-each (lambda (ast-rule) (for-each (lambda (symbol) (unless (eq? (ast-rule-find-child-context ast-rule (symbol-context-name symbol)) symbol) (throw-exception "Invalid AST grammar; " "The context name " (symbol-context-name symbol) " is not unique for rule " (ast-rule-as-symbol ast-rule) "."))) (cdr (ast-rule-production ast-rule)))) rules-list) ;;; Ensure, that all non-terminals can be derived from the start symbol: (let* ((start-rule (racr-specification-find-rule spec start-symbol)) (to-check (cons start-rule (ast-rule-subtypes start-rule))) (checked (list))) (let loop () (unless (null? to-check) (let ((rule* (car to-check))) (set! to-check (cdr to-check)) (set! checked (cons rule* checked)) (for-each (lambda (derivable-rule) (when (and (not (memq derivable-rule checked)) (not (memq derivable-rule to-check))) (set! to-check (cons derivable-rule to-check)))) (derivable-rules rule*)) (loop)))) (let ((non-derivable-rules (filter (lambda (rule*) (not (memq rule* checked))) rules-list))) (unless (null? non-derivable-rules) (throw-exception "Invalid AST grammar; " "The rules " (map ast-rule-as-symbol non-derivable-rules) " cannot be derived.")))) ;;; Ensure, that all non-terminals are productive: (let* ((productive-rules (list)) (to-check rules-list) (productive-rule? (lambda (rule*) (not (find (lambda (symb*) (and (symbol-non-terminal? symb*) (not (symbol-kleene? symb*)) ; Unbounded repetitions are always productive because of the empty list. (not (memq (symbol-non-terminal? symb*) productive-rules)))) (cdr (ast-rule-production rule*))))))) (let loop () (let ((productive-rule (find productive-rule? to-check))) (when productive-rule (set! to-check (remq productive-rule to-check)) (set! productive-rules (cons productive-rule productive-rules)) (loop)))) (unless (null? to-check) (throw-exception "Invalid AST grammar; " "The rules " (map ast-rule-as-symbol to-check) " are not productive.")))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Attribute Specification ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-syntax specify-ag-rule (lambda (x) (syntax-case x () ((_ spec att-name definition ...) (and (identifier? #'att-name) (not (null? #'(definition ...)))) #'(let ((spec* spec) (att-name* 'att-name)) (let-syntax ((specify-attribute* (syntax-rules () ((_ spec* att-name* ((non-terminal index) equation)) (specify-attribute spec* att-name* 'non-terminal 'index #t equation #f)) ((_ spec* att-name* ((non-terminal index) cached? equation)) (specify-attribute spec* att-name* 'non-terminal 'index cached? equation #f)) ((_ spec* att-name* ((non-terminal index) equation bottom equivalence-function)) (specify-attribute spec* att-name* 'non-terminal 'index #t equation (cons bottom equivalence-function))) ((_ spec* att-name* ((non-terminal index) cached? equation bottom equivalence-function)) (specify-attribute spec* att-name* 'non-terminal 'index cached? equation (cons bottom equivalence-function))) ((_ spec* att-name* (non-terminal equation)) (specify-attribute spec* att-name* 'non-terminal 0 #t equation #f)) ((_ spec* att-name* (non-terminal cached? equation)) (specify-attribute spec* att-name* 'non-terminal 0 cached? equation #f)) ((_ spec* att-name* (non-terminal equation bottom equivalence-function)) (specify-attribute spec* att-name* 'non-terminal 0 #t equation (cons bottom equivalence-function))) ((_ spec* att-name* (non-terminal cached? equation bottom equivalence-function)) (specify-attribute spec* att-name* 'non-terminal 0 cached? equation (cons bottom equivalence-function)))))) (specify-attribute* spec* att-name* definition) ...)))))) (define specify-attribute (lambda (spec attribute-name non-terminal context-name-or-position cached? equation circularity-definition) ;;; Before adding the attribute definition, ensure... (let ((wrong-argument-type ; ...correct argument types,... (or (and (not (symbol? attribute-name)) "Attribute name : symbol") (and (not (symbol? non-terminal)) "AST rule : non-terminal") (and (not (symbol? context-name-or-position)) (or (not (integer? context-name-or-position)) (< context-name-or-position 0)) "Production position : index or context-name") (and (not (procedure? equation)) "Attribute equation : function") (and circularity-definition (not (pair? circularity-definition)) (not (procedure? (cdr circularity-definition))) "Circularity definition : #f or (bottom-value equivalence-function) pair")))) (when wrong-argument-type (throw-exception "Invalid attribute definition; " "Wrong argument type (" wrong-argument-type ")."))) (unless (= (racr-specification-specification-phase spec) 2) ; ...that the RACR system is in the correct specification phase,... (throw-exception "Unexpected " attribute-name " attribute definition; " "Attributes can only be defined in the AG specification phase.")) (let ((ast-rule (racr-specification-find-rule spec non-terminal))) (unless ast-rule ; ...the given AST rule is defined,... (throw-exception "Invalid attribute definition; " "The non-terminal " non-terminal " is not defined.")) (let* ((context? ; ...the given context exists,... (if (symbol? context-name-or-position) (if (eq? context-name-or-position '*) (car (ast-rule-production ast-rule)) (ast-rule-find-child-context ast-rule context-name-or-position)) (if (>= context-name-or-position (length (ast-rule-production ast-rule))) (throw-exception "Invalid attribute definition; " "There exists no " context-name-or-position "'th position in the context of " non-terminal ".") (list-ref (ast-rule-production ast-rule) context-name-or-position))))) (unless context? (throw-exception "Invalid attribute definition; " "The non-terminal " non-terminal " has no " context-name-or-position " context.")) (unless (symbol-non-terminal? context?) ; ...it is a non-terminal and... (throw-exception "Invalid attribute definition; " non-terminal context-name-or-position " is a terminal.")) ; ...the attribute is not already defined for it: (when (memq attribute-name (map attribute-definition-name (symbol-attributes context?))) (throw-exception "Invalid attribute definition; " "Redefinition of " attribute-name " for " non-terminal context-name-or-position ".")) ;;; Everything is fine. Thus, add the definition to the AST rule's respective symbol: (symbol-attributes-set! context? (cons (make-attribute-definition attribute-name context? equation circularity-definition cached?) (symbol-attributes context?))))))) (define compile-ag-specifications (lambda (spec) ;;; Ensure, that the RACR system is in the correct specification phase and... (let ((current-phase (racr-specification-specification-phase spec))) (when (< current-phase 2) (throw-exception "Unexpected AG compilation; " "The AST specifications are not yet compiled.")) (if (> current-phase 2) (throw-exception "Unexpected AG compilation; " "The AG specifications already have been compiled.") (racr-specification-specification-phase-set! spec (+ current-phase 1)))) ; ...if so proceed to the next specification phase. ;;; Resolve attribute definitions inherited from a supertype. Thus,... (apply-wrt-ast-inheritance ; ...for every AST rule R which has a supertype... (lambda (rule) (let loop ((super-prod (ast-rule-production (ast-rule-supertype? rule))) (sub-prod (ast-rule-production rule))) (unless (null? super-prod) (for-each ; ...check for every attribute definition of R's supertype... (lambda (super-att-def) (unless (find ; ...if it is shadowed by an attribute definition of R.... (lambda (sub-att-def) (eq? (attribute-definition-name sub-att-def) (attribute-definition-name super-att-def))) (symbol-attributes (car sub-prod))) (symbol-attributes-set! ; ...If not, add... (car sub-prod) (cons (make-attribute-definition ; ...a copy of the attribute definition inherited... (attribute-definition-name super-att-def) (car sub-prod) ; ...to R. (attribute-definition-equation super-att-def) (attribute-definition-circularity-definition super-att-def) (attribute-definition-cached? super-att-def)) (symbol-attributes (car sub-prod)))))) (symbol-attributes (car super-prod))) (loop (cdr super-prod) (cdr sub-prod))))) (racr-specification-rules-list spec)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Attribute Evaluation ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (att-in-evaluation? n) (evaluator-state-in-evaluation? (node-evaluator-state n))) ; INTERNAL FUNCTION: Given a node n find a certain attribute associated with it, whereas in case no proper ; attribute is associated with n itself the search is extended to find a broadcast solution. If the ; extended search finds a solution, appropriate copy propergation attributes (i.e., broadcasters) are added. ; If no attribute instance can be found or n is a bud node, an exception is thrown. Otherwise, the ; attribute or its respective last broadcaster is returned. (define lookup-attribute (lambda (name n) (when (node-bud-node? n) (throw-exception "AG evaluator exception; " "Cannot access " name " attribute - the given node is a bud.")) (let loop ((n n)) ; Recursively... (let ((att (node-find-attribute n name))) ; ...check if the current node has a proper attribute instance.... (if att att ; ...If it has, return the found defining attribute instance. (let ((parent (node-parent n))) ; ...If no defining attribute instance can be found... (if (not parent) ; ...check if there exists a parent node that may provide a definition.... (throw-exception ; ...If not, throw an exception,... "AG evaluator exception; " "Cannot access unknown " name " attribute.") (let* ((att (loop parent)) ; ...otherwise proceed the search at the parent node. If it succeeds... (broadcaster ; ...construct a broadcasting attribute instance... (make-attribute-instance (make-attribute-definition ; ...whose definition context depends... name (if (eq? (node-ast-rule parent) 'list-node) ; ...if the parent node is a list node or not.... (list-ref ; ...If it is a list node the broadcaster's context is... (ast-rule-production (node-ast-rule (node-parent parent))) ; ...the list node's parent node and... (node-child-index? parent)) ; ...child position. (list-ref ; ...If the parent node is not a list node the broadcaster's context is... (ast-rule-production (node-ast-rule parent)) ; ...the parent node and... (node-child-index? n))) ; ...the current node's child position. Further,... (lambda (n . args) ; ...the broadcaster's equation just calls the parent node's counterpart. Finally,... (apply att-value name (ast-parent n) args)) (attribute-definition-circularity-definition (attribute-instance-definition att)) #f) n))) (node-attributes-set! n (cons broadcaster (node-attributes n))) ; ...add the constructed broadcaster and... broadcaster)))))))) ; ...return it as the current node's look-up result. (define att-value (lambda (name n . args) (let*-values (; The evaluator state used and changed throughout evaluation: ((evaluator-state) (values (node-evaluator-state n))) ; The attribute instance to evaluate: ((att) (values (lookup-attribute name n))) ; The attribute's definition: ((att-def) (values (attribute-instance-definition att))) ; The attribute cache entries used for evaluation and dependency tracking: ((evaluation-att-cache dependency-att-cache) (if (attribute-definition-cached? att-def) ; If the attribute instance is cached, no special action is required, except... (let ((att-cache (or ; ...finding the attribute cache entry to use... (hashtable-ref (attribute-instance-cache att) args #f) ; ...or construct a respective one. (let ((new-entry (make-attribute-cache-entry att args))) (hashtable-set! (attribute-instance-cache att) args new-entry) new-entry)))) (values att-cache att-cache)) ; If the attribute is not cached, special attention must be paid to avoid the permament storing ; of fixpoint results and attribute arguments on the one hand but still retaining correct ; evaluation which requires these information on the other hand. To do so we introduce two ; different types of attribute cache entries: ; (1) A parameter approximating entry for tracking dependencies and influences of the uncached ; attribute instance. ; (2) A set of temporary cycle entries for correct cycle detection and fixpoint computation. ; The "cycle-value" field of the parameter approximating entry is misused to store the hashtable ; containing the temporary cycle entries and must be deleted when evaluation finished. (let* ((dependency-att-cache (or (hashtable-ref (attribute-instance-cache att) racr-nil #f) (let ((new-entry (make-attribute-cache-entry att racr-nil))) (hashtable-set! (attribute-instance-cache att) racr-nil new-entry) (attribute-cache-entry-cycle-value-set! new-entry (make-hashtable equal-hash equal? 1)) new-entry))) (evaluation-att-cache (or (hashtable-ref (attribute-cache-entry-cycle-value dependency-att-cache) args #f) (let ((new-entry (make-attribute-cache-entry att args))) (hashtable-set! (attribute-cache-entry-cycle-value dependency-att-cache) args new-entry) new-entry)))) (values evaluation-att-cache dependency-att-cache)))) ; Support function that given an intermediate fixpoint result checks if it is different from the ; current cycle value and updates the cycle value and evaluator state accordingly: ((update-cycle-cache) (values (lambda (new-result) (unless ((cdr (attribute-definition-circularity-definition att-def)) new-result (attribute-cache-entry-cycle-value evaluation-att-cache)) (attribute-cache-entry-cycle-value-set! evaluation-att-cache new-result) (evaluator-state-ag-cycle-change?-set! evaluator-state #t)))))) ; Decide how to evaluate the attribute dependening on whether its value already is cached or its respective ; cache entry is circular, already in evaluation or starting point of a fix-point computation: (cond ; CASE (0): Attribute already evaluated for given arguments: ((not (eq? (attribute-cache-entry-value evaluation-att-cache) racr-nil)) ; Maintaine attribute cache entry dependencies, i.e., if this entry is evaluated throughout the ; evaluation of another entry, the other entry depends on this one. Afterwards,... (add-dependency:cache->cache dependency-att-cache) (attribute-cache-entry-value evaluation-att-cache)) ; ...return the cached value. ; CASE (1): Circular attribute that is starting point of a fixpoint computation: ((and (attribute-definition-circular? att-def) (not (evaluator-state-ag-in-cycle? evaluator-state))) (dynamic-wind (lambda () ; Maintaine attribute cache entry dependencies, i.e., if this entry is evaluated throughout the ; evaluation of another entry, the other depends on this one. Further this entry depends ; on any other entry that will be evaluated through its own evaluation. Further,.. (add-dependency:cache->cache dependency-att-cache) (evaluator-state-evaluation-stack-set! evaluator-state (cons dependency-att-cache (evaluator-state-evaluation-stack evaluator-state))) ; ...mark, that the entry is in evaluation and... (attribute-cache-entry-entered?-set! evaluation-att-cache #t) ; ...update the evaluator's state that we are about to start a fix-point computation. (evaluator-state-ag-in-cycle?-set! evaluator-state #t)) (lambda () (let loop () ; Start fix-point computation. Thus, as long as... (evaluator-state-ag-cycle-change?-set! evaluator-state #f) ; ...an entry's value changes... (update-cycle-cache (apply (attribute-definition-equation att-def) n args)) ; ...evaluate this entry. (when (evaluator-state-ag-cycle-change? evaluator-state) (loop))) (let ((result (attribute-cache-entry-cycle-value evaluation-att-cache))) ; When fixpoint computation finished update the caches of all circular entries evaluated. To do so,... (let loop ((att-cache (if (attribute-definition-cached? att-def) evaluation-att-cache dependency-att-cache))) (let ((att-def (attribute-instance-definition (attribute-cache-entry-context att-cache)))) (if (not (attribute-definition-circular? att-def)) ; ...ignore non-circular entries and just proceed with the entries they depend on (to ; ensure all strongly connected components within a weakly connected one are updated).... (for-each loop (attribute-cache-entry-cache-dependencies att-cache)) ; ...In case of circular entries... (if (attribute-definition-cached? att-def) ; ...check if they have to be cached and... (when (eq? (attribute-cache-entry-value att-cache) racr-nil) ; ...are not already processed.... ; ...If so cache them,... (attribute-cache-entry-value-set! att-cache (attribute-cache-entry-cycle-value att-cache)) (attribute-cache-entry-cycle-value-set! ; ...reset their cycle values to the bottom value and... att-cache (car (attribute-definition-circularity-definition att-def))) (for-each ; ...proceed with the entries they depend on. loop (attribute-cache-entry-cache-dependencies att-cache))) ; ...If a circular entry is not cached, check if it already is processed.... (when (> (hashtable-size (attribute-cache-entry-cycle-value att-cache)) 0) ; ...If not, delete its temporary cycle cache and... (hashtable-clear! (attribute-cache-entry-cycle-value att-cache)) (for-each ; ...proceed with the entries it depends on. loop (attribute-cache-entry-cache-dependencies att-cache))))))) result)) (lambda () ; Mark that fixpoint computation finished,... (evaluator-state-ag-in-cycle?-set! evaluator-state #f) ; the evaluation of the attribute cache entry finished and... (attribute-cache-entry-entered?-set! evaluation-att-cache #f) ; ...pop the entry from the evaluation stack. (evaluator-state-evaluation-stack-set! evaluator-state (cdr (evaluator-state-evaluation-stack evaluator-state)))))) ; CASE (2): Circular attribute already in evaluation for the given arguments: ((and (attribute-definition-circular? att-def) (attribute-cache-entry-entered? evaluation-att-cache)) ; Maintaine attribute cache entry dependencies, i.e., if this entry is evaluated throughout the ; evaluation of another entry, the other entry depends on this one. Finally,... (add-dependency:cache->cache dependency-att-cache) ; ...the intermediate fixpoint result is the attribute cache entry's cycle value. (attribute-cache-entry-cycle-value evaluation-att-cache)) ; CASE (3): Circular attribute not in evaluation and entered throughout a fixpoint computation: ((attribute-definition-circular? att-def) (dynamic-wind (lambda () ; Maintaine attribute cache entry dependencies, i.e., if this entry is evaluated throughout the ; evaluation of another entry, the other depends on this one. Further this entry depends ; on any other entry that will be evaluated through its own evaluation. Further,.. (add-dependency:cache->cache dependency-att-cache) (evaluator-state-evaluation-stack-set! evaluator-state (cons dependency-att-cache (evaluator-state-evaluation-stack evaluator-state))) ; ...mark, that the entry is in evaluation. (attribute-cache-entry-entered?-set! evaluation-att-cache #t)) (lambda () (let ((result (apply (attribute-definition-equation att-def) n args))) ; Evaluate the entry and... (update-cycle-cache result) ; ...update its cycle value. result)) (lambda () ; Mark that the evaluation of the attribute cache entry finished and... (attribute-cache-entry-entered?-set! evaluation-att-cache #f) ; ...pop it from the evaluation stack. (evaluator-state-evaluation-stack-set! evaluator-state (cdr (evaluator-state-evaluation-stack evaluator-state)))))) ; CASE (4): Non-circular attribute already in evaluation, i.e., unexpected cycle: ((attribute-cache-entry-entered? evaluation-att-cache) ; Maintaine attribute cache entry dependencies, i.e., if this entry is evaluated throughout the ; evaluation of another entry, the other entry depends on this one. Then,... (add-dependency:cache->cache dependency-att-cache) (throw-exception ; ...thrown an exception because we encountered an unexpected dependency cycle. "AG evaluator exception; " "Unexpected " name " cycle.")) (else ; CASE (5): Non-circular attribute not in evaluation: (dynamic-wind (lambda () ; Maintaine attribute cache entry dependencies, i.e., if this entry is evaluated throughout the ; evaluation of another entry, the other depends on this one. Further this entry depends ; on any other entry that will be evaluated through its own evaluation. Further,... (add-dependency:cache->cache dependency-att-cache) (evaluator-state-evaluation-stack-set! evaluator-state (cons dependency-att-cache (evaluator-state-evaluation-stack evaluator-state))) ; ...mark, that the entry is in evaluation. (attribute-cache-entry-entered?-set! evaluation-att-cache #t)) (lambda () (let ((result (apply (attribute-definition-equation att-def) n args))) ; Evaluate the entry and,... (when (attribute-definition-cached? att-def) ; ...if caching is enabled,... (attribute-cache-entry-value-set! evaluation-att-cache result)) ; ...cache its value. result)) (lambda () ; Mark that the evaluation of the attribute cache entry finished and... (if (attribute-definition-cached? att-def) (attribute-cache-entry-entered?-set! evaluation-att-cache #f) (hashtable-delete! (attribute-cache-entry-cycle-value dependency-att-cache) args)) ; ...pop it from the evaluation stack. (evaluator-state-evaluation-stack-set! evaluator-state (cdr (evaluator-state-evaluation-stack evaluator-state)))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Specification Queries ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; General Note: Because RACR specifications never change after compilation, there is no need to add and ; maintain dependencies when attributes query specifications. The specification query API therefore just ; forwards to the respective internal functions. Lists must be copied before they are returned however. ; Specification Queries: (define specification->phase (lambda (spec) (racr-specification-specification-phase spec))) (define specification->start-symbol (lambda (spec) (racr-specification-start-symbol spec))) (define specification->ast-rules (lambda (spec) (racr-specification-rules-list spec))) ; Already creates copy! (define specification->find-ast-rule (lambda (spec node-type) (racr-specification-find-rule spec node-type))) ; AST Rule Queries: (define ast-rule->symbolic-representation (lambda (ast-rule) (ast-rule-as-symbol ast-rule))) (define ast-rule->supertype? (lambda (ast-rule) (ast-rule-supertype? ast-rule))) (define ast-rule->production (lambda (rule) (append (ast-rule-production rule) (list)))) ; Create copy! ; Production Symbol Queries: (define symbol->name (lambda (symb) (symbol-name symb))) (define symbol->non-terminal? (lambda (symb) (symbol-non-terminal? symb))) (define symbol->kleene? (lambda (symb) (symbol-kleene? symb))) (define symbol->context-name (lambda (symb) (symbol-context-name symb))) (define symbol->attributes (lambda (symbol) (append (symbol-attributes symbol) (list)))) ; Create copy! ; Attribute Definition Queries: (define attribute->name (lambda (att-def) (attribute-definition-name att-def))) (define attribute->circular? (lambda (att-def) (attribute-definition-circular? att-def))) (define attribute->synthesized? (lambda (att-def) (attribute-definition-synthesized? att-def))) (define attribute->inherited? (lambda (att-def) (attribute-definition-inherited? att-def))) (define attribute->cached? (lambda (att-def) (attribute-definition-cached? att-def))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Abstract Syntax Tree Queries ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define ast-node? ; Scheme entities are either allocated as AST nodes or never will be => No need to add dependencies! (lambda (n) (node? n))) (define ast-specification (lambda (n) (when (or (ast-list-node? n) (ast-bud-node? n)) ; Remember: Terminal nodes as such are never exposed to users. (throw-exception "Cannot query specification; " "List and bud nodes are not part of any specification.")) ; The specification of a node can never change => No need to add dependencies! (ast-rule-specification (node-ast-rule n)))) (define ast-list-node? ; No dependency tracking needed! (lambda (n) (node-list-node? n))) (define ast-bud-node? ; No dependency tracking needed! (lambda (n) (node-bud-node? n))) (define ast-node-rule (lambda (n) (when (or (ast-list-node? n) (ast-bud-node? n)) ; Remember: Terminal nodes as such are never exposed to users. (throw-exception "Cannot query type; " "List and bud nodes have no type.")) (add-dependency:cache->node-type n) (node-ast-rule n))) (define ast-node-type (lambda (n) (symbol-name (car (ast-rule-production (ast-node-rule n)))))) (define ast-subtype? (lambda (a1 a2) (when (or (and (ast-node? a1) (or (ast-list-node? a1) (ast-bud-node? a1))) (and (ast-node? a2) (or (ast-list-node? a2) (ast-bud-node? a2)))) (throw-exception "Cannot perform subtype check; " "List and bud nodes cannot be tested for subtyping.")) (when (and (not (ast-node? a1)) (not (ast-node? a2))) (throw-exception "Cannot perform subtype check; " "At least one argument must be an AST node.")) ((lambda (t1/t2) (and (car t1/t2) (cdr t1/t2) (ast-rule-subtype? (car t1/t2) (cdr t1/t2)))) (if (symbol? a1) (let* ((t2 (node-ast-rule a2)) (t1 (racr-specification-find-rule (ast-rule-specification t2) a1))) (unless t1 (throw-exception "Cannot perform subtype check; " a1 " is no valid non-terminal (first argument undefined non-terminal).")) (add-dependency:cache->node-super-type a2 t1) (cons t1 t2)) (if (symbol? a2) (let* ((t1 (node-ast-rule a1)) (t2 (racr-specification-find-rule (ast-rule-specification t1) a2))) (unless t1 (throw-exception "Cannot perform subtype check; " a2 " is no valid non-terminal (second argument undefined non-terminal).")) (add-dependency:cache->node-sub-type a1 t2) (cons t1 t2)) (begin (add-dependency:cache->node-sub-type a1 (node-ast-rule a2)) (add-dependency:cache->node-super-type a2 (node-ast-rule a1)) (cons (node-ast-rule a1) (node-ast-rule a2)))))))) (define ast-has-parent? (lambda (n) (let ((parent (node-parent n))) (if parent (begin (add-dependency:cache->node-upwards parent) parent) (begin (add-dependency:cache->node-is-root n) #f))))) (define ast-parent (lambda (n) (let ((parent (node-parent n))) (unless parent (throw-exception "Cannot query parent of roots.")) (add-dependency:cache->node-upwards parent) parent))) (define ast-has-child? (lambda (context-name n) (add-dependency:cache->node-defines-context n context-name) (if (node-find-child n context-name) #t #f))) ; BEWARE: Never return the child if it exists, but instead just #t! (define ast-child (lambda (i n) (let ((child (if (symbol? i) (node-find-child n i) (and (>= i 1) (<= i (length (node-children n))) (list-ref (node-children n) (- i 1)))))) (unless child (throw-exception "Cannot query non-existent " i (if (symbol? i) "" "'th") " child.")) (add-dependency:cache->node-downwards child) (if (node-terminal? child) (node-children child) child)))) (define ast-has-sibling? (lambda (context-name n) (let ((parent? (ast-has-parent? n))) (and parent? (ast-has-child? context-name parent?))))) (define ast-sibling (lambda (i n) (ast-child i (ast-parent n)))) (define ast-child-index (lambda (n) (ast-find-child* (lambda (i child) (if (eq? child n) i #f)) (ast-parent n)))) (define ast-num-children (lambda (n) (add-dependency:cache->node-num-children n) (length (node-children n)))) (define ast-children (lambda (n . b) (reverse (let ((result (list))) (apply ast-for-each-child (lambda (i child) (set! result (cons child result))) n b) result)))) (define ast-for-each-child (lambda (f n . b) (let ((b (if (null? b) (list (cons 1 '*)) b))) (for-each (lambda (b) (if (eq? (cdr b) '*) (let ((pos (car b)) (ub (length (node-children n)))) (dynamic-wind (lambda () #f) (lambda () (let loop () (when (<= pos ub) (f pos (ast-child pos n)) (set! pos (+ pos 1)) (loop)))) (lambda () (when (> pos ub) (ast-num-children n))))) ; BEWARE: Access to number of children ensures proper dependency tracking! (let loop ((pos (car b))) (when (<= pos (cdr b)) (f pos (ast-child pos n)) (loop (+ pos 1)))))) b)))) (define ast-find-child (lambda (f n . b) (call/cc (lambda (c) (apply ast-for-each-child (lambda (i child) (when (f i child) (c child))) n b) #f)))) (define ast-find-child* (lambda (f n . b) (call/cc (lambda (c) (apply ast-for-each-child (lambda (i child) (let ((res (f i child))) (when res (c res)))) n b) #f)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Abstract Syntax Tree Construction ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (create-ast-2 spec rule children) (apply (=ast-node-factory (racr-specification-2-ast-scheme spec) rule) children)) (define (create-ast-list-2 children) ;;; Before constructing the list node ensure, that... (unless (for-all can-be-list-element? children) ; ...all children fit. (throw-exception "Cannot construct list node;" "The given children do not fit.")) ;;; When all constraints are satisfied,... (for-each ; ...flush all attribute cache entries depending on the children being roots,... (lambda (child) (for-each (lambda (influence) (flush-attribute-cache-entry (car influence))) (filter (lambda (influence) (vector-ref (cdr influence) 1)) (node-cache-influences child)))) children) (let ((new-list (make-node 'list-node #f (append children (list))))) ; ...construct the list node,... (for-each ; ...set it as parent of each child,... (lambda (child) (node-parent-set! child new-list)) children) (distribute-evaluator-state (make-evaluator-state) new-list) ; ...distribute its evaluator state and... new-list)) ; ...return it. ; INTERNAL FUNCTION: Is a Scheme entity permitted as non-terminal child of other AST nodes? (define (can-be-non-terminal-child? node) (and (ast-node? node) ; The node is a non-terminal node (Remember: Terminal nodes as such are never exposed to users),... (not (node-parent node)) ; ...not already part of another AST and... (not (evaluator-state-in-evaluation? (node-evaluator-state node))))) ; ...non of its attributes are in evaluation. ; INTERNAL FUNCTION: Is a Scheme entity permitted as element in list nodes? (define (can-be-list-element? node) (and (can-be-non-terminal-child? node) ; The node can be a non-terminal child and... (not (node-list-node? node)))) ; ...is not a list node. ; INTERNAL FUNCTION: Given a node in some context update its attribution (the given context must be valid). (define (update-attributes-2 parent-type context-name n) (define (equal-semantics a1 a2) ; Evaluate two attribute definitions always the same? (or ; Attribute definitions are semantically equivalent, if either... (eq? a1 a2) ; ...they are the same or... (and (eq? (->equation a1) (->equation a2)) ; ...have the same equation and... (if (=circular? a1) ; ...circularity definition. (and (=circular? a2) (equal? (=bottom-value a1) (=bottom-value a2)) (eq? (=equality-function a1) (=equality-function a2))) (not (=circular? a2)))))) ;;; Update the node's attributes w.r.t. its context. To do so,... (if (node-list-node? n) ; ...check if the node is a list. If so,... (for-each (lambda (n) (update-attributes-2 parent-type context-name n)) (node-children n)) ; ...update all its elements... (unless (or (node-terminal? n) (node-bud-node? n)) ; ...otherwise ensure it is an ordinary non-terminal. If so,... (let ((old-attribute-instances (node-attributes n))) (node-attributes-set! ; ...construct the list of its attribute instances, i.e.,... n (map ; ...for each... (lambda (attribute) (let ((instance? (node-find-attribute-2 n (->name attribute)))) ; ...existing instance with... (if (and instance? (equal-semantics (attribute-instance-definition instance?) attribute)) ; ...unchaged semantics... (begin (attribute-instance-definition-set! instance? attribute) ; ...just update the instance's definition... instance?) (make-attribute-instance attribute n)))) ; ...If a proper instance does not yet exist, add it. Finally,... (=attributes-for-context (node-ast-rule n) parent-type context-name (->name (node-ast-rule n))))) (for-each ; ...flush the cache of all instances no more defined or whose definition changed. (lambda (attribute-instance) (when (not (memq attribute-instance (node-attributes n))) (flush-attribute-instance attribute-instance) (attribute-instance-context-set! attribute-instance racr-nil))) old-attribute-instances))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define create-ast (lambda (spec rule children) ;;; Before constructing the node ensure, that... (when (< (racr-specification-specification-phase spec) 3) ; ...the RACR system is completely specified,... (throw-exception "Cannot construct " rule " fragment; " "The RACR specification still must be compiled.")) (let* ((ast-rule (racr-specification-find-rule spec rule)) (new-fragment (make-node ast-rule #f (list)))) (unless ast-rule ; ...the given AST rule is defined,... (throw-exception "Cannot construct " rule " fragment; " "Unknown non-terminal/rule.")) (unless (satisfies-contexts? children (cdr (ast-rule-production ast-rule))) ; ...and the children fit. (throw-exception "Cannot construct " rule " fragment; " "The given children do not fit.")) ;;; When all constraints are satisfied, construct the new fragment,... (node-children-set! ; ...add its children,... new-fragment (map ; ...set it as parent of each child,... (lambda (symbol child) (if (symbol-non-terminal? symbol) (begin (for-each ; ...flush all attribute cache entries depending on any added child being a root,... (lambda (influence) (flush-attribute-cache-entry (car influence))) (filter (lambda (influence) (vector-ref (cdr influence) 1)) (node-cache-influences child))) (node-parent-set! child new-fragment) child) (make-node 'terminal new-fragment child))) (cdr (ast-rule-production ast-rule)) children)) (distribute-evaluator-state (make-evaluator-state) new-fragment) ; ...distribute the new fragment's evaluator state and... (update-synthesized-attribution new-fragment) ; ...initialize its synthesized and... (for-each ; ...each child's inherited attributes. update-inherited-attribution (node-children new-fragment)) new-fragment))) ; Finally, return the newly constructed fragment. (define create-ast-list (lambda (children) ;;; Before constructing the list node ensure, that... (let ((new-list (make-node 'list-node #f (append children (list))))) ; BEWARE: create copy of children! (unless (for-all ; ...all children fit. (lambda (child) (valid-list-element-candidate? new-list child)) children) (throw-exception "Cannot construct list node; " "The given children do not fit.")) ;;; When all constraints are satisfied,... (for-each ; ...flush all attribute cache entries depending on the children being roots,... (lambda (child) (for-each (lambda (influence) (flush-attribute-cache-entry (car influence))) (filter (lambda (influence) (vector-ref (cdr influence) 1)) (node-cache-influences child)))) children) (for-each ; ...set the new list node as parent of every child,... (lambda (child) (node-parent-set! child new-list)) children) (distribute-evaluator-state (make-evaluator-state) new-list) ; ...construct and distribute its evaluator state and... new-list))) ; ...return it. (define create-ast-bud (lambda () (let ((bud-node (make-node 'bud-node #f (list)))) (distribute-evaluator-state (make-evaluator-state) bud-node) bud-node))) (define create-ast-mockup (lambda (rule) (create-ast (ast-rule-specification rule) (symbol-name (car (ast-rule-production rule))) (map (lambda (symbol) (cond ((not (symbol-non-terminal? symbol)) racr-nil) ((symbol-kleene? symbol) (create-ast-list (list))) (else (create-ast-bud)))) (cdr (ast-rule-production rule)))))) ; INTERNAL FUNCTION: Given two non-terminal nodes, return if the second can replace the first regarding its context. (define valid-replacement-candidate? (lambda (node candidate) (if (node-list-node? (node-parent node)) (valid-list-element-candidate? (node-parent node) candidate) (and (satisfies-context? candidate (list-ref (ast-rule-production (node-ast-rule (node-parent node))) (node-child-index? node))) (not (node-inside-of? node candidate)))))) ; INTERNAL FUNCTION: Given a list node and another node, return if the other node can become element of ; the list node regarding its context. (define valid-list-element-candidate? (lambda (list-node candidate) (let ((expected-type? ; If the list node has a parent, its parent induces a type for the list's elements. (if (node-parent list-node) (symbol-non-terminal? (list-ref (ast-rule-production (node-ast-rule (node-parent list-node))) (node-child-index? list-node))) #f))) (and ; The given candidate can be element of the list, if (1)... (if expected-type? ; ...either,... (satisfies-context? candidate expected-type? #f) ; ...the candidate fits regarding the context in which the list is, or,... (and ; ...in case no type is induced for the list's elements,... (ast-node? candidate) ; ...the candiate is a non-terminal node,... (not (node-list-node? candidate)) ; ...not a list node,... (not (node-parent candidate)) ; ...not already part of another AST and... (not (evaluator-state-in-evaluation? (node-evaluator-state candidate))))) ; ...non of its attributes are in evaluation,... (not (node-inside-of? list-node candidate)))))) ; ...and (2) its spaned AST does not contain the list node. ; INTERNAL FUNCTION: Given a node or terminal value and a context, return if the ; node/terminal value can become a child of the given context. (define satisfies-context? (case-lambda ((child context) (satisfies-context? child (symbol-non-terminal? context) (symbol-kleene? context))) ((child non-terminal? kleene?) (or ; The given child is valid if either,... (not non-terminal?) ; ...a terminal is expected or,... (and ; ...in case a non-terminal is expected,... (ast-node? child) ; ...the given child is an AST node,... (not (node-parent child)) ; ...does not already belong to another AST,... (not (evaluator-state-in-evaluation? (node-evaluator-state child))) ; ...non of its attributes are in evaluation and... (or (node-bud-node? child) ; ...the child either is a bud node or,... (if kleene? (and ; ...in case a list node is expected,... (node-list-node? child) ; ...is a list... (for-all ; ...whose children are... (lambda (child) (or ; ...either bud nodes or nodes of the expected type, or,... (node-bud-node? child) (ast-rule-subtype? (node-ast-rule child) non-terminal?))) (node-children child))) (and ; ...in case a non-list node is expected,... (not (node-list-node? child)) ; ...is a non-list node of... (ast-rule-subtype? (node-ast-rule child) non-terminal?))))))))) ; ...the expected type. ; INTERNAL FUNCTION: Given list of nodes or terminal values and a list of contexts, return if the ; nodes/terminal values can become children of the given contexts. (define satisfies-contexts? (lambda (children contexts) (and (= (length children) (length contexts)) (for-all satisfies-context? children contexts)))) ; INTERNAL FUNCTION: Given an AST node update its synthesized attribution, i.e., add missing synthesized ; attributes, delete superfluous ones, shadow equally named inherited attributes and update the ; definitions of existing synthesized attributes. (define update-synthesized-attribution (lambda (n) (when (and (not (node-terminal? n)) (not (node-list-node? n)) (not (node-bud-node? n))) (for-each (lambda (att-def) (let ((att (node-find-attribute n (attribute-definition-name att-def)))) (cond ((not att) (node-attributes-set! n (cons (make-attribute-instance att-def n) (node-attributes n)))) ((eq? (attribute-definition-equation (attribute-instance-definition att)) (attribute-definition-equation att-def)) (attribute-instance-definition-set! att att-def)) (else (flush-attribute-instance att) (node-attributes-set! n (cons (make-attribute-instance att-def n) (remq att (node-attributes n)))))))) (symbol-attributes (car (ast-rule-production (node-ast-rule n))))) (node-attributes-set! ; Delete all synthesized attribute instances not defined anymore: n (remp (lambda (att) (let ((remove? (and (attribute-definition-synthesized? (attribute-instance-definition att)) (not (eq? (symbol-ast-rule (attribute-definition-context (attribute-instance-definition att))) (node-ast-rule n)))))) (when remove? (flush-attribute-instance att)) remove?)) (node-attributes n)))))) ; INTERNAL FUNCTION: Given an AST node update its inherited attribution, i.e., add missing inherited ; attributes, delete superfluous ones and update the definitions of existing inherited attributes. ; If the given node is a list-node the inherited attributes of its elements are updated. (define update-inherited-attribution (lambda (n) ;;; Support function updating n's inherited attribution w.r.t. a list of inherited attribute definitions: (define update-by-defs (lambda (n att-defs) (for-each ; Add new and update existing inherited attribute instances: (lambda (att-def) (let ((att (node-find-attribute n (attribute-definition-name att-def)))) (cond ((not att) (node-attributes-set! n (cons (make-attribute-instance att-def n) (node-attributes n)))) ((not (attribute-definition-synthesized? (attribute-instance-definition att))) (if (eq? (attribute-definition-equation (attribute-instance-definition att)) (attribute-definition-equation att-def)) (attribute-instance-definition-set! att att-def) (begin (flush-attribute-instance att) (node-attributes-set! n (cons (make-attribute-instance att-def n) (remq att (node-attributes n)))))))))) att-defs) (node-attributes-set! ; Delete all inherited attribute instances not defined anymore: n (remp (lambda (att) (let ((remove? (and (attribute-definition-inherited? (attribute-instance-definition att)) (not (memq (attribute-instance-definition att) att-defs))))) (when remove? (flush-attribute-instance att)) remove?)) (node-attributes n))))) ;;; Perform the update: (let* ((parent (node-parent n)) (att-defs (cond ((not parent) (list)) ((not (node-list-node? parent)) (symbol-attributes (list-ref (ast-rule-production (node-ast-rule parent)) (node-child-index? n)))) ((node-parent parent) (symbol-attributes (list-ref (ast-rule-production (node-ast-rule (node-parent parent))) (node-child-index? parent)))) (else (list))))) (if (node-list-node? n) (for-each (lambda (n) (unless (node-bud-node? n) (update-by-defs n att-defs))) (node-children n)) (unless (node-bud-node? n) (update-by-defs n att-defs)))))) ; INTERNAL FUNCTION: Given an AST node delete its inherited attribute instances. Iff the given node ; is a list node, the inherited attributes of its elements are deleted. (define detach-inherited-attributes (lambda (n) (cond ((node-list-node? n) (for-each detach-inherited-attributes (node-children n))) ((node-non-terminal? n) (node-attributes-set! n (remp (lambda (att) (let ((remove? (attribute-definition-inherited? (attribute-instance-definition att)))) (when remove? (flush-attribute-instance att)) remove?)) (node-attributes n))))))) ; INTERNAL FUNCTION: Given an evaluator state and an AST fragment, change the ; fragment's evaluator state to the given one. (define distribute-evaluator-state (lambda (evaluator-state n) (node-evaluator-state-set! n evaluator-state) (unless (node-terminal? n) (for-each (lambda (n) (distribute-evaluator-state evaluator-state n)) (node-children n))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Dependency Tracking ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; INTERNAL FUNCTION: See "add-dependency:cache->node-characteristic". (define add-dependency:cache->node-upwards (lambda (influencing-node) (add-dependency:cache->node-characteristic influencing-node (cons 0 'up)))) ; INTERNAL FUNCTION: See "add-dependency:cache->node-characteristic". (define add-dependency:cache->node-downwards (lambda (influencing-node) (add-dependency:cache->node-characteristic influencing-node (cons 0 'down)))) ; INTERNAL FUNCTION: See "add-dependency:cache->node-characteristic". (define add-dependency:cache->node-is-root (lambda (influencing-node) (add-dependency:cache->node-characteristic influencing-node (cons 1 racr-nil)))) ; INTERNAL FUNCTION: See "add-dependency:cache->node-characteristic". (define add-dependency:cache->node-num-children (lambda (influencing-node) (add-dependency:cache->node-characteristic influencing-node (cons 2 racr-nil)))) ; INTERNAL FUNCTION: See "add-dependency:cache->node-characteristic". (define add-dependency:cache->node-type (lambda (influencing-node) (add-dependency:cache->node-characteristic influencing-node (cons 3 racr-nil)))) ; INTERNAL FUNCTION: See "add-dependency:cache->node-characteristic". (define add-dependency:cache->node-super-type (lambda (influencing-node comparision-type) (add-dependency:cache->node-characteristic influencing-node (cons 4 comparision-type)))) ; INTERNAL FUNCTION: See "add-dependency:cache->node-characteristic". (define add-dependency:cache->node-sub-type (lambda (influencing-node comparision-type) (add-dependency:cache->node-characteristic influencing-node (cons 5 comparision-type)))) ; INTERNAL FUNCTION: See "add-dependency:cache->node-characteristic". (define add-dependency:cache->node-defines-context (lambda (influencing-node context-name) (add-dependency:cache->node-characteristic influencing-node (cons 6 context-name)))) ; INTERNAL FUNCTION: Given a node N and a correlation C add an dependency-edge marked with C from ; the attribute cache entry currently in evaluation (considering the evaluator state of the AST N ; is part of) to N and an influence-edge vice versa. If no attribute cache entry is in evaluation ; no edges are added. The following seven correlations exist: ; (0) Dependency on the existence of the node w.r.t. a query from a certain direction encoded in C (i.e., ; existence of a node at the same location queried from the same direction (upwards or downwards the AST)) ; (1) Dependency on the node being a root (i.e., the node has no parent) ; (2) Dependency on the node's number of children (i.e., existence of a node at the same location and with ; the same number of children) ; (3) Dependency on the node's type (i.e., existence of a node at the same location and with the same type) ; (4) Dependency on whether the node's type is a supertype w.r.t. a certain type encoded in C or not ; (5) Dependency on whether the node's type is a subtype w.r.t. a certain type encoded in C or not ; (6) Dependency on whether the node defines a certain context (i.e., has child with a certain name) or not (define add-dependency:cache->node-characteristic (lambda (influencing-node correlation) (let ((dependent-cache (evaluator-state-in-evaluation? (node-evaluator-state influencing-node)))) (when dependent-cache (let ((dependency-vector (let ((dc-hit (assq influencing-node (attribute-cache-entry-node-dependencies dependent-cache)))) (and dc-hit (cdr dc-hit))))) (unless dependency-vector (set! dependency-vector (vector #f #f #f #f (list) (list) (list))) (attribute-cache-entry-node-dependencies-set! dependent-cache (cons (cons influencing-node dependency-vector) (attribute-cache-entry-node-dependencies dependent-cache))) (node-cache-influences-set! influencing-node (cons (cons dependent-cache dependency-vector) (node-cache-influences influencing-node)))) (let ((correlation-type (car correlation)) (correlation-arg (cdr correlation))) (vector-set! dependency-vector correlation-type (case correlation-type ((0) (let ((known-direction (vector-ref dependency-vector correlation-type))) (cond ((not known-direction) correlation-arg) ((eq? known-direction correlation-arg) known-direction) (else 'up/down)))) ((1 2 3) #t) ((4 5 6) (let ((known-args (vector-ref dependency-vector correlation-type))) (if (memq correlation-arg known-args) known-args (cons correlation-arg known-args)))))))))))) ; INTERNAL FUNCTION: Given an attribute cache entry C, add an dependency-edge from C to the entry currently ; in evaluation (considering the evaluator state of the AST C is part of) and an influence-edge vice-versa. ; If no attribute cache entry is in evaluation no edges are added. (define add-dependency:cache->cache (lambda (influencing-cache) (let ((dependent-cache (evaluator-state-in-evaluation? (node-evaluator-state (attribute-instance-context (attribute-cache-entry-context influencing-cache)))))) (when (and dependent-cache (not (memq influencing-cache (attribute-cache-entry-cache-dependencies dependent-cache)))) (attribute-cache-entry-cache-dependencies-set! dependent-cache (cons influencing-cache (attribute-cache-entry-cache-dependencies dependent-cache))) (attribute-cache-entry-cache-influences-set! influencing-cache (cons dependent-cache (attribute-cache-entry-cache-influences influencing-cache))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Primitive Rewrites ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; INTERNAL FUNCTION: Given an attribute instance, flush all its cache entries. (define flush-attribute-instance (lambda (att) (call-with-values (lambda () (hashtable-entries (attribute-instance-cache att))) (lambda (keys values) (vector-for-each flush-attribute-cache-entry values))))) ; INTERNAL FUNCTION: Given an attribute cache entry, delete it and all depending entries. (define flush-attribute-cache-entry (lambda (att-cache) (let ((influenced-caches (attribute-cache-entry-cache-influences att-cache))) ; Save all influenced attribute cache entries. ; Delete foreign influences: (for-each ; For every cache entry I the entry depends on,... (lambda (influencing-cache) (attribute-cache-entry-cache-influences-set! ; ...remove the influence edge from I to the entry. influencing-cache (remq att-cache (attribute-cache-entry-cache-influences influencing-cache)))) (attribute-cache-entry-cache-dependencies att-cache)) (for-each ; For every node N the attribute cache entry depends on... (lambda (node-dependency) (node-cache-influences-set! (car node-dependency) (remp ; ...remove the influence edge from N to the entry. (lambda (cache-influence) (eq? (car cache-influence) att-cache)) (node-cache-influences (car node-dependency))))) (attribute-cache-entry-node-dependencies att-cache)) ; Delete the attribute cache entry: (hashtable-delete! (attribute-instance-cache (attribute-cache-entry-context att-cache)) (attribute-cache-entry-arguments att-cache)) (attribute-cache-entry-cache-dependencies-set! att-cache (list)) (attribute-cache-entry-node-dependencies-set! att-cache (list)) (attribute-cache-entry-cache-influences-set! att-cache (list)) ; Proceed flushing, i.e., for every attribute cache entry D the entry originally influenced,... (for-each (lambda (dependent-cache) (flush-attribute-cache-entry dependent-cache)) ; ...flush D. influenced-caches)))) ; INTERNAL FUNCTION: Given an AST node n, flush all attribute cache entries that depend on ; information of the subtree spaned by n but are outside of it and, if requested, all attribute ; cache entries within the subtree spaned by n that depend on information outside of it. (define flush-inter-fragment-dependent-attribute-cache-entries (lambda (n flush-outgoing?) (let loop ((n* n)) (for-each (lambda (influence) (unless (node-inside-of? (attribute-instance-context (attribute-cache-entry-context (car influence))) n) (flush-attribute-cache-entry (car influence)))) (node-cache-influences n*)) (for-each (lambda (att) (vector-for-each (lambda (att-cache) (let ((flush-att-cache? (and flush-outgoing? (or (find (lambda (dependency) (not (node-inside-of? (car dependency) n))) (attribute-cache-entry-node-dependencies att-cache)) (find (lambda (influencing-cache) (not (node-inside-of? (attribute-instance-context (attribute-cache-entry-context influencing-cache)) n))) (attribute-cache-entry-cache-dependencies att-cache)))))) (if flush-att-cache? (flush-attribute-cache-entry att-cache) (for-each (lambda (dependent-cache) (unless (node-inside-of? (attribute-instance-context (attribute-cache-entry-context dependent-cache)) n) (flush-attribute-cache-entry dependent-cache))) (attribute-cache-entry-cache-influences att-cache))))) (call-with-values (lambda () (hashtable-entries (attribute-instance-cache att))) (lambda (key-vector value-vector) value-vector)))) (node-attributes n*)) (unless (node-terminal? n*) (for-each loop (node-children n*)))))) (define rewrite-terminal (lambda (i n new-value) ;;; Before changing the value of the terminal ensure, that... (when (evaluator-state-in-evaluation? (node-evaluator-state n)) ; ...no attributes are in evaluation and... (throw-exception "Cannot change terminal value; " "There are attributes in evaluation.")) (let ((n (if (symbol? i) (node-find-child n i) (and (>= i 1) (<= i (length (node-children n))) (list-ref (node-children n) (- i 1)))))) (unless (and n (node-terminal? n)) ; ...the given context is a terminal. (throw-exception "Cannot change terminal value; " "The given context does not exist or is no terminal.")) ;;; Everything is fine. Thus,... (let ((old-value (node-children n))) (for-each ; ...flush all attribute cache entries influenced by the terminal,... (lambda (influence) (flush-attribute-cache-entry (car influence))) (node-cache-influences n)) (node-children-set! n new-value) ; ...rewrite its value and... old-value)))) ; ...return its old value. (define rewrite-refine (lambda (n t . c) ;;; Before refining the non-terminal node ensure, that... (when (evaluator-state-in-evaluation? (node-evaluator-state n)) ; ...non of its attributes are in evaluation,... (throw-exception "Cannot refine node; " "There are attributes in evaluation.")) (when (or (node-list-node? n) (node-bud-node? n)) ; ...it is not a list or bud node,... (throw-exception "Cannot refine node; " "The node is a " (if (node-list-node? n) "list" "bud") " node.")) (let* ((old-rule (node-ast-rule n)) (new-rule (racr-specification-find-rule (ast-rule-specification old-rule) t))) (unless (and new-rule (ast-rule-subtype? new-rule old-rule)) ; ...the given type is a subtype and... (throw-exception "Cannot refine node; " t " is not a subtype of " (symbol-name (car (ast-rule-production old-rule))) ".")) (let ((additional-children (list-tail (ast-rule-production new-rule) (length (ast-rule-production old-rule))))) (unless (satisfies-contexts? c additional-children) ; ...all additional children fit. (throw-exception "Cannot refine node; " "The given additional children do not fit.")) ;;; Everything is fine. Thus,... (for-each ; ...flush the influenced attribute cache entries, i.e., all entries influenced by the node's... (lambda (influence) (flush-attribute-cache-entry (car influence))) (filter (lambda (influence) (or (and (vector-ref (cdr influence) 2) (not (null? c))) ; ...number of children,... (and (vector-ref (cdr influence) 3) (not (eq? old-rule new-rule))) ; ...type,... (find ; ...supertype,... (lambda (t2) (not (eq? (ast-rule-subtype? t2 old-rule) (ast-rule-subtype? t2 new-rule)))) (vector-ref (cdr influence) 4)) (find ; ...subtype or... (lambda (t2) (not (eq? (ast-rule-subtype? old-rule t2) (ast-rule-subtype? new-rule t2)))) (vector-ref (cdr influence) 5)) (find ; ...defined contexts and... (lambda (context-name) (let ((old-defines-context? (ast-rule-find-child-context old-rule context-name)) (new-defines-context? (ast-rule-find-child-context new-rule context-name))) (if old-defines-context? (not new-defines-context?) new-defines-context?))) (vector-ref (cdr influence) 6)))) (node-cache-influences n))) (for-each ; ...all entries depending on the new children being roots. Afterwards,... (lambda (child context) (when (symbol-non-terminal? context) (for-each (lambda (influence) (flush-attribute-cache-entry (car influence))) (filter (lambda (influence) (vector-ref (cdr influence) 1)) (node-cache-influences child))))) c additional-children) (node-ast-rule-set! n new-rule) ; ...update the node's type,... (update-synthesized-attribution n) ; ...synthesized attribution,... (node-children-set! ; ...insert the new children and... n (append (node-children n) (map (lambda (child context) (let ((child (if (symbol-non-terminal? context) child (make-node 'terminal n child)))) (node-parent-set! child n) (distribute-evaluator-state (node-evaluator-state n) child) ; ...update their evaluator state and... child)) c additional-children))) (for-each update-inherited-attribution ; ...inherited attribution. (node-children n)))))) (define rewrite-abstract (lambda (n t) ;;; Before abstracting the node ensure, that... (when (evaluator-state-in-evaluation? (node-evaluator-state n)) ; ...no attributes are in evaluation,... (throw-exception "Cannot abstract node; " "There are attributes in evaluation.")) (when (or (node-list-node? n) (node-bud-node? n)) ; ...the node is not a list or bud node,... (throw-exception "Cannot abstract node; " "The node is a " (if (node-list-node? n) "list" "bud") " node.")) (let* ((old-rule (node-ast-rule n)) (new-rule (racr-specification-find-rule (ast-rule-specification old-rule) t))) (unless (and new-rule (ast-rule-subtype? old-rule new-rule)) ; ...the new type is a supertype and... (throw-exception "Cannot abstract node; " t " is not a supertype of " (symbol-name (car (ast-rule-production old-rule))) ".")) ; ...permitted in the context in which the node is: (unless (or (not (node-parent n)) (valid-replacement-candidate? n (create-ast-mockup new-rule))) (throw-exception "Cannot abstract node; " "Abstraction to type " t " not permitted by context.")) ;;; Everything is fine. Thus,... (let* ((num-new-children (length (cdr (ast-rule-production new-rule)))) (children-to-remove (list-tail (node-children n) num-new-children))) (for-each ; ...flush all influenced attribute cache entries, i.e., all entries influenced by the node's... (lambda (influence) (flush-attribute-cache-entry (car influence))) (filter (lambda (influence) (or (and (vector-ref (cdr influence) 2) (not (null? children-to-remove))) ; ...number of children,... (and (vector-ref (cdr influence) 3) (not (eq? old-rule new-rule))) ; ...type... (find ; ...supertype,... (lambda (t2) (not (eq? (ast-rule-subtype? t2 old-rule) (ast-rule-subtype? t2 new-rule)))) (vector-ref (cdr influence) 4)) (find ; ...subtype or... (lambda (t2) (not (eq? (ast-rule-subtype? old-rule t2) (ast-rule-subtype? new-rule t2)))) (vector-ref (cdr influence) 5)) (find ; ...defined contexts and... (lambda (context-name) (let ((old-defines-context? (ast-rule-find-child-context old-rule context-name)) (new-defines-context? (ast-rule-find-child-context new-rule context-name))) (if old-defines-context? (not new-defines-context?) new-defines-context?))) (vector-ref (cdr influence) 6)))) (node-cache-influences n))) (for-each ; ...all entries cross-depending the removed ASTs. Afterwards,... (lambda (child-to-remove) (flush-inter-fragment-dependent-attribute-cache-entries child-to-remove #t)) children-to-remove) (node-ast-rule-set! n new-rule) ; ...update the node's type and its... (update-synthesized-attribution n) ; ...synthesized (because of possibly less) and... (update-inherited-attribution n) ; ...inherited (because of unshadowed) attributes. Further,... (for-each ; ...for every child to remove,... (lambda (child) (detach-inherited-attributes child) ; ...delete its inherited attributes,... (node-parent-set! child #f) ; ...detach it from the AST and... (distribute-evaluator-state (make-evaluator-state) child)) ; ...update its evaluator state. Then,... children-to-remove) (unless (null? children-to-remove) (if (> num-new-children 0) (set-cdr! (list-tail (node-children n) (- num-new-children 1)) (list)) (node-children-set! n (list)))) (for-each ; ...update the inherited attribution of all remaining children. Finally,... update-inherited-attribution (node-children n)) (map ; ...return the removed children. (lambda (child) (if (node-terminal? child) (node-children child) child)) children-to-remove))))) (define rewrite-subtree (lambda (old-fragment new-fragment) ;;; Before replacing the subtree ensure, that no attributes of the old fragment are in evaluation and... (when (evaluator-state-in-evaluation? (node-evaluator-state old-fragment)) (throw-exception "Cannot replace subtree; " "There are attributes in evaluation.")) (unless (valid-replacement-candidate? old-fragment new-fragment) ; ...the new fragment fits in its context. (throw-exception "Cannot replace subtree; " "The replacement does not fit.")) ;;; When all rewrite constraints are satisfied,... (detach-inherited-attributes old-fragment) ; ...delete the old fragment's inherited attribution. Then,... ; ...flush all attribute cache entries cross-depending the old fragment and... (flush-inter-fragment-dependent-attribute-cache-entries old-fragment #t) (for-each ; ...all entries depending on the new fragment being a root. Afterwards,... (lambda (influence) (flush-attribute-cache-entry (car influence))) (filter (lambda (influence) (vector-ref (cdr influence) 1)) (node-cache-influences new-fragment))) (distribute-evaluator-state (node-evaluator-state old-fragment) new-fragment) ; ...update both fragments' evaluator state,... (distribute-evaluator-state (make-evaluator-state) old-fragment) (set-car! ; ...replace the old fragment by the new one and... (list-tail (node-children (node-parent old-fragment)) (- (node-child-index? old-fragment) 1)) new-fragment) (node-parent-set! new-fragment (node-parent old-fragment)) (node-parent-set! old-fragment #f) (update-inherited-attribution new-fragment) ; ...update the new fragment's inherited attribution. Finally,... old-fragment)) ; ...return the removed old fragment. (define rewrite-add (lambda (l e) ;;; Before adding the element ensure, that... (when (evaluator-state-in-evaluation? (node-evaluator-state l)) ; ...no attributes of the list are in evaluation,... (throw-exception "Cannot add list element; " "There are attributes in evaluation.")) (unless (node-list-node? l) ; ...indeed a list is given as context and... (throw-exception "Cannot add list element; " "The given context is no list-node.")) (unless (valid-list-element-candidate? l e) ; ...the new element fits. (throw-exception "Cannot add list element; " "The new element does not fit.")) ;;; When all rewrite constraints are satisfied,... (for-each ; ...flush all attribute cache entries influenced by the list-node's number of children and... (lambda (influence) (flush-attribute-cache-entry (car influence))) (filter (lambda (influence) (vector-ref (cdr influence) 2)) (node-cache-influences l))) (for-each ; ...all entries depending on the new element being a root. Afterwards,... (lambda (influence) (flush-attribute-cache-entry (car influence))) (filter (lambda (influence) (vector-ref (cdr influence) 1)) (node-cache-influences e))) (node-children-set! l (append (node-children l) (list e))) ; ...add the new element,... (node-parent-set! e l) (distribute-evaluator-state (node-evaluator-state l) e) ; ...initialize its evaluator state and... (when (node-parent l) (update-inherited-attribution e)))) ; ...any inherited attributes defined for its new context. (define rewrite-insert (lambda (l i e) ;;; Before inserting the new element ensure, that... (when (evaluator-state-in-evaluation? (node-evaluator-state l)) ; ...no attributes of the list are in evaluation,... (throw-exception "Cannot insert list element; " "There are attributes in evaluation.")) (unless (node-list-node? l) ; ...indeed a list is given as context,... (throw-exception "Cannot insert list element; " "The given context is no list-node.")) (when (or (< i 1) (> i (+ (length (node-children l)) 1))) ; ...the list has enough elements and... (throw-exception "Cannot insert list element; " "The given index is out of range.")) (unless (valid-list-element-candidate? l e) ; ...the new element fits. (throw-exception "Cannot add list element; " "The new element does not fit.")) ;;; When all rewrite constraints are satisfied... (for-each ; ...flush all attribute cache entries influenced by the list's number of children. Further,... (lambda (influence) (flush-attribute-cache-entry (car influence))) (filter (lambda (influence) (vector-ref (cdr influence) 2)) (node-cache-influences l))) (for-each ; ...for each successor element after insertion,... (lambda (successor) (for-each ; ...flush all attribute cache entries depending on the respective element... (lambda (influence) (define query-direction? (vector-ref (cdr influence) 0)) ; ...via a downwards query. Then,... (when (or (eq? query-direction? 'down) (eq? query-direction? 'up/down)) (flush-attribute-cache-entry (car influence)))) (node-cache-influences successor))) (list-tail (node-children l) (- i 1))) (for-each ; ...flush all attribute cache entries depending on the new element being a root. Afterwards,... (lambda (influence) (flush-attribute-cache-entry (car influence))) (filter (lambda (influence) (vector-ref (cdr influence) 1)) (node-cache-influences e))) (cond ; ...insert the new element,... ((null? (node-children l)) (node-children-set! l (list e))) ((= (length (node-children l)) (- i 1)) (node-children-set! l (append (node-children l) (list e)))) (else (let ((insert-head (list-tail (node-children l) (- i 1)))) (set-cdr! insert-head (cons (car insert-head) (cdr insert-head))) (set-car! insert-head e)))) (node-parent-set! e l) (distribute-evaluator-state (node-evaluator-state l) e) ; ...initialize its evaluator state and... (when (node-parent l) (update-inherited-attribution e)))) ; ...any inherited attributes defined for its new context. (define rewrite-delete (lambda (n) ;;; Before deleting the element ensure, that... (when (evaluator-state-in-evaluation? (node-evaluator-state n)) ; ...no attributes are in evaluation and... (throw-exception "Cannot delete list element; " "There are attributes in evaluation.")) (unless (and (node-parent n) (node-list-node? (node-parent n))) ; ...the given node is element of a list. (throw-exception "Cannot delete list element; " "The given node is not element of a list.")) ;;; When all rewrite constraints are satisfied,... (detach-inherited-attributes n) ; ...delete the element's inherited attributes and... (for-each ; ...flush all attribute cache entries influenced by... (lambda (influence) (flush-attribute-cache-entry (car influence))) (filter (lambda (influence) (or (vector-ref (cdr influence) 2) ; ...the number of children of the list node the element is part of or... (let ((query-direction? (vector-ref (cdr influence) 0))) ; ...that query the list node via... (and (or (eq? query-direction? 'up) (eq? query-direction? 'up/down)) ; ...an upwards query and... (node-inside-of? ; ...are within the element's subtree. Also flush,... (attribute-instance-context (attribute-cache-entry-context (car influence))) n))))) (node-cache-influences (node-parent n)))) (for-each ; ...for the element itself and each successor element,... (lambda (successor) (for-each ; ...all attribute cache entries depending on the respective element... (lambda (influence) (define query-direction? (vector-ref (cdr influence) 0)) ; ...via a downwards query. Finally,... (when (or (eq? query-direction? 'down) (eq? query-direction? 'up/down)) (flush-attribute-cache-entry (car influence)))) (node-cache-influences successor))) (list-tail (node-children (node-parent n)) (- (node-child-index? n) 1))) (node-children-set! (node-parent n) (remq n (node-children (node-parent n)))) ; ...remove the element from the list,... (node-parent-set! n #f) (distribute-evaluator-state (make-evaluator-state) n) ; ...reset its evaluator state and... n)) ; ...return it. (define perform-rewrites (lambda (n strategy . transformers) (define root (let loop ((n n)) (if (ast-has-parent? n) (loop (ast-parent n)) n))) (define root-deleted/inserted? (let ((evaluator-state (node-evaluator-state root))) (lambda () (not (eq? evaluator-state (node-evaluator-state root)))))) (define find-and-apply (case strategy ((top-down) (lambda (n) (and (not (node-terminal? n)) (or (find (lambda (transformer) (transformer n)) transformers) (find find-and-apply (node-children n)))))) ((bottom-up) (lambda (n) (and (not (node-terminal? n)) (or (find find-and-apply (node-children n)) (find (lambda (transformer) (transformer n)) transformers))))) (else (throw-exception "Cannot perform rewrites; " "Unknown " strategy " strategy.")))) (let loop () (when (root-deleted/inserted?) (throw-exception "Cannot perform rewrites; " "A given transformer manipulated the root of the AST.")) (let ((match (find-and-apply root))) (if match (cons match (loop)) (list)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Initialisation ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (when (= (specification->phase ast-language) 1) (load-ast-language)))
true
7b8501d6f8d55eee6bdbfde1cbc56a733797fc2d
98fd12cbf428dda4c673987ff64ace5e558874c4
/paip/will/faster-miniKanren/test-check.scm
54261811c27a255168c85c652a41951ba2671bc5
[ "MIT", "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
476
scm
test-check.scm
(define test-failed #f) (define-syntax test (syntax-rules () ((_ title tested-expression expected-result) (begin (printf "Testing ~s\n" title) (let* ((expected expected-result) (produced tested-expression)) (or (equal? expected produced) (begin (set! test-failed #t) (printf "Failed: ~a~%Expected: ~a~%Computed: ~a~%" 'tested-expression expected produced))))))))
true
e0399de7dce96619e46206bbb07fd2ed59539d9d
1985c8c2340f31bd6d1dedd6ebbb4fc12c75da1b
/assembler.scm
126f845d08e0ada5d15983ce4ec905e3ec411fcd
[ "MIT" ]
permissive
siraben/meta-II
b51559474d30d7345c2d90d6b23e7ee9090187e6
38e26e7b6928f2aaeacc12b4b74af99a89affe29
refs/heads/master
2020-04-20T20:10:46.621585
2019-02-08T06:35:43
2019-02-08T06:35:43
169,069,512
15
0
null
null
null
null
UTF-8
Scheme
false
false
10,507
scm
assembler.scm
;; Assemble meta-II output to our bytecode format. (include "parser.scm") (include "meta-II.scm") (use-modules (rnrs io ports)) ;; set! this to #t to see debugging information. Note that `lookup` ;; will complain a lot but generally it's fine. (define verbose? #f) (define 16-bit-regs '((af . #b11) (bc . #b00) (de . #b01) (hl . #b10) (sp . #b11))) (define (lookup key alist) (let ((match (assoc key alist))) (if match (cdr match) (begin ;; Verbose (if verbose? (format #t "Failed to lookup: ~a\n" key)) #f)))) (define-record-type <inst> (make-inst-rec length generator) inst? (length inst-length) (generator inst-generator)) (define-syntax make-inst (syntax-rules () ((_ length generator) (make-inst-rec length (delay generator))))) (define (gen-inst inst) (force (inst-generator inst))) (define (unsigned-nat? x) (and (integer? x) (>= x 0))) (define (8-bit-imm? x) (and (unsigned-nat? x) (> (ash 1 8) x))) (define label? symbol?) (define (16-bit-imm-or-label? x) (and (unsigned-nat? x) (> (ash 1 16) x))) (define (16-bit-imm? x) (and (unsigned-nat? x) (> (ash 1 16) x))) (define (num->binary n) (format #f "~8,'0b" n)) (define (num->hex n) (format #f "~2,'0x" n)) ;; Least significant byte. (define (lsb n) (logand n 255)) ;; Most significant byte. (define (msb n) (ash n -8)) (define (resolve-label label-or-imm16) (if (16-bit-imm? label-or-imm16) label-or-imm16 (or (lookup label-or-imm16 *labels*) (error (format #f "Label not found: ~a" label-or-imm16))))) (define (simple-op? op) (lookup op simple-ops)) ;; Operations that don't receive arguments or have specific ones. (define simple-ops '((ID #x1) (NUM #x2) (SR #x3) (R #x5) (SET #x6) (BE #xA) (CI #xC) (GN1 #xD) (GN2 #xE) (LB #xF) (OUT #x10) (END #x11) )) (define (assemble-simple a) (let ((res (lookup a simple-ops))) (if res (make-inst (length res) res) (error (format #f "Operation not found: ~a" a))))) (define (add-label! name val) (if (assv name *labels*) (error (format #f "Cannot add another label of ~a" name)) (begin (if verbose? (format #t "Adding label ~a with value 0x~4,'0x\n" name val)) (set! *labels* `((,name . ,val) . ,*labels*))))) (define (advance-pc! count) (set! *pc* (+ *pc* count))) (define (assemble-label name) (add-label! name *pc*) '()) (define (assemble-org new-pc) (set! *pc* new-pc) '()) (define (string->bytes s) `(,@(map char->integer (string->list s)) 0)) (define (assemble-test str) (make-inst (+ 2 (string-length str)) `(0 ,@(string->bytes str)))) (define (assemble-copy str) (make-inst (+ 2 (string-length str)) `(#xb ,@(string->bytes str)))) (define (assemble-call label) (make-inst 3 (let ((imm16 (resolve-label label))) `(4 ,(lsb imm16) ,(msb imm16))))) (define (assemble-branch label) (make-inst 3 (let ((imm16 (resolve-label label))) `(#x7 ,(lsb imm16) ,(msb imm16))))) (define (assemble-branch-true label) (make-inst 3 (let ((imm16 (resolve-label label))) `(#x8 ,(lsb imm16) ,(msb imm16))))) (define (assemble-branch-false label) (make-inst 3 (let ((imm16 (resolve-label label))) `(#x9 ,(lsb imm16) ,(msb imm16))))) (define (assemble-expr expr) ;; Pattern match EXPR against the valid instructions and dispatch to ;; the corresponding sub-assembler. (match expr (((? simple-op? a)) (assemble-simple a)) (`(LABEL ,a) (assemble-label a)) (`(TST ,a) (assemble-test a)) (`(CLL ,a) (assemble-call a)) (`(B ,a) (assemble-branch a)) (`(ADR ,a) (assemble-branch a)) (`(BT ,a) (assemble-branch-true a)) (`(BF ,a) (assemble-branch-false a)) (`(CL ,a) (assemble-copy a)) (_ (error (format #f "Unknown expression: ~s\n" expr)))) ) (define *pc* 0) (define *labels* 0) (define (reset-pc!) (set! *pc* 0)) (define (reset-labels!) (set! *labels* '())) (define (write-bytevector-to-file bv fn) (let ((port (open-output-file fn))) (put-bytevector port bv) (close-port port))) (define (flatten l) (if (null? l) '() (append (car l) (flatten (cdr l))))) (define (all-sat? p l) (cond ((null? l) #t) ((p (car l)) (all-sat? p (cdr l))) (else #f))) (define (pass1 exprs) ;; Check each instruction for correct syntax and produce code ;; generating thunks. Meanwhile, increment PC accordingly and build ;; up labels. (reset-labels!) (reset-pc!) (format #t "Pass one...\n") ;; Every assembled instruction, or inlined procedure should return a ;; value. A value of () indicates that it will not be included in ;; pass 2. (filter (lambda (x) (not (null? (car x)))) (map-in-order (lambda (expr) (if (procedure? expr) ;; Evaluate an inlined procedure (could do anything(!)). (let ((macro-val (expr))) ;; But that procedure has to return () or an instruction ;; record. (if (not (or (null? macro-val) (inst? macro-val))) (error (format #f "Error during pass one: macro did not return an instruction record: instead got ~a. PC: ~a\n" macro-val *pc*)) (begin (if (inst? macro-val) ;; This macro generated an instruction ;; record, so advance the program counter. (advance-pc! (inst-length macro-val))) ;; Return a "tagged" result, where the original ;; expression is preserved. (cons macro-val expr)))) ;; Assemble a normal instruction. (let ((res (assemble-expr expr))) (if (inst? res) (advance-pc! (inst-length res))) ;; Return a "tagged" result, where the original expression ;; is preserved, for debugging purposes. (cons res expr)))) exprs))) (define (pass2 insts) (reset-pc!) (format #t "Pass two...\n") ;; Force the code generating thunks. All labels should be resolved by now. (map-in-order (lambda (x) (if (not (inst? (car x))) (error (format #f "Error during pass two: not an instruction record: ~a. PC: ~a." (car x) (num->hex *pc*)))) (advance-pc! (inst-length (car x))) (let ((res (gen-inst (car x)))) (if verbose? (format #t "PC: ~a ~a\n" (num->hex *pc*) (cdr x))) (cond ;; Check consistency of declared instruction length and actual ;; length. ((not (= (inst-length (car x)) (length res))) (error (format #f "Instruction length declared does not match actual: Expected length ~a, got length ~a of expression ~a\n PC: ~a" (inst-length (car x)) (length res) res *pc*))) ;; Check that everything is an 8-bit unsigned number. ((not (all-sat? 8-bit-imm? res)) (error (format #f "Invalid byte at ~4'0x: ~a" *pc* res))) (else ;; We're ok. res)))) insts) ) (define (assemble-prog prog) (pass2 (pass1 prog))) (define (assemble-to-binary prog) (map num->binary (flatten (assemble-prog prog)))) (define (assemble-to-hex prog) (map num->hex (flatten (assemble-prog prog)))) (define (assemble-to-file prog filename) (write-bytevector-to-file (u8-list->bytevector (flatten (assemble-prog prog))) filename)) ;; Take n elements from a list. (define (take n list) (if (or (zero? n) (null? list)) '() (cons (car list) (take (1- n) (cdr list))))) ;; For debugging purposes. Assemble the program and find the ;; instruction that is at the specified byte address. (define (assemble-find-instr-byte byte prog context) (let ((partial-asm (pass1 prog))) (let loop ((pc 0) (rest-insts partial-asm)) (cond ((null? rest-insts) (error "Reached end of program before specified byte address.")) ((>= pc byte) (map cdr (take context rest-insts))) (else (loop (+ pc (inst-length (caar rest-insts))) (cdr rest-insts))))))) (define (one-of-strings strings) (if (null? strings) fail (+++ (str (car strings)) (one-of-strings (cdr strings))))) (define masm-label (doM* (x <- (many1 alpha-num)) (return `(LABEL ,x)))) (define masm-simple-command (doM* (x <- (one-of-strings '("ID" "NUM" "SR" "R" "SET" "BE" "CI" "GN1" "GN2" "LB" "OUT" "END"))) (return `(,(string->symbol x))))) (define masm-complex-command-label (doM* (command-name <- (one-of-strings '("CLL" "BT" "BF" "B" "ADR"))) (many (char #\space)) (label <- (many1 alpha-num)) (return `(,(string->symbol command-name) ,label)))) (define masm-complex-command-str (doM* (command-name <- (one-of-strings '("TST" "CL"))) (many (char #\space)) (string <- parse-string) (return `(,(string->symbol command-name) ,string)))) (define masm-complex-command (<:> masm-complex-command-label masm-complex-command-str)) (define masm-command ;; Accepts tabs or eight spaces. (doM* (<:> (char #\tab) (str " ")) (<:> masm-simple-command masm-complex-command))) (define masm (sepby-n (<:> masm-command masm-label) (char #\newline))) (define (parse-masm-file filename) (let ((msg (read-file-string filename))) (masm msg))) (define (compile-masm-to-bytecode masm-filename bytecode-filename) (let* ((parse-res (parse-masm-file masm-filename))) (if (string=? (cdr parse-res) "\n") (assemble-to-file (car parse-res) bytecode-filename) (format #t "Warning: File ~a has unconsumed input ~a" masm-filename (cdr parse-res))))) (define (compile-meta-II metaII-filename masm-filename bytecode-filename) (meta-II-to-masm metaII-filename masm-filename) (compile-masm-to-bytecode masm-filename bytecode-filename))
true
da8311ed0fd90c500c9f645a8b2daa84e6e88209
a2bc20ee91471c8116985e0eb6da1d19ab61f6b0
/exercise_4_1/mod.scm
3645e48eab68d3bee69cb0fe538f553ece5245f3
[]
no_license
cthulhu-irl/my-scheme-practices
6209d01aa1497971a5b970ab8aa976bb3481e9c9
98867870b0cb0306bdeb209d076bdc80e2e0e8cc
refs/heads/master
2022-09-22T15:19:48.798783
2020-06-06T14:16:07
2020-06-06T14:16:07
265,855,102
0
0
null
null
null
null
UTF-8
Scheme
false
false
58
scm
mod.scm
(define (inc arg) (+ arg 1)) (define (dec arg) (- arg 1))
false
4b03155652907c5cf758d38b1292f0763a3dc601
2163cd08beac073044187423727f84510a1dbc34
/chapter-2/sicp_ch2_e2-2.scm
c7eda9db6bddfa1bd765365be6ef72934c8a00e4
[]
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
2,268
scm
sicp_ch2_e2-2.scm
#!/usr/bin/csi -s ;; sicp_ch2_e2-2.scm ;; Mac Radigan (load "../library/util.scm") (import util) ;;; 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) (newline) (display "(") (display (x-point p)) (display ",") (display (y-point p)) (display ")") (newline) ) ;; point construct (define (make-point x y) (cons x y)) (define (x-point pt) (car pt)) (define (y-point pt) (cdr pt)) (define (equal-point? pt1 pt2) (and (= (x-point pt1) (x-point pt2)) (= (y-point pt1) (y-point pt2)) ) ) ;; segment construct (define (make-segment pt1 pt2) (cons pt1 pt2)) (define (start-segment seg) (car seg)) (define (end-segment seg) (cdr seg)) (define (midpoint-segment seg) (make-point (/ (+ (x-point (start-segment seg)) (x-point (end-segment seg)) ) 2) (/ (+ (y-point (start-segment seg)) (y-point (end-segment seg)) ) 2) ) ) ;; test constructs (define pt-00 (make-point 0 0)) ; (0, 0) origin (define pt-10 (make-point 1 0)) ; (1, 0) (define pt-01 (make-point 0 1)) ; (0, 1) (define s-x (make-segment pt-00 pt-10)) ; (0,0) -> (0,1) (define s-y (make-segment pt-00 pt-01)) ; (0,0) -> (1,0) (define s-xy (make-segment pt-10 pt-01)) ; (1,0) -> (1,0) (define pt-mid (midpoint-segment s-xy)) ; (0.5,0.5) (print-point pt-mid) (ck "midpoint" equal-point? pt-mid (make-point 0.5 0.5)) ; -1/4 * 2/4 = -1/8 ;; *EOF*
false
bf148e1f723871b7af5972508d2d0c58c7c0cdf9
ac2a3544b88444eabf12b68a9bce08941cd62581
/tests/unit-tests/02-flonum/flasinh.scm
ce1bb5c6cec15615e057cd43ec08d6f22667dd57
[ "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
320
scm
flasinh.scm
(include "#.scm") (check-= (flasinh 0.) (flasinh-144 0.)) (check-= (flasinh 0.5) (flasinh-144 0.5)) (check-= (flasinh -0.5) (flasinh-144 -0.5)) (check-tail-exn type-exception? (lambda () (flasinh 0))) (check-tail-exn type-exception? (lambda () (flasinh 1/2))) (check-tail-exn type-exception? (lambda () (flasinh 'a)))
false
0c662e1ebb17a33bd9f66c62aa56760f11ff69d1
120324bbbf63c54de0b7f1ca48d5dcbbc5cfb193
/packages/surfage/s42/timing.scm
1868be4d1f9a335d234d4fbf4c7358bd92372853
[ "MIT", "X11-distribute-modifications-variant" ]
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
2,816
scm
timing.scm
; <PLAINTEXT> ; Timing for Eager Comprehensions in [outer..inner|expr]-Convention ; ================================================================= ; ; [email protected], Eindhoven, The Netherlands, Feb-2003. ; Scheme R5RS (incl. macros), SRFI-23 (error). ; ; Running the examples in Scheme48 (version 0.57): ; ,open srfi-23 ; ,load ec.scm ; ,load timing.scm ; ; Running the examples in PLT/DrScheme (version 202): ; ; open "ec.scm", click Execute ; (load "timing.scm") ; ; Running the examples in SCM (version 5d7): ; ; invoke SCM with -v on the command line ; (require 'macro) (require 'record) ; (load "ec.scm") ; (load "timing.scm") ; ======================================================================= ; Basic loops ; ======================================================================= ; ; We measure execution times for (:range var n) and for (: var n), ; both as an outer loop (to measure iteration speed) or as an inner ; loop (to measure start up overhead). For comparison the same is ; measured for a hand-coded DO-loop. (define (perf0 n) ; reference for loop duration (do ((i 0 (+ i 1))) ((= i n)) i)) (define (perf1 n) (do-ec (:range i n) i)) (define (perf2 n) (do-ec (: i n) i)) (define (perf0s n) ; reference for startup delay (do-ec (:range i n) (do ((i 0 (+ i 1))) ((= i 1)) i))) (define (perf1s n) (do-ec (:range i n) (:range j 1) i)) (define (perf2s n) (do-ec (:range i n) (: j 1) i)) (define n-perf 10000000) ; Scheme48 0.57 on HP 9000/800 server running HP-UX ; ------------------------------------------------- ; ; ,time (perf0 n-perf) 19.3 ; built-in do ; ,time (perf1 n-perf) 17.0 ; faster than built-in do (?) ; ,time (perf2 n-perf) 40.4 ; due to calling the generator as procedure ; ; ,time (perf0s n-perf) 57.5 ; built-in do in the inner loop ; ,time (perf1s n-perf) 78.5 ; due to checking exact? integer? ; ,time (perf2s n-perf) 274.0 ; due to dispatch mechanism ; ; [All times are CPU time in seconds for n-perf iterations.] ; PLT 202 on Pentium III Mobile, 1 GHz, 1 GB RAM, Windows 2k ; ---------------------------------------------------------- ; ; (time (perf0 n-perf)) 11.1 ; (time (perf1 n-perf)) 7.8 ; (time (perf2 n-perf)) 18.1 ; ; (time (perf0s n-perf)) 35.2 ; (time (perf1s n-perf)) 42.9 ; (time (perf2s n-perf)) 147.8 ; ; [All times are CPU time in seconds for n-perf iterations.] ; SCM 5d7 on Pentium III Mobile, 1 GHz, 1 GB RAM, Windows 2k ; ---------------------------------------------------------- ; ; (perf0 n-perf) 29.1 ; (perf1 n-perf) 30.0 ; (perf2 n-perf) 45.5 ; ; (perf0s n-perf) 79.2 ; (perf1s n-perf) 448.6 ; (perf2s n-perf) 756.2 ; ; [All times are CPU time in seconds for n-perf iterations.]
false
3ad7a444c638451f0e7693f312a3eb07f528a3a7
98fd12cbf428dda4c673987ff64ace5e558874c4
/sicp/v1/chapter-1.3/inaimathi-1.3.4.scm
34ffa3ab26562da986f7964d807f268011a408bc
[ "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
2,654
scm
inaimathi-1.3.4.scm
;; STILL in Chicken ;;; Stuff we still need (define (square n) (* n n)) (define tolerance 0.00001) (define (fixed-point f first-guess) (define (close-enough? v1 v2) (< (abs (- v1 v2)) tolerance)) (define (try guess) (let ((next (f guess))) (if (close-enough? guess next) next (try next)))) (try first-guess)) (define dx 0.00001) (define (deriv g) (lambda (x) (/ (- (g (+ x dx)) (g x)) dx))) (define (newton-transform g) (lambda (x) (- x (/ (g x) ((deriv g) x))))) (define (newtons-method g guess) (fixed-point (newton-transform g) guess)) (define (sqrt x) (newtons-method (lambda (y) (- (square y) x)) 1.0)) ;;; 1.40 (define (cube n) (expt n 3)) (define (cubic a b c) (lambda (x) (+ (cube x) (* a (square x)) (* b x) c))) ;;; 1.41 (define (inc a) (+ a 1)) (define (double fn) (lambda (n) (fn (fn n)))) ;; It returns 21. ;;; 1.42 (define (compose f g) (lambda (n) (f (g n)))) ;;; 1.43 (define (repeated fn reps) (define (rec acc ct) (if (= ct reps) acc (rec (compose acc fn) (+ ct 1)))) (rec fn 1)) ;;; 1.44 ;; a) (define (smooth fn) (lambda (x) (/ (+ (fn (- x dx)) (fn x) (fn (+ x dx))) 3))) ;; b) (repeated fn times) ;;; 1.45 ;; first up, earlier functions (define (average x y) (/ (+ x y) 2)) (define (average-damp f) (lambda (x) (average x (f x)))) (define (sqrt x) (fixed-point (lambda (y) (average y (/ x y))) 1.0)) ;; As stated in the problem, naively: (define (nth-root x n) (fixed-point (lambda (y) (average y (/ x (expt y (- n 1))))) 1.0)) ;; That'll never terminate for roots where n>3 ;; Allegedly, this works well enough for 4th-roots (define (4th-root x) (fixed-point (lambda (y) (average y (average y (/ x (expt y 3))))) 1.0)) ;; (4th-root 16) returns 2.0000000000022 ;; TODO ;; (load "inaimathi-1.3.4.scm") ;;; 1.46 ;; a) (define (iterative-improve improve good-enough?) (define (rec guess) (let ((next (improve guess))) (if (good-enough? guess next) guess (rec next)))) rec) ;; b) (define (old-sqrt n) (fixed-point (lambda (y) (average y (/ n y))) 1.0)) (define (new-fixed-point fn first-guess) ((iterative-improve fn (lambda (g n) ;;; tolerance is a top-level binding here (ideally, it'd be an optional argument to new-sqrt) (< (abs (- v1 v2)) tolerance))) first-guess)) (define (new-sqrt n) ((iterative-improve (lambda (g) (average g (/ n g))) (lambda (g n) ;;; tolerance is a top-level binding here (ideally, it'd be an optional argument to new-sqrt) (< (abs (- v1 v2)) tolerance))) 1.0))
false
52c177809c57fad46be66bdca6ebf74ea72c8252
6e359a216e1e435de5d39bc64e75998945940a8c
/ex4.42.scm
6d98bdd94b47ffd02ca89bee8e66d761a3627db0
[]
no_license
GuoDangLang/SICP
03a774dd4470624165010f65c27acc35d844a93d
f81b7281fa779a9d8ef03997214e47397af1a016
refs/heads/master
2021-01-19T04:48:22.891605
2016-09-24T15:26:57
2016-09-24T15:26:57
69,106,376
0
0
null
null
null
null
UTF-8
Scheme
false
false
842
scm
ex4.42.scm
(define (require p) (if (not p) (amb))) (define (distinct? items) (cond ((null? items) true) ((null? (cdr items)) true) ((member (car items) (cdr items)) false) (else (distinct? (cdr items))))) (define (multiple-dwelling) (let ((a (amb 1 2 3 4 5)) (b (amb 1 2 3 4 5)) (c (amb 1 2 3 4 5)) (d (amb 1 2 3 4 5)) (e (amb 1 2 3 4 5))) (require (or (and (= d 2) (not (= a 3))) (and (not (= d 2)) (= a 3)))) (require (or (and (= b 1) (not (= c 2))) (and (not (= b 1)) (= c 2)))) (require (or (and (= c 3) (not (= b 5))) (and (not (= c 3)) (= b 5)))) (require (or (and (= d 2) (not (= e 4))) (and (not (= d 2)) (= e 4)))) (require (or (and (= e 4) (not (= a 1))) (and (not (= e 4)) (= a 1)))) (require (distinct? (list a b c d e))) (list (list 'a a) (list 'b b) (list 'c c) (list 'd d) (list 'e e))))
false
5e48ec9edae8f46bf29fb2ec366569fe86b78c68
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
/test/tests/text/yaml/parser.scm
92917113bf335a3548734137c0445695a8297379
[ "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
11,241
scm
parser.scm
(import (rnrs) (text yaml parser) (text yaml nodes) (srfi :127) (srfi :39) (srfi :64)) (test-begin "YAML parser") (define (test-yaml-parser expected input) (test-equal input expected (map yaml-document->canonical-sexp (parse-yaml (open-string-input-port input)))) (test-equal input expected (map yaml-document->canonical-sexp (map canonical-sexp->yaml-document (map yaml-document->canonical-sexp (parse-yaml (open-string-input-port input))))))) (test-yaml-parser '((*yaml* (*directives* (%YAML 1 1)) ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "foo") #("tag:yaml.org,2002:seq" ("tag:yaml.org,2002:str" . "bar") ("tag:yaml.org,2002:int" . "1234") ("tag:yaml.org,2002:null" . "~")))))) "%YAML 1.1\n\ ---\n\ foo:\n \ - bar\n \ - 1234\n \ - ~") (test-yaml-parser '((*yaml* #("tag:yaml.org,2002:seq" ("tag:yaml.org,2002:str" . "bar")))) " - bar") (test-yaml-parser '((*yaml* #("tag:yaml.org,2002:seq" ("tag:yaml.org,2002:str" . "foo")))) "[ foo ]") (test-yaml-parser '((*yaml* #("tag:yaml.org,2002:seq" ("tag:yaml.org,2002:str" . "foo") ("tag:yaml.org,2002:str" . "bar")))) "[ foo, bar ]") ;; extra comma (test-yaml-parser '((*yaml* #("tag:yaml.org,2002:seq" ("tag:yaml.org,2002:str" . "foo")))) "[ foo, ]") (test-yaml-parser '((*yaml* #("tag:yaml.org,2002:seq" ("tag:yaml.org,2002:str" . "foo") ("tag:yaml.org,2002:str" . "bar")))) "[ foo, bar, ]") ;; mapping (test-yaml-parser '((*yaml* ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "foo") ("tag:yaml.org,2002:str" . "bar"))))) "{ foo: bar }") (test-yaml-parser '((*yaml* ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "foo") ("tag:yaml.org,2002:str" . "bar")) (("tag:yaml.org,2002:str" . "buz") ("tag:yaml.org,2002:str" . "bla"))))) "{ foo: bar, buz: bla }") (test-yaml-parser '((*yaml* ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "foo") ("tag:yaml.org,2002:str" . "bar"))))) "{ foo: bar, }") (test-yaml-parser '((*yaml* ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "foo") ("tag:yaml.org,2002:str" . "bar")) (("tag:yaml.org,2002:str" . "buz") ("tag:yaml.org,2002:str" . "bla"))))) "{ foo: bar, buz: bla, }") (test-yaml-parser '((*yaml* ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "foo") ("tag:yaml.org,2002:null" . ""))))) "foo:") (test-yaml-parser '((*yaml* ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:null" . "") ("tag:yaml.org,2002:null" . ""))))) "?") (test-yaml-parser '((*yaml* ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "foo") ("tag:yaml.org,2002:str" . "bar"))))) "---\n\ !!map {\n \ ? !!str \"foo\"\n \ : !!str \"bar\",\n\ }") (test-yaml-parser '((*yaml* #("tag:yaml.org,2002:seq" ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "one") ("tag:yaml.org,2002:int" . "1"))) ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "two") ("tag:yaml.org,2002:int" . "2"))) ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "three") ("tag:yaml.org,2002:int" . "3")))))) "[ one: 1, two: 2, three : 3 ]") (test-yaml-parser '((*yaml* ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "one") ("tag:yaml.org,2002:null" . ""))))) "{ one: , }") (test-yaml-parser '((*yaml* ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "generic") ("tag:yaml.org,2002:binary" . "R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs="))))) "generic: !!binary | R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=") ;; corner cases ;; we support null scalar only on explicit document (differ from PyYAML) (test-yaml-parser '() "") (test-yaml-parser '((*yaml* ("tag:yaml.org,2002:null" . ""))) "---") ;; resolver tests ;; float (test-yaml-parser '((*yaml* #("tag:yaml.org,2002:seq" ("tag:yaml.org,2002:float" . "1.2") ("tag:yaml.org,2002:float" . "6.8523015e+5") ("tag:yaml.org,2002:float" . "685.230_15e+03") ("tag:yaml.org,2002:float" . "685_230.15") ("tag:yaml.org,2002:float" . "190:20:30.15") ("tag:yaml.org,2002:float" . "+.inf") ("tag:yaml.org,2002:str" . "+.InF") ("tag:yaml.org,2002:float" . ".nan") ("tag:yaml.org,2002:str" . ".Nan")))) "- 1.2\n\ - 6.8523015e+5\n\ - 685.230_15e+03\n\ - 685_230.15\n\ - 190:20:30.15\n\ - +.inf\n\ - +.InF # non fload\n\ - .nan\n\ - .Nan # non float") (test-yaml-parser '((*yaml* #("tag:yaml.org,2002:seq" ("tag:yaml.org,2002:bool" . "ON") ("tag:yaml.org,2002:bool" . "OFF") ("tag:yaml.org,2002:str" . "y") ("tag:yaml.org,2002:str" . "n") ("tag:yaml.org,2002:bool" . "Yes") ("tag:yaml.org,2002:bool" . "No") ("tag:yaml.org,2002:bool" . "True") ("tag:yaml.org,2002:bool" . "False") ("tag:yaml.org,2002:str" . "TrUe")))) "- ON\n\ - OFF\n\ - y\n\ - n\n\ - Yes\n\ - No\n\ - True\n\ - False\n\ - TrUe") (test-yaml-parser '((*yaml* #("tag:yaml.org,2002:seq" ("tag:yaml.org,2002:int" . "685230") ("tag:yaml.org,2002:int" . "+685_230") ("tag:yaml.org,2002:int" . "02472256") ("tag:yaml.org,2002:int" . "0x_0A_74_AE") ("tag:yaml.org,2002:int" . "0b1010_0111_0100_1010_1110") ("tag:yaml.org,2002:int" . "190:20:30")))) "- 685230\n\ - +685_230\n\ - 02472256\n\ - 0x_0A_74_AE\n\ - 0b1010_0111_0100_1010_1110\n\ - 190:20:30") (test-yaml-parser '((*yaml* ("tag:yaml.org,2002:merge" . "<<"))) "<<") (test-yaml-parser '((*yaml* #("tag:yaml.org,2002:seq" ("tag:yaml.org,2002:null" . "~") ("tag:yaml.org,2002:null" . "null") ("tag:yaml.org,2002:null" . "") ("tag:yaml.org,2002:null" . "Null") ("tag:yaml.org,2002:null" . "NULL") ("tag:yaml.org,2002:str" . "NuLL")))) "- ~\n\ - null\n\ - \n\ - Null\n\ - NULL\n\ - NuLL") (test-yaml-parser '((*yaml* #("tag:yaml.org,2002:seq" ("tag:yaml.org,2002:timestamp" . "2001-12-15T02:59:43.1Z") ("tag:yaml.org,2002:timestamp" . "2001-12-14t21:59:43.10-05:00") ("tag:yaml.org,2002:timestamp" . "2001-12-14 21:59:43.10 -5") ("tag:yaml.org,2002:timestamp" . "2001-12-15 2:59:43.10") ("tag:yaml.org,2002:timestamp" . "2002-12-14")))) "- 2001-12-15T02:59:43.1Z\n\ - 2001-12-14t21:59:43.10-05:00\n\ - 2001-12-14 21:59:43.10 -5\n\ - 2001-12-15 2:59:43.10\n\ - 2002-12-14") (test-yaml-parser '((*yaml* ("tag:yaml.org,2002:value" . "="))) "=") ;; omap etc. (test-yaml-parser '((*yaml* (*directives* (%YAML 1 2)) ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "foo") #("tag:yaml.org,2002:omap" ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "foo") ("tag:yaml.org,2002:str" . "bar"))) ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "boo") ("tag:yaml.org,2002:str" . "buz")))))))) "%YAML 1.2\n\ ---\n\ foo: !!omap\n\ - foo: bar\n\ - boo: buz") (test-yaml-parser '((*yaml* #("tag:yaml.org,2002:omap" ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "one") ("tag:yaml.org,2002:int" . "1"))) ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "two") ("tag:yaml.org,2002:int" . "2"))) ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "three") ("tag:yaml.org,2002:int" . "3")))))) "!!omap [ one: 1, two: 2, three : 3 ]") (test-yaml-parser '((*yaml* ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "Block tasks") #("tag:yaml.org,2002:pairs" ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "meeting") ("tag:yaml.org,2002:str" . "with team."))) ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "meeting") ("tag:yaml.org,2002:str" . "with boss."))) ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "break") ("tag:yaml.org,2002:str" . "lunch."))) ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "meeting") ("tag:yaml.org,2002:str" . "with client.")))))))) "Block tasks: !!pairs\n \ - meeting: with team.\n \ - meeting: with boss.\n \ - break: lunch.\n \ - meeting: with client.") (test-yaml-parser '((*yaml* #("tag:yaml.org,2002:pairs" ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "meeting") ("tag:yaml.org,2002:str" . "with team"))) ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "meeting") ("tag:yaml.org,2002:str" . "with boss")))))) "!!pairs [ meeting: with team, meeting: with boss ]") (test-yaml-parser '((*yaml* ("tag:yaml.org,2002:map" (("tag:yaml.org,2002:str" . "baseball players") ("tag:yaml.org,2002:set" (("tag:yaml.org,2002:str" . "Mark McGwire") ("tag:yaml.org,2002:null" . "")) (("tag:yaml.org,2002:str" . "Sammy Sosa") ("tag:yaml.org,2002:null" . "")) (("tag:yaml.org,2002:str" . "Ken Griffey") ("tag:yaml.org,2002:null" . ""))))))) "baseball players: !!set\n \ ? Mark McGwire\n \ ? Sammy Sosa\n \ ? Ken Griffey") (test-yaml-parser '((*yaml* ("tag:yaml.org,2002:set" (("tag:yaml.org,2002:str" . "Boston Red Sox") ("tag:yaml.org,2002:null" . "")) (("tag:yaml.org,2002:str" . "Detroit Tigers") ("tag:yaml.org,2002:null" . "")) (("tag:yaml.org,2002:str" . "New York Yankees") ("tag:yaml.org,2002:null" . ""))))) "!!set { Boston Red Sox, Detroit Tigers, New York Yankees }") ;; TODO test parser errors (test-end)
false
72309cc40a7d271913b312b97409efd338e95aac
2bcf33718a53f5a938fd82bd0d484a423ff308d3
/programming/sicp/ch2/ex-2.54.scm
794a9d06d4a83befb15638f713c00f889eee6f7d
[]
no_license
prurph/teach-yourself-cs
50e598a0c781d79ff294434db0430f7f2c12ff53
4ce98ebab5a905ea1808b8785949ecb52eee0736
refs/heads/main
2023-08-30T06:28:22.247659
2021-10-17T18:27:26
2021-10-17T18:27:26
345,412,092
0
0
null
null
null
null
UTF-8
Scheme
false
false
600
scm
ex-2.54.scm
#lang scheme ;; https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-16.html#%_thm_2.54 ;; Cheap xor that only accepts two arguments (define (xor a b) (if (not (and (boolean? a) (boolean? b))) (error "xor called with non-boolean argument") (not (eq? a b)))) ;; Could also implement with pair? and null? (define (my-equal? l1 l2) (cond ((xor (list? l1) (list? l2)) #f) ((and (list? l1) (empty? l1)) (empty? l2)) ((not (list? l1)) (eq? l1 l2)) (else (and (my-equal? (car l1) (car l2)) (my-equal? (cdr l1) (cdr l2))))))
false
c4ec33a141ab74a40359787a4424ce9c08532471
5355071004ad420028a218457c14cb8f7aa52fe4
/4.4/e-4.55.scm
3984b0ebc56d5f2503bd4de286835da6b273736a
[]
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
475
scm
e-4.55.scm
; Exercise 4.55. Give simple queries that retrieve the following ; information from the data base: ; a. all people supervised by Ben Bitdiddle; ; b. the names and jobs of all people in the accounting division; ; c. the names and addresses of all people who live in Slumerville. ; ------------------------------------------------------------- ; a) (supervisor (Ben Bitdiddle) ?name) ; ; b) (job ?name (accounting . ?skills)) ; ; c) (address ?name (Slumerville . ?address))
false
43c9edf85fe204211b1712c8b24e2091d03df684
defeada37d39bca09ef76f66f38683754c0a6aa0
/System.Xml/mono/xml/xsl/xsl-name-util.sls
7ef28d6af6c3b93abdd75adff78d9f766f3407c6
[]
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,407
sls
xsl-name-util.sls
(library (mono xml xsl xsl-name-util) (export new is? xsl-name-util? local-name-of from-list-string from-string) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new Mono.Xml.Xsl.XslNameUtil a ...))))) (define (is? a) (clr-is Mono.Xml.Xsl.XslNameUtil a)) (define (xsl-name-util? a) (clr-is Mono.Xml.Xsl.XslNameUtil a)) (define-method-port local-name-of Mono.Xml.Xsl.XslNameUtil LocalNameOf (static: System.String System.String)) (define-method-port from-list-string Mono.Xml.Xsl.XslNameUtil FromListString (static: System.Xml.XmlQualifiedName[] System.String System.Xml.XPath.XPathNavigator)) (define-method-port from-string Mono.Xml.Xsl.XslNameUtil FromString (static: System.Xml.XmlQualifiedName System.String System.Xml.XmlNamespaceManager) (static: System.Xml.XmlQualifiedName System.String System.Xml.Xsl.IStaticXsltContext) (static: System.Xml.XmlQualifiedName System.String System.Collections.Hashtable) (static: System.Xml.XmlQualifiedName System.String System.Xml.XPath.XPathNavigator System.Boolean) (static: System.Xml.XmlQualifiedName System.String System.Xml.XPath.XPathNavigator)))
true
7a7e91ddf9c0dbbad9d7d7133113b5905c9b62ca
d1b4ab0145e5d6e1b4c5d97cee0293a83cd7eace
/jrh-lisp/ox-pptx-template.scm
37a6b3679f7266380cb7f38a5fefce832ab3decd
[ "MIT" ]
permissive
jrhope/emacs.d
a9d43c30569843c334bc9c6bef8bc8d9ef4f0cc0
0ddfb1b3aaee2f4e85bb44836fea8405100d82a2
refs/heads/master
2021-01-13T09:38:09.109269
2020-10-27T01:52:11
2020-10-27T01:52:11
72,023,457
0
0
null
null
null
null
UTF-8
Scheme
false
false
30,644
scm
ox-pptx-template.scm
;; This file was auto-generated by ox-pptx. (import (only (srfi 1) list-tabulate)) (define pptx ::org.apache.poi.xslf.usermodel.XMLSlideShow (org.apache.poi.xslf.usermodel.XMLSlideShow (java.io.FileInputStream "%T"))) (define-syntax plain-text (syntax-rules () ((_ e) e))) (define (paragraph . rest) ::void #!void) ;;; Define constants. (define-constant *title* ::String %t) (define-constant *subtitle* ::String %s) (define-constant *date* ::java.util.Date (java.util.Date%d)) (define-constant *now* ::java.util.Date (java.util.Date)) (define-constant *disp-date* ::String ((java.text.SimpleDateFormat "dd MMMM yyyy"):format *date*)) (define-constant *author* ::String %a) (define-constant *table-style* (((->org.apache.poi.xslf.usermodel.XSLFTable ((->org.apache.poi.xslf.usermodel.XSLFSheet (pptx:slides 2)):shapes 2)):getCTTable):getTblPr)) (define-constant *text-shape-bottom-inset* (->org.apache.poi.xslf.usermodel.XSLFTextShape ((->org.apache.poi.xslf.usermodel.XSLFSheet (pptx:slides 2)):shapes 1)):bottom-inset) (define-constant *text-shape-left-inset* (->org.apache.poi.xslf.usermodel.XSLFTextShape ((->org.apache.poi.xslf.usermodel.XSLFSheet (pptx:slides 2)):shapes 1)):left-inset) (define-constant *text-shape-right-inset* (->org.apache.poi.xslf.usermodel.XSLFTextShape ((->org.apache.poi.xslf.usermodel.XSLFSheet (pptx:slides 2)):shapes 1)):right-inset) (define-constant *text-shape-top-inset* (->org.apache.poi.xslf.usermodel.XSLFTextShape ((->org.apache.poi.xslf.usermodel.XSLFSheet (pptx:slides 2)):shapes 1)):top-inset) (define-constant *text-paragraph-indents* (map *:.indent (->org.apache.poi.xslf.usermodel.XSLFTextShape ((->org.apache.poi.xslf.usermodel.XSLFSheet (pptx:slides 2)):shapes 1)):text-paragraphs)) (define-constant *text-paragraph-left-margins* (map *:.left-margin (->org.apache.poi.xslf.usermodel.XSLFTextShape ((->org.apache.poi.xslf.usermodel.XSLFSheet (pptx:slides 2)):shapes 1)):text-paragraphs)) (define-constant *text-paragraph-bullet-characters* (map *:.bullet-character (->org.apache.poi.xslf.usermodel.XSLFTextShape ((->org.apache.poi.xslf.usermodel.XSLFSheet (pptx:slides 2)):shapes 1)):text-paragraphs)) (define-constant *text-color* (->org.apache.poi.xslf.usermodel.XSLFTextRun ((->org.apache.poi.xslf.usermodel.XSLFTextParagraph ((->org.apache.poi.xslf.usermodel.XSLFTextShape ((->org.apache.poi.xslf.usermodel.XSLFSheet (pptx:slides 2)):shapes 1)):text-paragraphs 0)):text-runs 0)):font-color) (define-constant *page-size* (((->org.apache.poi.xslf.usermodel.XSLFSlideMaster (pptx:slide-masters 0)):get-layout org.apache.poi.xslf.usermodel.SlideLayout:TITLE_AND_CONTENT):get-placeholder 1):anchor) ;;; update-contents performs a search and replace for the title, name, ;;; and date strings within an array of shapes. (define (update-contents shapes ::java.util.List[org.apache.poi.xslf.usermodel.XSLFShape] #!optional (withsubtitle ::boolean #f)) (for-each (lambda (shape ::org.apache.poi.xslf.usermodel.XSLFShape) (cond ((? s::org.apache.poi.xslf.usermodel.XSLFTextShape shape) (for-each (lambda (paragraph ::org.apache.poi.xslf.usermodel.XSLFTextParagraph) (for-each (lambda (run ::org.apache.poi.xslf.usermodel.XSLFTextRun) (when (run:raw-text:contains "Presentation Title") (set! run:text (run:raw-text:replace-all "Presentation Title" (if withsubtitle (string-append *title* "\n\n" *subtitle*) *title*)))) (when (run:raw-text:contains "13 June 2016") (set! run:text (run:raw-text:replace-all "13 June 2016" *disp-date*))) (when (run:raw-text:contains "Presenter Name, Presenter Title") (set! run:text (run:raw-text:replace-all "Presenter Name, Presenter Title" *author*))) (when (run:raw-text:contains "Date of presentation") (set! run:text (run:raw-text:replace-all "Date of presentation" *disp-date*)))) paragraph:text-runs)) s:text-paragraphs)))) shapes)) ;;; Update Master (update-contents (->org.apache.poi.xslf.usermodel.XSLFSlideMaster (pptx:slide-masters 0)):shapes) ;;; Update Layouts (for-each (lambda (layout ::org.apache.poi.xslf.usermodel.XSLFSlideLayout) (update-contents layout:shapes)) (->org.apache.poi.xslf.usermodel.XSLFSlideMaster (pptx:slide-masters 0)):slide-layouts) ;;; Update Custom Title Page (update-contents (->org.apache.poi.xslf.usermodel.XSLFSheet (pptx:slides 0)):shapes (not (eq? #!null *subtitle*))) ;;; Remove other pages (let loop ((n ::int (- (pptx:slides:size) 1))) (when (> n 0) (pptx:removeSlide n) (loop (- n 1)))) ;;; Remove Image 7 and Image 8, which aren't needed (only referenced ;;; in the (just-removed) last slide. (let ((pkg pptx:package-part:package)) (for-each (lambda (part ::org.apache.poi.openxml4j.opc.PackagePart) (pkg:delete-part-recursive part:part-name)) (pkg:get-parts-by-name (java.util.regex.Pattern:compile "/ppt/media/image[78]\.png")))) ;;; Update core properties. (let ((props ::org.apache.poi.ooxml.POIXMLProperties$CoreProperties pptx:properties:core-properties)) (set! props:created (java.util.Optional:of *now*)) (set! props:creator *author*) (set! props:modified (->String #!null)) (set! props:revision "0") (set! props:title *title*) (if *subtitle* (set! props:subject-property *subtitle*)) (let ((under ::org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart props:underlying-properties)) (set! under:last-modified-by-property *author*))) ;;; Save file, then re-open it -- this flushes some obsolete ;;; relationships for the slides we just deleted. (let* ((pptxfile ::String (or (java.lang.System:get-property "pptxfile") "file.pptx")) (out ::java.io.FileOutputStream (java.io.FileOutputStream pptxfile))) (pptx:write out) (out:close) (set! pptx (org.apache.poi.xslf.usermodel.XMLSlideShow (java.io.FileInputStream pptxfile)))) ;;; Functions to create slides. (define-constant SECTION_HEADER org.apache.poi.xslf.usermodel.SlideLayout:SECTION_HEADER) (define-constant TITLE_AND_CONTENT org.apache.poi.xslf.usermodel.SlideLayout:TITLE_AND_CONTENT) (define-constant TITLE_ONLY org.apache.poi.xslf.usermodel.SlideLayout:TITLE_ONLY) (define (set-slide-title! (slide ::org.apache.poi.xslf.usermodel.XSLFSlide) title) (let ((s (slide:get-placeholder 0))) (s:clear-text) (let ((p (s:add-new-text-paragraph))) (for-each (lambda (t) (add-text p t #t)) title)))) (define (create-section-header-slide title #!optional subtitle) (let* ((layout ((->org.apache.poi.xslf.usermodel.XSLFSlideMaster (pptx:slide-masters 0)):get-layout SECTION_HEADER)) (slide (pptx:create-slide layout))) (set-slide-title! slide title) (if subtitle (set! (slide:get-placeholder 1):text (->String subtitle)) (slide:remove-shape (slide:get-placeholder 1))))) (define (add-text (p ::org.apache.poi.xslf.usermodel.XSLFTextParagraph) text #!optional bold italic) ::org.apache.poi.xslf.usermodel.XSLFTextRun (if (eq? text 'nil) (add-text p '(plain-text "") bold italic) (let ((tag (car text))) (case tag ((plain-text) (let* ((t (p:add-new-text-run))) (set! t:bold bold) (set! t:italic italic) (set! t:text (cadr text)) t)) ((entity) (let ((t (add-text p (caddr text) bold italic))) (when (> (cadr text) 0) (add-text p '(plain-text " ") bold italic)) t)) ((code verbatim) (let ((t (add-text p (caddr text) bold italic))) (set! t:font-family "Courier") (when (> (cadr text) 0) (add-text p '(plain-text " ") bold italic)) t)) ((bold) (let ((t ::org.apache.poi.xslf.usermodel.XSLFTextRun #!null)) (do ((texts (cddr text) (cdr texts))) ((null? texts)) (set! t (add-text p (car texts) #t italic))) (when (> (cadr text) 0) (add-text p '(plain-text " ") bold italic)) t)) ((italic) (let ((t ::org.apache.poi.xslf.usermodel.XSLFTextRun #!null)) (do ((texts (cddr text) (cdr texts))) ((null? texts)) (set! t (add-text p (car texts) bold #t))) (when (> (cadr text) 0) (add-text p '(plain-text " ") bold italic)) t)) ((link) (let* ((t (add-text p (cadddr text) bold italic)) (hl (t:create-hyperlink))) (hl:set-address (format #f "~a:~a" (cadr text) (caddr text))) t)) ((subscript) (let ((t ::org.apache.poi.xslf.usermodel.XSLFTextRun #!null)) (do ((texts (cddr text) (cdr texts))) ((null? texts)) (set! t (add-text p (car texts) bold italic)) (set! t:subscript #t)) (when (> (cadr text) 0) (add-text p '(plain-text " ") bold italic)) t)) ((superscript) (let ((t ::org.apache.poi.xslf.usermodel.XSLFTextRun #!null)) (do ((texts (cddr text) (cdr texts))) ((null? texts)) (set! t (add-text p (car texts) bold italic)) (set! t:superscript #t)) (when (> (cadr text) 0) (add-text p '(plain-text " ") bold italic)) t)) ((footnote-reference) (add-text p (cadr text) bold italic)) ((latex-environment latex-fragment) (add-text p (caddr text) bold italic)) ((line-break) (p:add-line-break)))))) (define (get-string text) ::String (let ((tag (car text))) (case tag ((plain-text) (cadr text)) ((entity) (get-string (caddr text))) ((code verbatim) (get-string (caddr text))) ((bold) (get-string (caddr text))) ((italic) (get-string (caddr text))) ((link) (get-string (cadddr text))) ((footnote-reference) (get-string (cadr text))) (else "")))) (define (insert-list (s ::org.apache.poi.xslf.usermodel.XSLFTextShape) lst #!optional (set-props? ::boolean #f)) (do ((lst lst (cdr lst))) ((null? lst)) (let ((tag (caar lst))) (case tag ((plain-list) (let ((ord (cadar lst)) (depth (caddar lst)) (data (cdddar lst))) (do ((data data (cdr data))) ((null? data)) (let ((checkbox (caddar data)) (paragraph (car (cdddar data))) (kids (cdr (cdddar data)))) (let ((p (s:add-new-text-paragraph))) (set! p:indent-level depth) (if (eq? ord 'ordered) (let ((num (cadar data))) (p:set-bullet-auto-number org.apache.poi.sl.usermodel.AutoNumberingScheme:arabicPeriod (->int num))) (set! p:bullet #t)) (when (and set-props? (< depth (length *text-paragraph-indents*))) (set! p:indent (*text-paragraph-indents* depth)) (set! p:left-margin (*text-paragraph-left-margins* depth)) (unless (eq? ord 'ordered) (set! p:bullet-character (*text-paragraph-bullet-characters* depth)))) (unless (eq? checkbox 'nil) (let* ((x (cdr (assq checkbox '((on . #\x2611) (off . #\x2610) (trans . #\x2610))))) (txt `(plain-text ,(format "~a " x))) (t (add-text p txt))) (when set-props? (set! t:font-color *text-color*)))) (do ((texts (cdr paragraph) (cdr texts))) ((null? texts)) (let ((t (add-text p (car texts)))) (when set-props? (set! t:font-color *text-color*)))) (when (not (null? kids)) (insert-list s kids set-props?))))))) (else (insert-list s `((plain-list unordered (item - nil (paragraph (plain-text ,(format #f "Cannot insert ~a here." tag)))))))))))) (define (create-list-slide title lst) (let* ((layout ((->org.apache.poi.xslf.usermodel.XSLFSlideMaster (pptx:slide-masters 0)):get-layout TITLE_AND_CONTENT)) (slide (pptx:create-slide layout))) (set-slide-title! slide title) (let ((s ::org.apache.poi.xslf.usermodel.XSLFTextShape (slide:get-placeholder 1))) (s:clear-text) (do ((lst lst (cdr lst))) ((null? lst)) (insert-list s lst)) (set! s:text-autofit org.apache.poi.sl.usermodel.TextShape$TextAutofit:NORMAL)))) (define (ext->imgtype ext::String) (cond ((string=? ext "png") org.apache.poi.sl.usermodel.PictureData$PictureType:PNG) ((string=? ext "svg") org.apache.poi.sl.usermodel.PictureData$PictureType:SVG) ((or (string=? ext "jpg") (string=? ext "jpeg")) org.apache.poi.sl.usermodel.PictureData$PictureType:JPEG) ((string=? ext "gif") org.apache.poi.sl.usermodel.PictureData$PictureType:GIF) ((string=? ext "tiff") org.apache.poi.sl.usermodel.PictureData$PictureType:TIFF) ((string=? ext "eps") org.apache.poi.sl.usermodel.PictureData$PictureType:EPS) ((string=? ext "bmp") org.apache.poi.sl.usermodel.PictureData$PictureType:BMP) ((string=? ext "emf") org.apache.poi.sl.usermodel.PictureData$PictureType:EMF) ((string=? ext "wmf") org.apache.poi.sl.usermodel.PictureData$PictureType:WMF) (else 0))) (define (insert-image (slide ::org.apache.poi.xslf.usermodel.XSLFSlide) (filename ::String)) (let* ((data ::bytevector (path-bytes filename)) (bytes ::byte[] data:buffer) (ext (path-extension filename)) (type (ext->imgtype ext)) (index (pptx:add-picture bytes type)) (p (slide:create-picture index)) (image-size index:image-dimension) (anchor p:anchor)) (when (string=? ext "svg") ;; every svg shows 200x200 as its size, because it's dumb. So ;; pull out the actual size from the XML. Yes, DOM is ;; inefficient. (let* ((xmlfile (java.io.File filename)) (factory (javax.xml.parsers.DocumentBuilderFactory:newInstance)) (builder (factory:newDocumentBuilder)) (doc (builder:parse xmlfile)) (elem doc:document-element)) (elem:normalize) (let ((widthstr ::String (elem:get-attribute "width")) (heightstr ::String (elem:get-attribute "height"))) (when (and (not (string=? widthstr "")) (not (string=? heightstr ""))) (set! widthstr (widthstr:replace-all "px" "")) (set! heightstr (heightstr:replace-all "px" "")) (let ((w (java.lang.Integer:parseInt widthstr)) (h (java.lang.Integer:parseInt heightstr))) (set! image-size (java.awt.Dimension w h))))))) (when (> image-size:width *page-size*:width) (image-size:set-size *page-size*:width (/ (* image-size:height *page-size*:width) image-size:width))) (when (> image-size:height *page-size*:height) (image-size:set-size (/ (* image-size:width *page-size*:height) image-size:height) *page-size*:height)) (anchor:set-rect (+ *page-size*:x (/ (- *page-size*:width image-size:width) 2)) (+ *page-size*:y (/ (- *page-size*:height image-size:height) 2)) image-size:width image-size:height) (set! p:anchor anchor))) (define (insert-paragraph (slide ::org.apache.poi.xslf.usermodel.XSLFSlide) lst s) (unless (null? lst) (if (equal? 'img (caar lst)) (insert-image slide (cadar lst)) (let* ((s ::org.apache.poi.xslf.usermodel.XSLFTextShape (or s (let ((s (slide:create-text-box))) (s:clear-text) (set! s:text-autofit org.apache.poi.sl.usermodel.TextShape$TextAutofit:NORMAL) s))) (p (s:add-new-text-paragraph))) (set! s:anchor *page-size*) (do ((texts lst (cdr texts))) ((null? texts)) (let ((t (add-text p (car texts)))) (set! t:font-color *text-color*))))))) (define (insert-center (slide ::org.apache.poi.xslf.usermodel.XSLFSlide) content) (let* ((s ::org.apache.poi.xslf.usermodel.XSLFTextShape (let ((s (slide:create-text-box))) (s:clear-text) (set! s:text-autofit org.apache.poi.sl.usermodel.TextShape$TextAutofit:NORMAL) s)) (p (s:add-new-text-paragraph))) (set! s:anchor *page-size*) (set! p:text-align org.apache.poi.sl.usermodel.TextParagraph$TextAlign:CENTER) (do ((texts (cdar content) (cdr texts))) ((null? texts)) (let ((t (add-text p (car texts)))) (set! t:font-color *text-color*))))) (define (optimize-table-columns (tbl ::org.apache.poi.xslf.usermodel.XSLFTable)) (let ((nr tbl:number-of-rows) (nc tbl:number-of-columns)) (do ((c ::int 0 (+ c 1))) ((= c (- nc 1))) (let ((w-orig (tbl:get-column-width c)) (w-orig+1 (tbl:get-column-width (+ c 1))) (h-orig tbl:anchor:height) (th-orig (apply min (list-tabulate nr (lambda (r) (tbl:get-cell r c):text-height))))) (let ((w w-orig) (w+1 w-orig+1) (th-best th-orig) (h-best h-orig)) (do ((try 8 (- try 1))) ((= try 0) (tbl:set-column-width c w) (tbl:set-column-width (+ c 1) w+1) (tbl:update-cell-anchor)) (let* ((this-w (* try 0.25 w-orig)) (this-w+1 (+ w-orig+1 w-orig (- this-w)))) (tbl:set-column-width c this-w) (tbl:set-column-width (+ c 1) this-w+1) (tbl:update-cell-anchor) (let ((th (apply min (list-tabulate nr (lambda (r) (tbl:get-cell r c):text-height))))) (when (and (<= th th-best) (<= tbl:anchor:height h-best)) (set! h-best tbl:anchor:height) (set! th-best th) (set! w this-w) (set! w+1 this-w+1)))))))))) (define (insert-table (slide ::org.apache.poi.xslf.usermodel.XSLFSlide) caption rows) (let ((s (slide:create-table))) (set! s:anchor *page-size*) ((s:getCTTable):setTblPr *table-style*) (do ((rows rows (cdr rows)) (i 0 (+ i 1))) ((null? rows)) (unless (equal? (car rows) '(row nil)) (let ((r (s:add-row))) (set! r:height 25) (do ((cells (cdar rows) (cdr cells))) ((null? cells)) (let* ((c (r:add-cell)) (p (c:add-new-text-paragraph))) (set! c:text-autofit org.apache.poi.sl.usermodel.TextShape$TextAutofit:SHAPE) (do ((texts (cdar cells) (cdr texts))) ((null? texts)) (add-text p (car texts) (= i 0))) (c:resize-to-fit-text) (c:set-border-color org.apache.poi.sl.usermodel.TableCell$BorderEdge:top java.awt.Color:white) (c:set-border-color org.apache.poi.sl.usermodel.TableCell$BorderEdge:bottom java.awt.Color:white) (c:set-border-color org.apache.poi.sl.usermodel.TableCell$BorderEdge:left java.awt.Color:white) (c:set-border-color org.apache.poi.sl.usermodel.TableCell$BorderEdge:right java.awt.Color:white)))))) (let ((nc ::int s:number-of-columns) (nr ::int s:number-of-rows) (a s:anchor)) (let loop ((w ::double 0) (i ::int 0)) (if (< i nc) ;; calculate the full width (loop (+ w (s:get-column-width i)) (+ i 1)) (let loop2 ((h ::double 0) (i ::int 0)) (if (< i nr) ;; calculate the full height (loop2 (+ h (s:get-row-height i)) (+ i 1)) (begin ;; scale all columns to full page width (do ((i ::int 0 (+ i 1))) ((= i nc)) (s:set-column-width i (* (s:get-column-width i) (/ *page-size*:width w)))) (set! w *page-size*:width) (a:set-rect (+ *page-size*:x (/ (- *page-size*:width w) 2)) *page-size*:y w h) (set! s:anchor a) (s:update-cell-anchor) ;; adjust relative column widths to reduce height ;; needed given a fixed font size (optimize-table-columns s) (when (not (equal? '((plain-text "")) caption)) (let* ((cap (let ((s (slide:create-text-box))) (s:clear-text) (set! s:text-autofit org.apache.poi.sl.usermodel.TextShape$TextAutofit:NORMAL) s)) (p (cap:add-new-text-paragraph)) (a2 cap:anchor)) (for-each (lambda (t) (let ((r (add-text p t))) (set! r:font-size (* r:font-size 0.8d0)))) caption) (set! p:text-align org.apache.poi.sl.usermodel.TextParagraph$TextAlign:CENTER) (a2:set-rect (+ *page-size*:x (/ (- *page-size*:width w) 2)) h w 12) (set! cap:anchor a2))))))))))) (define (insert-block (slide ::org.apache.poi.xslf.usermodel.XSLFSlide) block) (let* ((s (let ((s (slide:create-text-box))) (s:clear-text) (set! s:text-autofit org.apache.poi.sl.usermodel.TextShape$TextAutofit:NORMAL) s)) (p (s:add-new-text-paragraph)) (t (p:add-new-text-run))) (set! s:anchor *page-size*) (set! t:font-family "Courier") (set! t:text (cadr block)))) (define (insert-data (slide ::org.apache.poi.xslf.usermodel.XSLFSlide) contents) (let ((last-text-shape ::org.apache.poi.xslf.usermodel.XSLFTextShape #!null)) (do ((contents contents (cdr contents))) ((null? contents)) (let* ((datum (car contents)) (tag (car datum))) (case tag ((paragraph) (insert-paragraph slide (cdr datum) last-text-shape)) ((plain-list) (let* ((s (or last-text-shape (let ((s (slide:create-text-box))) (s:clear-text) (set! s:text-autofit org.apache.poi.sl.usermodel.TextShape$TextAutofit:NORMAL) s)))) (set! s:anchor *page-size*) (set! s:bottom-inset *text-shape-bottom-inset*) (set! s:left-inset *text-shape-left-inset*) (set! s:right-inset *text-shape-right-inset*) (set! s:top-inset *text-shape-top-inset*) (insert-list s (list datum) #t) (set! s:text-autofit org.apache.poi.sl.usermodel.TextShape$TextAutofit:NORMAL))) ((table) (insert-table slide (cadr datum) (cddr datum))) ((example-block src-block fixed-width) (insert-block slide datum)) ((center) (insert-center slide (cdr datum))) ((latex-environment latex-fragment) (insert-image slide (cadr datum)))) (let* ((ss slide:shapes) (ln (ss:size))) (if (and (> ln 0) (not (memq tag '(center table src-block example-block fixed-width))) (org.apache.poi.xslf.usermodel.XSLFTextShape? (ss (- ln 1)))) (set! last-text-shape (ss (- ln 1))) (set! last-text-shape #!null))))))) (define (create-title-only-slide title content) (let* ((layout ((->org.apache.poi.xslf.usermodel.XSLFSlideMaster (pptx:slide-masters 0)):get-layout TITLE_ONLY)) (slide (pptx:create-slide layout))) (set-slide-title! slide title) (insert-data slide content) (do ((i ::int 1 (+ i 1))) ((= i (slide:shapes:size))) (when (? s::org.apache.poi.xslf.usermodel.XSLFTextShape (slide:shapes i)) (s:resize-to-fit-text))) (let repeat ((repeat-count 0)) (let loop ((i ::int 1) (n ::int (slide:shapes:size)) (h ::double 0)) (if (= i n) (let ((d (/ (- *page-size*:height h -20) 2))) (if (< d -0.5) (let ((scale (/ *page-size*:height (- h 20))) (y *page-size*:y)) (do ((i 1 (+ i 1))) ((= i n)) (let* ((s (->org.apache.poi.xslf.usermodel.XSLFShape (slide:shapes i))) (a s:anchor)) (cond ((? ts::org.apache.poi.xslf.usermodel.XSLFTextShape s) (set! ts:text-autofit org.apache.poi.sl.usermodel.TextShape$TextAutofit:NORMAL) (a:set-rect a:x y a:width (* scale a:height)) (set! ts:anchor a) (set! y (+ y ts:anchor:height))) ((? ps::org.apache.poi.xslf.usermodel.XSLFPictureShape s) (let ((scale (- 1 (* 0.25 (- 1 scale))))) (if (> (* scale a:height) (/ *page-size*:height 2)) (a:set-rect (+ a:x (/ (* (- 1 scale) a:width) 2)) y (* scale a:width) (* scale a:height)) (a:set-rect a:x y a:width a:height))) (set! ps:anchor a) (set! y (+ y a:height))) ((? tbl::org.apache.poi.xslf.usermodel.XSLFTable s) (do ((r 0 (+ r 1))) ((= r tbl:number-of-rows)) (do ((c 0 (+ c 1))) ((= c tbl:number-of-columns)) (let ((cell (tbl:get-cell r c))) (for-each (lambda (paragraph ::org.apache.poi.xslf.usermodel.XSLFTextParagraph) (for-each (lambda (run ::org.apache.poi.xslf.usermodel.XSLFTextRun) (run:set-font-size (java.lang.Math:max 1.0d0 (* run:font-size scale)))) paragraph:text-runs)) cell:text-paragraphs)))) (tbl:update-cell-anchor) (optimize-table-columns tbl) (set! y (+ y tbl:anchor:height))) (else (a:set-rect a:x y a:width (* scale a:height)) (set! s:anchor a) (set! y (+ y a:height)))))) (when (< repeat-count 10) (repeat (+ repeat-count 1)))) (do ((i 1 (+ i 1))) ((= i n)) (let* ((s (->org.apache.poi.xslf.usermodel.XSLFShape (slide:shapes i))) (a s:anchor)) (a:set-rect a:x (+ *page-size*:y a:y d) a:width a:height) (set! s:anchor a))))) (let ((a (slide:shapes i):anchor)) (a:set-rect a:x h a:width a:height) (set! (slide:shapes i):anchor a) (loop (+ i 1) n (+ h 20 a:height)))))))) (define (create-slide title content) ((if (and (= 1 (length content)) (eq? 'plain-list (caar content))) create-list-slide create-title-only-slide) title content)) ;;; File contents start here. %c ;;; File contents end here. (let* ((pptxfile ::String (or (java.lang.System:get-property "pptxfile") "file.pptx")) (out ::java.io.FileOutputStream (java.io.FileOutputStream pptxfile))) (format #t "creating ~a...~%%" pptxfile) (pptx:write out) (out:close) (format #t "Done.~%%"))
true
ea27bce8400b459c8d68a30238a8108923ebdc7b
203ad0bd8ae7276ddb4c12041b1644538957c386
/subst/trie.scm
af82afe906609a74603454cad673a946900975c8
[]
no_license
lkuper/relational-research
b432a6a9b76723a603406998dcbe9f0aceace97c
7ab9955b08d2791fe63a08708415ae3f100f6df5
refs/heads/master
2021-01-25T10:07:27.074811
2010-05-15T04:13:07
2010-05-15T04:13:07
2,870,499
1
0
null
null
null
null
UTF-8
Scheme
false
false
3,206
scm
trie.scm
(module trie (t:bind t:unbind t:lookup t:binding-value t:size) ;(import (rnrs) (rnrs records syntactic) (ikarus)) (import scheme) ;;; subst ::= (empty) ;;; | (node even odd) ;;; | (data idx val) ;(define-record-type node (fields e o)) (define-record node (e o)) ;(define-record-type data (fields idx val)) ;(define-record data (idx val)) (define data? pair?) (define data-idx car) (define data-val cdr) (define-syntax make-data (syntax-rules () [(_ i-exp v-exp) (cons i-exp v-exp)])) (define shift (lambda (n) (fxsra n 1))) (define unshift (lambda (n i) (fx+ (fxsll n 1) i))) (define t:size (lambda (x) (size x))) (define t:bind (lambda (xi v s) ;(unless (and (fixnum? xi) (>= xi 0)) ;(error 't:bind "index must be a fixnum, got ~s" xi)) (bind xi v s))) (define t:unbind (lambda (xi s) ;(unless (and (fixnum? xi) (>= xi 0)) ;(error 't:unbind "index must be a fixnum, got ~s" xi)) (unbind xi s))) (define t:lookup (lambda (xi s) ;(unless (and (fixnum? xi) (>= xi 0)) ;(error 't:lookup "index must be a fixnum, got ~s" xi)) (lookup xi s))) (define t:binding-value (lambda (s) ;(unless (data? s) ;(error 't:binding-value "not a binding ~s" s)) (data-val s))) (define push (lambda (xi vi xj vj) (if (fxeven? xi) (if (fxeven? xj) (make-node (push (shift xi) vi (shift xj) vj) '()) (make-node (make-data (shift xi) vi) (make-data (shift xj) vj))) (if (fxeven? xj) (make-node (make-data (shift xj) vj) (make-data (shift xi) vi)) (make-node '() (push (shift xi) vi (shift xj) vj)))))) (define bind (lambda (xi vi s*) (cond [(node? s*) (if (fxeven? xi) (make-node (bind (shift xi) vi (node-e s*)) (node-o s*)) (make-node (node-e s*) (bind (shift xi) vi (node-o s*))))] [(data? s*) (let ([xj (data-idx s*)] [vj (data-val s*)]) (if (fx= xi xj) (make-data xi vi) (push xi vi xj vj)))] [else (make-data xi vi)]))) (define lookup (lambda (xi s*) (cond [(node? s*) (if (fxeven? xi) (lookup (shift xi) (node-e s*)) (lookup (shift xi) (node-o s*)))] [(data? s*) (if (fx= (data-idx s*) xi) s* #f)] [else #f]))) (define size (lambda (s*) (cond [(node? s*) (fx+ (size (node-e s*)) (size (node-o s*)))] [(data? s*) 1] [else 0]))) (define cons^ (lambda (e o) (cond [(or (node? e) (node? o)) (make-node e o)] [(data? e) (make-data (unshift (data-idx e) 0) (data-val e))] [(data? o) (make-data (unshift (data-idx o) 1) (data-val o))] [else '()]))) (define unbind (lambda (xi s*) (cond [(node? s*) (if (fxeven? xi) (cons^ (unbind (shift xi) (node-e s*)) (node-o s*)) (cons^ (node-e s*) (unbind (shift xi) (node-o s*))))] [(and (data? s*) (fx= (data-idx s*) xi)) '()] [else s*]))) )
true
67aa8092414b290e56ca4115fd44165645119aa2
542b1510c22ad5c41ba2f896f674c275c34e9195
/srfi/160/at.sld
8e4794ea5d114c5c0cefb32d01b940828700c24e
[ "MIT" ]
permissive
diamond-lizard/srfi-160
c88b955a7c5e6a5656876a4b9fea452a282b3d24
69b2abad0da573ee22acebb0dc4eefebea72fae1
refs/heads/main
2023-03-03T22:32:31.181967
2020-11-20T06:00:43
2020-11-20T06:00:43
311,722,584
0
1
MIT
2021-01-28T15:50:57
2020-11-10T16:41:12
Scheme
UTF-8
Scheme
false
false
1,593
sld
at.sld
(define-library (srfi 160 @) (import (scheme base)) (import (scheme case-lambda)) (import (scheme cxr)) (import (only (scheme r5rs) inexact->exact)) (import (scheme complex)) (import (scheme write)) (import (srfi 128)) (import (srfi 160 base)) ;; Constructors (export make-@vector @vector @vector-unfold @vector-unfold-right @vector-copy @vector-reverse-copy @vector-append @vector-concatenate @vector-append-subvectors) ;; Predicates (export @? @vector? @vector-empty? @vector=) ;; Selectors (export @vector-ref @vector-length) ;; Iteration (export @vector-take @vector-take-right @vector-drop @vector-drop-right @vector-segment @vector-fold @vector-fold-right @vector-map @vector-map! @vector-for-each @vector-count @vector-cumulate) ;; Searching (export @vector-take-while @vector-take-while-right @vector-drop-while @vector-drop-while-right @vector-index @vector-index-right @vector-skip @vector-skip-right @vector-any @vector-every @vector-partition @vector-filter @vector-remove) ;; Mutators (export @vector-set! @vector-swap! @vector-fill! @vector-reverse! @vector-copy! @vector-reverse-copy! @vector-unfold! @vector-unfold-right!) ;; Conversion (export @vector->list list->@vector reverse-@vector->list reverse-list->@vector @vector->vector vector->@vector) ;; Misc (export make-@vector-generator @vector-comparator write-@vector) (include "@-impl.scm") )
false
7ae4f64e0debc062cdb48337bd0c098f02474ffc
710bd922d612840b3dc64bd7c64d4eefe62d50f0
/scheme/tool-schake/package.scm
f32887651d4e43841bef97cea2e797f370529c5f
[ "MIT" ]
permissive
prefics/scheme
66c74b93852f2dfafd4a95e04cf5ec6b06057e16
ae615dffa7646c75eaa644258225913e567ff4fb
refs/heads/master
2023-08-23T07:27:02.254472
2023-08-12T06:47:59
2023-08-12T06:47:59
149,110,586
0
0
null
null
null
null
UTF-8
Scheme
false
false
788
scm
package.scm
;;; package.scm -- package definition for the schake tool (define-structure tool-schake (export <target> make-target target? target-name target-doc target-dependents target-script target-needs-update? target-modification-time run-target-script update-target-directly targets target-names targets-clear! the-target with-target target-ref target-add target-delete ->target target-run target-exists? target-update (deftarget :syntax) $always $never <target-file> make-file-target file-target-file-name (deftarget-file :syntax) (def-c-application :syntax) (def-structure-target :syntax) include load-schakefile load-schakefile-from ) (open scheme-runtime scheme-posix scheme-environment) (doc "Schake tool") (files schake.scm))
false
b52bf7b2ec364e5dc2623e99aaaa1cf23ef7934e
ab2b756cdeb5aa94b8586eeb8dd5948b7f0bba27
/src/lisp/binary_convert.scm
fe20f47661cb5f200c5e07d0d4b486a9d3c8a10d
[]
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
272
scm
binary_convert.scm
(import (basics.scm)) (define (binary_convert2 L N) (cond (((= L nil) N) (true (binary_convert2 (cdr L) (+ (car L) (* 2 N))))))) (macro binary_convert (L) (binary_convert2 L 0)) (= 20 (binary_convert (tree (1 0 1 0 0))))
false
b22fca6e0d6987a62e9dde7dad5606a12d34ab3a
aeba5709adda459de7fc29269dc265f262864db7
/floron.scm
4b78a7de3fd8ef4c5ac8f77459901f2aafed6e11
[]
no_license
wuschel/floron
19bc9929e27e3cfe58c5b413bf4d20b0bc7664c0
52b7453eff70d651cf3d19c06f1cd85e2e8524a9
refs/heads/master
2021-01-12T15:15:11.818914
2016-09-16T14:58:33
2016-09-16T14:58:47
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,632
scm
floron.scm
(import (scheme base) (scheme read) (scheme write) (scheme file) (scheme cxr) (steen markdown) (chibi filesystem) (chibi time) (chibi sxml)) ;; Generic helpers (define-syntax λ (syntax-rules () ((_ args body) (lambda args body)))) (define (read-file f) (with-input-from-file f read)) (define (write-to-file file proc) (call-with-output-file file (λ (f) (display proc f)))) (define (atom? x) (not (or (pair? x) (null? x) (vector? x)))) (define key car) (define value cadr) (define (fetch k table) (cond ((null? table); '()) (error (string-append "Key not found: " (symbol->string k)))) ((eq? (key (car table)) k) (value (car table))) (else (fetch k (cdr table))))) (define (replace old new ls) (cond ((null? ls) '()) ((atom? ls) (if (eq? old ls) new ls)) ((list? ls) (cons (replace old new (car ls)) (replace old new (cdr ls)))))) (define (multireplace table ls) (if (null? table) ls (multireplace (cdr table) (let ((entry (car table))) (replace (key entry) (value entry) ls))))) ;; Post helpers (define-record-type <post> (make-post-info title date id body) post? (title post-title) (date post-date) (id post-id) (body post-body)) (define (padded num) (let ((str (number->string num))) (if (= 1 (string-length str)) (string-append "0" str) str))) (define (seconds->ymd seconds) (let ((time-t (seconds->time seconds))) (string-append (number->string (+ 2000 (- (time-year time-t) 100))) "/" ; wtf, chibi (padded (time-month time-t)) "/" (padded (time-day time-t))))) (define (make-post post) (let ((title (fetch 'title post)) (date (seconds->ymd (fetch 'date post))) (id (fetch 'id post))) (make-post-info title date id (call-with-input-file (string-append (post-dir config) "/" id "/post.md") markdown->sxml)))) ;; Blog helpers (define-record-type <blog> (make-blog-info title author) blog? (title blog-title) (author blog-author)) (define (make-blog config) (let ((title (fetch 'title config)) (author (fetch 'author config))) (make-blog-info title author))) ;; Configuration (define-record-type <config> (make-config blog posts post-dir out-dir) config? (blog config-blog) (posts config-posts) (post-dir post-dir) (out-dir out-dir)) (define (load-config) (let ((cfg (read-file "config.scm"))) (let ((config (fetch 'config cfg)) (posts (fetch 'posts cfg))) (make-config (make-blog config) posts (fetch 'post-dir config) (fetch 'out-dir config))))) ;; Interesting stuff (define (render page bindings) (multireplace bindings (read-file page))) (define (page-title page root) (string-append page " | " root)) (define (make-link file) (string-append "/" file)) (define (render-post post) (render "templates/post.scm" `((post-body ,(post-body post)) (post-date ,(post-date post)) (post-title ,(post-title post))))) (define (render-post-page blog post) (render "templates/layout.scm" `((page-title ,(page-title (post-title post) (blog-title blog))) (blog-title ,(blog-title blog)) (blog-author ,(blog-author blog)) (blog-content ,(render-post post))))) (define (render-index-item post) (render "templates/index.scm" `((post-title ,(fetch 'title post)) (post-date ,(seconds->ymd (fetch 'date post))) (post-desc ,(fetch 'description post)) (post-link ,(make-link (fetch 'id post)))))) (define (render-index blog posts) (render "templates/layout.scm" `((page-title ,(page-title "Index" (blog-title blog))) (blog-title ,(blog-title blog)) (blog-author ,(blog-author blog)) (blog-content ,(map render-index-item posts))))) ;; Start (define config (load-config)) (define (render-blog) (let ((posts (map make-post (config-posts config))) (out (out-dir config))) (create-directory out 493) (write-to-file (string-append out "/index.html") (sxml->xml (render-index (config-blog config) (config-posts config)))) (for-each (λ (post) (let ((path (string-append out "/" (post-id post))) (page (render-post-page (config-blog config) post))) (create-directory path 493) (write-to-file (string-append path "/index.html") (sxml->xml page)))) posts))) (render-blog)
true
41dc110c2d8647c5adfb0375ef955a31642f49e9
58381f6c0b3def1720ca7a14a7c6f0f350f89537
/Chapter 2/2.2/Ex2.43.scm
7f4d8e6a18356bf216a3c5bd463f54266298a32e
[]
no_license
yaowenqiang/SICPBook
ef559bcd07301b40d92d8ad698d60923b868f992
c8a0228ebf66d9c1ddc5ef1fcc1d05d8684f090a
refs/heads/master
2020-04-19T04:03:15.888492
2015-11-02T15:35:46
2015-11-02T15:35:46
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
422
scm
Ex2.43.scm
#lang planet neil/sicp (flatmap (lambda (new-row) (map (lambda (rest-of-queens) (adjoin-position new-row k rest-of-queens)) (queen-cols (- k 1)))) (enumerate-interval 1 board-size)) ;; With this approach, the queen positions are calculated for every row in ;; the columns and this will be slow. The original calculated it for every ;; column once. ;; It is exponential in terms of T
false
6c98c1c1b0d943c0f6711f38cdab8e68cc30f90c
ae0d7be8827e8983c926f48a5304c897dc32bbdc
/Gauche-tir/trunk/lib/tir04/tmp/20070619/as.scm
b9727885ebed0f6ea74ec698d6f542364154e36d
[ "MIT" ]
permissive
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
EUC-JP
Scheme
false
false
31,693
scm
as.scm
;;; coding: euc-jp ;;; -*- scheme -*- ;;; vim:set ft=scheme ts=8 sts=2 sw=2 et: ;;; $Id$ ;;; account scheduler ;;; 概要: ;;; カレンダー付き手帳アプリ。 ;;; TODO: どこから修正/作成するか考える。 ;;; - データ操作部分を独立プロセス化する? ;;; -- とりあえず、ライブラリ分割ぐらいはすべき。 ;;; --- モジュール名は? ;;; ---- 仮に、as.storageとする ;;; -- プロトコルはSETP ;;; - 問題点は、ファイルの送受信の効率が悪い事 ;;; -- サーバをまたがないという前提で良いなら、 ;;; ファイルパスのみを転送する事でもokだし、 ;;; ファイルで送受信したいものは大きなサイズのアーカイヴや画像/映像/音声 ;;; などの事が多い為、それら本体をジャーナリングログに残す意味は薄く、 ;;; それなら転送せずに反映する方法でもよいと思われる ;;; TODO: url構成を変更する。 ;;; - /yyyy/mm/dd ではなく、 ;;; /groupname/yyyy/mm/dd とする。 ;;; groupnameに旧仕様のregionを入れ、そこの ;;; .metadataファイルに、グループ設定を入れる。 ;;; - 各アカウントは最初、一つだけのグループに属し、 ;;; プライベートな情報はそこに書き込むという仕様にする。 ;;; TODO: 識別情報登録時に、 ;;; 最初に登録したアカウントを、 ;;; 強制的に、root(""だか'()だか#fだか)の所有者とするように ;;; する事。 ;;; そして、上位ディレクトリ/グループの所有者は、 ;;; 下位ディレクトリ/グループへの権限を持つ、という仕様とする。 ;;; これによって、権限を管理できるようにする。 ;;; TODO: MIME typeを決める。 ;;; - Content-Type: application/as; data-type=moge ;;; -- application/as以外の場合は、そのまま出力する。 ;;; TODO: ;;; - http://as.tir.jp/one に設置する。 ;;; - プラグインシステムを実装する事。 ;;; - ジャーナリングログが必要。 ;;; -- これはsyslog転送のような、汎用の仕組みにすべきか? ;;; - データ暗号化があるのが好ましいが、必須ではない ;;; - PATH_INFOではなく、dnsのAAAAレコードを使うか? ;;; -- wikiならそれでもいいが、今回はカレンダー機能が軸になる為、 ;;; 逆順になるのが好ましくないので、PATH_INFO使用とする。 ;;; TODO: これは、httpd化した方がいいかも知れない ;;; (しかし、httpd化には時間がかかる為、そうするにしても、 ;;; まず、一通り動作するものが完成してからにする事!) ;;; urlについて: ;;; - PATH_INFOをwikinameとして使う。 ;;; - wikiname自体は基本的に\w系文字のみとする。 ;;; -- %nnエンコードが必要になる名前は不可。 ;;; -- 内部情報構成の都合上、.も不可。 ;;; -- 間違わないように、小文字のみでの構成とする。大文字不可。 ;;; -- アンダーバーはok。 ;;; - 区切り文字は/。 ;;; -- rootのみが、PATH_INFOの末尾を/で終える事が可能とする。 ;;; -- root以外は、PATH_INFOの末尾を/で終えないようにする。 ;;; --- とは言え、内部的には、path-info-keylistを使っているので、 ;;; どちらなのかは区別できないが。 ;;; ただ、このシステムからPATH_INFO付きurlを出す際には、 ;;; root以外は末尾を/で終えないようにする、という約束とする。 ;;; note: ;;; - 内部形式はwikiに近い状態とする。 ;;; -- データは、PATH_INFOの通りのディレクトリを作り、 ;;; そのディレクトリ内に.contentというファイルを作り、 ;;; その中にrfc822形式でメタデータ込みで保存する。 ;;; (つまり、追記okかつヘッダにメタデータを持たせる事を可能にする) ;;; TODO: 一通り完成したら、再利用可能なように、各部分をモジュールに分解する。 ;;; - content-treeを操作/レンダリングする部分 ;;; -- rfc822型ファイル操作ユーティリティ ;;; - 各種プラグインシステム ;;; - アカウントマネージャ ;;; - その他 ;;; TODO: データのメモリキャッシュの実装 ;;; TODO: 同一アカウントに別々の接続元から同時にログインできない仕組みを ;;; 実装する必要がある (define-module tir04.tmp.20070619.as (use gauche.parameter) (use rfc.822) (use file.util) (use util.list) (use dbm) (use text.html-lite) (use text.tree) (use www.cgi) (use tir04.cgi.util) (use tir04.cgi.ident) (use tir04.cgi.session.ident) (use tir04.dbm.util) (use srfi-19) (use gauche.sequence) (use srfi-1) ;(use wc-frame) (use tir04.util.calendar) (use tir04.tmp.20070619.as.storage) (export <cgi-as> cgi-as-execute )) (select-module tir04.tmp.20070619.as) (define-class <cgi-as> () ( ;; TODO: 情報定義スロットがとりあえず必要 ;; (とりあえず、秘密にすべき設定値はスロットで持たせる事) (information-keywords :accessor information-keywords-of :init-keyword :information-keywords :init-value '()) (setting-keywords :accessor setting-keywords-of :init-keyword :setting-keywords :init-value '()) (cgi-ident :accessor cgi-ident-of :init-keyword :cgi-ident :init-value #f) ;; private slot (csa :accessor csa-of :init-value #f) )) (define-method informations-of ((self <cgi-as>) keyword . opt-fallback) (apply get-keyword keyword (information-keywords-of self) opt-fallback)) (define-method settings-of ((self <cgi-as>) keyword . opt-fallback) (apply get-keyword keyword (setting-keywords-of self) opt-fallback)) (define-method initialize ((self <cgi-as>) initargs) (next-method) (unless (file-exists? (settings-of self :storage-dir)) (make-directory* (settings-of self :storage-dir))) (set! (csa-of self) (make <cgi-session-ident> :dbm-type (settings-of self :dbm-type) :dbm-path (string-append (settings-of self :storage-dir) "/" "csa") :expire-second (* 1 24 60 60) :cgi-ident (cgi-ident-of self))) #t) ;;; ---- (define (make-response:not-logined self params) (make-page self (list (html:h1 (het (informations-of self :title))) (html:ul (html:li (html:login/logout self 'login "ログイン"))) ))) (define (html:login/logout self type label) (make-cgi-session-ident-form (csa-of self) '() type (html:input :type "submit" :value label))) (define (path-info-keylist->date path-info-keylist) (define (str-is-number-only? str) (and str (not (#/\D/ str)))) (define (path-info-keylist->year+month+day+rest) ;; まず、最初の要素をチェック (let1 year? (car path-info-keylist) (if (not (and (str-is-number-only? year?) (= 4 (string-size year?)))) (values #f #f #f path-info-keylist) (let1 month? (and (not (null? (cdr path-info-keylist))) (cadr path-info-keylist)) (if (not (and (str-is-number-only? month?) (= 2 (string-size month?)))) (values (x->integer year?) 1 1 (cdr path-info-keylist)) (let1 day? (and (not (null? (cddr path-info-keylist))) (caddr path-info-keylist)) (if (not (and (str-is-number-only? day?) (= 2 (string-size day?)))) (values (x->integer year?) (x->integer month?) 1 (cddr path-info-keylist)) (values (x->integer year?) (x->integer month?) (x->integer day?) (cdddr path-info-keylist))))))))) (cond ((not path-info-keylist) (current-date)) ((null? path-info-keylist) (current-date)) (else ;; まず、path-info-keylistから、年月日である可能性のある要素を取り出す (receive (year month day rest) (path-info-keylist->year+month+day+rest) (values (if (not year) (current-date) (make-date 0 0 0 0 day month year (date-zone-offset (current-date)))) rest))))) (define (with-dbm self dbm-name rw-mode proc) (with-dbm-open (settings-of self :dbm-type) :path (string-append (settings-of self :storage-dir) "/" (x->string dbm-name)) :rw-mode rw-mode :key-convert #t :value-convert #t proc)) (define (get-user-info self ident-info) ;; dbmからuser-infoを読む (guard (e (else #f)) ; TODO: エラー処理 (with-dbm self "user-info" :read (lambda (dbm) (dbm-get dbm (get-keyword :uid ident-info) #f))))) (define (set-user-info! self ident-info user-info) (guard (e (else #f)) ; TODO: エラー処理 (with-dbm self "user-info" :write (lambda (dbm) (dbm-put! dbm (get-keyword :uid ident-info) user-info))))) (define (make-response:logined:user-info self params ident-info path-info-keylist user-info) (let1 cc (cgi-get-parameter "cc" params) ;; まずディスパッチする (cond ((equal? "confirm" cc) (make-response:logined:user-info:confirm self params ident-info user-info)) ((equal? "submit" cc) (make-response:logined:user-info:submit self params ident-info user-info)) ((equal? "done" cc) (make-response:logined:user-info:done self params ident-info user-info)) (else ; or "edit" (make-response:logined:user-info:edit self params ident-info user-info))))) (define (make-response:logined:user-info:confirm self params ident-info user-info) ;; TODO: 入力内容のチェックが必要 (let ((name (cgi-get-parameter "name" params))) (make-page self (make-form (self-path/path-info) `( ("c" "ui") ("cc" "submit") ("name" ,name) ) (list (html:p "以下の内容で設定を行います。") (html:div "名前: " (html:tt (het name))) (html:input :type "submit" :value "本当に設定する") ))))) (define (make-response:logined:user-info:submit self params ident-info user-info) ;; TODO: 入力内容のチェックが必要 (let ((name (cgi-get-parameter "name" params))) (set-user-info! self ident-info `(:name ,name)) (location (append-params-to-url (self-path/path-info) '(("c" "ui") ("cc" "done")))))) (define (make-response:logined:user-info:done self params ident-info user-info) (make-page self (list (html:p "設定が完了しました。") (html:ul (html:li (html:a :href (self-path/path-info) "戻る")))))) (define (make-response:logined:user-info:edit self params ident-info user-info) ;; 設定項目の編集画面を出す ;; TODO: まず、設定可能項目を決める必要がある。 ;; - 名前 ;; - 他には??? (define (read-from-user-info keyword . opt-fallback) (if (not user-info) (car opt-fallback) (apply get-keyword keyword user-info opt-fallback))) (make-page self (make-form (self-path/path-info) '( ("c" "ui") ("cc" "confirm") ) (list (if (not user-info) (html:p "識別情報が設定されていません。設定を行ってください。") (html:p "識別情報を編集できます。")) (html:div "名前: " (html:input :type "text" :name "name" :value (read-from-user-info :name ""))) (html:input :type "submit" :value "設定する") (html:p "(今のところ、名前しか設定できません。" "設定項目は今後、増える予定です)") (if (not user-info) '() (list (html:hr) (html:ul (html:li (html:a :href (self-path/path-info) "(戻る)"))))))))) (define (do-redirect self src-path params) ;; まず、pathを検証する。 ;; /始まりで、以降は\wまたは/のみを含む文字列とする。 ;; 但し、pathが空なら、/が指定されたものとして扱う。 (let1 path (if (string=? "" src-path) "/" src-path) (or (and-let* ((m (#/^\/[\/\w]*$/ path))) (location (append-params-to-url (string-append (self-path) path) (remove (lambda (x) (equal? (car x) "redirect_path")) params)))) (make-page self (list (html:h1 "error") (html:div "不正なpathが指定されました")))))) (define (make-response:logined self params path-info-keylist ident-info session-parameter) ;; まず、ユーザ情報を取り出す ;; ユーザ情報が存在しない場合は、強制的に設定画面へと遷移させる (let1 user-info (get-user-info self ident-info) (if (not user-info) (make-response:logined:user-info self params ident-info (current-date) user-info) ;; CGI引数の解釈を行う (let ( (redirect-path (cgi-get-parameter "redirect_path" params)) (c (cgi-get-parameter "c" params)) ) (if redirect-path (do-redirect self redirect-path params) (cond ((equal? "ui" c) (make-response:logined:user-info self params ident-info path-info-keylist user-info)) ((equal? "edit" c) (make-response:logined:edit self params ident-info path-info-keylist user-info)) ((equal? "submit" c) (make-response:logined:submit self params ident-info path-info-keylist user-info)) (else ;; fallback or "display" (make-response:logined:display self params ident-info path-info-keylist user-info)))))))) (define (make-month m y) (make-date 0 0 0 0 1 m y (date-zone-offset (current-date)))) (define (date->prev-month date) (if (= (date-month date) 1) (make-month 12 (- (date-year date) 1)) (make-month (- (date-month date) 1) (date-year date)))) (define (date->next-month date) (if (= (date-month date) 12) (make-month 1 (+ (date-year date) 1)) (make-month (+ (date-month date) 1) (date-year date)))) (define (url-chop url) ;; urlの末尾の要素を落とした文字列を返す。 (let1 m (#/\/[^\/]*\/?$/ url) (if m (m 'before) url))) (define (calendar-html path-info-keylist edit-mode?) (let1 date (path-info-keylist->date path-info-keylist) ;; TODO: 各日付にリンクをつける ;; 先月/来月も含める ;; 先月/来月へのリンクもつける(nnk互換) ;; 以下のようなフォーマットとする。 ;; ← 2007/07 → ;; 日 月 火 水 木 金 土 ;; 01 02 03 04 05 06 07 ;; 08 09 10 11 12 13 14 ;; 15 16 17 18 19 20 21 ;; 22 23 24 25 26 27 28 ;; 29 30 31 01 02 03 04 ;; TODO: input text形式の入力ボックスもつけるべき? ;; 今はつけない。つけるとしても後で。 (define (date->url-month date) (format "~a/~4,'0d/~2,'0d" (self-path) (date-year date) (date-month date))) (define (date->url-day date) (format "~a/~4,'0d/~2,'0d/~2,'0d" (self-path) (date-year date) (date-month date) (date-day date))) (define (url-filter url) (if edit-mode? (append-params-to-url url '(("c" "edit"))) url)) (let ( (prev-month (date->prev-month date)) (next-month (date->next-month date)) ) (html:table :summary "calendar" (html:thead (html:tr (html:th :colspan "1" '()) (html:th :colspan "1" (if (null? path-info-keylist) "↑" (html:a :href (url-filter (let1 new-url (url-chop (self-path/path-info)) (if (< (string-length (self-path)) (string-length new-url)) new-url (self-path/slash)))) "↑"))) (html:th :colspan "3" (html:a :href (url-filter (date->url-day (current-date))) "今")) (html:th :colspan "1" (if (null? path-info-keylist) "√" (html:a :href (url-filter (self-path/slash)) "√"))) (html:th :colspan "1" '()) ) (html:tr (html:th (html:a :href (url-filter (date->url-month prev-month)) "←")) (html:th :colspan "5" (html:a :href (url-filter (date->url-month date)) (het (date->string date "~Y/~m")))) (html:th (html:a :href (url-filter (date->url-month next-month)) "→")) ) (html:tr (map (lambda (x) (html:th (het x))) '("日" "月" "火" "水" "木" "金" "土")))) (html:tbody (map (lambda (row) (html:tr (map (lambda (col) (html:td col)) row))) (datetime->calendar-list (date->datetime date) (lambda (datetime target-day? current-month?) (let1 str (format "~2,'0d" (date-day (datetime->date datetime))) (define (filter-current-month str) (if current-month? str (html:span :style "font-size:0.5em" str))) (let1 link-filter (if edit-mode? (cut html:a :href (url-filter (date->url-day (datetime->date datetime))) <>) ;; TODO: edit-mode時以外にも、 ;; 該当日付に対応するコンテンツが ;; あるなら、 ;; リンク化しないといけない。 ;; あとで実装する事。 identity) (link-filter (if (and (= (date-year (datetime->date datetime)) (date-year (current-date))) (= (date-month (datetime->date datetime)) (date-month (current-date))) (= (date-day (datetime->date datetime)) (date-day (current-date)))) ;; TODO: このままでは背景色が赤系だとまずくなる。 ;; 何らかのportableな方法を導入する事。 (html:span :style "color:red" (filter-current-month (het str))) (filter-current-month (het str)))))))))) (html:tfoot (html:tr (html:th :colspan "7" (if edit-mode? (html:a :href (self-path/path-info) "(view mode)") (html:a :href (append-params-to-url (self-path/path-info) '(("c" "edit"))) "(edit mode)") )))))))) (define (html:page-selector-form self path-info-keylist edit-mode?) (make-form (self-path/path-info) (if edit-mode? '(("c" "edit")) '()) (html:div "ページ直接移動: " (html:input :type "text" :name "redirect_path" :value (let1 p (string-join path-info-keylist "/" 'prefix) (if (string=? p "") "/" p))) (html:input :type "submit" :value "移動") ))) (define (make-response:logined:edit:form self params ident-info path-info-keylist user-info) (make-page self (list (html:page-selector-form self path-info-keylist #t) (html:hr) (html:as-edit-form self params ident-info path-info-keylist) (html:hr) (html:div :style "float:right" (html:login/logout self 'logout "ログアウト")) (calendar-html path-info-keylist #t) ))) (define (make-response:logined:edit self params ident-info path-info-keylist user-info) (let1 cc (cgi-get-parameter "cc" params) ;; まずディスパッチする (cond ((equal? "preview" cc) (make-response:logined:edit:preview self params ident-info path-info-keylist user-info)) ((equal? "submit" cc) (make-response:logined:edit:submit self params ident-info path-info-keylist user-info)) ((equal? "done" cc) (make-response:logined:edit:done self params ident-info path-info-keylist user-info)) (else ; or "form" (make-response:logined:edit:form self params ident-info path-info-keylist user-info))))) (define (make-response:logined:display self params ident-info path-info-keylist user-info) (make-page self (list (html:page-selector-form self path-info-keylist #f) (html:hr) (html:display self params ident-info path-info-keylist) (html:hr) ;(html:h1 (het (informations-of self :title))) (html:div :style "float:right; text-align:right" (html:login/logout self 'logout "ログアウト") ;; TODO: 名前表示をすべきかは微妙 (html:div "名前: " (html:tt (het (get-keyword :name user-info)))) (html:div (html:a :href (append-params-to-url (self-path/path-info) '(("c" "ui"))) "(識別情報編集)")) ) (html:div :style "float:left" (calendar-html path-info-keylist #f)) ))) (define (html:as-edit-form self params ident-info path-info-keylist) (receive (path path-dir content-lock-file path-content-file path-dir-config-file) (get-content-parameter self path-info-keylist) ;; まず、現在の内容を取り出す ;;;;; TODO: あとで (let1 pair #f (html:div (make-form (self-path/path-info) '(("c" "edit") ("cc" "preview") ) (list ;; TODO: Content-Type変更の為のリンクを追加 (html:input :type "text" :name "text" :value "") (html:input :type "submit" :value "送信") )))))) (define (get-content-parameter self path-info-keylist) (let* ( (path (string-join path-info-keylist "/" 'prefix)) (path-dir (string-append (settings-of self :storage-dir) "/" "content-tree" path)) (content-lock-file (string-append (settings-of self :storage-dir) "/" "content-tree.lock")) (path-content-file (string-append path-dir "/.content")) (path-dir-config-file (string-append path-dir "/.config")) ) (values path path-dir content-lock-file path-content-file path-dir-config-file))) (define (html:display self params ident-info path-info-keylist) ;; path-info-keylistから、該当データを取り出し、適切に表示する ;; TODO: まずは、該当するディレクトリ及び.contentファイルのpathを求めるところまで作る事 (receive (path path-dir content-lock-file path-content-file path-dir-config-file) (get-content-parameter self path-info-keylist) ;; 表示すべき情報を、以下の手順で求める ;; - まず、path-contentが存在するなら、それを取得する(rfc822形式) ;; - 取得したcontentまたは#fに対し、以下を順に適用する ;; -- path-dir-configによる、何らかの設定が存在するなら、それを適用する ;; (結果はrfc822形式または#f) ;; -- pathに対応する、フィルタプラグインが存在するなら、それを適用する ;; (結果はrfc822形式または#f) ;; -- 最後に、その結果を、Content-Typeに応じた出力プラグインを用いて、 ;; html形式(またはその他の形式)として出力する。 ;; 最後まで#fのままだった場合は、404またはそれに類するページを出す。 ;; TODO: ファイルに異常がある場合、 ;; (ファイルは存在するがアクセス権限が無くて読めない等) ;; 適切にエラーを返すようにしたい ;; 但し、.contentは追記型ファイルとして、膨大なデータが ;; 溜め込まれている可能性もある為、 ;; rfc822形式のbody部分は直接取り込まずに、 ;; 最初はport状態として保持しておくものとする。 ;; (port状態か、その他の状態かは、キーワードで示すものとする) (define (path-dir-config-filter pair) ;; TODO: あとで pair) (define (path-plugin-filter pair) ;; TODO: あとで pair) (define (rfc822-output-filter pair) (if (not pair) (list (html:h1 "content not found") (html:div "このurlにはデータが存在しません。" (html:br) "おそらく、url間違いか、削除されたかのどれかです。" (html:br) "「" (html:a :href (append-params-to-url (self-path/path-info) '(("c" "edit"))) "edit mode") "」のところから、内容を新たに作成する事も可能です。" )) ;; TODO: あとで (html:div "データがあります。あとで表示部分を実装します。"))) (let1 path-content-port #f (dynamic-wind (lambda () ;; TODO: 同時にロックした方がいいかも ;; (しかし詳細未定) (set! path-content-port (open-input-file path-content-file :if-does-not-exist #f))) (lambda () (let* ((path-content-headers (if path-content-port (rfc822-header->list path-content-port) #f)) (path-content-pair0 (if path-content-port (cons path-content-headers path-content-port) #f)) ;; まず、これをpath-dir-configに設定されたフィルタにかける (path-content-pair1 (path-dir-config-filter path-content-pair0)) ;; 次に、これをpathに対応するプラグインフィルタにかける (path-content-pair2 (path-plugin-filter path-content-pair1)) ) ;; 最後に、結果を、Content-Typeに応じて適切にフォーマットして返す ;; 最後まで#fだった場合は、404またはそれに類する結果を返す事 (rfc822-output-filter path-content-pair2))) (lambda () ;; TODO: dynamic-wind突入時にロックしているなら、 ;; ここでアンロックする事 (when path-content-port (close-input-port path-content-port)) (set! path-content-port #f)))))) (define (make-response:logined:submit self params ident-info path-info-keylist user-info) ;; TODO: あとで (let1 new-msg (or (cgi-get-parameter "text" params) "") #f) (location (self-path))) (define (make-page self . body) (cgi-tree-make :http-header '(:pragma "no-cache") :encoding (x->string (gauche-character-encoding)) :css-url (informations-of self :css-url) :robots "NOINDEX,NOFOLLOW" :js #f :title (informations-of self :title) :body-header #f :body-footer (list (html:hr) (html:address (html:a :name "bottom" (informations-of self :title)))) :body body)) (define-method cgi-as-execute ((self <cgi-as>)) (cgi-main (lambda (orig-params) (with-cgi-session-ident (csa-of self) orig-params (lambda (true-params ident-info session-parameter) (with-path-info-keylist (lambda (path-info-keylist) (if ident-info (make-response:logined self true-params path-info-keylist ident-info session-parameter) (make-response:not-logined self true-params))))))) :on-error cgi-on-error/stack-trace ) 0) ;;; -------- (provide "tir04/tmp/20070619/as")
false
b6834416a3036508cd78adcd39ecbe0c42638390
41648be07e8803784690d9b4f6f08091e322b193
/core-immutable.ss
4420361c7b449d891b21a11d6ef89df3b0e8b94a
[]
no_license
samth/not-a-box
dad25a9ea65debf318a14f2a5f5788b331b62a76
9fa61e07b278be52148612fb5a77f4058eca5a9f
refs/heads/master
2021-01-19T12:51:12.457049
2017-03-02T19:57:20
2017-03-03T19:59:37
82,343,642
0
0
null
2017-02-17T22:27:36
2017-02-17T22:27:36
null
UTF-8
Scheme
false
false
427
ss
core-immutable.ss
(define immutables (make-weak-eq-hashtable)) (define (immutable? v) (or (hamt? v) (and (or (string? v) (bytes? v) (vector? v) (box? v)) (hashtable-ref immutables v #f)))) (define (unsafe-immutable? v) (hashtable-ref immutables v #f)) (define (unsafe-mutable? v) (not (unsafe-immutable? v))) (define (set-immutable! v) (hashtable-set! immutables v #t))
false
73c4483a240d95a98584f84f8774db3c2fc3b354
9b790264236d9c7a474a4802f4442356cab9da1a
/src/token.scm
8b436de8a6dc1949e2edcc45c86c83535496248c
[ "MIT" ]
permissive
harryposner/schlox
448a0301eab6dab1a526627ec5eea0e86f7a7c16
9ffeca792052029c0e3525ff31d1a1f083598a0a
refs/heads/master
2023-01-21T23:50:03.289594
2020-11-24T06:19:40
2020-11-24T06:19:40
304,046,012
6
0
null
null
null
null
UTF-8
Scheme
false
false
71
scm
token.scm
(declare (unit token)) (define-record token type lexeme literal line)
false
b57bdcc00ba6ba39a5e3cfabb82b0a98743b482f
b43e36967e36167adcb4cc94f2f8adfb7281dbf1
/sicp/ch4/code/interpreter-advance-test.scm
9bdf4927e0dd1e9112e73301cb16ccae884e0d65
[]
no_license
ktosiu/snippets
79c58416117fa646ae06a8fd590193c9dd89f414
08e0655361695ed90e1b901d75f184c52bb72f35
refs/heads/master
2021-01-17T08:13:34.067768
2016-01-29T15:42:14
2016-01-29T15:42:14
53,054,819
1
0
null
2016-03-03T14:06:53
2016-03-03T14:06:53
null
UTF-8
Scheme
false
false
197
scm
interpreter-advance-test.scm
(load "interpreter.scm") (define init-environment (make-empty-environment)) (define-variable! 'a '*unassigned* init-environment) ;(lookup-variable-value 'a init-environment) Should raise an error!
false
f8e467ac99a2384c992595ceb46ec8b4797efd41
355306b3af7b33911551c9114840ca032bfcb90f
/tests/depth1-bool-binary32.fpcore
01104a1b68bb2273a20441de10f7a387f8c56d90
[ "MIT" ]
permissive
FPBench/FPBench
80d22747454dc2e4964792bc72369d5dfb8f517c
6feb1dd753e465ac8bce7bd19f837749982ffee8
refs/heads/main
2023-02-08T00:54:53.337027
2022-11-23T00:02:02
2022-11-23T00:02:02
50,637,596
42
18
MIT
2022-11-23T00:02:03
2016-01-29T04:34:28
Racket
UTF-8
Scheme
false
false
3,011
fpcore
depth1-bool-binary32.fpcore
;; -*- mode: scheme -*- ;; Exhaustive at depth 1 (FPCore () :precision binary32 (if (< 1.0 1.0) 1.0 0.0)) (FPCore (arg1) :precision binary32 (if (< arg1 1.0) 1.0 0.0)) (FPCore (arg1) :precision binary32 (if (< 1.0 arg1) 1.0 0.0)) (FPCore (arg1) :precision binary32 (if (< arg1 arg1) 1.0 0.0)) (FPCore (arg1 arg2) :precision binary32 (if (< arg1 arg2) 1.0 0.0)) (FPCore (arg1 arg2) :precision binary32 (if (< arg2 arg1) 1.0 0.0)) (FPCore () :precision binary32 (if (> 1.0 1.0) 1.0 0.0)) (FPCore (arg1) :precision binary32 (if (> arg1 1.0) 1.0 0.0)) (FPCore (arg1) :precision binary32 (if (> 1.0 arg1) 1.0 0.0)) (FPCore (arg1) :precision binary32 (if (> arg1 arg1) 1.0 0.0)) (FPCore (arg1 arg2) :precision binary32 (if (> arg1 arg2) 1.0 0.0)) (FPCore (arg1 arg2) :precision binary32 (if (> arg2 arg1) 1.0 0.0)) (FPCore () :precision binary32 (if (<= 1.0 1.0) 1.0 0.0)) (FPCore (arg1) :precision binary32 (if (<= arg1 1.0) 1.0 0.0)) (FPCore (arg1) :precision binary32 (if (<= 1.0 arg1) 1.0 0.0)) (FPCore (arg1) :precision binary32 (if (<= arg1 arg1) 1.0 0.0)) (FPCore (arg1 arg2) :precision binary32 (if (<= arg1 arg2) 1.0 0.0)) (FPCore (arg1 arg2) :precision binary32 (if (<= arg2 arg1) 1.0 0.0)) (FPCore () :precision binary32 (if (>= 1.0 1.0) 1.0 0.0)) (FPCore (arg1) :precision binary32 (if (>= arg1 1.0) 1.0 0.0)) (FPCore (arg1) :precision binary32 (if (>= 1.0 arg1) 1.0 0.0)) (FPCore (arg1) :precision binary32 (if (>= arg1 arg1) 1.0 0.0)) (FPCore (arg1 arg2) :precision binary32 (if (>= arg1 arg2) 1.0 0.0)) (FPCore (arg1 arg2) :precision binary32 (if (>= arg2 arg1) 1.0 0.0)) (FPCore () :precision binary32 (if (== 1.0 1.0) 1.0 0.0)) (FPCore (arg1) :precision binary32 (if (== arg1 1.0) 1.0 0.0)) (FPCore (arg1) :precision binary32 (if (== 1.0 arg1) 1.0 0.0)) (FPCore (arg1) :precision binary32 (if (== arg1 arg1) 1.0 0.0)) (FPCore (arg1 arg2) :precision binary32 (if (== arg1 arg2) 1.0 0.0)) (FPCore (arg1 arg2) :precision binary32 (if (== arg2 arg1) 1.0 0.0)) (FPCore () :precision binary32 (if (!= 1.0 1.0) 1.0 0.0)) (FPCore (arg1) :precision binary32 (if (!= arg1 1.0) 1.0 0.0)) (FPCore (arg1) :precision binary32 (if (!= 1.0 arg1) 1.0 0.0)) (FPCore (arg1) :precision binary32 (if (!= arg1 arg1) 1.0 0.0)) (FPCore (arg1 arg2) :precision binary32 (if (!= arg1 arg2) 1.0 0.0)) (FPCore (arg1 arg2) :precision binary32 (if (!= arg2 arg1) 1.0 0.0)) (FPCore () :precision binary32 (if (isfinite 1.0) 1.0 0.0)) (FPCore (arg1) :precision binary32 (if (isfinite arg1) 1.0 0.0)) (FPCore () :precision binary32 (if (isinf 1.0) 1.0 0.0)) (FPCore (arg1) :precision binary32 (if (isinf arg1) 1.0 0.0)) (FPCore () :precision binary32 (if (isnan 1.0) 1.0 0.0)) (FPCore (arg1) :precision binary32 (if (isnan arg1) 1.0 0.0)) (FPCore () :precision binary32 (if (isnormal 1.0) 1.0 0.0)) (FPCore (arg1) :precision binary32 (if (isnormal arg1) 1.0 0.0)) (FPCore () :precision binary32 (if (signbit 1.0) 1.0 0.0)) (FPCore (arg1) :precision binary32 (if (signbit arg1) 1.0 0.0))
false
718cb0ae22cb98121a2ef9bf6a7600bf8e05fb3e
c085780da34766c02f47f181bd8a7bb515126caa
/lr2.scm
2636c348a2f75dd004c6d397df7abf281b5fdef6
[]
no_license
juleari/r5rs
37ede50989e59b0936f7aac2b204cb9affa22d21
880b0df41e94c103386c158cc172b658f485a465
refs/heads/master
2016-09-16T17:23:42.192923
2016-05-04T11:58:18
2016-05-04T11:58:18
42,339,524
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,952
scm
lr2.scm
; Написать процедуру (palindrom? xs), которая будет проверять является ли список палиндромом ; (Палиндромом считается список, который с конца читается также как и сначала) (define (palindrom? xs) (equal? xs (reverse xs))) (palindrom? '((1 2 3) 1 (1 2 3))) ; #t (palindrom? '((1 2 3) 1 (3 2 1))) ; #f ; Написать процедуру (palindrom-req? xs), которая будет проверять является ли содержимое списка палиндромом ; palindrom-req1 (define (palindrom-req? xs) (define (helper xs ys) (or (and (null? xs) (null? ys)) (and (list? (car xs)) (list? (car ys)) (helper (car xs) (reverse (car ys))) (helper (cdr xs) (cdr ys))) (and (not (list? (car xs))) (equal? (car xs) (car ys)) (helper (cdr xs) (cdr ys))))) (helper xs (reverse xs))) ; palindrom-req2 (define (palindrom-req? xs) (define (my-flatten xs) (or (and (null? xs) '()) (and (list? (car xs)) (append (my-flatten (car xs)) (my-flatten (cdr xs)))) (cons (car xs) (my-flatten (cdr xs))))) (palindrom? (my-flatten xs))) (palindrom-req? '((1 2 3) 1 (1 2 3))) ; #f (palindrom-req? '((1 2 3) 1 (3 2 1))) ; #t ; Написать процедуру (count pred? xs) которая будет возвращать количество элементов списка xs, ; удовлетворяющих условию pred? (define (count pred? xs) (or (and (null? xs) 0) (and (pred? (car xs)) (+ 1 (count pred? (cdr xs)))) (count pred? (cdr xs)))) (count odd? '(1 2 3 4 5 6 7)) ; 4 ; Написать процедуру add, которая будет складывать произвольное количество элементов. ; add1 (define (add . xs) (if (null? xs) 0 (+ (car xs) (apply add (cdr xs))))) ; add2 (define (add . xs) (apply + xs)) (add) ; 0 (add 1 4 6 2 8) ; 21 ; Написать процедуру (polynom as x), которая будет вычислять значение полинома (a0*x^n + ... + an) ; polynom1 (define (polynom as x) (define (helper as n) (if (null? as) 0 (+ (* (car as) (expt x n)) (helper (cdr as) (+ 1 n))))) (helper as 0)) ; polynom2 (define (polynom as x) (define (helper as y) (if (null? as) 0 (+ (* (car as) y) (helper (cdr as) (* y x))))) (if (null? as) 0 (helper as 1))) ; polynom3 (define (polynom as x) (define (helper as sum) (if (null? as) sum (helper (cdr as) (+ (* sum x) (car as))))) (helper (reverse as) 0)) (polynom '(3 2) 10) (polynom '(-4 1 -5 2 3) 2)
false
e2e087553b8703caabf3c3ae8c3a131fda11752e
eaa28dbef6926d67307a4dc8bae385f78acf70f9
/lib/pikkukivi/command/swap-extension.sld
37f21606014fb8ddc4c8553567cf845af0686c7c
[ "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
776
sld
swap-extension.sld
(define-library (pikkukivi command swap-extension) (export swap-extension) (import (scheme base) (scheme file) (gauche base) (util match) (file util)) (begin (define (swap-extension args) (match args ((srcext destext) (let ((src-files (directory-list (current-directory) :children? #t :filter (lambda (e) (and (not (file-is-directory? e)) (equal? srcext (path-extension e))))))) (for-each (lambda (f) (print f) (move-file f (path-swap-extension f destext))) src-files)))))))
false
9dd0f80979c555adb390b818ab4067d3a08c4dd5
defeada37d39bca09ef76f66f38683754c0a6aa0
/System/system/net/end-point-listener.sls
2af711bead6594083e58c682a8536a15046dcc8b
[]
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,195
sls
end-point-listener.sls
(library (system net end-point-listener) (export new is? end-point-listener? add-prefix unbind-context remove-prefix bind-context? close) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Net.EndPointListener a ...))))) (define (is? a) (clr-is System.Net.EndPointListener a)) (define (end-point-listener? a) (clr-is System.Net.EndPointListener a)) (define-method-port add-prefix System.Net.EndPointListener AddPrefix (System.Void System.Net.ListenerPrefix System.Net.HttpListener)) (define-method-port unbind-context System.Net.EndPointListener UnbindContext (System.Void System.Net.HttpListenerContext)) (define-method-port remove-prefix System.Net.EndPointListener RemovePrefix (System.Void System.Net.ListenerPrefix System.Net.HttpListener)) (define-method-port bind-context? System.Net.EndPointListener BindContext (System.Boolean System.Net.HttpListenerContext)) (define-method-port close System.Net.EndPointListener Close (System.Void)))
true
c5c1a0f13c70bdfb14b4278ce59aa6acab34ce70
648776d3a0d9a8ca036acaf6f2f7a60dcdb45877
/queries/wgsl_bevy/highlights.scm
4ba25a9350f14812177d24ec3f9196ee84edb1e1
[ "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
611
scm
highlights.scm
; inherits wgsl [ "virtual" "override" ] @keyword [ "#import" "#define_import_path" "as" ] @include "::" @punctuation.delimiter (function_declaration (import_path ((identifier) @function .))) (import_path (identifier) @namespace (identifier)) (struct_declaration (preproc_ifdef (struct_member (variable_identifier_declaration (identifier) @field)))) (struct_declaration (preproc_ifdef (preproc_else (struct_member (variable_identifier_declaration (identifier) @field))))) (preproc_ifdef name: (identifier) @constant.macro) [ "#ifdef" "#ifndef" "#endif" "#else" ] @preproc
false
9f70b287f9fbc7d6f229a8d238f3dc9b9fd09222
140a499a12332fa8b77fb738463ef58de56f6cb9
/worlds/core/verbcode/22/countup-5.scm
f8e54b4d1300272da7072a85457e459487fc0152
[ "MIT" ]
permissive
sid-code/nmoo
2a5546621ee8c247d4f2610f9aa04d115aa41c5b
cf504f28ab473fd70f2c60cda4d109c33b600727
refs/heads/master
2023-08-19T09:16:37.488546
2023-08-15T16:57:39
2023-08-15T16:57:39
31,146,820
10
0
null
null
null
null
UTF-8
Scheme
false
false
384
scm
countup-5.scm
(let ((func (get args 0)) (low (get args 1)) (high (get args 2)) (state (call-cc (lambda (x) (list low x))))) (if (nil? state) ; stopping condition nil ; return (let ((idx (get state 0)) (cont (get state 1))) (if (> idx high) (cont nil) (do (func idx) (cont ((+ idx 1) cont)))))))
false
b54f00d83c6d32dc44a7faef291ce2246d7c4aad
a9d1a0e915293c3e6101e598b3f8fc1d8b8647a9
/scheme/raytrace/test-canvas.scm
94c47b258abbb2c62509af694f429af628964fe6
[]
no_license
mbillingr/raytracing
a3b5b988007536a7065e51ef2fc17e6b5ac44d43
9c786e5818080cba488d3795bc6777270c505e5e
refs/heads/master
2021-04-16T17:10:40.435285
2020-11-11T07:02:18
2020-11-11T07:02:18
249,372,261
2
4
null
null
null
null
UTF-8
Scheme
false
false
1,531
scm
test-canvas.scm
(import (scheme base) (scheme write) (raytrace testing) (raytrace tuple) (raytrace canvas)) (test "Creating a canvas" (given (c <- (canvas 10 20))) (then ((canvas-width c) == 10) ((canvas-height c) == 20) (c == (canvas-clear! (canvas 10 20) (color 0 0 0))))) (test "Writing pixels to a canvas" (given (c <- (canvas 10 20)) (red <- (color 1 0 0))) (when (pixel-set! c 2 3 red)) (then ((pixel-get c 2 3) == red))) (test "Constructing the PPM header and pixel data" (given (c <- (canvas 5 3)) (c1 <- (color 1.5 0 0)) (c2 <- (color 0 0.5 0)) (c3 <- (color -0.5 0 1))) (when (pixel-set! c 0 0 c1) (pixel-set! c 2 1 c2) (pixel-set! c 4 2 c3) (ppm <- (canvas->ppm c))) (then (ppm == "P3 5 3 255 255 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 128 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 255 "))) (test "Splitting long lines in PPM files" (given (c <- (canvas 10 2))) (when (canvas-clear! c (color 1 0.8 0.6)) (ppm <- (canvas->ppm c))) (then (ppm == "P3 10 2 255 255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 "))) (test "PPM files are terminated by a newline character" (given (c <- (canvas 5 3))) (when (ppm <- (canvas->ppm c))) (then ((string-ref ppm (- (string-length ppm) 1)) == #\newline)))
false
f2e82878e5d27caac55731ca6b908a99ef7f6c4b
7054455f2fcbf47a2c58627305a7ce26eabb3297
/reser.meta
df1bbe123ab516ce9b301d22a5e775d557a98d78
[]
no_license
Adellica/reser
c5908acf3b4e5b74e2db457e0fa5367edeec4a1c
6781bfe2ca9c7738274eb38a1fd52604e214e6ad
refs/heads/master
2016-09-05T23:13:05.792616
2016-01-30T14:30:14
2016-01-30T14:30:14
33,715,868
7
1
null
null
null
null
UTF-8
Scheme
false
false
88
meta
reser.meta
;; -*- scheme -*- ((author . "Adellica") (needs spiffy intarweb uri-common matchable))
false
f32cc772060ac36f81dcda820e30a2710f425877
95927b79b2bc9bb9af824ef249a9caf7dcc1bc42
/modules.scm
367294fbefc604842974642bbfdf85b405b68026
[]
no_license
tbl3rd/network-simulation-scsh-cpp
7b337be2db72163f72da572bf327fe5d4a489ca1
6666d376e012bfcc7913c5276a81a0a3ad984e3a
refs/heads/master
2021-01-22T07:32:41.034002
2013-03-19T01:09:14
2013-03-19T01:09:14
8,867,480
1
0
null
null
null
null
UTF-8
Scheme
false
false
1,065
scm
modules.scm
; Forms for mapping between Scheme objects and their values ; represented as binary images in strings of octets, used ; to help build frames and so on. (define-structure octets (export integer->octets octets->integer string<->octets (define-string<->octets-procedures :syntax)) (open scheme scsh) (files octets)) ; A random collection of procedures used in the simulator. (define-structure miscellaneous (export list->generator list-of-n remove make-random-16-bit-integer make-random-32-bit-integer make-random-48-bit-integer unbuffered-pipe) (open big-scheme random scheme scsh) (files miscellaneous)) ; A network simulator toolkit. Currently export only make-network ; which returns a curried simulator procedure that takes the pathname ; of a bridge or router application to test. (define-structure network (export make-network) (open scheme scsh octets miscellaneous) (files network))
false
64a5e88562b195d954a0e180092532186a4b7b5f
895daaa3a466ec7f61773b892920dfbe8d78780e
/examples/literals.scm
e89f6e2fb253064c5d40419afca267b24fcd7149
[]
no_license
jwalsh/scheme-workshop-2014
feac007278a4255ccdb6c82814ea18bbf646d8fa
32718dbdc3a83d0508f7b6110c59e7e960db7b62
refs/heads/master
2016-09-05T16:18:50.247061
2015-03-25T19:17:42
2015-03-25T19:17:42
26,870,183
0
0
null
null
null
null
UTF-8
Scheme
false
false
43
scm
literals.scm
(quote a) (quote #(a b c)) (quote (+ 1 2))
false