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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f827dc3083f0d4411df5b630f3050dec697531f9 | 2f88dd127122c2444597a65d8b7a23926aebbac1 | /st-character.scm | 621925f13fb19fbe22bf2dfe4592209ee2798ff0 | [
"BSD-2-Clause"
]
| permissive | KenDickey/Crosstalk | 6f980b7188c1cc6bd176a8e0cd10b032f768b4e6 | b449fb7c711ad287f9b49e7167d8cedd514f5d81 | refs/heads/master | 2023-05-26T10:07:12.674162 | 2023-05-21T22:59:26 | 2023-05-21T22:59:26 | 58,777,987 | 11 | 1 | null | null | null | null | UTF-8 | Scheme | false | false | 7,425 | scm | st-character.scm | ;;; FILE: "st-character.scm"
;;; IMPLEMENTS: Characters
;;; AUTHOR: Ken Dickey
;;; DATE: 12 June 2016
;; (require 'st-core-classes)
(import (scheme char))
(define Character
(newSubclassName:iVars:cVars:
Object
'Character '() '())
)
(set! st-character-behavior (perform: Character 'methodDict))
(addSelector:withMethod:
Character
'is:
(lambda (self symbol)
(or (eq? symbol 'Character)
(superPerform:with: self 'is: symbol))))
(perform:with:
Character
'category: "Kernel-Text")
(perform:with:
Character
'comment:
"I support Unicode, rather than ASII characters.")
(addSelector:withMethod:
Character
'printOn:
(lambda (self port)
(display "$" port)
(display self port)))
(addSelector:withMethod:
Character
'=
(lambda (self otherChar)
(char=? self otherChar)))
(addSelector:withMethod:
Character
'<
(lambda (self otherChar)
(char<? self otherChar)))
(addSelector:withMethod:
Character
'>
(lambda (self otherChar)
(char>? self otherChar)))
(addSelector:withMethod:
Character
'>=
(lambda (self otherChar)
(char>=? self otherChar)))
(addSelector:withMethod:
Character
'<=
(lambda (self otherChar)
(char<=? self otherChar)))
(addSelector:withMethod:
Character
'asLowercase
(lambda (self)
(char-downcase self)))
(addSelector:withMethod:
Character
;; NB: Some Unicode chars have no upcase equivalent
'asUppercase
(lambda (self)
(char-upcase self)))
(addSelector:withMethod:
Character
'asString
(lambda (self)
(string self)))
(addSelector:withMethod:
Character
'asSymbol
(lambda (self)
(string->symbol (string self))))
(addSelector:withMethod:
Character
'asCharacter
(lambda (self) self))
(addSelector:withMethod:
Character
'asInteger
(lambda (self) (char->integer self)))
(addSelector:withMethod:
Character
'value ;; NOT an instance variable !!
(lambda (self)
(char->integer self)))
(addSelector:withMethod:
(class Character)
'value:
(lambda (self anInteger)
(integer->char anInteger)))
(addSelector:withMethod:
Character
'isLetter
(lambda (self)
(char-alphabetic? self)))
(addSelector:withMethod:
Character
'isDigit
(lambda (self)
(char-numeric? self)))
(addSelector:withMethod:
(class Character)
'digitValue:
;"Answer the Character whose digit value is x.
; For example, answer $9 for x=9, $0 for x=0, $A for x=10, $Z for x=35."
(lambda (self aChar)
(let ( (val
($::: "0123456789abcdefghijklmnopqrstuvwxyz"
'indexOf:startingAt:ifAbsent:
(char-downcase aChar)
1
(lambda () #f)))
)
(if val (- val 1) ; zero is index 1
-1)))
)
(addSelector:withMethod:
Character
'digitValue
;"Answer the Character whose digit value is x.
; For example, answer $9 for x=9, $0 for x=0, $A for x=10, $Z for x=35."
(lambda (self)
(let ( (val
($::: "0123456789abcdefghijklmnopqrstuvwxyz"
'indexOf:startingAt:ifAbsent:
(char-downcase self)
1
(lambda () #f)))
)
(if val (- val 1) ; zero is index 1
-1)))
)
(addSelector:withMethod:
Character
'isSeparator
(lambda (self)
(char-whitespace? self)))
(addSelector:withMethod:
Character
'isAlphaNumeric
(lambda (self)
(or (char-alphabetic? self)
(char-numeric? self))))
(addSelector:withMethod:
Character
'isValidInIdentifiers
(lambda (self)
(or (char-alphabetic? self)
(char-numeric? self))))
(addSelector:withMethod:
Character
'tokenish ;; 'isTokenish ??
(lambda (self)
(or (char-alphabetic? self)
(char-numeric? self)
(char=? self #\:))))
(addSelector:withMethod:
Character
'isUppercase
(lambda (self)
(char-upper-case? self)))
(addSelector:withMethod:
Character
'isLowercase
(lambda (self)
(char-lower-case? self)))
(define st-special-chars ;; "\\" = (string #\\)
(string->list "+-/\\*~<>=@,%|&?!"))
(addSelector:withMethod:
Character
'isSpecial
(lambda (self)
;; remember to return a boolean..
(if (member self st-special-chars) st-true st-false)))
;;; Named characters
(define named-characters
'((aleph . #x8D) ; math
(arrowUp . 30)
(arrowLeft . 28)
(arrowRight . 29)
(arrowDown . 31)
(backspace . 8)
(bullit . #x9F)
(circle . #x9E) ; math
(contourIntegral . #x93) ; math
(cr . 13)
(delete . 127)
(doesNotExist . #x83) ; math
(dot . #xB7) ; math
(end . 4)
(emptySet . #x84) ; math
(enter . 3)
(escape . 27)
(euro . 164)
(exists . #x82) ; math
(forAll . #x80) ; math
(greaterNotEqual . #x9D) ; math
(greaterOrEqual . #x99) ; math
(greaterOverEqual . #x9B) ; math
(home . 1)
(identical . #x95) ; math
(infinity . #x85) ; math; a.k.a. offscale
(insert . 5)
(integral . #x92) ; math
(lessNotEqual . #x9C) ; math
(lessOrEqual . #x98) ; math
(lessOverEqual . #x9A) ; math
(lf . 10) ; line feed
(nbsp . 202) ; non-breakable space
(newlineCharacter . 10) ; NB: lf NOT cr
(newline . 10) ; NB: lf NOT cr
(nl . 10) ; NB: lf NOT cr
(newPage . 12) ; form feed
(notEqual . #x94) ; math
(notIdentical . #x96) ; math
(null . 0)
(odot . #x8E) ; math
(oplus . #x8F) ; math
(otimes . #x90) ; math
(partial . #x81) ; math
(pageDown . 12)
(pageUp . 11)
(space . 32)
(strictlyEquivalent . #x97) ; math
(summation . #x91) ; math
(tab . 9)
(times . #xD7) ; math
)
)
(for-each
(lambda (pair)
(let ( (char (integer->char (cdr pair))) )
(addSelector:withMethod:
(class Character)
(car pair)
(lambda (self) char))))
named-characters)
(addSelector:withMethod:
(class Character)
'new
(lambda (self) (error "cannot create new characters" self)))
(addSelector:withMethod:
(class Character)
'new:
(lambda (self value) (error "cannot create new characters" self value)))
(addSelector:withMethod:
(class Character)
'value:
(lambda (self value)
(unless (integer? value)
(error: "Character value: anInteger" value))
(integer->char value)))
;; (provide 'st-character)
;;; --- E O F --- ;;;
| false |
ce85135ad06442434a62f2ce6db99ff0abeca7d3 | a5d31dc29c25d1f2c0dab633459de05f5996679a | /benchmark-verification/even-odd.sch | e7913107db27e1187212b7155fa3326d80283f3e | []
| no_license | jebcat1982/soft-contract | 250461a231b150b803df9275f33ee150de043f00 | 4df509a75475843a2caeb7e235301f277446e06c | refs/heads/master | 2021-01-21T22:06:10.092109 | 2014-05-26T11:51:00 | 2014-05-26T11:51:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 228 | sch | even-odd.sch | (module eo
(provide
[even? (int? . -> . bool?)]
[odd? (int? . -> . bool?)])
(define (even? n)
(if (zero? n) #t (odd? (sub1 n))))
(define (odd? n)
(if (zero? n) #f (even? (sub1 n)))))
(require eo)
(even? •) | false |
402e8bd9d1b9bc5b4766c5a35bee157bdd1a76e6 | 4b480cab3426c89e3e49554d05d1b36aad8aeef4 | /chapter-02/ex2.47-gsong.scm | 8c4d97e3505097d6a805c8edb95f7953717bde80 | []
| no_license | tuestudy/study-sicp | a5dc423719ca30a30ae685e1686534a2c9183b31 | a2d5d65e711ac5fee3914e45be7d5c2a62bfc20f | refs/heads/master | 2021-01-12T13:37:56.874455 | 2016-10-04T12:26:45 | 2016-10-04T12:26:45 | 69,962,129 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 2,806 | scm | ex2.47-gsong.scm | (load "../misc/scheme-test.scm")
(define (make-vect xcor ycor) (cons xcor ycor))
(define (xcor-vect vect) (car vect))
(define (ycor-vect vect) (cdr vect))
(define (add-vect v1 v2) (make-vect (+ (xcor-vect v1) (xcor-vect v2)) (+ (ycor-vect v1) (ycor-vect v2))))
(define (scale-vect v1 s) (make-vect (* s (xcor-vect v1)) (* s (ycor-vect v1))))
(define (sub-vect v1 v2) (add-vect v1 (scale-vect v2 -1)))
(run (make-testcase
'(assert-equal? (xcor-vect (make-vect 1 1)) 1)
'(assert-equal? (xcor-vect (make-vect 2 1)) 2)
'(assert-equal? (ycor-vect (make-vect 1 1)) 1)
'(assert-equal? (ycor-vect (make-vect 2 3)) 3)
'(assert-equal? (xcor-vect (add-vect (make-vect 1 0) (make-vect 4 0))) 5)
'(assert-equal? (ycor-vect (add-vect (make-vect 1 0) (make-vect 4 4))) 4)
'(assert-equal? (xcor-vect (sub-vect (make-vect 1 0) (make-vect 4 0))) -3)
'(assert-equal? (ycor-vect (sub-vect (make-vect 1 0) (make-vect 4 4))) -4)
'(assert-equal? (xcor-vect (scale-vect (make-vect 1 0) 3)) 3)
'(assert-equal? (ycor-vect (scale-vect (make-vect 1 4) 2)) 8)
))
(define (make-frame origin edge1 edge2)
(list origin edge1 edge2))
(define (get_origin f)
(car f))
(define (get_edge1 f)
(cadr f))
(define (get_edge2 f)
(caddr f))
(define (get_edge2_f2 f)
(cddr f))
(define (make-frame2 origin edge1 edge2)
(cons origin (cons edge1 edge2)))
(run (make-testcase
'(assert-equal? (xcor-vect (get_origin (make-frame (make-vect 5 3) (make-vect 1 0) (make-vect 0 1)))) 5)
'(assert-equal? (ycor-vect (get_origin (make-frame (make-vect 5 3) (make-vect 1 0) (make-vect 0 1)))) 3)
'(assert-equal? (xcor-vect (get_edge1 (make-frame (make-vect 5 3) (make-vect 1 0) (make-vect 0 1)))) 1)
'(assert-equal? (ycor-vect (get_edge1 (make-frame (make-vect 5 3) (make-vect 1 0) (make-vect 0 1)))) 0)
'(assert-equal? (xcor-vect (get_edge2 (make-frame (make-vect 5 3) (make-vect 1 0) (make-vect 0 1)))) 0)
'(assert-equal? (ycor-vect (get_edge2 (make-frame (make-vect 5 3) (make-vect 1 0) (make-vect 0 1)))) 1)
'(assert-equal? (xcor-vect (get_origin (make-frame2 (make-vect 5 3) (make-vect 1 0) (make-vect 0 1)))) 5)
'(assert-equal? (ycor-vect (get_origin (make-frame2 (make-vect 5 3) (make-vect 1 0) (make-vect 0 1)))) 3)
'(assert-equal? (xcor-vect (get_edge1 (make-frame2 (make-vect 5 3) (make-vect 1 0) (make-vect 0 1)))) 1)
'(assert-equal? (ycor-vect (get_edge1 (make-frame2 (make-vect 5 3) (make-vect 1 0) (make-vect 0 1)))) 0)
'(assert-equal? (xcor-vect (get_edge2_f2 (make-frame2 (make-vect 5 3) (make-vect 1 0) (make-vect 0 1)))) 0)
'(assert-equal? (ycor-vect (get_edge2_f2 (make-frame2 (make-vect 5 3) (make-vect 1 0) (make-vect 0 1)))) 1)
)) | false |
de57081b765b78b06655cb9d638c404a96675baa | 1dfe3abdff4803aee6413c33810f5570d0061783 | /.chezscheme_libs/srfi/srfi-11.sls | a762a2bbca0d7d43c920ced9722c41f3a3a55bca | [
"X11-distribute-modifications-variant"
]
| permissive | Saigut/chezscheme-libs | 73cb315ed146ce2be6ae016b3f86cf3652a657fc | 1fd12abbcf6414e4d50ac8f61489a73bbfc07b9d | refs/heads/master | 2020-06-12T14:56:35.208313 | 2016-12-11T08:51:15 | 2016-12-11T08:51:15 | 75,801,338 | 6 | 2 | null | null | null | null | UTF-8 | Scheme | false | false | 177 | sls | srfi-11.sls | #!r6rs
;; Automatically generated by private/make-aliased-libraries.sps
(library (srfi srfi-11)
(export
let*-values
let-values)
(import (srfi srfi-11 let-values))
)
| false |
b89dd62c6a6d765b9357d5b16b414424003a7c80 | defeada37d39bca09ef76f66f38683754c0a6aa0 | /UnityEngine/unity-engine/guilayout-utility.sls | a5b72fcbe79e7e6259739e0f5cc402af84ea4277 | []
| 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 | 2,615 | sls | guilayout-utility.sls | (library (unity-engine guilayout-utility)
(export new
is?
guilayout-utility?
get-last-rect
get-rect
end-group
begin-group
get-aspect-rect)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...) #'(clr-new UnityEngine.GUILayoutUtility a ...)))))
(define (is? a) (clr-is UnityEngine.GUILayoutUtility a))
(define (guilayout-utility? a)
(clr-is UnityEngine.GUILayoutUtility a))
(define-method-port
get-last-rect
UnityEngine.GUILayoutUtility
GetLastRect
(static: UnityEngine.Rect))
(define-method-port
get-rect
UnityEngine.GUILayoutUtility
GetRect
(static:
UnityEngine.Rect
System.Single
System.Single
System.Single
System.Single
UnityEngine.GUIStyle
UnityEngine.GUILayoutOption[])
(static:
UnityEngine.Rect
System.Single
System.Single
System.Single
System.Single
UnityEngine.GUILayoutOption[])
(static:
UnityEngine.Rect
System.Single
System.Single
System.Single
System.Single
UnityEngine.GUIStyle)
(static:
UnityEngine.Rect
System.Single
System.Single
System.Single
System.Single)
(static:
UnityEngine.Rect
System.Single
System.Single
UnityEngine.GUIStyle
UnityEngine.GUILayoutOption[])
(static:
UnityEngine.Rect
System.Single
System.Single
UnityEngine.GUILayoutOption[])
(static:
UnityEngine.Rect
System.Single
System.Single
UnityEngine.GUIStyle)
(static: UnityEngine.Rect System.Single System.Single)
(static:
UnityEngine.Rect
UnityEngine.GUIContent
UnityEngine.GUIStyle
UnityEngine.GUILayoutOption[])
(static:
UnityEngine.Rect
UnityEngine.GUIContent
UnityEngine.GUIStyle))
(define-method-port
end-group
UnityEngine.GUILayoutUtility
EndGroup
(static: System.Void System.String))
(define-method-port
begin-group
UnityEngine.GUILayoutUtility
BeginGroup
(static: System.Void System.String))
(define-method-port
get-aspect-rect
UnityEngine.GUILayoutUtility
GetAspectRect
(static:
UnityEngine.Rect
System.Single
UnityEngine.GUIStyle
UnityEngine.GUILayoutOption[])
(static:
UnityEngine.Rect
System.Single
UnityEngine.GUILayoutOption[])
(static: UnityEngine.Rect System.Single UnityEngine.GUIStyle)
(static: UnityEngine.Rect System.Single)))
| true |
f3ca42d7423a0c0c4a869aa85713327cd0b07e62 | d47ddad953f999e29ce8ef02b059f945c76a791e | /lab2-and-3/homework6/mult-matrices.scm | a0b2bc781a120e572e8615585234f4c625c0ef03 | []
| no_license | IvanIvanov/fp2013 | 7f1587ef1f2261f8cd0cd3dd99ec147c4043a2ae | 2ac1bb1102cb65e0ecbfa8d2fb3ca69953ae4ecf | refs/heads/master | 2016-09-11T10:08:59.873239 | 2014-01-23T20:38:27 | 2014-01-23T20:40:34 | 13,211,029 | 5 | 2 | null | 2014-01-10T15:55:14 | 2013-09-30T09:18:33 | Scheme | UTF-8 | Scheme | false | false | 1,546 | scm | mult-matrices.scm | (define (nth l index)
(define (nth-iter l index elem-so-far)
(cond
( (= index 0) elem-so-far)
(else (nth-iter (cdr l) (- index 1) (car l)))))
(nth-iter l index (car l)))
(define (range a b)
(cond
( (> a b) (list))
(else (cons a (range (+ a 1) b)))))
(define (first l) (nth l 1))
(define (last l) (nth l (length l)))
;;; функцията взима матрица и връща списък с 2 елемента с размерностите на матрицата
(define (dimension M)
(cons (length M) (cons (length (car M)) (list) )))
;;; връща колоната с даден index
(define (get-column M index)
(map (lambda (row) (nth row index)) M))
;;; връща главния диагонал на квадратната матрица M
(define (diagonal M)
(map (lambda (elem index) (nth elem index)) M (range 1 (length M))))
;;; транспониране на матрица
(define (transpose M)
(map (lambda (index) (get-column M index)) (range 1 (length (car M)))))
;;; предикат, който казва дали две матрици могат да бъдат умножени
;;; MxP * PxN = MxN
(define (can-multiply? M1 M2)
(= (last (dimension M1)) (first (dimension M2))))
(define (mult-matrices M1 M2)
(cond
( (not (can-multiply? M1 M2)) (list))
(else (map (lambda (row)
(map (lambda (col)
(apply + (map * row col)))
(transpose M2)))
M1)))) | false |
41bc5441b115cf828570b37ee9863917c0fab7d5 | 4fd95c081ccef6afc8845c94fedbe19699b115b6 | /chapter_1/1.8.scm | 09cf53bc805933536530b3a96f0569beec0abe89 | [
"MIT"
]
| permissive | ceoro9/sicp | 61ff130e655e705bafb39b4d336057bd3996195d | 7c0000f4ec4adc713f399dc12a0596c770bd2783 | refs/heads/master | 2020-05-03T09:41:04.531521 | 2019-08-08T12:14:35 | 2019-08-08T12:14:35 | 178,560,765 | 1 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 904 | scm | 1.8.scm | ;; Newton's method to find 1^3
(define infelicity 0.01)
(define (cube x) (* x x x))
(define (square x) (* x x))
(define (abs x) (if (< x 0) (* -1 x) x))
(define (is-good-enough? guess x)(< (abs (- (cube guess) x)) infelicity))
(define (average x y) (/ (+ x y) 2))
(define (improve guess x) (average guess (/ (+ (/ x (square guess)) (* 2 guess)) 3)))
(define (cubic-iter guess x)
(if (is-good-enough? guess x)
guess
(cubic-iter (improve guess x) x)))
(define (cubic x) (cubic-iter 1 x))
(define (cubic-tiny-iter guess-prev guess-current x)
(if (< (abs (- guess-current guess-prev)) infelicity)
guess-current
(cubic-tiny-iter guess-current (improve guess-current x) x)))
(define (cubic-tiny x) (cubic-tiny-iter 1 (improve 1 x) x))
(display (cubic 10))
(display "\n")
(display (cubic-tiny 10))
(display "\n")
(display (cubic 0.4224))
(display "\n")
(display (cubic-tiny 0.4224))
| false |
69fd3e714d40e5260ea3fbeeb918a11f8bfc6ab1 | 235b9cee2c18c6288b24d9fa71669a7ee1ee45eb | /compiler/convert-assignments.ss | 7e1c0bdf91678c0d2d5f1b489242c0df97278a7a | []
| no_license | Tianji-Zhang/p423 | f627046935a58c16a714b230d4a528bdcda41057 | f66fc2167539615a9cd776343e48664b902d98b1 | refs/heads/master | 2021-01-18T04:33:38.905963 | 2013-05-18T05:56:41 | 2013-05-18T05:56:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 3,105 | ss | convert-assignments.ss | ;; convert-assignments.ss
;;
;; part of p423-sp12/srwaggon-p423
;; http://github.iu.edu/p423-sp12/srwaggon-p423
;; introduced in A14
;; 2012 / 8 / 26
;;
;; Samuel Waggoner
;; [email protected]
;; revised in A14
;; 2012 / 8 / 26
#!chezscheme
(library (compiler convert-assignments)
(export convert-assignments)
(import
;; Load Chez Scheme primitives:
(chezscheme)
;; Load compiler framework:
(framework match)
(framework helpers)
(compiler helpers)
)
#|
||
|#
(define-who (convert-assignments expr)
(define (convert-binding uvar* expr* assign*)
(cond
[(null? uvar*) (values '() '())]
[else (let-values ([(bind* tmp*)
(convert-binding (cdr uvar*) (cdr expr*) assign*)])
(let ([x (car uvar*)]
[e (car expr*)])
(if (memq x assign*)
(let ([tmp (unique-name who)])
(values `((,tmp ,e) . ,bind*) `((,x . ,tmp) . ,tmp*)))
(values `((,x ,e) . ,bind*) tmp*))))]
))
(define (convert-formal uvar* assign*)
(cond
[(null? uvar*) (values '() '())]
[else (let-values ([(formal* tmp*) (convert-formal (cdr uvar*) assign*)])
(let ([x (car uvar*)])
(if (memq x assign*)
(let ([tmp (unique-name who)])
(values `(,tmp . ,formal*) `((,x . ,tmp) . ,tmp*)))
(values `(,x . ,formal*) tmp*))))]
))
(define (zip-bind* assign* tmp*)
(map (lambda (x)
`(,x (cons ,(cdr (assq x tmp*)) (void))))
assign*)
)
(define (Expr new*)
(lambda (expr)
(match expr
[,uvar (guard (uvar? uvar))
(if (memq uvar new*) `(car ,uvar) uvar)]
[(quote ,immediate) (guard (immediate? immediate))
`(quote ,immediate)]
[(begin ,[e*] ... ,[e])
`(begin ,e* ... ,e)]
[(if ,[t] ,[c] ,[a])
`(if ,t ,c ,a)]
[(letrec ([,uvar* ,[e*]] ...) ,[b])
`(letrec ([,uvar* ,e*] ...) ,b)]
[(let ([,uvar* ,[e*]] ...) (assigned ,assigned* ,b))
(let*-values ([(body) ((Expr (append new* assigned*)) b)]
[(bind* tmp*) (convert-binding uvar* e* assigned*)]
[(assign-bind*) (zip-bind* assigned* tmp*)])
`(let ,bind*
(let ,assign-bind* ,body)))]
[(lambda ,uvar* (assigned ,assigned* ,b))
(let*-values ([(body) ((Expr (append new* assigned*)) b)]
[(formal* tmp*) (convert-formal uvar* assigned*)]
[(assign-bind*) (zip-bind* assigned* tmp*)])
`(lambda ,formal*
(let ,assign-bind* ,body)))]
[(set! ,uvar ,[e])
`(set-car! ,uvar ,e)]
[(,prim ,[e*] ...) (guard (prim? prim))
`(,prim ,e* ...)]
[(,[rator] ,[rand*] ...)
`(,rator ,rand* ...)]
[,else
(invalid who 'expression else)]
)))
((Expr '()) expr)
)) ;; end library
| false |
4391f7fcc07c9a970cd5438d97a842dbb465ace6 | c63772c43d0cda82479d8feec60123ee673cc070 | /ch3/30.scm | 16e520d53f52a6685b90586d8f46ad6de0b20229 | [
"Apache-2.0"
]
| permissive | liuyang1/sicp-ans | 26150c9a9a9c2aaf23be00ced91add50b84c72ba | c3072fc65baa725d252201b603259efbccce990d | refs/heads/master | 2021-01-21T05:02:54.508419 | 2017-09-04T02:48:46 | 2017-09-04T02:48:52 | 14,819,541 | 2 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 547 | scm | 30.scm | (load "wire.scm")
(define (two-adder a1 a2 b1 b2 c-in s1 s2 c-out)
(define c1 (make-wire))
(full-adder a1 b1 c-in s1 c1)
(full-adder a2 b2 c1 s2 c-out)
'ok)
; test code
(define a1 (make-wire))
(define b1 (make-wire))
(define a2 (make-wire))
(define b2 (make-wire))
(define c-in (make-wire))
(define s1 (make-wire))
(define s2 (make-wire))
(define c-out (make-wire))
(two-adder a1 a2 b1 b2 c-in s1 s2 c-out)
(set-signal! a1 1)
(set-signal! a2 1)
(set-signal! b1 1)
(set-signal! b2 1)
(set-signal! c-in 1)
(display (append c-out s2 s1))
| false |
d54f14f18516281a7850dd77b7b78b87c6ae1a4b | e0d40ccf2c167727b34984f8d355c0e1d28aa771 | /lang/digrap/lib/representation-of-graph.scm | 0a6c30082c120b4dd43e6bbfee9075f1e1fc30a9 | []
| no_license | pyzh/xieyuheng.github.io | ace04793dea622beef050adf12d64ccecc3dcaa9 | c01e9e216f55d38395cb47045f0f1a1dd338f535 | refs/heads/master | 2020-03-25T22:22:27.656913 | 2018-08-09T17:21:52 | 2018-08-09T17:21:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 2,084 | scm | representation-of-graph.scm | (define ?
(lambda (x)
(and (list x)
(not (null? x))
(eq? (car x) '))))
;; 希望给出比较不平凡的例子作为测试
;; 以使所有的递归在基本的测试中都能被跑到
(define example-graph
;; memory == O(|V|+|E|)
;; 点中保存与自己相邻的边 边中保存与自己相邻的点
'(
;; 在下面的表示中 每一个点边元素都用方括号
;; vertex-list (0-dimension-geometry-object-list)
;; 每个点中有一个列表储存着所有以这个
(#2=[(vertex-2 #2# (:value 222))
(edge:2-->3 #4#) (edge:3-->2 #6#)]
#3=[(vertex-3 #3# (:value 333))
(edge:2-->3 #4#) (edge:3-->2 #6#)])
;; edge-list (1-dimension-geometry-object-list)
;; 注意边和点的储存方式是一致的
(#4=[(edge:2-->3 #4# (:edge-type black-arrow))
;; 两个点在下面的列表中储存的顺序
;; 体现着这条边连接它们的方式
(vertex-2 #2#) (vertex-3 #3#)]
#6=[(edge:3-->2 #6# (:edge-type black-arrow))
(vertex-3 #3#) (vertex-2 #2#)])
;; 可以发现图的几何语义限制了上面的列表的样子
;; 在图的语义下:
;; 2-dim几何体 能且只能 与两个1-dim几何体相连
;; 并且其邻接列表是有序的
;; 1-dim几何体 能 与0个或1个或多个2-dim几何体相连
;; 并且遗忘了其邻接列表的顺序
;; 显然在这里我们可以进行推广
;; 在这种实现方式下所能得到的最广泛的推广是:
;; 可以有n-dim几何体列表
;; 几何体都可以和任意维数的几何体相连接
;; 显然利用这种实现的推广
;; 只要再向上面一样添加某先限制条件
;; 就能够形成代数拓扑中的某些复形的语义
;; 但是要注意的是限制条件对语义的影响可能是相当微妙的
;; 几何语义的建立 可以帮助我们决定应该实现什么样的 基本处理函数
;; 基本的观察 与 基本的几何想像 总能把人们引向有趣而丰富的理论
))
| false |
650256f747725e0655d10051d1c7a53ffb3e97fe | 5667f13329ab94ae4622669a9d53b649c4551e24 | /flonum/expansion/math.flonum.expansion.log.scm | 2aa5b3a5b53f306e1aece3843b1a1fb5ff1883f5 | []
| no_license | dieggsy/chicken-math | f01260e53cdb14ba4807f7e662c9e5ebd2da4dda | 928c9793427911bb5bb1d6b5a01fcc86ddfe7065 | refs/heads/master | 2021-06-11T07:14:21.461591 | 2021-04-12T22:12:14 | 2021-04-12T22:12:14 | 172,310,771 | 2 | 1 | null | null | null | null | UTF-8 | Scheme | false | false | 3,937 | scm | math.flonum.expansion.log.scm | #|
Compute log and log1p with 105-bit accuracy
Both implementations do some argument reduction, find excellent 53-bit initial estimates, and then
perform one Newton step.
|#
(module math.flonum.expansion.log (fp2log fp2log1p)
(import scheme
chicken.base
chicken.type
chicken.flonum
math.flonum.functions
math.flonum.error
math.flonum.log
math.flonum.expansion.base
math.flonum.expansion.exp)
;; ===================================================================================================
;; log
#|
Argument reduction for log:
log(x) = log(x*2^k) - k*log(2)
A value of k that reduces any x to [0.5, 1.0] is
k = -truncate(log(x)/log(2))
|#
(define-values (log2-hi log2-lo) (values 0.6931471805599453 2.3190468138462996e-17))
(: fp2log-reduction (float float -> float float float))
(define (fp2log-reduction x2 x1)
(define k (- (fptruncate (fp/ (fplog+ x1 x2) (fplog 2.0)))))
(cond [(fp> k 1023.0)
;; This can happen if x is subnormal; just multiply in pieces
(let* ([k0 1023.0]
[k1 (fp- k k0)]
[2^k0 (fpexpt 2.0 k0)]
[2^k1 (fpexpt 2.0 k1)])
[let*-values ([(x2 x1) (values (* x2 2^k0 2^k1) (* x1 2^k0 2^k1))])
(values k x2 x1)])]
[else
(let ([2^k (fpexpt 2.0 k)])
(let*-values ([(x2 x1) (values (fp* x2 2^k) (fp* x1 2^k))])
(values k x2 x1)))]))
(: fp2log (float float -> float float))
(define (fp2log x2 x1)
(define x (fp+ x1 x2))
(cond [(fp<= x 0.0) (cond [(fp= x 0.0) (values -inf.0 0.0)]
[else (values +nan.0 0.0)])]
[(fp= x +inf.0) (values +inf.0 0.0)]
[(or (fp< x 0.5) (fp> x 2.5))
;; Reduce arguments
(let*-values ([(k x2 x1) (fp2log-reduction x2 x1)]
[(y2 y1) (fp2log x2 x1)]
[(z2 z1) (fp2* log2-hi log2-lo k)])
(fp2- y2 y1 z2 z1))]
[else
;; Estimate log(x) and do a Newton iteration using expm1
(let*-values ([(y) (fplog+ x2 x1)]
[(x2 x1) (fp2+ x2 x1 -1.0)]
[(z2 z1) (fpexpm1/error y)]
[(w2 w1) (fp2+ z2 z1 1.0)]
[(dy2 dy1) (fp2- x2 x1 z2 z1)]
[(dy2 dy1) (fp2/ dy2 dy1 w2 w1)])
(fp2+ dy2 dy1 y))]))
;; ===================================================================================================
;; log1p
#|
Argument reduction for log1p:
log1p(x) = k*log(2) + log1p(x/2^k + (1/2^k - 1))
A `k' that reduces any argument `x' to (-1/2,1/2) is
k = round(log1p(x)/log(2))
|#
(: fp2log1p-reduction (float float float float float -> float float float))
(define (fp2log1p-reduction x2 x1 a2 a1 y)
(define k (fpround (fp/ y (fplog 2.0))))
(define 2^k (fpexpt 2.0 k))
(define-values (j2 j1) (fast-fp-/error (/ 1.0 2^k) 1.0))
(let*-values ([(x2 x1) (values (/ x2 2^k) (/ x1 2^k))]
[(x2 x1) (fp2+ x2 x1 j2 j1)])
(values k x2 x1)))
(: fp2log1p (float float -> float float))
(define (fp2log1p x2 x1)
(define-values (a2 a1) (fp2+ x2 x1 1.0))
(define y (fplog+ a2 a1))
(cond
[(or (fp< y -0.5) (fp> a2 2.0)) (fp2log a2 a1)]
[(fp= (fp+ x2 x1) 0.0) (values x2 0.0)]
[(fp> y 0.5)
(let*-values ([(k x2 x1) (fp2log1p-reduction x2 x1 a2 a1 y)]
[(y2 y1) (fp2log1p x2 x1)]
[(z2 z1) (fp2* log2-hi log2-lo k)])
(fp2+ y2 y1 z2 z1))]
[else
(let*-values ([(z2 z1) (fpexpm1/error y)]
[(w2 w1) (fp2+ z2 z1 1.0)]
[(dy2 dy1) (fp2- x2 x1 z2 z1)]
[(dy2 dy1) (fp2/ dy2 dy1 w2 w1)])
(fp2+ dy2 dy1 y))])))
| false |
bbb09db3af3ff28f9eb3b33149952af3998ab4c8 | a09ad3e3cf64bc87282dea3902770afac90568a7 | /5/21.scm | 6d64162bb6fce41d35862355ad993bd7798b75ca | []
| no_license | lockie/sicp-exercises | aae07378034505bf2e825c96c56cf8eb2d8a06ae | 011b37387fddb02e59e05a70fa3946335a0b5b1d | refs/heads/master | 2021-01-01T10:35:59.759525 | 2018-11-30T09:35:35 | 2018-11-30T09:35:35 | 35,365,351 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 2,478 | scm | 21.scm |
;; a
(define count-leaves-recursive-machine
(make-machine
'(t tmp r continue) ; registers
(list
(list 'null? null?)
(list 'pair? pair?)
(list 'car car)
(list 'cdr cdr)
(list '+ +)) ; ops
'(
(assign continue (label count-leaves-done))
count-leaves-loop
(test (op null?) (reg t))
(branch (label null))
(test (op pair?) (reg t))
(branch (label recurse))
(assign r (const 1))
(goto (reg continue))
recurse
(save continue)
(assign continue (label after-count-1))
(save t)
(assign t (op car) (reg t))
(goto (label count-leaves-loop))
after-count-1
(restore t)
(restore continue)
(save r)
(save continue)
(assign continue (label after-count-2))
(assign t (op cdr) (reg t))
(goto (label count-leaves-loop))
after-count-2
(restore continue)
(assign tmp (reg r))
(restore r)
(assign r (op +) (reg r) (reg tmp))
(goto (reg continue))
null
(assign r (const 0))
(goto (reg continue))
count-leaves-done)))
(set-register-contents! count-leaves-recursive-machine 't '((1 (2 3)) 4))
(start count-leaves-recursive-machine)
(get-register-contents count-leaves-recursive-machine 'r)
;; b
(define count-leaves-recursive-machine2
(make-machine
'(t n r continue) ; registers
(list
(list 'null? null?)
(list 'pair? pair?)
(list 'car car)
(list 'cdr cdr)
(list '+ +)) ; ops
'(
(assign n (const 0))
(assign continue (label count-leaves-done))
count-iter
(test (op null?) (reg t))
(branch (label null))
(test (op pair?) (reg t))
(branch (label recurse))
(assign r (op +) (reg n) (const 1))
(goto (reg continue))
recurse
(save t)
(assign t (op car) (reg t))
(save continue)
(assign continue (label after-count-1))
(goto (label count-iter))
after-count-1
(restore continue)
(restore t)
(assign t (op cdr) (reg t))
(assign n (reg r))
(goto (label count-iter))
null
(assign r (reg n))
(goto (reg continue))
count-leaves-done)))
(set-register-contents! count-leaves-recursive-machine2 't '((1 (2 3)) 4))
(start count-leaves-recursive-machine2)
(get-register-contents count-leaves-recursive-machine2 'r)
| false |
7997d69852812aa3eb23218bc6b4325328d424c8 | 120324bbbf63c54de0b7f1ca48d5dcbbc5cfb193 | /packages/slib/srfi-2.scm | adb253081332a6ec8221c35a63a541d7b86f3fb6 | [
"MIT"
]
| permissive | evilbinary/scheme-lib | a6d42c7c4f37e684c123bff574816544132cb957 | 690352c118748413f9730838b001a03be9a6f18e | refs/heads/master | 2022-06-22T06:16:56.203827 | 2022-06-16T05:54:54 | 2022-06-16T05:54:54 | 76,329,726 | 609 | 71 | MIT | 2022-06-16T05:54:55 | 2016-12-13T06:27:36 | Scheme | UTF-8 | Scheme | false | false | 1,443 | scm | srfi-2.scm | ;;"srfi-2.scm": Guarded LET* special form
;Copyright (C) 2003 Aubrey Jaffer
;
;Permission to copy this software, to modify it, to redistribute it,
;to distribute modified versions, and to use it for any purpose is
;granted, subject to the following restrictions and understandings.
;
;1. Any copy made of this software must include this copyright notice
;in full.
;
;2. I have made no warranty or representation that the operation of
;this software will be error-free, and I am under no obligation to
;provide any services, by way of maintenance, update, or otherwise.
;
;3. In conjunction with products arising from the use of this
;material, there shall be no use of my name in any advertising,
;promotional, or sales literature without prior written consent in
;each case.
;;@code{(require 'srfi-2)}
;;@ftindex srfi-2
;;@body
;;@url{http://srfi.schemers.org/srfi-2/srfi-2.html}
(defmacro and-let* (claws . body)
(define (andin claw ans)
(if (and (pair? ans) (eq? 'and (car ans)))
`(and ,claw ,@(cdr ans))
`(and ,claw ,ans)))
(do ((claws (reverse claws) (cdr claws))
(ans (cond ((null? body) '(and))
((null? (cdr body)) (car body))
(else (cons 'begin body)))
(let ((claw (car claws)))
(cond ((symbol? claw)
(andin claw ans))
((and (pair? claw) (null? (cdr claw)))
(andin (car claw) ans))
(else
`(let (,claw) ,(andin (car claw) ans)))))))
((null? claws) ans)))
| false |
f478af67ab638b0e98cd6b67b11592c6400ad6d6 | 2fea3118be4354a114e675615432f39fbd64ec6b | /previous-attempts/previous-attempts.scm | e2f907ef04e1ed9ec457b51d51ea0c833f0e2fe0 | []
| no_license | orinatic/Match-Define | b9866e54fbb8d6b32de589c7db9f6a4170d807b3 | c7a3d5fab231ed38afd3a53dafd51a96aca78cbd | refs/heads/master | 2021-01-19T05:36:54.815897 | 2015-05-13T05:53:10 | 2015-05-13T05:53:10 | 34,953,341 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 6,953 | scm | previous-attempts.scm | ;;the code that actually runs the matcher
(define (*run-match* vars pattern)
((match:->combinators vars) pattern '() (lambda (d n) d)))
;;If we decide to go with the macro system
;;system, we're contemplating overwriting the actual definitions of
;;let, let*, define, etc with these match versions (as the match
;;versions are backwards compatible).
;; Our eval-environment system isn't fully backwards-compatible yet
;; (the expressions in the let statement need to be made into an
;; alist. If they're used with a match statement as well, then the
;; caller needs to append the expressions with the output of the call
;; to *run-match*, as in
;;
;;((dict-let (append (*run-match* '((? y) (? x)) '((1 2))) '((d 5)))
;; (+ d x y 400)))
;;
;;Please see the final report for a full API for the macros and
;;eval-environment system, along with the API for our repl version.
;Our define macro
(define-syntax match-define
(sc-macro-transformer
(lambda (exp env)
(let* ((vars (cadr exp))
(vals (caddr exp))
(dict (*run-match* vars vals)))
(if dict
;(pp
`(begin
,@(map (lambda(entry)
(let ((val
(close-syntax (cadr entry) env)))
`(define ,(car entry) ,val)))
dict))
`(pp 'failed-match))))));)
;A helper assign function
(define (assign-iter todo done)
(if (null? todo)
(filter pair? done)
(let* ((assign (car todo))
(vars (car assign))
(vals (cadr assign)))
(if (identifier? vars)
(assign-iter (cdr todo) (append done (list assign)))
(assign-iter
(cdr todo)
(append done (or (*run-match* vars vals)
(begin (warn 'match-failed-in-let)
'()))))))))
;Our let macro
(define-syntax match-let
(sc-macro-transformer
(lambda (exp env)
(let* ((body (cddr exp))
(dict (assign-iter (cadr exp) '())))
`(let ( ,@(map (lambda(entry)
`(,(car entry) ,(cadr entry)))
dict))
(begin ,@(map (lambda (statement)
statement)
body)))
))))
;Our let* macro
(define-syntax match-let*
(sc-macro-transformer
(lambda (exp env)
(let* ((body (cddr exp))
(dict (assign-iter (cadr exp) '())))
`(let* ( ,@(map (lambda(entry)
`(,(car entry) ,(cadr entry)))
dict))
(begin ,@(map (lambda (statement)
statement)
body)))))))
;Our letrec macro
(define-syntax match-letrec
(sc-macro-transformer
(lambda (exp env)
(let* ((body (cddr exp))
(dict (assign-iter (cadr exp) '())))
`(letrec ( ,@(map (lambda(entry)
`(,(car entry) ,(cadr entry)))
dict))
(begin ,@(map (lambda (statement)
statement)
body)))
))))
;The macro for named-let.
(define-syntax match-named-let
(sc-macro-transformer
(lambda (exp env)
(let* ((name (cadr exp))
(body (cdddr exp))
(dict (assign-iter (caddr exp) '())))
`(let ,name ( ,@(map (lambda(entry)
`(,(car entry) ,(cadr entry)))
dict))
(begin ,@(map (lambda (statement)
statement)
body)))))))
;;;; Our dict-let macro, which attempts to use the environment-eval
;;;; trick.
;;;; Does not allow the body to use variables that are defined
;;;; externally. We're working on a fix for this.
(define-syntax dict-let
(sc-macro-transformer
(lambda (exp env)
(let ((dict (cadr exp))
(body (caddr exp)))
`(lambda ()
(define (empty a) 'nothing)
(let ((our-env (procedure-environment empty)))
(let dict-define-loop ((todo ,dict))
(if (null? todo)
'done
(let ((var (caar todo))
(val (cadar todo)))
(environment-define our-env var val)
(dict-define-loop (cdr todo)))))
(eval ,body our-env)))))))
;;;; Match-define tests
(match-define ((? y) (? x)) ((1 2)))
;x->2
;y->1
(match-define ((? y) (? x)) ((1)))
;failed-match
;;;; Match-let tests
(match-let ((((? y) (? x)) ((1 2)))
(d 5))
(+ d x y)) ;-> 8
(match-let ((((? y) (? x)) ((1 2))))
(+ x y)) ;-> 3
(match-let ((((? r)) ((4 2)))
(d 5))
d)
;-> Warning: match-failed-in-let
;5
(match-let ((((? y)) ((1 2))))
(+ x y))
;Warning: match-failed-in-let
;3
(match-let ((((? y)) ((4 2)))
(d 5))
d)
;Warning: match-failed-in-let
;5
;
;;;;Match-let* tests
(match-let* ((((? y) (? x)) ((1 2)))
(d (+ y x)))
(+ d x y)) ;-> 6
(match-let* ((((? y) (? x)) ((1 2)))
(((? c) (? d)) (((+ 3 x) y))))
(+ c d x y)) ;-> 9
;;;; Match-letrec tests
;;Letrec test cases!
;This test case taken from the MIT Scheme Documentation
(match-letrec ((even?
(lambda (n)
(if (zero? n)
#t
(odd? (- n 1)))))
(odd?
(lambda (n)
(if (zero? n)
#f
(even? (- n 1))))))
(even? 88))
;#t Success!
(match-letrec ((((? y) (? x)) ((1 2)))
(d 5))
(+ d x y)) ;-> 8
(match-letrec ((((? y) (? x)) ((1 2))))
(+ x y)) ;-> 3
(match-letrec ((((? r)) ((4 2)))
(d 5))
d)
;Warning: match-failed-in-let
;Value: 5
;;checking letrec
(match-letrec ((even?
(lambda (n)
(if (zero? n)
(begin
(pp y)
#t)
(odd? (- n 1)))))
(((? y) (? x)) ((1 2)))
(odd?
(lambda (n)
(if (zero? n)
(begin
(pp x)
#f)
(even? (- n 1))))))
(even? 88))
;1
;Value: #t
;Success!
;checking if letrec works. We letrec even? and odd? (which call each
;other) and then letrec four? and five? (which call each other) and
;then call four?
(match-letrec ((even?
(lambda (n)
(if (zero? n)
(begin
(pp y)
#t)
(odd? (- n 1)))))
(((? y) (? x)) ((1 2)))
(odd?
(lambda (n)
(if (zero? n)
(begin
(pp x)
#f)
(even? (- n 1))))))
(if (odd? x) ;this should be false, as x should be 2
(even? y)
(match-letrec ((four?
(lambda (n)
(if (zero? (- n 4))
n
(five? (- n 1)))))
(five?
(lambda (n)
(if (zero? (- n 5))
n
(even? (- n 1))))))
(four? 500))))
;2
;Value: #t
;Success!
;yes, four? and five? are dumb functions, but we can do nested
;match-letrecs and it works, which is what we were trying to test!
;;;;; Match-named-let testing
;Borrowed from the MIT Scheme documentation
;This aims to test if named let actually works
(match-named-let loop
((numbers '(3 -2 1 6 -5))
(nonneg '())
(neg '()))
(cond ((null? numbers)
(list nonneg neg))
((>= (car numbers) 0)
(loop (cdr numbers)
(cons (car numbers) nonneg)
neg))
(else
(loop (cdr numbers)
nonneg
(cons (car numbers) neg)))))
; ((6 1 3) (-5 -2))
;Success!
;Another test for named-let
(match-named-let godeeper
((cat 'yayyoufinished)
(noodles '(1 2 3 4 5 6)))
(if (null? noodles)
cat
(godeeper cat (cdr noodles))))
;yayyoufinished
;Success!
| true |
505799b7f94390f1c8d310d3e4ad687d19ced75b | 8dc3d1218b88ef245d39dea08b8c9488ddc20905 | /naturalize.scm | 6229d0d54a0adc90f48465699cc8c2919af9a391 | []
| no_license | amoe/anankasm | 77b121246d82d8e1708cecedf6df08c76ffe5afa | d5e4af9ab3380fa7e190d52ccdfba64e9c784737 | refs/heads/master | 2022-10-22T19:58:25.729190 | 2022-09-23T07:16:34 | 2022-09-23T07:16:34 | 26,482,606 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 6,937 | scm | naturalize.scm | #lang racket
(require scheme/string)
(require scheme/system)
(require srfi/1) ; list library
(require srfi/26) ; cut & cute
(require srfi/64)
(require (prefix-in taglib: "taglib.scm"))
(require (prefix-in munge-tag: "munge-tag.scm"))
(require "histogram.scm")
(require "interface.scm")
(require "options.scm")
(require "replaygain.scm")
(provide main)
(define *tag-map*
(list
(cons 'artist (cons taglib:tag-artist taglib:tag-set-artist))
(cons 'album (cons taglib:tag-album taglib:tag-set-album))
(cons 'tracknumber (cons taglib:tag-track taglib:tag-set-track))
(cons 'title (cons taglib:tag-title taglib:tag-set-title))
(cons 'date (cons taglib:tag-year taglib:tag-set-year))
(cons 'genre (cons taglib:tag-genre taglib:tag-set-genre))))
; ENTRY POINT
(define (main . args)
(check-commands)
(let ((args (configure args)))
(check-permissions args)
(let ((times (save-mtimes args)))
(define (cleanup v) (load-mtimes args times))
(with-handlers ((exn:break? cleanup))
(let ((tmpl (pass-to-editor (apply files->template args))))
(printf "parsed template as ~s" tmpl)
(strip-tags args)
(apply-tags tmpl args)
(display "applying replaygain... ")
(flush-output)
(unless (option 'skip-replaygain)
(replaygain args))
(say "done.")
(load-mtimes args times)
(move-files tmpl args))))))
(define (check-permissions lst)
(when (not (every writable? lst))
(error 'check-permissions
"not all files are writable, please fix and rerun")))
(define (check-commands)
(let loop ((required-executables '("replaygain" "eyeD3")))
(when (not (null? required-executables))
(let ((command (car required-executables)))
(when (not (find-executable-path command))
(error 'check-commands "command not found: ~a" command)))
(loop (cdr required-executables)))))
(define (files->template . args)
(define tags
(map
(lambda (tag)
(cons tag
(apply select-from-tags
(cons (lookup-getter tag) args))))
(global-tag-list)))
(define tracks
(let ((track-indices (iota (length args) 1)))
(map
(lambda (file index)
(map (lambda (tag)
(if (and (eq? tag 'tracknumber)
(option 'number-automatically))
index
(tag-proc/cleanup (lookup-getter tag) file)))
(local-tag-list)))
args track-indices)))
(let ((result (cons tags tracks)))
(printf "using result: ~s" result)
result))
(define (strip-tags args)
(debug "stripping tags")
(apply run-command
(append (list *default-eyed3* "--remove-all" "--no-color")
args)))
(define (apply-tags tmpl files)
(say "writing tags...")
(printf "global tags are apparently ~s" (template:global-tags tmpl))
(for-each
(lambda (t) (apply-one-tag t files))
(template:global-tags tmpl))
(apply-local-tags (template:local-tags tmpl) files))
(define (move-files tmpl files)
(debug "moving files to correct locations")
(for-each
(lambda (old new)
(make-parents new)
(rename-file-or-directory old new #t)) ; we don't care if it exists
files (template->new-names tmpl files)))
; Make the parents of PATH
(define (make-parents path)
(let-values (((base name must-be-dir?)
(split-path path)))
(make-directory* base)))
(define (identity x) x)
(define *abbreviated-tag-map*
(list
(cons "a" (cons 'artist identity))
(cons "A" (cons 'album identity))
(cons "t" (cons 'title identity))
(cons "T" (cons 'tracknumber (compose (cute zero-pad <> 2) number->string)))
(cons "d" (cons 'date number->string))
(cons "g" (cons 'genre identity))))
(define (zero-pad str len)
(let ((diff (- len (string-length str))))
(if (positive? diff)
(string-append (make-string diff #\0) str)
str)))
; We can only build part of the list at the start so this is not valid
(define (template->new-names tmpl files)
(let ((ga (build-global-abbrevs tmpl)))
(map
(lambda (lt file)
(let ((la (build-local-abbrevs lt)))
(append-extension
(xformat (filename-template)
(append ga la))
file)))
(template:local-tags tmpl) files)))
; Append the extension of old to new, if there was one
(define (append-extension new old)
(let ((ext (filename-extension old)))
(if ext
(string-append new "." (bytes->string/locale ext))
old)))
(define (build-local-abbrevs lt)
(filter-map
(lambda (abbrev)
(let ((proc (cddr abbrev)))
(cond
((list-index (cute eq? <> (cadr abbrev)) (local-tag-list))
=> (lambda (idx)
(cons (car abbrev)
(munge-tag:munge-tag
(proc (list-ref lt idx))))))
(else #f))))
*abbreviated-tag-map*))
(define (build-global-abbrevs tmpl)
(let ((gt (template:global-tags tmpl)))
(map
(lambda (abbrev)
(let ((proc (cddr abbrev)))
(cons
(car abbrev)
(munge-tag:munge-tag
(proc (cdr (assq (cadr abbrev) gt)))))))
(filter
(lambda (abbrev)
(memq (cadr abbrev) (global-tag-list)))
*abbreviated-tag-map*))))
; At the moment we're not displaying the histogram frequencies to the user,
; we're just sorting by them, so option 1 always has the highest frequency
(define (select-from-tags get-tag . args)
(let ((tags (map (lambda (f) (tag-proc/cleanup get-tag f)) args)))
(let ((hist (sort (histogram tags) frequency>?)))
(if (just-one? hist)
(caar hist)
(choose (map car hist) 1)))))
(define (lookup-getter tag)
(cadr (assq tag *tag-map*)))
(define (lookup-setter tag)
(cddr (assq tag *tag-map*)))
(define (save-mtimes files)
(map file-or-directory-modify-seconds files))
(define (load-mtimes files times)
(for-each file-or-directory-modify-seconds files times))
(define (just-one? lst) (= (length lst) 1))
(define (tag-proc/cleanup proc file)
(let ((f (taglib:file-new file)))
(let ((datum (proc (taglib:file-tag f))))
(taglib:file-save f)
(taglib:file-free f)
datum)))
(define template:global-tags car)
(define template:local-tags cdr)
(define (apply-local-tags lt files)
(for-each
(lambda (local-tag file)
(for-each
(lambda (key val)
(tag-proc/cleanup
(lambda (t)
((lookup-setter key) t val))
file))
(local-tag-list) local-tag))
lt files))
(define (apply-one-tag tag files)
(for-each
(lambda (file)
(tag-proc/cleanup
(let ((set-tag (lookup-setter (car tag))))
(lambda (t) (set-tag t (cdr tag))))
file))
files))
| false |
5ada66dfd37187f9554cbb5803375d3f7b4b052b | ece1c4300b543df96cd22f63f55c09143989549c | /Chapter2/Exercise 2.12.scm | f396e6a41694bc16271efc2b453d4061e44deadc | []
| no_license | candlc/SICP | e23a38359bdb9f43d30715345fca4cb83a545267 | 1c6cbf5ecf6397eaeb990738a938d48c193af1bb | refs/heads/master | 2022-03-04T02:55:33.594888 | 2019-11-04T09:11:34 | 2019-11-04T09:11:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 2,189 | scm | Exercise 2.12.scm | ; After debugging her program, Alyssa shows it to a potential user, who complains that her program solves the wrong problem. He wants a program that can deal with numbers represented as a center value and an additive tolerance; for example, he wants to work with intervals such as 3.5 ±± 0.15 rather than [3.35, 3.65]. Alyssa returns to her desk and fixes this problem by supplying an alternate constructor and alternate selectors:
; (define (make-center-width c w)
; (make-interval (- c w) (+ c w)))
; (define (center i)
; (/ (+ (lower-bound i)
; (upper-bound i))
; 2))
; (define (width i)
; (/ (- (upper-bound i)
; (lower-bound i))
; 2))
; Unfortunately, most of Alyssa’s users are engineers. Real engineering situations usually involve measurements with only a small uncertainty, measured as the ratio of the width of the interval to the midpoint of the interval. Engineers usually specify percentage tolerances on the parameters of devices, as in the resistor specifications given earlier.
; Exercise 2.12: Define a constructor make-center-percent that takes a center and a percentage tolerance and produces the desired interval. You must also define a selector percent that produces the percentage tolerance for a given interval. The center selector is the same as the one shown above.
#lang planet neil/sicp
(define (make_interval a b) (cons a b))
(define (upper_bound x) (car x))
(define (lower_bound x) (cdr x))
(define (make_center_width c w)
(make_interval (- c w) (+ c w)))
(define (center i)
(/ (+ (lower_bound i)
(upper_bound i))
2))
(define (width i)
(/ (- (upper_bound i)
(lower_bound i))
2))
(define (make_center_percentage c p)
(make_center_width c (* c p))
)
(define (percentage x)
(let
(
(c (center x))
)
(if
(= c (upper_bound x))
0
(/ (- (lower_bound x) c) c)
)
)
)
(define a (make_center_percentage 10 (/ 1 10)))
(center a)
(percentage a)
``````````````````````````````
Welcome to DrRacket, version 6.6 [3m].
Language: planet neil/sicp, with debugging; memory limit: 128 MB.
10
1/10
> | false |
74a311d03b409b5a0cbf46c81762cbfc46aa5c8f | 92b8d8f6274941543cf41c19bc40d0a41be44fe6 | /testsuite/let1.scm | 9545c72b05995b23401a2cc808fbff8a9f9a2858 | [
"MIT"
]
| permissive | spurious/kawa-mirror | 02a869242ae6a4379a3298f10a7a8e610cf78529 | 6abc1995da0a01f724b823a64c846088059cd82a | refs/heads/master | 2020-04-04T06:23:40.471010 | 2017-01-16T16:54:58 | 2017-01-16T16:54:58 | 51,633,398 | 6 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 144 | scm | let1.scm | (let ((bar (let ((abck (lambda () "Ok."))) abck)))
(let ((baz (list (bar))))
(let ((foo (bar))) (format #t "~a~%" foo))))
;; Output: Ok.
| false |
9efdc32d807f20eb60fc34585b2c01dd83fc2caa | bbf024156a05ec1b70df909cce6c7afcff454fef | /pred-to-scores.scm | dcd6917db2d81882b06b3ef54a201660a1f02eb4 | []
| no_license | rachelbasse/hmm-np-chunker | 5167a7923ac94e7b3fd157ffff84f7d69851f97e | 764691063ac050c92b0eba1f2cf9ba38329f4ec4 | refs/heads/master | 2020-03-21T06:11:27.558971 | 2018-06-21T20:32:37 | 2018-06-21T20:32:37 | 138,204,706 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 3,600 | scm | pred-to-scores.scm | ;;;; HELLO! I generate the measures in measures.txt.
;;;; BEFORE you load me, load lib, enc-testing, hmm, and pred.
; initialize counts
(define count-env (extend-top-level-environment user-initial-environment))
(vector-map
(lambda (n)
(eval (list 'define n 0) count-env))
#(x0x0 x0x1 x0x2 x1x0 x1x1 x1x2 x2x0 x2x1 x2x2 x0 x1 x2))
; compare predicted state-sequences with actual state-sequences
; <compare!> takes two matrices and compares their respective entries.
(define compare! (lambda (predicted actual)
(if (zero? (vector-length predicted))
'done
(begin (vector-for-each
(lambda (pred act)
(if (= pred act)
(eval (list 'inc! (symbol 'x act)) count-env)
(eval (list 'inc! (symbol 'x act 'x pred)) count-env)))
(vector-head predicted) (vector-head actual))
(compare! (vector-behead predicted) (vector-behead actual))))))
(compare! prediction-matrix enc-state-matrix)
; define measures
(define tp (lambda (lit) (eval lit count-env)))
(define fp (lambda (lit)
(eval (list '+ (symbol 'x0 lit) (symbol 'x1 lit) (symbol 'x2 lit)) count-env)))
(define fn (lambda (lit)
(eval (list '+ (symbol lit 'x0) (symbol lit 'x1) (symbol lit 'x2)) count-env)))
(define precision (lambda (lit)
(if (zero? (tp lit))
1
(exact->inexact (/ (tp lit) (+ (tp lit) (fp lit)))))))
(define recall (lambda (lit)
(if (zero? (tp lit))
1
(exact->inexact (/ (tp lit) (+ (tp lit) (fn lit)))))))
(define f-measure (lambda (lit)
(if (zero? (+ (precision lit) (recall lit)))
1
(/ (* 2 (precision lit) (recall lit))
(+ (precision lit) (recall lit))))))
(define state-measure-list '(I B O Avg))
(define i (symbol 'x 2))
(define b (symbol 'x 0))
(define o (symbol 'x 1))
(define prec-i (precision i))
(define prec-b (precision b))
(define prec-o (precision o))
(define prec-avg (/ (+ prec-i prec-b prec-o) 3))
(define rec-i (recall i))
(define rec-b (recall b))
(define rec-o (recall o))
(define rec-avg (/ (+ rec-i rec-b rec-o) 3))
(define f-i (f-measure i))
(define f-b (f-measure b))
(define f-o (f-measure o))
(define f-avg (/ (+ f-i f-b f-o) 3))
(define percent (lambda (n) (* n 100.)))
(define prec-list (map percent (list prec-i prec-b prec-o prec-avg)))
(define rec-list (map percent (list rec-i rec-b rec-o rec-avg)))
(define f-list (map percent (list f-i f-b f-o f-avg)))
(define accuracy
(percent (/ (eval '(+ x0 x1 x2) count-env)
(eval '(+ x0x0 x0x1 x0x2 x1x0 x1x1 x1x2 x2x0 x2x1 x2x2
x0 x1 x2)
count-env))))
(define error-list
(map
(lambda (lit)
(eval lit count-env))
'(x0x1 x0x2 x1x0 x1x2 x2x0 x2x1)))
; write measures to file scores.txt
(define scores (open-output-file "scores.txt" #t))
(set-current-output-port! scores)
(write-string
"\n================================================================================\nRESULTS FOR: Smoothing: ")
(write opt-smooth-type)
(write-string " at strength ")
(write opt-smooth-param)
(write-string ";\nLog-space: ")
(write opt-log)
(write-string "; Emissions: ")
(write opt-emit)
(write-string "; Double-count: ")
(write opt-double-count)
(write-string ".\n\nAccuracy: ")
(write accuracy)
(write-string "\nKey: ")
(write state-measure-list)
(write-string "\nPrecision: ")
(write prec-list)
(write-string "\nRecall: ")
(write rec-list)
(write-string "\nF-Measure: ")
(write f-list)
(write-string "\n(BpO BpI OpB OpI IpB IpO): ")
(write error-list)
(flush-output)
(close-all-open-files)
;; THE END
| false |
557cc385632e3554de3f6eba19dc0d7ad685beb0 | 000dbfe5d1df2f18e29a76ea7e2a9556cff5e866 | /sitelib/util/concurrent/pipeline.scm | d1cf39c142734b704a01f0dca4b88594b1c5e9da | [
"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 | 2,477 | scm | pipeline.scm | ;;; -*- mode: scheme; coding: utf-8 -*-
;;;
;;; util/concurrent/pipeline.scm - Concurrent pipeline
;;;
;;; Copyright (c) 2018 Takashi Kato <[email protected]>
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; 2. Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
(library (util concurrent pipeline)
(export )
(import (rnrs)
(util concurrent actor)
(util concurrent shared-queue))
(define-record-type pipe-error
(seald #t)
(fields condition message))
(define-record-type pipe-stop-message
(seald #t))
(define *pipe:stop-message* (make-pipe-stop-message))
(define-record-type pipe-unit
(parent <actor>)
(fields error-receiver)
(lambda (n)
(lambda (proc make-receiver make-sender make-error-sender)
(let-values (((error-receiver/client error-sender/actor)
(make-error-sender)))
((n (lambda (receiver sender)
(define stop? #f)
(let loop ((msg (receiver)))
(guard (e (else (error-sender/actor (make-pipe-error e msg))))
(let ((r (proc msg)))
(when (pipe-stop-message? r) (set! stop? #t))
(sender r)))
(unless stop? (loop (receiver)))))
make-sender make-error-sender #f)
error-receiver/client)))))
)
| false |
88d8ce763e8c3eb904c32b7ae5cf96dbe7ae3fe6 | abc7bd420c9cc4dba4512b382baad54ba4d07aa8 | /src/ws/sim/simulator_alpha_datatypes.ss | e9bacaebd714004f940205a4221700e3dd3ba19e | [
"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 | 15,890 | ss | simulator_alpha_datatypes.ss | ;; simulator_alpha_datatypes.ss
;; [2005.10.18] This file encapsulates the datatype definitions and
;; global parameters used by the simulator.
;; NOTE: If I had this to do over again I would use some kind of oop system.
;; There is basically a class-hierarchy three deep:
;; NODE -- Basic information about a node.
;; |-> SIMOBJECT -- State associated with the simulator
;; |-> GOBJECT -- State associated with the visualization of the simulator.
(module simulator_alpha_datatypes mzscheme
(require ;(all-except (lib "compat.ss") reg:define-struct) ;; gives us reg:define-struct
(lib "include.ss")
(all-except "../constants.ss" test-this these-tests)
(all-except "../util/helpers.ss" id flush-output-port test-this these-tests)
"../../plt/iu-match.ss"
"../util/hash.ss"
"../../plt/hashtab.ss"
"../compiler_components/logfiles.ss"
)
(provide
; simalpha-total-messages
; simalpha-total-tokens
; logger
evntlessthan
soc-return-buffer
escape-alpha-sim
posdist
;; Global parameter: temporary, for debugging:
global-graph
token->key key->token
invcheck-simworld
invcheck-simobject
simtok-equal?
node->simobject ;; Constructor.
bare-msg-object ;; Safe msg-object constructor.
;;==================================================
;; HACK: FIXME : FIND A BETTER SYSTEM
make-simworld
simworld?
simworld-graph
simworld-object-graph
simworld-all-objs
simworld-obj-hash
simworld-scheduler-queue
simworld-vtime
simworld-led-toggle-states
simworld-connectivity-function
set-simworld-graph!
set-simworld-object-graph!
set-simworld-all-objs!
set-simworld-obj-hash!
set-simworld-scheduler-queue!
set-simworld-vtime!
set-simworld-led-toggle-states!
set-simworld-connectivity-function!
make-simevt
simevt?
simevt-vtime
simevt-msgobj
set-simevt-vtime!
set-simevt-msgobj!
make-simtok
simtok?
simtok-name
simtok-subid
set-simtok-name!
set-simtok-subid!
make-node
node?
node-id
node-pos
set-node-id!
set-node-pos!
make-simobject
simobject?
simobject-node
simobject-I-am-SOC
simobject-token-store
simobject-incoming-msg-buf
simobject-local-msg-buf
simobject-outgoing-msg-buf
simobject-timed-token-buf
simobject-local-sent-messages
simobject-local-recv-messages
simobject-token-table
simobject-redraw
simobject-gobj
simobject-homepage
simobject-scheduler
simobject-meta-handler
simobject-worldptr
set-simobject-node!
set-simobject-I-am-SOC!
set-simobject-token-store!
set-simobject-incoming-msg-buf!
set-simobject-local-msg-buf!
set-simobject-outgoing-msg-buf!
set-simobject-timed-token-buf!
set-simobject-local-sent-messages!
set-simobject-local-recv-messages!
set-simobject-token-table!
set-simobject-redraw!
set-simobject-gobj!
set-simobject-homepage!
set-simobject-scheduler!
set-simobject-meta-handler!
set-simobject-worldptr!
make-gobject
gobject?
gobject-circ
gobject-rled
gobject-gled
gobject-bled
gobject-title
gobject-label
gobject-edgelist
set-gobject-circ!
set-gobject-rled!
set-gobject-gled!
set-gobject-bled!
set-gobject-title!
set-gobject-label!
set-gobject-edgelist!
make-msg-object
msg-object?
msg-object-token
msg-object-sent-time
msg-object-parent
msg-object-to
msg-object-args
set-msg-object-token!
set-msg-object-sent-time!
set-msg-object-parent!
set-msg-object-to!
set-msg-object-args!
;;==================================================
)
(chezimports scheme)
; =======================================================================
;; This structure contains all the global data needed by a simulation.
;; (Well, that's a bit of a lie, because the simulator also requires a
;; number of global parameters to be set appropropriately.)
(reg:define-struct
(simworld ;; Hard state:
graph
;; Soft state:
object-graph all-objs
;; obj-hash maps node-ids onto simobjects:
obj-hash
;; This is a pointer to the queue used by the scheduler.
;; It's a sorted list of simevts?
scheduler-queue
;; This is updated by the scheduler, the current global vtime.
vtime
;; [2005.11.07] A hash table mapping node-ids to a list of all the leds that are toggled on.
;; Could have added this to the simobject structure, but I'm reluctant, as it is only a presentation detail:
led-toggle-states
;; This is a function which models the channels, it takes two locations and returns either:
;; 1) a number, representing a fixed loss percentage
;; 2) a function of time, representing the loss percentage over time
connectivity-function
))
;; Sanity checker for simworld.
;; Fairly heavy weight, probably don't want to run constantly.
;; Keep this up to date with changing data structure invariants.
;;
;; This is not fully defensive, so if there is a corruption in the
;; data-structure, you may get any number of different of errors. But
;; you will get some kind of error. Anything that goes through is as
;; clean as we can certify.
;;
;; You can improve the error messages as needed. Even on the fly if
;; you encounter a violation.
(define (invcheck-simworld w)
(ASSERT (simworld? w))
;; Check graph-of-nodes
(let ((g (simworld-graph w)))
(ASSERT (list? g)) ;; Don't have to check explicitely
(ASSERT (andmap list? g))
(ASSERT (andmap (lambda (row) (andmap node? row)) g)))
;; Check graph-of-simobject, plus sanity check simobjects:
(let ((og (simworld-object-graph w)))
(ASSERT (list? og))
(ASSERT (andmap list? og))
(ASSERT (andmap (lambda (row) (andmap invcheck-simobject row)) og))
;; Make sure the simobjects correspond physically to the nodes.
(ASSERT (set-eq? (list->set (map simobject-node (map car og)))
(list->set (map car (simworld-graph w))))))
;; Make sure the hash-table contains the same substance as the object-graph.
(let ((hsh (hashtab->list (simworld-obj-hash w))))
(for-each (lambda (pr)
(ASSERT (= (car pr) (node-id (simobject-node (cdr pr)))))) hsh)
(ASSERT (set-eq? (list->set (map cdr hsh))
(list->set (map car (simworld-object-graph w))))))
;; Check vtime.
(ASSERT (integer? (simworld-vtime w)))
;; Check led-toggle-states
(let ([hsh (hashtab->list (simworld-led-toggle-states w))]
[ids (map node-id (map car (simworld-graph w)))])
(for-each (lambda (pr)
(ASSERT (memq (car pr) ids))
(ASSERT (list-subsetq? (cdr pr) '(red green blue))))
hsh))
;; Check connectivity-function, not much to say here.
(ASSERT (or (not (simworld-connectivity-function w))
(procedure? (simworld-connectivity-function w))))
#t)
;; [2005.03.13] Adding this to represent events-to-happen in the simulator.
(reg:define-struct (simevt vtime msgobj))
;; [2005.05.06]
;; A first class representation of tokens:
(reg:define-struct (simtok name subid))
;; TODO: Change the system to use these ^^
(define (simtok-equal? x y)
(DEBUGMODE
(unless (and (simtok? x) (simtok? y))
(error 'simtok-equal? "These are not both simtoks: ~s ~s" x y)))
(and (eq? (simtok-name x) (simtok-name y))
(eqv? (simtok-subid x) (simtok-subid y))))
;; This structure contains everything an executing token handler needs
;; to know about the local node. "this" is a simobject. tokstore is
;; a struct containing all the stored values.
; [2005.03.05] Putting everything in simobject, "this" provides everything.
;(reg:define-struct (localinfo this I-am-SOC tokstore))
;; Positions are just 2-element lists.
(reg:define-struct (node id pos))
;; [2005.11.16] NOT USED YET:
;; Graphical Node-Object
;; This is the graphical representation of a node, it consists of several graphical subparts.
(reg:define-struct (gobject circ ;; The circle
rled gled bled ;; The LEDs
title label ;; The title above the node, and debug-text/label below the node.
edgelist ;; An association list binding neighbor ID to a graphical line object.
))
;; Optionally put in a guarded constructor:
#;
(DEBUGMODE
(define make-gobject
(let ((orig make-gobject))
(lambda (c r g b t l e)
(if (and (list? e)
;; Don't know how to check instance relationships for SWL objects...
)
(orig c r g b t l e)
(error 'make-gobject "Invalid edge table: ~s" e))))))
;; This is a very important and central structure that represents a simulated node.
;;<br>
;;<br> [2004.06.11] Added homepage just for my internal hackery.
;;<br> [2004.06.13] Be careful to change "cleanse-world" if you change
;;<br> this, we don't want multiple simulation to be thrashing eachother.
;;<br> [2004.07.08] I don't know why I didn't do this, but I'm storing the
;;<br> token-cache in the structure too
(reg:define-struct (simobject node I-am-SOC
;; The token store is a hash table mapping simtok objects to token
;; objects. The token objects themselves are just records of stored
;; variables. However, by convention, the first slot of the token
;; object is a counter for how many times the handler has been
;; invoked.
token-store ;; Changing this to hash table indexed by token names.
;; All these buffers get changed when a token handler runs:
incoming-msg-buf ;; Stores simulation events
local-msg-buf ;; Stores simulation events
outgoing-msg-buf ;; Stores simulation events
timed-token-buf ;; Stores simulation events
local-sent-messages local-recv-messages
;; This stores #(invoked sent received) counters for every token name:
token-table
redraw ;; A boolean indicating whether the object needs be redrawn.
gobj ;; Pointer to the graphical representation of this object.
homepage ;; Not currently used, a "blackboard".
;; This is a function that processes incoming messages
scheduler ;; and returns simulation actions.
;; Not used in the simple scheduler as of [2005.09.27]
;; This function takes msg-obj and vtime and executes a token handler:
meta-handler
worldptr ;; A pointer to the relevent simworld object.
))
;; The following builds a simobject from a node and initializes all the values to their default state.
;; This is essentially the constructor for the type 'simobject.
;; Optionally takes
;; .returns A fresh, initialized simobject.
(define node->simobject
(case-lambda
[(nd) (node->simobject nd #f)]
[(nd world)
(DEBUGASSERT (or (not world) (simworld? world)))
(let ([so (apply make-simobject (make-list 16 'simobject-field-uninitialized))])
(set-simobject-node! so nd)
(set-simobject-token-store! so (make-default-hash-table 100))
(set-simobject-incoming-msg-buf! so '())
(set-simobject-outgoing-msg-buf! so '())
(set-simobject-local-msg-buf! so '())
(set-simobject-timed-token-buf! so '())
(set-simobject-local-sent-messages! so 0)
(set-simobject-local-recv-messages! so 0)
(set-simobject-token-table! so (make-default-hash-table 100))
(set-simobject-redraw! so #f)
(set-simobject-gobj! so #f)
(set-simobject-homepage! so '())
(set-simobject-I-am-SOC! so #f)
(set-simobject-scheduler! so #f)
(set-simobject-meta-handler! so #f)
(set-simobject-worldptr! so world)
so)]))
;; And then this is the invariant-checker for simobjects.
(define (invcheck-simobject so)
(or (and (simobject? so)
;; TODO: FINISH
)
(error 'invcheck-simobject "failed invariant:\n ~s\n" so)))
;; This structure represents a message transmitted across a channel.
;; None of these should be mutated:
(reg:define-struct (msg-object token ;; This is a simtok object. Used to just be a symbol (name).
sent-time ;; when it was sent --This is currently mutated within the scheduler [2005.09.27]
parent ;; :: simobject - who I got it from
to ;; :: nodeid - who its going to, #f for broadcast
args))
;; [2005.11.03] These totals were simply global vars. But PLT's module
;; system had a problem with that. I could maybe think of something
;; more efficient to do here since these are called hundreds of thousands of times.
;; This one is just used to count up the messages during a simulation: <br>
;;
;; [2005.11.26] This information is now in the individual simobjects,
;; replacing these with functions that sum up the simobject values.
;(define simalpha-total-messages (reg:make-parameter 0 (lambda (x) x)))
;; This one counts total token handlers fired.
;(define simalpha-total-tokens (reg:make-parameter 0 (lambda (x) x)))
;; Safer version:
(define (safe-construct-msg-object token timestamp parent args)
;(unless (token-name? token) (error 'safe-construct-msg-object "bad token name: ~s" token))
(DEBUGMODE
(unless (simtok? token) (error 'safe-construct-msg-object "bad token: ~s" token)) ;
(unless (or (number? timestamp) (not timestamp))
(error 'safe-construct-msg-object "bad timestamp: ~s" timestamp))
(unless (list? args)
(error 'safe-construct-msg-object "bad args: ~s" args)))
(make-msg-object token timestamp parent #f args))
;; [2004.06.28] This is a helper to construct the locally used
;; messages that don't have a parent, timestamp, etc.
(define (bare-msg-object rator rands . time)
(safe-construct-msg-object rator ;; token
(if (null? time) #f (car time)) ;; timestamp
#f ;; parent
rands))
;; This makes it use a lame sort of text display instead of the graphics display:
;(define-regiment-parameter simulator-output-text #f (lambda (x) x))
;; This is a SEPERATE LOGGER for debug info as opposed to simulation events.
;; [2005.10.25] This doesn't appear to be used
; (define-regiment-parameter sim-debug-logger
; (lambda args
; (begin ;critical-section
; (apply printf args)))
; (lambda (x)
; (unless (procedure? x)
; (error 'simulator-debug-logger "~s is not a procedure" x))
; x))
; (define-syntax silently
; (syntax-rules ()
; [(_ expr ...) (parameterize ([sim-debug-logger (lambda args (void))])
; expr ...)]))
;; #f trumps any time, EXCEPT 0, 0 trumps all.
(define (evntlessthan a b)
(vtimelessthan (simevt-vtime a) (simevt-vtime b)))
(define (vtimelessthan at bt)
(cond
[(eq? at 0) #t]
[(eq? bt 0) #f]
[(not at) #t]
[(not bt) #f]
[else (<= at bt)]))
(define global-graph (reg:make-parameter #f (lambda (x) x)))
;; Global parameter to hold globally returned values:
(define soc-return-buffer
(reg:make-parameter '()
(lambda (ls) ls)))
;; Global parameter contains continuation for exiting the alpha-sim. Invoked by soc-finished.
(define escape-alpha-sim
(reg:make-parameter (lambda (x) (error 'escape-alpha-sim "parameter holds no continuation"))
(lambda (k) (if (procedure? k) k
(error 'escape-alpha-sim "bad continuation: ~a" k)))))
;; These shouldn't need to be reset after/before a run of the simulator.
(define reverse-table (make-default-hash-table))
;; This is not going to *change* over the course of our evaluation:
(define max-positive (most-positive-fixnum))
(define (token->key t)
(DEBUGMODE
(if (not (simtok? t))
(error 'token->key "This is not a simtok object: ~s" t)))
(let ((n (hash (list (simtok-name t) (simtok-subid t)) max-positive)))
(hashtab-set! reverse-table n t)
;(disp " Token->key " t n)
n))
(define (key->token k)
(hashtab-get reverse-table k))
;; Helper to determine the distance between two 2d positions.
(define (posdist a b)
(sqrt (+ (expt (- (car a) (car b)) 2)
(expt (- (cadr a) (cadr b)) 2))))
) ;; End module
| true |
bc3e3847fff8a5aec4e202743f45fd9f9c7e6df7 | f17ecf48249d4fba76d276ba35248a70b7fa347e | /schemep3-scrobble.scm | 9250c673790f177908e7cd04d0d88457ab58f918 | []
| no_license | liulanghaitun/schemep3 | 8f7832d32cc4cf73936ba7a5d6afaa6278b37bb7 | 513a3f2bbe164f510d1d4c6edd02eaadab75ff0c | refs/heads/master | 2023-03-16T10:01:43.121901 | 2019-08-27T00:36:09 | 2019-08-27T00:36:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 3,984 | scm | schemep3-scrobble.scm | #lang scheme/gui
(require srfi/2)
(require framework)
(require "cwb-scrobble.scm")
(require "schemep3-database.scm")
(require "schemep3-playback.scm")
(require "schemep3-helpers.scm")
(require "schemep3-mixins-gui.scm")
(require "schemep3-frame-console.scm")
(define audioscrobbler-username (preferences-backed-variable 'scrobble-username ""))
(define audioscrobbler-password (preferences-backed-variable 'scrobble-password ""))
(define (scrobble?)
(and (> (string-length (audioscrobbler-username)) 0)
(> (string-length (audioscrobbler-password)) 0)))
(add-pre-play-hook
(lambda (index file-index)
(and-let* (((scrobble?))
(filename (schemep3-database-index->filename file-index))
(artist (schemep3-database-retrieve-field file-index 'artist))
(album (schemep3-database-retrieve-field file-index 'album))
(title (schemep3-database-retrieve-field file-index 'title))
(duration (schemep3-database-retrieve-field file-index 'duration)))
(thread
(lambda ()
(if
(scrobble:now-playing
#:artist artist
#:album album
#:title title
#:duration (inexact->exact duration)
#:username (audioscrobbler-username)
#:password (audioscrobbler-password))
(console:printf "[scrobble] Now Playing Win - ~A~%" filename)
(console:printf "[scrobble] Now Playing Fail - ~A~%" filename)))))))
(add-post-play-hook
(lambda (index file-index elapsed percent)
(and-let* (((scrobble?))
(filename (schemep3-database-index->filename file-index))
(artist (schemep3-database-retrieve-field file-index 'artist))
(album (schemep3-database-retrieve-field file-index 'album))
(title (schemep3-database-retrieve-field file-index 'title))
(duration (schemep3-database-retrieve-field file-index 'duration))
(rating (schemep3-database-retrieve-field file-index 'rating))
((>= percent 50))
((>= elapsed 30)))
(thread
(lambda ()
(if
(scrobble:submit
#:artist artist
#:album album
#:title title
#:love (and rating (> rating 4))
#:duration (inexact->exact duration)
#:username (audioscrobbler-username)
#:password (audioscrobbler-password))
(console:printf "[scrobble] Scrobble Win - ~A~%" filename)
(console:printf "[scrobble] Scrobble Fail - ~A~%" filename)))))))
(preferences:add-panel
"AudioScrobbler"
(lambda (parent)
(let* ((v-panel (new vertical-panel%
(parent parent)))
(username-field
(new (stored-value-mixin text-field%)
(parent v-panel)
(settor-gettor audioscrobbler-username)
(label "Username:")))
(password-field
(new (stored-value-mixin text-field%)
(parent v-panel)
(style '(password single))
(settor-gettor audioscrobbler-password)
(label "Password:")))
(password-2-field
(new text-field%
(parent v-panel)
(init-value (or (audioscrobbler-password) ""))
(style '(password single))
(label "Reenter Password:"))))
(preferences:add-can-close-dialog-callback
(lambda ()
(if (string=?
(send password-field get-value)
(send password-2-field get-value))
#t
(begin
(message-box "Schemep3 Preferences"
"Password fields do not match"
(send v-panel get-top-level-window)
'(ok))
#f))))
v-panel)))
| false |
f4fff524ab3a379545bee45d8cc5e9227821ae19 | 2c291b7af5cd7679da3aa54fdc64dc006ee6ff9b | /ch4/exercise.4.11.scm | 2a9400dfec8641550fcd5121a360a6e806db558d | []
| no_license | etscrivner/sicp | caff1b3738e308c7f8165fc65a3f1bc252ce625a | 3b45aaf2b2846068dcec90ea0547fd72b28f8cdc | refs/heads/master | 2021-01-10T12:08:38.212403 | 2015-08-22T20:01:44 | 2015-08-22T20:01:44 | 36,813,957 | 1 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 1,695 | scm | exercise.4.11.scm | (define (make-frame-segment var val)
(cons var val))
(define (frame-segment-variable segment) (car segment))
(define (frame-segment-value segment) (cdr segment))
(define (make-frame variables values)
(map make-frame-segment variables values))
(define (add-binding-to-frame! var val frame)
(set-cdr! frame (append (cdr frame)
(list (make-frame-segment var val)))))
(define (extend-environment vars vals base-env)
(if (= (length vars) (length vals))
(cons (make-frame vars vals) base-env)
(if (< (length vars) (length vals))
(error "Too many arguments supplied" vars vals)
(error "Too few arguments supplied" vars vals))))
(define (lookup-variable-value var env)
(if (eq? env the-empty-environment)
(error "Unbound variable" var)
(let ((result (filter (lambda (x) (eq? var (car x)))
(first-frame env))))
(if (not (null? result))
(cdar result)
(lookup-variable-value var (enclosing-environment env))))))
(define (set-variable-value! var val env)
(if (eq? env the-empty-environment)
(error "Unbound variable" var)
(let ((result (filter (lambda (x) (eq? var (car x)))
(first-frame env))))
(if (not (null? result))
(set-cdr! (car result) val)
(set-variable-value! var val (enclosing-environment env))))))
(define (define-variable! var val env)
(let ((result (filter (lambda (x) (eq? var (car x)))
(first-frame env))))
(if (not (null? result))
(set-cdr! (car result) val)
(add-binding-to-frame! var val (first-frame env)))))
| false |
fd621b1f36a260c6d58a7b59957415465c1e40a4 | 404799b4b2d5f83ee5304392826a69defc25da77 | /ex2-14.scm | b6992f5106d32c17c2dc104caaddd36365a2114b | []
| no_license | WuzhangFang/SICP-exercise | 38ae650c63e74bb7c6639bf984285e06743db925 | d9977009ec3e32a74edb13b4f13f6ebbbc44ab32 | refs/heads/master | 2020-04-16T16:01:18.058287 | 2019-10-01T21:52:40 | 2019-10-01T21:52:40 | 165,722,260 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 664 | scm | ex2-14.scm | ;;; Exercise 2.14
(load "ex2-8.scm")
(load "ex2-12.scm")
;(define (par1 r1 r2)
; (div-interval
; (mul-interval r1 r2)
; (add-interval r1 r2)))
;(define (par2 r1 r2)
; (let ((one (make-interval 1 1)))
; (div-interval one (add-interval (div-interval one r1) (div-interval one r2)))))
;(make-interval 95 105)
;(par1 (make-interval 95 105) (make-interval 95 105))
;(par2 (make-interval 95 105) (make-interval 95 105))
(div-interval (make-center-percent 10 1) (make-center-percent 10 1))
(div-interval (make-center-percent 10 0.01) (make-center-percent 10 0.01))
(div-interval (make-center-percent 10 0.0001) (make-center-percent 10 0.0001))
| false |
58bf89b938c2c90c7fb8feec8b108ed36d701993 | 37245ece3c767e9434a93a01c2137106e2d58b2a | /src/unsyntax/store.sld | ab06a5aff2e6996a6b1fea077de17a4033b38985 | [
"MIT"
]
| permissive | mnieper/unsyntax | 7ef93a1fff30f20a2c3341156c719f6313341216 | 144772eeef4a812dd79515b67010d33ad2e7e890 | refs/heads/master | 2023-07-22T19:13:48.602312 | 2021-09-01T11:15:54 | 2021-09-01T11:15:54 | 296,947,908 | 12 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 2,243 | sld | store.sld | ;; Copyright © Marc Nieper-Wißkirchen (2020).
;; This file is part of unsyntax.
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation files
;; (the "Software"), to deal in the Software without restriction,
;; including without limitation the rights to use, copy, modify, merge,
;; publish, distribute, sublicense, and/or sell copies of the Software,
;; and to permit persons to whom the Software is furnished to do so,
;; subject to the following conditions:
;; The above copyright notice and this permission notice (including the
;; next paragraph) shall be included in all copies or substantial
;; portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(define-library (unsyntax store)
(export make-runtime-binding
make-binding
make-meta-binding
binding?
binding-type
binding-value
library-table-intern!
record-expanded-library!
expanded-libraries
with-frame
with-bindings
current-store-ref
lookup
bind!
bind-core!
bind-global!
current-globals
ref-global
set-global!
set-keyword!
set-property!
arguments->vector
current-locations
current-meta-level
in-meta)
(import (scheme base)
(scheme case-lambda)
(srfi 1)
(srfi 2)
(srfi 8)
(srfi 111)
(srfi 125)
(srfi 128)
(unsyntax auxiliary-syntax)
(unsyntax rib)
(unsyntax error)
(unsyntax library)
(unsyntax variable))
(include "store/store.scm"
"store/library-table.scm"
"store/context.scm"))
| false |
c58125e157ed6b52997ae054b1fd7d74c6c25325 | 5fe14ef1ced9caa3b7d1fc3248ba86155e9628f5 | /tests/srfi-8.scm | dc7ab9e975cec906c267de628ab74f10c0e304bd | []
| no_license | mario-goulart/chicken-tests | 95720ed5b29e7a7c209d4431b9558f21916752f1 | 04b8e059aaacaea308aac40082d346e884cb901c | refs/heads/master | 2020-06-02T08:18:08.888442 | 2012-07-12T14:02:29 | 2012-07-12T14:02:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 917 | scm | srfi-8.scm | ; Test suite for SRFI-8
; 2004-01-01 / lth
;(cond-expand (srfi-8))
(define (writeln . xs)
(for-each display xs)
(newline))
(define (fail token . more)
(writeln "Error: test failed: " token)
#f)
(or (call-with-current-continuation
(lambda (k)
(handle-exceptions exn
(k #f)
(eval '(receive (a b) (values 1 2)
(or (and (equal? a 1)
(equal? b 2))
(fail 'receive:1))))
(eval '(receive (a) 1
(or (equal? a 1)
(fail 'receive:2))))
(eval '(receive (a) (values 1)
(or (equal? a 1)
(fail 'receive:3))))
(eval '(receive () (values) #t))
(eval '(receive (a . rest) (values 1 2 3)
(or (and (equal? a 1)
(equal? rest '(2 3)))
(fail 'receive:4))))
(eval '(receive a (values 1 2 3)
(or (equal? a '(1 2 3))
(fail 'receive:5))))
#t)))
(fail 'receive:0)) ; Syntax or the 0-values form
(writeln "Done.")
| false |
317a0c90c1348c0789c317f82687fba1e1369a0f | 5c4964460d5d9fcb190a35457ace51ab914ef3ff | /section-3.5.scm | 0842e6107de3452baedff4dd34b86de910794b62 | []
| no_license | lmcchun/sicp-solutions | 0636333c65cfba35197c9c4939977d5bb0117aed | 3beb68aeeb3b1cabb7b55a27fd67a289693a64f1 | refs/heads/master | 2021-01-17T19:08:49.028304 | 2016-06-12T16:11:20 | 2016-06-12T16:11:20 | 60,976,032 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 17,904 | scm | section-3.5.scm | (#%require (only racket/base random))
(define the-empty-stream '())
(define stream-null? null?)
(define-syntax cons-stream
(syntax-rules ()
((_ first second) (cons first (delay second)))))
(define (stream-ref s n)
(if (= n 0)
(stream-car s)
(stream-ref (stream-cdr s) (- n 1))))
(define (stream-map proc s)
(if (stream-null? s)
the-empty-stream
(cons-stream (proc (stream-car s))
(stream-map proc (stream-cdr s)))))
(define (stream-for-each proc s)
(if (stream-null? s)
'done
(begin (proc (stream-car s))
(stream-for-each proc (stream-cdr s)))))
(define (display-stream s)
(stream-for-each display-line s))
(define (display-line x)
(newline)
(display x))
(define (stream-car stream)
(car stream))
(define (stream-cdr stream)
(force (cdr stream)))
(define (stream-enumerate-interval low high)
(if (> low high)
the-empty-stream
(cons-stream
low
(stream-enumerate-interval (+ low 1) high))))
(define (stream-filter pred stream)
(cond ((stream-null? stream) the-empty-stream)
((pred (stream-car stream))
(cons-stream (stream-car stream)
(stream-filter pred
(stream-cdr stream))))
(else (stream-filter pred (stream-cdr stream)))))
(define (memo-proc proc)
(let ((already-run? #f) (result #f))
(lambda ()
(if (not already-run?)
(begin (set! result (proc))
(set! already-run? #t)
result)
result))))
; ex 3.50
(define (stream-map proc . argstreams)
(if (stream-null? (car argstreams))
the-empty-stream
(cons-stream
(apply proc (map stream-car argstreams))
(apply stream-map
(cons proc (map stream-cdr argstreams))))))
;
(define (integers-starting-from n)
(cons-stream n (integers-starting-from (+ n 1))))
(define integers (integers-starting-from 1))
(define (divisible? x y)
(= (remainder x y) 0))
(define (fibgen a b)
(cons-stream a (fibgen b (+ a b))))
(define (sieve stream)
(cons-stream
(stream-car stream)
(sieve (stream-filter
(lambda (x)
(not (divisible? x (stream-car stream))))
(stream-cdr stream)))))
(define primes (sieve (integers-starting-from 2)))
(define ones (cons-stream 1 ones))
(define (add-streams s1 s2)
(stream-map + s1 s2))
(define integers (cons-stream 1 (add-streams ones integers)))
(define fibs
(cons-stream 0
(cons-stream 1
(add-streams (stream-cdr fibs)
fibs))))
(define (scale-stream stream factor)
(stream-map (lambda (x) (* x factor)) stream))
(define double (cons-stream 1 (scale-stream double 2)))
(define primes
(cons-stream
2
(stream-filter prime? (integers-starting-from 2))))
(define (square n)
(* n n))
(define (prime? n)
(letrec ((iter
(lambda (ps)
(cond ((> (square (stream-car ps)) n) #t)
((divisible? n (stream-car ps)) #f)
(else (iter (stream-cdr ps)))))))
(iter primes)))
; ex 3.54
(define (mul-streams s1 s2)
(stream-map * s1 s2))
(define factorials
(cons-stream 1
(mul-streams (integers-starting-from 2)
factorials)))
; ex 3.55
(define (partial-sums stream)
(cons-stream (stream-car stream)
(add-streams (stream-cdr stream)
(partial-sums stream))))
; ex 3.56
(define (merge s1 s2)
(cond ((stream-null? s1) s2)
((stream-null? s2) s1)
(else
(let ((s1car (stream-car s1))
(s2car (stream-car s2)))
(cond ((< s1car s2car)
(cons-stream s1car (merge (stream-cdr s1) s2)))
((> s1car s2car)
(cons-stream s2car (merge s1 (stream-cdr s2))))
(else
(cons-stream s1car
(merge (stream-cdr s1)
(stream-cdr s2)))))))))
(define S (cons-stream 1
(merge (scale-stream S 2)
(merge (scale-stream S 3)
(scale-stream S 5)))))
; ex 3.58
(define (expand num den radix)
(cons-stream
(quotinet (* num radix) den)
(expand (remainder (* num radix) den) den radix)))
; ex 3.59
(define (div-streams s1 s2)
(stream-map / s1 s2))
(define (integrate-series stream)
(div-streams stream integers))
(define exp-series
(cons-stream 1 (integrate-series exp-series)))
(define cosine-series
(cons-stream 1 (scale-stream
(integrate-series sine-series)
-1)))
(define sine-series
(cons-stream 0 (integrate-series cosine-series)))
; ex 3.60
(define (mul-series s1 s2)
(cons-stream (* (stream-car s1)
(stream-car s2))
(add-streams (scale-stream (stream-cdr s2)
(stream-car s1))
(mul-series (stream-cdr s1) s2))))
; ex 3.61
(define (invert-unit-series series)
(cons-stream 1
(scale-stream (mul-series (stream-cdr series)
(invert-unit-series series))
-1)))
; ex 3.62
(define (div-series num denom)
(let ((denom-const (stream-car denom)))
(if (= denom-const 0)
(error "denom constant term is zero" 'div-series)
(mul-series
num
(scale-stream
(invert-unit-series
(scale-stream denom (/ 1 denom-const)))
denom-const)))))
(define tangent-series
(div-series sine-series cosine-series))
;
(define (sqrt-improve guess x)
(/ (+ guess (/ x guess)) 2))
(define (sqrt-stream x)
(letrec ((guesses
(cons-stream 1.0
(stream-map (lambda (guess)
(sqrt-improve guess x))
guesses))))
guesses))
(define (pi-summands n)
(cons-stream (/ 1.0 n)
(stream-map - (pi-summands (+ n 2)))))
(define pi-stream
(scale-stream (partial-sums (pi-summands 1)) 4))
(define (euler-transform s)
(let ((s0 (stream-ref s 0))
(s1 (stream-ref s 1))
(s2 (stream-ref s 2)))
(cons-stream (- s2 (/ (square (- s2 s1))
(+ s0 (* -2 s1) s2)))
(euler-transform (stream-cdr s)))))
(define (make-tableau transform s)
(cons-stream s
(make-tableau transform
(transform s))))
(define (accelerated-sequence transform s)
(stream-map stream-car
(make-tableau transform s)))
; ex 3.64
(define (stream-limit stream tolerance)
(letrec ((iter
(lambda (head rest tolerance)
(let ((cur (stream-car rest)))
(if (< (abs (- cur head)) tolerance)
cur
(iter cur (stream-cdr rest) tolerance))))))
(iter (stream-car stream) (stream-cdr stream) tolerance)))
(define (another-sqrt x tolerance)
(stream-limit (sqrt-stream x) tolerance))
; ex 3.65
(define (ln2-summands n)
(cons-stream (/ 1.0 n)
(stream-map - (ln2-summands (+ n 1)))))
(define ln2-stream
(partial-sums (ln2-summands 1)))
(define (display-n-stream-elements stream n)
(if (> n 0)
(if (stream-null? stream)
'ok
(begin (display (stream-car stream))
(newline)
(display-n-stream-elements (stream-cdr stream) (- n 1))))
'ok))
;
(define (interleave s1 s2)
(if (stream-null? s1)
s2
(cons-stream (stream-car s1)
(interleave s2 (stream-cdr s1)))))
(define (pairs s t)
(cons-stream
(list (stream-car s) (stream-car t))
(interleave
(stream-map (lambda (x) (list (stream-car s) x))
(stream-cdr t))
(pairs (stream-cdr s) (stream-cdr t)))))
; ex 3.67
(define (all-pairs s t)
(cons-stream
(list (stream-car s1) (stream-car s2))
(interleave
(stream-map
(lambda (x) (list (stream-car s1) x))
(stream-cdr s2))
(interleave
(stream-map
(lambda (x) (list x (stream-car s2)))
(stream-cdr s1))
(all-pairs (stream-cdr s1) (stream-cdr s2))))))
; ???
(define (all-pairs-1 s t)
(cons-stream
(list (stream-car s) (stream-car t))
(interleave
(stream-map (lambda (x) (list (stream-car s) x))
(stream-cdr t))
(pairs (stream-cdr s) t))))
; ex 3.69
(define (triples s t u)
(cons-stream
(list (stream-car s) (stream-car t) (stream-car u))
(interleave
(stream-map
(lambda (x) (cons (stream-car s) x))
(stream-cdr (pairs t u)))
(triples (stream-cdr s) (stream-cdr t) (stream-cdr u)))))
(define pythagorean
(stream-filter
(lambda (triplet)
(= (+ (square (car triplet))
(square (cadr triplet)))
(square (caddr triplet))))
(triples integers integers integers)))
; ex 3.70
(define (merge-weighted weight s1 s2)
(cond ((stream-null? s1) s2)
((stream-null? s2) s1)
(else
(let ((s1car (stream-car s1))
(s2car (stream-car s2)))
(cond ((<= (weight s1car) (weight s2car))
(cons-stream s1car
(merge-weighted weight (stream-cdr s1) s2)))
(else
(cons-stream s2car
(merge-weighted weight s1 (stream-cdr s2)))))))))
(define (weighted-pairs weight s1 s2)
(cons-stream
(list (stream-car s1) (stream-car s2))
(merge-weighted
weight
(stream-map (lambda (x) (list (stream-car s1) x))
(stream-cdr s2))
(weighted-pairs weight (stream-cdr s1) (stream-cdr s2)))))
(define sump
(weighted-pairs (lambda (p) (+ (car p) (cadr p)))
integers
integers))
(define s235
(let ((stream
(stream-filter (lambda (number)
(or (= (remainder number 2) 0)
(= (remainder number 3) 0)
(= (remainder number 5) 0)))
integers)))
(weighted-pairs
(lambda (p)
(let ((i (car p)) (j (cadr p)))
(+ (* 2 i) (* 3 j) (* 5 i j))))
stream
stream)))
; ex 3.71
(define (cube-sum p)
(let ((i (car p)) (j (cadr p)))
(+ (* i i i) (* j j j))))
(define cubew
(weighted-pairs cube-sum integers integers))
(define (ramanujan stream max-count)
(if (> max-count 0)
(let* ((head (stream-car stream))
(currrent-cube-sum (cube-sum head))
(rest (stream-cdr stream))
(next (stream-car rest)))
(if (= currrent-cube-sum (cube-sum next))
(begin (display "(")
(display currrent-cube-sum)
(display " ")
(display head)
(display " ")
(display next)
(display ")")
(newline)
(ramanujan (stream-cdr stream) (- max-count 1)))
(ramanujan (stream-cdr stream) max-count)))
'ok))
; ex 3.72
(define (square-sum p)
(+ (square (car p)) (square (cadr p))))
(define squarew
(weighted-pairs
square-sum
integers
integers))
(define (squares-3ways stream max-count)
(if (> max-count 0)
(let* ((head (stream-car stream))
(currrent-square-sum (square-sum head))
(rest (stream-cdr stream))
(second (stream-car rest))
(third (stream-car (stream-cdr rest))))
(if (= currrent-square-sum
(square-sum second)
(square-sum third))
(begin (display "(")
(display currrent-square-sum)
(display " ")
(display head)
(display " ")
(display second)
(display " ")
(display third)
(display ")")
(newline)
(squares-3ways (stream-cdr stream) (- max-count 1)))
(squares-3ways (stream-cdr stream) max-count)))
'ok))
;
(define (integral integrand initial-value dt)
(let ((int
(cons-stream initial-value
(add-streams (scale-stream integrand dt)))))
int))
; ex 3.73
(define (RC R C dt)
(let ((rc-model
(lambda (v0 i-stream)
(add-streams
(scale-stream i-stream R)
(integral
(scale-stream i-stream (/ 1 C))
v0
dt)))))
rc-model))
; ex 3.74
(define (make-zero-crossings input-stream last-value)
(cons-stream
(sign-change-detector (stream-car input-stream) last-value)
(make-zero-crossings (stream-cdr input-stream)
(stream-car input-stream))))
;; (define zero-crossings (make-zero-crossings sense-data 0))
;; (define zero-crossings
;; (stream-map sign-change-detector
;; sense-data
;; (cons-stream 0 sense-data)))
; ex 3.75
(define (make-zero-crossings input-stream last-value last-avpt)
(let ((avpt (/ (+ (stream-car input-stream) last-value) 2)))
(cons-stream (sign-change-detector avpt last-avpt)
(make-zero-crossings (stream-cdr input-stream)
(stream-car input-stream)
avpt))))
; ex 3.76
(define (smooth s)
(stream-map
(lambda (x1 x2) (/ (+ x1 x2) 2))
(cons-stream 0 s)
x))
(define (make-zero-crossings input-stream transform last-value)
(let ((transformed (transform input-stream)))
(stream-map sign-change-detector
transformed
(cons-stream 0 transformed))))
;
(define (integral delayed-integrand initial-value dt)
(letrec ((int
(cons-stream initial-value
(let ((integrand (force delayed-integrand)))
(add-streams (scale-stream integrand dt)
int)))))
int))
(define (solve f y0 dt)
(define y (integral (delay dy) y0 dt))
(define dy (stream-map f y))
y)
; ex 3.77
(define (integral delayed-integrand initial-value dt)
(cons-stream initial-value
(let ((integrand (force delayed-integrand)))
(if (stream-null? integrand)
the-empty-stream
(integral (stream-cdr integrand)
(+ (* dt (stream-car integrand))
initial-value)
dt)))))
; ex 3.78
(define (solve-2nd a b y0 dy0 dt)
(define y (integral (delay dy) y0 dt))
(define dy (integral (delay ddy) dy0 dt))
(define ddy (add-streams (scale-stream dy a)
(scale-stream y b)))
y)
; ex 3.79
(define (solve-2nd f y0 dy0 dt)
(define y (integral (delay dy) y0 dt))
(define dy (integral (delay ddy) dy0 dt))
(define ddy (stream-map f dy y))
y)
; ex 3.80
(define (RLC R L C dt)
(let ((rlc-model
(lambda (vC0 iL0)
(letrec ((iL (integral (delay diL) iL0 dt))
(vC (integral (delay dvC) vC0 dt))
(diL (add-streams (scale-stream vC (/ 1 L))
(scale-stream iL (- (/ R L)))))
(dvC (scale-stream iL (/ -1 C))))
(cons iL vC)))))
rlc-model))
;
(define random-init
120)
(define (rand-update x)
(let ((a 27) (b 26) (m 127))
(modulo (+ (* a x) b) m)))
(define rand
(let ((x random-init))
(lambda ()
(set! x (rand-update x))
x)))
(define random-numbers
(cons-stream random-init
(stream-map rand-update random-numbers)))
(define (map-successive-pairs f s)
(cons-stream
(f (stream-car s) (stream-car (stream-cdr s)))
(map-successive-pairs f (stream-cdr (stream-cdr s)))))
(define cesaro-stream
(map-successive-pairs (lambda (r1 r2) (= (gcd r1 r2) 1))
random-numbers))
(define (monte-carlo experiment-stream passed failed)
(let ((next
(lambda (passed failed)
(cons-stream
(/ passed (+ passed failed))
(monte-carlo
(stream-cdr experiment-stream) passed failed)))))
(if (stream-car experiment-stream)
(next (+ passed 1) failed)
(next passed (+ failed 1)))))
(define pi
(stream-map (lambda (p) (sqrt (/ 6 p)))
(monte-carlo cesaro-stream 0 0)))
; ex 3.81
(define (random-number-generator random-init command-stream)
(if (stream-null? command-stream)
the-empty-stream
(let ((command (stream-car command-stream)))
(cond ((eq? command 'generator)
(let ((random-number (random-update random-init)))
(cons-stream random-number
(random-number-generator random-number
(stream-cdr command-stream)))))
((and (pair? command)
(eq? (car command) 'reset))
(let ((reset-number (cdr command)))
(cons-stream reset-number
(random-number-generator reset-number
(stream-cdr command-stream)))))
(else
(error "bad command -- " command))))))
; ex 3.82
(define (random-in-range low high)
(let ((range (- high low)))
(+ low (* (random) range))))
(define (random-number-pairs low1 high1 low2 high2)
(cons-stream
(cons (random-in-range low1 high1)
(random-in-range low2 high2))
(random-number-pairs low1 high1 low2 high2)))
(define (estimate-integral pred x1 x2 y1 y2)
(let ((area (* (- x2 x1) (- y2 y1)))
(randoms (random-number-pairs x1 x2 y1 y2)))
(scale-stream (monte-carlo (stream-map pred randoms) 0 0) area)))
(define estimate-pi-stream
(let ((unit-pred
(lambda (p)
(<= (+ (square (car p))
(square (cdr p))) 1))))
(estimate-integral unit-pred -1.0 1.0 -1.0 1.0)))
| true |
d1da04021c35ee33f8171cfcb2137abe1c704581 | 000dbfe5d1df2f18e29a76ea7e2a9556cff5e866 | /sitelib/rfc/x.509.scm | 84c5e75313d20787a926d0e5293803107d4b894b | [
"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 | 7,562 | scm | x.509.scm | ;;; -*- mode:scheme; coding:utf-8; -*-
;;;
;;; rfc/x.509 - X.509 certificate utility library.
;;;
;;; Copyright (c) 2010-2013 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 (rfc x.509)
(export make-x509-certificate
x509-certificate?
bytevector->x509-certificate read-x509-certificate
x509-certificate->bytevector write-x509-certificate
x509-certificate->bytevector <x509-certificate>
x509-certificate-expired?
x509-certificate-issuer-dn
x509-certificate-subject-dn
x509-certificate-public-key
x509-certificate-validity
x509-certificate-serial-number
x509-certificate-version
x509-certificate-signature
x509-certificate-signature-algorithm
x509-certificate-extensions
validate-x509-certificate
x509-certificate-signature-validator
x509-certificate-validity-validator
x509-name? <x509-name> x509-name
x509-name->string
list->x509-name
x509-validity? <x509-validity>
make-x509-validity
x509-validity-not-before
x509-validity-not-after
x509-certificate-template?
x509-certificate-template-builder
sign-x509-certificate-template
;; Below are only for backward compatibilities
(rename (x509-certificate-version x509-certificate-get-version)
(x509-certificate-serial-number
x509-certificate-get-serial-number)
(x509-certificate-issuer-dn x509-certificate-get-issuer-dn)
(x509-certificate-subject-dn
x509-certificate-get-subject-dn))
x509-certificate-get-not-before
x509-certificate-get-not-after
x509-certificate-get-signature-algorithm
(rename (x509-certificate-signature x509-certificate-get-signature)
(x509-certificate-public-key
x509-certificate-get-public-key))
x509:verify
x509:check-validity
x509:verify-certificate
;; for backward compatibility
(rename (x509:verify verify)
(x509:check-validity check-validity))
;; certificate generation
make-x509-issuer
make-x509-validity
(rename (make-x509-validity make-validity))
make-x509-simple-certificate
make-x509-self-signed-certificate
;; for backward compatibility
(rename (make-x509-self-signed-certificate
make-x509-basic-certificate)))
(import (rnrs)
(clos user)
(sagittarius crypto asn1)
(sagittarius crypto keys)
(sagittarius crypto digests)
(sagittarius crypto signatures)
(sagittarius crypto pkix algorithms)
(sagittarius crypto pkix certificate)
(sagittarius combinators)
(srfi :19 time))
(define-generic make-x509-certificate)
(define-method make-x509-certificate ((bv <bytevector>))
(bytevector->x509-certificate bv))
(define-method make-x509-certificate ((p <port>))
(read-x509-certificate p))
(define-method make-x509-certificate ((o <asn1-object>))
(asn1-object->x509-certificate o))
(define x509-certificate-get-not-before
(.$ x509-validity-not-before x509-certificate-validity))
(define x509-certificate-get-not-after
(.$ x509-validity-not-after x509-certificate-validity))
(define x509-certificate-get-signature-algorithm
(.$ x509-algorithm-identifier-oid x509-certificate-signature-algorithm))
;; **DEPRECATED** It's a wrong idea to use certificate to verify a signature
;; use (sagittarius crypto signatures) instead
(define (x509:verify cert message signature . ignore)
(define oid (x509-certificate-signature-algorithm cert))
(define verifier ((oid->verifier-maker oid)
(x509-certificate-public-key cert)
:der-encode #f))
(verifier-verify-signature verifier message signature))
(define (x509:verify-certificate cert public-key)
(validate-x509-certificate cert
(x509-certificate-signature-validator public-key)))
(define (x509:check-validity cert :optional (date (current-date)))
(validate-x509-certificate cert
(x509-certificate-validity-validator date)))
(define +sha256-with-rsa-encryption+
*signature-algorithm:rsa-pkcs-v1.5-sha256*)
(define +sha256-with-ecdsa-encryption+ *signature-algorithm:ecdsa-sha256*)
(define +eddsa-ed25519-encryption+ *signature-algorithm:ed25519*)
(define +eddsa-ed448-encryption+ *signature-algorithm:ed448*)
(define (make-x509-issuer lis)
(apply x509-name (map (lambda (c) (list (car c) (cdr c))) lis)))
(define (make-x509-self-signed-certificate keypair serial-number
issuer validity subject)
(define private-key (key-pair-private keypair))
(define oid
(cond ((rsa-private-key? private-key) +sha256-with-rsa-encryption+)
((ecdsa-private-key? private-key) +sha256-with-ecdsa-encryption+)
((eddsa-private-key? private-key)
(if (ed25519-key? private-key)
+eddsa-ed25519-encryption+
+eddsa-ed448-encryption+))
(else (assertion-violation 'make-x509-self-signed-certificate
"Keypair not supported" keypair))))
(sign-x509-certificate-template
(x509-certificate-template-builder
(issuer-dn issuer)
(subject-dn subject)
(serial-number serial-number)
(not-before (x509-validity-not-before validity))
(not-after (x509-validity-not-after validity))
(public-key (key-pair-public keypair)))
oid private-key))
(define (make-x509-simple-certificate public-key
serial-number subject validity
issuer-cert issuer-private-key)
(define private-key issuer-private-key)
(define oid
(cond ((rsa-private-key? private-key) +sha256-with-rsa-encryption+)
((ecdsa-private-key? private-key) +sha256-with-ecdsa-encryption+)
((eddsa-private-key? private-key)
(if (ed25519-key? private-key)
+eddsa-ed25519-encryption+
+eddsa-ed448-encryption+))
(else (assertion-violation 'make-x509-simple-certificate
"Private key not supported"
private-key))))
(sign-x509-certificate-template
(x509-certificate-template-builder
(issuer-dn (x509-certificate-subject-dn issuer-cert))
(subject-dn subject)
(serial-number serial-number)
(not-before (x509-validity-not-before validity))
(not-after (x509-validity-not-after validity))
(public-key public-key))
oid private-key))
)
| false |
046666038ec90ff00acb3a66b9d2d0be25b5e83f | b43e36967e36167adcb4cc94f2f8adfb7281dbf1 | /scheme/swl1.3/nt/cat.ss | fcc98a654dd74719671f15b8b944bea3e01b5e7b | [
"SWL",
"TCL"
]
| permissive | 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 | 1,709 | ss | cat.ss | ;; This file is intended to help with Makefile.vc under Windows NT.
;; It converts \ to / in filenames for the benefit of Scheme I/O primitives.
;;
;; Unix: cat src ... > dest
;; NT: echo replace dest src ... | $(Scheme) ..\..\nt\cat.ss
;;
;; Unix: cat src ... >> dest
;; NT: echo append dest src ... | $(Scheme) ..\..\nt\cat.ss
(optimize-level 3)
(define cat-to
(lambda (mode dest srcs)
(define buf-size 4096)
(printf "cat-to: ~s ~s ~s~n" mode dest srcs)
(let ([op (open-output-file dest mode)]
[buf (make-string buf-size)])
(for-each
(lambda (src)
(call-with-input-file src
(lambda (ip)
(let lp ()
(let ([n (block-read ip buf buf-size)])
(unless (eof-object? n) (block-write op buf n) (lp)))))))
srcs)
(close-output-port op))))
(define read-filename
(lambda ()
(let eat-whitespace ()
(let ([c (peek-char)])
(unless (eof-object? c)
(when (char-whitespace? c) (read-char) (eat-whitespace)))))
(let ([op (open-output-string)])
(let lp ()
(let ([x (read-char)])
(case x
[(#\space #\tab #\newline #!eof) (get-output-string op)]
[(#\\) (write-char #\/ op) (lp)]
[else (write-char x op) (lp)]))))))
(let ([mode (read)])
(unless (memq mode '(replace append))
(assertion-violationf 'cat.ss
"invalid mode ~s. Valid modes are replace or append"
mode))
(let ([dest (read-filename)])
(let lp ([srcs '()])
(let ([src (read-filename)])
(if (fxzero? (string-length src))
(cat-to mode dest (reverse srcs))
(lp (cons src srcs)))))))
| false |
b8d91846bc0096742cfe8958aa7c978de5e489c4 | e2ca24b819b3fcc4ccc7e9fb018920c07acd1195 | /mud/server.scm | 195153a17084e3207a7dfdfd4f2edadf8a665256 | []
| no_license | NalaGinrut/guile-mud | 102025bd808f2d403cd2e14b3aa3bb8ac8e398ae | 75637516222d9133f2924d965c31360e9efe825c | refs/heads/master | 2020-05-20T06:51:07.988402 | 2013-10-08T09:58:00 | 2013-10-08T09:58:00 | 13,392,317 | 3 | 2 | null | null | null | null | UTF-8 | Scheme | false | false | 8,761 | scm | server.scm | ;;; Web Server
;; Copyright (C) 2013
;; "Mu Lei" known as "NalaGinrut" <[email protected]>
;; Artanis 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.
;; Artanis 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 (mud server)
#:use-module (srfi srfi-9)
#:use-module (srfi srfi-9 gnu)
#:use-module (rnrs bytevectors)
#:use-module (ice-9 binary-ports)
#:use-module (mud request)
#:use-module (mud response)
#:use-module (system repl error-handling)
#:use-module (ice-9 control)
#:use-module (ice-9 iconv)
#:export (define-server-impl
lookup-server-impl
open-server
read-client
handle-request
sanitize-response
write-client
close-server
serve-one-client
run-server))
(define *timer* (gettimeofday))
(define (print-elapsed who)
(let ((t (gettimeofday)))
(pk who (+ (* (- (car t) (car *timer*)) 1000000)
(- (cdr t) (cdr *timer*))))
(set! *timer* t)))
(eval-when (expand)
(define *time-debug?* #f))
(define-syntax debug-elapsed
(lambda (x)
(syntax-case x ()
((_ who)
(if *time-debug?*
#'(print-elapsed who)
#'*unspecified*)))))
(define-record-type server-impl
(make-server-impl name open read write close)
server-impl?
(name server-impl-name)
(open server-impl-open)
(read server-impl-read)
(write server-impl-write)
(close server-impl-close))
(define-syntax-rule (define-server-impl name open read write close)
(define name
(make-server-impl 'name open read write close)))
(define (lookup-server-impl impl)
"Look up a server implementation. If IMPL is a server
implementation already, it is returned directly. If it is a symbol, the
binding named IMPL in the ‘(web server IMPL)’ module is
looked up. Otherwise an error is signaled.
Currently a server implementation is a somewhat opaque type, useful only
for passing to other procedures in this module, like
‘read-client’."
(cond
((server-impl? impl) impl)
((symbol? impl)
(let ((impl (module-ref (resolve-module `(mud server ,impl)) impl)))
(if (server-impl? impl)
impl
(error "expected a server impl in module" `(mud server ,impl)))))
(else
(error "expected a server-impl or a symbol" impl))))
;; -> server
(define (open-server impl open-params)
"Open a server for the given implementation. Return one value, the
new server object. The implementation's ‘open’ procedure is
applied to OPEN-PARAMS, which should be a list."
(apply (server-impl-open impl) open-params))
;; -> (client request body | #f #f #f)
(define (read-client impl server)
"Read a new client from SERVER, by applying the implementation's
‘read’ procedure to the server. If successful, return three
values: an object corresponding to the client, a request object, and the
request body. If any exception occurs, return ‘#f’ for all three
values."
(call-with-error-handling
(lambda ()
((server-impl-read impl) server))
#:pass-keys '(quit interrupt)
#:on-error (if (batch-mode?) 'backtrace 'debug)
#:post-error (lambda _ (values #f #f #f))))
;; -> response body
;; -> response body state
(define (handle-request handler request body state)
"Handle a given request, returning the response and body.
The response and response body are produced by calling the given
HANDLER with REQUEST and BODY as arguments.
The elements of STATE are also passed to HANDLER as
arguments, and may be returned as additional values. The new
STATE, collected from the HANDLER's return values, is then
returned as a list. The idea is that a server loop receives a handler
from the user, along with whatever state values the user is interested
in, allowing the user's handler to explicitly manage its state."
(call-with-error-handling
(lambda ()
(call-with-values (lambda ()
(with-stack-and-prompt
(lambda ()
(apply handler request body state))))
(lambda (response body . state)
(debug-elapsed 'handler)
(values response body)
(debug-elapsed 'sanitize)
(values response body state))))
#:pass-keys '(quit interrupt)
#:on-error (if (batch-mode?) 'backtrace 'debug)
#:post-error (lambda _
(values (generate-default-response request) #f state))))
;; -> unspecified values
(define (write-client impl server client response body)
"Write an HTTP response and body to CLIENT. If the server and
client support persistent connections, it is the implementation's
responsibility to keep track of the client thereafter, presumably by
attaching it to the SERVER argument somehow."
(call-with-error-handling
(lambda ()
((server-impl-write impl) server client response body))
#:pass-keys '(quit interrupt)
#:on-error (if (batch-mode?) 'backtrace 'debug)
#:post-error (lambda _ (values))))
;; -> unspecified values
(define (close-server impl server)
"Release resources allocated by a previous invocation of
‘open-server’."
((server-impl-close impl) server))
(define call-with-sigint
(if (not (provided? 'posix))
(lambda (thunk handler-thunk) (thunk))
(lambda (thunk handler-thunk)
(let ((handler #f))
(catch 'interrupt
(lambda ()
(dynamic-wind
(lambda ()
(set! handler
(sigaction SIGINT (lambda (sig) (throw 'interrupt)))))
thunk
(lambda ()
(if handler
;; restore Scheme handler, SIG_IGN or SIG_DFL.
(sigaction SIGINT (car handler) (cdr handler))
;; restore original C handler.
(sigaction SIGINT #f)))))
(lambda (k . _) (handler-thunk)))))))
(define (with-stack-and-prompt thunk)
(call-with-prompt (default-prompt-tag)
(lambda () (start-stack #t (thunk)))
(lambda (k proc)
(with-stack-and-prompt (lambda () (proc k))))))
;; -> new-state
(define (serve-one-client handler impl server state)
"Read one request from SERVER, call HANDLER on the request
and body, and write the response to the client. Return the new state
produced by the handler procedure."
(debug-elapsed 'serve-again)
(call-with-values
(lambda ()
(read-client impl server))
(lambda (client request body)
(debug-elapsed 'read-client)
(if client
(call-with-values
(lambda ()
(handle-request handler request body state))
(lambda (response body state)
(debug-elapsed 'handle-request)
(write-client impl server client response body)
(debug-elapsed 'write-client)
state))
state))))
(define* (run-server handler #:optional (impl 'http) (open-params '())
. state)
"Run Guile's built-in web server.
HANDLER should be a procedure that takes two or more arguments,
the HTTP request and request body, and returns two or more values, the
response and response body.
For example, here is a simple \"Hello, World!\" server:
@example
(define (handler request body)
(values '((content-type . (text/plain)))
\"Hello, World!\"))
(run-server handler)
@end example
The response and body will be run through ‘sanitize-response’
before sending back to the client.
Additional arguments to HANDLER are taken from
STATE. Additional return values are accumulated into a new
STATE, which will be used for subsequent requests. In this way a
handler can explicitly manage its state.
The default server implementation is ‘http’, which accepts
OPEN-PARAMS like ‘(#:port 8081)’, among others. See \"Web
Server\" in the manual, for more information."
(let* ((impl (lookup-server-impl impl))
(server (open-server impl open-params)))
(call-with-sigint
(lambda ()
(let lp ((state state))
(lp (serve-one-client handler impl server state))))
(lambda ()
(close-server impl server)
(values)))))
| true |
de864c0c0c7693816a82661e9711ef2a6a340f37 | b62560d3387ed544da2bbe9b011ec5cd6403d440 | /steel-examples/callcc.scm | 27099dd49f93d63159aa44a28b6b1e7660e933bd | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Apache-2.0"
]
| permissive | mattwparas/steel | c6fb91b20c4e613e6a8db9d9310d1e1c72313df2 | 700144a5a1aeb33cbdb2f66440bbe38cf4152458 | refs/heads/master | 2023-09-04T03:41:35.352916 | 2023-09-01T03:26:01 | 2023-09-01T03:26:01 | 241,949,362 | 207 | 10 | Apache-2.0 | 2023-09-06T04:31:21 | 2020-02-20T17:39:28 | Rust | UTF-8 | Scheme | false | false | 3,193 | scm | callcc.scm | (define (for-each func lst)
(if (null? lst)
void
(begin
(func (car lst))
(if (null? lst)
void
(for-each func (cdr lst))))))
; (for-each (lambda (x) (displayln x)) '(1 2 3 4 5))
;; [LISTOF X] -> ( -> X u 'you-fell-off-the-end)
(define (generate-one-element-at-a-time lst)
;; Both internal functions are closures over lst
;; Internal variable/Function which passes the current element in a list
;; to its return argument (which is a continuation), or passes an end-of-list marker
;; if no more elements are left. On each step the function name is
;; rebound to a continuation which points back into the function body,
;; while return is rebound to whatever continuation the caller specifies.
(define (control-state return)
(for-each
(lambda (element)
(set! return (call/cc
(lambda (resume-here)
;; Grab the current continuation
(set! control-state resume-here)
; (displayln "GETTING HERE")
(return element))))) ;; (return element) evaluates to next return
lst)
;; TODO
;; this is reading the local variable
;; but it needs to be reading from the heap
(return 'you-fell-off-the-end))
;; (-> X u 'you-fell-off-the-end)
;; This is the actual generator, producing one item from a-list at a time.
; (define (generator)
; (call/cc control-state))
(lambda () (call/cc control-state)))
;; TODO: don't use IDs for ordering - find something (depth + stack offset or arg position) that will better identify the position of a variable. The fact is that certain variables are created later, which means the offsets are all goofy.
; (define generate-one-element-at-a-time
; (λ (lst)
; ((λ (control-state)
; ((λ (control-state0)
; (begin
; (set! control-state control-state0)
; (λ ()
; (call/cc control-state))))
; (λ (return)
; (begin
; (for-each
; (λ (element)
; (set! return
; (call/cc
; (λ (resume-here)
; (begin
; (set! control-state
; resume-here)
; (return element))))))
; lst)
; (return (quote you-fell-off-the-end))))))
; 123)))
;; Return the generator
; generator)
(define generate-digit
(generate-one-element-at-a-time '(0 1 2)))
; (generate-digit) ;; 0
; (generate-digit) ;; 1
; (generate-digit) ;; 2
; (generate-digit) ;; you-fell-off-the-end
; (generate-digit) ;; you-fell-off-the-end
; (equal? 0 (generate-digit)) ;; 0
; (equal? 1 (generate-digit)) ;; 1
; (equal? 2 (generate-digit)) ;; 2
; ; (define res (generate-digit))
; ; (displayln res)
; (equal? 'you-fell-off-the-end (generate-digit)) ;; you-fell-off-the-end
; (equal? 'you-fell-off-the-end (generate-digit)) ;; you-fell-off-the-end
| false |
f827ec0568be28a94ecfdca92149b604594059b0 | defeada37d39bca09ef76f66f38683754c0a6aa0 | /UnityEngine/unity-engine/asset-bundle-manifest.sls | c935834a5eb68bded560e64256474be552a93071 | []
| 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,321 | sls | asset-bundle-manifest.sls | (library (unity-engine asset-bundle-manifest)
(export new
is?
asset-bundle-manifest?
get-all-dependencies
get-asset-bundle-hash
get-direct-dependencies
get-all-asset-bundles
get-all-asset-bundles-with-variant)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...) #'(clr-new UnityEngine.AssetBundleManifest a ...)))))
(define (is? a) (clr-is UnityEngine.AssetBundleManifest a))
(define (asset-bundle-manifest? a)
(clr-is UnityEngine.AssetBundleManifest a))
(define-method-port
get-all-dependencies
UnityEngine.AssetBundleManifest
GetAllDependencies
(System.String[] System.String))
(define-method-port
get-asset-bundle-hash
UnityEngine.AssetBundleManifest
GetAssetBundleHash
(UnityEngine.Hash128 System.String))
(define-method-port
get-direct-dependencies
UnityEngine.AssetBundleManifest
GetDirectDependencies
(System.String[] System.String))
(define-method-port
get-all-asset-bundles
UnityEngine.AssetBundleManifest
GetAllAssetBundles
(System.String[]))
(define-method-port
get-all-asset-bundles-with-variant
UnityEngine.AssetBundleManifest
GetAllAssetBundlesWithVariant
(System.String[])))
| true |
3e417838256ca02d5bc7456b0248c9cba6bc5c42 | 79209f2d7a824df1ccaa93a76da5970b9c074d6c | /tests/sim/board-ports.scm | 275fd5b1ac42103ed32c7e23653b9dde27e0cc11 | [
"BSD-2-Clause"
]
| permissive | mgritz/chip-remote | 79fd5586d9c3b5722f5a8e8925911396d5e698f7 | 03f6282a22935fd455de79a0a3c09a501e61ff07 | refs/heads/master | 2020-04-01T06:56:43.405901 | 2018-10-13T13:04:12 | 2018-10-13T13:04:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 583 | scm | board-ports.scm | ;; Copyright (c) 2011-2018 chip-remote workers, All rights reserved.
;;
;; Terms for redistribution and use can be found in LICENCE.
(use-modules (test chip-remote)
(chip-remote protocol)
(srfi srfi-1))
(define connection (init-connection))
(define (looks-good? p)
(and (list? p)
(pair? (car p))
(fold (lambda (x acc)
(and (memq (car x) '(ports focus))
acc))
#t
p)))
(test-with-tag 'broken-ports-reply (looks-good? (ports connection)))
(close-connection connection)
(quit 0)
| false |
f454a6792dfd3bb9f9fb1eb2c07e52b8997c4c66 | cca999903bc2305da28e598c46298e7d31dbdef5 | /src/web/collections/test/tiina-3-5.ss | 4f3c6b568538fbad4fb17c7c2bc155a9c8f3cdf5 | [
"Apache-2.0"
]
| permissive | ds26gte/kode.pyret.org | 211183f7045f69cf998a8ebd8a9373cd719d29a1 | 534f2d4b61a6d6c650a364186a4477a52d1cd986 | refs/heads/master | 2021-01-11T14:56:43.120765 | 2018-05-02T22:27:55 | 2018-05-02T22:27:55 | 80,234,747 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 1,863 | ss | tiina-3-5.ss | ; Kertolaskupeli
;
; Kertolaskupeli, joka kysyy käyttäjältä oikeaa vastausta kertolaskutehtäviin, tarkistaa tuloksen,
; kertoo käyttäjälle menikö oikein ja laskee pisteet.
; ---------------------------------------------------------------
;(require teachpacks/display-read)
(require wescheme/dhnSHUnLTh)
;; RATKAISU1
;; kysymys: Luku Luku -> Merkkijono
(define (kysymys a b)
(string-append "Laske: " (number->string a) " * " (number->string b)))
;; kertolaskukoe : Luku Luku -> Luku
(define (kertolaskukoe kerrat pisteet)
(let* [(a (random 10))
(b (random 10))
(vastaus (display-read-number (kysymys a b)))]
(if (<= kerrat 0)
(display-value "Testi loppui. Pisteesi: " pisteet)
(if (and (number? vastaus) (= (* a b) vastaus))
(begin
(display-info "Oikein")
(kertolaskukoe (sub1 kerrat) (add1 pisteet)))
(begin
(display-info "Väärin")
(kertolaskukoe (sub1 kerrat) pisteet))))))
;; koe : Luku -> Luku
(define (koe kerrat)
(kertolaskukoe kerrat 0))
;; aloittaa kokeen (kysymysten määrä)
(koe 10)
;; RATKAISU2 (kysyy uudelleen, jos meni väärin)
;; kertolasku-koe2 : Luku Luku Luku Luku -> Luku
(define (kertolaskukoe2 kerrat pisteet a b)
(let [(vastaus (display-read-number (kysymys a b)))]
(if (<= kerrat 0)
(display-value "Testi loppui. Pisteesi: " pisteet)
(if (and (number? vastaus) (= (* a b) vastaus))
(begin
(display-info "Oikein")
(kertolaskukoe2 (sub1 kerrat) (add1 pisteet) (random 10)(random 10)))
(begin
(display-info "Väärin. Yritä uudelleen.")
(kertolaskukoe2 (sub1 kerrat) pisteet a b))))))
;; koe2 : Luku -> Luku
(define (koe2 kerrat)
(kertolaskukoe2 kerrat 0 (random 10)(random 10)))
(koe2 10)
| false |
64b2501b31092289e4960c402a936e47010fd637 | a7a99f1f9124d23b04558fdac002f9153079b9c0 | /tests/examples/uniform-draw.ss | a8b1ca501a4e45777e1c6d3e0183e4f6aa07635b | []
| no_license | stuhlmueller/sine | a451c3803283de220f3475dba4c6c1fcde883822 | ce6ec938e8f46c31925f23b557284405c1ba0b11 | refs/heads/master | 2016-09-06T10:23:19.360983 | 2012-07-20T21:09:59 | 2012-07-20T21:10:11 | 3,517,254 | 4 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 245 | ss | uniform-draw.ss | #!r6rs
(import (rnrs)
(scheme-tools)
(sine utils)
(sine spn))
(define uniform-draw-expr
'(uniform-draw (list 1 2 3 4 5 'foo 'bar 'baz)))
(for-each pen (log-marginal->marginal (time (marginalize uniform-draw-expr))))
| false |
b2f8386e0a58d6e7ab55e2eaa088feab87116ce0 | b562a328845e6c4e87194a6e65effdd9aa3b2b9b | /machine-code/disassembler/x86-opcodes.rkt | 4a06446eb266774ba315229189e85d8af7d47f88 | [
"MIT"
]
| permissive | samth/disassemble | 9e0b25d8f8564ca31fc2075ff796f80576d495cd | da196911af96982b4ccbf16e5d5562f3e70885f5 | refs/heads/master | 2023-05-10T12:56:13.036456 | 2023-04-27T01:45:19 | 2023-04-27T01:45:19 | 1,224,531 | 61 | 15 | MIT | 2023-04-27T01:45:20 | 2011-01-05T22:14:44 | Scheme | UTF-8 | Scheme | false | false | 81,387 | rkt | x86-opcodes.rkt | ;; -*- mode: scheme; coding: utf-8 -*-
;; Opcode table for the Intel 80x86 processor
;; Copyright © 2008, 2009, 2010, 2012, 2013, 2017, 2018 Göran Weinholt <[email protected]>
;; SPDX-License-Identifier: MIT
#!r6rs
;;; Table syntax
;; <table> --> #(<entry>[256]) ; the index is an opcode byte
;; <entry> --> <table>
;; | <instr>
;; | <prefix-set>
;; | <group>
;; | <datasize>
;; | <addrsize>
;; | <mode>
;; | <sse>
;; | <vex>
;; | <mem/reg>
;; | <f64>
;; | <d64>
;; | #f
;; <instr> --> (<mnemonic> <operand>*)
;; <prefix-set> --> (*prefix* <prefix-name>+)
;; <prefix-name> --> operand | address
;; | cs | ds | es | fs | gs | ss
;; | lock | repz | repnz
;; | rex | rex.w | rex.r | rex.x | rex.b
;; <group> --> #(Group <name>
;; <reg-vector for ModR/M.mod=0, 1 or 2>
;; <reg-vector for ModR/M.mod=3>*)
;; <reg-vector> --> #(<reg-entry>[8]) ; the index is ModR/M.reg
;; <reg-entry> --> #(<entry>[8]) ; the index is ModR/M.R/M
;; | <instr>
;; | <datasize>
;; | <addrsize>
;; | <mode>
;; | <sse>
;; | <vex>
;; | <f64>
;; | <d64>
;; | #f
;; <datasize> --> #(Datasize <entry for 16-bit data>
;; <entry for 32-bit data>
;; <entry for 64-bit data>)
;; <addrsize> --> #(Datasize <entry for 16-bit addressing>
;; <entry for 32-bit addressing>
;; <entry for 64-bit addressing>)
;; <mode> --> #(Mode <entry for 16/32-bit mode>
;; <entry for 64-bit mode>)
;; <sse> --> #(Prefix <entry for no prefix>
;; <entry for F3 prefix>
;; <entry for 66 prefix>
;; <entry for F2 prefix>)
;; <vex> --> #(VEX <entry for no VEX prefix>
;; <entry for VEX.128 prefix>
;; <entry for VEX.256 prefix>*)
;; <mem/reg> --> #(Mem/reg <entry for memory operand in ModR/M>
;; <entry for register operand>)
;; These can be ignored in legacy mode:
;; <f64> --> #(f64 <instr>) ; force 64-bit operand size
;; <d64> --> #(d64 <instr>) ; default 64-bit operand size
;; <name> is a string. <mnemonic> and <operand> are symbols.
;;; Operand syntax
;; The abbreviations here are the same as in the Intel manual,
;; appendix A. Uppercase letters are addressing methods, lower case
;; letters specify operand type. There are some differences though:
;; Normally the operand syntax will have initial upper case letters
;; for designating an addressing method, but where this is not the
;; case a single * has been prepended.
;; "1" has been changed to "*unity", so that all operands are written
;; as symbols.
;; For Intel AVX instructions, the opcode syntaxes K, KW, WK, B, BW,
;; WB, In have been used and are not official.
(library (machine-code disassembler x86-opcodes)
(export
opcodes pseudo-mnemonics mnemonic-aliases
lock-instructions
branch-hint-instructions
rep-instructions
repz-instructions
bnd-instructions
XOP-opcode-map-8 XOP-opcode-map-9 XOP-opcode-map-A)
(import
(rnrs (6)))
(define lock-instructions
'(adc add and btc btr bts cmpxchg cmpxchg8b
cmpxchg16b dec inc neg not or sbb sub
xadd xchg xor))
;; TODO: Can these use hints? loopnz loopz loop jcxz jecxz jrcxz
(define branch-hint-instructions
'(jo jno jb jnb jz jnz jbe jnbe js jns jp jnp jl
jnl jle jnle))
(define rep-instructions
'(ins outs movs lods stos
;; VIA PadLock:
montmul xsha1 xsha256
xstore xcryptecb
xcryptcbc xcryptctr
xcryptcfb xcryptofb))
(define repz-instructions
'(cmps scas))
(define bnd-instructions
'(call ret jmp jo jno jb jnb jz jnz jbe jnbe js
jns jp jnp jl jnl jle jnle))
;; (mnemonic immediate pseudo-op). This table contains a list of
;; pseudo-ops, where `mnemonic' is used in the opcode table,
;; `immediate' specifies a value for the immediate operand, and
;; `pseudo-op' is a programmer-friendly name. The immediate listed
;; is always the last operand in an instruction. Note that some
;; instructions have two encodings: one with a register and one with
;; an immediate.
;; For the *3dnow* mnemonic the rule is that if an immediate is not
;; listed here, it is an illegal opcode. For the other mnemonics an
;; unlisted immediate normally means the original mnemonic should be
;; shown, with immediates preserved.
;; Examples:
;; (*3dnow* mm0 mm1 #xFF) => invalid opcode
;; (*3dnow* mm0 mm1 #x94) <=> (pfmin mm0 mm1)
;; (vpermil2ps xmm0 xmm1 xmm3 xmm4 3) <=> (vpermilmo2ps xmm0 xmm1 xmm3 xmm4)
;; (vpermil2ps xmm0 xmm1 xmm3 xmm4 15) <=> (vpermil2ps xmm0 xmm1 xmm3 xmm4 15)
;; (aam #x0a) <=> (aam)
(define pseudo-mnemonics
'((*3dnow* #x0C pi2fw)
(*3dnow* #x0D pi2fd)
(*3dnow* #x1C pf2iw)
(*3dnow* #x1D pf2id)
(*3dnow* #x80 pfnacc)
(*3dnow* #x8E pfpnacc)
(*3dnow* #x90 pfcmpge)
(*3dnow* #x94 pfmin)
(*3dnow* #x96 pfrcp)
(*3dnow* #x97 pfrsqrt)
(*3dnow* #x9A pfsub)
(*3dnow* #x9E pfadd)
(*3dnow* #xA0 pfcmpgt)
(*3dnow* #xA4 pfmax)
(*3dnow* #xA6 pfrcpit1)
(*3dnow* #xA7 pfrsqit1)
(*3dnow* #xAA pfsubr)
(*3dnow* #xAA pfacc)
(*3dnow* #xB0 pfcmpeq)
(*3dnow* #xB4 pfmul)
(*3dnow* #xB6 pfrcpit2)
(*3dnow* #xB7 pmulhrw)
(*3dnow* #xBB pswapd)
(*3dnow* #xBF pavgusb)
;; These two are from AMD Geode:
(*3dnow* #x86 pfrcpv)
(*3dnow* #x87 pfrsqrtv)
(aam #x0A aam)
(aad #x0A aad)
(vpermil2pd #b0000 vpermiltd2pd)
(vpermil2pd #b0001 vpermiltd2pd)
(vpermil2pd #b0010 vpermilmo2pd)
(vpermil2pd #b0011 vpermilmz2pd)
(vpermil2ps #b0000 vpermiltd2ps)
(vpermil2ps #b0001 vpermiltd2ps)
(vpermil2ps #b0010 vpermilmo2ps)
(vpermil2ps #b0011 vpermilmz2ps)
(pclmulqdq #b00000000 pclmullqlqdq)
(pclmulqdq #b00000001 pclmulhqlqdq)
(pclmulqdq #b00010000 pclmullqhqdq)
(pclmulqdq #b00010001 pclmulhqhqdq)
(cmppd 0 cmpeqpd)
(cmppd 1 cmpltpd)
(cmppd 2 cmplepd)
(cmppd 3 cmpunordpd)
(cmppd 4 cmpneqpd)
(cmppd 5 cmpnltpd)
(cmppd 6 cmpnlepd)
(cmppd 7 cmpordpd)
(vcmppd #x00 vcmpeqpd)
(vcmppd #x01 vcmpltpd)
(vcmppd #x02 vcmplepd)
(vcmppd #x03 vcmpunordpd)
(vcmppd #x04 vcmpneqpd)
(vcmppd #x05 vcmpnltpd)
(vcmppd #x06 vcmpnlepd)
(vcmppd #x07 vcmpordpd)
(vcmppd #x08 vcmpeq_uqpd)
(vcmppd #x09 vcmpngepd)
(vcmppd #x0a vcmpngtpd)
(vcmppd #x0b vcmpfalsepd)
(vcmppd #x0c vcmpneq_oqpd)
(vcmppd #x0d vcmpgepd)
(vcmppd #x0e vcmpgtpd)
(vcmppd #x0f vcmptruepd)
(vcmppd #x10 vcmpeq_ospd)
(vcmppd #x11 vcmplt_oqpd)
(vcmppd #x12 vcmple_oqpd)
(vcmppd #x13 vcmpunord_spd)
(vcmppd #x14 vcmpneq_uspd)
(vcmppd #x15 vcmpnlt_uqpd)
(vcmppd #x16 vcmpnle_uqpd)
(vcmppd #x17 vcmpord_spd)
(vcmppd #x18 vcmpeq_uspd)
(vcmppd #x19 vcmpnge_uqpd)
(vcmppd #x1a vcmpngt_uqpd)
(vcmppd #x1b vcmpfalse_ospd)
(vcmppd #x1c vcmpneq_ospd)
(vcmppd #x1d vcmpge_oqpd)
(vcmppd #x1e vcmpgt_oqpd)
(vcmppd #x1f vcmptrue_uspd)
(cmpps 0 cmpeqps)
(cmpps 1 cmpltps)
(cmpps 2 cmpleps)
(cmpps 3 cmpunordps)
(cmpps 4 cmpneqps)
(cmpps 5 cmpnltps)
(cmpps 6 cmpnleps)
(cmpps 7 cmpordps)
(vcmpps #x00 vcmpeqps)
(vcmpps #x01 vcmpltps)
(vcmpps #x02 vcmpleps)
(vcmpps #x03 vcmpunordps)
(vcmpps #x04 vcmpneqps)
(vcmpps #x05 vcmpnltps)
(vcmpps #x06 vcmpnleps)
(vcmpps #x07 vcmpordps)
(vcmpps #x08 vcmpeq_uqps)
(vcmpps #x09 vcmpngeps)
(vcmpps #x0a vcmpngtps)
(vcmpps #x0b vcmpfalseps)
(vcmpps #x0c vcmpneq_oqps)
(vcmpps #x0d vcmpgeps)
(vcmpps #x0e vcmpgtps)
(vcmpps #x0f vcmptrueps)
(vcmpps #x10 vcmpeq_osps)
(vcmpps #x11 vcmplt_oqps)
(vcmpps #x12 vcmple_oqps)
(vcmpps #x13 vcmpunord_sps)
(vcmpps #x14 vcmpneq_usps)
(vcmpps #x15 vcmpnlt_uqps)
(vcmpps #x16 vcmpnle_uqps)
(vcmpps #x17 vcmpord_sps)
(vcmpps #x18 vcmpeq_usps)
(vcmpps #x19 vcmpnge_uqps)
(vcmpps #x1a vcmpngt_uqps)
(vcmpps #x1b vcmpfalse_osps)
(vcmpps #x1c vcmpneq_osps)
(vcmpps #x1d vcmpge_oqps)
(vcmpps #x1e vcmpgt_oqps)
(vcmpps #x1f vcmptrue_usps)
(cmpsd 0 cmpeqsd)
(cmpsd 1 cmpltsd)
(cmpsd 2 cmplesd)
(cmpsd 3 cmpunordsd)
(cmpsd 4 cmpneqsd)
(cmpsd 5 cmpnltsd)
(cmpsd 6 cmpnlesd)
(cmpsd 7 cmpordsd)
(vcmpsd #x00 vcmpeqsd)
(vcmpsd #x01 vcmpltsd)
(vcmpsd #x02 vcmplesd)
(vcmpsd #x03 vcmpunordsd)
(vcmpsd #x04 vcmpneqsd)
(vcmpsd #x05 vcmpnltsd)
(vcmpsd #x06 vcmpnlesd)
(vcmpsd #x07 vcmpordsd)
(vcmpsd #x08 vcmpeq_uqsd)
(vcmpsd #x09 vcmpngesd)
(vcmpsd #x0a vcmpngtsd)
(vcmpsd #x0b vcmpfalsesd)
(vcmpsd #x0c vcmpneq_oqsd)
(vcmpsd #x0d vcmpgesd)
(vcmpsd #x0e vcmpgtsd)
(vcmpsd #x0f vcmptruesd)
(vcmpsd #x10 vcmpeq_ossd)
(vcmpsd #x11 vcmplt_oqsd)
(vcmpsd #x12 vcmple_oqsd)
(vcmpsd #x13 vcmpunord_ssd)
(vcmpsd #x14 vcmpneq_ussd)
(vcmpsd #x15 vcmpnlt_uqsd)
(vcmpsd #x16 vcmpnle_uqsd)
(vcmpsd #x17 vcmpord_ssd)
(vcmpsd #x18 vcmpeq_ussd)
(vcmpsd #x19 vcmpnge_uqsd)
(vcmpsd #x1a vcmpngt_uqsd)
(vcmpsd #x1b vcmpfalse_ossd)
(vcmpsd #x1c vcmpneq_ossd)
(vcmpsd #x1d vcmpge_oqsd)
(vcmpsd #x1e vcmpgt_oqsd)
(vcmpsd #x1f vcmptrue_ussd)
(cmpss 0 cmpeqss)
(cmpss 1 cmpltss)
(cmpss 2 cmpless)
(cmpss 3 cmpunordss)
(cmpss 4 cmpneqss)
(cmpss 5 cmpnltss)
(cmpss 6 cmpnless)
(cmpss 7 cmpordss)
(vcmpss #x00 vcmpeqss)
(vcmpss #x01 vcmpltss)
(vcmpss #x02 vcmpless)
(vcmpss #x03 vcmpunordss)
(vcmpss #x04 vcmpneqss)
(vcmpss #x05 vcmpnltss)
(vcmpss #x06 vcmpnless)
(vcmpss #x07 vcmpordss)
(vcmpss #x08 vcmpeq_uqss)
(vcmpss #x09 vcmpngess)
(vcmpss #x0a vcmpngtss)
(vcmpss #x0b vcmpfalsess)
(vcmpss #x0c vcmpneq_oqss)
(vcmpss #x0d vcmpgess)
(vcmpss #x0e vcmpgtss)
(vcmpss #x0f vcmptruess)
(vcmpss #x10 vcmpeq_osss)
(vcmpss #x11 vcmplt_oqss)
(vcmpss #x12 vcmple_oqss)
(vcmpss #x13 vcmpunord_sss)
(vcmpss #x14 vcmpneq_usss)
(vcmpss #x15 vcmpnlt_uqss)
(vcmpss #x16 vcmpnle_uqss)
(vcmpss #x17 vcmpord_sss)
(vcmpss #x18 vcmpeq_usss)
(vcmpss #x19 vcmpnge_uqss)
(vcmpss #x1a vcmpngt_uqss)
(vcmpss #x1b vcmpfalse_osss)
(vcmpss #x1c vcmpneq_osss)
(vcmpss #x1d vcmpge_oqss)
(vcmpss #x1e vcmpgt_oqss)
(vcmpss #x1f vcmptrue_usss)))
;; A mapping from common alternative mnemonics to the mnemonics
;; used in the opcodes table.
(define mnemonic-aliases
'((wait . fwait)
(sal . shl)
(xlat . xlatb)
(loope . loopz)
(loopne . loopnz)
(jnae . jb) (setnae . setb) (cmovnae . cmovb)
(jae . jnb) (setae . setnb) (cmovae . cmovnb)
(je . jz) (sete . setz) (cmove . cmovz)
(jne . jnz) (setne . setnz) (cmovne . cmovnz)
(jna . jbe) (setna . setbe) (cmovna . cmovbe)
(ja . jnbe) (seta . setnbe) (cmova . cmovnbe)
(jpe . jp) (setpe . setp) (cmovpe . cmovp)
(jpo . jnp) (setpo . setnp) (cmovpo . cmovnp)
(jnge . jl) (setnge . setl) (cmovnge . cmovl)
(jge . jnl) (setge . setnl) (cmovge . cmovnl)
(jng . jle) (setng . setle) (cmovng . cmovle)
(jg . jnle) (setg . setnle) (cmovg . cmovnle)
(jc . jb) (setc . setb) (cmovc . cmovb)
(jnc . jnb) (setnc . setnb) (cmovnc . cmovnb)
(int1 . icebp)
(setalc . salc)))
(define opcodes
'#((add Eb Gb)
(add Ev Gv)
(add Gb Eb)
(add Gv Ev)
(add *AL Ib)
(add *rAX Iz)
#(Mode (push *ES) #f)
#(Mode (pop *ES) #f)
;; 08
(or Eb Gb)
(or Ev Gv)
(or Gb Eb)
(or Gv Ev)
(or *AL Ib)
(or *rAX Iz)
#(Mode (push *CS) #f)
;; 0F: Two-byte opcodes
#(#(Group "Group 6"
#((sldt Rv/Mw) (str Rv/Mw) (lldt Ew) (ltr Ew)
(verr Ew) (verw Ew) (jmpe Ev) #f))
#(Group "Group 7"
#((sgdt Ms) (sidt Ms) (lgdt Ms) (lidt Ms)
(smsw Rv/Mw) #f (lmsw Ew) (invlpg Mb))
#(#(#f (vmcall) (vmlaunch) (vmresume) (vmxoff)
#f #f #f)
#((monitor) (mwait) (clac) (stac) #f #f #f #f)
#((xgetbv) (xsetbv) #f #f #f #f #f #f)
#((vmrun) (vmmcall) (vmload) (vmsave)
(stgi) (clgi) (skinit) (invlpga))
(smsw Rv/Mw)
#f
(lmsw Ew)
#(#(Mode #f (swapgs)) (rdtscp) #f #f #f #f #f #f)))
(lar Gv Ew)
(lsl Gv Ew)
#f
#(Mode #f (syscall))
(clts)
#(Mode #f #(Datasize (sysret) (sysret) (sysretq)))
;; 0F 08
(invd)
(wbinvd)
#f
(ud2)
#f
#(Group "Group P"
#((prefetch Mb) (prefetchw Mb)
;; Reserved aliases:
(prefetch Mb) (prefetchw Mb)
(prefetch Mb) (prefetch Mb)
(prefetch Mb) (prefetch Mb)))
(femms)
(*3dnow* Pq Qq Ib)
;; 0F 10
#(Prefix #(VEX (movups Vps Wps) (vmovups Vps Wps))
#(VEX (movss Vss Wss)
#(Mem/reg (vmovss Vss Mq) (vmovss Vss Bss Wss))
#f)
#(VEX (movupd Vpd Wpd) (vmovupd Vpd Wpd))
#(VEX (movsd Vsd Wsd)
#(Mem/reg (vmovsd Vsd Mq) (vmovsd Vsd Bsd Wsd))
#f))
#(Prefix #(VEX (movups Wps Vps) (vmovups Wps Vps))
#(VEX (movss Wss Vss)
#(Mem/reg (vmovss Mq Vss) (vmovss Wss Bss Vss))
#f)
#(VEX (movupd Wpd Vpd) (vmovupd Wpd Vpd))
#(VEX (movsd Wsd Vsd)
#(Mem/reg (vmovsd Mq Vsd) (vmovsd Wsd Bsd Vsd))
#f))
#(Prefix #(VEX #(Mem/reg (movlps Vps Mq) (movhlps Vps Uq))
#(Mem/reg (vmovlps Vps Bps Mq) (vmovhlps Vps Bps Uq))
#f)
#(VEX (movsldup Vps Wps) (vmovsldup Vps Wps))
#(VEX (movlpd Vsd Mq) (vmovlpd Vsd Bsd Mq))
#(VEX (movddup Vpd Wsd) (vmovddup Vpd Wsd)))
#(Prefix #(VEX (movlps Mq Vps) (vmovlps Mq Vps) #f)
#f
#(VEX (movlpd Mq Vsd) (vmovlpd Mq Vsd) #f)
#f)
#(Prefix #(VEX (unpcklps Vps Wq) (vunpcklps Vps Bps Wq)) #f
#(VEX (unpcklpd Vpd Wq) (vunpcklpd Vpd Bpd Wq)) #f)
#(Prefix #(VEX (unpckhps Vps Wq) (vunpckhps Vps Bps Wq)) #f
#(VEX (unpckhpd Vpd Wq) (vunpckhpd Vpd Bpd Wq)) #f)
#(Prefix #(VEX #(Mem/reg (movhps Vps Mq) (movlhps Vps Uq))
#(Mem/reg (vmovhps Vps Bps Mq) (vmovlhps Vps Bps Uq))
#f)
#(VEX (movshdup Vps Wps) (vmovshdup Vps Wps))
#(VEX (movhpd Vsd Mq) (vmovhpd Vsd Bsd Mq) #f)
#f)
#(Prefix #(VEX (movhps Mq Vps) (vmovhps Mq Vps) #f) #f
#(VEX (movhpd Mq Vsd) (vmovhpd Mq Vsd) #f) #f)
;; 0F 18
#(Group "Group 16"
#((prefetchnta Mb) (prefetcht0 Mb)
(prefetcht1 Mb) (prefetcht2 Mb)
;; Reserved for future use:
(prefetchnta Mb) (prefetchnta Mb)
(prefetchnta Mb) (prefetchnta Mb))
#(#f #f #f #f #f #f #f #f))
(nop Ev)
#(Prefix (bndldx bnd Emib)
(bndcl bnd Edq/mode)
(bndmov bnd Ebnd)
(bndcu bnd Edq/mode))
#(Prefix (bndstx Emib bnd)
(bndmk bnd Edq/mode/norel)
(bndmov Ebnd bnd)
(bndcn bnd Edq/mode))
(nop Ev)
(nop Ev)
(nop Ev)
(nop Ev)
;; 0F 20
(mov Rd/q Cd/q)
(mov Rd/q Dd/q)
(mov Cd/q Rd/q)
(mov Dd/q Rd/q)
#f ;(MOV r32,tr). AMD SSE5 was here
#f
#f ;(MOV tr,r32)
#f
;; 0F 28
#(Prefix #(VEX (movaps Vps Wps) (vmovaps Vps Wps))
#f
#(VEX (movapd Vpd Wpd) (vmovapd Vpd Wpd))
#f)
#(Prefix #(VEX (movaps Wps Vps) (vmovaps Vps Wps))
#f
#(VEX (movapd Wpd Vpd) (vmovapd Wpd Vpd))
#f)
#(Prefix (cvtpi2ps Vps Qq)
#(VEX (cvtsi2ss Vss Ed/q)
(vcvtsi2ss Vss Bss Ed/q)
#f)
(cvtpi2pd Vpd Qq)
#(VEX (cvtsi2sd Vsd Ed/q)
(vcvtsi2sd Vsd Bsd Ed/q)
#f))
#(Prefix #(VEX (movntps Mdq Vps)
(vmovntps Mdq Vps)
#f)
(movntss Md Vss)
#(VEX (movntpd Mdq Vpd)
(vmovntpd Mdq Vpd)
#f)
(movntsd Mq Vsd))
#(Prefix (cvttps2pi Pq Wps)
#(VEX (cvttss2si Gd/q Wss)
(vcvttss2si Gd/q Wss)
#f)
(cvttpd2pi Pq Wpd)
#(VEX (cvttsd2si Gd/q Wsd)
(vcvttsd2si Gd/q Wsd)
#f))
#(Prefix (cvtps2pi Pq Wps)
#(VEX (cvtss2si Gd/q Wss)
(vcvtss2si Gd/q Wss)
#f)
(cvtpd2pi Pq Wpd)
#(VEX (cvtsd2si Gd/q Wsd)
(vcvtsd2si Gd/q Wsd)
#f))
#(Prefix #(VEX (ucomiss Vss Wss) (vucomiss Vss Wss) #f)
#f
#(VEX (ucomisd Vsd Wsd) (vucomisd Vsd Wsd) #f)
#f)
#(Prefix #(VEX (comiss Vps Wps)
(vcomiss Vps Wps)
#f)
#f
#(VEX (comisd Vpd Wsd)
(vcomisd Vpd Wsd)
#f)
#f)
;; 0F 30
(wrmsr)
(rdtsc)
(rdmsr)
(rdpmc)
#(Mode (sysenter) #f)
#(Mode (sysexit) #f)
#f
(getsec)
;; 0F 38: Three-byte opcode
#(#(Prefix (pshufb Pq Qq) #f #(VEX (pshufb Vdq Wdq) (vpshufb Vdq Bdq Wdq) #f) #f)
#(Prefix (phaddw Pq Qq) #f #(VEX (phaddw Vdq Wdq) (vphaddw Vdq Bdq Wdq) #f) #f)
#(Prefix (phaddd Pq Qq) #f #(VEX (phaddd Vdq Wdq) (vphaddd Vdq Bdq Wdq) #f) #f)
#(Prefix (phaddsw Pq Qq) #f #(VEX (phaddsw Vdq Wdq) (vphaddsw Vdq Bdq Wdq) #f) #f)
#(Prefix (pmaddubsw Pq Qq) #f #(VEX (pmaddubsw Vdq Wdq) (vpmaddubsw Vdq Bdq Wdq) #f) #f)
#(Prefix (phsubw Pq Qq) #f #(VEX (phsubw Vdq Wdq) (vphsubw Vdq Bdq Wdq) #f) #f)
#(Prefix (phsubd Pq Qq) #f #(VEX (phsubd Vdq Wdq) (vphsubd Vdq Bdq Wdq) #f) #f)
#(Prefix (phsubsw Pq Qq) #f #(VEX (phsubsw Vdq Wdq) (vphsubsw Vdq Bdq Wdq) #f) #f)
;; 0F 38 08
#(Prefix (psignb Pq Qq) #f #(VEX (psignb Vdq Wdq) (vpsignb Vdq Bdq Wdq) #f) #f)
#(Prefix (psignw Pq Qq) #f #(VEX (psignw Vdq Wdq) (vpsignw Vdq Bdq Wdq) #f) #f)
#(Prefix (psignd Pq Qq) #f #(VEX (psignd Vdq Wdq) (vpsignd Vdq Bdq Wdq) #f) #f)
#(Prefix (pmulhrsw Pq Qq) #f #(VEX (pmulhrsw Vdq Wdq) (vpmulhrsw Vdq Bdq Wdq) #f) #f)
#(Prefix #f #f #(VEX #f (vpermilps Vps Bps Wps)) #f)
#(Prefix #f #f #(VEX #f (vpermilpd Vpd Bpd Wpd)) #f)
#(Prefix #f #f #(VEX #f (vtestps Vps Wps)) #f)
#(Prefix #f #f #(VEX #f (vtestpd Vpd Wpd)) #f)
;; 0F 38 10
#(Prefix #f #f (pblendvb Vdq Wdq) #f)
#f #f #f
#(Prefix #f #f (blendvps Vdq Wdq) #f)
#(Prefix #f #f (blendvpd Vdq Wdq) #f)
#f
#(Prefix #f #f #(VEX (ptest Vdq Wdq) (vptest Vdq Wdq)) #f)
;; 0F 38 18
#(Prefix #f #f #(VEX #f (vbroadcastss Vss Md)) #f)
#(Prefix #f #f #(VEX #f #f (vbroadcastsd Vsd Mq)) #f)
#(Prefix #f #f #(VEX #f #f (vbroadcastf128 Vsd Mdq)) #f)
#f
#(Prefix (pabsb Pq Qq) #f
#(VEX (pabsb Vdq Wdq) (vpabsb Vdq Wdq) #f) #f)
#(Prefix (pabsw Pq Qq) #f
#(VEX (pabsw Vdq Wdq) (vpabsw Vdq Wdq) #f) #f)
#(Prefix (pabsd Pq Qq) #f
#(VEX (pabsd Vdq Wdq) (vpabsd Vdq Wdq) #f) #f)
#f
;; 0F 38 20
#(Prefix #f #f #(VEX (pmovsxbw Vdq Udq/Mq) (vpmovsxbw Vdq Udq/Mq) #f) #f)
#(Prefix #f #f #(VEX (pmovsxbd Vdq Udq/Md) (vpmovsxbd Vdq Udq/Md) #f) #f)
#(Prefix #f #f #(VEX (pmovsxbq Vdq Udq/Mw) (vpmovsxbq Vdq Udq/Mw) #f) #f)
#(Prefix #f #f #(VEX (pmovsxwd Vdq Udq/Md) (vpmovsxwd Vdq Udq/Md) #f) #f)
#(Prefix #f #f #(VEX (pmovsxwq Vdq Udq/Mq) (vpmovsxwq Vdq Udq/Mq) #f) #f)
#(Prefix #f #f #(VEX (pmovsxdq Vdq Udq/Mq) (vpmovsxdq Vdq Udq/Mq) #f) #f)
#f #f
;; 0F 38 28
#(Prefix #f #f #(VEX (pmuldq Vdq Wdq) (vpmuldq Vdq Bdq Wdq) #f) #f)
#(Prefix #f #f #(VEX (pcmpeqq Vdq Wdq) (vpcmpeqq Vdq Bdq Wdq) #f) #f)
#(Prefix #f #f #(VEX (movntdqa Vdq Mdq) (vmovntdqa Vdq Mdq) #f) #f)
#(Prefix #f #f #(VEX (packusdw Vdq Wdq) (vpackusdw Vdq Bdq Wdq) #f) #f)
#(Prefix #f #f #(VEX #f (vmaskmovps Vdq Bps Mps)) #f)
#(Prefix #f #f #(VEX #f (vmaskmovpd Vdq Bpd Mpd)) #f)
#(Prefix #f #f #(VEX #f (vmaskmovps Mps Bdq Vps)) #f)
#(Prefix #f #f #(VEX #f (vmaskmovpd Mpd Bdq Vpd)) #f)
;; 0F 38 30
#(Prefix #f #f #(VEX (pmovzxbw Vdq Udq/Mq) (vpmovzxbw Vdq Udq/Mq) #f) #f)
#(Prefix #f #f #(VEX (pmovzxbd Vdq Udq/Md) (vpmovzxbd Vdq Udq/Md) #f) #f)
#(Prefix #f #f #(VEX (pmovzxbq Vdq Udq/Mw) (vpmovzxbq Vdq Udq/Mw) #f) #f)
#(Prefix #f #f #(VEX (pmovzxwd Vdq Udq/Mq) (vpmovzxwd Vdq Udq/Mq) #f) #f)
#(Prefix #f #f #(VEX (pmovzxwq Vdq Udq/Md) (vpmovzxwq Vdq Udq/Md) #f) #f)
#(Prefix #f #f #(VEX (pmovzxdq Vdq Udq/Mq) (vpmovzxdq Vdq Udq/Mq) #f) #f)
#f
#(Prefix #f #f #(VEX (pcmpgtq Vdq Wdq) (vpcmpgtq Vdq Bdq Wdq) #f) #f)
;; 0F 38 38
#(Prefix #f #f #(VEX (pminsb Vdq Wdq) (vpminsb Vdq Bdq Wdq) #f) #f)
#(Prefix #f #f #(VEX (pminsd Vdq Wdq) (vpminsd Vdq Bdq Wdq) #f) #f)
#(Prefix #f #f #(VEX (pminuw Vdq Wdq) (vpminuw Vdq Bdq Wdq) #f) #f)
#(Prefix #f #f #(VEX (pminud Vdq Wdq) (vpminud Vdq Bdq Wdq) #f) #f)
#(Prefix #f #f #(VEX (pmaxsb Vdq Wdq) (vpmaxsb Vdq Bdq Wdq) #f) #f)
#(Prefix #f #f #(VEX (pmaxsd Vdq Wdq) (vpmaxsd Vdq Bdq Wdq) #f) #f)
#(Prefix #f #f #(VEX (pmaxuw Vdq Wdq) (vpmaxuw Vdq Bdq Wdq) #f) #f)
#(Prefix #f #f #(VEX (pmaxud Vdq Wdq) (vpmaxud Vdq Bdq Wdq) #f) #f)
;; 0F 38 40
#(Prefix #f #f #(VEX (pmulld Vdq Wdq) (vpmulld Vdq Bdq Wdq) #f) #f)
#(Prefix #f #f #(VEX (phminposuw Vdq Wdq) (vphminposuw Vdq Wdq) #f) #f)
#f #f #f #f #f #f
;; 0F 38 48
#f #f #f #f #f #f #f #f
;; 0F 38 50
#f #f #f #f #f #f #f #f
;; 0F 38 58
#f #f #f #f #f #f #f #f
;; 0F 38 60
#f #f #f #f #f #f #f #f
;; 0F 38 68
#f #f #f #f #f #f #f #f
;; 0F 38 70
#f #f #f #f #f #f #f #f
;; 0F 38 78
#f #f #f #f #f #f #f #f
;; 0F 38 80
#(Prefix #f
#f
#(Mode (invept Gd Mdq)
(invept Gq Mdq))
#f)
#(Prefix #f
#f
#(Mode (invvpid Gd Mdq)
(invvpid Gq Mdq))
#f)
#f #f #f #f #f #f
;; 0F 38 88
#f #f #f #f #f #f #f #f
;; 0F 38 90
#f #f #f #f
#f #f
#(Prefix #f #f ;FMA4 stuff
#(VEX #f #(Datasize #f
(vfmaddsub132ps Vps Bdq Wps)
(vfmaddsub132pd Vpd Bdq Wpd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfmsubadd132ps Vps Bdq Wps)
(vfmsubadd132pd Vpd Bdq Wpd)))
#f)
;; 0F 38 98
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfmadd132ps Vps Bdq Wps)
(vfmadd132pd Vpd Bdq Wpd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfmadd132ss Vss Bss Wss)
(vfmadd132sd Vsd Bsd Wsd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfmsub132ps Vps Bdq Wps)
(vfmsub132pd Vpd Bdq Wpd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfmsub132ss Vss Bss Wss)
(vfmsub132sd Vsd Bsd Wsd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfnmadd132ps Vps Bdq Wps)
(vfnmadd132pd Vpd Bdq Wpd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfnmadd132ss Vss Bss Wss)
(vfnmadd132sd Vsd Bsd Wsd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfnmsub132ps Vps Bdq Wps)
(vfnmsub132pd Vpd Bdq Wpd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfnmsub132ss Vss Bss Wss)
(vfnmsub132sd Vsd Bsd Wsd)))
#f)
;; 0F 38 A0
#f #f #f #f #f #f
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfmaddsub213ps Vps Bdq Wps)
(vfmaddsub213pd Vpd Bdq Wpd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfmsubadd213ps Vps Bdq Wps)
(vfmsubadd213pd Vpd Bdq Wpd)))
#f)
;; 0F 38 A8
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfmadd213ps Vps Bdq Wps)
(vfmadd213pd Vpd Bdq Wpd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfmadd213ss Vss Bss Wss)
(vfmadd213sd Vsd Bsd Wsd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfmsub213ps Vps Bdq Wps)
(vfmsub213pd Vpd Bdq Wpd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfmsub213ss Vss Bss Wss)
(vfmsub213sd Vsd Bsd Wsd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfnmadd213ps Vps Bdq Wps)
(vfnmadd213pd Vpd Bdq Wpd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfnmadd213ss Vss Bss Wss)
(vfnmadd213sd Vsd Bsd Wsd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfnmsub213ps Vps Bdq Wps)
(vfnmsub213pd Vpd Bdq Wpd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfnmsub213ss Vss Bss Wss)
(vfnmsub213sd Vsd Bsd Wsd)))
#f)
;; 0F 38 B0
#f #f #f #f #f #f
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfmaddsub231ps Vps Bdq Wps)
(vfmaddsub231pd Vpd Bdq Wpd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfmsubadd231ps Vps Bdq Wps)
(vfmsubadd231pd Vpd Bdq Wpd)))
#f)
;; 0F 38 B8
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfmadd231ps Vps Bdq Wps)
(vfmadd231pd Vpd Bdq Wpd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfmadd231ss Vss Bss Wss)
(vfmadd231sd Vsd Bsd Wsd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfmsub231ps Vps Bdq Wps)
(vfmsub231pd Vpd Bdq Wpd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfmsub231ss Vss Bss Wss)
(vfmsub231sd Vsd Bsd Wsd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfnmadd231ps Vps Bdq Wps)
(vfnmadd231pd Vpd Bdq Wpd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfnmadd231ss Vss Bss Wss)
(vfnmadd231sd Vsd Bsd Wsd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfnmsub231ps Vps Bdq Wps)
(vfnmsub231pd Vpd Bdq Wpd)))
#f)
#(Prefix #f #f
#(VEX #f #(Datasize #f
(vfnmsub231ss Vss Bss Wss)
(vfnmsub231sd Vsd Bsd Wsd)))
#f)
;; 0F 38 C0
#f #f #f #f #f #f #f #f
;; 0F 38 C8
#(Prefix (sha1nexte Vdq Wdq) #f #f #f)
#(Prefix (sha1msg1 Vdq Wdq) #f #f #f)
#(Prefix (sha1msg2 Vdq Wdq) #f #f #f)
#(Prefix (sha256rnds2 Vdq Wdq *XMM0) #f #f #f)
#(Prefix (sha256msg1 Vdq Wdq) #f #f #f)
#(Prefix (sha256msg2 Vdq Wdq) #f #f #f)
#f #f
;; 0F 38 D0
#f #f #f #f #f #f #f #f
;; 0F 38 D8
#f #f #f
#(Prefix #f #f #(VEX (aesimc Vdq Wdq) (vaesimc Vo Wo)) #f)
#(Prefix #f #f #(VEX (aesenc Vdq Wdq) (vaesenc Vo Ho Wo)) #f)
#(Prefix #f #f #(VEX (aesenclast Vdq Wdq) (vaesenclast Vo Ho Wo)) #f)
#(Prefix #f #f #(VEX (aesdec Vdq Wdq) (vaesdec Vo Ho Wo)) #f)
#(Prefix #f #f #(VEX (aesdeclast Vdq Wdq) (vaesdeclast Vo Ho Wo)) #f)
;; 0F 38 E0
#f #f #f #f #f #f #f #f
;; 0F 38 E8
#f #f #f #f #f #f #f #f
;; 0F 38 F0
#(Prefix/eos (movbe Gv Mv)
;; XXX: AMD indicates a VEX encoding of this
(crc32 Gd/q Eb))
#(Prefix/eos (movbe Mv Gv)
(crc32 Gd/q Ev))
#(VEX #f (andn Gd/q By Ed/q))
#(Group "VEX group #17"
#(#f
#(VEX #f (blsr By Ed/q))
#(VEX #f (blsmsk By Ed/q))
#(VEX #f (blsi By Ed/q))
#f #f #f #f))
#f #f
#(Prefix #f (adox Gd/q Ed/q) (adcx Gd/q Ed/q) #f)
#(VEX #f (bextr Gd/q Ed/q By))
;; 0F 38 F8
#f #f #f #f #f #f #f #f)
(dmint)
;; 0F 3A: Three-byte opcode (also RDM in AMD Geode)
#(#f
#f
#f
#f
#(Prefix #f #f #(VEX #f (vpermilps Vps Wps Ib)) #f)
#(Prefix #f #f #(VEX #f (vpermilpd Vpd Wpd Ib)) #f)
#(Prefix #f #f #(VEX #f #f (vperm2f128 Vdq Bdq Wdq Ib)) #f)
#f
;; 0F 3A 08
#(Prefix #f #f #(VEX (roundps Vdq Wdq Ib) (vroundps Vdq Wdq Ib)) #f)
#(Prefix #f #f #(VEX (roundpd Vdq Wdq Ib) (vroundpd Vdq Wdq Ib)) #f)
#(Prefix #f #f #(VEX (roundss Vss Wss Ib) (vroundss Vss Bss Wss Ib) #f) #f)
#(Prefix #f #f #(VEX (roundsd Vsd Wsd Ib) (vroundsd Vsd Bsd Wsd Ib) #f) #f)
#(Prefix #f #f #(VEX (blendps Vdq Wdq Ib) (vblendps Vdq Bdq Wdq Ib)) #f)
#(Prefix #f #f #(VEX (blendpd Vdq Wdq Ib) (vblendpd Vdq Bdq Wdq Ib)) #f)
#(Prefix #f #f #(VEX (pblendw Vdq Wdq Ib) (vpblendw Vdq Bdq Wdq Ib) #f) #f)
#(Prefix (palignr Vq Qq Ib) #f
#(VEX (palignr Vdq Wdq Ib)
(vpalignr Vdq Bdq Wdq Ib)
#f)
#f)
;; 0F 3A 10
#f #f #f #f
#(Prefix #f #f #(VEX (pextrb Rd/Mb Vdq Ib) (vpextrb Rd/Mb Vdq Ib) #f) #f)
#(Prefix #f #f #(VEX (pextrw Rd/Mw Vdq Ib) (vpextrw Rd/Mw Vdq Ib) #f) #f)
#(Prefix #f
#f
#(Datasize #f
#(VEX (pextrd Ed Vdq Ib) (vpextrd Ed Vdq Ib) #f)
#(VEX (pextrq Eq Vdq Ib) (vpextrq Eq Vdq Ib) #f))
#f)
#(Prefix #f #f #(VEX (extractps Ed Vdq Ib)
(vextractps Ed Vdq Ib)
#f)
#f)
;; 0F 3A 18
#(Prefix #f #f #(VEX #f #f (vinsertf128 Vdq Bdq Wo Ib)) #f)
#(Prefix #f #f #(VEX #f #f (vextractf128 Wo Bdq Ib)) #f)
#f
#f
#f
#f ;TODO: vcvtps2ph
#f
#f
;; 0F 3A 20
#(Prefix #f #f
#(VEX (pinsrb Vdq Rd/Mb Ib)
(vpinsrb Vdq Bdq Rd/Mb Ib)
#f)
#f)
#(Prefix #f #f
#(VEX (insertps Vdq Udq/Md Ib)
(vinsertps Vdq Bdq Udq/Md Ib)
#f)
#f)
#(Prefix #f
#f
#(Datasize #f
#(VEX (pinsrd Vdq Ed Ib) (vpinsrd Vdq Bdq Ed Ib) #f)
#(VEX (pinsrq Vdq Eq Ib) (vpinsrq Vdq Bdq Eq Ib) #f))
#f)
#f #f #f #f #f
;; 0F 3A 28
#f #f #f #f #f #f #f #f
;; 0F 3A 30
#f #f #f #f #f #f #f #f
;; 0F 3A 38
#f #f #f #f #f #f #f #f
;; 0F 3A 40
#(Prefix #f #f #(VEX (dpps Vps Wps Ib) (vdpps Vps Bps Wpd Ib)) #f)
#(Prefix #f #f #(VEX (dppd Vpd Wpd Ib) (vdppd Vpd Bpd Wpd Ib) #f) #f)
#(Prefix #f #f #(VEX (mpsadbw Vdq Wdq Ib) (vmpsadbw Vdq Bdq Wdq Ib) #f) #f)
#f
#(Prefix #f #f (pclmulqdq Vdq Wdq Ib) #f)
#f
#f
#f
;; 0F 3A 48
#(Prefix #f #f #(VEX #f (vpermil2ps Vps Bps WKps KWps In)) #f)
#(Prefix #f #f #(VEX #f (vpermil2pd Vpd Bpd WKpd KWpd In)) #f)
#(Prefix #f #f #(VEX #f (vblendvps Vx Hx Wx Lx)) #f)
#(Prefix #f #f #(VEX #f (vblendvpd Vx Hx Wx Lx)) #f)
#(Prefix #f #f #(VEX #f (vpblendvb Vo Ho Wo Lo)) #f)
#f
#f
#f
;; 0F 3A 50
#f #f #f #f #f #f #f #f
;; 0F 3A 58
#f
#f
#f
#f
#(Prefix #f #f #(VEX #f (vfmaddsubps Vps Kps WBps BWps)) #f)
#(Prefix #f #f #(VEX #f (vfmaddsubpd Vpd Kpd WBpd BWpd)) #f)
#(Prefix #f #f #(VEX #f (vfmsubaddps Vps Kps WBps BWps)) #f)
#(Prefix #f #f #(VEX #f (vfmsubaddpd Vpd Kpd WBpd BWpd)) #f)
;; 0F 3A 60
#(Prefix #f #f #(VEX (pcmpestrm Vdq Wdq Ib) (vpcmpestrm Vdq Wdq Ib) #f) #f)
#(Prefix #f #f #(VEX (pcmpestri Vdq Wdq Ib) (vpcmpestri Vdq Wdq Ib) #f) #f)
#(Prefix #f #f #(VEX (pcmpistrm Vdq Wdq Ib) (vpcmpistrm Vdq Wdq Ib) #f) #f)
#(Prefix #f #f #(VEX (pcmpistri Vdq Wdq Ib) (vpcmpistri Vdq Wdq Ib) #f) #f)
#f #f #f #f
;; 0F 3A 68
#(Prefix #f #f #(VEX #f (vfmaddps Vps Kps WBps BWps)) #f)
#(Prefix #f #f #(VEX #f (vfmaddpd Vpd Kpd WBpd BWpd)) #f)
#(Prefix #f #f #(VEX #f (vfmaddss Vss Kss WBss BWss) #f) #f)
#(Prefix #f #f #(VEX #f (vfmaddsd Vsd Ksd WBsd BWsd) #f) #f)
#(Prefix #f #f #(VEX #f (vfmsubps Vps Kps WBps BWps)) #f)
#(Prefix #f #f #(VEX #f (vfmsubpd Vpd Kpd WBpd BWpd)) #f)
#(Prefix #f #f #(VEX #f (vfmsubss Vss Kss WBss BWss) #f) #f)
#(Prefix #f #f #(VEX #f (vfmsubsd Vsd Ksd WBsd BWsd) #f) #f)
;; 0F 3A 70
#f #f #f #f #f #f #f #f
;; 0F 3A 78
#(Prefix #f #f #(VEX #f (vfnmaddps Vps Kps WBps BWps)) #f)
#(Prefix #f #f #(VEX #f (vfnmaddpd Vpd Kpd WBpd BWpd)) #f)
#(Prefix #f #f #(VEX #f (vfnmaddss Vss Kss WBss BWss) #f) #f)
#(Prefix #f #f #(VEX #f (vfnmaddsd Vsd Ksd WBsd BWsd) #f) #f)
#(Prefix #f #f #(VEX #f (vfnmsubps Vps Kps WBps BWps)) #f)
#(Prefix #f #f #(VEX #f (vfnmsubpd Vpd Kpd WBpd BWpd)) #f)
#(Prefix #f #f #(VEX #f (vfnmsubss Vss Kss WBss BWss) #f) #f)
#(Prefix #f #f #(VEX #f (vfnmsubsd Vsd Ksd WBsd BWsd) #f) #f)
;; 0F 3A 80
#f #f #f #f #f #f #f #f
;; 0F 3A 88
#f #f #f #f #f #f #f #f
;; 0F 3A 90
#f #f #f #f #f #f #f #f
;; 0F 3A 98
#f #f #f #f #f #f #f #f
;; 0F 3A A0
#f #f #f #f #f #f #f #f
;; 0F 3A A8
#f #f #f #f #f #f #f #f
;; 0F 3A B0
#f #f #f #f #f #f #f #f
;; 0F 3A B8
#f #f #f #f #f #f #f #f
;; 0F 3A C0
#f #f #f #f #f #f #f #f
;; 0F 3A C8
#f #f #f #f
#(Prefix (sha1rnds4 Vdq Wdq Ib) #f #f #f)
#f #f #f
;; 0F 3A D0
#f #f #f #f #f #f #f #f
;; 0F 3A D8
#f #f #f #f #f #f #f
#(Prefix #f #f
#(VEX (aeskeygenassist Vdq Wdq Ib) (vaeskeygenassist Vdq Wo Ib))
#f)
;; 0F 3A E0
#f #f #f #f #f #f #f #f
;; 0F 3A E8
#f #f #f #f #f #f #f #f
;; 0F 3A F0
#f #f #f #f #f #f #f #f
;; 0F 3A F8
#f #f #f #f #f #f #f #f)
#f #f #f #f #f
;; 0F 40
(cmovo Gv Ev)
(cmovno Gv Ev)
(cmovb Gv Ev)
(cmovnb Gv Ev)
(cmovz Gv Ev)
(cmovnz Gv Ev)
(cmovbe Gv Ev)
(cmovnbe Gv Ev)
;; 0F 48
(cmovs Gv Ev)
(cmovns Gv Ev)
(cmovp Gv Ev)
(cmovnp Gv Ev)
(cmovl Gv Ev)
(cmovnl Gv Ev)
(cmovle Gv Ev)
(cmovnle Gv Ev)
;; 0F 50
#(Prefix #(VEX (movmskps Gd Ups) (vmovmskps Gd Ups)) #f
#(VEX (movmskpd Gd Upd) (vmovmskpd Gd Upd)) #f)
#(Prefix #(VEX (sqrtps Vps Wps) (vsqrtps Vps Wps))
#(VEX (sqrtss Vss Wss) (vsqrtss Vss Bss Wss) #f)
#(VEX (sqrtpd Vpd Wpd) (vsqrtpd Vpd Wpd))
#(VEX (sqrtsd Vsd Wsd) (vsqrtsd Vsd Bsd Wsd) #f))
#(Prefix #(VEX (rsqrtps Vps Wps) (vrsqrtps Vps Wps))
#(VEX (rsqrtss Vss Wss) (vrsqrtss Vss Bss Wss) #f)
#f #f)
#(Prefix #(VEX (rcpps Vps Wps) (vrcpps Vps Wps))
#(VEX (rcpss Vss Wss) (vrcpss Vss Bss Wss) #f)
#f #f)
#(Prefix #(VEX (andps Vps Wps) (vandps Vps Bps Wps)) #f
#(VEX (andpd Vpd Wpd) (vandpd Vpd Bpd Wpd)) #f)
#(Prefix #(VEX (andnps Vps Wps) (vandnps Vpd Bpd Wpd)) #f
#(VEX (andnpd Vpd Wpd) (vandnpd Vpd Bpd Wpd)) #f)
#(Prefix #(VEX (orps Vps Wps) (vorps Vps Bps Wps)) #f
#(VEX (orpd Vpd Wpd) (vorpd Vpd Bpd Wpd)) #f)
#(Prefix #(VEX (xorps Vps Wps) (vxorps Vps Bps Wps)) #f
#(VEX (xorpd Vpd Wpd) (vxorpd Vpd Bpd Wpd)) #f)
;; 0F 58
#(Prefix #(VEX (addps Vps Wps)
(vaddps Vps Bps Wps))
#(VEX (addss Vss Wss)
(vaddss Vss Bss Wss)
#f)
#(VEX (addpd Vpd Wpd)
(vaddpd Vpd Bpd Wpd))
#(VEX (addsd Vsd Wsd)
(vaddsd Vsd Bsd Wsd)
#f))
#(Prefix #(VEX (mulps Vps Wps) (vmulps Vps Bps Wps))
#(VEX (mulss Vss Wss) (vmulss Vss Bss Wss) #f)
#(VEX (mulpd Vpd Wpd) (vmulpd Vpd Bpd Wpd))
#(VEX (mulsd Vsd Wsd) (vmulsd Vsd Bsd Wsd) #f))
#(Prefix #(VEX (cvtps2pd Vpd Wps)
(vcvtps2pd Vpd Wps/128))
#(VEX (cvtss2sd Vsd Wss)
(vcvtss2sd Vsd Bdq Wss)
#f)
#(VEX (cvtpd2ps Vps Wpd)
(vcvtpd2ps Vps Wpd))
#(VEX (cvtsd2ss Vss Wsd)
(vcvtsd2ss Vss Bdq Wsd)))
#(Prefix #(VEX (cvtdq2ps Vps Wdq)
(vcvtdq2ps Vps Wdq))
#(VEX (cvttps2dq Vdq Wps)
(vcvttps2dq Vdq Wps))
#(VEX (cvtps2dq Vdq Wps)
(vcvtps2dq Vdq Wps))
#f)
#(Prefix #(VEX (subps Vps Wps) (vsubps Vps Bps Wps))
#(VEX (subss Vss Wss) (vsubss Vss Bss Wss) #f)
#(VEX (subpd Vpd Wpd) (vsubpd Vpd Bpd Wpd))
#(VEX (subsd Vsd Wsd) (vsubsd Vsd Bsd Wsd) #f))
#(Prefix #(VEX (minps Vps Wps) (vminps Vps Bps Wps))
#(VEX (minss Vss Wss) (vminss Vss Bss Wss) #f)
#(VEX (minpd Vpd Wpd) (vminpd Vpd Bpd Wpd))
#(VEX (minsd Vsd Wsd) (vminsd Vsd Bsd Wsd) #f))
#(Prefix #(VEX (divps Vps Wps) (vdivps Vps Bps Wps))
#(VEX (divss Vss Wss) (vdivss Vss Bss Wss) #f)
#(VEX (divpd Vpd Wpd) (vdivpd Vpd Bpd Wpd))
#(VEX (divsd Vsd Wsd) (vdivsd Vsd Bsd Wsd) #f))
#(Prefix #(VEX (maxps Vps Wps) (vmaxps Vps Bps Wps))
#(VEX (maxss Vss Wss) (vmaxss Vss Bss Wss) #f)
#(VEX (maxpd Vpd Wpd) (vmaxpd Vpd Bpd Wpd))
#(VEX (maxsd Vsd Wsd) (vmaxsd Vsd Bsd Wpd) #f))
;; 0F 60
#(Prefix (punpcklbw Pq Qd) #f #(VEX (punpcklbw Vdq Wq) (vpunpcklbw Vdq Bdq Wq) #f) #f)
#(Prefix (punpcklwd Pq Qd) #f #(VEX (punpcklwd Vdq Wq) (vpunpcklwd Vdq Bdq Wq) #f) #f)
#(Prefix (punpckldq Pq Qd) #f #(VEX (punpckldq Vdq Wq) (vpunpckldq Vdq Bdq Wq) #f) #f)
#(Prefix (packsswb Pq Qq) #f #(VEX (packsswb Vdq Wdq) (vpacksswb Vdq Bdq Wdq) #f) #f)
#(Prefix (pcmpgtb Pq Qq) #f #(VEX (pcmpgtb Vdq Wdq) (vpcmpgtb Vdq Bdq Wdq) #f) #f)
#(Prefix (pcmpgtw Pq Qq) #f #(VEX (pcmpgtw Vdq Wdq) (vpcmpgtw Vdq Bdq Wdq) #f) #f)
#(Prefix (pcmpgtd Pq Qq) #f #(VEX (pcmpgtd Vdq Wdq) (vpcmpgtd Vdq Bdq Wdq) #f) #f)
#(Prefix (packuswb Pq Qq) #f #(VEX (packuswb Vdq Wdq) (vpackuswb Vdq Wdq) #f) #f)
;; 0F 68
#(Prefix (punpckhbw Pq Qd) #f #(VEX (punpckhbw Vdq Wq) (vpunpckhbw Vdq Bdq Wq) #f) #f)
#(Prefix (punpckhwd Pq Qd) #f #(VEX (punpckhwd Vdq Wq) (vpunpckhwd Vdq Bdq Wq) #f) #f)
#(Prefix (punpckhdq Pq Qd) #f #(VEX (punpckhdq Vdq Wq) (vpunpckhdq Vdq Bdq Wq) #f) #f)
#(Prefix (packssdw Pq Qq) #f #(VEX (packssdw Vdq Wdq) (vpackssdw Vdq Bdq Wdq) #f) #f)
#(Prefix #f #f #(VEX (punpcklqdq Vdq Wq) (vpunpcklqdq Vdq Bdq Wq) #f) #f)
#(Prefix #f #f #(VEX (punpckhqdq Vdq Wq) (vpunpckhqdq Vdq Bdq Wq) #f) #f)
#(Prefix #(Datasize #f
(movd Pq Ed)
(movq Pq Eq))
#f
#(Datasize #f
#(VEX (movd Vdq Ed) (vmovd Vdq Ed) #f)
#(VEX (movq Vdq Eq) (vmovq Vdq Eq) #f))
#f)
#(Prefix (movq Pq Qq)
#(VEX (movdqu Vdq Wdq) (vmovdqu Vdq Wdq))
#(VEX (movdqa Vdq Wdq) (vmovdqa Vdq Wdq))
#f)
;; 0F 70
#(Prefix (pshufw Pq Qq Ib)
#(VEX (pshufhw Vdq Wdq Ib) (vpshufhw Vdq Wdq Ib) #f)
#(VEX (pshufd Vdq Wdq Ib) (vpshufd Vdq Wdq Ib) #f)
#(VEX (pshuflw Vdq Wdq Ib) (vpshuflw Vdq Wdq Ib) #f))
#(Group "Group 12"
#(#f #f #f #f #f #f #f #f)
#(#f #f
#(Prefix (psrlw Nq Ib) #f #(VEX (psrlw Udq Ib) (vpsrlw Bdq Udq Ib) #f) #f) #f
#(Prefix (psraw Nq Ib) #f #(VEX (psraw Udq Ib) (vpsraw Bdq Udq Ib) #f) #f) #f
#(Prefix (psllw Nq Ib) #f #(VEX (psllw Udq Ib) (vpsllw Bdq Udq Ib) #f) #f) #f))
#(Group "Group 13"
#(#f #f #f #f #f #f #f #f)
#(#f #f
#(Prefix (psrld Nq Ib) #f #(VEX (psrld Udq Ib) (vpsrld Bdq Udq Ib) #f) #f) #f
#(Prefix (psrad Nq Ib) #f #(VEX (psrad Udq Ib) (vpsrad Bdq Udq Ib) #f) #f) #f
#(Prefix (pslld Nq Ib) #f #(VEX (pslld Udq Ib) (vpslld Bdq Udq Ib) #f) #f) #f))
#(Group "Group 14"
#(#f #f #f #f #f #f #f #f)
#(#f #f
#(Prefix (psrlq Nq Ib) #f #(VEX (psrlq Udq Ib) (vpsrlq Bdq Udq Ib) #f) #f)
#(Prefix #f #f #(VEX (psrldq Udq Ib) (vpsrldq Bdq Udq Ib) #f) #f)
#f #f
#(Prefix (psllq Nq Ib) #f #(VEX (psllq Udq Ib) (vpsllq Bdq Udq Ib) #f) #f)
#(Prefix #f #f #(VEX (pslldq Udq Ib) (vpslldq Bdq Udq Ib) #f) #f)))
#(Prefix (pcmpeqb Pq Qq) #f #(VEX (pcmpeqb Vdq Wdq) (vpcmpeqb Vdq Bdq Wdq) #f) #f)
#(Prefix (pcmpeqw Pq Qq) #f #(VEX (pcmpeqw Vdq Wdq) (vpcmpeqw Vdq Bdq Wdq) #f) #f)
#(Prefix (pcmpeqd Pq Qq) #f #(VEX (pcmpeqd Vdq Wdq) (vpcmpeqd Vdq Bdq Wdq) #f) #f)
#(Prefix #(VEX (emms) (vzeroupper) (vzeroall)) #f #f #f)
;; 0F 78
#(Prefix #(Mode (vmread Ed Gd) ;SVDC sr, m80 on AMD Geode
(vmread Eq Gq))
#f
#(Group "Group 17"
#((extrq Vdq Ib Ib)
#f #f #f #f #f #f #f))
(insertq Vdq Uq Ib Ib))
#(Prefix #(Mode (vmwrite Gd Ed) ;RSDC sr, m80 on AMD Geode
(vmwrite Gq Eq))
#f
(extrq Vdq Uq)
(insertq Vdq Udq))
;; 0F 7A: AMD SSE5 (also SVLDT m80 on AMD Geode)
#(#f #f #f #f #f #f #f #f
;; 0F 7A 08
#f #f #f #f #f #f #f #f
;; 0F 7A 10
(frczps Vps Wps)
(frczpd Vpd Wpd)
(frczss Vss Wss)
(frczsd Vsd Wsd)
#f #f #f #f
;; 0F 7A 18
#f #f #f #f #f #f #f #f
;; 0F 7A 20
#f #f #f #f #f #f #f #f
;; 0F 7A 28
#f #f #f #f #f #f #f #f
;; 0F 7A 30
(cvtph2ps Vps Wdq)
(cvtps2ph Wdq Vps)
#f #f #f #f #f #f
;; 0F 7A 38
#f #f #f #f #f #f #f #f
;; 0F 7A 40
#f
(phaddbw Vdq Wdq)
(phaddbd Vdq Wdq)
(phaddbq Vdq Wdq)
#f #f
(phaddwd Vdq Wdq)
(phaddwq Vdq Wdq)
;; 0F 7A 48
#f #f #f
(phadddq Vdq Wdq)
#f #f #f #f
;; 0F 7A 50
#f
(phaddubw Vdq Wdq)
(phaddubd Vdq Wdq)
(phaddubq Vdq Wdq)
#f #f
(phadduwd Vdq Wdq)
(phadduwq Vdq Wdq)
;; 0F 7A 58
#f #f #f
(phaddudq Vdq Wdq)
#f #f #f #f
;; 0F 7A 60
#f
(phsubbw Vdq Wdq)
(phsubwd Vdq Wdq)
(phsubdq Vdq Wdq)
#f #f #f #f
;; 0F 7A 68
#f #f #f #f #f #f #f #f
;; 0F 7A 70
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 0F 7A 80
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 0F 7A 90
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 0F 7A A0
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 0F 7A B0
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 0F 7A C0
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 0F 7A D0
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 0F 7A E0
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 0F 7A F0
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f)
;; AMD SSE5 (RSLDT m80 on AMD Geode)
#(#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
#f #f #f #f #f #f #f
;; 0F 7B 40
(protb Vpd Wdq Ib)
(protw Vpd Wdq Ib)
(protd Vpd Wdq Ib)
(protq Vpd Wdq Ib)
#f #f #f #f #f #f #f
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
#f #f #f #f #f #f #f #f #f #f)
#(Prefix (svts Mem80)
#f
#(VEX (haddpd Vpd Wpd) (vhaddpd Vpd Bpd Wpd))
#(VEX (haddps Vps Wps) (vhaddps Vps Bps Wps)))
#(Prefix (rsts Mem80)
#f
#(VEX (hsubpd Vpd Wpd) (vhsubpd Vpd Bpd Wpd))
#(VEX (hsubps Vps Wps) (vhsubps Vps Bps Wps)))
#(Prefix #(Datasize #f
(movd Ed Pq)
(movq Eq Pq))
#(VEX (movq Vq Wq) (vmovq Vq Wq) #f)
#(Datasize #f
#(VEX (movd Ed Vdq) (vmovd Ed Vdq) #f)
#(VEX (movq Eq Vdq) (vmovq Eq Vdq) #f))
#f)
#(Prefix (movq Qq Pq)
#(VEX (movdqu Wdq Vdq) (vmovdqu Wdq Vdq))
#(VEX (movdqa Wdq Vdq) (vmovdqa Wdq Vdq))
#f)
;; 0F 80
#(f64 (jo Jz))
#(f64 (jno Jz))
#(f64 (jb Jz))
#(f64 (jnb Jz))
#(f64 (jz Jz))
#(f64 (jnz Jz))
#(f64 (jbe Jz))
#(f64 (jnbe Jz))
;; 0F 88
#(f64 (js Jz))
#(f64 (jns Jz))
#(f64 (jp Jz))
#(f64 (jnp Jz))
#(f64 (jl Jz))
#(f64 (jnl Jz))
#(f64 (jle Jz))
#(f64 (jnle Jz))
;; 0F 90
(seto Eb)
(setno Eb)
(setb Eb)
(setnb Eb)
(setz Eb)
(setnz Eb)
(setbe Eb)
(setnbe Eb)
;; 0F 98
(sets Eb)
(setns Eb)
(setp Eb)
(setnp Eb)
(setl Eb)
(setnl Eb)
(setle Eb)
(setnle Eb)
;; 0F A0
#(d64 (push *FS))
#(d64 (pop *FS))
(cpuid)
(bt Ev Gv)
(shld Ev Gv Ib)
(shld Ev Gv *CL)
#(Group "VIA PadLock Group"
#(#f #f #f #f #f #f #f #f)
#((montmul) (xsha1) (xsha256)
#f #f #f #f #f))
#(Group "VIA PadLock Group"
#(#f #f #f #f #f #f #f #f)
#((xstore) (xcryptecb)
(xcryptcbc) (xcryptctr)
(xcryptcfb) (xcryptofb)
#f #f))
;; 0F A8
#(d64 (push *GS))
#(d64 (pop *GS))
(rsm)
(bts Ev Gv)
(shrd Ev Gv Ib)
(shrd Ev Gv *CL)
#(Group "Group 15"
#((fxsave M) (fxrstor M)
#(VEX (ldmxcsr Md) (vldmxcsr Md) #f)
#(VEX (stmxcsr Md) (vstmxcsr Md) #f)
(xsave M) (xrstor M) #f (clflush Mb))
#(#f #f #f #f #f (lfence) (mfence) (sfence)))
(imul Gv Ev)
;; 0F B0
(cmpxchg Eb Gb)
(cmpxchg Ev Gv)
(lss Gv Mp)
(btr Ev Gv)
(lfs Gv Mp)
(lgs Gv Mp)
(movzx Gv Eb)
(movzx Gv Ew)
;; 0F B8
#(Prefix (jmpe Jz) (popcnt Gv Ev) #f #f)
#(Group "Group 10"
#(#f #f #f #f #f #f #f #f))
#(Group "Group 8"
#(#f #f #f #f
(bt Ev Ib) (bts Ev Ib)
(btr Ev Ib) (btc Ev Ib)))
(btc Ev Gv)
(bsf Gv Ev)
#(Prefix (bsr Gv Ev) (lzcnt Gv Ev) #f #f)
(movsx Gv Eb)
(movsx Gv Ew)
;; 0F C0
(xadd Eb Gb)
(xadd Ev Gv)
#(Prefix #(VEX (cmpps Vps Wps Ib)
(vcmpps Vps Bps Wps Ib))
#(VEX (cmpss Vss Wss Ib)
(vcmpss Vss Bss Wss Ib)
#f)
#(VEX (cmppd Vpd Wpd Ib)
(vcmppd Vpd Bpd Wpd Ib))
#(VEX (cmpsd Vsd Wsd Ib)
(vcmpsd Vsd Bsd Wsd Ib)
#f))
(movnti Md/q Gd/q)
#(Prefix (pinsrw Pq Ew Ib) #f
#(VEX (pinsrw Vdq Rd/Mw Ib) (vpinsrw Vdq Bdq Rd/Mw Ib) #f) #f)
#(Prefix (pextrw Gd Nq Ib) #f
#(VEX (pextrw Gd Udq Ib) (vpextrw Gd Udq Ib) #f) #f)
#(Prefix #(VEX (shufps Vps Wps Ib) (vshufps Vps Bps Wps Ib)) #f
#(VEX (shufpd Vpd Wpd Ib) (vshufpd Vpd Bpd Wpd Ib)) #f)
#(Group "Group 9"
#(#f #(Datasize #f
(cmpxchg8b Mq)
(cmpxchg16b Mdq))
#f #f #f #f
#(Prefix (vmptrld Mq) (vmxon Mq) (vmclear Mq) #f)
(vmptrst Mq))
#(#f #f #f #f #f #f (rdrand Ev) (rdseed Ev)))
;; 0F C8
(bswap *rAX/r8)
(bswap *rCX/r9)
(bswap *rDX/r10)
(bswap *rBX/r11)
(bswap *rSP/r12)
(bswap *rBP/r13)
(bswap *rSI/r14)
(bswap *rDI/r15)
;; 0F D0
#(Prefix #f #f
#(VEX (addsubpd Vpd Wpd)
(vaddsubpd Vpd Bpd Wpd))
#(VEX (addsubps Vps Wps)
(vaddsubps Vps Bps Wps)))
#(Prefix (psrlw Pq Qq) #f #(VEX (psrlw Vdq Wdq) (vpsrlw Vdq Bdq Wdq) #f) #f)
#(Prefix (psrld Pq Qq) #f #(VEX (psrld Vdq Wdq) (vpsrld Vdq Bdq Wdq) #f) #f)
#(Prefix (psrlq Pq Qq) #f #(VEX (psrlq Vdq Wdq) (vpsrlq Vdq Bdq Wdq) #f) #f)
#(Prefix (paddq Pq Qq) #f #(VEX (paddq Vdq Wdq) (vpaddq Vdq Bdq Wdq) #f) #f)
#(Prefix (pmullw Pq Qq) #f #(VEX (pmullw Vdq Wdq) (vpmullw Vdq Bdq Wdq) #f) #f)
#(Prefix #f
(movq2dq Vdq Nq)
#(VEX (movq Wq Vq) (vmovq Wq Vq) #f)
(movdq2q Pq Nq))
#(Prefix (pmovmskb Gd Nq) #f #(VEX (pmovmskb Gd Udq) (vpmovmskb Gd Udq) #f) #f)
;; 0F D8 (also SMINT)
#(Prefix (psubusb Pq Qq) #f #(VEX (psubusb Vdq Wdq) (vpsubusb Vdq Bdq Wdq) #f) #f)
#(Prefix (psubusw Pq Qq) #f #(VEX (psubusw Vdq Wdq) (vpsubusw Vdq Bdq Wdq) #f) #f)
#(Prefix (pminub Pq Qq) #f #(VEX (pminub Vdq Wdq) (vpminub Vdq Bdq Wdq) #f) #f)
#(Prefix (pand Pq Qq) #f #(VEX (pand Vdq Wdq) (vpand Vdq Bdq Wdq) #f) #f)
#(Prefix (paddusb Pq Qq) #f #(VEX (paddusb Vdq Wdq) (vpaddusb Vdq Bdq Wdq) #f) #f)
#(Prefix (paddusw Pq Qq) #f #(VEX (paddusw Vdq Wdq) (vpaddusw Vdq Bdq Wdq) #f) #f)
#(Prefix (pmaxub Pq Qq) #f #(VEX (pmaxub Vdq Wdq) (vpmaxub Vdq Bdq Wdq) #f) #f)
#(Prefix (pandn Pq Qq) #f #(VEX (pandn Vdq Wdq) (vpandn Vdq Bdq Wdq) #f) #f)
;; 0F E0
#(Prefix (pavgb Pq Qq) #f #(VEX (pavgb Vdq Wdq) (vpavgb Vdq Bdq Wdq) #f) #f)
#(Prefix (psraw Pq Qq) #f #(VEX (psraw Vdq Wdq) (vpsraw Vdq Bdq Wdq) #f) #f)
#(Prefix (psrad Pq Qq) #f #(VEX (psrad Vdq Wdq) (vpsrad Vdq Bdq Wdq) #f) #f)
#(Prefix (pavgw Pq Qq) #f #(VEX (pavgw Wdq Wdq) (vpavgw Vdq Bdq Wdq) #f) #f)
#(Prefix (pmulhuw Pq Qq) #f #(VEX (pmulhuw Vdq Wdq) (vpmulhuw Vdq Bdq Wdq) #f) #f)
#(Prefix (pmulhw Pq Qq) #f #(VEX (pmulhw Vdq Wdq) (vpmulhw Vdq Bdq Wdq) #f) #f)
#(Prefix #f
#(VEX (cvtdq2pd Vpd Wq) (vcvtdq2pd Vpd Wq/128))
#(VEX (cvttpd2dq Vq Wpd) (vcvttpd2dq Vq/128 Wpd))
#(VEX (cvtpd2dq Vq Wpd) (vcvtpd2dq Vq/128 Wpd)))
#(Prefix (movntq Mq Pq) #f
#(VEX (movntdq Mdq Vdq) (vmovntdq Mdq Vdq) #f) #f)
;; 0F E8
#(Prefix (psubsb Pq Qq) #f #(VEX (psubsb Vdq Wdq) (vpsubsb Vdq Bdq Wdq) #f) #f)
#(Prefix (psubsw Pq Qq) #f #(VEX (psubsw Vdq Wdq) (vpsubsw Vdq Bdq Wdq) #f) #f)
#(Prefix (pminsw Pq Qq) #f #(VEX (pminsw Vdq Wdq) (vpminsw Vdq Bdq Wdq) #f) #f)
#(Prefix (por Pq Qq) #f #(VEX (por Vdq Wdq) (vpor Vdq Bdq Wdq) #f) #f)
#(Prefix (paddsb Pq Qq) #f #(VEX (paddsb Vdq Wdq) (vpaddsb Vdq Bdq Wdq) #f) #f)
#(Prefix (paddsw Pq Qq) #f #(VEX (paddsw Vdq Wdq) (vpaddsw Vdq Bdq Wdq) #f) #f)
#(Prefix (pmaxsw Pq Qq) #f #(VEX (pmaxsw Vdq Wdq) (vpmaxsw Vdq Bdq Wdq) #f) #f)
#(Prefix (pxor Pq Qq) #f #(VEX (pxor Vdq Wdq) (vpxor Vdq Bdq Wdq) #f) #f)
;; 0F F0
#(Prefix #f #f #f #(VEX (lddqu Vpd Mdq) (vlddqu Vpd Mdq)))
#(Prefix (psllw Pq Qq) #f #(VEX (psllw Vdq Wdq) (vpsllw Vdq Bdq Wdq) #f) #f)
#(Prefix (pslld Pq Qq) #f #(VEX (pslld Vdq Wdq) (vpslld Vdq Bdq Wdq) #f) #f)
#(Prefix (psllq Pq Qq) #f #(VEX (psllq Vdq Wdq) (vpsllq Vdq Bdq Wdq) #f) #f)
#(Prefix (pmuludq Pq Qq) #f #(VEX (pmuludq Vdq Wdq) (vpmuludq Vdq Bdq Wdq) #f) #f)
#(Prefix (pmaddwd Pq Qq) #f #(VEX (pmaddwd Vdq Wdq) (vpmaddwd Vdq Bdq Wdq) #f) #f)
#(Prefix (psadbw Pq Qq) #f #(VEX (psadbw Vdq Wdq) (vpsadbw Vdq Bdq Wdq) #f) #f)
#(Prefix (maskmovq Pq Nq) #f
#(VEX (maskmovdqu Vdq Udq)
(vmaskmovdqu Vdq Udq)
#f)
#f)
;; 0F F8
#(Prefix (psubb Pq Qq) #f #(VEX (psubb Vdq Wdq) (vpsubb Vdq Bdq Wdq) #f) #f)
#(Prefix (psubw Pq Qq) #f #(VEX (psubw Vdq Wdq) (vpsubw Vdq Bdq Wdq) #f) #f)
#(Prefix (psubd Pq Qq) #f #(VEX (psubd Vdq Wdq) (vpsubd Vdq Bdq Wdq) #f) #f)
#(Prefix (psubq Pq Qq) #f #(VEX (psubq Vdq Wdq) (vpsubq Vdq Bdq Wdq) #f) #f)
#(Prefix (paddb Pq Qq) #f #(VEX (paddb Vdq Wdq) (vpaddb Vdq Bdq Wdq) #f) #f)
#(Prefix (paddw Pq Qq) #f #(VEX (paddw Vdq Wdq) (vpaddw Vdq Bdq Wdq) #f) #f)
#(Prefix (paddd Pq Qq) #f #(VEX (paddd Vdq Wdq) (vpaddd Vdq Bdq Wdq) #f) #f)
#f)
;; end of two-byte opcode table
;; 10
(adc Eb Gb)
(adc Ev Gv)
(adc Gb Eb)
(adc Gv Ev)
(adc *AL Ib)
(adc *rAX Iz)
#(Mode (push *SS) #f)
#(Mode (pop *SS) #f)
;; 18
(sbb Eb Gb)
(sbb Ev Gv)
(sbb Gb Eb)
(sbb Gv Ev)
(sbb *AL Ib)
(sbb *rAX Iz)
#(Mode (push *DS) #f)
#(Mode (pop *DS) #f)
;; 20
(and Eb Gb)
(and Ev Gv)
(and Gb Eb)
(and Gv Ev)
(and *AL Ib)
(and *rAX Iz)
(*prefix* es)
#(Mode (daa) #f)
;; 28
(sub Eb Gb)
(sub Ev Gv)
(sub Gb Eb)
(sub Gv Ev)
(sub *AL Ib)
(sub *rAX Iz)
(*prefix* cs)
#(Mode (das) #f)
;; 30
(xor Eb Gb)
(xor Ev Gv)
(xor Gb Eb)
(xor Gv Ev)
(xor *AL Ib)
(xor *rAX Iz)
(*prefix* ss)
#(Mode (aaa) #f)
;; 38
(cmp Eb Gb)
(cmp Ev Gv)
(cmp Gb Eb)
(cmp Gv Ev)
(cmp *AL Ib)
(cmp *rAX Iz)
(*prefix* ds)
#(Mode (aas) #f)
;; 40
#(Mode (inc *eAX) (*prefix* rex))
#(Mode (inc *eCX) (*prefix* rex rex.b))
#(Mode (inc *eDX) (*prefix* rex rex.x))
#(Mode (inc *eBX) (*prefix* rex rex.x rex.b))
#(Mode (inc *eSP) (*prefix* rex rex.r))
#(Mode (inc *eBP) (*prefix* rex rex.r rex.b))
#(Mode (inc *eSI) (*prefix* rex rex.r rex.x))
#(Mode (inc *eDI) (*prefix* rex rex.r rex.x rex.b))
;; 48
#(Mode (dec *eAX) (*prefix* rex rex.w))
#(Mode (dec *eCX) (*prefix* rex rex.w rex.b))
#(Mode (dec *eDX) (*prefix* rex rex.w rex.x))
#(Mode (dec *eBX) (*prefix* rex rex.w rex.x rex.b))
#(Mode (dec *eSP) (*prefix* rex rex.w rex.r))
#(Mode (dec *eBP) (*prefix* rex rex.w rex.r rex.b))
#(Mode (dec *eSI) (*prefix* rex rex.w rex.r rex.x))
#(Mode (dec *eDI) (*prefix* rex rex.w rex.r rex.x rex.b))
;; 50
#(d64 (push *rAX/r8))
#(d64 (push *rCX/r9))
#(d64 (push *rDX/r10))
#(d64 (push *rBX/r11))
#(d64 (push *rSP/r12))
#(d64 (push *rBP/r13))
#(d64 (push *rSI/r14))
#(d64 (push *rDI/r15))
;; 58
#(d64 (pop *rAX/r8))
#(d64 (pop *rCX/r9))
#(d64 (pop *rDX/r10))
#(d64 (pop *rBX/r11))
#(d64 (pop *rSP/r12))
#(d64 (pop *rBP/r13))
#(d64 (pop *rSI/r14))
#(d64 (pop *rDI/r15))
;; 60
#(Mode #(Datasize (pushaw)
(pushad)
#f)
#f)
#(Mode #(Datasize (popaw)
(popad)
#f)
#f)
#(Mode (bound Gv Ma)
#f)
#(Mode (arpl Ew Gw)
(movsxd Gv Ed))
(*prefix* fs)
(*prefix* gs)
(*prefix* operand)
(*prefix* address)
;; 68
#(d64 (push Iz))
(imul Gv Ev Iz)
#(d64 (push IbS))
(imul Gv Ev IbS)
(ins Yb *DX)
(ins Yz *DX)
(outs *DX Xb)
(outs *DX Xz)
;; 70
#(f64 (jo Jb))
#(f64 (jno Jb))
#(f64 (jb Jb))
#(f64 (jnb Jb))
#(f64 (jz Jb))
#(f64 (jnz Jb))
#(f64 (jbe Jb))
#(f64 (jnbe Jb))
;; 78
#(f64 (js Jb))
#(f64 (jns Jb))
#(f64 (jp Jb))
#(f64 (jnp Jb))
#(f64 (jl Jb))
#(f64 (jnl Jb))
#(f64 (jle Jb))
#(f64 (jnle Jb))
;; 80
#(Group "Group 1"
#((add Eb Ib) (or Eb Ib) (adc Eb Ib) (sbb Eb Ib)
(and Eb Ib) (sub Eb Ib) (xor Eb Ib) (cmp Eb Ib)))
#(Group "Group 1"
#((add Ev Iz) (or Ev Iz) (adc Ev Iz) (sbb Ev Iz)
(and Ev Iz) (sub Ev Iz) (xor Ev Iz) (cmp Ev Iz)))
#(Mode #(Group "Redundant Group 1"
#((add Eb Ib) (or Eb Ib) (adc Eb Ib) (sbb Eb Ib)
(and Eb Ib) (sub Eb Ib) (xor Eb Ib) (cmp Eb Ib)))
#f)
#(Group "Group 1"
#((add Ev IbS) (or Ev IbS) (adc Ev IbS) (sbb Ev IbS)
(and Ev IbS) (sub Ev IbS) (xor Ev IbS) (cmp Ev IbS)))
(test Eb Gb)
(test Ev Gv)
(xchg Eb Gb)
(xchg Ev Gv)
;; 88
(mov Eb Gb)
(mov Ev Gv)
(mov Gb Eb)
(mov Gv Ev)
(mov Ew Sw)
(lea Gv M)
(mov Sw Ew)
#(Group "Group 1A" ;Three byte XOP prefix
#(#(d64 (pop Ev))
#f #f #f #f #f #f #f))
;; 90
(*nop*)
(xchg *rCX/r9 *rAX)
(xchg *rDX/r10 *rAX)
(xchg *rBX/r11 *rAX)
(xchg *rSP/r12 *rAX)
(xchg *rBP/r13 *rAX)
(xchg *rSI/r14 *rAX)
(xchg *rDI/r15 *rAX)
;; 98
#(Datasize (cbw) (cwde) (cdqe))
#(Datasize (cwd) (cdq) (cqo))
#(Mode (callf Ap) #f)
(fwait)
#(Mode #(Datasize (pushfw)
(pushfd)
#f)
#(Datasize (pushfw)
(pushfq)
(pushfq)))
#(Mode #(Datasize (popfw)
(popfd)
#f)
#(Datasize (popfw)
(popfq)
(popfq)))
(sahf)
(lahf)
;; A0
(mov *AL Ob)
(mov *rAX Ov)
(mov Ob *AL)
(mov Ov *rAX)
(movs Yb Xb)
(movs Yv Xv)
(cmps Xb Yb)
(cmps Xv Yv)
;; A8
(test *AL Ib)
(test *rAX Iz)
(stos Yb *AL)
(stos Yv *rAX)
(lods *AL Xb)
(lods *rAX Xv)
(scas *AL Yb)
(scas *rAX Yv)
;; B0
(mov *AL/R8L Ib)
(mov *CL/R9L Ib)
(mov *DL/R10L Ib)
(mov *BL/R11L Ib)
(mov *AH/R12L Ib)
(mov *CH/R13L Ib)
(mov *DH/R14L Ib)
(mov *BH/R15L Ib)
;; B8
(mov *rAX/r8 Iv)
(mov *rCX/r9 Iv)
(mov *rDX/r10 Iv)
(mov *rBX/r11 Iv)
(mov *rSP/r12 Iv)
(mov *rBP/r13 Iv)
(mov *rSI/r14 Iv)
(mov *rDI/r15 Iv)
;; C0
#(Group "Shift Group 2"
#((rol Eb Ib) (ror Eb Ib) (rcl Eb Ib)
(rcr Eb Ib) (shl Eb Ib) (shr Eb Ib) #f (sar Eb Ib)))
#(Group "Shift Group 2"
#((rol Ev Ib) (ror Ev Ib) (rcl Ev Ib)
(rcr Ev Ib) (shl Ev Ib) (shr Ev Ib) #f (sar Ev Ib)))
#(f64 (ret Iw))
#(f64 (ret))
#(Mode (les Gz Mp) #f) ;Three byte VEX prefix
#(Mode (lds Gz Mp) #f) ;Two byte VEX prefix
#(Group "Group 11"
#((mov Eb Ib) #f #f #f #f #f #f #f))
#(Group "Group 11"
#((mov Ev Iz) #f #f #f #f #f #f #f))
;; C8
(enter Iw Ib)
#(d64 (leave))
(retf Iw)
(retf)
(int3)
(int Ib)
#(Mode (into) #f)
#(Datasize (iretw)
(iretd)
(iretq))
;; D0
#(Group "Shift Group 2"
#((rol Eb *unity) (ror Eb *unity) (rcl Eb *unity) (rcr Eb *unity)
(shl Eb *unity) (shr Eb *unity) #f (sar Eb *unity)))
#(Group "Shift Group 2"
#((rol Ev *unity) (ror Ev *unity) (rcl Ev *unity) (rcr Ev *unity)
(shl Ev *unity) (shr Ev *unity) #f (sar Ev *unity)))
#(Group "Shift Group 2"
#((rol Eb *CL) (ror Eb *CL) (rcl Eb *CL)
(rcr Eb *CL) (shl Eb *CL) (shr Eb *CL) #f (sar Eb *CL)))
#(Group "Shift Group 2"
#((rol Ev *CL) (ror Ev *CL) (rcl Ev *CL)
(rcr Ev *CL) (shl Ev *CL) (shr Ev *CL) #f (sar Ev *CL)))
#(Mode (aam Ib) #f)
#(Mode (aad Ib) #f)
#(Mode (salc) #f)
(xlatb)
;; D8: x87 escape
#(Group "x87 D8"
#((fadd Md)
(fmul Md)
(fcom Md)
(fcomp Md)
(fsub Md)
(fsubr Md)
(fdiv Md)
(fdivr Md))
#((fadd *st0 *st)
(fmul *st0 *st)
(fcom *st0 *st)
(fcomp *st0 *st)
(fsub *st0 *st)
(fsubr *st0 *st)
(fdiv *st0 *st)
(fdivr *st0 *st)))
#(Group "x87 D9"
#((fld Md)
#f
(fst Md)
(fstp Md)
(fldenv M)
(fldcw Mw)
(fnstenv M)
(fnstcw Mw))
#((fld *st0 *st)
(fxch *st0 *st)
#((fnop) #f #f #f #f #f #f #f)
#f
#((fchs) (fabs) #f #f (ftst) (fxam) #f #f)
#((fld1) (fldl2t) (fldl2e) (fldpi) (fldlg2) (fldln2) (fldz) #f)
#((f2xm1) (fyl2x) (fptan) (fpatan) (fxtract) (fprem1) (fdecstp) (fincstp))
#((fprem) (fyl2xp1) (fsqrt) (fsincos) (frndint) (fscale) (fsin) (fcos))))
#(Group "x87 DA"
#((fiadd Md)
(fimul Md)
(ficom Md)
(ficomp Md)
(fisub Md)
(fisubr Md)
(fidiv Md)
(fidivr Md))
#((fcmovb *st0 *st)
(fcmove *st0 *st)
(fcmovbe *st0 *st)
(fcmovu *st0 *st)
#f
#(#f (fucompp) #f #f #f #f #f #f)
#f
#f))
#(Group "x87 DB"
#((fild Md)
(fisttp Md)
(fist Md)
(fistp Md)
#f
(fld Mem80)
#f
(fstp Mem80))
#((fcmovnb *st0 *st)
(fcmovne *st0 *st)
(fcmovnbe *st0 *st)
(fcmovnu *st0 *st)
#(#f #f (fnclex) (fninit) #f #f #f #f)
(fucomi *st0 *st)
(fcomi *st0 *st)
#f))
#(Group "x87 DC"
#((fadd Mq)
(fmul Mq)
(fcom Mq)
(fcomp Mq)
(fsub Mq)
(fsubr Mq)
(fdiv Mq)
(fdivr Mq))
#((fadd *st *st0)
(fmul *st *st0)
#f
#f
(fsub *st *st0)
(fsubr *st *st0)
(fdivr *st *st0)
(fdiv *st *st0)))
#(Group "x87 DD"
#((fld Mq)
(fisttp Mq)
(fst Mq)
(fstp Mq)
(frstor M)
#f
(fnsave M)
(fnstsw Mw))
#((ffree *st)
#f
(fst *st)
(fstp *st)
(fucom *st *st0)
(fucomp *st)
#f
#f))
#(Group "x87 DE"
#((fiadd Mw)
(fimul Mw)
(ficom Mw)
(ficomp Mw)
(fisub Mw)
(fisubr Mw)
(fidiv Mw)
(fdivr Mw))
#((faddp *st *st0)
(fmulp *st *st0)
#f
#(#f (fcompp) #f #f #f #f #f #f)
(fsubrp *st *st0)
(fsubp *st *st0)
(fdivrp *st *st0)
(fdivp *st *st0)))
#(Group "x87 DF"
#((fild Mw)
(fisttp Mw)
(fist Mw)
(fistp Mw)
(fbld Mem80)
(fild Mq)
(fbstp Mem80)
(fistp Mq))
#(#f
#f
#f
#f
#((fnstsw *AX) #f #f #f #f #f #f #f)
(fucomip *st0 *st)
(fcomip *st0 *st)
#f))
;; E0
#(f64 (loopnz Jb))
#(f64 (loopz Jb))
#(f64 (loop Jb))
#(Mode #(Addrsize (jcxz Jb)
(jecxz Jb)
#f)
#(Addrsize #f
#(f64 (jecxz Jb))
#(f64 (jrcxz Jb))))
(in *AL Ib)
(in *eAX Ib)
(out Ib *AL)
(out Ib *eAX)
;; E8
#(f64 (call Jz))
#(f64 (jmp Jz))
#(Mode (jmpf Ap) #f)
#(f64 (jmp Jb))
(in *AL *DX)
(in *eAX *DX)
(out *DX *AL)
(out *DX *eAX)
;; F0
(*prefix* lock)
(icebp)
(*prefix* repnz)
(*prefix* repz)
(hlt)
(cmc)
#(Group "Unary Group 3"
#((test Eb Ib) (test/amd Eb Ib) (not Eb) (neg Eb)
(mul Eb) (imul Eb) (div Eb) (idiv Eb)))
#(Group "Unary Group 3"
#((test Ev Iz) (test/amd Ev Iz) (not Ev) (neg Ev)
(mul Ev) (imul Ev) (div Ev) (idiv Ev)))
;; F8
(clc) (stc)
(cli) (sti)
(cld) (std)
#(Group "Group 4"
#((inc Eb) (dec Eb) #f #f #f #f #f #f))
#(Group "Group 5"
#((inc Ev)
(dec Ev)
#(f64 (call Ev))
(callf Mp)
#(f64 (jmp Ev))
(jmpf Mp)
#(d64 (push Ev))
#f))))
;; AMDs XOP opcode maps are not part of the other opcode map.
(define XOP-opcode-map-8
'#(#f #f #f #f #f #f #f #f
;; 08
#f #f #f #f #f #f #f #f
;; 10
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 20
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 30
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 40
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 50
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 60
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 70
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 80
#f #f #f #f #f
#(VEX #f (vpmacssww Vo Ho Wo Lo))
#(VEX #f (vpmacsswd Vo Ho Wo Lo))
#(VEX #f (vpmacssdql Vo Ho Wo Lo))
#f #f #f #f #f #f
#(VEX #f (vpmacssdd Vo Ho Wo Lo))
#(VEX #f (vpmacssdqh Vo Ho Wo Lo))
;; 90
#f #f #f #f #f
#(VEX #f (vpmacsww Vo Ho Wo Lo))
#(VEX #f (vpmacswd Vo Ho Wo Lo))
#(VEX #f (vpmacsdql Vo Ho Wo Lo))
#f #f #f #f #f #f
#(VEX #f (vpmacsdd Vo Ho Wo Lo))
#(VEX #f (vpmacsdqh Vo Ho Wo Lo))
;; A0
#f #f
#(VEX #f #(W (vpcmov Vx Hx Wx Lx) (vpcmov Vx Hx Lx Wx)))
#(VEX #f #(W (vpperm Vo Ho Wo Lo) (vpperm Vo Ho Lo Wo)))
#f #f
#(VEX #f (vpmadcsswd Vo Ho Wo Lo))
#f
#f #f #f #f #f #f #f #f
;; B0
#f #f #f #f #f #f
#(VEX #f (vpmadcswd Vo Ho Wo Lo))
#f
#f #f #f #f #f #f #f #f
;; C0
#(VEX #f (vprotb Vo Wo Ib))
#(VEX #f (vprotw Vo Wo Ib))
#(VEX #f (vprotd Vo Wo Ib))
#(VEX #f (vprotq Vo Wo Ib))
#f #f #f #f #f #f #f #f
#f #f #f #f ;TODO
;; D0
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; E0
#f #f #f #f #f #f #f #f #f #f #f #f
#f #f #f #f ;TODO
;; F0
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f))
(define XOP-opcode-map-9
'#(#f
#(VEX #f
#(Group "XOP group #1"
#(#f (blcfill By Ed/q) (blsfill By Ed/q) (blcs By Ed/q)
(tzmsk By Ed/q) (blcic By Ed/q) (blsic By Ed/q)
(t1mskc By Ed/q))))
#(VEX #f
#(Group "XOP group #2"
#(#f (blcmsk By Ed/q) #f #f
#f #f (blci By Ed/q) #f)))
#f #f #f #f #f
;; 08
#f #f #f #f #f #f #f #f
;; 10
#f #f
#(VEX #f
#(Group "XOP group #3"
#((llwpcb Rd/q) (slwpcb Rd/q) #f #f #f #f #f #f)))
#f #f #f #f #f
;; 18
#f #f #f #f #f #f #f #f
;; 20
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 30
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 40
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 50
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 60
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 70
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 80
#(VEX #f (vfrczps Vx Wx))
#(VEX #f (vfrczpd Vx Wx))
#(VEX #f (vfrczss Vq Wss))
#(VEX #f (vfrczsd Vq Wsd))
#f #f #f #f
#f #f #f #f ;AMD's opcode map places VPSHA* here
#f #f #f #f
;; 90
#(VEX #f #(W (vprotb Vo Wo Ho) (vprotb Vo Ho Wo)))
#(VEX #f #(W (vprotw Vo Wo Ho) (vprotw Vo Ho Wo)))
#(VEX #f #(W (vprotd Vo Wo Ho) (vprotd Vo Ho Wo)))
#(VEX #f #(W (vprotq Vo Wo Ho) (vprotq Vo Ho Wo)))
#(VEX #f #(W (vpshlb Vo Wo Ho) (vpshlb Vo Ho Wo)))
#(VEX #f #(W (vpshlw Vo Wo Ho) (vpshlw Vo Ho Wo)))
#(VEX #f #(W (vpshld Vo Wo Ho) (vpshld Vo Ho Wo)))
#(VEX #f #(W (vpshlq Vo Wo Ho) (vpshlq Vo Ho Wo)))
#(VEX #f #(W (vpshab Vo Wo Ho) (vpshab Vo Ho Wo)))
#(VEX #f #(W (vpshaw Vo Wo Ho) (vpshaw Vo Ho Wo)))
#(VEX #f #(W (vpshad Vo Wo Ho) (vpshad Vo Ho Wo)))
#(VEX #f #(W (vpshaq Vo Wo Ho) (vpshaq Vo Ho Wo)))
#f #f #f #f
;; A0
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; B0
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; C0
#f
#(VEX #f (vphaddbw Vo Wo))
#(VEX #f (vphaddbd Vo Wo))
#(VEX #f (vphaddbq Vo Wo))
#f #f
#(VEX #f (vphaddwd Vo Wo))
#(VEX #f (vphaddwq Vo Wo))
#f #f #f
#(VEX #f (vphadddq Vo Wo))
#f #f #f #f
;; D0
#f
#(VEX #f (vphaddubw Vo Wo)) ;"VPHADDUBWD"?
#(VEX #f (vphaddubd Vo Wo))
#(VEX #f (vphaddubq Vo Wo))
#f #f
#(VEX #f (vphadduwd Vo Wo))
#(VEX #f (vphadduwq Vo Wo))
#f #f #f
#(VEX #f (vphaddudq Vo Wo))
#f #f #f #f
;; E0
#f
#(VEX #f (vphsubbw Vo Wo))
#(VEX #f (vphsubwd Vo Wo))
#(VEX #f (vphsubdq Vo Wo))
#f #f #f #f #f #f #f #f #f #f #f #f
;; F0
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f))
(define XOP-opcode-map-A
'#(#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 10
#(Prefix (bextr Gd/q Ed/q Id) #f #f #f #f)
#f
#(VEX #f
#(Group "XOP group #4"
#((lwpins By Ed Id) (lwpval By Ed Id) #f #f #f #f #f #f)))
#f #f #f #f #f #f #f #f #f #f #f #f #f
;; 20
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 30
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 40
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 50
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 60
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 70
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 80
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; 90
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; A0
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; B0
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; C0
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; D0
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; E0
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f
;; F0
#f #f #f #f #f #f #f #f #f #f #f #f #f #f #f #f)))
| false |
4aabb0085134b07d6a829c6317a667a4b20e4881 | 710bd922d612840b3dc64bd7c64d4eefe62d50f0 | /scheme/scheme-runtime/number.scm | e9170312546cff30a0faf36703b15a9d0d06772d | [
"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 | 4,849 | scm | number.scm | ;;; number.scm -- numerical routine
(define (number? obj) (or (%fixnum? obj) (%real? obj)))
(define (complex? o) #f)
(define (real? o) (%real? o))
(define (rational? o) #f)
(define (integer? o) (%fixnum? o))
(define (exact? o) (integer? o))
(define (inexact? o) (real? o))
; (define (= z1 z2 ...))
; (define (< x1 x2 ...))
; (define (> x1 x2 ...))
; (define (<= x1 x2 ...))
; (define (>= x1 x2 ...))
(define (zero? z) (= z 0))
(define (positive? x) (>= x 0))
(define (negative? x) (< x 0))
(define (odd? n) (= (remainder n 2) 1))
(define (even? n) (= (remainder n 2) 0))
;;; MIN & MAX allows more than one argument
(define (max x1 x2) (if (< x1 x2) x2 x1))
(define (min x1 x2) (if (< x1 x2) x1 x2))
; (define (+ z1 ...))
; (define (* z1 ...))
; (define (- z1 z2))
; (define (/ z1 z2 ...))
(define (abs x) (if (negative? x) (- 0 x) x))
; (define (quotient n1 n2))
; (define (remainder n1 n2))
; (define (modulo n1 n2))
(define (gcd/2 a b)
(if (zero? b)
(if (and (inexact? b) (exact? a))
(exact->inexact (abs a))
(abs a))
(gcd/2 b (remainder a b))))
(define (gcd . n)
(if (null? n)
0
(let repeat ((a (car n))
(b (cdr n)))
(if (null? b)
a
(repeat (gcd/2 a (car b)) (cdr b))))))
(define (lcm/2 a b) (/ (abs (* a b)) (gcd/2 a b)))
(define (lcm . n)
(if (null? n)
1
(let repeat ((a (car n)) (b (cdr n)))
(if (null? b)
a
(repeat (lcm/2 a (car b)) (cdr b))))))
(define (numerator q) (%numerator q))
(define (denominator q) (%denominator q))
(define (floor x)
(cond ((%real? x) (%floor x))
((%fixnum? x) x)
(else (error "FLOOR expects a number, got ~a" x))))
(define (ceiling x)
(cond ((%real? x) (%ceiling x))
((%fixnum? x) x)
(else (error "CEILING expects a number, got ~a" x))))
(define (truncate x)
(cond ((%real? x) (%truncate x))
((%fixnum? x) x)
(else (error "TRUNCATE expects a number, got ~a" x))))
(define (round x)
(cond ((%real? x) (%round x))
((%fixnum? x) (%round x))
(else (error "ROUND expects a number, got ~a" x))))
(define (rationalize x y) (error "Unimplemented RATIONALIZE"))
(define (exp z)
(cond ((%real? z) (%exp z))
((%fixnum? z) (%exp (%fixnum->real z)))
(else (error "EXP expects a number, got ~a" z))))
(define (log z)
(cond ((%real? z) (%log z))
((%fixnum? z) (%log (%fixnum->real z)))
(else (error "LOG expects a number, got ~a" z))))
(define (sin z)
(cond ((%real? z) (%sin z))
((%fixnum? z) (%sin (%fixnum->real z)))
(else (error "SIN expects a number, got ~a" z))))
(define (cos z)
(cond ((%real? z) (%cos z))
((%fixnum? z) (%cos (%fixnum->real z)))
(else (error "COS expects a number, got ~a" z))))
(define (tan z)
(cond ((%real? z) (%tan z))
((%fixnum? z) (%tan (%fixnum->real z)))
(else (error "TAN expects a number, got ~a" z))))
(define (asin z)
(cond ((%real? z) (%asin z))
((%fixnum? z) (%asin (%fixnum->real z)))
(else (error "ASIN expects a number, got ~a" z))))
(define (acos z)
(cond ((%real? z) (%acos z))
((%fixnum? z) (%acos (%fixnum->real z)))
(else (error "ACOS expects a number, got ~a" z))))
;(define (atan z) (%atan z))
;(define (atan y x))
(define (sqrt z)
(cond ((%real? z) (%sqrt z))
((%fixnum? z) (%sqrt (%fixnum->real z)))
(else (error "SQRT expects a number, got ~a" z))))
(define (expt z1 z2)
(cond ((%real? z1)
(cond ((%real? z2) (%expt z1 z2))
((%fixnum? z2) (%expt z1 (%fixnum->real z2)))
(else (error "EXPT expects a number as 2nd arg, got ~a" z2))))
((%fixnum? z1)
(cond ((%real? z2) (%expt (%fixnum->real z1) z2))
((%fixnum? z2) (%expt (%fixnum->real z1) (%fixnum->real z2)))
(else (error "EXPT expects a number as 2nd arg, got ~a" z2))))
(else (error "EXPT expects two numbers as arguments, got ~a and ~a"
z1 z2))))
(define (make-rectangular x1 x2) (error "Unimplemented MAKE-RECTANGULAR"))
(define (make-polar x1 x2) (error "Unimplemented MAKE-POLAR"))
(define (real-part z) (error "Unimplemented REAL-PART"))
(define (imag-part z) (error "Unimplemented IMAG-PART"))
(define (magnitude z) (error "Unimplemented MAGNITUDE"))
(define (angle z) (error "Unimplemented ANGLE"))
(define (exact->inexact z)
(cond ((%fixnum? z) (%fixnum->real z))
((%real? z) z)
(else (error "EXACT->INEXACT expects a number, got ~a" z))))
; (cond ((%fixnum? z) (%fixnum->real z))
; ((%rational? z) (/ (%fixnum->real (numerator z))
; (%fixnum->real (denominator z))))
; (else z)))
(define (inexact->exact z)
(if (%real? z) (%floor z) z))
| false |
cb38d10cdb9d5ef39809de4deeb274ed5eb3b41d | 3629e5c33ebbc3acbaa660fb324c26357098147c | /examples/glbook/example6-3.scm | 33815b7b8a87cac80810dbe287441159e2e84529 | [
"MIT",
"LicenseRef-scancode-x11-sg"
]
| permissive | shirok/Gauche-gl | f31a62ce4c2d91795f972b668861a77626b02cb5 | a569e3009314f81bc513827064e05869220c6a9d | refs/heads/master | 2023-06-07T15:56:17.514969 | 2023-06-01T06:56:48 | 2023-06-01T06:56:48 | 9,487,174 | 4 | 5 | MIT | 2018-09-24T21:39:18 | 2013-04-17T02:13:32 | C | UTF-8 | Scheme | false | false | 1,853 | scm | example6-3.scm | ;; Example 6-3 Antialised Lines
(use gl)
(use gl.glut)
(define *rot-angle* 0)
(define (init)
(let ((g (gl-get-float GL_LINE_WIDTH_GRANULARITY)))
(format #t "GL_LINE_WIDTH_GRANULARITY value is ~s\n" g))
(let ((r (gl-get-float GL_LINE_WIDTH_RANGE)))
(format #t "GL_LINE_WIDTH_RANGE values are ~s ~s\n" (ref r 0) (ref r 1)))
(gl-enable GL_LINE_SMOOTH)
(gl-enable GL_BLEND)
(gl-blend-func GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA)
(gl-hint GL_LINE_SMOOTH_HINT GL_DONT_CARE)
(gl-line-width 1.5)
(gl-clear-color 0.0 0.0 0.0 0.0)
)
(define (disp)
(gl-clear GL_COLOR_BUFFER_BIT)
(gl-color 0.0 1.0 0.0)
(gl-push-matrix)
(gl-rotate (- *rot-angle*) 0.0 0.0 0.1)
(gl-begin GL_LINES)
(gl-vertex -0.5 0.5)
(gl-vertex 0.5 -0.5)
(gl-end)
(gl-pop-matrix)
(gl-color 0.0 0.0 1.0)
(gl-push-matrix)
(gl-rotate *rot-angle* 0.0 0.0 0.1)
(gl-begin GL_LINES)
(gl-vertex 0.5 0.5)
(gl-vertex -0.5 -0.5)
(gl-end)
(gl-pop-matrix)
(gl-flush)
)
(define (reshape w h)
(gl-viewport 0 0 w h)
(gl-matrix-mode GL_PROJECTION)
(gl-load-identity)
(if (<= w h)
(glu-ortho-2d -1.0 1.0 (* -1.0 (/ h w)) (* 1.0 (/ h w)))
(glu-ortho-2d (* -1.0 (/ w h)) (* 1.0 (/ w h)) -1.0 1.0))
(gl-matrix-mode GL_MODELVIEW)
(gl-load-identity)
)
(define (keyboard key x y)
(cond
((or (= key (char->integer #\r))
(= key (char->integer #\R)))
(inc! *rot-angle* 20.0)
(if (>= *rot-angle* 360.0) (set! *rot-angle* 0.0))
(glut-post-redisplay))
((= key 27) ;ESC
(exit 0)))
)
(define (main args)
(glut-init args)
(glut-init-display-mode (logior GLUT_SINGLE GLUT_RGB))
(glut-init-window-size 200 200)
(glut-create-window (car args))
(init)
(glut-reshape-func reshape)
(glut-keyboard-func keyboard)
(glut-display-func disp)
(glut-main-loop)
0)
| false |
a04dec109757d5b6bc1119fa5a43a2e94702de55 | 3323fb4391e76b853464a9b2fa478cd7429e9592 | /exercise-2.17.ss | f18255fe992b581b287d596211e5414ceb664552 | []
| no_license | simpleliangsl/hello-scheme | ceb203933fb056523f5288ce716569096a71ad97 | 31434fb810475ee0e8ec2e6816995a0041c47f44 | refs/heads/master | 2023-06-16T12:07:28.744188 | 2021-07-15T06:39:32 | 2021-07-15T06:39:32 | 386,197,304 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 178 | ss | exercise-2.17.ss | (define (last-pair items)
(if (null? (cdr items))
(car items)
(last-pair (cdr items))
)
)
; (last-pair (list 2 3)) => 3
; (last-pair (list 2 3 17)) => 17 | false |
cdc8e16ce5379ac4fdfc55ff89a025aef978e3ab | 0021f53aa702f11464522ed4dff16b0f1292576e | /scm/p42.scm | 991e975072944ec6038e92c499a645639b76ff93 | []
| no_license | mtsuyugu/euler | fe40dffbab1e45a4a2a297c34b729fb567b2dbf2 | 4b17df3916f1368eff44d6bc36202de4dea3baf7 | refs/heads/master | 2021-01-18T14:10:49.908612 | 2016-10-07T15:35:45 | 2016-10-07T15:35:45 | 3,059,459 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 646 | scm | p42.scm | (use gauche.sequence)
(use srfi-13)
(define (p42)
(define (alpha->integer c)
(- (char->integer c)
(char->integer #\A)
-1))
(define (word->num word)
(fold (lambda (x y) (+ y (alpha->integer x))) 0 (string->list word)))
(define (is-triangle-number? num)
(integer? (/ (- (sqrt (+ 1 (* 8 num))) 1) 2)))
(let* ((in (open-input-file "words.txt"))
(line (read-line in)))
(close-input-port in)
(fold (lambda (s y)
(let1 num (word->num s)
(+ y (if (is-triangle-number? num) 1 0))))
0 (remove string-null? (sort (string-split line #/"?,?"/))))))
(print (p42))
| false |
2d955f03a81f2ed6daf2cf6143e4f3ca2ff87bbc | 9c8c0fb8f206ea8b1871df102737c1cb51b7c516 | /src/zmq.scm | 8394758cb77d848a905b37a31d86ba530ec9afed | [
"MIT"
]
| permissive | massimo-nocentini/chicken-zmq | 3c4ca6cbed51e2fbcdcc0b5287b7d05194f039b5 | b62a1dc8c66c84134770a41802f927d36a7e0f81 | refs/heads/master | 2020-04-20T02:32:32.536355 | 2019-04-11T09:00:23 | 2019-04-11T09:00:23 | 168,574,171 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 4,879 | scm | zmq.scm |
(module zmq *
(import scheme (chicken format) (chicken base) (chicken foreign) )
(import-for-syntax (chicken format))
(foreign-declare "#include <zmq.h>")
(define zmq_ctx_new (foreign-lambda c-pointer "zmq_ctx_new"))
(define zmq_ctx_get (foreign-lambda int "zmq_ctx_get" c-pointer int))
(define zmq_errno (foreign-lambda int "zmq_errno"))
(define zmq_strerror (foreign-lambda (const c-string) "zmq_strerror" int))
(define zmq_socket (foreign-lambda c-pointer "zmq_socket" c-pointer int))
(define zmq_bind (foreign-lambda int "zmq_bind" c-pointer (const c-string)))
(define zmq_recv (foreign-lambda int "zmq_recv" c-pointer c-pointer size_t int))
(define zmq_send (foreign-lambda int "zmq_send" c-pointer (const c-pointer) size_t int))
(define zmq_close (foreign-lambda int "zmq_close" c-pointer))
(define zmq_ctx_destroy (foreign-lambda int "zmq_ctx_destroy" c-pointer))
(define zmq_connect (foreign-lambda int "zmq_connect" c-pointer (const c-string)))
(define zmq_version (foreign-lambda void "zmq_version" (c-pointer int) (c-pointer int) (c-pointer int)))
(define zmq_setsockopt (foreign-lambda int "zmq_setsockopt" c-pointer int (const c-pointer) size_t))
(define zmq_poll (foreign-lambda int "zmq_poll" (c-pointer (struct "zmq_pollitem_t")) int long))
(define zmq_msg_init (foreign-lambda int "zmq_msg_init" (c-pointer (struct "zmq_msg_t"))))
(define zmq_msg_more (foreign-lambda int "zmq_msg_more" (const (c-pointer (struct "zmq_msg_t")))))
(define zmq_msg_close (foreign-lambda int "zmq_msg_close" (c-pointer (struct "zmq_msg_t"))))
(define zmq_msg_send (foreign-lambda int "zmq_msg_send" (c-pointer (struct "zmq_msg_t")) c-pointer int))
(define zmq_msg_recv (foreign-lambda int "zmq_msg_recv" (c-pointer (struct "zmq_msg_t")) c-pointer int))
(define zmq_proxy (foreign-lambda int "zmq_proxy" c-pointer c-pointer c-pointer))
;(define zmq_poller_new (foreign-lambda c-pointer "zmq_poller_new"))
;(define zmq_poller_destroy (foreign-lambda int "zmq_poller_destroy" (c-pointer c-pointer)))
;(define zmq_poller_add (foreign-lambda int "zmq_poller_add" c-pointer c-pointer c-pointer short))
;(define zmq_poller_modify (foreign-lambda int "zmq_poller_modify" c-pointer c-pointer c-pointer short))
;(define zmq_poller_remove (foreign-lambda int "zmq_poller_remove" c-pointer c-pointer short))
;(define zmq_poller_wait (foreign-lambda int "zmq_poller_wait" c-pointer (c-pointer (struct "zmq_poller_event_t")) long))
;(define zmq_poller_wait_all (foreign-lambda int "zmq_poller_wait_all" c-pointer (c-pointer (struct "zmq_poller_event_t")) int long))
; Socket types.
(define-foreign-variable ZMQ_REP_inner int "ZMQ_REP")
(define-foreign-variable ZMQ_REQ_inner int "ZMQ_REQ")
(define-foreign-variable ZMQ_PUB_inner int "ZMQ_PUB")
(define-foreign-variable ZMQ_SUB_inner int "ZMQ_SUB")
(define-foreign-variable ZMQ_PUSH_inner int "ZMQ_PUSH")
(define-foreign-variable ZMQ_PULL_inner int "ZMQ_PULL")
(define-foreign-variable ZMQ_ROUTER_inner int "ZMQ_ROUTER")
(define-foreign-variable ZMQ_DEALER_inner int "ZMQ_DEALER")
(define-foreign-variable ZMQ_XPUB_inner int "ZMQ_XPUB")
(define-foreign-variable ZMQ_XSUB_inner int "ZMQ_XSUB")
(define ZMQ_REP ZMQ_REP_inner)
(define ZMQ_REQ ZMQ_REQ_inner)
(define ZMQ_PUB ZMQ_PUB_inner)
(define ZMQ_SUB ZMQ_SUB_inner)
(define ZMQ_PUSH ZMQ_PUSH_inner)
(define ZMQ_PULL ZMQ_PULL_inner)
(define ZMQ_ROUTER ZMQ_ROUTER_inner)
(define ZMQ_DEALER ZMQ_DEALER_inner)
(define ZMQ_XPUB ZMQ_XPUB_inner)
(define ZMQ_XSUB ZMQ_XSUB_inner)
(define-foreign-variable ZMQ_POLLIN_inner int "ZMQ_POLLIN")
(define ZMQ_POLLIN ZMQ_POLLIN_inner)
; Send/recv options.
(define-foreign-variable ZMQ_DONTWAIT_inner int "ZMQ_DONTWAIT")
(define-foreign-variable ZMQ_SNDMORE_inner int "ZMQ_SNDMORE")
(define ZMQ_DONTWAIT ZMQ_DONTWAIT_inner)
(define ZMQ_SNDMORE ZMQ_SNDMORE_inner)
; Socket options.
(define-foreign-variable ZMQ_SUBSCRIBE_inner int "ZMQ_SUBSCRIBE")
(define-foreign-variable ZMQ_XPUB_VERBOSE_inner int "ZMQ_XPUB_VERBOSE")
(define ZMQ_SUBSCRIBE ZMQ_SUBSCRIBE_inner)
(define ZMQ_XPUB_VERBOSE ZMQ_XPUB_VERBOSE_inner)
(define make-zmq_pollitem_t
(foreign-lambda* (c-pointer (struct "zmq_pollitem_t"))
((int nbr))
"zmq_pollitem_t items [nbr];
C_return(items);"))
(define set-zmq_pollitem_t!
(foreign-lambda* void
(((c-pointer (struct "zmq_pollitem_t")) items)
(int i)
(c-pointer socket)
(short events))
"zmq_pollitem_t item = { .socket = socket, .fd = 0, .events = events, .revents = 0};
items[i] = item;"))
(define zmq_pollitem_t-revents
(foreign-lambda* short
(((c-pointer (struct "zmq_pollitem_t")) items)
(int i))
"C_return(items[i].revents);"))
(define make-zmq_msg_t
(foreign-lambda* (c-pointer (struct "zmq_msg_t"))
()
"zmq_msg_t msg;
C_return(&msg);"))
)
| false |
235a950c830278456d19af9ba955d03a83fe66cc | f59b3ca0463fed14792de2445de7eaaf66138946 | /section-4/4_75.scm | 1e381c0cee2d2fb5a51a1fe0e9f8a5373fa4a4b3 | []
| no_license | uryu1994/sicp | f903db275f6f8c2da0a6c0d9a90c0c1cf8b1e718 | b14c728bc3351814ff99ace3b8312a651f788e6c | refs/heads/master | 2020-04-12T01:34:28.289074 | 2018-06-26T15:17:06 | 2018-06-26T15:17:06 | 58,478,460 | 0 | 1 | null | 2018-06-20T11:32:33 | 2016-05-10T16:53:00 | Scheme | UTF-8 | Scheme | false | false | 574 | scm | 4_75.scm | (load "./microshaft")
(define (unique-query exp) (car exp))
(define (uniquely-asserted operands frame-stream)
(stream-flatmap
(lambda (frame)
(let ((result (qeval (unique-query operands) (singleton-stream frame))))
(if (and (not (stream-null? result))
(stream-null? (stream-cdr result)))
result
the-empty-stream)))
frame-stream))
(put 'unique 'qeval uniquely-asserted)
(query-driver-loop)
(unique (job ?x (computer wizard)))
(unique (job ?x (computer programmer)))
(and (job ?x ?j) (unique (job ?anyone ?j)))
| false |
d749ddf721f32868ca45ba16539571cb37ab1235 | b43e36967e36167adcb4cc94f2f8adfb7281dbf1 | /scheme/swl1.3/tests/error-help/test4.ss | f48c735a199fb0afb61a801fe2445d4354615b2f | [
"SWL",
"TCL"
]
| permissive | 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 | 70 | ss | test4.ss | ; Test error "duplicate mark #~s= seen"
(#327=(a b c #327=d) #327#)
| false |
0762028ac93f85fd114ee9b0fb28eb58354d289e | 8ac3afd282844107d15635d7b959a302a371c0e0 | /c/5-3.ss | 12aac7c766869db83266dc2cbca1f9b3930a8590 | []
| no_license | noelwelsh/opencl | f0de13a1a2767661f960816b5723cdc6e56620d2 | 7c18657df9681ce9a2ff1d74ca5fbad4705b86ca | refs/heads/master | 2020-04-02T17:24:59.759065 | 2010-05-18T15:54:58 | 2010-05-18T15:54:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 3,629 | ss | 5-3.ss | #lang at-exp scheme/base
(require scheme/foreign
(except-in scheme/contract ->)
scribble/srcdoc
(file "include/cl.ss")
(file "lib.ss")
(file "syntax.ss")
(file "types.ss"))
(require/doc scheme/base
scribble/manual
(for-label (file "../../c/types.ss")))
;;;;
(define-opencl clCreateSampler
(_fun [context : _cl_context]
[normalized_coords : _cl_bool]
[addressing_mode : _cl_addressing_mode]
[filter_mode : _cl_filter_mode]
[errcode_ret : (_ptr o _cl_int)]
-> [sample : _cl_sampler/null]
->
(cond
[(= errcode_ret CL_SUCCESS)
sample]
[(= errcode_ret CL_INVALID_CONTEXT)
(error 'clCreateSampler "context is not a valid context")]
[(= errcode_ret CL_INVALID_VALUE)
(error 'clCreateSampler "addressing_mode, filter_mode or normalized_coords or combination of these argument values are not valid")]
[(= errcode_ret CL_INVALID_OPERATION)
(error 'clCreateSampler "images are not supported by any device associated with context")]
[(= errcode_ret CL_OUT_OF_HOST_MEMORY)
(error 'clCreateSampler "there is a failure to allocate resources required by the OpenCL implementation on the host")]
[else
(error 'clCreateSampler "Invalid error code: ~e" errcode_ret)])))
(provide/doc
[proc-doc
clCreateSampler
(([ctxt _cl_context/c]
[normalized? _cl_bool/c]
[addressing-mode _cl_addressing_mode/c]
[filter-mode _cl_filter_mode/c])
()
. ->d .
[sampler _cl_sampler/c])
@{}])
;;;;
(define-opencl clRetainSampler
(_fun [sampler : _cl_sampler]
-> [status : _cl_int]
-> (cond [(= status CL_SUCCESS) (void)]
[(= status CL_INVALID_SAMPLER)
(error 'clRetainSampler "sampler is not a valid sampler object")]
[else
(error 'clRetainSampler "Invalid error code: ~e" status)])))
(provide/doc
[proc-doc
clRetainSampler
(([sampler _cl_sampler/c])
()
. ->d .
[v void])
@{}])
;;;;
(define-opencl clReleaseSampler
(_fun [sampler : _cl_sampler]
-> [status : _cl_int]
-> (cond [(= status CL_SUCCESS) (void)]
[(= status CL_INVALID_SAMPLER)
(error 'clReleaseSampler "sampler is not a valid sampler object")]
[else
(error 'clReleaseSampler "Invalid error code: ~e" status)])))
(provide/doc
[proc-doc
clReleaseSampler
(([sampler _cl_sampler/c])
()
. ->d .
[v void])
@{}])
;;;;
(define-opencl-info clGetSamplerInfo
(clGetSamplerInfo:length clGetSamplerInfo:generic)
_cl_sampler_info _cl_sampler_info/c
(args [sampler : _cl_sampler _cl_sampler/c])
(error status
(cond [(= status CL_INVALID_VALUE)
(error 'clGetSamplerInfo "param_name is not valid or if size in bytes specified by param_value_size is < size of return type and param_value is not NULL")]
[(= status CL_INVALID_SAMPLER)
(error 'clGetSamplerInfo "sampler is not a valid sampler object")]
[else
(error 'clGetSamplerInfo "Invalid error code: ~e" status)]))
(variable param_value_size)
(fixed [_cl_uint _cl_uint/c CL_SAMPLER_REFERENCE_COUNT]
[_cl_context _cl_context/c CL_SAMPLER_CONTEXT]
[_cl_addressing_mode _cl_addressing_mode/c CL_SAMPLER_ADDRESSING_MODE]
[_cl_filter_mode _cl_filter_mode/c CL_SAMPLER_FILTER_MODE]
[_cl_bool _cl_bool/c CL_SAMPLER_NORMALIZED_COORDS])) | false |
799fa447240bbff3db666e7ed593aa196ba143f7 | 000dbfe5d1df2f18e29a76ea7e2a9556cff5e866 | /sitelib/text/markdown/parser/factories.scm | be49108d8bf3f6370164691c8667404ffc4f1509 | [
"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 | 16,478 | scm | factories.scm | ;;; -*- mode:scheme; coding:utf-8 -*-
;;;
;;; text/markdown/parser/factories.scm - Parser factories
;;;
;;; Copyright (c) 2022 Takashi Kato <[email protected]>
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; 2. Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
#!nounbound
(library (text markdown parser factories)
(export block-start?
block-start:of block-start:none
block-start:at-index
block-start:at-column
block-start:replace-active-block-parser
block-start-parsers
block-start-new-index
block-start-new-column
block-start-replace-active-block-parser?
try-start-heading
try-start-thematic-break
try-start-indented-code-block
try-start-fenced-code-block
try-start-html-block
try-start-block-quote-block
try-start-list-block)
(import (rnrs)
(core misc)
(srfi :13 strings)
(srfi :14 char-sets)
(srfi :115 regexp)
(srfi :197 pipeline)
(text markdown parser blocks)
(text markdown parser nodes)
(text markdown parser parsing)
(text markdown parser source)
(text markdown parser scanner))
(define-vector-type block-start
(make-block-start parsers new-index new-column replace-active-block-parser?)
block-start?
(parsers block-start-parsers)
(new-index block-start-new-index block-start-new-index-set!)
(new-column block-start-new-column block-start-new-column-set!)
(replace-active-block-parser? block-start-replace-active-block-parser?
block-start-replace-active-block-parser?-set!))
(define (block-start:none) #f)
(define (block-start:of . parsers)
(make-block-start parsers #f #f #f))
(define (block-start:at-index bs new-index)
(block-start-new-index-set! bs new-index)
bs)
(define (block-start:at-column bs new-column)
(block-start-new-column-set! bs new-column)
bs)
(define (block-start:replace-active-block-parser bs)
(block-start-replace-active-block-parser?-set! bs #t)
bs)
(define (try-start-heading parser-state matched-block-parser)
(if (>= (parser-state-indent parser-state) +parsing-code-block-indent+)
(block-start:none)
(let* ((line (parser-state-line parser-state))
(nns (parser-state-next-non-space-index parser-state)))
(cond ((and (eqv? (source-line:char-at line nns) #\#)
(atx-heading parser-state (source-line:substring line nns)))
=> (lambda (p)
(chain (block-start:of p)
(block-start:at-index _ (source-line:length line)))))
((setex-heading-level parser-state line nns) =>
(lambda (level)
(let ((lines (matched-block-parser:paragraph-lines
matched-block-parser)))
(if (source-lines:empty? lines)
(block-start:none)
(chain (block-start:of
(make-heading-parser
(parser-state-document parser-state)
level lines))
(block-start:at-index _ (source-line:length line))
(block-start:replace-active-block-parser _))))))
(else (block-start:none))))))
(define (atx-heading parser-state line)
(define scanner (scanner:of (source-lines:of line)))
(let ((level (scanner:match-char scanner #\#)))
(cond ((or (zero? level) (> level 6)) #f)
((not (scanner:has-next? scanner))
(make-heading-parser (parser-state-document parser-state)
level (source-lines:empty)))
((not (memv (scanner:peek scanner) '(#\space #\tab))) #f)
(else
(scanner:whitespace scanner) ;; skip
(let ((start (scanner:position scanner)))
(let loop ((end start) (hash-can-end? #t))
(if (scanner:has-next? scanner)
(let ((c (scanner:peek scanner)))
(case c
((#\#)
(cond (hash-can-end?
(scanner:match-char scanner #\#)
(let ((ws (scanner:whitespace scanner)))
(loop (if (scanner:has-next? scanner)
(scanner:position scanner)
end)
(positive? ws))))
(else
(scanner:next! scanner)
(loop (scanner:position scanner)
hash-can-end?))))
((#\space #\tab)
(scanner:next! scanner)
(loop end #t))
(else
(scanner:next! scanner)
(loop (scanner:position scanner) #f))))
(let* ((source (scanner:source scanner start end))
(content (source-lines:content source)))
(if (string-null? content)
(make-heading-parser
(parser-state-document parser-state)
level (source-lines:empty))
(make-heading-parser
(parser-state-document parser-state)
level source))))))))))
(define (setex-heading-level parser-state sl index)
(define (setex-heading-rest? sl index marker)
(let* ((content (source-line-content sl))
(last (string-length content))
(after-marker (or (string-skip content marker index) last))
(after-space (or (string-skip content parsing:space/tab?
after-marker)
last)))
(>= after-space last)))
(case (source-line:char-at sl index)
((#\=) (and (setex-heading-rest? sl (+ index 1) #\=) 1))
((#\-) (and (setex-heading-rest? sl (+ index 1) #\-) 2))
(else #f)))
(define (try-start-thematic-break parser-state matched-block-parser)
(define (thematic-break? line index)
(define scanner (scanner:of (source-lines:of line)))
(define (try-scan scanner pos char)
(scanner:position! scanner pos)
(let loop ((count 0))
(let ((c (scanner:next! scanner)))
(cond ((eqv? c char) (loop (+ count 1)))
((memv c '(#\space #\tab)) (loop count))
((not c) count)
(else -1)))))
;; skip until index
(let ((pos (scanner:position (scanner:skip! scanner index))))
(or (>= (try-scan scanner pos #\-) 3)
(>= (try-scan scanner pos #\_) 3)
(>= (try-scan scanner pos #\*) 3))))
(if (>= (parser-state-indent parser-state) +parsing-code-block-indent+)
(block-start:none)
(let ((next-non-space (parser-state-next-non-space-index parser-state))
(line (parser-state-line parser-state)))
(if (thematic-break? line next-non-space)
(chain (block-start:of (make-thematic-break-parser
(parser-state-document parser-state)))
(block-start:at-index _ (source-line:length line)))
(block-start:none)))))
(define (try-start-indented-code-block parser-state matched-block-parser)
(if (and (>= (parser-state-indent parser-state) +parsing-code-block-indent+)
(not (parser-state-blank? parser-state))
(not (paragraph-node?
(block-parser-block
(parser-state:active-block-parser parser-state)))))
(chain (block-start:of (make-indented-code-block-parser
(parser-state-document parser-state)))
(block-start:at-column _ (+ (parser-state-column parser-state)
+parsing-code-block-indent+)))
(block-start:none)))
(define (try-start-fenced-code-block parser-state matched-block-parser)
(define (check-opener line index indent)
(define scanner (scanner:of (source-lines:of line)))
(define (try-scan scanner pos c)
(scanner:position! scanner pos)
(let ((n (scanner:match-char scanner c)))
(and n (>= n 3) n)))
(define (make fc fl indent)
(cons (make-fenced-code-block-parser (parser-state-document parser-state)
fc fl indent)
fl))
(do ((i 0 (+ i 1)))
((= i index))
(scanner:next! scanner))
(let ((pos (scanner:position scanner)))
(cond ((try-scan scanner pos #\`) =>
(lambda (n)
;; If the infor string comes after a backtick fence,
;; it may not contain backtick characters
(and (not (scanner:find-char scanner #\`))
(make #\` n indent))))
((try-scan scanner pos #\~) => (lambda (n) (make #\~ n indent)))
(else #f))))
(let ((indent (parser-state-indent parser-state))
(nns (parser-state-next-non-space-index parser-state)))
(cond ((>= indent +parsing-code-block-indent+) (block-start:none))
((check-opener (parser-state-line parser-state) nns indent) =>
(lambda (bp&c)
(chain (block-start:of (car bp&c))
(block-start:at-index _ (+ nns (cdr bp&c))))))
(else (block-start:none)))))
(define html-block-patterns
`#(
(#f #f) ;; block type 0, not used
(,(rx "<" (w/nocase (or "script" "pre" "style" "textarea"))
(or space ">" eol))
,(rx "</" (w/nocase (or "script" "pre" "style" "textarea")) ">"))
(,(rx bol ,*parsing:html-comment-open-pattern*)
,*parsing:html-comment-close-pattern*) ;; comment
(,(rx bol ,*parsing:html-pi-open-pattern*)
,*parsing:html-pi-close-pattern*) ;; PI
(,(rx bol ,*parsing:html-declaration-open-pattern*)
,*parsing:html-declaration-close-pattern*) ;; <!ATTR ... > or so
(,(rx bol ,*parsing:html-cdata-open-pattern*)
,*parsing:html-cdata-close-pattern*) ;; <![CDATA[ ... ]]>
(,(rx "<" (? "/")
(w/nocase
(or
"address" "article" "aside"
"base" "basefont" "blockquote" "body"
"caption" "center" "col" "colgroup"
"dd" "details" "dialog" "dir" "div" "dl" "dt"
"fieldset" "figcaption" "figure" "footer" "from" "frame" "frameset"
"h1" "h2" "h3" "h4" "h5" "h6" "head" "header" "hr" "html"
"iframe"
"legend" "li" "link"
"main" "menu" "menuitem"
"nav" "noframes"
"ol" "optgroup" "option"
"p" "param"
"section" "source" "summary"
"table" "tbody" "td" "tfoot" "thead" "title" "tr" "track"
"ul"))
(or space (: (? "/") ">") eol))
#t)
(,(rx bol
(or ,*parsing:html-open-tag-pattern*
,*parsing:html-close-tag-pattern*)
(* space) eol)
#t))
)
(define (try-start-html-block parser-state matched-block-parser)
(define (check-lazy)
(define bp (matched-block-parser:get matched-block-parser))
(or (paragraph-node? (block-parser-block bp))
(block-parser-allow-lazy-continuation-line?
(parser-state:active-block-parser parser-state))))
(define (check-match i line)
(let ((o&c (vector-ref html-block-patterns i)))
(and (regexp-search (car o&c) line)
(cadr o&c))))
(let* ((nns (parser-state-next-non-space-index parser-state))
(indent (parser-state-indent parser-state))
(source (parser-state-line parser-state))
(line (source-line-content (source-line:substring source nns)))
(size (vector-length html-block-patterns)))
(if (and (< indent +parsing-code-block-indent+)
(eqv? (source-line:char-at source nns) #\<))
(let loop ((i 1))
(cond ((and (= i 7) (check-lazy)) (block-start:none))
((and (< i size) (check-match i line)) =>
(lambda (closer?)
(let ((doc (parser-state-document parser-state))
(index (parser-state-index parser-state))
(closer (and (regexp? closer?) closer?)))
(chain (block-start:of (make-html-block-parser doc closer))
(block-start:at-index _ index)))))
((< i size) (loop (+ i 1)))
(else (block-start:none))))
(block-start:none))))
(define (try-start-block-quote-block parser-state matched-block-parser)
(let ((nns (parser-state-next-non-space-index parser-state)))
(if (block-quote-parser:marker? parser-state nns)
(let ((col (+ (parser-state-column parser-state)
(parser-state-indent parser-state)
1))
(line (parser-state-line parser-state)))
(chain (block-start:of (make-block-quote-parser
(parser-state-document parser-state)))
(block-start:at-column _ (if (parsing:space/tab?
(source-line:char-at line
(+ nns 1)))
(+ col 1)
col))))
(block-start:none))))
(define (try-start-list-block ps matched-block-parser)
(define matched (matched-block-parser:get matched-block-parser))
(define (in-paragraph? matched-block-parser)
(not (source-lines:empty?
(matched-block-parser:paragraph-lines matched-block-parser))))
(define (list-match? a b)
(or (and (bullet-list-node? a) (bullet-list-node? b)
(eqv? (bullet-list-node-bullet-marker a)
(bullet-list-node-bullet-marker b)))
(and (ordered-list-node? a) (ordered-list-node? b)
(eqv? (ordered-list-node-delimiter a)
(ordered-list-node-delimiter b)))))
(cond ((>= (parser-state-indent ps) +parsing-code-block-indent+)
(block-start:none))
((parse-list (parser-state-document ps)
(parser-state-line ps)
(parser-state-next-non-space-index ps)
(+ (parser-state-column ps) (parser-state-indent ps))
(in-paragraph? matched-block-parser)) =>
(lambda (list-data)
(define col (car list-data))
(define lip (make-list-item-parser
(parser-state-document ps)
(- col (parser-state-column ps))))
(define block (cdr list-data))
(if (or (not (list-block-parser? matched))
(not (list-match? (block-parser-block matched) block)))
(let ((lbp (make-list-block-parser block)))
(list-node-tight-set! block "true")
(chain (block-start:of lbp lip)
(block-start:at-column _ col)))
(chain (block-start:of lip)
(block-start:at-column _ col)))))
(else (block-start:none))))
(define (parse-list doc line marker-index marker-column in-paragraph?)
(define (space-tab-end? line index)
(if (< index (source-line:length line))
(parsing:space/tab? (source-line:char-at line index))
#t))
(define (parse-ordered-list doc line index)
(define scanner (scanner:of (source-lines:of line)))
(do ((i 0 (+ i 1))) ((= i index)) (scanner:next! scanner))
(let ((digits (scanner:match-charset scanner char-set:digit)))
(and (not (> digits 9))
(let ((c (scanner:peek scanner)))
(case c
((#\. #\))
(and (>= digits 1)
(space-tab-end? line (+ digits index 1))
(let ((n (source-line:substring line index
(+ digits index))))
(cons (make-ordered-list-node doc
(string->number (source-line-content n)) c)
(+ digits index 1)))))
(else #f))))))
(define (parse-list-marker doc line index)
(let ((c (source-line:char-at line index)))
(case c
((#\- #\+ #\*)
(and (space-tab-end? line (+ index 1))
(cons (make-bullet-list-node doc c) (+ index 1))))
(else (parse-ordered-list doc line index)))))
(cond ((parse-list-marker doc line marker-index) =>
(lambda (list-marker)
(define block (car list-marker))
(define index-after-marker (cdr list-marker))
(define marker-length (- index-after-marker marker-index))
(define column-after-marker (+ marker-column marker-length))
(define (check-content line content-column index-after-marker)
(define len (source-line:length line))
(let loop ((i index-after-marker) (cc content-column))
(if (= i len)
(values cc #f)
(case (source-line:char-at line i)
((#\tab)
(loop (+ i 1) (+ cc (parsing:columns->next-tab-stop cc))))
((#\space) (loop (+ i 1) (+ cc 1)))
(else (values cc #t))))))
(let-values (((content-column has-content?)
(check-content line
column-after-marker
index-after-marker)))
(if (and in-paragraph?
(or (and (ordered-list-node? block)
(not (= (ordered-list-node-start-number block)
1)))
(not has-content?)))
#f
(let ((cc (if (or (not has-content?)
(> (- content-column column-after-marker)
+parsing-code-block-indent+))
(+ column-after-marker 1)
content-column)))
(cons cc block))))))
(else #f)))
)
| false |
74d92396fe0ccb2667087ffc44425a851312870f | 4590ebd066ad40c5d6af7200437edb1850145c62 | /lib9ml/chicken/9ML-toolkit/trunk/NineMLdiagram.scm | b90797cd7c20b8b954989ac43e03b40e9adf4ae8 | []
| no_license | QPC-WORLDWIDE/old_nineml_repo | ac5c69f578eb670244f9e6ca8c231334f94b7336 | e46cb248991fa575ea2ea076cc9a7ee3eaeac9e7 | refs/heads/master | 2021-12-09T08:13:51.660841 | 2016-05-04T00:58:54 | 2016-05-04T00:58:54 | 415,718,534 | 1 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 3,693 | scm | NineMLdiagram.scm |
(define (Diagram:module-initialize module-name enter-module find-module eval-env )
(define path-sigfun (Pdot (Pident (ident-create "Signal")) "sigfun"))
(define sigfun-type (Tcon (Tpath path-sigfun) '()))
(define ident-diagram (ident-create "diagram"))
(define path-diagram (Pident ident-diagram))
(define diagram-type (Tcon (Tpath path-diagram) '()))
(define ident-pure (ident-create "pure"))
(define path-pure (Pident ident-pure))
(define pure-type (Tcon (Tpath path-pure) '()))
(define-values (type-variables reset-type-variables
find-type-variable
begin-def end-def newvar generalize
make-deftype make-valtype make-kind
binop ternop path-star path-list path-arrow
star-type list-type arrow-type label-type string-type bot-type
)
(core-utils))
(let (
(sig
(list
(Type_sig ident-pure (make-typedecl (make-kind 0) #f))
(Type_sig ident-diagram (make-typedecl (make-kind 0) #f))
(Value_sig (ident-create "IDENTITY")
(make-valtype '() (arrow-type diagram-type diagram-type)))
(Value_sig (ident-create "SENSE")
(make-valtype '() (arrow-type (list-type label-type) (arrow-type diagram-type diagram-type))))
(Value_sig (ident-create "ACTUATE")
(make-valtype '() (arrow-type (list-type label-type) (arrow-type diagram-type diagram-type))))
(Value_sig (ident-create "ASSIGN")
(make-valtype '() (arrow-type (list-type label-type) (arrow-type pure-type diagram-type))))
(Value_sig (ident-create "ODE")
(make-valtype '() (arrow-type (list-type sigfun-type) (arrow-type sigfun-type (arrow-type sigfun-type (arrow-type pure-type diagram-type))))))
(Value_sig (ident-create "PURE")
(make-valtype '() (arrow-type sigfun-type pure-type)))
(Value_sig (ident-create "GROUP")
(make-valtype '() (arrow-type pure-type (arrow-type pure-type pure-type))))
(Value_sig (ident-create "RELATION")
(make-valtype '() (arrow-type label-type (arrow-type label-type (arrow-type sigfun-type (arrow-type pure-type pure-type))))))
(Value_sig (ident-create "SEQUENCE")
(make-valtype '() (arrow-type diagram-type (arrow-type diagram-type diagram-type))))
(Value_sig (ident-create "UNION")
(make-valtype '() (arrow-type diagram-type (arrow-type diagram-type diagram-type))))
(Value_sig (ident-create "TRANSITION")
(make-valtype '() (arrow-type diagram-type (arrow-type diagram-type (arrow-type sigfun-type diagram-type)))))
(Value_sig (ident-create "TRANSIENT")
(make-valtype '() (arrow-type diagram-type (arrow-type diagram-type (arrow-type sigfun-type diagram-type)))))
(Value_sig (ident-create "RTRANSITION")
(make-valtype '() (arrow-type diagram-type
(arrow-type diagram-type
(arrow-type sigfun-type (arrow-type sigfun-type diagram-type))))))
))
(struct
(list
(Type_def ident-diagram (make-kind 0)
(make-deftype '() (Tcon (Tpath path-diagram) '()) ))
(datacon 'diagram 'SENSE 2)
(datacon 'diagram 'ACTUATE 2)
(datacon 'diagram 'ASSIGN 2)
(datacon 'diagram 'ODE 4)
(datacon 'pure 'RELATION 4)
(datacon 'pure 'PURE 1)
(datacon 'pure 'GROUP 2)
(datacon 'diagram 'IDENTITY 1)
(datacon 'diagram 'TRANSITION 3)
(datacon 'diagram 'TRANSIENT 3)
(datacon 'diagram 'RTRANSITION 4)
(datacon 'diagram 'SEQUENCE 2)
(datacon 'diagram 'UNION 2)
))
)
(let ((modname (ident-create module-name)))
(enter-module modname (Signature sig))
(eval-env (mod-eval-cbv (eval-env) (list (Module_def modname (Structure struct)))))
)
))
| false |
33445229f044576be03a6883032e8aa1bfa3e5b7 | 4b2aeafb5610b008009b9f4037d42c6e98f8ea73 | /8/counting-sort-bang.scm | c44a71b3e2390a1da5c268f60886ee1af1a09985 | []
| no_license | mrinalabrol/clrs | cd461d1a04e6278291f6555273d709f48e48de9c | f85a8f0036f0946c9e64dde3259a19acc62b74a1 | refs/heads/master | 2021-01-17T23:47:45.261326 | 2010-09-29T00:43:32 | 2010-09-29T00:43:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 953 | scm | counting-sort-bang.scm | (define (counting-sort! fortuita)
(let* ((max (+ (vector-max fortuita) 1))
(numerata (make-vector (inexact->exact max) 0)))
(loop ((for x (in-vector fortuita)))
(vector-set! numerata x (+ (vector-ref numerata x) 1)))
(loop ((for x i (in-vector numerata 1)))
(vector-set! numerata i (+ x (vector-ref numerata (- i 1)))))
(let ((length (vector-length fortuita)))
(loop continue ((with swap-count 0 (+ swap-count 1))
(until (= swap-count length))
(with index (- length 1)))
(let* ((ref (vector-ref fortuita index))
(count-index (- (vector-ref numerata ref) 1)))
(vector-set! numerata ref count-index)
(if (= count-index index)
(continue (=> index (- index 1)))
(begin
(vector-swap! fortuita index count-index)
(continue))))))))
| false |
72295b2f874b0ab760afd1d2059b762f7eebbe3f | eef5f68873f7d5658c7c500846ce7752a6f45f69 | /test/algorithm-vector.scm | a7d83307f8fefb2863ef9c0f2f555842b60c9093 | [
"MIT"
]
| permissive | alvatar/spheres | c0601a157ddce270c06b7b58473b20b7417a08d9 | 568836f234a469ef70c69f4a2d9b56d41c3fc5bd | refs/heads/master | 2021-06-01T15:59:32.277602 | 2021-03-18T21:21:43 | 2021-03-18T21:21:43 | 25,094,121 | 13 | 3 | null | null | null | null | UTF-8 | Scheme | false | false | 66 | scm | algorithm-vector.scm | (##spheres-load core: testing)
(##spheres-load algorithm/vector)
| false |
6322c5290b995bbb4450392728a9b8e1a41054ce | ab2b756cdeb5aa94b8586eeb8dd5948b7f0bba27 | /src/lisp/tests/primes.scm | 1f59bcc7bb8c4a5e4ff54f1a299ef7c28d3aa787 | []
| 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 | 694 | scm | primes.scm | ;This calculates the biggest prime below the input.
;This calculation happens completely at compile-time.
(import (basics.scm))
(macro prime_p (N L)
(cond (((= () L) true)
((= 0 (rem N (car L))) false)
(true (prime_p N (cdr L))))))
(macro square (x) (* x x))
(macro prime2 (Limit N L B)
(cond (((> N (- (square Limit) 2)) B)
((and (< N Limit)
(prime_p N L))
(prime2 Limit
(+ N 1)
(reverse (cons N (reverse L)))
N))
((prime_p N L)
(prime2 Limit
(+ N 1)
L
N))
(true (prime2 Limit (+ N 1) L B)))))
(macro prime (N)
(prime2 N 3 (2) 0))
(= (prime 10) 97)
| false |
6c4e970e41f41253f96944389cf4286b417b38b3 | 923209816d56305004079b706d042d2fe5636b5a | /test/http/header-field/expect.scm | 732cd251ab19d4c17cf092f4beee7fc5bb892f38 | [
"BSD-3-Clause",
"BSD-2-Clause"
]
| permissive | tabe/http | 4144cb13451dc4d8b5790c42f285d5451c82f97a | ab01c6e9b4e17db9356161415263c5a8791444cf | refs/heads/master | 2021-01-23T21:33:47.859949 | 2010-06-10T03:36:44 | 2010-06-10T03:36:44 | 674,308 | 1 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 758 | scm | expect.scm | #!r6rs
(import (rnrs (6))
(http header-field expect)
(http assertion)
(xunit))
(assert-parsing-successfully Expect
"Expect: 100-continue"
`(,(string->list "Expect")
#\:
(,(string->list "100-continue"))
))
(assert-parsing-successfully Expect
"Expect: abc,foo=bar;baz"
`(,(string->list "Expect")
#\:
(((#\a #\b #\c) ())
((#\f #\o #\o) ((#\= (#\b #\a #\r) ((#\; () (#\b #\a #\z) ()))))))
))
(report)
| false |
6235c3032c961a101bb9267d8de3de2bba8e3f98 | c0c083d36459d67a7217af1fca14abf9cc385edd | /tl1/lexer.sld | 568bb1fc96921f6097c643bfa198da12cfb067ca | []
| no_license | SaitoAtsushi/TL1 | d4a8536a9ec4fad134d8e436f907d11c34a220ec | e9cb9d99f6ab2d2a16111e792b7193b84dac9d56 | refs/heads/master | 2021-07-12T19:27:31.571506 | 2021-03-04T17:16:47 | 2021-03-04T17:16:47 | 31,844,186 | 4 | 1 | null | null | null | null | UTF-8 | Scheme | false | false | 3,238 | sld | lexer.sld | ;;; -*- mode: gauche -*-
(define-library (tl1 lexer)
(export tl1-tokenize)
(import (scheme base)
(scheme write)
(scheme char)
(tl1 exception))
(begin
(define (reverse! lst)
(let lp ((lst lst) (ans '()))
(if (null? lst) ans
(let ((tail (cdr lst)))
(set-cdr! lst ans)
(lp tail lst)))))
(define (skip-while port pred)
(do ((ch (peek-char port) (peek-char port)))
((or (eof-object? ch) (not (pred ch))))
(read-char port)))
(define (skip-whitespace port)
(skip-while port char-whitespace?))
(define (read-while port pred)
(call-with-port (open-output-string)
(lambda(out)
(do ((ch (peek-char port) (peek-char port)))
((or (eof-object? ch) (not (pred ch)))
(get-output-string out))
(write-char (read-char port) out)))))
(define (subsequent-letter? ch)
(or (char-alphabetic? ch) (char-numeric? ch)))
(define (digit? ch)
(or (char-numeric? ch)
(case ch
((#\A #\B #\C #\D #\E #\F #\a #\b #\c #\d #\e #\f) #t)
(else #f))))
(define (lex port)
(skip-whitespace port)
(let ((ch (peek-char port)))
(case ch
((#\= #\+ #\- #\* #\/ #\# #\, #\( #\) #\< #\> #\[ #\] #\{ #\})
(read-char port) ch)
((#\; #\.) (read-char port) (lex port))
((#\:)
(read-char port)
(let ((nch (peek-char port)))
(if (eqv? nch #\=)
(begin (read-char port) ':=)
#\:)))
((#\")
(read-char port)
(let* ((str (read-while port (lambda(ch)(not (char=? #\" ch)))))
(end (read-char port)))
(when (eof-object? end)
(raise-tl1-error "string literal is not closed"))
str))
((#\$)
(read-char port)
(let ((num (string->number (read-while port digit?) 16)))
(unless (>= 255 num) (raise-tl1-error "number is too big" num))
num))
((#\')
(read-char port)
(let* ((nch (read-char port))
(end (read-char port)))
(if (char=? end #\')
(char->integer nch)
(raise-tl1-error "expected quotation mark but" end))))
((#\%)
(read-char port)
(skip-while port (lambda(ch)(not (char=? ch #\newline))))
(lex port))
(else
(cond
((eof-object? ch) ch)
((char-numeric? ch)
(let ((num (string->number (read-while port char-numeric?))))
(unless (>= 255 num) (raise-tl1-error "number is too big" num))
num))
((char-alphabetic? ch)
(let ((ident (read-while port subsequent-letter?)))
(string->symbol (string-downcase ident))))
(else (raise-tl1-error "Invalid character" ch)))))))
(define (tl1-tokenize port)
(let loop ((result '()))
(let ((token (lex port)))
(if (eof-object? token)
(reverse! result)
(loop (cons token result))))))
))
| false |
7a54a175007f5039ae83aebb77e145cce0434025 | bf6fad8f5227d0b0ef78598065c83b89b8f74bbc | /chapter03/fibonacci.ss | 85a4c423f3dc27f444984ef5de77fa3824084f33 | []
| no_license | e5pe0n/tspl | 931d1245611280457094bd000e20b1790c3e2499 | bc76cac2307fe9c5a3be2cea36ead986ca94be43 | refs/heads/main | 2023-08-18T08:21:29.222335 | 2021-09-28T11:04:54 | 2021-09-28T11:04:54 | 393,668,056 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 1,080 | ss | fibonacci.ss | (define print
(lambda (x)
(for-each display `(,x "\n"))))
(define fibonacci
(lambda (n)
(let fib ([i n])
(cond
[(= i 0) 0]
[(= i 1) 1]
[else (+ (fib (- i 1)) (fib (- i 2)))]))))
(define fibonacci-acc
(lambda (n)
(if (= n 0)
0
(let fib ([i n] [a1 1] [a2 0])
(if (= i 1)
a1
(fib (- i 1) (+ a1 a2) a1))))))
(print (fibonacci 0)) ; 0
(print (fibonacci 1)) ; 1
(print (fibonacci 2)) ; 1
(print (fibonacci 3)) ; 2
(print (fibonacci 4)) ; 3
(print (fibonacci 5)) ; 5
(print (fibonacci 6)) ; 8
(print (fibonacci 20)) ; 6765
(print (fibonacci 30)) ; 832040
(print (fibonacci 35)) ; 9227465
(print (fibonacci 40)) ; 102334155
(newline)
(print (fibonacci-acc 0)) ; 0
(print (fibonacci-acc 1)) ; 1
(print (fibonacci-acc 2)) ; 1
(print (fibonacci-acc 3)) ; 2
(print (fibonacci-acc 4)) ; 3
(print (fibonacci-acc 5)) ; 5
(print (fibonacci-acc 6)) ; 8
(print (fibonacci-acc 20)) ; 6765
(print (fibonacci-acc 30)) ; 832040
(print (fibonacci-acc 35)) ; 9227465
(print (fibonacci-acc 40)) ; 102334155 | false |
d73dcb56d8e5313f1cffc595ff03637bc21e8d27 | ece1c4300b543df96cd22f63f55c09143989549c | /Chapter3/Exercise3.51.scm | 71aadd5d83dc62176773c8d2b9ffe8cc74cb4350 | []
| no_license | candlc/SICP | e23a38359bdb9f43d30715345fca4cb83a545267 | 1c6cbf5ecf6397eaeb990738a938d48c193af1bb | refs/heads/master | 2022-03-04T02:55:33.594888 | 2019-11-04T09:11:34 | 2019-11-04T09:11:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 873 | scm | Exercise3.51.scm | ; Exercise 3.51: In order to take a closer look at delayed evaluation, we will use the following procedure, which simply returns its argument after printing it:
; (define (show x)
; (display-line x)
; x)
; What does the interpreter print in response to evaluating each expression in the following sequence?187
; (define x
; (stream-map
; show
; (stream-enumerate-interval 0 10)))
; (stream-ref x 5)
; (stream-ref x 7)
(load "/home/soulomoon/git/SICP/Chapter3/stream.scm")
(define (show x)
(display-line x)
x)
(define x
(stream-map
show
(stream-enumerate-interval 0 10)))
(stream-ref x 5)
(stream-ref x 7)
(stream-ref x 4)
; Welcome to DrRacket, version 6.7 [3m].
; Language: SICP (PLaneT 1.18); memory limit: 128 MB.
; 0
; 1
; 2
; 3
; 4
; 55
; 6
; 77
; 4
; >
;it runs it to get what it need when it need it, and cach it in memory. | false |
4a558e4537ac4459bab7b2a974ac78f8dd7d874b | a8216d80b80e4cb429086f0f9ac62f91e09498d3 | /lib/chibi/test.sld | 4aa039c380cba2a79fac7d9b8099eeb3860f1841 | [
"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,343 | sld | test.sld |
(define-library (chibi test)
(export
;; basic interface
test test-equal test-error test-assert test-not test-values
test-group current-test-group
test-begin test-end test-syntax-error test-propagate-info
test-run test-exit test-equal?
;; test and group data
test-get-name! test-group-name test-group-ref
test-group-set! test-group-inc! test-group-push!
;; parameters
current-test-verbosity
current-test-applier current-test-skipper current-test-reporter
current-test-group-reporter test-failure-count
current-test-epsilon current-test-comparator
current-test-filters current-test-removers
current-test-group-filters current-test-group-removers
current-column-width current-group-indent)
(import (scheme base)
(scheme case-lambda)
(scheme write)
(scheme complex)
(scheme process-context)
(scheme time)
(chibi diff)
(chibi term ansi)
(chibi optional))
(cond-expand
(chibi
(import (only (chibi) pair-source print-exception)))
(chicken
(import (only (chicken) print-error-message))
(begin
(define (pair-source x) #f)
(define print-exception print-error-message)))
(else
(begin
(define (pair-source x) #f)
(define print-exception write))))
(include "test.scm"))
| false |
9735742ec3ff19573ef59c27575af47554eb9d6a | c5de45adc74a609415f9318fda24479561a5728b | /day9-in-class.ss | 688f2da4bc5a4c3902cb00c896497f6ec028f20c | []
| no_license | rhit-zhuz9/CSSE304 | 8b7498336cf9573b18b3cd0f5654ddfb1b1dfc69 | f3a10bf17ca1daa532f277a0cf4f7c9746ea89e7 | refs/heads/master | 2023-03-15T11:54:52.913169 | 2018-05-30T03:00:43 | 2018-05-30T03:00:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 128 | ss | day9-in-class.ss | (define a (list + *))
(define aa '(1 2 3 . 4))
(define bb (cons (car aa) (cdr aa)))
(set-car! aa 5)
(set-car! (cdr aa) 6)
aa
bb | false |
39f158b51a11fdf9e8bf3096a0c8ac1fa244fff2 | 000dbfe5d1df2f18e29a76ea7e2a9556cff5e866 | /sitelib/asn.1/parser.scm | d9be7e829047604a92177607127cf3e39f7e558f | [
"BSD-3-Clause",
"LicenseRef-scancode-other-permissive",
"MIT",
"BSD-2-Clause"
]
| permissive | ktakashi/sagittarius-scheme | 0a6d23a9004e8775792ebe27a395366457daba81 | 285e84f7c48b65d6594ff4fbbe47a1b499c9fec0 | refs/heads/master | 2023-09-01T23:45:52.702741 | 2023-08-31T10:36:08 | 2023-08-31T10:36:08 | 41,153,733 | 48 | 7 | NOASSERTION | 2022-07-13T18:04:42 | 2015-08-21T12:07:54 | Scheme | UTF-8 | Scheme | false | false | 26,402 | scm | parser.scm | ;; This file is automatically generated by lalr.scm. DO NOT EDIT!!
(library
(asn.1 parser)
(export
asn.1-parser
make-lexical-token
lexical-token?
lexical-token-value
lexical-token-category
lexical-token-source
make-source-location
source-location?
source-location-input
source-location-line
source-location-column)
(import (rnrs) (asn.1 types) (srfi :1 lists))
(define-record-type
lexical-token
(fields category source value))
(define-record-type
source-location
(fields input line column offset length))
(define *max-stack-size* 500)
(define (lr-driver
action-table
goto-table
reduction-table)
(define ___atable action-table)
(define ___gtable goto-table)
(define ___rtable reduction-table)
(define ___lexerp #f)
(define ___errorp #f)
(define ___stack #f)
(define ___sp 0)
(define ___curr-input #f)
(define ___reuse-input #f)
(define ___input #f)
(define (___consume)
(set! ___input
(if ___reuse-input ___curr-input (___lexerp)))
(set! ___reuse-input #f)
(set! ___curr-input ___input))
(define (___pushback) (set! ___reuse-input #t))
(define (___initstack)
(set! ___stack (make-vector *max-stack-size* 0))
(set! ___sp 0))
(define (___growstack)
(let ((new-stack
(make-vector (* 2 (vector-length ___stack)) 0)))
(let loop ((i (- (vector-length ___stack) 1)))
(if (>= i 0)
(begin
(vector-set! new-stack i (vector-ref ___stack i))
(loop (- i 1)))))
(set! ___stack new-stack)))
(define (___checkstack)
(if (>= ___sp (vector-length ___stack))
(___growstack)))
(define (___push delta new-category lvalue)
(set! ___sp (- ___sp (* delta 2)))
(let* ((state (vector-ref ___stack ___sp))
(new-state
(cdr (assoc new-category (vector-ref ___gtable state)))))
(set! ___sp (+ ___sp 2))
(___checkstack)
(vector-set! ___stack ___sp new-state)
(vector-set! ___stack (- ___sp 1) lvalue)))
(define (___reduce st)
((vector-ref ___rtable st)
___stack
___sp
___gtable
___push
___pushback))
(define (___shift token attribute)
(set! ___sp (+ ___sp 2))
(___checkstack)
(vector-set! ___stack (- ___sp 1) attribute)
(vector-set! ___stack ___sp token))
(define (___action x l)
(let ((y (assoc x l))) (if y (cadr y) (cadar l))))
(define (___recover tok)
(let find-state ((sp ___sp))
(if (< sp 0)
(set! ___sp sp)
(let* ((state (vector-ref ___stack sp))
(act (assoc 'error (vector-ref ___atable state))))
(if act
(begin (set! ___sp sp) (___sync (cadr act) tok))
(find-state (- sp 2)))))))
(define (___sync state tok)
(let ((sync-set
(map car (cdr (vector-ref ___atable state)))))
(set! ___sp (+ ___sp 4))
(___checkstack)
(vector-set! ___stack (- ___sp 3) #f)
(vector-set! ___stack (- ___sp 2) state)
(let skip ()
(let ((i (___category ___input)))
(if (eq? i '*eoi*)
(set! ___sp -1)
(if (memq i sync-set)
(let ((act (assoc i (vector-ref ___atable state))))
(vector-set! ___stack (- ___sp 1) #f)
(vector-set! ___stack ___sp (cadr act)))
(begin (___consume) (skip))))))))
(define (___category tok)
(if (lexical-token? tok)
(lexical-token-category tok)
tok))
(define (___value tok)
(if (lexical-token? tok)
(lexical-token-value tok)
tok))
(define (___run)
(let loop ()
(if ___input
(let* ((state (vector-ref ___stack ___sp))
(i (___category ___input))
(attr (___value ___input))
(act (___action i (vector-ref ___atable state))))
(cond ((not (symbol? i))
(___errorp
"Syntax error: invalid token: "
___input)
#f)
((eq? act 'accept) (vector-ref ___stack 1))
((eq? act '*error*)
(if (eq? i '*eoi*)
(begin
(___errorp
"Syntax error: unexpected end of input")
#f)
(begin
(___errorp
"Syntax error: unexpected token : "
___input)
(___recover i)
(if (>= ___sp 0)
(set! ___input #f)
(begin (set! ___sp 0) (set! ___input '*eoi*)))
(loop))))
((>= act 0)
(___shift act attr)
(set! ___input (if (eq? i '*eoi*) '*eoi* #f))
(loop))
(else (___reduce (- act)) (loop))))
(let* ((state (vector-ref ___stack ___sp))
(acts (vector-ref ___atable state))
(defact (if (pair? acts) (cadar acts) #f)))
(if (and (= 1 (length acts)) (< defact 0))
(___reduce (- defact))
(___consume))
(loop)))))
(lambda (lexerp errorp)
(set! ___errorp errorp)
(set! ___lexerp lexerp)
(___initstack)
(___run)))
(define asn.1-parser
(lr-driver
'#(((*default* -52)
(WORD 3)
(CLASS 2)
(COMPONENTS 1)
(*eoi* -37))
((*default* *error*) (OF 11))
((*default* -53))
((*default* -52) (CLASS 2) (ASSIGN 12))
((*default* -54) (IMPLICIT 15) (EXPLICIT 14))
((*default* -40))
((*default* -38) (COMMA 18) (POSTRBRACE 17))
((*default* -2))
((*default* -48))
((*default* -3) (WORD 19))
((*default* *error*) (*eoi* 20))
((*default* *error*) (WORD 21))
((*default* -52) (CLASS 2) (COMPONENTS 1))
((*default* -54) (IMPLICIT 15) (EXPLICIT 14))
((*default* -55))
((*default* -56))
((*default* *error*)
(SEQUENCE 28)
(SET 27)
(CHOICE 26))
((*default* -52)
(WORD 30)
(CLASS 2)
(COMPONENTS 1)
(RBRACE -39)
(*eoi* -39))
((*default* -52)
(WORD 30)
(CLASS 2)
(COMPONENTS 1))
((*default* *error*) (ASSIGN 33))
((*default* -1) (*eoi* accept))
((*default* -12))
((*default* -54) (IMPLICIT 15) (EXPLICIT 14))
((*default* -7))
((*default* -4))
((*default* *error*)
(WORD 39)
(SEQUENCE 38)
(SET 37)
(CHOICE 26)
(ANY 36)
(ENUM 35))
((*default* *error*) (LBRACE 47))
((*default* *error*) (LBRACE 48))
((*default* *error*) (LBRACE 49))
((*default* -49))
((*default* -52) (CLASS 2))
((*default* -42))
((*default* -41))
((*default* -52) (CLASS 2) (COMPONENTS 1))
((*default* *error*)
(WORD 39)
(SEQUENCE 38)
(SET 37)
(CHOICE 26)
(ANY 36)
(ENUM 35))
((*default* -27) (LBRACE 56))
((*default* -28) (DEFINED 57))
((*default* -25) (LBRACE 48) (OF -14))
((*default* -24) (LBRACE 49) (OF -13))
((*default* -23))
((*default* -47))
((*default* -50) (OPTIONAL 59))
((*default* -30))
((*default* -44))
((*default* -46))
((*default* -45))
((*default* *error*) (OF 61))
((*default* *error*) (WORD 62))
((*default* -52)
(WORD 30)
(CLASS 2)
(COMPONENTS 1)
(RBRACE -37))
((*default* -52)
(WORD 30)
(CLASS 2)
(COMPONENTS 1)
(RBRACE -37))
((*default* -5))
((*default* -10))
((*default* -9))
((*default* -8))
((*default* -11))
((*default* -60) (POSTRBRACE 68))
((*default* *error*) (WORD 70))
((*default* *error*) (BY 73))
((*default* -26))
((*default* -51))
((*default* -43))
((*default* -52) (CLASS 2))
((*default* -52) (CLASS 2))
((*default* -33))
((*default* -31) (COMMA 77) (POSTRBRACE 76))
((*default* *error*) (RBRACE 78))
((*default* *error*) (RBRACE 79))
((*default* *error*) (RBRACE 80))
((*default* -61))
((*default* -6))
((*default* *error*) (NUMBER 81))
((*default* -57))
((*default* *error*) (RBRACE 83) (COMMA 82))
((*default* *error*) (WORD 84))
((*default* -54) (IMPLICIT 15) (EXPLICIT 14))
((*default* -54) (IMPLICIT 15) (EXPLICIT 14))
((*default* -32) (WORD 62))
((*default* *error*) (WORD 62))
((*default* -21))
((*default* -20))
((*default* -19))
((*default* -59))
((*default* *error*) (WORD 70))
((*default* -22))
((*default* -29))
((*default* *error*)
(WORD 39)
(SEQUENCE 91)
(SET 90)
(CHOICE 26)
(ANY 36)
(ENUM 35))
((*default* *error*)
(WORD 39)
(SEQUENCE 38)
(SET 37)
(CHOICE 26)
(ANY 36)
(ENUM 35))
((*default* -34))
((*default* -35))
((*default* -58))
((*default* -25) (LBRACE 48))
((*default* -24) (LBRACE 49))
((*default* -17))
((*default* -16))
((*default* -18))
((*default* -50) (OPTIONAL 59))
((*default* -36))
((*default* -15)))
(vector
'((22 . 4)
(20 . 5)
(18 . 6)
(17 . 7)
(5 . 8)
(2 . 9)
(1 . 10))
'()
'()
'((22 . 13))
'((23 . 16))
'()
'()
'()
'()
'()
'()
'()
'((22 . 22) (5 . 23) (3 . 24))
'((23 . 25))
'()
'()
'((9 . 29))
'((22 . 4) (20 . 31) (5 . 8))
'((22 . 4) (20 . 32) (5 . 8))
'()
'()
'()
'((23 . 34))
'()
'()
'((19 . 40)
(13 . 41)
(11 . 42)
(10 . 43)
(9 . 44)
(7 . 45)
(6 . 46))
'()
'()
'()
'()
'((22 . 13))
'()
'()
'((22 . 22) (5 . 23) (3 . 50))
'((13 . 51)
(11 . 42)
(10 . 52)
(9 . 53)
(7 . 54)
(6 . 46)
(4 . 55))
'()
'((12 . 58))
'()
'()
'()
'()
'((21 . 60))
'()
'()
'()
'()
'()
'((16 . 63) (15 . 64) (14 . 65))
'((22 . 4) (20 . 5) (18 . 6) (17 . 66) (5 . 8))
'((22 . 4) (20 . 5) (18 . 6) (17 . 67) (5 . 8))
'()
'()
'()
'()
'()
'((26 . 69))
'((25 . 71) (24 . 72))
'()
'()
'()
'()
'((22 . 74))
'((22 . 75))
'()
'()
'()
'()
'()
'()
'()
'()
'()
'()
'()
'((23 . 85))
'((23 . 86))
'((16 . 87))
'((16 . 88))
'()
'()
'()
'()
'((25 . 89))
'()
'()
'((13 . 92) (11 . 42) (10 . 93) (9 . 94) (8 . 95))
'((13 . 51)
(11 . 42)
(10 . 52)
(9 . 53)
(7 . 54)
(6 . 46)
(4 . 96))
'()
'()
'()
'()
'()
'()
'()
'()
'((21 . 97))
'()
'())
(vector
'()
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($2 (vector-ref ___stack (- ___sp 1)))
($1 (vector-ref ___stack (- ___sp 3))))
$1))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 1 (list (cons '() $1)))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 1 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($3 (vector-ref ___stack (- ___sp 1)))
($2 (vector-ref ___stack (- ___sp 3)))
($1 (vector-ref ___stack (- ___sp 5))))
(___push 3 2 (list (cons $1 (list $3))))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($4 (vector-ref ___stack (- ___sp 1)))
($3 (vector-ref ___stack (- ___sp 3)))
($2 (vector-ref ___stack (- ___sp 5)))
($1 (vector-ref ___stack (- ___sp 7))))
(___push
4
2
(cond ((assoc $2 $1)
=>
(lambda (slot) (set-cdr! slot (list $4)) $1))
(else (append! $1 (list (list $2 $4))))))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($4 (vector-ref ___stack (- ___sp 1)))
($3 (vector-ref ___stack (- ___sp 3)))
($2 (vector-ref ___stack (- ___sp 5)))
($1 (vector-ref ___stack (- ___sp 7))))
(___push
4
3
(begin
(asn.1-type-tag-set! $3 $1)
(if $2 (tag-explicit! $3) $3)))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 3 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 4 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 4 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 4 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 4 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($3 (vector-ref ___stack (- ___sp 1)))
($2 (vector-ref ___stack (- ___sp 3)))
($1 (vector-ref ___stack (- ___sp 5))))
(___push
3
5
(make-asn.1-type :type $1 :child $3))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 6 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 6 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($6 (vector-ref ___stack (- ___sp 1)))
($5 (vector-ref ___stack (- ___sp 3)))
($4 (vector-ref ___stack (- ___sp 5)))
($3 (vector-ref ___stack (- ___sp 7)))
($2 (vector-ref ___stack (- ___sp 9)))
($1 (vector-ref ___stack (- ___sp 11))))
(___push
6
7
(begin
(asn.1-type-tag-set! $5 $3)
(let ((ret (make-asn.1-type
:type
$1
:child
(list $5)
:loop
#t
:optional
$6)))
(if $4 (tag-explicit! ret) ret))))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 8 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 8 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 8 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($4 (vector-ref ___stack (- ___sp 1)))
($3 (vector-ref ___stack (- ___sp 3)))
($2 (vector-ref ___stack (- ___sp 5)))
($1 (vector-ref ___stack (- ___sp 7))))
(___push
4
9
(make-asn.1-type :type $1 :child $3))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($4 (vector-ref ___stack (- ___sp 1)))
($3 (vector-ref ___stack (- ___sp 3)))
($2 (vector-ref ___stack (- ___sp 5)))
($1 (vector-ref ___stack (- ___sp 7))))
(___push
4
9
(make-asn.1-type :type $1 :child $3))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($4 (vector-ref ___stack (- ___sp 1)))
($3 (vector-ref ___stack (- ___sp 3)))
($2 (vector-ref ___stack (- ___sp 5)))
($1 (vector-ref ___stack (- ___sp 7))))
(___push
4
9
(make-asn.1-type :type $1 :child $3))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($4 (vector-ref ___stack (- ___sp 1)))
($3 (vector-ref ___stack (- ___sp 3)))
($2 (vector-ref ___stack (- ___sp 5)))
($1 (vector-ref ___stack (- ___sp 7))))
(___push 4 10 (make-asn.1-type :type $1))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 11 (make-asn.1-type :type $1))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 11 (make-asn.1-type :type $1))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 11 (make-asn.1-type :type $1))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($2 (vector-ref ___stack (- ___sp 1)))
($1 (vector-ref ___stack (- ___sp 3))))
(___push
2
11
(make-asn.1-type
:type
$1
:child
#f
:defined-by
$2))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 11 (make-asn.1-type :type $1))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* () (___push 0 12 '())))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($3 (vector-ref ___stack (- ___sp 1)))
($2 (vector-ref ___stack (- ___sp 3)))
($1 (vector-ref ___stack (- ___sp 5))))
(___push 3 12 $3)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 13 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 14 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($2 (vector-ref ___stack (- ___sp 1)))
($1 (vector-ref ___stack (- ___sp 3))))
(___push 2 14 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 15 (list $1))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($3 (vector-ref ___stack (- ___sp 1)))
($2 (vector-ref ___stack (- ___sp 3)))
($1 (vector-ref ___stack (- ___sp 5))))
(___push 3 15 (append! $1 (list $3)))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($3 (vector-ref ___stack (- ___sp 1)))
($2 (vector-ref ___stack (- ___sp 3)))
($1 (vector-ref ___stack (- ___sp 5))))
(___push 3 15 (append! $1 (list $3)))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($4 (vector-ref ___stack (- ___sp 1)))
($3 (vector-ref ___stack (- ___sp 3)))
($2 (vector-ref ___stack (- ___sp 5)))
($1 (vector-ref ___stack (- ___sp 7))))
(___push
4
16
(let ((ret $4))
(asn.1-type-name-set! ret $1)
(asn.1-type-tag-set! ret $2)
(if $3 (tag-explicit! ret) ret)))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* () (___push 0 17 '())))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 17 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($2 (vector-ref ___stack (- ___sp 1)))
($1 (vector-ref ___stack (- ___sp 3))))
(___push 2 17 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 18 (list $1))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($3 (vector-ref ___stack (- ___sp 1)))
($2 (vector-ref ___stack (- ___sp 3)))
($1 (vector-ref ___stack (- ___sp 5))))
(___push 3 18 (append! $1 (list $3)))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($3 (vector-ref ___stack (- ___sp 1)))
($2 (vector-ref ___stack (- ___sp 3)))
($1 (vector-ref ___stack (- ___sp 5))))
(___push 3 18 (append! $1 (list $3)))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($2 (vector-ref ___stack (- ___sp 1)))
($1 (vector-ref ___stack (- ___sp 3))))
(___push
2
19
(begin (asn.1-type-optional-set! $1 $2) $1))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 19 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 19 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 19 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($4 (vector-ref ___stack (- ___sp 1)))
($3 (vector-ref ___stack (- ___sp 3)))
($2 (vector-ref ___stack (- ___sp 5)))
($1 (vector-ref ___stack (- ___sp 7))))
(___push
4
20
(let ((ret $4))
(asn.1-type-name-set! ret $1)
(asn.1-type-tag-set! ret $2)
(if $3 (tag-explicit! ret) ret)))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 20 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($3 (vector-ref ___stack (- ___sp 1)))
($2 (vector-ref ___stack (- ___sp 3)))
($1 (vector-ref ___stack (- ___sp 5))))
(___push
3
20
(let ((ret $3))
(asn.1-type-tag-set! $1)
(if $2 (tag-explicit! ret) ret)))))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* () (___push 0 21 #f)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 21 #t)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* () (___push 0 22 #f)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 22 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* () (___push 0 23 #f)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 23 #t)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* () (___push 1 23 #f)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 24 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($3 (vector-ref ___stack (- ___sp 1)))
($2 (vector-ref ___stack (- ___sp 3)))
($1 (vector-ref ___stack (- ___sp 5))))
(___push 3 24 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($2 (vector-ref ___stack (- ___sp 1)))
($1 (vector-ref ___stack (- ___sp 3))))
(___push 2 25 $1)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* () (___push 0 26 #f)))
(lambda (___stack ___sp ___goto-table ___push yypushback)
(let* (($1 (vector-ref ___stack (- ___sp 1))))
(___push 1 26 $1)))))))
| false |
6236656106836905501c1107f68c5ba5254f47c7 | f6c954bac9db8e566fdd24249a4970dd759455eb | /stream.scm | ec3c46bcf8b672a6c11a6532283b33716503efd0 | []
| no_license | yangzhixuan/sicp_hw | 247de20628128345d22b417b86b30ce981cdaa12 | 48b67ec630cf5b57954ae7e18e4c1d915db148b9 | refs/heads/master | 2021-01-13T02:16:57.495913 | 2014-05-14T07:49:23 | 2014-05-14T07:49:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 870 | scm | stream.scm | (define-syntax mydelay
(syntax-rules ()
[(_ expr1 expr2 ...)
(lambda () (begin expr1 expr2 ...))]))
(define (myforce promise)
(promise))
(define-syntax stream-cons
(syntax-rules ()
[(_ a b)
(cons a (mydelay b))]))
(define (stream-car p)
(car p))
(define (stream-cdr p)
(myforce (cdr p)))
(define (stream-null) '())
(define (stream-null? stream)
(null? stream))
(define (stream-map op . ls)
(let [(cars (map stream-car ls))]
(if (memv stream-null cars)
stream-null
(stream-cons
(apply op cars)
(apply stream-map (cons op (map stream-cdr ls)))))))
(define ns
(stream-cons
1
(stream-map (lambda (x) (+ x 1)) ns)))
(define (print-stream s)
(let loop ([i 0] [s s])
(cond [(or (> i 20) (null? s)) #f]
[else (printf "~A~N" (stream-car s))
(loop (+ i 1) (stream-cdr s))])))
| true |
722926244b993307a893c8baf9aa30f82cf90d45 | 8807c9ce1537d4c113cb5640f021be645d1bee50 | /tests/test.scm | 3d9cd54906718798eb971e2318e8e9afc27a9b44 | []
| no_license | Borderliner/tehila | fabd8dbf981fe0f637e986d12d568c582ac36c47 | 576a89dc0a1be192ead407265bc2272cd6a55226 | refs/heads/master | 2020-04-05T09:46:46.508539 | 2010-12-14T01:03:45 | 2010-12-14T01:03:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 996 | scm | test.scm | (require-extension lolevel)
(require-extension gl)
(require-extension glu)
(require-extension glut)
(require-extension srfi-4)
(load "list_utils.scm")
(load "binary_utils.scm")
(load "image_utils.scm")
(print "Ok, good to go. Enjoy")
(define (make-check-image)
(let* ((check-image-height 64)
(check-image-width 64)
(buffer-size (* check-image-width check-image-height 4))
(buffer (make-u8vector (* check-image-width check-image-height 4) 0))
(dummy 255)
(counter 0))
(do ((i 0 (+ i 1))) ((> i (- check-image-height 1)) buffer)
(do ((j 0 (+ j 1))) ((> j (- check-image-width 1)))
(let ((c (if (or (equal? i 0) (equal? (remainder 64 i) 0)) 255 0)))
(u8vector-set! buffer (+ counter 0) dummy)
(u8vector-set! buffer (+ counter 1) dummy)
(u8vector-set! buffer (+ counter 2) dummy)
(u8vector-set! buffer (+ counter 3) 255)
(set! counter (+ 4 counter)))))))
(print (make-check-image))
| false |
333e708af8eb5218f95875df625a00bbcc75032d | 6610a6531c4ea2c8d43b8b5c573a68620730476b | /harlani.scm | 1589033c33e66aea61e2684fd72aa077f781e18a | [
"BSD-3-Clause-Open-MPI"
]
| permissive | catufunwa/harlan | 5f00a6a23a975be0fd94526cb3668a85344f9aaf | 9902239cc74edf10d5a65083492c30ea4d4b5dbb | refs/heads/master | 2021-01-17T12:03:59.289385 | 2013-12-24T01:46:22 | 2013-12-24T01:46:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 1,941 | scm | harlani.scm | (import
(elegant-weapons match)
(except (chezscheme) compile debug)
(harlan compiler)
(harlan compile-opts)
(harlan driver))
;; copied from harlanc.scm.
(define (output-filename input)
(let ((base (path-last (path-root input))))
(if (make-shared-object)
(string-append base ".so")
base)))
(define (compile path)
(let-values (((source testspec) (read-source path)))
(g++-compile-stdin (harlan->c++ source) (output-filename path))))
(parse-args (command-line))
(display "Some useful options:\n")
(display " (make-shared-object) -- Compile to a shared library instead of an executable\n")
(display " (harlan-library-path) -- Where Harlan finds imported libraries\n")
(display " (harlan-runtime-path) -- Where Harlan finds its runtime files\n")
(display " (verbose) -- Make Harlan print detailed information\n")
(display " (debug) -- Generate debugging information\n")
(display " (timing) -- Display pass timing information\n")
(display "\n")
(display "Compile a file with (compile \"filename\")\n")
(define-syntax try
(syntax-rules (catch)
((_ (catch (x) handler-body ... e)
body ...)
(call/cc (lambda (k)
(with-exception-handler
(lambda (x)
handler-body ... (k e))
(lambda ()
body ...)))))))
(define-syntax match-commands
(syntax-rules (=>)
((_ e cmd ...)
(match e
((cmd . ,args)
(try (catch (x) (display-condition x) (newline))
(begin (display (apply cmd args)) (newline)))) ...
(else (display "unrecognized command\n"))))))
(define debug generate-debug)
(call/cc
(lambda (exit)
(let repl ()
(display "> ")
(match-commands
(read)
make-shared-object
harlan-library-path
harlan-runtime-path
compile
verbose
debug
timing
exit)
(repl))))
| true |
35104f6ad68f3d9a82bc7a340a3df6afdc3880a7 | b43e36967e36167adcb4cc94f2f8adfb7281dbf1 | /scheme/swl1.3/tests/error-help/test33.ss | f9168fcf4335ec43b35e79d5aa4899675ad5f47f | [
"SWL",
"TCL"
]
| permissive | 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 | 87 | ss | test33.ss | ; Test error "parenthesized list terminated by close bracket"
(define pair '(a . b])
| false |
31bfea0717606a7811f93da5c40485a723c94866 | 9046fb7fa896d41aecd0f98c8cdd26447ccf9a1a | /A13-multiple-files/parse.ss | 5c4f5f40d743778e037fe0862edf8358e7cef1f1 | []
| no_license | Joycexuy2/CSSE304 | 25743e01c1fb7e743ba0a83145872517229617b5 | 6e405e5a277ad14228d031d9fcbdc54325e9a88a | refs/heads/master | 2021-01-11T06:59:53.372832 | 2016-10-25T22:27:11 | 2016-10-25T22:27:11 | 71,944,384 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 7,470 | ss | parse.ss | ; This is a parser for simple Scheme expressions, such as those in EOPL, 3.1 thru 3.3.
; You will want to replace this with your parser that includes more expression types, more options for these types, and error-checking.
; Procedures to make the parser a little bit saner.
(define 1st car)
(define 2nd cadr)
(define 3rd caddr)
(define 4rd cadddr)
;;(define parse-exp
; (lambda (datum)
; (cond
; [(symbol? datum) (var-exp datum)]
; [(number? datum) (lit-exp datum)]
; [(pair? datum)
; (cond
;
; [else (app-exp (parse-exp (1st datum))
; (map parse-exp (cdr datum)))])]
; [else (eopl:error 'parse-exp "bad expression: ~s" datum)])))
;;helper, check whether the list are all symbol
(define list-of-expression?
[lambda (e)
(if (list? e) (andmap expression? e) #f)])
(define lambda-var?
[lambda (e)
(cond
[(symbol? e) #t]
[(pair? e)
(let helper ([rest e])
(cond
[(null? rest) #t]
[(symbol? rest) #t]
[else
(and (symbol? (car rest)) (helper (cdr rest)))]))]
[else #f])])
(define-datatype expression expression?
[var-exp (id symbol?)]
[lit-exp (id lit?)]
[lambda-exp (var (lambda (v) (or (symbol? v) (list-of-expression? v))))
(body list-of-expression?)]
[lambda-var-exp (var lambda-var?)]
[set!-exp (id symbol?) (r-val-exp expression)]
[if-else-exp (condition-exp expression?)
(true-exp expression?) (false-exp expression?)]
[if-exp (condition-exp expression?)
(true-exp expression?)]
[let-exp (ls list-of-expression?)
(body list-of-expression?)]
[single-let-exp (var expression?)
(body expression?)]
[named-let-exp (name expression?)
(ls list-of-expression?) (body list-of-expression?)]
[let*-exp (ls list-of-expression?)
(body list-of-expression?)]
[letrec-exp (ls list-of-expression?)
(body list-of-expression?)]
[app-exp (rator expression?)
(rand list-of-expression?)])
(define lit?
(lambda (e)
(or (number? e)
(string? e)
(symbol? e)
(boolean? e)
(char? e)
(vector? e)
(list? e))))
(define parse-exp
(lambda (datum)
(cond
[(and (list? datum) (eq? 'quote (1st datum)))
(if (> (length datum) 2)
(eopl:error 'parse-exp "Invalid syntax for quote: ~s" datum)
(lit-exp (cadr datum)))]
[((lambda (e)
(or (number? e)
(string? e)
(boolean? e)
(char? e)
(vector? e))) datum) (lit-exp datum)]
[(symbol? datum) (var-exp datum)]
;;set! expression
[(eqv? (1st datum) 'set!)
(cond
[(> (length datum) 3)
(eopl:error 'parse-exp "Too many parts: ~s" datum)]
[(= (length datum) 3)
(if (symbol? (2nd datum))
(set!-exp (parse-exp (2nd datum)) (parse-exp (3rd datum)))
(eopl:error 'parse-exp "declaration in set-expression ~s must take a symbol" (2nd datum)))]
[else (eopl:error 'parse-exp "set expression ~s has incorrect arguments" datum)]
)]
[(pair? datum)
(cond
[(not (list? datum))
(eopl:error 'parse-exp "expression ~s is an improper list" datum)]
;;lambda expression
[(eqv? (car datum) 'lambda)
(cond
[(< (length datum) 3)
(eopl:error 'parse-exp "lambda expression: ~s" datum)]
[(symbol? (2nd datum))
(lambda-exp (2nd datum) (map parse-exp (cddr datum)))]
[(list? (2nd datum))
(if (andmap (lambda (v) (symbol? v)) (cadr datum))
(lambda-exp (map parse-exp (2nd datum)) (map parse-exp (cddr datum)))
(eopl:error 'parse-exp "lambda argument list: formals must be symbols: ~s" datum))]
[else (eopl:error 'parse-exp "Incorrect lambda syntax: ~s" datum)])]
;;if expression
[(eqv? 'if (1st datum))
(cond
[(= 2 (length datum))
(eopl:error 'parse-exp "missing then and else parts: ~s" datum)]
[(= 3 (length datum))
(if-exp (parse-exp (2nd datum)) (parse-exp (3rd datum)))]
[(= 4 (length datum))
(if-else-exp (parse-exp (2nd datum))
(parse-exp (3rd datum))
(parse-exp (4th datum)))]
[else
(eopl:error 'parse-exp "if-expression: ~s does not have the right format: condition, then, else" datum)])]
;;let expression
[(or (eqv? 'let (1st datum)) (eqv? 'letrec (1st datum)) (eqv? 'let* (1st datum)));;check whether the 1st datum meeet any let type
(cond
[(< (length datum) 3) (eopl:error 'parse-exp "let-expression has incorrect length")]
[else
(letrec ([parse-let
(lambda (ls)
(let helper ((rest ls))
(cond
[(null? rest) (list)]
[(not (list? rest)) (eopl:error 'parse-exp "~s-list is not a proper list" (1st datum) rest)]
[(not (list? (car rest))) (eopl:error 'parse-exp "declaration in ~s-list is not a proper list" (1st datum) (car rest))]
[(not (= 2 (length (car rest)))) (eopl:error 'parse-exp "declaration in ~s-list must be in length of two ~s" (1st datum) (car rest))]
[(not (symbol? (caar rest))) (eopl:error 'parse-exp "variable in ~s must be a symbol ~s" (1st datum) (caar rest))]
[else
(cons (single-let-exp (parse-exp (caar rest))
(parse-exp (cadar rest)))
(helper (cdr rest)))])))])
(cond
[(symbol? (2nd datum))
(cond
[(= 3 (length datum)) (eopl:error 'parse-exp "named-let-exp has incorrect length ~s" datum)]
[(not (eqv? 'let (1st datum))) (eopl:error 'parse-exp "declaration in ~s must be a proper list ~s" (1st datum) (2nd datum))]
[else (named-let-exp (var-exp (2nd datum))
(parse-let (3rd datum))
(map parse-exp (cdddr datum)))])]
[(eqv? 'let (1st datum))
(let-exp (parse-let (2nd datum)) (map parse-exp (cddr datum)))]
[(eqv? 'let* (1st datum))
(let*-exp (parse-let (2nd datum)) (map parse-exp (cddr datum)))]
[else
(letrec-exp (parse-let (2nd datum)) (map parse-exp (cddr datum)))]))])]
[else (app-exp (parse-exp (1st datum))
(map parse-exp (cdr datum)))])]
[else (eopl:error 'parse-exp "bad expression: ~s" datum)])))
;;#4b
(define unparse-exp
(lambda (e)
(cases expression e
[var-exp (id) id]
[lit-exp (id) id]
[lambda-var-exp (var) var]
[lambda-exp (var body)
(cons 'lambda (cons (if (symbol? var) var (map unparse-exp var))
(map unparse-exp body)))]
[set!-exp (id r-val-exp)
(list 'set! (unparse-exp id) (unparse-exp r-val-exp))]
[if-exp (condition-exp true-exp)
(list 'if (unparse-exp condition-exp) (unparse-exp true-exp))]
[if-else-exp (condition-exp true-exp false-exp)
(list 'if (unparse-exp condition-exp) (unparse-exp true-exp) (unparse-exp false-exp))]
[let-exp (ls body)
(cons* 'let (map unparse-exp ls) (map unparse-exp body))]
[single-let-exp (var body)
(list (unparse-exp var) (unparse-exp body))]
[named-let-exp (name ls body) (cons 'let
(cons (unparse-exp name) (cons (map unparse-exp ls) (map unparse-exp body))))]
[let*-exp (ls body) (cons* 'let*
(cons (map unparse-exp ls) (map unparse-exp body)))]
[letrec-exp (ls body) (cons* 'letrec
(cons (map unparse-exp ls) (map unparse-exp body)))]
[app-exp (rator rand) (cons (unparse-exp rator) (map unparse-exp rand))])))
| false |
aed79f0ca2a50cae5a52da55cf11bcc5380c3a2c | 4f17c70ae149426a60a9278c132d5be187329422 | /scheme/r6rs/io/ports.ss | 49c3e7005f582902fea8b17e61bdba8a2464220e | []
| no_license | okuoku/yuni-core | 8da5e60b2538c79ae0f9d3836740c54d904e0da4 | c709d7967bcf856bdbfa637f771652feb1d92625 | refs/heads/master | 2020-04-05T23:41:09.435685 | 2011-01-12T15:54:23 | 2011-01-12T15:54:23 | 889,749 | 2 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 2,327 | ss | ports.ss | (library (yuni scheme r6rs io ports)
(export
binary-port? buffer-mode buffer-mode? bytevector->string call-with-bytevector-output-port call-with-port
call-with-string-output-port close-port eol-style error-handling-mode file-options flush-output-port
get-bytevector-all get-bytevector-n get-bytevector-n! get-char get-datum get-line get-string-all get-string-n
get-string-n! get-u8 &i/o &i/o-decoding i/o-decoding-error? &i/o-encoding i/o-encoding-error-char
i/o-encoding-error? i/o-error-filename i/o-error-port i/o-error-position i/o-error? &i/o-file-already-exists
i/o-file-already-exists-error? &i/o-file-does-not-exist i/o-file-does-not-exist-error? &i/o-file-is-read-only
i/o-file-is-read-only-error? &i/o-file-protection i/o-file-protection-error? &i/o-filename
i/o-filename-error? &i/o-invalid-position i/o-invalid-position-error? &i/o-port
i/o-port-error? &i/o-read i/o-read-error? &i/o-write i/o-write-error? lookahead-char
lookahead-u8 make-custom-binary-input-port make-custom-binary-input/output-port make-custom-binary-output-port
make-custom-textual-input-port make-custom-textual-input/output-port make-custom-textual-output-port
make-i/o-decoding-error make-i/o-encoding-error make-i/o-error make-i/o-file-already-exists-error
make-i/o-file-does-not-exist-error make-i/o-file-is-read-only-error make-i/o-file-protection-error
make-i/o-filename-error make-i/o-invalid-position-error make-i/o-port-error make-i/o-read-error
make-i/o-write-error latin-1-codec make-transcoder native-eol-style native-transcoder open-bytevector-input-port
open-bytevector-output-port open-file-input-port open-file-input/output-port open-file-output-port
open-string-input-port open-string-output-port output-port-buffer-mode port-eof? port-has-port-position?
port-has-set-port-position!? port-position port-transcoder port? put-bytevector put-char put-datum put-string
put-u8 set-port-position! standard-error-port standard-input-port standard-output-port string->bytevector
textual-port? transcoded-port transcoder-codec transcoder-eol-style transcoder-error-handling-mode utf-16-codec
utf-8-codec input-port? output-port? current-input-port current-output-port current-error-port eof-object eof-object?
get-bytevector-some
)
(import (yuni scheme r6rs))
)
| false |
be97930bd46b843d8d212fe04e33496d5cea1ce2 | ac2a3544b88444eabf12b68a9bce08941cd62581 | /gsc/tests/67-s64vector/vectorlength.scm | 15bafb05673d6f0e25f582decb94e23e2732121a | [
"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 | 272 | scm | vectorlength.scm | (declare (extended-bindings) (not constant-fold) (not safe))
(define a (##s64vector -9223372036854775808 9223372036854775807))
(define b (##make-s64vector 10 99))
(define c '#s64(1 2 3 4))
(define (test v)
(println (##s64vector-length v)))
(test a)
(test b)
(test c)
| false |
9551f60f9b11f87d9e951b5e48a618947af9d9e9 | 140c661a4b57f338d421a4b5e7bcb7cda02c841c | /srfi-signature.scm | 706abec6bcea7669a483ba6f9ff340ab40d1b1e8 | []
| no_license | srfi-explorations/srfi-conversion | 80a95ba6f333476baf2720137c4986675a918383 | de9992701fe2e2c7a43aeb8e74afd7e25b13b312 | refs/heads/master | 2021-07-20T05:40:42.054466 | 2021-02-28T22:49:15 | 2021-02-28T22:49:15 | 243,240,534 | 1 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 4,041 | scm | srfi-signature.scm | #! /usr/bin/env chibi-scheme
#| Given input signatures, generate HTML with the recommended markup.
* TODO
- Automate testing.
- Specify the input syntax precisely.
- Handle macros expressed with square brackets.
* See "example-signatures.scm" for example input.
|#
(import (scheme base)
(scheme char)
(scheme process-context)
(scheme read)
(scheme write)
(srfi 1)
(srfi 130)
(srfi 166)
(chibi sxml)
(srfi-index)
(utilities))
(define (prepose sep xs)
(append-map (lambda (x) (list sep x)) xs))
(define (space-prepose xs)
(prepose " " xs))
(define (interpose sep xs)
(if (null? xs) '() (cdr (prepose sep xs))))
(define (comma-separate xs) (interpose ", " xs))
(define (space-separate xs) (interpose " " xs))
(define (ascii-alphanumeric? char)
(or (char<=? #\A char #\Z)
(char<=? #\a char #\z)
(char<=? #\0 char #\9)))
(define tab-amount 2)
(define (weird->hyphen string)
(define (mangle char)
(cond ((char=? char #\-) char)
((ascii-alphanumeric? char) (char-downcase char))
(else #\-)))
(let loop ((in (string->list string)) (out '()) (had-hyphen? #t))
(if (null? in) (list->string (reverse out))
(let* ((char (mangle (car in))) (hyphen? (char=? #\- char)))
(loop (cdr in) (if (and hyphen? had-hyphen?) out (cons char out))
hyphen?)))))
(define unique-html-id
(let ((used '()))
(lambda (string)
(let loop ((n 1))
(let ((id (if (= n 1) string
(string-append string "-" (number->string n)))))
(cond ((member id used) (loop (+ n 1)))
(else (set! used (cons id used))
id)))))))
(define (signature-html-id string)
(unique-html-id (string-append "def-" (weird->hyphen string))))
(define zero-width-space "\x200B;")
(define long-rightwards-arrow "\x27F6;") ; ⟶
(define (signature->sxml signature)
(define (parenthesized html-id name arguments returns note)
`(dt (@ (id ,html-id))
"("
(dfn ,name)
,(if (null? arguments)
`(")" (span))
`(span ,arguments ")"))
,@(if returns
`((span (@ (class "returns"))
" "
,long-rightwards-arrow
" "
,@(comma-separate
(map (lambda (r) (show #f (pretty r)))
returns))))
'())
,@(if note `(" " (p ,note)) '())))
(define (syntax-args arguments literals)
(let descend ((arguments arguments))
(cond ((null? arguments) '())
((pair? arguments)
`("("
,@(space-separate (map descend arguments))
")"))
((symbol? arguments)
(cond ((eq? arguments '...) arguments)
((memq arguments literals)
`(code ,arguments))
(else `(var ,arguments))))
(else (error "Unexpected macro argument." arguments)))))
(let* ((arguments (signature/arguments signature))
(name (signature/name signature))
(note (signature/note signature))
(returns (signature/returns signature))
(type (signature/type signature))
(html-id (signature-html-id (symbol->string name))))
(case (signature/type signature)
((other) `(dt (@ (id ,html-id)) (dfn ,name)))
((procedure)
(parenthesized html-id
name
(space-prepose (map (lambda (a) `(var ,a)) arguments))
returns
note))
((syntax)
(parenthesized html-id
name
(syntax-args arguments (signature/literals signature))
returns
note))
(else (error "Unrecognized type." type)))))
(define (main)
(let ((signatures (map list->signatures (read-all-forms))))
(sxml-display-as-html
`(html
(head (title "SRFI Signatures")
(link (@ (rel "stylesheet") (href "signature.css"))))
(body
(dl (@ (class "signatures"))
,(map (lambda (s)
(cond ((signature? s) (signature->sxml s))
((pair? s)
(if (null? (cdr s))
(signature->sxml (car s))
`(div ,(map signature->sxml s))))
(else '())))
signatures)))))))
(main) | false |
89c6c8dd7cd35515e466b0b4102d0405098ac422 | 2920e836b4e8cd7823f59ae05620f08572bd297e | /linedit/commands.scm | c31e7b94902924378b46ac18cbe07b2588732bd5 | []
| no_license | duncanmak/linedit | 036a2c6bf640baabfd6c9c6205cee50168ed7ec9 | 9e458453fed0cc13e647f713f8dbf882ebda4da7 | refs/heads/master | 2021-01-22T22:56:58.850491 | 2014-12-13T20:30:37 | 2014-12-13T20:30:37 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | Scheme | false | false | 3,853 | scm | commands.scm | ;;; -*- Mode: Scheme; scheme48-package: commands -*-
;;;
;;; Copyright © 2007 Duncan Mak <[email protected]>
;;;
;;; This code is placed in the Public Domain. All warranties are
;;; disclaimed.
;;;
;;; Linedit Commands
;;;
;;; This file contains the commands used by linedit.
;;;
;;; All commands take the form
;;;
;;; command line [key]
;;;
;;; and return a new line.
;;;
;;; While the 'key' argument is optional, it cannot be omitted
;;; entirely. Commands that do not make use of the key argument should
;;; be defined in this form:
;;;
;;; (define (command-that-discards-key line . key))
;;;
;;; This allows callers of the command to pass only the 'line'
;;; argument, but preserves the command interface.
;;;
(define (accept-line l . k)
(newline)
(add-line-history (line:history l) (line->string l))
(reset-edit-history (line:history l))
(signal 'interrupt l))
(define (insert-char l k)
(tputs (enter-insert-mode)
(string k)
(exit-insert-mode))
(line-insert l k))
;; (define (insert-char l k)
;; (let ((nl (line-insert l k)))
;; (display-line nl)
;; nl))
(define (delete-backward-char l . k)
(if (null? (line:left l))
l
(begin (tputs (cursor-left)
(delete-character))
(shift-left l))))
(define (delete-char l . k)
(if (null? (line:right l))
l
(begin (tputs (delete-character))
(shift-right l))))
(define (move-beginning-of-line l . k)
(tputs (column-address (line:column l)))
(beginning-of-line l))
(define (move-end-of-line l . k)
(tputs (column-address (+ (line:column l) (line:length l))))
(end-of-line l))
(define (backward-char l . k)
(if (null? (line:left l))
l
(begin (tputs (cursor-left))
(shift-left l (get-char l line:left)))))
(define (forward-char l . k)
(if (null? (line:right l))
l
(begin (tputs (cursor-right))
(shift-right l (get-char l line:right)))))
(define (clear-line l . k)
(tputs (column-address (line:column l))
(clr-eol))
l)
(define (display-line l . k)
(tputs (column-address 0)
(line:prompt l)
(line->string l)
(column-address (line:cursor l)))
l)
(define (kill-line l . k)
(tputs (clr-eol))
(copy-line l (line:left l) '()))
(define (move-word l direction action)
(let loop ((line l)
(skip-space #t))
(let ((c (get-char line direction)))
(cond
((null? c) line)
((char-letter? c) (loop (action line) #f))
((and (not (char-alphabetic? c)) skip-space)
(loop (action line) #t))
(else line)))))
(define (backward-word l . k)
(move-word l line:left backward-char))
(define (forward-word l . k)
(move-word l line:right forward-char))
(define (kill-word l . k)
(move-word l line:right delete-char))
(define (backward-kill-word l . k)
(move-word l line:left delete-backward-char))
(define (history-next-input l . k)
(let* ((h (line:history l))
(hist (get-line-history h 'next)))
(if (not (null? hist))
(replace-with-string l hist)
l)))
(define (history-prev-input l . k)
(let* ((h (line:history l))
(hist (get-line-history h 'previous)))
(if (not (null? hist))
(replace-with-string l hist)
l)))
(define (replace-with-string l s)
(clear-line l)
(display s)
(copy-line l (reverse (string->list s))))
(define (undo l . k)
(let* ((h (line:history l))
(edit (get-edit-history h 'previous)))
(if (not (null? edit))
(replace-with-line l edit)
l)))
(define (redo l . k)
(let* ((h (line:history l))
(edit (get-edit-history h 'next)))
(if (not (null? edit))
(replace-with-line l edit)
l)))
(define (replace-with-line l nl)
(clear-line l)
(display-line nl)
nl) | false |
fac62371be87d4f5303bc1ea50c508b3ba598e3a | 12fc725f8273ebfd9ece9ec19af748036823f495 | /tools/schemelib/common/util.ss | 2bbdb221238d57ef59817546ae2d5c7e4ace2e06 | []
| no_license | contextlogger/contextlogger2 | 538e80c120f206553c4c88c5fc51546ae848785e | 8af400c3da088f25fd1420dd63889aff5feb1102 | refs/heads/master | 2020-05-05T05:03:47.896638 | 2011-10-05T23:50:14 | 2011-10-05T23:50:14 | 1,675,623 | 1 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 3,742 | ss | util.ss | #lang scheme
(require (except-in (lib "util.scm" "wg")
identity nor nand true? false?
any-pred every-pred
puts string-join
case-eq inspect flatten
write-nl display-nl))
(provide (all-from-out (lib "util.scm" "wg")))
(require (lib "module-util.scm" "wg"))
(require "module.ss")
(require* "pred.ss")
(define* puts
(case-lambda
((val) (begin
(display val)
(newline)))
((val out) (begin
(display val out)
(newline out)))))
(define* write-nl
(case-lambda
((datum) (begin (write datum) (newline)))
((datum out) (begin (write datum out) (newline out)))))
(define* display-nl
(case-lambda
((datum) (begin (display datum) (newline)))
((datum out) (begin (display datum out) (newline out)))))
;; Now in "scheme" language.
;; (define-syntax* thunk
;; (syntax-rules ()
;; ((_ body ...)
;; (lambda () body ...))))
(define* (constant x)
(thunk x))
;; Apparently this is defined in recent versions of PLT Scheme,
;; with exactly the same name as we came up with for it.
;;(define* (hash-has-key? hash key)
;; (and (hash-ref hash key #f) #t))
;; For whatever reason this macro no longer works when defined in the
;; "mzscheme" language, so we export a copy that is defined in
;; "scheme" language.
(define-syntax* case-eq
(syntax-rules (else)
((_ e (a b) ... (else c))
(cond ((eq? e a) b) ... (else c)))
((_ e (a b) ...)
(cond ((eq? e a) b) ...))))
;; "case" appears to be broken in some versions of PLT Scheme, so we
;; are defining this one to avoid problems. Surely "cond" at least
;; must work. Here we use equal? instead of eqv?.
(define-syntax* case-equal
(syntax-rules (else)
((_ e (a b) ... (else c))
(cond ((equal? e a) b) ... (else c)))
((_ e (a b) ...)
(cond ((equal? e a) b) ...))))
;; Note that action and cleanup are expressions, not thunks. Note also
;; that as we are doing functional programming, it is important to
;; preserve the result of "action" in the event there is no exception.
(define-syntax* try-finally
(syntax-rules ()
((_ action cleanup)
(let ((res #f))
(with-handlers
((void (lambda (exn) cleanup (raise exn))))
(set! res action))
cleanup
res))))
(define* (path-dirname path)
(let-values (((base name must-be-dir) (split-path path)))
(unless (path? base)
(error "cannot get directory component from pathname" path))
base))
#|
Copyright 2009 Helsinki Institute for Information Technology (HIIT)
and the authors. All rights reserved.
Authors: Tero Hasu <[email protected]>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
|#
| true |
38886fa017f321dcbcc6c03625ac796cbe9975f8 | ebf028b3a35ae1544bba1a1f9aa635135486ee6c | /tests/lunula/hmac.scm | a093df22ce69e34944348f06ccaecc72cd874628 | [
"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 | 984 | scm | hmac.scm | #!/usr/bin/env ypsilon
#!r6rs
(import (rnrs)
(only (core) format)
(ypsilon gcrypt)
(lunula hmac)
(xunit))
(gcry_check_version "1.4.5") ; you might modify the version
(gcry_control GCRYCTL_DISABLE_SECMEM)
(gcry_control GCRYCTL_INITIALIZATION_FINISHED)
(define *key* "1234567890")
(define *string*
(format (string-append
"GET~%webservices.amazon.com~%/onca/xml~%AWSAccessKeyId=~a&"
"ItemId=~a&"
"Operation=~a&"
"ResponseGroup=~a&"
"Service=~a&"
"Timestamp=~a&"
"Version=~a")
"00000000000000000000"
"0679722769"
"ItemLookup"
"ItemAttributes%2COffers%2CImages%2CReviews"
"AWSECommerceService"
"2009-01-01T12%3A00%3A00Z"
"2009-01-06"))
(define *data* (string->utf8 *string*))
(define *expected* "Nace+U3Az4OhN7tISqgs1vdLBHBEijWcBeCqL5xN9xg=")
(assert-string=? *expected* (sha-256 *key* *data*))
(report)
| false |
1b84dc73a2080852dc4375c6ad1be7e5c83bd0e6 | c146bf025d0d330185badb8ef0de0fe0c56267f3 | /cKanren/comptests.scm | f036ced085afffaf8e7756d4ab1bb12ca5a85b9e | [
"MIT"
]
| permissive | webyrd/peano-challenge | ea6a35cd8859026327d83f4ee0af6264bf27019b | 5fe83bd2e5e9a8fe0ea2e079af82f6b3fe34e5c8 | refs/heads/master | 2020-04-04T09:38:06.082340 | 2014-01-05T06:25:29 | 2014-01-05T06:25:29 | 15,646,599 | 3 | 1 | null | null | null | null | UTF-8 | Scheme | false | false | 1,777 | scm | comptests.scm | (library (cKanren comptests)
(export run-comptests)
(import
(rnrs)
(cKanren ck)
(cKanren neq)
(cKanren fd)
(cKanren tester)
(cKanren tree-unify))
(define n-queenso
(lambda (q n)
(let loop ((i n) (l '()))
(cond
((zero? i)
(fresh ()
(== q l)
(distinctfd l)
(diagonalso n l)))
(else
(fresh (x)
(infd x (range 1 n))
(loop (- i 1) (cons x l))))))))
(define diagonalso
(lambda (n l)
(let loop ((r l) (s (cdr l)) (i 0) (j 1))
(cond
((or (null? r) (null? (cdr r))) succeed)
((null? s) (loop (cdr r) (cddr r) (+ i 1) (+ i 2)))
(else
(let ((qi (car r)) (qj (car s)))
(fresh ()
(diago qi qj (- j i) (range 0 (* 2 n)))
(loop r (cdr s) i (+ j 1)))))))))
(define diago
(lambda (qi qj d rng)
(fresh (si sj)
(infd si sj rng)
(=/=fd qi sj)
(plusfd qi d si)
(=/=fd qj si)
(plusfd qj d sj))))
(define distincto
(lambda (l)
(conde
((== l '()))
((fresh (a) (== l `(,a))))
((fresh (a ad dd)
(== l `(,a ,ad . ,dd))
(=/= a ad)
(distincto `(,a . ,dd))
(distincto `(,ad . ,dd)))))))
(define (run-comptests)
(test-check "Distinct Queens 1"
(run* (q)
(fresh (x)
(n-queenso x 8)
(distincto x)))
'(_.0))
(test-check "Distinct Queens 2"
(let ((answers (run* (q) (n-queenso q 4))))
(run* (q) (distincto answers)))
'(_.0))
(test-check "infd/Distinct 1"
(run* (q) (infd q '(2 3 4)) (distincto `(a 3 ,q)))
'(2 4)))
)
| false |
90cacdf3cc0bb4c79fa626c046861be3c16b9e9a | 784dc416df1855cfc41e9efb69637c19a08dca68 | /src/std/actor.ss | fffbf20bf7989a7c09b4b5bb7a19bc5ddb5f2faf | [
"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 | 280 | ss | actor.ss | ;;; -*- Gerbil -*-
;;; (C) vyzo
;;; std actor interface: messages, protocols and rpc
package: std
(import :std/actor/message
:std/actor/proto
:std/actor/rpc)
(export (import: :std/actor/message
:std/actor/proto
:std/actor/rpc))
| false |
6357109d1c321fd1bf414ea421b7ce705bceb30b | 26aaec3506b19559a353c3d316eb68f32f29458e | /modules/xml/xml.scm | 78c8018a80733e2202519848ece415a696c33b51 | [
"BSD-3-Clause"
]
| permissive | mdtsandman/lambdanative | f5dc42372bc8a37e4229556b55c9b605287270cd | 584739cb50e7f1c944cb5253966c6d02cd718736 | refs/heads/master | 2022-12-18T06:24:29.877728 | 2020-09-20T18:47:22 | 2020-09-20T18:47:22 | 295,607,831 | 1 | 0 | NOASSERTION | 2020-09-15T03:48:04 | 2020-09-15T03:48:03 | null | UTF-8 | Scheme | false | false | 4,708 | scm | xml.scm | #|
LambdaNative - a cross-platform Scheme framework
Copyright (c) 2009-2015, University of British Columbia
All rights reserved.
Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
* Neither the name of the University of British Columbia nor
the names of its contributors may be used to endorse or
promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|#
;; minimal interface to libxml2
(##namespace ("xml#"))
(##include "~~lib/gambit#.scm")
(##include "xml#.scm")
(##namespace ("" string->u8vector))
(c-declare #<<c-declare-end
#include <stdio.h>
#include <libxml/tree.h>
#include <libxml/parser.h>
c-declare-end
)
(c-define-type xmlDoc (pointer "xmlDoc"))
(c-define-type xmlNode (pointer "xmlNode"))
(c-define-type xmlAttribute (pointer "xmlAttribute"))
(define xmlParseFile (c-lambda (char-string) xmlDoc "xmlParseFile"))
(define (xmlParseMemory u8v) ((c-lambda (scheme-object int) xmlDoc
"___result=xmlParseMemory(___CAST(void*,___BODY_AS(___arg1,___tSUBTYPED)),___arg2);")
u8v (u8vector-length u8v)))
(define xmlDocGetRootElement (c-lambda (xmlDoc) xmlNode "xmlDocGetRootElement"))
(define xmlNodeListGetString (c-lambda (xmlDoc xmlNode int) char-string "xmlNodeListGetString"))
(define xmlFreeDoc (c-lambda (xmlDoc) void "xmlFreeDoc"))
(define-macro (xml name entry type)
`(define ,(string->symbol (string-append "xml" (symbol->string name) "->" (symbol->string entry)))
(c-lambda (,(string->symbol (string-append "xml" (symbol->string name)))) ,type
,(string-append "___result=___arg1->" (symbol->string entry) ";"))))
(xml Node children xmlNode)
(xml Node next xmlNode)
(xml Node name char-string)
(xml Node content char-string)
(xml Node properties xmlAttribute)
(xml Node type int)
(xml Node doc xmlDoc)
(xml Attribute name char-string)
(xml Attribute children xmlNode)
(xml Attribute next xmlAttribute)
(define XML_ELEMENT_NODE ((c-lambda () int "___result=XML_ELEMENT_NODE;")))
(define XML_TEXT_NODE ((c-lambda () int "___result=XML_TEXT_NODE;")))
(define (xml-element? n) (fx= (xmlNode->type n) XML_ELEMENT_NODE))
(define (xml-text? n) (fx= (xmlNode->type n) XML_TEXT_NODE))
;; decode the xml data structure
(define (node-attrs n)
(let loop ((a (xmlNode->properties n))(res '(@)))
(if (not a) res
(loop (xmlAttribute->next a) (append res (list (list
(string->symbol (xmlAttribute->name a)) (xmlNodeListGetString (xmlNode->doc n) (xmlAttribute->children a) 1))))))))
(define (node-list _n)
(let loop ((n _n)(res '()))
(if (not n) res
(loop (xmlNode->next n) (append res
(if (xml-element? n) (list n)
(if (xml-text? n) (list (xmlNode->content n)) '())))))))
(define (sxml name attrs children)
(append (list (string->symbol name)) (if (= (length attrs) 1) '() (list attrs)) children))
(define (node->sxml n)
(map (lambda (n)
(if (string? n) n
(sxml (xmlNode->name n)
(node-attrs n)
(node->sxml (xmlNode->children n)))))
(node-list n)))
(define (xmlfile->sxml fname)
(if (file-exists? fname)
(let* ((d (xmlParseFile fname))
(r (if d (xmlDocGetRootElement d) #f))
(res (if r (car (node->sxml r)) #f)))
(if d (xmlFreeDoc d))
res
) #f))
(define (xml->sxml data)
(let* ((u8v (if (string? data) (string->u8vector data) data))
(d (xmlParseMemory u8v))
(r (if d (xmlDocGetRootElement d) #f))
(res (if r (car (node->sxml r)) #f)))
(if d (xmlFreeDoc d))
res))
;; eof
| false |
a6f000addde24544760a4c0dc3fd77e56971d99a | 9e2d6956e6036b292339aeefb23297d6c99a1df3 | /stream.ss | e75fca3f6baf96cdcf1712e472ba333f67f8049d | []
| no_license | pijones/cs275_lab9 | efc23675281b2cf81330d987b750a3a908e2e1ea | 7809c1590c660a811ae3d2650d7cc6927bb3aec3 | refs/heads/master | 2021-01-16T00:56:47.124245 | 2013-05-01T20:01:34 | 2013-05-01T20:01:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 2,473 | ss | stream.ss | ;; stream operator definitions
;; using Dr. Scheme delay and force
(module stream mzscheme
(define car$
(lambda (s)
(if (promise? s) (car$ (force s)) (car s))))
(define cdr$
(lambda (s)
(if (promise? s) (cdr$ (force s)) (force (cdr s)))))
(define-syntax cons$
(syntax-rules ()
[(_ x y) (cons x (delay y))]))
;; other useful stream functions
; (nth$ n s) returns the nth cdr$ of s
(define nth$
(lambda (n s)
(if (zero? n) s
(nth$ (sub1 n) (cdr$ s)))))
(define show$
(lambda (n s)
(if (zero? n) s
(cons (car$ s) (show$ (sub1 n) (cdr$ s))))))
;; +$ forms the stream of element by element sums of the elements of its
; argument streams
(define +$
(lambda (s1 s2)
(cons$ (+ (car$ s1) (car$ s2))
(+$ (cdr$ s1) (cdr$ s2)))))
;; append$, etc. are lazy-list versions of the usual functions
(define append$
(lambda (x y)
(if (null? x) y
(cons$ (car$ x) (append$ (cdr$ x) y)))))
(define map$
(lambda (f s)
(cons$ (f (car$ s)) (map$ f (cdr$ s)))))
(define filter$
(lambda (f l)
(let filter1$ ([l l])
(cond [(null? l) ()]
[(f (car$ l)) (cons$ (car$ l) (filter1$ (cdr$ l)))]
[else (filter1$ (cdr$ l))]))))
(define fold$
(lambda (recur-case base-case base-test lyst)
(let help-fold ([l lyst])
(if (base-test l)
base-case
(recur-case (car$ l) (help-fold (cdr$ l)))))))
; print the first n members of stream s:
(define printn$
(lambda (s n)
(if (= 0 n)
'done
(begin
(printf "~s~%" (car$ s))
(printn$ (cdr$ s) (- n 1))))))
; print the stream s, pausing after each 10 to ask the user if the
; printing should continue:
(define print$
(lambda (s)
(letrec ([printn
(lambda (s n)
(if (= 0 n)
s
(begin
(printf "~s " (car$ s))
(printn (cdr$ s) (- n 1)))))]
[printrow
(lambda (s)
(printf "~%Want more? ")
(if (eq? (read) 'y)
(printrow (printn s 10))
'done))])
(printrow (printn s 10)))))
(provide cons$ car$ cdr$ nth$ show$ +$ append$ map$ filter$ fold$ printn$ print$)
)
| true |
ae9da44ad568c1b718c89fae0e80dde3ac7b7d4c | b60cb8e39ec090137bef8c31ec9958a8b1c3e8a6 | /test/R5RS/letrec-begin.scm | 1472b41a2a68f67789a8552665e180c0477caaa1 | []
| no_license | acieroid/scala-am | eff387480d3baaa2f3238a378a6b330212a81042 | 13ef3befbfc664b77f31f56847c30d60f4ee7dfe | refs/heads/master | 2021-01-17T02:21:41.692568 | 2021-01-15T07:51:20 | 2021-01-15T07:51:20 | 28,140,080 | 32 | 16 | null | 2020-04-14T08:53:20 | 2014-12-17T14:14:02 | Scheme | UTF-8 | Scheme | false | false | 125 | scm | letrec-begin.scm | (letrec ((h (lambda ()
'()))
(i 1)
(res (begin
(h)
i)))
res)
| false |
43de62de5c1f82d08ac0f1ac3b681ae21ff10e33 | a8216d80b80e4cb429086f0f9ac62f91e09498d3 | /lib/chibi/binary-types.scm | 69a55e413b7f3215412afd7fc1de42ab6a31ae1b | [
"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 | 5,656 | scm | binary-types.scm |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; utilities
(define (read-u16/be in)
(let* ((i (read-u8 in))
(j (read-u8 in)))
(if (eof-object? j)
(error "end of input")
(+ (arithmetic-shift i 8) j))))
(define (read-u16/le in)
(let* ((i (read-u8 in))
(j (read-u8 in)))
(if (eof-object? j)
(error "end of input")
(+ (arithmetic-shift j 8) i))))
(define (assert-read-u8 in i)
(let ((i2 (read-u8 in)))
(if (not (eqv? i i2))
(error "unmatched value, expected: " i " but got: " i2)
i2)))
(define (assert-read-char in ch)
(let ((ch2 (read-char in)))
(if (not (eqv? ch ch2))
(error "unmatched value, expected: " ch " but got: " ch2)
ch2)))
(define (assert-read-string in s)
(let ((s2 (read-string (string-length s) in)))
(if (not (equal? s s2))
(error "unmatched value, expected: " s " but got: " s2)
s2)))
(define (assert-read-bytevector in bv)
(let ((bv2 (read-bytevector (bytevector-length bv) in)))
(if (not (equal? bv bv2))
(error "unmatched value, expected: " bv " but got: " bv2)
bv2)))
(define (assert-read-integer in len radix)
(let* ((s (string-trim-both (read-string len in)
(lambda (ch) (or (eqv? ch #\space) (eqv? ch #\null)))))
(n (if (equal? s "") 0 (string->number s radix))))
(or n (error "invalid number syntax: " s))))
(define (read-padded-string in len pad)
(string-trim-right (read-string len in) pad))
(define (read-literal val)
(cond
((integer? val) (lambda (in) (assert-read-u8 in val)))
((char? val) (lambda (in) (assert-read-char in val)))
((string? val) (lambda (in) (assert-read-string in val)))
((bytevector? val) (lambda (in) (assert-read-bytevector in val)))
(else (error "unknown binary literal: " val))))
(define (write-literal val)
(cond
((integer? val) (lambda (x out) (write-u8 val out)))
((char? val) (lambda (x out) (write-char val out)))
((string? val) (lambda (x out) (write-string val out)))
((bytevector? val) (lambda (x out) (write-bytevector val out)))
(else (error "unknown binary literal: " val))))
(define (write-padded-integer out n radix len left-pad-ch right-pad-ch)
(let ((s (string-pad (number->string n radix) (- len 1) left-pad-ch)))
(cond
((>= (string-length s) len)
(error "number too large for width" n radix len))
(else
(write-string s out)
(write-char right-pad-ch out)))))
(define (write-u16/be n out)
(write-u8 (arithmetic-shift n -8) out)
(write-u8 (bitwise-and n #xFF) out))
(define (write-u16/le n out)
(write-u8 (bitwise-and n #xFF) out)
(write-u8 (arithmetic-shift n -8) out))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; syntax
(define-syntax define-auxiliary-syntax
(syntax-rules ()
((define-auxiliary-syntax name)
(define-syntax name
(syntax-rules ()
((name . x)
(syntax-error "invalid use of auxiliary syntax" (name . x))))))))
(define-auxiliary-syntax make:)
(define-auxiliary-syntax pred:)
(define-auxiliary-syntax read:)
(define-auxiliary-syntax write:)
(define-auxiliary-syntax block:)
(define-syntax syntax-let-optionals*
(syntax-rules ()
((syntax-let-optionals* () type-args expr)
expr)
((syntax-let-optionals* ((param default) . rest) (arg0 . args) expr)
(let ((param arg0))
(syntax-let-optionals* rest args expr)))
((syntax-let-optionals* ((param default) . rest) () expr)
(let ((param default))
(syntax-let-optionals* rest () expr)))
((syntax-let-optionals* (param . rest) (arg0 . args) expr)
(let ((param arg0))
(syntax-let-optionals* rest args expr)))
((syntax-let-optionals* (param . rest) () expr)
(syntax-error "missing required parameter" param expr))))
(define-syntax define-binary-type
(syntax-rules ()
((define-binary-type (name params ...) gen-pred gen-read gen-write)
(define-syntax name
(syntax-rules (pred: read: write:)
((name pred: type-args)
(syntax-let-optionals* (params ...) type-args gen-pred))
((name read: type-args)
(syntax-let-optionals* (params ...) type-args gen-read))
((name write: type-args)
(syntax-let-optionals* (params ...) type-args gen-write)))))))
(define-binary-type (u8)
(lambda (x) (and (exact-integer? x) (<= 0 x 255)))
read-u8
write-u8)
(define-binary-type (u16/le)
(lambda (x) (and (exact-integer? x) (<= 0 x 65536)))
read-u16/le
write-u16/le)
(define-binary-type (u16/be)
(lambda (x) (and (exact-integer? x) (<= 0 x 65536)))
read-u16/be
write-u16/be)
(define-binary-type (padded-string len (pad #\null))
(lambda (x) (and (string? x) (<= (string-length x) len)))
(lambda (in) (read-padded-string in len pad))
(lambda (str out)
(write-string (string-pad-right str len pad) out)))
(define-binary-type (fixed-string len)
(lambda (x) (and (string? x) (= (string-length x) len)))
(lambda (in)
(read-string len in))
(lambda (str out)
(write-string str out)))
(define-binary-type (octal len)
exact-integer?
(lambda (in) (assert-read-integer in len 8))
(lambda (n out)
(write-padded-integer out n 8 len #\0 #\null)))
(define-binary-type (decimal len)
exact-integer?
(lambda (in) (assert-read-integer in len 10))
(lambda (n out)
(write-padded-integer out n 10 len #\0 #\null)))
(define-binary-type (hexadecimal len)
exact-integer?
(lambda (in) (assert-read-integer in len 16))
(lambda (n out)
(write-padded-integer out n 16 len #\0 #\null)))
| true |
73c2b911b2b7d0026d83502546e6d223f275114c | 4a3d36180ad5e7e8223cd8c60ef7103e81ca5b85 | /PPL_Polimi/exams/20170720/exercise_1.scm | ee0326d2c5d45a7f830a24b60d386122a4224ab1 | [
"MIT"
]
| permissive | leonardoarcari/haskell_playground | 56404e997008a2abe07d59bd78f2081c7bd5291c | 19f812d8ffd14dcdc89cd1f55eb9913f76d1fccc | refs/heads/master | 2021-09-04T04:20:35.456422 | 2018-01-15T18:38:00 | 2018-01-15T18:38:00 | 113,197,657 | 1 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 319 | scm | exercise_1.scm | #lang racket
(define (print+sub x y)
(display x)
(display " ")
(display y)
(display " -> ")
(- x y))
(define (puzzle)
(call/cc (lambda (exit)
(define (local e)
(call/cc
(lambda (local-exit)
(exit (print+sub e
(call/cc
(lambda (new-exit)
(set! exit new-exit)
(local-exit #f))))))))
(local 6)
(exit 2)))) | false |
9ae44c95e63faa3c558e8095ca30640dcebac465 | 4fd95c081ccef6afc8845c94fedbe19699b115b6 | /chapter_3/3.49.scm | c04f8983f7e6f294b3d4fdb323fac64bad799123 | [
"MIT"
]
| permissive | ceoro9/sicp | 61ff130e655e705bafb39b4d336057bd3996195d | 7c0000f4ec4adc713f399dc12a0596c770bd2783 | refs/heads/master | 2020-05-03T09:41:04.531521 | 2019-08-08T12:14:35 | 2019-08-08T12:14:35 | 178,560,765 | 1 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 775 | scm | 3.49.scm | ; When the process does not know which locks it needs to acquire,
; before accessing to some shared resource(acquiring another lock).
; So it can be a situation when process #1 acquired a lock A, then
; it finds out all the locks to acquire during operation: B, C, D.
; But there is an another concurrent process #2, which rigth after process #1
; acquired lock A, acquires lock B and finds out all locks to acquire during
; operation: A, E. So when execution of process #1 is resumed, it cannot acquire
; lock B, since if was already acquired by process #2 and process #2 cannot proceed,
; since lock A is acquired by process #1. So the main problem here, that we need to
; guarantee that lock on shared resource is not going to be in results, which this
; resource holds.
| false |
6ec27ec52e5526798022e863da889009d6dab222 | 069111ccfe6585670fb7bc2047ff968c3d1ba86f | /sample/currentfolder.scm | 556a3dda893e3d075f5a8231873f616d774e98f5 | [
"MIT"
]
| permissive | SaitoAtsushi/Gauche-OLE | 431eb9c2116592f2ccf1e71dbf09ffe10b45028b | 10ad8c54faaa7c0368eb0295cd99de3e0ebc7a8e | refs/heads/master | 2020-05-19T10:26:46.881876 | 2019-05-05T03:10:12 | 2019-05-05T03:10:12 | 184,971,684 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 305 | scm | currentfolder.scm | #!/usr/bin/env gosh
(use win.ole)
(use gauche.collection)
(define (ShowFolderFileList folderspec)
(let* ((fso (make-ole "Scripting.FileSystemObject"))
(f (fso 'GetFolder folderspec)))
(for-each (^x (print (~ x 'Name))) (~ f 'files))))
(ShowFolderFileList ".")
(ole-release!)
| false |
630034746a77d1bcdde3178893d3f62b4c776ae6 | 2b0a8566daf71015a61920f9175e65f66cf42c50 | /src/kawa/robots/ui.scm | 35644e1bfd0c40a8477c3115b33a89ea4f550e60 | []
| no_license | bitsai/robots | be5e7c428b519d2a796905eb6bd74969626751fb | 6eb9982c111bd50ef80b660c080577809b1dd0f9 | refs/heads/master | 2021-01-10T21:16:42.190894 | 2011-12-03T19:01:13 | 2011-12-03T19:01:13 | 1,904,417 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 488 | scm | ui.scm | (require 'android-defs)
(require "robots.scm")
(define *text-view* ::android.widget.TextView #!null)
(activity
ui
(on-create
((this):setContentView kawa.robots.R$layout:main)
(set! *text-view* ((this):findViewById kawa.robots.R$id:text_view))
(new-game))
((onClick v ::android.view.View)
(process-input (as android.widget.Button v):text)))
(define (append-output s)
(*text-view*:append s))
(define (set-output s)
(*text-view*:setText (as String s)))
| false |
f1710effa45843934dc42f10e302b24257780906 | defeada37d39bca09ef76f66f38683754c0a6aa0 | /mscorlib/system/reflection/mono-property.sls | a69b943643f9963a0c7d6cf67b098ab82b28e496 | []
| 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 | 3,933 | sls | mono-property.sls | (library (system reflection mono-property)
(export new
is?
mono-property?
get-optional-custom-modifiers
get-required-custom-modifiers
get-object-data
get-accessors
is-defined?
get-custom-attributes
set-value
get-value
get-get-method
get-index-parameters
get-set-method
to-string
attributes
can-read?
can-write?
property-type
reflected-type
declaring-type
name)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...) #'(clr-new System.Reflection.MonoProperty a ...)))))
(define (is? a) (clr-is System.Reflection.MonoProperty a))
(define (mono-property? a) (clr-is System.Reflection.MonoProperty a))
(define-method-port
get-optional-custom-modifiers
System.Reflection.MonoProperty
GetOptionalCustomModifiers
(System.Type[]))
(define-method-port
get-required-custom-modifiers
System.Reflection.MonoProperty
GetRequiredCustomModifiers
(System.Type[]))
(define-method-port
get-object-data
System.Reflection.MonoProperty
GetObjectData
(System.Void
System.Runtime.Serialization.SerializationInfo
System.Runtime.Serialization.StreamingContext))
(define-method-port
get-accessors
System.Reflection.MonoProperty
GetAccessors
(System.Reflection.MethodInfo[] System.Boolean))
(define-method-port
is-defined?
System.Reflection.MonoProperty
IsDefined
(System.Boolean System.Type System.Boolean))
(define-method-port
get-custom-attributes
System.Reflection.MonoProperty
GetCustomAttributes
(System.Object[] System.Type System.Boolean)
(System.Object[] System.Boolean))
(define-method-port
set-value
System.Reflection.MonoProperty
SetValue
(System.Void
System.Object
System.Object
System.Reflection.BindingFlags
System.Reflection.Binder
System.Object[]
System.Globalization.CultureInfo))
(define-method-port
get-value
System.Reflection.MonoProperty
GetValue
(System.Object
System.Object
System.Reflection.BindingFlags
System.Reflection.Binder
System.Object[]
System.Globalization.CultureInfo)
(System.Object System.Object System.Object[]))
(define-method-port
get-get-method
System.Reflection.MonoProperty
GetGetMethod
(System.Reflection.MethodInfo System.Boolean))
(define-method-port
get-index-parameters
System.Reflection.MonoProperty
GetIndexParameters
(System.Reflection.ParameterInfo[]))
(define-method-port
get-set-method
System.Reflection.MonoProperty
GetSetMethod
(System.Reflection.MethodInfo System.Boolean))
(define-method-port
to-string
System.Reflection.MonoProperty
ToString
(System.String))
(define-field-port
attributes
#f
#f
(property:)
System.Reflection.MonoProperty
Attributes
System.Reflection.PropertyAttributes)
(define-field-port
can-read?
#f
#f
(property:)
System.Reflection.MonoProperty
CanRead
System.Boolean)
(define-field-port
can-write?
#f
#f
(property:)
System.Reflection.MonoProperty
CanWrite
System.Boolean)
(define-field-port
property-type
#f
#f
(property:)
System.Reflection.MonoProperty
PropertyType
System.Type)
(define-field-port
reflected-type
#f
#f
(property:)
System.Reflection.MonoProperty
ReflectedType
System.Type)
(define-field-port
declaring-type
#f
#f
(property:)
System.Reflection.MonoProperty
DeclaringType
System.Type)
(define-field-port
name
#f
#f
(property:)
System.Reflection.MonoProperty
Name
System.String))
| true |
d60a62f34a14548030ca436ae6d3aa8df7b89ab3 | defeada37d39bca09ef76f66f38683754c0a6aa0 | /mscorlib/system/runtime/compiler-services/unsafe-value-type-attribute.sls | 6a9f9b1f74c6a0942b1744a6e634b720aa14bc53 | []
| 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 | 580 | sls | unsafe-value-type-attribute.sls | (library (system runtime compiler-services unsafe-value-type-attribute)
(export new is? unsafe-value-type-attribute?)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new
System.Runtime.CompilerServices.UnsafeValueTypeAttribute
a
...)))))
(define (is? a)
(clr-is System.Runtime.CompilerServices.UnsafeValueTypeAttribute a))
(define (unsafe-value-type-attribute? a)
(clr-is
System.Runtime.CompilerServices.UnsafeValueTypeAttribute
a)))
| true |
f6d208bc539d58e5f6ae52b3e12d817f9c9e5277 | d11ad5e19d63d2cf6ca69f12ecae02a9b9871ad3 | /haskell/Reader.ss | e6fb9d1aa70f5c491473f3df83508eca107bb64f | [
"Apache-2.0"
]
| permissive | willfaught/sham1 | 3e708368a02ce8af204dbf26cc94f01e75ea39a8 | 371e9a6fd810628f8e9a79868b9f457bfcf8dc29 | refs/heads/master | 2022-08-28T20:46:09.904927 | 2022-08-18T22:04:51 | 2022-08-18T22:04:51 | 151,862 | 1 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 826 | ss | Reader.ss | (module Reader scheme
(require (lib "Compilation.ss" "sham" "haskell")
(lib "List.ss" "sham" "haskell")
(lib "Maybe.ss" "sham" "haskell")
(lib "Parsing.ss" "sham" "haskell")
(lib "Transformation.ss" "sham" "haskell")
(lib "TypeChecking.ss" "sham" "haskell"))
(provide (rename-out (readHaskellSyntax read-syntax)))
(define (readHaskellSyntax inputName inputPort)
(port-count-lines! inputPort)
(let* ((parser (Just-value (lookup 'module (parsers inputName))))
(haskellSyntax (parser (lambda () (languageLexer inputPort))))
(coreSyntax (transformSyntax haskellSyntax))
(types (moduleTypes coreSyntax))
(emit (compileModule coreSyntax types)))
;(pretty-print types)
(pretty-print emit)
emit))) | false |
3636e19dbae4fdadbb880e8b86b9c5b70ade609c | 5927f3720f733d01d4b339b17945485bd3b08910 | /hato-httpd.scm | 360f799b0f83e712a8d135e38af5629f4a60c95a | []
| no_license | ashinn/hato | 85e75c3b6c7ca7abca512dc9707da6db3b50a30d | 17a7451743c46f29144ce7c43449eef070655073 | refs/heads/master | 2016-09-03T06:46:08.921164 | 2013-04-07T03:22:52 | 2013-04-07T03:22:52 | 32,322,276 | 5 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 17,477 | scm | hato-httpd.scm | ;; hato-httpd.scm -- a web server
;;
;; Copyright (c) 2009 Alex Shinn. All rights reserved.
;; BSD-style license: http://synthcode.com/license.txt
(require-library
srfi-1 srfi-13 srfi-69 tcp lolevel matchable sendfile let-args
hato-config hato-uri hato-utils hato-log hato-daemon hato-mime hato-http)
(module hato-httpd (main)
(import scheme chicken extras ports regex posix files data-structures)
(import srfi-1 srfi-13 srfi-69 tcp lolevel matchable sendfile let-args)
(import hato-config hato-uri hato-utils hato-log hato-daemon hato-mime)
(import hato-http)
(define-logger (current-log-level set-current-log-level! info)
(log-emergency log-alert log-critical log-error
log-warn log-notice log-info log-debug))
(define *program-name* "hato-httpd")
(define-syntax read-version
(er-macro-transformer
(lambda (e r c) (call-with-input-file "VERSION" read-line))))
(define *program-version* (read-version))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; This looks big and hairy, but it's mutation-free and guarantees:
;; (string=? s (path-normalize s)) <=> (eq? s (path-normalize s))
;; i.e. fast and simple for already normalized paths.
(define (path-normalize path)
(let* ((len (string-length path)) (len-1 (- len 1)))
(define (collect i j res)
(if (>= i j) res (cons (substring path i j) res)))
(define (finish i res)
(if (zero? i)
path
(apply string-append (reverse (collect i len res)))))
;; loop invariants:
;; - res is a list such that (string-concatenate-reverse res)
;; is always the normalized string up to j
;; - the tail of the string from j onward can be concatenated to
;; the above value to get a partially normalized path referring
;; to the same location as the original path
(define (inside i j res)
(if (>= j len)
(finish i res)
(if (eqv? #\/ (string-ref path j))
(boundary i (+ j 1) res)
(inside i (+ j 1) res))))
(define (boundary i j res)
(if (>= j len-1)
(finish i res)
(case (string-ref path j)
((#\.)
(case (string-ref path (+ j 1))
((#\.)
(if (or (>= j (- len 2)) (eqv? #\/ (string-ref path (+ j 2))))
(if (>= i (- j 1))
(if (null? res)
(backup j "" '())
(backup j (car res) (cdr res)))
(backup j (substring path i j) res))
(inside i (+ j 2) res)))
((#\/)
(if (= i j)
(boundary (+ j 2) (+ j 2) res)
(let ((s (substring path i j)))
(boundary (+ j 2) (+ j 2) (cons s res)))))
(else (inside i (+ j 1) res))))
((#\/) (boundary (+ j 1) (+ j 1) (collect i j res)))
(else (inside i (+ j 1) res)))))
(define (backup j s res)
(let ((pos (+ j 3)))
(cond
;; case 1: we're reduced to accumulating parents of the cwd
((or (string=? s "/..") (string=? s ".."))
(boundary pos pos (cons "/.." (cons s res))))
;; case 2: the string isn't a component itself, skip it
((or (string=? s "") (string=? s ".") (string=? s "/"))
(if (pair? res)
(backup j (car res) (cdr res))
(boundary pos pos (if (string=? s "/") '("/") '("..")))))
;; case3: just take the directory of the string
(else
(let ((d (pathname-directory s)))
(cond
((string=? d "/")
(boundary pos pos (if (null? res) '("/") res)))
((string=? d ".")
(boundary pos pos res))
(else (boundary pos pos (cons "/" (cons d res))))))))))
;; start with boundary if abs path, otherwise inside
(if (zero? len)
path
((if (eqv? #\/ (string-ref path 0)) boundary inside) 0 1 '()))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (http-respond status msg . headers)
(printf "HTTP/1.1 ~S ~A\r\n" status msg)
(if (pair? headers)
(for-each
(lambda (h)
(display (car h)) (display ": ") (display (cdr h)) (display "\r\n"))
(car headers)))
(display "\r\n"))
(define http-mime-type
(let ((types (make-hash-table eq?)))
(condition-case
(call-with-input-file (if (file-exists? "/etc/mime.types")
"/etc/mime.types"
"/etc/httpd/mime.types")
(lambda (in)
(let lp ()
(let ((line (read-line in)))
(cond
((not (eof-object? line))
(let ((ls (string-split
(cond ((string-index line #\#)
=> (lambda (i) (substring line 0 i)))
(else line)))))
(if (and (pair? ls) (pair? (cdr ls)))
(for-each
(lambda (x)
(hash-table-set! types (string->symbol x) (car ls)))
(cdr ls)))
(lp))))))))
(exn () #f))
(lambda (file)
(let* ((ext (pathname-extension file))
(mtype (or (and ext (hash-table-ref/default
types
(string->symbol (string-downcase ext))
#f))
"application/octet-stream")))
(if (equal? mtype "text/html")
(string-append mtype "; charset=UTF-8")
mtype)))))
(define (http-base-headers config)
`((Server . ,*program-name*)
(Connection . close)
(Date . ,(seconds->string (current-seconds)))))
(define (http-file-headers file config)
(append (http-base-headers config)
`((Content-Length . ,(file-size file))
(Content-Type . ,(http-mime-type file)))))
(define (http-send-file file request headers config)
(let ((fd (condition-case (file-open file open/rdonly) (exn () #f))))
(cond
(fd
(http-respond 200 "OK" (http-file-headers file config))
(condition-case (sendfile fd (current-output-port)) (exn () #f))
(file-close fd))
(else ;; don't provide any more info in this case
(http-respond 404 "File not found" '())))))
(define (http-document-root file uri headers config)
(or (conf-get config 'document-root)
(string-append (current-directory) "/www")))
(define (http-resolve-file file uri headers config)
(string-append
(http-document-root file uri headers config) "/"
(string-trim (path-normalize file)
(lambda (c) (if (eqv? c #\.) #t (eqv? c #\/))))))
(define (http-send-directory vdir uri headers config)
(cond
((find (lambda (f) (file-exists? (string-append vdir "/" f)))
(conf-get-list config 'index-files))
=> (lambda (f)
(let ((uri2 (uri-with-path uri (string-append (uri-path uri) "/" f))))
(http-handle-get uri2 headers config config))))
(else
(http-respond 200 "OK" (append (http-base-headers config)
'((Content-Type . "text/html"))))
(display "<html><body bgcolor=white><pre>\n")
(let ((dir (string-trim (pathname-directory (uri-path uri)) #\/)))
(for-each
(lambda (file) (print "<a href=\"" dir "/" file "\">" file "</a>"))
(directory vdir)))
(display "</pre></body></html>\n"))))
(define (char-uri? ch)
(<= 33 (char->integer ch) 126))
(define (string-match-substitute m subst str)
(let lp ((ls subst) (res '()))
(cond
((null? ls) (string-concatenate-reverse res))
((number? (car ls)) (lp (cdr ls) (cons (or (list-ref m (car ls)) "") res)))
(else (lp (cdr ls) (cons (car ls) res))))))
(define (http-handle-get uri headers config vconfig)
(let ((path (uri-path uri)))
(cond
;; 0) sanity checks
((> (string-length path) 4096)
(log-warn "long request: ~S" (substring path 0 4096))
(http-respond 414 "Request-URI Too Long" '()))
((not (string-every char-uri? path))
(log-warn "bad request: ~S" path)
(http-respond 400 "Bad Request" '()))
;; 1) dispatch on rewrite rules
((any (lambda (x) (cond ((string-match (car x) path)
=> (lambda (m) (list x m)))
(else #f)))
(conf-multi config 'rewrite))
=> (match-lambda
(((rx subst . flags) m)
(log-notice "redirecting: ~S ~S" path m)
(let ((new-path (string-match-substitute m subst path)))
(cond
((memq 'redirect flags)
(log-notice "redirecting => ~S" new-path)
(http-respond 302 "Moved Temporarily"
`((Location . ,new-path))))
(else
(log-notice "internal redirecting => ~S" new-path)
(http-handle-request (list 'GET new-path "HTTP/1.1")
headers ;; XXXX adjust host
config)))))
(rule
(log-error "bad rewrite rule: ~S => ~S" path rule)
(http-respond 500 "Internal System Error"))))
(else
;; 2) determine actual file in virtual directory
(let ((vfile (http-resolve-file path uri headers vconfig)))
(log-notice "GET ~S ~S" vfile headers)
(let ((vconfig (condition-case
(conf-load
(string-append (pathname-directory vfile)
"/.config")
config)
(exn () vconfig))))
;; 3) verify permissions
(cond
(#f
(log-warn "no permissions")
(http-respond 401 "Unauthorized" '()))
;; 4) determine handler from vdir, extension
(else
(if (directory? vfile)
(http-send-directory vfile uri headers vconfig)
(case (conf-get (list (conf-multi vconfig 'handlers))
(string->symbol
(or (pathname-extension vfile) "xxx")))
((private)
(log-warn "trying to access private file: ~S" vfile)
(http-respond 404 "Not Found" '()))
((scheme)
(let ((handler (load-scheme-script vfile vconfig)))
(http-respond
200 "OK"
(append (http-base-headers config)
'((Content-Type . "text/html; charset=UTF-8"))))
(handler vfile uri headers vconfig)))
((cgi)
(system vfile))
(else ; static file
(http-send-file vfile uri headers vconfig))))))))))))
(define (http-handle-head uri headers config vconfig)
(http-handle-get uri headers config vconfig))
(define (http-handle-post uri headers config vconfig)
(http-handle-get uri headers config vconfig))
(define (black-listed? ipaddr config)
(assoc ipaddr (conf-multi config 'black-list)))
(define scheme-script-cache (make-hash-table))
(define hash-table-ref/cache!
(let ((miss (list 'miss)))
(lambda (tab key thunk)
(let ((x (hash-table-ref/default tab key miss)))
(if (eq? x miss)
(let ((res (thunk)))
(hash-table-set! tab key res)
res)
x)))))
(define (hash-table-ref/load! tab path proc)
(let* ((mtime (file-modification-time path))
(cell (hash-table-ref/cache!
tab
path
(lambda () (cons mtime (proc path))))))
(if (> mtime (car cell))
(let ((res (proc path)))
(hash-table-set! tab path (cons mtime res))
res)
(cdr cell))))
(define (%load-scheme-script path config)
(call-with-input-file path
(lambda (in)
(cond ((eqv? #\# (peek-char in))
(read-char in)
(if (eqv? #\! (peek-char in)) (read-line in))))
(let* ((modname (string-append "modscheme-" path))
(handler-name (string-append modname "#handle"))
(body `(module ,(string->symbol modname) (handle)
(import scheme chicken)
,@(read-file in))))
(eval body)
(eval (string->symbol handler-name))))))
(define (load-scheme-script path config)
(hash-table-ref/load!
scheme-script-cache
path
(lambda (path) (%load-scheme-script path config))))
(define (http-handle-request request headers config)
(let* ((uri (or (string->path-uri 'http (cadr request) #t #t)
(make-uri 'http #f #f #f)))
(host (cond ((or (and (uri? uri) (uri-host uri))
(mime-ref headers "Host"))
=> string-downcase->symbol)
(else #f)))
(uri (if (or (uri-host uri) (not host))
uri
(uri-with-host uri host)))
(vconfig (cond
((assq-ref (conf-multi config 'virtual-hosts) host)
=> (lambda (x) (conf-extend x config)))
(else config))))
(log-notice "request: ~S uri: ~S" request uri)
(case (car request)
((GET) (http-handle-get uri headers config vconfig))
((HEAD) (http-handle-head uri headers config vconfig))
((POST) (http-handle-post uri headers config vconfig))
(else
(log-error "unknown method: ~S" request)
(http-respond 400 "Bad Request" '())))))
(define (make-http-handler config)
(lambda ()
(receive (local remote) (tcp-addresses (current-input-port))
(cond
((black-listed? remote config)
(log-warn "black-listed: ~S" remote)
(http-respond 401 "Unauthorized" '()))
(else
(let* ((request (http-parse-request))
(headers (mime-headers->list (current-input-port) 128)))
(cond
((not (= 3 (length request)))
(log-error "bad request: ~S" request)
(http-respond 400 "Bad Request" '()))
(else
(http-handle-request request headers config)))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (show-help . o)
(display "usage: ") (display *program-name*) (display "[options ...]\n")
(display
"
-h, --help print this message
-V, --version print version number
-c, --config=<file> specify config file
--no-config don't load any config file
-r, --root=<dir> specify document root (default `pwd`/www)
-p, --port=<num> specify TCP port to listen on (default 5555)
-u, --user=<id> specify user to run as
-g, --group=<id> specify group to run as
-d, --debug debug run, don't detach
-k, --kill kill a running process
"))
(define (show-version . o)
(display *program-name*) (display " ")
(display *program-version*) (newline))
(define (main args)
(let-args args
((name "name=s" *program-name*)
(help "help|h" => show-help)
(version "version|V" => show-version)
(confdir "config-dir=s"
(or (get-environment-variable "HTTP_CONF_DIR")
(if (zero? (current-user-id))
(string-append "/etc/" name)
(string-append (get-environment-variable "HOME")
"/" name))))
(rcfile "config|c=s" (string-append confdir "/httpd.conf"))
(docroot "root|r=s")
(port "port|p=i")
(user "user|u=s")
(group "group|g=s")
(norc? "no-config")
(debug? "debug|d")
(kill? "kill|k")
(else (opt rest cont) (error "invalid option" opt)))
(let* ((config
(conf-extend
(filter
(lambda (x) (cadr x))
`((debug? ,debug?)
(user-id
,(and user (or (string->number user)
(cond ((user-information user) => caddr)
(else #f)))))
(group-id
,(and group (or (string->number group)
(cond ((group-information group) => caddr)
(else #f)))))
(document-root ,docroot)
(port ,port)))
(if (and (not norc?) (file-exists? rcfile))
(conf-load rcfile)
'())))
(pid-file (or (conf-get config 'pid-file)
(string-append name ".pid"))))
;; verify the config
;;(conf-verify
;; config
;; '())
;; run
(cond
(kill?
(daemon-kill pid-file 'name: name))
(debug?
((make-http-handler config)))
(else
(daemonize 'name: name
'pid-file: pid-file
'tcp-port: (conf-get config 'port 5556)
'user-id: (conf-get config 'user-id)
'group-id: (conf-get config 'group-id)
'tcp-debug?: (conf-get config 'debug?)
'tcp-handler: (make-http-handler config)
))))))
)
(import hato-httpd)
(main (command-line-arguments))
| true |
ebbeb99576646b5b3d3613694566c91a27a5330e | d0964c947dd6809ad0f67dd243ae1d6de8103df7 | /quiz/questions.scm | a175ac7e38f21d74bc399e3a75290d86f3842e39 | []
| no_license | kvalle/learning-scheme | 1eaf59c53cb52bfce87a8a92e4cc0ee2983419e5 | 28174c859e35fe694a6e3c77b11f1bbbbe9cb6a6 | refs/heads/master | 2021-01-15T17:46:54.913091 | 2015-05-03T18:17:33 | 2015-05-03T18:20:48 | 10,746,185 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 595 | scm | questions.scm | (list (cons "What is the answer to life, the universe and everything?"
(list (cons #t "42")
(cons #f "Cake")
(cons #f "Music, girls, and booze")
(cons #f "All of the above")))
(cons "To be, or not to be?"
(list (cons #t "Be")
(cons #f "Not be")
(cons #f "That is the question")))
(cons "Foo, bar, or baz?"
(list (cons #t "Foo")
(cons #t "Bar")
(cons #t "Baz")
(cons #f "Qux")))
(cons "What is the answer to this question?"
(list (cons #t "THIS is the answer.")
(cons #f "There is no correct answer to this question"))))
| false |
2fe4e4eeeed97a17ecb6c0d1ac0574d6a64d3383 | 8a0660bd8d588f94aa429050bb8d32c9cd4290d5 | /sitelib/srfi/%3a41.scm | 8636c7c5980a750f3e4ba890f5db2c005fd8baff | [
"BSD-2-Clause"
]
| permissive | david135/sagittarius-scheme | dbec76f6b227f79713169985fc16ce763c889472 | 2fbd9d153c82e2aa342bfddd59ed54d43c5a7506 | refs/heads/master | 2016-09-02T02:44:31.668025 | 2013-12-21T07:24:08 | 2013-12-21T07:24:08 | 32,497,456 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 124 | scm | %3a41.scm | ;; -*- mode: scheme; coding: utf-8; -*-
#!compatible
(library (srfi :41)
(export :all)
(import (srfi :41 streams))) | false |
a7c37b45e3e708a086a9c4b2b643d7aa866180ed | 3604661d960fac0f108f260525b90b0afc57ce55 | /SICP-solutions/3.72-square-sums.scm | be05b8142f97d595553ea2e714d98248dfe00332 | []
| no_license | rythmE/SICP-solutions | b58a789f9cc90f10681183c8807fcc6a09837138 | 7386aa8188b51b3d28a663958b807dfaf4ee0c92 | refs/heads/master | 2021-01-13T08:09:23.217285 | 2016-09-27T11:33:11 | 2016-09-27T11:33:11 | 69,350,592 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 667 | scm | 3.72-square-sums.scm | (load "3.70-merge-weighted.scm")
(define square-in-3
(define (square-sum pair)
(let ((i (car pair))
(j (cadr pair)))
(+ (square i) (square j))))
(define (stream-filter-3 weight stream)
(let ((x (stream-car stream))
(y (stream-car (stream-cdr stream)))
(z (stream-car (stream-cdr (stream-cdr stream))))
(cond ((stream-null? stream) the-empty-stream)
(= (weight x) (weight y) (weight z))
(cons-stream x (stream-filter-3 weight (stream-cdr stream))))
(else (stream-filter-3 weight (stream-cdr stream))))))
(let ((sq-sums-pairs (weighted-pairs integers integers square-sum)))
(stream-filter-3 square-sum q-sums-pairs))) | false |
43e8f0e8f5c8d70310d603cefc4eb8e5c32a97b8 | 53d4e640e1f666f3005653e7b4ab8a26fa3bd2fc | /guix/home/common/cfg/mcron.scm | 5bb133264a41a8e370088cf81fd8c798164a4796 | []
| no_license | Bost/dotfiles | fe64c8c032658306b5ff1815e50c3d39d6246274 | c5f2a8d465d203e98a45b41fb9dc02b54e591471 | refs/heads/master | 2023-08-29T06:55:49.676142 | 2023-08-10T09:29:26 | 2023-08-10T11:22:27 | 5,963,855 | 4 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 4,703 | scm | mcron.scm | #|
guix shell --development guix help2man git strace --pure
./pre-inst-env guix repl
(add-to-load-path
(string-append (getenv "HOME") "/dev/guix"))
|#
(define-module (cfg mcron)
#:use-module (gnu home services mcron) #| home-mcron-service-type |#
#:use-module (gnu services) #| service |#
#:use-module (guix gexp) #| #~ #$ etc. |#
#:export (mcron-service))
;; https://github.com/clojure-quant/infra-guix/blob/main/home/config-nuc.scm
;; (define do-job
;; ;; as user "bost" at 17:05 This runs from the user's home directory.
;; ;; #~(job
;; ;; '(next-minute-from (next-hour '(17)) '(5))
;; ;; (invoke "touch"
;; ;; (string-append "/tmp/srvc-second-"
;; ;; (number->string (current-time))))
;; ;; #:user "bost")
;; #~(job '(next-second)
;; ;; (lambda () ...) doesn't work
;; (list
;; (invoke "touch"
;; (string-append "/tmp/srvc-second-"
;; (number->string (current-time))))))
;; )
(define srvc-singleton-<time>
'(lambda ()
;; (lambda () ...) doesn't work (when NOT IN a gexp?)
;; (list ...) doesn't work when IN a gexp?
(invoke "touch"
(string-append "/tmp/srvc-singleton-"
(number->string (current-time))))
;; get the pid of the parent process and kill that process;
;; i.e. effectively kill this job-process
(kill (getppid) SIGINT)))
(define srvc-multi-<time>
'(lambda ()
;; (lambda () ...) doesn't work (when NOT IN a gexp?)
;; (list ...) doesn't work when IN a gexp?
(invoke "touch"
(string-append "/tmp/srvc-multi-"
(number->string (current-time))))))
(define srvc-touch-once
'(lambda ()
(system "touch /tmp/srvc-touch-once")
;; get the pid of the parent process and kill that process;
;; i.e. effectively kill this job-process
(kill (getppid) SIGINT)))
;; See also https://github.com/leahneukirchen/snooze
(define mcron-service
;; TODO test if the command-string can be created by string-append
(service
home-mcron-service-type
(home-mcron-configuration
(jobs
(let* (;; every second
;; (job-period '(next-second))
;; every 5 seconds
(job-period '(next-second (range 0 60 5))))
(list
;; see '(gexp->derivation "the-thing" build-exp)' in the manual
;; Also: #+ vs. #$
;; In a cross-compilation context, it is useful to distinguish
;; between references to the native build of a package—that can
;; run on the host—versus references to cross builds of a package.
;; To that end, the #+ plays the same role as #$, but is a
;; reference to a native package build
;; #~(job '#$job-period '#$srvc-singleton-<time>)
;; #~(job '#$job-period '#$srvc-multi-<time>)
;; #~(job '#$job-period '#$srvc-touch-once)
#~(job '#$job-period (lambda ()
;; (lambda () ...) doesn't work (when NOT IN a gexp?)
;; (list ...) doesn't work when IN a gexp?
;; TODO this doesn't get invoked at ALL!!!
(invoke "touch"
(string-append "/tmp/srvc-job-singleton-"
(number->string (current-time))))
;; get the pid of the parent process and kill that process;
;; i.e. effectively kill this job-process
(kill (getppid) SIGINT)))
#~(job '#$job-period (lambda ()
;; (lambda () ...) doesn't work (when NOT IN a gexp?)
;; (list ...) doesn't work when IN a gexp?
;; TODO this doesn't get invoked at ALL!!!
(invoke "touch"
(string-append "/tmp/srvc-job-multi-"
(number->string (current-time))))))
#~(job '#$job-period (lambda ()
;; TODO this doesn't get killed
(system "touch /tmp/srvc-job-lambda-touch-once")
;; get the pid of the parent process and kill that process;
;; i.e. effectively kill this job-process
(kill (getppid) SIGINT)))
#~(job '#$job-period "touch /tmp/srvc-job-string-touch-periodically-0")
))))))
| false |
66f1fbec9f3ef9e89fc0b6c7729602abae6a4727 | 0021f53aa702f11464522ed4dff16b0f1292576e | /scm/p49.scm | ce549f123a37cf15fa23ebd32a251fcab574f473 | []
| no_license | mtsuyugu/euler | fe40dffbab1e45a4a2a297c34b729fb567b2dbf2 | 4b17df3916f1368eff44d6bc36202de4dea3baf7 | refs/heads/master | 2021-01-18T14:10:49.908612 | 2016-10-07T15:35:45 | 2016-10-07T15:35:45 | 3,059,459 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 796 | scm | p49.scm | (use util.combinations)
(load "./eratosthenes.scm")
(load "./util.scm")
(define (p49)
(eratosthenes 10000)
(let ((prime-list (prime-list-less-than 10000)))
(combinations-for-each (lambda (x)
(let ((n1 (car x))
(n2 (cadr x)))
(if (and (> n1 999)
(> n2 999))
(let1 n3 (+ n2 (- n2 n1))
(if (and (< n3 10000)
(prime? n3)
(apply = (map digit-sort (list n1 n2 n3))))
(print (digit-append n1 n2 n3)))))))
prime-list 2)))
(p49)
| false |
f360fa493a743982744a73a5e0dba74194f341af | 1ed47579ca9136f3f2b25bda1610c834ab12a386 | /sec3/q3.10.scm | ea498d940fcd0abf77635d3d99776ff2135e59c4 | []
| no_license | thash/sicp | 7e89cf020e2bf5ca50543d10fa89eb1440f700fb | 3fc7a87d06eccbe4dcd634406e3b400d9405e9c4 | refs/heads/master | 2021-05-28T16:29:26.617617 | 2014-09-15T21:19:23 | 2014-09-15T21:19:23 | 3,238,591 | 0 | 1 | null | null | null | null | UTF-8 | Scheme | false | false | 905 | scm | q3.10.scm | ;; letを使って局所変数を明示的に作り出すことも出来る。
(define (make-withdraw initial-amount)
(let ((balance initial-amount))
(lambda (amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds."))))
;; ここで、letは単に手続き呼び出しのsyntax sugarに過ぎない。 (ref: sec1.3.2)
;; (let ((<var> <exp>)) <body>)
;; ↓ 次のように置き換えられる
;; ((lambda (<var>) <body>) <exp>)
;; 実際に置き換えてみる。
(define (make-withdraw initial-amount)
((lambda (balance)
(lambda (amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds.")))
initial-amount))
;; で、絵をかけと。
;; ref: http://wizardbook.wordpress.com/2010/12/14/exercise-3-10/
| false |
30e34a9194093ea4a226064b1924cc839eefdf57 | 25a487e394b2c8369f295434cf862321c26cd29c | /lib/pikkukivi/commands/colours.sls | e9f83be2ec27a12bca2c4a1265823884e2d635cf | []
| no_license | mytoh/loitsu | b11e1ed9cda72c0a0b0f59070c9636c167d01a2c | d197cade05ae4acbf64c08d1a3dd9be6c42aac58 | refs/heads/master | 2020-06-08T02:00:50.563515 | 2013-12-17T10:23:04 | 2013-12-17T10:23:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 794 | sls | colours.sls | (library (pikkukivi commands colours)
(export
colours)
(import
(silta base)
(silta write)
(only (srfi :1 lists)
iota)
(only (srfi :13 strings)
string-join
string-every)
(maali)
)
(define (colours-boxes-base)
(display "base:")
(newline)
(for-each
(lambda (n)
(display (paint "█" n)))
(iota 16))
(newline))
(define (colours-boxes-others)
(display "others:")
(newline)
(for-each
(lambda (n)
(display (paint "█" n))
(if (exact-integer? (/ n 27))
(newline)))
(iota 240 16 1))
(newline))
(define (colours-boxes)
(colours-boxes-base)
(colours-boxes-others))
(define (colours type)
(colours-boxes))
))
| false |
7cc59afb131d1d1b8f5872ebc50a89f50afdb4ef | 951b7005abfe3026bf5b3bd755501443bddaae61 | /astonish/数字电路的模拟器.scm | b1f8a4342ef0ae1c1c3d8f14e97217517f715b5c | []
| no_license | WingT/scheme-sicp | d8fd5a71afb1d8f78183a5f6e4096a6d4b6a6c61 | a255f3e43b46f89976d8ca2ed871057cbcbb8eb9 | refs/heads/master | 2020-05-21T20:12:17.221412 | 2016-09-24T14:56:49 | 2016-09-24T14:56:49 | 63,522,759 | 2 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 8,546 | scm | 数字电路的模拟器.scm | ;基本功能块
;延时:
(define inverter-delay 2)
(define and-gate-delay 3)
(define or-gate-delay 5)
;inverter
(define (inverter input output)
(define (invert-input)
(let ((new-value (logical-not (get-signal input))))
(after-delay inverter-delay
(lambda () (set-signal! output new-value)))))
(add-action! input invert-input)
'ok)
(define (logical-not x) (- 1 x))
;and-gate
(define (and-gate a1 a2 output)
(define (and-action-procedure)
(let ((new-value (logical-and (get-signal a1)
(get-signal a2))))
(after-delay and-gate-delay
(lambda () (set-signal! output new-value)))))
(add-action! a1 and-action-procedure)
(add-action! a2 and-action-procedure)
'ok)
(define (logical-and a b)
(* a b))
;3.28
;or-gate
(define (or-gate a1 a2 output)
(define (or-gate-procedure)
(let ((new-value (logical-or (get-signal a1)
(get-signal a2))))
(after-delay or-gate-delay
(lambda () (set-signal! output new-value)))))
(add-action! a1 or-gate-procedure)
(add-action! a2 or-gate-procedure)
'ok)
(define (logical-or a b)
(if (>= (+ a b) 1)
1
0))
;3.29
;or-gate-delay = and-gate-delay + 2 * inverter-delay
(define (or-gate-2 a1 a2 output)
(let ((a (make-wire))
(b (make-wire))
(c (make-wire)))
(inverter a1 a)
(inverter a2 b)
(and-gate a b c)
(inverter c output)
'ok))
;3.30
(define (half-adder a b s c)
(let ((d (make-wire))
(e (make-wire)))
(or-gate a b d)
(and-gate a b c)
(inverter c e)
(and-gate d e s)
'ok))
(define (full-adder a b c-in sum c-out)
(let ((s (make-wire))
(c1 (make-wire))
(c2 (make-wire)))
(half-adder b c-in s c1)
(half-adder a s sum c2)
(or-gate c2 c1 c-out)
'ok))
(define (ripple-carry-adder a b s c)
(if (null? a)
(set-signal! c 0)
(let ((c1 (make-wire)))
(full-adder (car a) (car b) c1 (car s) c)
(ripple-carry-adder (cdr a) (cdr b) (cdr s) c1)))
'ok)
;线路的表示
(define (make-wire)
(let ((signal-value 0)
(action-procedures '()))
(define (set-my-signal! new-value)
(if (not (= new-value signal-value))
(begin
(set! signal-value new-value)
(call-each action-procedures))
'done))
(define (accept-action-procedure! proc)
(set! action-procedures (cons proc action-procedures))
(proc));先执行一次,初始化
(define (dispatch m)
(cond ((eq? m 'get-signal) signal-value)
((eq? m 'set-signal!) set-my-signal!)
((eq? m 'add-action!) accept-action-procedure!)
(else (error "wrong operation type"))))
dispatch))
(define (call-each action-procedures)
(if (null? action-procedures)
'done
(begin
((car action-procedures))
(call-each (cdr action-procedures)))))
(define (get-signal wire)
(wire 'get-signal))
(define (set-signal! wire new-value)
((wire 'set-signal!) new-value))
(define (add-action! wire proc)
((wire 'add-action!) proc))
;待处理表的实现
(define (empty-agenda? agenda)
(null? (segments agenda)))
(define (make-time-segment time queue)
(cons time queue))
(define (segment-time s) (car s))
(define (segment-queue s) (cdr s))
(define (make-agenda)
(list 0))
(define (current-time agenda)
(car agenda))
(define (set-current-time! agenda time)
(set-car! agenda time))
(define (segments agenda)
(cdr agenda))
(define (set-segments! agenda segments)
(set-cdr! agenda segments))
(define (first-segment agenda)
(let ((segments (segments agenda)))
(if (null? segments)
(error "first-segment: no segment")
(car segments))))
(define (rest-segment agenda)
(let ((segments (segments agenda)))
(if (null? segments)
(error "rest-segment: no segment")
(cdr segments))))
(define (add-to-agenda! time action agenda)
(define (belongs-before? segments)
(or (null? segments)
(< time (segment-time (car segments)))))
(define (make-new-time-segment time action)
(let ((q (make-queue)))
(insert-queue! q action)
(cons time q)))
(define (add-to-segments! segments)
(if (= time (segment-time (car segments)))
(insert-queue! (segment-queue (car segments))
action)
(let ((rest (cdr segments)))
(if (belongs-before? rest)
(set-cdr! segments
(cons (make-new-time-segment
time
action)
rest))
(add-to-segments! rest)))))
(let ((segments (segments agenda)))
(if (belongs-before? segments)
(set-segments! agenda
(cons
(make-new-time-segment time action)
segments))
(add-to-segments! segments))))
(define (remove-first-agenda-item! agenda)
(let ((q (segment-queue (first-segment agenda))))
(delete-queue! q)
(if (empty-queue? q)
(set-segments! agenda (rest-segment agenda)))))
(define (first-agenda-item agenda)
(if (empty-agenda? agenda)
(error "first-agenda-item: agenda empty")
(let ((first-seg (first-segment agenda)))
(set-current-time! agenda (segment-time first-seg))
(front-queue (segment-queue first-seg)))))
;队列操作
(define (make-queue)
(cons '() '()))
(define (front-ptr queue)
(car queue))
(define (rear-ptr queue)
(cdr queue))
(define (empty-queue? queue)
(null? (front-ptr queue)))
(define (set-front-ptr! queue item)
(set-car! queue item))
(define (set-rear-ptr! queue item)
(set-cdr! queue item))
(define (front-queue queue)
(if (empty-queue? queue)
(error "front-queue:queue empty")
(car (front-ptr queue))))
(define (insert-queue! queue item)
(let ((new-pair (list item)))
(cond ((empty-queue? queue)
(set-front-ptr! queue new-pair)
(set-rear-ptr! queue new-pair)
queue)
(else (set-cdr! (rear-ptr queue) new-pair)
(set-rear-ptr! queue new-pair)
queue))))
(define (delete-queue! queue)
(cond ((empty-queue? queue)
(error "delete-queue!:queue empty"))
(else (set-front-ptr! queue (cdr (front-ptr queue)))
queue)))
;待处理表
(define (after-delay delay action)
(add-to-agenda! (+ delay (current-time the-agenda))
action
the-agenda))
(define (propagate)
(if (empty-agenda? the-agenda)
'done
(let ((first-item (first-agenda-item the-agenda)))
(first-item)
(remove-first-agenda-item! the-agenda)
(propagate))))
;实例:监视器
(define (probe name wire)
(add-action! wire
(lambda ()
(newline)
(display name)
(display " ")
(display (current-time the-agenda))
(display " new-value = ")
(display (get-signal wire)))))
;检测部分
(define the-agenda (make-agenda))
(define input-1 (make-wire))
(define input-2 (make-wire))
(define sum (make-wire))
(define carry (make-wire))
(probe 'sum sum)
(probe 'carry carry)
(half-adder input-1 input-2 sum carry)
(set-signal! input-1 1)
(propagate)
(set-signal! input-2 1)
(propagate)
;级联进位全加器检查
(define the-agenda (make-agenda))
(define (generate-operand n)
(if (= n 0)
'()
(let ((wire (make-wire)))
(cons wire (generate-operand (- n 1))))))
(define (set-operand! wires operand)
(if (null? wires)
'done
(begin
(set-signal! (car wires) (car operand))
(set-operand! (cdr wires) (cdr operand)))))
(define (add-probe s)
(if (null? s)
'done
(begin
(probe 'sum (car s))
(add-probe (cdr s)))))
(define a (generate-operand 4))
(define b (generate-operand 4))
(define s (generate-operand 4))
(probe 'sum4 (car s))
(probe 'sum3 (cadr s))
(probe 'sum2 (caddr s))
(probe 'sum1 (cadddr s))
(define c (make-wire))
(probe 'carry c)
(ripple-carry-adder a b s c)
(set-operand! a '(0 0 1 1))
(set-operand! b '(0 1 0 1))
(propagate)
;2.32
(define the-agenda (make-agenda))
(define input-1 (make-wire))
(define input-2 (make-wire))
(define output (make-wire))
(probe 'output output)
(and-gate input-1 input-2 output)
(set-signal! input-1 0)
(set-signal! input-2 1)
(propagate)
(set-signal! input-1 1)
(propagate)
(set-signal! input-2 0)
(propagate)
| false |
2f9fd4dc2db5412f287d4e3ade3d00f2c78ebfaf | 37c751fc27e790303b84730013217d1c8cbb60cc | /s48/cml/pkg-def.scm | 83625d96c2c9fd9d6df5ff194cbf5d157a1185a6 | [
"LicenseRef-scancode-public-domain",
"BSD-3-Clause"
]
| permissive | gitGNU/gnu_sunterlib | e82df45894f0075e2ad2df88ce6edf0f1704c6a0 | 96d443b55c990506e81f2c893e02245b7e2b5f4c | refs/heads/master | 2023-08-06T09:32:59.463520 | 2017-03-07T14:31:05 | 2017-03-07T14:31:05 | 90,394,267 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 610 | scm | pkg-def.scm | (define-package "cml"
(1 1)
((install-lib-version (1 3 0)))
(write-to-load-script
`((config)
(load ,(absolute-file-name "packages.scm"
(get-directory 'scheme #f)))))
(install-file "README" 'doc)
(install-file "NEWS" 'doc)
(install-string (COPYING) "COPYING" 'doc)
(install-file "packages.scm" 'scheme)
(install-file "async-channels.scm" 'scheme)
(install-file "placeholder.scm" 'scheme)
(install-file "trans-id.scm" 'scheme)
(install-file "channel.scm" 'scheme)
(install-file "jar.scm" 'scheme)
(install-file "rendezvous.scm" 'scheme))
| false |
b9238d6c8847950bd27c436cdc8beafcf126aab8 | f0747cba9d52d5e82772fd5a1caefbc074237e77 | /prebuilt-ppc64le.scm | 9a541f97cf91dcb481c1ca6fea76148050cbc6f9 | []
| no_license | philhofer/distill | a3b024de260dca13d90e23ecbab4a8781fa47340 | 152cb447cf9eef3cabe18ccf7645eb597414f484 | refs/heads/master | 2023-08-27T21:44:28.214377 | 2023-04-20T03:20:55 | 2023-04-20T03:20:55 | 267,761,972 | 3 | 0 | null | 2021-10-13T19:06:55 | 2020-05-29T04:06:55 | Scheme | UTF-8 | Scheme | false | false | 1,073 | scm | prebuilt-ppc64le.scm | (quote (#(#(archive tar.zst) "3wDaCiXzp-6_G2KMr3fyrL5V_yPO3ZEZD6LflzjTMDU=" "https://b2cdn.sunfi.sh/file/pub-cdn/3wDaCiXzp-6_G2KMr3fyrL5V_yPO3ZEZD6LflzjTMDU=") #(#(archive tar.zst) "fGGPGYYKDoSJL4f3Gfuluhfmomem4l-uIQ7bF6fSVho=" "https://b2cdn.sunfi.sh/file/pub-cdn/fGGPGYYKDoSJL4f3Gfuluhfmomem4l-uIQ7bF6fSVho=") #(#(archive tar.zst) "3KXDXhz_gZfLUaJfH5jcY0wl7RQL6MCahBeKGdywW9g=" "https://b2cdn.sunfi.sh/file/pub-cdn/3KXDXhz_gZfLUaJfH5jcY0wl7RQL6MCahBeKGdywW9g=") #(#(archive tar.zst) "sSfmpyQRLFOrwgbWpYChEubd-eE0prpce1ESI3za96A=" "https://b2cdn.sunfi.sh/file/pub-cdn/sSfmpyQRLFOrwgbWpYChEubd-eE0prpce1ESI3za96A=") #(#(archive tar.zst) "XvsiCkJeM5--v71t0thZdDdpU7OsMNTi8obFJZLE2DY=" "https://b2cdn.sunfi.sh/file/pub-cdn/XvsiCkJeM5--v71t0thZdDdpU7OsMNTi8obFJZLE2DY=") #(#(archive tar.zst) "pfr-ZWBcrfTFEEDqdtHZoUeiGDhVmckYl3ChHHHugFM=" "https://b2cdn.sunfi.sh/file/pub-cdn/pfr-ZWBcrfTFEEDqdtHZoUeiGDhVmckYl3ChHHHugFM=") #(#(archive tar.zst) "lvb5S7lqK81TcLTesyJlIaaNOxwG0TobSXLRtm10jZk=" "https://b2cdn.sunfi.sh/file/pub-cdn/lvb5S7lqK81TcLTesyJlIaaNOxwG0TobSXLRtm10jZk="))) | false |
82a38c1a005dc6ff4426880153886ea77c320480 | 6fea30c362c12359ce93a72846fe72a29cd62999 | /verifiers/is.scm | ad0904a55ab12d95d0ef001aeb5cfbfd61b97dc3 | []
| no_license | certainty/chicken_veritas | 173b4b16545eacd367721b50fed316bc45489e63 | a7171b9842ab8fb0aa626cf90d7f12d42bc4575b | refs/heads/master | 2016-09-06T00:20:33.694897 | 2014-03-16T16:09:44 | 2014-03-16T16:09:44 | 39,297,328 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 9,560 | scm | is.scm | (module veritas-verifiers-is
*
(import chicken scheme data-structures extras ports srfi-69)
(use veritas srfi-1 matchable fmt format-textdiff srfi-1)
(define (eval-expr complement? expr)
((if complement? not identity) expr))
(define (message-from-predicate-form form)
(if (list? form)
(let* ((rest (third form))
(name (car rest))
(args (flatten (cdr rest))))
(with-output-to-string
(lambda ()
(for-each (cut printf "~A " <>) args))))
form))
(define-syntax is
(syntax-rules (a an true false)
((_ true)
(is #t))
((_ false)
(is #f))
((_ pred-or-value)
(if (procedure? pred-or-value)
(is-verifier pred-or-value)
(is-verifier (make-equal-predicate pred-or-value))))
((_ pred value0 value1 ...)
(is-verifier/curried-predicate pred (list value0 value1 ...)))))
(define ((predicate-applier pred) subject complement?)
(let ((value (force (verification-subject-expression-promise subject)))
(expr (verification-subject-quoted-expression subject)))
(values (pred value)
(sprintf "Expected (~a ~a) to be true" (third expr) value))))
(define ((make-equal-predicate a) subject complement?)
(let* ((b (force (verification-subject-expression-promise subject)))
(res (or (equal? a b)
(and (number? a)
(inexact? a)
(inexact? b)
(approx-equal? a b)))))
(values res (make-equality-failure-message a b))))
(define (make-equality-failure-message expected actual)
(cond
((and (string? actual) (string? expected))
(let ((actual-lines (string-split actual "\n"))
(expected-lines (string-split expected "\n")))
(with-output-to-string
(lambda ()
(printf "expected: ~s~%" expected)
(printf " got: ~s~%" actual)
(when (or (> (length actual-lines) 1) (> (length expected-lines) 1))
(let ((hunks (textdiff actual-lines expected-lines 3)))
(print "\nDiff:")
((make-format-textdiff 'context) (current-output-port) hunks "actual" "" "expected" "")))))))
(else
(with-output-to-string
(lambda ()
(print "expected: " expected)
(print " got: " actual))))))
(define current-equality-epsilon (make-parameter 1e-5))
(define (approx-equal? a b #!optional (epsilon (current-equality-epsilon)))
(cond
((> (abs a) (abs b))
(approx-equal? b a epsilon))
((zero? b)
(< (abs a) epsilon))
(else
(< (abs (/ (- a b) b)) epsilon))))
;;(verify subj (is 3))
;;(verify subj (is (predicate-constructor args)))
;;(verify subj (is curried-pred args)) ;; (is > 3)
(define ((is-verifier pred) subject complement?)
(let* ((quoted-expr (verification-subject-quoted-expression subject))
(expr (verification-subject-expression-promise subject))
(value (force expr)))
(receive (result message) (pred subject complement?)
(if result
(pass subject)
(fail subject message)))))
(define ((is-verifier/curried-predicate pred values) subject complement?)
(let* ((quoted-expr (verification-subject-quoted-expression subject))
(expr (verification-subject-expression-promise subject))
(value (force expr))
(result (eval-expr complement? (apply pred value values))))
(if result
(pass subject)
(fail subject
(if complement?
(sprintf "Expected ~S not to be ~S" value quoted-expr)
(sprintf "Expected ~S to be ~A" value (message-from-predicate-form quoted-expr)))))))
(define-syntax verify-type
(lambda (form rename env)
(let* ((type (cadr form))
(type-pred (string->symbol (conc (symbol->string type) "?")))
(%type-verifier (rename 'type-verifier)))
`(,%type-verifier ,type-pred (quote ,type)))))
(define ((type-verifier type-pred type) subject complement?)
(let* ((quoted-expr (verification-subject-quoted-expression))
(expr (verification-subject-expression-promise subject))
(value (force expr))
(result (eval-expr complement? (type-pred value))))
(if result
(pass subject)
(fail subject (sprintf "Expected ~S ~A be a ~A" value (if complement? "not to" "to") type)))))
(define ((close-to what #!key (delta 0.3)) actual complement?)
(values (approx-equal? what actual delta)
(sprintf "Expected ~a to be roughly equal to ~a (epsilon ~a)" actual what delta)))
(define roughly close-to)
(define ((any-of item . more-items) subject complement?)
(let ((value (force (verification-subject-expression-promise subject))))
(values (member value (cons item more-items))
(sprintf "Expected ~a to be a member of ~a" value (cons item more-items)))))
(define ((none-of item . more-items) subject complement?)
(let ((value (force (verification-subject-expression-promise subject))))
(values (not (member value (cons item more-items)))
(sprintf "Expected ~a not to be a member of ~a" value (cons item more-items)))))
(define ((list-including item . more-items) subject complement?)
(let ((value (force (verification-subject-expression-promise subject))))
(values (and (list? value)
(every (cut member <> value) (cons item more-items)))
(sprintf "Expected ~a to be a list that includes ~a" value (cons item more-items)))))
(define ((vector-including . args) subject complement?)
(let ((value (force (verification-subject-expression-promise subject))))
(values (and (vector? value)
(let ((value (vector->list value)))
(every (cut member <> value) args)))
(sprintf "Expected ~a to be vector that includes ~a" value args))))
(define ((hash-table-including . args) subject complement?)
(let ((value (force (verification-subject-expression-promise subject))))
(values (and (hash-table? value)
(every (lambda (pair)
(equal? (cdr pair) (hash-table-ref value (car pair))))
args))
(sprintf "Expected ~a to be a hash-table that includes ~a" value args))))
)
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;; Have/Has
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; (define-syntax has
;; (syntax-rules ()
;; ((_ amount procedure-or-sugar)
;; (if (procedure? (quote procedure-or-sugar))
;; (have-matcher amount procedure-or-sugar (quote procedure-or-sugar))
;; (have-matcher amount (quote procedure-or-sugar) (quote procedure-or-sugar))))))
;; (define (have-matcher expected-amount procedure-or-sugar procedure-or-sugar-name #!key (compare =))
;; (let ((actual-amount #f))
;; (matcher
;; (check (subject)
;; (let* ((collection (if (procedure? procedure-or-sugar) (procedure-or-sugar (force subject)) (force subject)))
;; (item-amount (size collection)))
;; (set! actual-amount item-amount)
;; (compare item-amount expected-amount)))
;; (message (form subject negate)
;; (if negate
;; (sprintf "Didn't expect ~A ~A" expected-amount procedure-or-sugar-name)
;; (sprintf "Expected ~A ~A but found ~A" expected-amount procedure-or-sugar-name actual-amount))))))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;; raise
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; (define-syntax raise
;; (syntax-rules (error errors with)
;; ((_ error)
;; (make-error-matcher))
;; ((_ errors)
;; (make-error-matcher))
;; ((_ (kind more-kinds ...))
;; (make-error-matcher kinds: '(kind more-kinds ...)))))
;; (define (make-error-matcher #!key (kinds #f) (properties #f))
;; (let ((message "")
;; (negative-message ""))
;; (make-matcher
;; (lambda (code)
;; (handle-exceptions exn
;; (let* ((condition (condition->list exn))
;; (exn-kinds (map car condition)))
;; (cond
;; ((and kinds properties) #t)
;; (kinds
;; (if (every (cut member <> exn-kinds) kinds)
;; #t
;; (begin
;; (set! message (sprintf "Expected exn of kinds ~A but got ~A" kinds exn-kinds))
;; ;FIXME find proper wording
;; (set! negative-message (sprintf "Expected exn not of kinds ~A but got ~A" kinds exn-kinds))
;; #f)))
;; (properties #t)
;; (else
;; (set! message (sprintf "Expecte errors but didn't get one"))
;; (set! negative-message (sprintf "Expected no errors but got one"))
;; #t)))
;; (force code)
;; #f))
;; (lambda (form subject negate)
;; (if negate
;; negative-message
;; message)))))
| true |
10d8f93e1d09a56d38e2c462c58d92ce26ae2b39 | c27f74958de01e46f2ead89e1ab6c952dc8238ad | /usr/share/guile/2.2/language/cps/slot-allocation.scm | f623aac75d9b940b6a2ac7f557e9b96318f651b5 | []
| no_license | git-for-windows/git-sdk-32 | 051ab8b76e3eb68126fc31dcc061f0d93341bb8d | e948a750b18992de20c64155e8c6959c475748ed | refs/heads/main | 2023-08-31T21:32:13.595310 | 2023-08-30T11:37:43 | 2023-08-30T11:37:43 | 87,077,227 | 36 | 64 | null | 2023-08-25T08:34:40 | 2017-04-03T13:29:09 | C | UTF-8 | Scheme | false | false | 42,941 | scm | slot-allocation.scm | ;; Continuation-passing style (CPS) intermediate language (IL)
;; Copyright (C) 2013-2020 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Commentary:
;;;
;;; A module to assign stack slots to variables in a CPS term.
;;;
;;; Code:
(define-module (language cps slot-allocation)
#:use-module (ice-9 control)
#:use-module (ice-9 match)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-9)
#:use-module (srfi srfi-11)
#:use-module (srfi srfi-26)
#:use-module (language cps)
#:use-module (language cps utils)
#:use-module (language cps intmap)
#:use-module (language cps intset)
#:export (allocate-slots
lookup-slot
lookup-maybe-slot
lookup-representation
lookup-constant-value
lookup-maybe-constant-value
lookup-nlocals
lookup-call-proc-slot
lookup-parallel-moves
lookup-slot-map))
(define-record-type $allocation
(make-allocation slots representations constant-values call-allocs
shuffles frame-size)
allocation?
;; A map of VAR to slot allocation. A slot allocation is an integer,
;; if the variable has been assigned a slot.
;;
(slots allocation-slots)
;; A map of VAR to representation. A representation is 'scm, 'f64,
;; 'u64, or 's64.
;;
(representations allocation-representations)
;; A map of VAR to constant value, for variables with constant values.
;;
(constant-values allocation-constant-values)
;; A map of LABEL to /call allocs/, for expressions that continue to
;; $kreceive continuations: non-tail calls and $prompt expressions.
;;
;; A call alloc contains two pieces of information: the call's /proc
;; slot/ and a /dead slot map/. The proc slot indicates the slot of a
;; procedure in a procedure call, or where the procedure would be in a
;; multiple-value return.
;;
;; The dead slot map indicates, what slots should be ignored by GC
;; when marking the frame. A dead slot map is a bitfield, as an
;; integer.
;;
(call-allocs allocation-call-allocs)
;; A map of LABEL to /parallel moves/. Parallel moves shuffle locals
;; into position for a $call, $callk, or $values, or shuffle returned
;; values back into place in a $kreceive.
;;
;; A set of moves is expressed as an ordered list of (SRC . DST)
;; moves, where SRC and DST are slots. This may involve a temporary
;; variable.
;;
(shuffles allocation-shuffles)
;; The number of local slots needed for this function. Because we can
;; contify common clause tails, we use one frame size for all clauses
;; to avoid having to adjust the frame size when continuing to labels
;; from other clauses.
;;
(frame-size allocation-frame-size))
(define-record-type $call-alloc
(make-call-alloc proc-slot slot-map)
call-alloc?
(proc-slot call-alloc-proc-slot)
(slot-map call-alloc-slot-map))
(define (lookup-maybe-slot var allocation)
(intmap-ref (allocation-slots allocation) var (lambda (_) #f)))
(define (lookup-slot var allocation)
(intmap-ref (allocation-slots allocation) var))
(define (lookup-representation var allocation)
(intmap-ref (allocation-representations allocation) var))
(define *absent* (list 'absent))
(define (lookup-constant-value var allocation)
(let ((value (intmap-ref (allocation-constant-values allocation) var
(lambda (_) *absent*))))
(when (eq? value *absent*)
(error "Variable does not have constant value" var))
value))
(define (lookup-maybe-constant-value var allocation)
(let ((value (intmap-ref (allocation-constant-values allocation) var
(lambda (_) *absent*))))
(if (eq? value *absent*)
(values #f #f)
(values #t value))))
(define (lookup-call-alloc k allocation)
(intmap-ref (allocation-call-allocs allocation) k))
(define (lookup-call-proc-slot k allocation)
(or (call-alloc-proc-slot (lookup-call-alloc k allocation))
(error "Call has no proc slot" k)))
(define (lookup-parallel-moves k allocation)
(intmap-ref (allocation-shuffles allocation) k))
(define (lookup-slot-map k allocation)
(or (call-alloc-slot-map (lookup-call-alloc k allocation))
(error "Call has no slot map" k)))
(define (lookup-nlocals allocation)
(allocation-frame-size allocation))
(define-syntax-rule (persistent-intmap2 exp)
(call-with-values (lambda () exp)
(lambda (a b)
(values (persistent-intmap a) (persistent-intmap b)))))
(define (compute-defs-and-uses cps)
"Return two LABEL->VAR... maps indicating values defined at and used
by a label, respectively."
(define (vars->intset vars)
(fold (lambda (var set) (intset-add set var)) empty-intset vars))
(persistent-intmap2
(intmap-fold
(lambda (label cont defs uses)
(define (get-defs k)
(match (intmap-ref cps k)
(($ $kargs names vars) (vars->intset vars))
(_ empty-intset)))
(define (return d u)
(values (intmap-add! defs label d)
(intmap-add! uses label u)))
(match cont
(($ $kfun src meta self)
(return (intset self) empty-intset))
(($ $kargs _ _ ($ $continue k src exp))
(match exp
((or ($ $const) ($ $closure))
(return (get-defs k) empty-intset))
(($ $call proc args)
(return (get-defs k) (intset-add (vars->intset args) proc)))
(($ $callk _ proc args)
(return (get-defs k) (intset-add (vars->intset args) proc)))
(($ $primcall name args)
(return (get-defs k) (vars->intset args)))
(($ $branch kt ($ $primcall name args))
(return empty-intset (vars->intset args)))
(($ $branch kt ($ $values args))
(return empty-intset (vars->intset args)))
(($ $values args)
(return (get-defs k) (vars->intset args)))
(($ $prompt escape? tag handler)
(return empty-intset (intset tag)))))
(($ $kclause arity body alt)
(return (get-defs body) empty-intset))
(($ $kreceive arity kargs)
(return (get-defs kargs) empty-intset))
(($ $ktail)
(return empty-intset empty-intset))))
cps
empty-intmap
empty-intmap)))
(define (compute-reverse-control-flow-order preds)
"Return a LABEL->ORDER bijection where ORDER is a contiguous set of
integers starting from 0 and incrementing in sort order. There is a
precondition that labels in PREDS are already renumbered in reverse post
order."
(define (has-back-edge? preds)
(let/ec return
(intmap-fold (lambda (label labels)
(intset-fold (lambda (pred)
(if (<= label pred)
(return #t)
(values)))
labels)
(values))
preds)
#f))
(if (has-back-edge? preds)
;; This is more involved than forward control flow because not all
;; live labels are reachable from the tail.
(persistent-intmap
(fold2 (lambda (component order n)
(intset-fold (lambda (label order n)
(values (intmap-add! order label n)
(1+ n)))
component order n))
(reverse (compute-sorted-strongly-connected-components preds))
empty-intmap 0))
;; Just reverse forward control flow.
(let ((max (intmap-prev preds)))
(intmap-map (lambda (label labels) (- max label)) preds))))
(define* (add-prompt-control-flow-edges conts succs #:key complete?)
"For all prompts in DFG in the range [MIN-LABEL, MIN-LABEL +
LABEL-COUNT), invoke F with arguments PROMPT, HANDLER, and BODY for each
body continuation in the prompt."
(define (intset-filter pred set)
(intset-fold (lambda (i set)
(if (pred i) set (intset-remove set i)))
set
set))
(define (intset-any pred set)
(intset-fold (lambda (i res)
(if (or res (pred i)) #t res))
set
#f))
(define (compute-prompt-body label)
(persistent-intset
(let visit-cont ((label label) (level 1) (labels empty-intset))
(cond
((zero? level) labels)
((intset-ref labels label) labels)
(else
(match (intmap-ref conts label)
(($ $ktail)
;; Possible for bailouts; never reached and not part of
;; prompt body.
labels)
(cont
(let ((labels (intset-add! labels label)))
(match cont
(($ $kreceive arity k) (visit-cont k level labels))
(($ $kargs names syms ($ $continue k src ($ $primcall 'wind)))
(visit-cont k (1+ level) labels))
(($ $kargs names syms
($ $continue k src ($ $prompt escape? tag handler)))
(visit-cont handler level (visit-cont k (1+ level) labels)))
(($ $kargs names syms ($ $continue k src ($ $primcall 'unwind)))
(visit-cont k (1- level) labels))
(($ $kargs names syms ($ $continue k src ($ $branch kt)))
(visit-cont k level (visit-cont kt level labels)))
(($ $kargs names syms ($ $continue k src exp))
(visit-cont k level labels)))))))))))
(define (visit-prompt label handler succs)
(let ((body (compute-prompt-body label)))
(define (out-or-back-edge? label)
;; Most uses of visit-prompt-control-flow don't need every body
;; continuation, and would be happy getting called only for
;; continuations that postdominate the rest of the body. Unless
;; you pass #:complete? #t, we only invoke F on continuations
;; that can leave the body, or on back-edges in loops.
(intset-any (lambda (succ)
(or (not (intset-ref body succ))
(<= succ label)))
(intmap-ref succs label)))
(intset-fold (lambda (pred succs)
(intmap-replace succs pred handler intset-add))
(if complete? body (intset-filter out-or-back-edge? body))
succs)))
(intmap-fold
(lambda (label cont succs)
(match cont
(($ $kargs _ _
($ $continue k _ ($ $prompt escape? tag handler)))
(visit-prompt k handler succs))
(_ succs)))
conts
succs))
(define (rename-keys map old->new)
(persistent-intmap
(intmap-fold (lambda (k v out)
(intmap-add! out (intmap-ref old->new k) v))
map
empty-intmap)))
(define (rename-intset set old->new)
(intset-fold (lambda (old set) (intset-add set (intmap-ref old->new old)))
set empty-intset))
(define (rename-graph graph old->new)
(persistent-intmap
(intmap-fold (lambda (pred succs out)
(intmap-add! out
(intmap-ref old->new pred)
(rename-intset succs old->new)))
graph
empty-intmap)))
(define (compute-live-variables cps defs uses)
"Compute and return two values mapping LABEL->VAR..., where VAR... are
the definitions that are live before and after LABEL, as intsets."
(let* ((succs (add-prompt-control-flow-edges cps (compute-successors cps)))
(preds (invert-graph succs))
(old->new (compute-reverse-control-flow-order preds))
(init (persistent-intmap (intmap-fold
(lambda (old new init)
(intmap-add! init new empty-intset))
old->new empty-intmap))))
(call-with-values
(lambda ()
(solve-flow-equations (rename-graph preds old->new)
init init
(rename-keys defs old->new)
(rename-keys uses old->new)
intset-subtract intset-union intset-union))
(lambda (in out)
;; As a reverse control-flow problem, the values flowing into a
;; node are actually the live values after the node executes.
;; Funny, innit? So we return them in the reverse order.
(let ((new->old (invert-bijection old->new)))
(values (rename-keys out new->old)
(rename-keys in new->old)))))))
(define (compute-needs-slot cps defs uses)
(define (get-defs k) (intmap-ref defs k))
(define (get-uses label) (intmap-ref uses label))
(intmap-fold
(lambda (label cont needs-slot)
(intset-union
needs-slot
(match cont
(($ $kargs _ _ ($ $continue k src exp))
(let ((defs (get-defs label)))
(define (defs+* uses)
(intset-union defs uses))
(define (defs+ use)
(intset-add defs use))
(match exp
(($ $const)
empty-intset)
(($ $primcall (or 'load-f64 'load-u64 'load-s64) (val))
empty-intset)
(($ $primcall 'free-ref (closure slot))
(defs+ closure))
(($ $primcall 'free-set! (closure slot value))
(defs+* (intset closure value)))
(($ $primcall 'cache-current-module! (mod . _))
(defs+ mod))
(($ $primcall 'cached-toplevel-box _)
defs)
(($ $primcall 'cached-module-box _)
defs)
(($ $primcall 'resolve (name bound?))
(defs+ name))
(($ $primcall 'make-vector/immediate (len init))
(defs+ init))
(($ $primcall 'vector-ref/immediate (v i))
(defs+ v))
(($ $primcall 'vector-set!/immediate (v i x))
(defs+* (intset v x)))
(($ $primcall 'allocate-struct/immediate (vtable nfields))
(defs+ vtable))
(($ $primcall 'struct-ref/immediate (s n))
(defs+ s))
(($ $primcall 'struct-set!/immediate (s n x))
(defs+* (intset s x)))
(($ $primcall (or 'add/immediate 'sub/immediate
'uadd/immediate 'usub/immediate 'umul/immediate
'ursh/immediate 'ulsh/immediate)
(x y))
(defs+ x))
(($ $primcall 'builtin-ref (idx))
defs)
(_
(defs+* (get-uses label))))))
(($ $kreceive arity k)
;; Only allocate results of function calls to slots if they are
;; used.
empty-intset)
(($ $kclause arity body alternate)
(get-defs label))
(($ $kfun src meta self)
(intset self))
(($ $ktail)
empty-intset))))
cps
empty-intset))
(define (compute-lazy-vars cps live-in live-out defs needs-slot)
"Compute and return a set of vars whose allocation can be delayed
until their use is seen. These are \"lazy\" vars. A var is lazy if its
uses are calls, it is always dead after the calls, and if the uses flow
to the definition. A flow continues across a node iff the node kills no
values that need slots, and defines only lazy vars. Calls also kill
flows; there's no sense in trying to juggle a pending frame while there
is an active call."
(define (list->intset list)
(persistent-intset
(fold (lambda (i set) (intset-add! set i)) empty-intset list)))
(let* ((succs (compute-successors cps))
(gens (intmap-map
(lambda (label cont)
(match cont
(($ $kargs _ _ ($ $continue _ _ ($ $call proc args)))
(intset-subtract (intset-add (list->intset args) proc)
(intmap-ref live-out label)))
(($ $kargs _ _ ($ $continue _ _ ($ $callk _ proc args)))
(intset-subtract (intset-add (list->intset args) proc)
(intmap-ref live-out label)))
(($ $kargs _ _ ($ $continue k _($ $values args)))
(match (intmap-ref cps k)
(($ $ktail) (list->intset args))
(_ #f)))
(_ #f)))
cps))
(kills (intmap-map
(lambda (label in)
(let* ((out (intmap-ref live-out label))
(killed (intset-subtract in out))
(killed-slots (intset-intersect killed needs-slot)))
(and (eq? killed-slots empty-intset)
;; Kill output variables that need slots.
(intset-intersect (intmap-ref defs label)
needs-slot))))
live-in))
(preds (invert-graph succs))
(old->new (compute-reverse-control-flow-order preds)))
(define (subtract lazy kill)
(cond
((eq? lazy empty-intset)
lazy)
((not kill)
empty-intset)
((and lazy (eq? empty-intset (intset-subtract kill lazy)))
(intset-subtract lazy kill))
(else
empty-intset)))
(define (add live gen) (or gen live))
(define (meet in out)
;; Initial in is #f.
(if in (intset-intersect in out) out))
(call-with-values
(lambda ()
(let ((succs (rename-graph preds old->new))
(init (persistent-intmap
(intmap-fold
(lambda (old new in)
(intmap-add! in new #f))
old->new empty-intmap)))
(kills (rename-keys kills old->new))
(gens (rename-keys gens old->new)))
(solve-flow-equations succs init init kills gens
subtract add meet)))
(lambda (in out)
;; A variable is lazy if its uses reach its definition.
(intmap-fold (lambda (label out lazy)
(match (intmap-ref cps label)
(($ $kargs names vars)
(let ((defs (list->intset vars)))
(intset-union lazy (intset-intersect out defs))))
(_ lazy)))
(rename-keys out (invert-bijection old->new))
empty-intset)))))
(define (find-first-zero n)
;; Naive implementation.
(let lp ((slot 0))
(if (logbit? slot n)
(lp (1+ slot))
slot)))
(define (find-first-trailing-zero n)
(let lp ((slot (let lp ((count 2))
(if (< n (ash 1 (1- count)))
count
;; Grow upper bound slower than factor 2 to avoid
;; needless bignum allocation on 32-bit systems
;; when there are more than 16 locals.
(lp (+ count (ash count -1)))))))
(if (or (zero? slot) (logbit? (1- slot) n))
slot
(lp (1- slot)))))
(define (integers from count)
(if (zero? count)
'()
(cons from (integers (1+ from) (1- count)))))
(define (solve-parallel-move src dst tmp)
"Solve the parallel move problem between src and dst slot lists, which
are comparable with eqv?. A tmp slot may be used."
;; This algorithm is taken from: "Tilting at windmills with Coq:
;; formal verification of a compilation algorithm for parallel moves"
;; by Laurence Rideau, Bernard Paul Serpette, and Xavier Leroy
;; <http://gallium.inria.fr/~xleroy/publi/parallel-move.pdf>
(define (split-move moves reg)
(let loop ((revhead '()) (tail moves))
(match tail
(((and s+d (s . d)) . rest)
(if (eqv? s reg)
(cons d (append-reverse revhead rest))
(loop (cons s+d revhead) rest)))
(_ #f))))
(define (replace-last-source reg moves)
(match moves
((moves ... (s . d))
(append moves (list (cons reg d))))))
(let loop ((to-move (map cons src dst))
(being-moved '())
(moved '())
(last-source #f))
;; 'last-source' should always be equivalent to:
;; (and (pair? being-moved) (car (last being-moved)))
(match being-moved
(() (match to-move
(() (reverse moved))
(((and s+d (s . d)) . t1)
(if (or (eqv? s d) ; idempotent
(not s)) ; src is a constant and can be loaded directly
(loop t1 '() moved #f)
(loop t1 (list s+d) moved s)))))
(((and s+d (s . d)) . b)
(match (split-move to-move d)
((r . t1) (loop t1 (acons d r being-moved) moved last-source))
(#f (match b
(() (loop to-move '() (cons s+d moved) #f))
(_ (if (eqv? d last-source)
(loop to-move
(replace-last-source tmp b)
(cons s+d (acons d tmp moved))
tmp)
(loop to-move b (cons s+d moved) last-source))))))))))
(define-inlinable (add-live-slot slot live-slots)
(logior live-slots (ash 1 slot)))
(define-inlinable (kill-dead-slot slot live-slots)
(logand live-slots (lognot (ash 1 slot))))
(define-inlinable (compute-slot live-slots hint)
(if (and hint (not (logbit? hint live-slots)))
hint
(find-first-zero live-slots)))
(define (compute-shuffles cps slots call-allocs live-in)
(define (get-cont label)
(intmap-ref cps label))
(define (get-slot var)
(intmap-ref slots var (lambda (_) #f)))
(define (get-slots vars)
(let lp ((vars vars))
(match vars
((var . vars) (cons (get-slot var) (lp vars)))
(_ '()))))
(define (get-proc-slot label)
(call-alloc-proc-slot (intmap-ref call-allocs label)))
(define (compute-live-slots label)
(intset-fold (lambda (var live)
(match (get-slot var)
(#f live)
(slot (add-live-slot slot live))))
(intmap-ref live-in label)
0))
;; Although some parallel moves may proceed without a temporary slot,
;; in general one is needed. That temporary slot must not be part of
;; the source or destination sets, and that slot should not correspond
;; to a live variable. Usually the source and destination sets are a
;; subset of the union of the live sets before and after the move.
;; However for stack slots that don't have names -- those slots that
;; correspond to function arguments or to function return values -- it
;; could be that they are out of the computed live set. In that case
;; they need to be adjoined to the live set, used when choosing a
;; temporary slot.
(define (compute-tmp-slot live stack-slots)
(find-first-zero (fold add-live-slot live stack-slots)))
(define (parallel-move src-slots dst-slots tmp-slot)
(solve-parallel-move src-slots dst-slots tmp-slot))
(define (compute-receive-shuffles label proc-slot)
(match (get-cont label)
(($ $kreceive arity kargs)
(let* ((results (match (get-cont kargs)
(($ $kargs names vars) vars)))
(value-slots (integers (1+ proc-slot) (length results)))
(result-slots (get-slots results))
;; Filter out unused results.
(value-slots (filter-map (lambda (val result) (and result val))
value-slots result-slots))
(result-slots (filter (lambda (x) x) result-slots))
(live (compute-live-slots kargs)))
(parallel-move value-slots
result-slots
(compute-tmp-slot live value-slots))))))
(define (add-call-shuffles label k args shuffles)
(match (get-cont k)
(($ $ktail)
(let* ((live (compute-live-slots label))
(tail-slots (integers 0 (length args)))
(moves (parallel-move (get-slots args)
tail-slots
(compute-tmp-slot live tail-slots))))
(intmap-add! shuffles label moves)))
(($ $kreceive)
(let* ((live (compute-live-slots label))
(proc-slot (get-proc-slot label))
(call-slots (integers proc-slot (length args)))
(arg-moves (parallel-move (get-slots args)
call-slots
(compute-tmp-slot live call-slots))))
(intmap-add! (intmap-add! shuffles label arg-moves)
k (compute-receive-shuffles k proc-slot))))))
(define (add-values-shuffles label k args shuffles)
(match (get-cont k)
(($ $ktail)
(let* ((live (compute-live-slots label))
(src-slots (get-slots args))
(dst-slots (integers 1 (length args)))
(moves (parallel-move src-slots dst-slots
(compute-tmp-slot live dst-slots))))
(intmap-add! shuffles label moves)))
(($ $kargs _ dst-vars)
(let* ((live (logior (compute-live-slots label)
(compute-live-slots k)))
(src-slots (get-slots args))
(dst-slots (get-slots dst-vars))
(moves (parallel-move src-slots dst-slots
(compute-tmp-slot live '()))))
(intmap-add! shuffles label moves)))))
(define (add-prompt-shuffles label k handler shuffles)
(intmap-add! shuffles handler
(compute-receive-shuffles handler (get-proc-slot label))))
(define (compute-shuffles label cont shuffles)
(match cont
(($ $kargs names vars ($ $continue k src exp))
(match exp
(($ $call proc args)
(add-call-shuffles label k (cons proc args) shuffles))
(($ $callk _ proc args)
(add-call-shuffles label k (cons proc args) shuffles))
(($ $values args)
(add-values-shuffles label k args shuffles))
(($ $prompt escape? tag handler)
(add-prompt-shuffles label k handler shuffles))
(_ shuffles)))
(_ shuffles)))
(persistent-intmap
(intmap-fold compute-shuffles cps empty-intmap)))
(define (compute-frame-size cps slots call-allocs shuffles)
;; Minimum frame has one slot: the closure.
(define minimum-frame-size 1)
(define (get-shuffles label)
(intmap-ref shuffles label))
(define (get-proc-slot label)
(match (intmap-ref call-allocs label (lambda (_) #f))
(#f 0) ;; Tail call.
(($ $call-alloc proc-slot) proc-slot)))
(define (max-size var size)
(match (intmap-ref slots var (lambda (_) #f))
(#f size)
(slot (max size (1+ slot)))))
(define (max-size* vars size)
(fold max-size size vars))
(define (shuffle-size moves size)
(match moves
(() size)
(((src . dst) . moves)
(shuffle-size moves (max size (1+ src) (1+ dst))))))
(define (call-size label nargs size)
(shuffle-size (get-shuffles label)
(max (+ (get-proc-slot label) nargs) size)))
(define (measure-cont label cont size)
(match cont
(($ $kargs names vars ($ $continue k src exp))
(let ((size (max-size* vars size)))
(match exp
(($ $call proc args)
(call-size label (1+ (length args)) size))
(($ $callk _ proc args)
(call-size label (1+ (length args)) size))
(($ $values args)
(shuffle-size (get-shuffles label) size))
(_ size))))
(($ $kreceive)
(shuffle-size (get-shuffles label) size))
(_ size)))
(intmap-fold measure-cont cps minimum-frame-size))
(define (allocate-args cps)
(intmap-fold (lambda (label cont slots)
(match cont
(($ $kfun src meta self)
(intmap-add! slots self 0))
(($ $kclause arity body alt)
(match (intmap-ref cps body)
(($ $kargs names vars)
(let lp ((vars vars) (slots slots) (n 1))
(match vars
(() slots)
((var . vars)
(lp vars
(intmap-add! slots var n)
(1+ n))))))))
(_ slots)))
cps empty-intmap))
(define (allocate-lazy-vars cps slots call-allocs live-in lazy)
(define (compute-live-slots slots label)
(intset-fold (lambda (var live)
(match (intmap-ref slots var (lambda (_) #f))
(#f live)
(slot (add-live-slot slot live))))
(intmap-ref live-in label)
0))
(define (allocate var hint slots live)
(match (and hint (intmap-ref slots var (lambda (_) #f)))
(#f (if (intset-ref lazy var)
(let ((slot (compute-slot live hint)))
(values (intmap-add! slots var slot)
(add-live-slot slot live)))
(values slots live)))
(slot (values slots (add-live-slot slot live)))))
(define (allocate* vars hints slots live)
(match (vector vars hints)
(#(() ()) slots)
(#((var . vars) (hint . hints))
(let-values (((slots live) (allocate var hint slots live)))
(allocate* vars hints slots live)))))
(define (get-proc-slot label)
(match (intmap-ref call-allocs label (lambda (_) #f))
(#f 0)
(call (call-alloc-proc-slot call))))
(define (allocate-call label args slots)
(allocate* args (integers (get-proc-slot label) (length args))
slots (compute-live-slots slots label)))
(define (allocate-values label k args slots)
(match (intmap-ref cps k)
(($ $ktail)
(allocate* args (integers 1 (length args))
slots (compute-live-slots slots label)))
(($ $kargs names vars)
(allocate* args
(map (cut intmap-ref slots <> (lambda (_) #f)) vars)
slots (compute-live-slots slots label)))))
(define (allocate-lazy label cont slots)
(match cont
(($ $kargs names vars ($ $continue k src exp))
(match exp
(($ $call proc args)
(allocate-call label (cons proc args) slots))
(($ $callk _ proc args)
(allocate-call label (cons proc args) slots))
(($ $values args)
(allocate-values label k args slots))
(_ slots)))
(_
slots)))
;; Sweep right to left to visit uses before definitions.
(persistent-intmap
(intmap-fold-right allocate-lazy cps slots)))
(define (compute-var-representations cps)
(define (get-defs k)
(match (intmap-ref cps k)
(($ $kargs names vars) vars)
(_ '())))
(intmap-fold
(lambda (label cont representations)
(match cont
(($ $kargs _ _ ($ $continue k _ exp))
(match (get-defs k)
(() representations)
((var)
(match exp
(($ $values (arg))
(intmap-add representations var
(intmap-ref representations arg)))
(($ $primcall (or 'scm->f64 'load-f64
'bv-f32-ref 'bv-f64-ref
'fadd 'fsub 'fmul 'fdiv))
(intmap-add representations var 'f64))
(($ $primcall (or 'scm->u64 'scm->u64/truncate 'load-u64
'char->integer
'bv-length 'vector-length 'string-length
'uadd 'usub 'umul
'ulogand 'ulogior 'ulogxor 'ulogsub 'ursh 'ulsh
'uadd/immediate 'usub/immediate 'umul/immediate
'ursh/immediate 'ulsh/immediate
'bv-u8-ref 'bv-u16-ref 'bv-u32-ref 'bv-u64-ref))
(intmap-add representations var 'u64))
(($ $primcall (or 'scm->s64 'load-s64
'bv-s8-ref 'bv-s16-ref 'bv-s32-ref 'bv-s64-ref))
(intmap-add representations var 's64))
(_
(intmap-add representations var 'scm))))
(vars
(match exp
(($ $values args)
(fold (lambda (arg var representations)
(intmap-add representations var
(intmap-ref representations arg)))
representations args vars))))))
(($ $kfun src meta self)
(intmap-add representations self 'scm))
(($ $kclause arity body alt)
(fold1 (lambda (var representations)
(intmap-add representations var 'scm))
(get-defs body) representations))
(($ $kreceive arity kargs)
(fold1 (lambda (var representations)
(intmap-add representations var 'scm))
(get-defs kargs) representations))
(($ $ktail) representations)))
cps
empty-intmap))
(define* (allocate-slots cps #:key (precolor-calls? #t))
(let*-values (((defs uses) (compute-defs-and-uses cps))
((representations) (compute-var-representations cps))
((live-in live-out) (compute-live-variables cps defs uses))
((constants) (compute-constant-values cps))
((needs-slot) (compute-needs-slot cps defs uses))
((lazy) (if precolor-calls?
(compute-lazy-vars cps live-in live-out defs
needs-slot)
empty-intset)))
(define (empty-live-slots)
#b0)
(define (compute-call-proc-slot live-slots)
(+ 2 (find-first-trailing-zero live-slots)))
(define (compute-prompt-handler-proc-slot live-slots)
(if (zero? live-slots)
0
(1- (find-first-trailing-zero live-slots))))
(define (get-cont label)
(intmap-ref cps label))
(define (get-slot slots var)
(intmap-ref slots var (lambda (_) #f)))
(define (get-slots slots vars)
(let lp ((vars vars))
(match vars
((var . vars) (cons (get-slot slots var) (lp vars)))
(_ '()))))
(define (compute-live-slots* slots label live-vars)
(intset-fold (lambda (var live)
(match (get-slot slots var)
(#f live)
(slot (add-live-slot slot live))))
(intmap-ref live-vars label)
0))
(define (compute-live-in-slots slots label)
(compute-live-slots* slots label live-in))
(define (compute-live-out-slots slots label)
(compute-live-slots* slots label live-out))
(define slot-desc-dead 0)
(define slot-desc-live-raw 1)
(define slot-desc-live-scm 2)
(define slot-desc-unused 3)
(define (compute-slot-map slots live-vars nslots)
(intset-fold
(lambda (var slot-map)
(match (get-slot slots var)
(#f slot-map)
(slot
(let ((desc (match (intmap-ref representations var)
((or 'u64 'f64 's64) slot-desc-live-raw)
('scm slot-desc-live-scm))))
(logior slot-map (ash desc (* 2 slot)))))))
live-vars 0))
(define (allocate var hint slots live)
(cond
((not (intset-ref needs-slot var))
(values slots live))
((get-slot slots var)
=> (lambda (slot)
(values slots (add-live-slot slot live))))
((and (not hint) (intset-ref lazy var))
(values slots live))
(else
(let ((slot (compute-slot live hint)))
(values (intmap-add! slots var slot)
(add-live-slot slot live))))))
(define (allocate* vars hints slots live)
(match (vector vars hints)
(#(() ()) (values slots live))
(#((var . vars) (hint . hints))
(call-with-values (lambda () (allocate var hint slots live))
(lambda (slots live)
(allocate* vars hints slots live))))))
(define (allocate-defs label vars slots)
(let ((live (compute-live-in-slots slots label))
(live-vars (intmap-ref live-in label)))
(let lp ((vars vars) (slots slots) (live live))
(match vars
(() (values slots live))
((var . vars)
(call-with-values (lambda () (allocate var #f slots live))
(lambda (slots live)
(lp vars slots
(let ((slot (get-slot slots var)))
(if (and slot (not (intset-ref live-vars var)))
(kill-dead-slot slot live)
live))))))))))
;; PRE-LIVE are the live slots coming into the term. POST-LIVE
;; is the subset of PRE-LIVE that is still live after the term
;; uses its inputs.
(define (allocate-call label k args slots call-allocs pre-live)
(match (get-cont k)
(($ $ktail)
(let ((tail-slots (integers 0 (length args))))
(values (allocate* args tail-slots slots pre-live)
call-allocs)))
(($ $kreceive arity kargs)
(let*-values
(((post-live) (compute-live-out-slots slots label))
((proc-slot) (compute-call-proc-slot post-live))
((call-slots) (integers proc-slot (length args)))
((slots pre-live) (allocate* args call-slots slots pre-live))
;; Allow the first result to be hinted by its use, but
;; hint the remaining results to stay in place. This
;; strikes a balance between avoiding shuffling,
;; especially for unused extra values, and avoiding frame
;; size growth due to sparse locals.
((slots result-live)
(match (get-cont kargs)
(($ $kargs () ())
(values slots post-live))
(($ $kargs (_ . _) (_ . results))
(let ((result-slots (integers (+ proc-slot 2)
(length results))))
(allocate* results result-slots slots post-live)))))
((slot-map) (compute-slot-map slots (intmap-ref live-out label)
(- proc-slot 2)))
((call) (make-call-alloc proc-slot slot-map)))
(values slots
(intmap-add! call-allocs label call))))))
(define (allocate-values label k args slots call-allocs)
(match (get-cont k)
(($ $ktail)
(values slots call-allocs))
(($ $kargs (_) (dst))
;; When there is only one value in play, we allow the dst to be
;; hinted (see compute-lazy-vars). If the src doesn't have a
;; slot, then the actual slot for the dst would end up being
;; decided by the call that args it. Because we don't know the
;; slot, we can't really compute the parallel moves in that
;; case, so just bail and rely on the bytecode emitter to
;; handle the one-value case specially.
(match args
((src)
(let ((post-live (compute-live-out-slots slots label)))
(values (allocate dst (get-slot slots src) slots post-live)
call-allocs)))))
(($ $kargs _ dst-vars)
(let ((src-slots (get-slots slots args))
(post-live (compute-live-out-slots slots label)))
(values (allocate* dst-vars src-slots slots post-live)
call-allocs)))))
(define (allocate-prompt label k handler slots call-allocs)
(match (get-cont handler)
(($ $kreceive arity kargs)
(let*-values
(((handler-live) (compute-live-in-slots slots handler))
((proc-slot) (compute-prompt-handler-proc-slot handler-live))
((slot-map) (compute-slot-map slots (intmap-ref live-in handler)
(- proc-slot 2)))
((result-vars) (match (get-cont kargs)
(($ $kargs names vars) vars)))
((value-slots) (integers (1+ proc-slot) (length result-vars)))
((slots result-live) (allocate* result-vars value-slots
slots handler-live)))
(values slots
(intmap-add! call-allocs label
(make-call-alloc proc-slot slot-map)))))))
(define (allocate-cont label cont slots call-allocs)
(match cont
(($ $kargs names vars ($ $continue k src exp))
(let-values (((slots live) (allocate-defs label vars slots)))
(match exp
(($ $call proc args)
(allocate-call label k (cons proc args) slots call-allocs live))
(($ $callk _ proc args)
(allocate-call label k (cons proc args) slots call-allocs live))
(($ $values args)
(allocate-values label k args slots call-allocs))
(($ $prompt escape? tag handler)
(allocate-prompt label k handler slots call-allocs))
(_
(values slots call-allocs)))))
(_
(values slots call-allocs))))
(call-with-values (lambda ()
(let ((slots (allocate-args cps)))
(intmap-fold allocate-cont cps slots empty-intmap)))
(lambda (slots calls)
(let* ((slots (allocate-lazy-vars cps slots calls live-in lazy))
(shuffles (compute-shuffles cps slots calls live-in))
(frame-size (compute-frame-size cps slots calls shuffles)))
(make-allocation slots representations constants calls
shuffles frame-size))))))
| true |
7f61afb506aa412966a8d5cfb720e315ac747d45 | e8e2b3f22c7e1921e99f44593fc0ba5e5e44eebb | /PortableApps/GnuCashPortable/App/GnuCash/share/gnucash/scm/qif-import/qif-to-gnc.scm | 519d6e90a35d9a7d5eaccb333d062b7b29a1c00b | []
| no_license | 314pi/PortableOffice | da262df5eaca240a00921e8348d366efa426ae57 | 08a5e828b35ff3cade7c56d101d7f6712b19a308 | refs/heads/master | 2022-11-25T19:20:33.942725 | 2018-05-11T07:49:35 | 2018-05-11T07:49:35 | 132,839,264 | 1 | 2 | null | 2022-11-02T22:19:00 | 2018-05-10T02:42:46 | Python | UTF-8 | Scheme | false | false | 54,672 | scm | qif-to-gnc.scm | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; qif-to-gnc.scm
;;; this is where QIF transactions are transformed into a
;;; Gnucash account tree.
;;;
;;; Copyright 2000-2001 Bill Gribble <[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 2 of
;; the License, or (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program; if not, contact:
;;
;; Free Software Foundation Voice: +1-617-542-5942
;; 51 Franklin Street, Fifth Floor Fax: +1-617-542-2652
;; Boston, MA 02110-1301, USA [email protected]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(use-modules (srfi srfi-13))
(use-modules (gnucash printf))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; qif-import:find-or-make-acct
;;
;; Given a colon-separated account path, return an Account* to
;; an existing or new account.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (qif-import:find-or-make-acct acct-info check-types? commodity
check-commodity? default-currency
gnc-acct-hash old-root new-root)
(let* ((sep (gnc-get-account-separator-string))
(gnc-name (qif-map-entry:gnc-name acct-info))
(existing-account (hash-ref gnc-acct-hash gnc-name))
(same-gnc-account
(gnc-account-lookup-by-full-name old-root gnc-name))
(allowed-types
(qif-map-entry:allowed-types acct-info))
(make-new-acct #f)
(incompatible-acct #f))
(define (compatible? account)
(let ((acc-type (xaccAccountGetType account))
(acc-commodity (xaccAccountGetCommodity account)))
(and
(if check-types?
(and (list? allowed-types)
(memv acc-type allowed-types))
#t)
(if check-commodity?
(gnc-commodity-equiv acc-commodity commodity)
#t))))
(define (make-unique-name-variant long-name short-name)
(if (not (null? (gnc-account-lookup-by-full-name old-root long-name)))
(let loop ((count 2))
(let* ((test-name
(string-append long-name (sprintf #f " %a" count)))
(test-acct
(gnc-account-lookup-by-full-name old-root test-name)))
(if (and (not (null? test-acct)) (not (compatible? test-acct)))
(loop (+ 1 count))
(string-append short-name (sprintf #f " %a" count)))))
short-name))
;; If a GnuCash account already exists in the old root with the same
;; name, that doesn't necessarily mean we can use it. The type and
;; commodity must be compatible.
(if (and same-gnc-account (not (null? same-gnc-account)))
(if (compatible? same-gnc-account)
(begin
;; The existing GnuCash account is compatible, so we
;; can use it. Make sure we use the same type.
(set! make-new-acct #f)
(set! incompatible-acct #f)
(set! allowed-types
(list (xaccAccountGetType same-gnc-account))))
(begin
;; There's an existing, incompatible account with that name,
;; so we have to make a new account with different properties
;; and a slightly different name.
(set! make-new-acct #t)
(set! incompatible-acct #t)))
(begin
;; Otherwise, there's no existing account with the same name.
(set! make-new-acct #t)
(set! incompatible-acct #f)))
;; here, existing-account means a previously *created* account
;; (possibly a new account, possibly a copy of an existing gnucash
;; acct)
(if (and (and existing-account (not (null? existing-account)))
(compatible? existing-account))
existing-account
(let ((new-acct (xaccMallocAccount (gnc-get-current-book)))
(parent-acct #f)
(parent-name #f)
(acct-name #f)
(last-sep #f))
;; This procedure returns a default account type. This could
;; be smarter, but at least it won't allow security account
;; types to be used on currency-denominated accounts.
(define (default-account-type allowed-types currency?)
(if (or (not allowed-types)
(null? allowed-types))
;; None of the allowed types are compatible.
;; Bug detected!
(throw 'bug
"qif-import:find-or-make-acct"
"No valid account types allowed for account ~A."
(list acct-name)
#f)
(if (memv (car allowed-types) (list GNC-STOCK-TYPE
GNC-MUTUAL-TYPE))
;; The type is incompatible with a currency.
(if currency?
(default-account-type (cdr allowed-types)
currency?)
(car allowed-types))
;; The type is compatible with a currency.
(if currency?
(car allowed-types)
(default-account-type (cdr allowed-types)
currency?)))))
(set! last-sep (gnc:string-rcontains gnc-name sep))
(xaccAccountBeginEdit new-acct)
;; if this is a copy of an existing gnc account, copy the
;; account properties. For incompatible existing accts,
;; we'll do something different later.
(if (and same-gnc-account (not (null? same-gnc-account)))
(begin
(xaccAccountSetName
new-acct (xaccAccountGetName same-gnc-account))
(xaccAccountSetDescription
new-acct (xaccAccountGetDescription same-gnc-account))
(xaccAccountSetType
new-acct (xaccAccountGetType same-gnc-account))
(xaccAccountSetCommodity
new-acct (xaccAccountGetCommodity same-gnc-account))
(xaccAccountSetNotes
new-acct (xaccAccountGetNotes same-gnc-account))
(xaccAccountSetColor
new-acct (xaccAccountGetColor same-gnc-account))
(xaccAccountSetCode
new-acct (xaccAccountGetCode same-gnc-account))))
;; If this is a nested account foo:bar:baz, make sure
;; that foo:bar and foo exist also.
(if last-sep
(begin
(set! parent-name (substring gnc-name 0 last-sep))
(set! acct-name (substring gnc-name (+ (string-length sep)
last-sep))))
(set! acct-name gnc-name))
;; If this is a completely new account (as opposed to a copy
;; of an existing account), use the parameters passed in.
(if make-new-acct
(begin
;; Set the name, description, and commodity.
(xaccAccountSetName new-acct acct-name)
(if (qif-map-entry:description acct-info)
(xaccAccountSetDescription
new-acct (qif-map-entry:description acct-info)))
(xaccAccountSetCommodity new-acct commodity)
;; If there was an existing, incompatible account with
;; the same name, set the new account name to be unique,
;; and set a description that hints at what's happened.
(if incompatible-acct
(let ((new-name (make-unique-name-variant
gnc-name acct-name)))
(xaccAccountSetName new-acct new-name)
(xaccAccountSetDescription
new-acct
(_ "QIF import: Name conflict with another account."))))
;; Set the account type.
(xaccAccountSetType new-acct
(default-account-type
(qif-map-entry:allowed-types acct-info)
(gnc-commodity-is-currency commodity)))))
(xaccAccountCommitEdit new-acct)
;; If a parent account is needed, find or make it.
(if last-sep
(let ((pinfo (make-qif-map-entry)))
(qif-map-entry:set-qif-name! pinfo parent-name)
(qif-map-entry:set-gnc-name! pinfo parent-name)
(qif-map-entry:set-allowed-types!
acct-info (list (xaccAccountGetType new-acct)))
(qif-map-entry:set-allowed-types!
pinfo (qif-map-entry:allowed-parent-types acct-info))
(set! parent-acct (qif-import:find-or-make-acct
pinfo #t default-currency #f default-currency
gnc-acct-hash old-root new-root))))
(if (and parent-acct (not (null? parent-acct)))
(gnc-account-append-child parent-acct new-acct)
(gnc-account-append-child new-root new-acct))
(hash-set! gnc-acct-hash gnc-name new-acct)
new-acct))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; qif-import:qif-to-gnc
;;
;; This is the top-level of the back end conversion from QIF
;; to GnuCash. All the account mappings and so on should be
;; done before this is called.
;;
;; This procedure returns:
;; success: the root of the imported tree
;; failure: a symbol indicating the reason
;; cancel: #t
;; bug: #f
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (qif-import:qif-to-gnc qif-files-list
qif-acct-map qif-cat-map
qif-memo-map stock-map
default-currency-name
transaction-status-pref
progress-dialog)
;; This procedure does all the work. We'll define it, then call it safely.
(define (private-convert)
(let* ((old-root (gnc-get-current-root-account))
(new-root (xaccMallocAccount (gnc-get-current-book)))
(gnc-acct-hash (make-hash-table 20))
(sep (gnc-get-account-separator-string))
(default-currency
(gnc-commodity-table-find-full
(gnc-commodity-table-get-table (gnc-get-current-book))
GNC_COMMODITY_NS_CURRENCY default-currency-name))
(sorted-accounts-list '())
(markable-xtns '())
(sorted-qif-files-list (sort qif-files-list
(lambda (a b)
(> (length (qif-file:xtns a))
(length (qif-file:xtns b))))))
(work-to-do 0)
(work-done 0))
;; This procedure handles progress reporting, pause, and cancel.
(define (update-progress)
(set! work-done (+ 1 work-done))
(if (and progress-dialog
(zero? (remainder work-done 8)))
(begin
(gnc-progress-dialog-set-value progress-dialog
(/ work-done work-to-do))
(qif-import:check-pause progress-dialog)
(if qif-import:canceled
(throw 'cancel)))))
(if progress-dialog
(gnc-progress-dialog-set-sub progress-dialog
(_ "Preparing to convert your QIF data")))
;; Build a list of all accounts to create for the import tree.
;; We need to iterate over the account, category, and payee/memo
;; mappings to build the list.
(hash-fold
(lambda (k v p)
(if (qif-map-entry:display? v)
(set! sorted-accounts-list
(cons v sorted-accounts-list)))
#t)
#t qif-acct-map)
(hash-fold
(lambda (k v p)
(if (qif-map-entry:display? v)
(set! sorted-accounts-list
(cons v sorted-accounts-list)))
#t)
#t qif-cat-map)
(hash-fold
(lambda (k v p)
(if (qif-map-entry:display? v)
(set! sorted-accounts-list
(cons v sorted-accounts-list)))
#t)
#t qif-memo-map)
(set! work-to-do (length sorted-accounts-list))
;; Before trying to mark transactions, prune down the list to
;; those that are transfers between QIF accounts.
(for-each
(lambda (qif-file)
(for-each
(lambda (xtn)
(set! work-to-do (+ 1 work-to-do))
(let splitloop ((splits (qif-xtn:splits xtn)))
(if (qif-split:category-is-account? (car splits))
(begin
(set! markable-xtns (cons xtn markable-xtns))
(set! work-to-do (+ 1 work-to-do)))
(if (not (null? (cdr splits)))
(splitloop (cdr splits))))))
(qif-file:xtns qif-file)))
qif-files-list)
;; Build a local account tree to hold converted transactions.
(if progress-dialog
(gnc-progress-dialog-set-sub progress-dialog
(_ "Creating accounts")))
;; Sort the account list on the depth of the account path. If a
;; short part is explicitly mentioned, make sure it gets created
;; before the deeper path that would create the parent accounts
;; without enough information about their type.
(set! sorted-accounts-list
(sort sorted-accounts-list
(lambda (a b)
(< (gnc:substring-count (qif-map-entry:gnc-name a)
sep)
(gnc:substring-count (qif-map-entry:gnc-name b)
sep)))))
;; Make all the accounts.
(for-each
(lambda (acctinfo)
(let* ((security
(and stock-map
(hash-ref stock-map
(qif-import:get-account-name
(qif-map-entry:qif-name acctinfo)))))
(ok-types (qif-map-entry:allowed-types acctinfo))
(equity? (memv GNC-EQUITY-TYPE ok-types))
(stock? (or (memv GNC-STOCK-TYPE ok-types)
(memv GNC-MUTUAL-TYPE ok-types))))
(update-progress)
(cond ((and equity? security) ;; a "retained holdings" acct
(qif-import:find-or-make-acct acctinfo #f
security #t
default-currency
gnc-acct-hash
old-root new-root))
((and security (or stock?
(gnc-commodity-is-currency security)))
(qif-import:find-or-make-acct
acctinfo #f security #t default-currency
gnc-acct-hash old-root new-root))
(#t
(qif-import:find-or-make-acct
acctinfo #f default-currency #t default-currency
gnc-acct-hash old-root new-root)))))
sorted-accounts-list)
;; Run through the markable transactions marking any
;; duplicates. marked transactions/splits won't get imported.
(if progress-dialog
(gnc-progress-dialog-set-sub progress-dialog
(_ "Matching transfers between accounts")))
(if (> (length markable-xtns) 1)
(let xloop ((xtn (car markable-xtns))
(rest (cdr markable-xtns)))
;; Update the progress.
(update-progress)
(if (not (qif-xtn:mark xtn))
(qif-import:mark-matching-xtns xtn rest))
(if (not (null? (cdr rest)))
(xloop (car rest) (cdr rest)))))
;; Iterate over files. Going in the sort order by number of
;; transactions should give us a small speed advantage.
(for-each
(lambda (qif-file)
(if progress-dialog
(gnc-progress-dialog-set-sub progress-dialog
(string-append (_ "Converting") " "
(qif-file:path qif-file))))
(for-each
(lambda (xtn)
;; Update the progress.
(update-progress)
(if (not (qif-xtn:mark xtn))
;; Convert into a GnuCash transaction.
(let ((gnc-xtn (xaccMallocTransaction
(gnc-get-current-book))))
(xaccTransBeginEdit gnc-xtn)
;; All accounts & splits are required to be in the
;; user-specified currency. Use it for the txn too.
(xaccTransSetCurrency gnc-xtn default-currency)
;; Build the transaction.
(qif-import:qif-xtn-to-gnc-xtn xtn qif-file gnc-xtn
gnc-acct-hash
qif-acct-map
qif-cat-map
qif-memo-map
transaction-status-pref
progress-dialog)
;; rebalance and commit everything
(xaccTransCommitEdit gnc-xtn))))
(qif-file:xtns qif-file)))
sorted-qif-files-list)
;; Finished.
(if progress-dialog
(gnc-progress-dialog-set-value progress-dialog 1))
new-root))
;; Safely convert the files and return the result.
(gnc:backtrace-if-exception
(lambda ()
(catch 'cancel
(lambda ()
(catch 'bad-date private-convert (lambda (key . args) key)))
(lambda (key . args) #t)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; qif-import:qif-xtn-to-gnc-xtn
;; translate a single transaction to a set of gnucash splits and
;; a gnucash transaction structure.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (qif-import:qif-xtn-to-gnc-xtn qif-xtn qif-file gnc-xtn
gnc-acct-hash
qif-acct-map qif-cat-map qif-memo-map
transaction-status-pref
progress-dialog)
(let ((splits (qif-xtn:splits qif-xtn))
(gnc-near-split (xaccMallocSplit (gnc-get-current-book)))
(near-split-total (gnc-numeric-zero))
(near-acct-info #f)
(near-acct-name #f)
(near-acct #f)
(qif-payee (qif-xtn:payee qif-xtn))
(qif-number (qif-xtn:number qif-xtn))
(qif-action (qif-xtn:action qif-xtn))
(qif-security (qif-xtn:security-name qif-xtn))
(qif-default-split (qif-xtn:default-split qif-xtn))
(qif-memo #f)
(qif-date (qif-xtn:date qif-xtn))
(qif-from-acct (qif-xtn:from-acct qif-xtn))
(qif-cleared (qif-xtn:cleared qif-xtn))
(n- (lambda (n) (gnc-numeric-neg n)))
(nsub (lambda (a b) (gnc-numeric-sub a b 0 GNC-DENOM-LCD)))
(n+ (lambda (a b) (gnc-numeric-add a b 0 GNC-DENOM-LCD)))
(n* (lambda (a b) (gnc-numeric-mul a b 0 GNC-DENOM-REDUCE)))
(n/ (lambda (a b) (gnc-numeric-div a b 0 GNC-DENOM-REDUCE))))
;; Set properties of the whole transaction.
;; Set the transaction date.
(cond
((not qif-date)
(qif-import:log progress-dialog
"qif-import:qif-xtn-to-gnc-xtn"
(_ "Missing transaction date."))
(throw 'bad-date
"qif-import:qif-xtn-to-gnc-xtn"
"Missing transaction date."
#f
#f))
(else
(apply xaccTransSetDate gnc-xtn (qif-xtn:date qif-xtn))))
;; fixme: bug #105
(if qif-payee
(xaccTransSetDescription gnc-xtn qif-payee))
(if qif-number
;; Use function that will set either tran-num or split-action per
;; book option.
(gnc-set-num-action gnc-xtn gnc-near-split qif-number #f))
;; Look for the transaction memo (QIF "M" line). When a default split
;; exists, the memo can be found there. Otherwise, it will be in the
;; first member of the splits list.
(if qif-default-split
(set! qif-memo (qif-split:memo qif-default-split))
(set! qif-memo (qif-split:memo (car (qif-xtn:splits qif-xtn)))))
(if qif-memo
(if (or (not qif-payee)
(equal? qif-payee ""))
(xaccTransSetDescription gnc-xtn qif-memo)
;; Use the memo for the transaction notes. Previously this went to
;; the debit/credit lines. See bug 495219 for more information.
(xaccTransSetNotes gnc-xtn qif-memo)))
;; Look for the transaction status (QIF "C" line). When it exists, apply
;; the cleared (c) or reconciled (y) status to the split. Otherwise, apply
;; user preference.
(if (eq? qif-cleared 'cleared)
(xaccSplitSetReconcile gnc-near-split #\c)
(if (eq? qif-cleared 'reconciled)
(xaccSplitSetReconcile gnc-near-split #\y)
;; Apply user preference by default.
(xaccSplitSetReconcile gnc-near-split transaction-status-pref)))
(if (not qif-security)
(begin
;; NON-STOCK TRANSACTIONS: the near account is the current
;; bank-account or the default associated with the file.
;; the far account is the one associated with the split
;; category.
(set! near-acct-info (hash-ref qif-acct-map qif-from-acct))
(set! near-acct-name (qif-map-entry:gnc-name near-acct-info))
(set! near-acct (hash-ref gnc-acct-hash near-acct-name))
;; iterate over QIF splits. Each split defines one "far
;; end" for the transaction.
(for-each
(lambda (qif-split)
(if (not (qif-split:mark qif-split))
(let ((gnc-far-split (xaccMallocSplit
(gnc-get-current-book)))
(far-acct-info #f)
(far-acct-name #f)
(far-acct #f)
(split-amt (qif-split:amount qif-split))
;; For split transactions, get this split's memo.
(memo
(if qif-default-split
(qif-split:memo qif-split) #f))
(cat (qif-split:category qif-split)))
(if (not split-amt) (set! split-amt (gnc-numeric-zero)))
;; fill the splits in (near first). This handles
;; files in multiple currencies by pulling the
;; currency value from the file import.
(set! near-split-total (n+ near-split-total split-amt))
(xaccSplitSetValue gnc-far-split (n- split-amt))
(xaccSplitSetAmount gnc-far-split (n- split-amt))
(if memo (xaccSplitSetMemo gnc-far-split memo))
;; figure out what the far acct is
(cond
;; If the category is an account, use the account mapping.
((and (not (string=? cat ""))
(qif-split:category-is-account? qif-split))
(set! far-acct-info (hash-ref qif-acct-map cat)))
;; Otherwise, if it isn't empty, use the category mapping.
((not (string=? cat ""))
(set! far-acct-info (hash-ref qif-cat-map cat)))
;; Otherwise, for non-split QIF transactions, try a payee
;; mapping, and if that doesn't work, try mapping the
;; transaction memo. For split transactions, map the memo
;; for this particular split line. If all else fails, use
;; the default category mapping (the Unspecified account,
;; unless the user has changed it).
(#t
(set! far-acct-info
(if (= (length splits) 1)
(or (and (string? qif-payee)
(not (string=? qif-payee ""))
(hash-ref qif-memo-map qif-payee))
(and (string? qif-memo)
(not (string=? qif-memo ""))
(hash-ref qif-memo-map qif-memo)))
(and (string? memo)
(not (string=? memo ""))
(hash-ref qif-memo-map memo))))
(if (not far-acct-info)
(set! far-acct-info (hash-ref qif-cat-map cat)))))
(set! far-acct-name (qif-map-entry:gnc-name far-acct-info))
(set! far-acct (hash-ref gnc-acct-hash far-acct-name))
;; set the reconcile status.
(let ((cleared (qif-split:matching-cleared qif-split)))
(if (eq? 'cleared cleared)
(xaccSplitSetReconcile gnc-far-split #\c))
(if (eq? 'reconciled cleared)
(xaccSplitSetReconcile gnc-far-split #\y)))
;; finally, plug the split into the account
(xaccSplitSetAccount gnc-far-split far-acct)
(xaccSplitSetParent gnc-far-split gnc-xtn))))
splits)
;; the value of the near split is the total of the far splits.
(xaccSplitSetValue gnc-near-split near-split-total)
(xaccSplitSetAmount gnc-near-split near-split-total)
(xaccSplitSetParent gnc-near-split gnc-xtn)
(xaccSplitSetAccount gnc-near-split near-acct))
;; STOCK TRANSACTIONS: the near/far accounts depend on the
;; "action" encoded in the Number field. It's generally the
;; security account (for buys, sells, and reinvests) but can
;; also be an interest, dividend, or SG/LG account.
(let* ((share-price (qif-xtn:share-price qif-xtn))
(num-shares (qif-xtn:num-shares qif-xtn))
(split-amt #f)
(xtn-amt (qif-split:amount (car (qif-xtn:splits qif-xtn))))
(qif-accts #f)
(qif-near-acct #f)
(qif-far-acct #f)
(qif-commission-acct #f)
(far-acct-info #f)
(far-acct-name #f)
(far-acct #f)
(commission-acct #f)
(commission-amt (qif-xtn:commission qif-xtn))
(commission-split #f)
(gnc-far-split (xaccMallocSplit (gnc-get-current-book))))
(if (not num-shares) (set! num-shares (gnc-numeric-zero)))
;; Determine the extended price of all shares without commission.
(if xtn-amt
;; Adjust for commission (if any).
(if commission-amt
(case qif-action
((sell sellx shrsout)
(set! split-amt (n+ xtn-amt commission-amt)))
(else
(set! split-amt (nsub xtn-amt commission-amt))))
(set! split-amt xtn-amt))
;; There's no grand total available.
(if share-price
;; Use the given share price, despite possible rounding.
(set! split-amt (n* num-shares share-price))
(set! split-amt (gnc-numeric-zero))))
;; Determine the share price.
(if (not share-price)
(set! share-price (gnc-numeric-zero))
(if (and xtn-amt (not (gnc-numeric-zero-p num-shares)))
;; There's a share price but it could be imprecise
;; enough to cause rounding. We can compute a better
;; share price ourselves. For more information, see
;; bug 373584.
(set! share-price (n/ split-amt num-shares))))
;; I don't think this should ever happen, but I want
;; to keep this check just in case.
(if (> (length splits) 1)
(gnc:warn "qif-import:qif-xtn-to-gnc-xtn: "
"splits in stock transaction!"))
(set! qif-accts
(qif-split:accounts-affected (car (qif-xtn:splits qif-xtn))
qif-xtn))
(set! qif-near-acct (car qif-accts))
(set! qif-far-acct (cadr qif-accts))
(set! qif-commission-acct (caddr qif-accts))
;; Translate the QIF account names into GnuCash accounts.
(if (and qif-near-acct qif-far-acct)
(begin
;; Determine the near account.
(set! near-acct-info
(or (hash-ref qif-acct-map qif-near-acct)
(hash-ref qif-cat-map qif-near-acct)))
(set! near-acct-name (qif-map-entry:gnc-name near-acct-info))
(set! near-acct (hash-ref gnc-acct-hash near-acct-name))
;; Determine the far account.
(if (or (not (string? qif-far-acct))
(string=? qif-far-acct ""))
;; No far account name is specified, so try a
;; payee or memo mapping to get a default.
(set! far-acct-info
(or (hash-ref qif-memo-map (qif-xtn:payee qif-xtn))
(hash-ref qif-memo-map
(qif-split:memo
(car (qif-xtn:splits qif-xtn)))))))
(if (not far-acct-info)
(set! far-acct-info
(or (hash-ref qif-acct-map qif-far-acct)
(hash-ref qif-cat-map qif-far-acct))))
(set! far-acct-name (qif-map-entry:gnc-name far-acct-info))
(set! far-acct (hash-ref gnc-acct-hash far-acct-name))))
;; the amounts and signs: are shares going in or out?
;; are amounts currency or shares?
(case qif-action
((buy buyx reinvint reinvdiv reinvsg reinvsh reinvmd reinvlg)
(if (not share-price) (set! share-price (gnc-numeric-zero)))
(xaccSplitSetAmount gnc-near-split num-shares)
(xaccSplitSetValue gnc-near-split split-amt)
(xaccSplitSetValue gnc-far-split (n- xtn-amt))
(xaccSplitSetAmount gnc-far-split (n- xtn-amt)))
((sell sellx)
(if (not share-price) (set! share-price (gnc-numeric-zero)))
(xaccSplitSetAmount gnc-near-split (n- num-shares))
(xaccSplitSetValue gnc-near-split (n- split-amt))
(xaccSplitSetValue gnc-far-split xtn-amt)
(xaccSplitSetAmount gnc-far-split xtn-amt))
((cgshort cgshortx cgmid cgmidx cglong cglongx intinc intincx
div divx miscinc miscincx xin rtrncap rtrncapx)
(xaccSplitSetValue gnc-near-split xtn-amt)
(xaccSplitSetAmount gnc-near-split xtn-amt)
(xaccSplitSetValue gnc-far-split (n- xtn-amt))
(xaccSplitSetAmount gnc-far-split (n- xtn-amt)))
((xout miscexp miscexpx margint margintx)
(xaccSplitSetValue gnc-near-split (n- xtn-amt))
(xaccSplitSetAmount gnc-near-split (n- xtn-amt))
(xaccSplitSetValue gnc-far-split xtn-amt)
(xaccSplitSetAmount gnc-far-split xtn-amt))
((shrsin)
;; getting rid of the old equity-acct-per-stock trick.
;; you must now have a cash/basis value for the stock.
(xaccSplitSetAmount gnc-near-split num-shares)
(xaccSplitSetValue gnc-near-split split-amt)
(xaccSplitSetValue gnc-far-split (n- xtn-amt))
(xaccSplitSetAmount gnc-far-split (n- xtn-amt)))
((shrsout)
;; shrsout is like shrsin
(xaccSplitSetAmount gnc-near-split (n- num-shares))
(xaccSplitSetValue gnc-near-split (n- split-amt))
(xaccSplitSetValue gnc-far-split xtn-amt)
(xaccSplitSetAmount gnc-far-split xtn-amt))
;; stock splits: QIF just specifies the split ratio, not
;; the number of shares in and out, so we have to fetch
;; the number of shares from the security account
;; FIXME : this could be wrong. Make sure the
;; share-amount is at the correct time.
((stksplit)
(let* ((splitratio (n/ num-shares (gnc-numeric-create 10 1)))
(in-shares
(xaccAccountGetBalance near-acct))
(out-shares (n* in-shares splitratio)))
(xaccSplitSetAmount gnc-near-split out-shares)
(xaccSplitSetAmount gnc-far-split (n- in-shares))
(xaccSplitSetValue gnc-near-split (n- split-amt))
(xaccSplitSetValue gnc-far-split split-amt))))
(let ((cleared (qif-split:matching-cleared
(car (qif-xtn:splits qif-xtn)))))
(if (eq? 'cleared cleared)
(xaccSplitSetReconcile gnc-far-split #\c))
(if (eq? 'reconciled cleared)
(xaccSplitSetReconcile gnc-far-split #\y)))
(if qif-commission-acct
(let* ((commission-acct-info
(or (hash-ref qif-acct-map qif-commission-acct)
(hash-ref qif-cat-map qif-commission-acct)))
(commission-acct-name
(and commission-acct-info
(qif-map-entry:gnc-name commission-acct-info))))
(if commission-acct-name
(set! commission-acct
(hash-ref gnc-acct-hash commission-acct-name)))))
(if (and commission-amt commission-acct)
(begin
(set! commission-split (xaccMallocSplit
(gnc-get-current-book)))
(xaccSplitSetValue commission-split commission-amt)
(xaccSplitSetAmount commission-split commission-amt)))
(if (and qif-near-acct qif-far-acct)
(begin
(xaccSplitSetParent gnc-near-split gnc-xtn)
(xaccSplitSetAccount gnc-near-split near-acct)
(xaccSplitSetParent gnc-far-split gnc-xtn)
(xaccSplitSetAccount gnc-far-split far-acct)
(if commission-split
(begin
(xaccSplitSetParent commission-split gnc-xtn)
(xaccSplitSetAccount commission-split
commission-acct)))))))
;; QIF indicates a void transaction by starting the payee with "**VOID**".
(if (and (string? qif-payee)
(string-prefix? "**VOID**" qif-payee))
(xaccTransVoid gnc-xtn "QIF"))
;; return the modified transaction (though it's ignored).
gnc-xtn))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; qif-import:mark-matching-xtns
;; find transactions that are the "opposite half" of xtn and
;; mark them so they won't be imported.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (qif-import:mark-matching-xtns xtn candidate-xtns)
(let splitloop ((splits-left (qif-xtn:splits xtn)))
;; splits-left starts out as all the splits of this transaction.
;; if multiple splits match up with a single split on the other
;; end, we may remove more than one split from splits-left with
;; each call to mark-some-splits.
(if (not (null? splits-left))
(if (and (not (qif-split:mark (car splits-left)))
(qif-split:category-is-account? (car splits-left)))
(set! splits-left
(qif-import:mark-some-splits
splits-left xtn candidate-xtns))
(set! splits-left (cdr splits-left))))
(if (not (null? splits-left))
(splitloop splits-left))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; qif-import:mark-some-splits
;; find split(s) matching elements of splits and mark them so they
;; don't get imported.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (qif-import:mark-some-splits splits xtn candidate-xtns)
(let* ((n- (lambda (n) (gnc-numeric-neg n)))
(nsub (lambda (a b) (gnc-numeric-sub a b 0 GNC-DENOM-LCD)))
(n+ (lambda (a b) (gnc-numeric-add a b 0 GNC-DENOM-LCD)))
(n* (lambda (a b) (gnc-numeric-mul a b 0 GNC-DENOM-REDUCE)))
(n/ (lambda (a b) (gnc-numeric-div a b 0 GNC-DENOM-REDUCE)))
(split (car splits))
(near-acct-name #f)
(far-acct-name #f)
(date (qif-xtn:date xtn))
(amount (n- (qif-split:amount split)))
(group-amount #f)
(security-name (qif-xtn:security-name xtn))
(action (qif-xtn:action xtn))
(bank-xtn? (not security-name))
(different-acct-splits '())
(same-acct-splits '())
(how #f)
(done #f))
(if bank-xtn?
(begin
(set! near-acct-name (qif-xtn:from-acct xtn))
(set! far-acct-name (qif-split:category split))
(set! group-amount (gnc-numeric-zero))
;; group-amount is the sum of all the splits in this xtn
;; going to the same account as 'split'. We might be able
;; to match this whole group to a single matching opposite
;; split.
(for-each
(lambda (s)
(if (and (qif-split:category-is-account? s)
(string=? far-acct-name (qif-split:category s)))
(begin
(set! same-acct-splits
(cons s same-acct-splits))
(set! group-amount (nsub group-amount (qif-split:amount s))))
(set! different-acct-splits
(cons s different-acct-splits))))
splits)
(set! same-acct-splits (reverse same-acct-splits))
(set! different-acct-splits (reverse different-acct-splits)))
;; stock transactions. they can't have splits as far as I can
;; tell, so the 'different-acct-splits' is always '()
(let ((qif-accts
(qif-split:accounts-affected split xtn)))
(set! near-acct-name (car qif-accts))
(set! far-acct-name (cadr qif-accts))
(set! same-acct-splits (list split))
(if action
;; we need to do some special massaging to get
;; transactions to match up. Quicken thinks the near
;; and far accounts are different than we do.
(case action
((intincx divx cglongx cgmidx cgshortx rtrncapx margintx
sellx)
(set! amount (n- amount))
(set! near-acct-name (qif-xtn:from-acct xtn))
(set! far-acct-name (qif-split:category split)))
((miscincx miscexpx)
(set! amount (n- amount))
(set! near-acct-name (qif-xtn:from-acct xtn))
(set! far-acct-name (qif-split:miscx-category split)))
((buyx)
(set! near-acct-name (qif-xtn:from-acct xtn))
(set! far-acct-name (qif-split:category split)))
((xout)
(set! amount (n- amount)))))))
;; this is the grind loop. Go over every unmarked transaction in
;; the candidate-xtns list.
(let xtn-loop ((xtns candidate-xtns))
(if (and (not (qif-xtn:mark (car xtns)))
(string=? (qif-xtn:from-acct (car xtns)) far-acct-name))
(begin
(set! how
(qif-import:xtn-has-matches? (car xtns) near-acct-name
date amount group-amount))
(if how
(begin
(qif-import:merge-and-mark-xtns xtn same-acct-splits
(car xtns) how)
(set! done #t)))))
;; iterate with the next transaction
(if (and (not done)
(not (null? (cdr xtns))))
(xtn-loop (cdr xtns))))
;; return the rest of the splits to iterate on
(if (not how)
(cdr splits)
(case (car how)
((one-to-one many-to-one)
(cdr splits))
((one-to-many)
different-acct-splits)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; qif-import:xtn-has-matches?
;; check for one-to-one, many-to-one, one-to-many split matches.
;; returns either #f (no match) or a cons cell with the car being one
;; of 'one-to-one 'one-to-many 'many-to-one, the cdr being a list of
;; splits that were part of the matching group.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (qif-import:xtn-has-matches? xtn acct-name date amount group-amt)
(let ((same-acct-splits '())
(this-group-amt (gnc-numeric-zero))
(how #f)
(date-matches
(let ((self-date (qif-xtn:date xtn)))
(and (pair? self-date)
(pair? date)
(eq? (length self-date) 3)
(eq? (length date) 3)
(= (car self-date) (car date))
(= (cadr self-date) (cadr date))
(= (caddr self-date) (caddr date)))))
(n- (lambda (n) (gnc-numeric-neg n)))
(nsub (lambda (a b) (gnc-numeric-sub a b 0 GNC-DENOM-LCD)))
(n+ (lambda (a b) (gnc-numeric-add a b 0 GNC-DENOM-LCD)))
(n* (lambda (a b) (gnc-numeric-mul a b 0 GNC-DENOM-REDUCE)))
(n/ (lambda (a b) (gnc-numeric-div a b 0 GNC-DENOM-REDUCE))))
(if date-matches
(begin
;; calculate a group total for splits going to acct-name
(let split-loop ((splits-left (qif-xtn:splits xtn)))
(let ((split (car splits-left)))
;; does the account match up?
(if (and (qif-split:category-is-account? split)
(string? acct-name)
(string=? (qif-split:category split) acct-name))
;; if so, get the amount
(let ((this-amt (qif-split:amount split))
(stock-xtn (qif-xtn:security-name xtn))
(action (qif-xtn:action xtn)))
;; need to change the sign of the amount for some
;; stock transactions (buy/sell both positive in
;; QIF)
(if (and stock-xtn action)
(case action
((xout sellx intincx divx cglongx cgshortx
miscincx miscexpx)
(set! this-amt (n- this-amt)))))
;; we might be done if this-amt is either equal
;; to the split amount or the group amount.
(cond
((gnc-numeric-equal this-amt amount)
(set! how
(cons 'one-to-one (list split))))
((and group-amt (gnc-numeric-equal this-amt group-amt))
(set! how
(cons 'one-to-many (list split))))
(#t
(set! same-acct-splits (cons split same-acct-splits))
(set! this-group-amt
(n+ this-group-amt this-amt))))))
;; if 'how' is non-#f, we are ready to return.
(if (and (not how)
(not (null? (cdr splits-left))))
(split-loop (cdr splits-left)))))
;; now we're out of the loop. if 'how' isn't set,
;; we can still have a many-to-one match.
(if (and (not how)
(gnc-numeric-equal this-group-amt amount))
(set! how (cons 'many-to-one same-acct-splits)))))
;; we're all done. 'how' either is #f or a
;; cons of the way-it-matched and a list of the matching
;; splits.
how))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; (qif-split:accounts-affected split xtn)
;; Get the near and far ends of a split, returned as a list
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (qif-split:accounts-affected split xtn)
(let ((near-acct-name #f)
(far-acct-name #f)
(commission-acct-name #f)
(security (qif-xtn:security-name xtn))
(action (qif-xtn:action xtn))
(from-acct (qif-xtn:from-acct xtn)))
;; for non-security transactions, the near account is the
;; acct in which the xtn is, and the far is the account
;; linked by the category line.
(if (not security)
;; non-security transactions
(begin
(set! near-acct-name from-acct)
(set! far-acct-name (qif-split:category split)))
;; security transactions : the near end is either the
;; brokerage, the stock, or the category
(begin
(case action
((buy buyx sell sellx reinvint reinvdiv reinvsg reinvsh
reinvlg reinvmd shrsin shrsout stksplit)
(set! near-acct-name (default-stock-acct from-acct security)))
((div cgshort cglong cgmid intinc miscinc miscexp
rtrncap margint xin xout)
(set! near-acct-name from-acct))
((divx cgshortx cglongx cgmidx intincx rtrncapx margintx)
(set! near-acct-name
(qif-split:category (car (qif-xtn:splits xtn)))))
((miscincx miscexpx)
(set! near-acct-name
(qif-split:miscx-category (car (qif-xtn:splits xtn))))))
;; the far split: where is the money coming from?
;; Either the brokerage account, the category,
;; or an external account
(case action
((buy sell)
(set! far-acct-name from-acct))
((buyx sellx miscinc miscincx miscexp miscexpx xin xout)
(set! far-acct-name
(qif-split:category (car (qif-xtn:splits xtn)))))
((stksplit)
(set! far-acct-name (default-stock-acct from-acct security)))
((cgshort cgshortx reinvsg reinvsh)
(set! far-acct-name
(default-cgshort-acct from-acct security)))
((cglong cglongx reinvlg)
(set! far-acct-name
(default-cglong-acct from-acct security)))
((cgmid cgmidx reinvmd)
(set! far-acct-name
(default-cgmid-acct from-acct security)))
((intinc intincx reinvint)
(set! far-acct-name
(default-interest-acct from-acct security)))
((margint margintx)
(set! far-acct-name
(default-margin-interest-acct from-acct)))
((rtrncap rtrncapx)
(set! far-acct-name
(default-capital-return-acct from-acct security)))
((div divx reinvdiv)
(set! far-acct-name
(default-dividend-acct from-acct security)))
((shrsin shrsout)
(set! far-acct-name
(default-equity-holding security))))
;; the commission account, if it exists
(if (qif-xtn:commission xtn)
(set! commission-acct-name
(default-commission-acct from-acct)))))
(list near-acct-name far-acct-name commission-acct-name)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; qif-import:merge-and-mark-xtns
;; we know that the splits match. Pick one to mark and
;; merge the information into the other one.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (qif-import:merge-and-mark-xtns xtn splits other-xtn how)
;; merge transaction fields
(let ((action (qif-xtn:action xtn))
(o-action (qif-xtn:action other-xtn))
(security (qif-xtn:security-name xtn))
(o-security (qif-xtn:security-name other-xtn))
(split (car splits))
(match-type (car how))
(match-splits (cdr how)))
(case match-type
;; many-to-one: the other-xtn has several splits that total
;; in amount to 'split'. We want to preserve the multi-split
;; transaction.
((many-to-one)
(qif-xtn:mark-split xtn split)
(qif-import:merge-xtn-info xtn other-xtn)
(for-each
(lambda (s)
(qif-split:set-matching-cleared! s (qif-xtn:cleared xtn)))
match-splits))
;; one-to-many: 'split' is just one of a set of splits in xtn
;; that total up to the split in match-splits.
((one-to-many)
(qif-xtn:mark-split other-xtn (car match-splits))
(qif-import:merge-xtn-info other-xtn xtn)
(for-each
(lambda (s)
(qif-split:set-matching-cleared!
s (qif-xtn:cleared other-xtn)))
splits))
;; otherwise: one-to-one, a normal single split match.
(else
(cond
;; If one transaction has more splits than the other, mark the
;; one with less splits, regardless of all other conditions.
;; Otherwise, QIF split transactions will become mangled. For
;; more information, see bug 114724.
((< (length (qif-xtn:splits xtn))
(length (qif-xtn:splits other-xtn)))
(qif-xtn:mark-split xtn split)
(qif-import:merge-xtn-info xtn other-xtn)
(qif-split:set-matching-cleared!
(car match-splits) (qif-xtn:cleared xtn)))
((> (length (qif-xtn:splits xtn))
(length (qif-xtn:splits other-xtn)))
(qif-xtn:mark-split other-xtn (car match-splits))
(qif-import:merge-xtn-info other-xtn xtn)
(qif-split:set-matching-cleared!
split (qif-xtn:cleared other-xtn)))
;; this is a transfer involving a security xtn. Let the
;; security xtn dominate the way it's handled.
((and (not action) o-action o-security)
(qif-xtn:mark-split xtn split)
(qif-import:merge-xtn-info xtn other-xtn)
(qif-split:set-matching-cleared!
(car match-splits) (qif-xtn:cleared xtn)))
((and action (not o-action) security)
(qif-xtn:mark-split other-xtn (car match-splits))
(qif-import:merge-xtn-info other-xtn xtn)
(qif-split:set-matching-cleared!
split (qif-xtn:cleared other-xtn)))
;; this is a security transaction from one brokerage to another
;; or within a brokerage. The "foox" xtn has the most
;; information about what went on, so use it.
((and action o-action o-security)
(case o-action
((buyx sellx cgshortx cgmidx cglongx intincx divx
margintx rtrncapx miscincx miscexpx)
(qif-xtn:mark-split xtn split)
(qif-import:merge-xtn-info xtn other-xtn)
(qif-split:set-matching-cleared!
(car match-splits) (qif-xtn:cleared xtn)))
(else
(qif-xtn:mark-split other-xtn (car match-splits))
(qif-import:merge-xtn-info other-xtn xtn)
(qif-split:set-matching-cleared!
split (qif-xtn:cleared other-xtn)))))
;; Otherwise, this is a normal no-frills split match.
(#t
(qif-xtn:mark-split other-xtn (car match-splits))
(qif-import:merge-xtn-info other-xtn xtn)
(qif-split:set-matching-cleared!
split (qif-xtn:cleared other-xtn))))))))
(define (qif-import:merge-xtn-info from-xtn to-xtn)
(if (and (qif-xtn:payee from-xtn)
(not (qif-xtn:payee to-xtn)))
(qif-xtn:set-payee! to-xtn (qif-xtn:payee from-xtn)))
(if (and (qif-xtn:address from-xtn)
(not (qif-xtn:address to-xtn)))
(qif-xtn:set-address! to-xtn (qif-xtn:address from-xtn)))
(if (and (qif-xtn:number from-xtn)
(not (qif-xtn:number to-xtn)))
(qif-xtn:set-number! to-xtn (qif-xtn:number from-xtn))))
(define (qif-xtn:mark-split xtn split)
(qif-split:set-mark! split #t)
(let ((all-marked #t))
(let loop ((splits (qif-xtn:splits xtn)))
(if (not (qif-split:mark (car splits)))
(set! all-marked #f)
(if (not (null? (cdr splits)))
(loop (cdr splits)))))
(if all-marked
(qif-xtn:set-mark! xtn #t))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; qif-import:qif-to-gnc-undo
;;
;; Cancel the import by removing all newly created accounts,
;; splits, and transactions.
;;
;; NOTE: Any new commodities should be destroyed by the druid.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (qif-import:qif-to-gnc-undo root)
(if root
(let ((txns (gnc:account-tree-get-transactions root)))
;; Destroy all the transactions and their splits.
(for-each (lambda (elt) (xaccTransDestroy elt)) txns)
;; Destroy the accounts
(xaccAccountBeginEdit root)
(xaccAccountDestroy root))))
| false |
bc1fc663732d5180478073c56194ee1ee0164f4b | 8a0660bd8d588f94aa429050bb8d32c9cd4290d5 | /ext/ffi/win32/defs.scm | 05a981788cafcc5fdc84302800e2547ae74e920e | [
"BSD-2-Clause"
]
| permissive | david135/sagittarius-scheme | dbec76f6b227f79713169985fc16ce763c889472 | 2fbd9d153c82e2aa342bfddd59ed54d43c5a7506 | refs/heads/master | 2016-09-02T02:44:31.668025 | 2013-12-21T07:24:08 | 2013-12-21T07:24:08 | 32,497,456 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 6,348 | scm | defs.scm | ;;; -*- mode: scheme; coding: utf-8; -*-
;;;
;;; defs.scm - Win32 API basic typedefs
;;;
;;; Copyright (c) 2000-2011 Takashi Kato <[email protected]>
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; 2. Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
;; based on Cygwin's windef.h
(library (win32 defs)
(export BOOL PBOOL LPBOOL
BYTE PBYTE LPBYTE
CHAR PCHAR LPCH PCH NPSTR LPSTR PSTR
LPCCH PCSTR LPCSTR
LPWSTR LPCWSTR
WORD PWORD LPWORD
SHORT PSHORT
HALF_PTR PHALF_PTR UHALF_PTR PUHALF_PTR
FLOAT PFLOAT
INT PINT LPINT UINT PUINT LPUINT
INT_PTR PINT_PTR UINT_PTR PUINT_PTR
DWORD PDWORD LPDWORD
LPVOID PCVOID LPCVOID
LONG PLONG LONG_PTR PLONG_PTR ULONG_PTR PULONG_PTR
SIZE_T PSIZE_T SSIZE_T PSSIZE_T
DWORD_PTR PDWORD_PTR LONG64 PLONG64
INT64 PINT64 ULONG64 PULONG64
UINT64 PUINT64 DWORD64 PDWORD64
WPARAM LPARAM LRESULT LONG
ATOM
HANDLE HHOOK HGLOBAL GLOBALHANDLE LOCALHANDLE
HGDIOBJ HACCEL HBITMAP HBRUSH HCOLORSPACE
HDC HGLOBAL HDESK HENHMETAFILE HFONT HICON HKEY
PHKEY HMENU HMETAFILE HINSTANCE HMODULE
HPALETTE HPEN HRGN HRSRC HSTR HTASK
HWND HWINSTA HKL HFILE HCURSOR COLORREF
FARPROC NEARPROC PROC
;; structs
RECT PRECT LPRECT LPCRECT
RECTL PRECTL LPRECTL LPCRECTL
POINT PPOINT LPPOINT
POINTL PPOINTL LPPOINTL
SIZE PSIZE LPSIZE
SIZEL PSIZEL LPSIZEL
POINTS PPOINTS LPPOINTS)
(import (core)
(sagittarius ffi))
;; bool
(define-c-typedef bool BOOL (* PBOOL) (* LPBOOL))
;; byte
(define-c-typedef uint8_t BYTE (* PBYTE) (* LPBYTE))
;; char
(define-c-typedef char
CHAR
(s* PCHAR) (s* LPCH) (s* PCH) (s* NPSTR) (s* LPSTR)
(s* PSTR) (s* LPCCH) (s* PCSTR) (s* LPCSTR))
;; wchar_t
(define-c-typedef wchar_t* LPWSTR LPCWSTR)
;; short
(define-c-typedef unsigned-short WORD (* PWORD) (* LPWORD))
(define-c-typedef short SHORT (* PSHORT))
(define-c-typedef void* HALF_PTR (* PHALF_PTR))
(define-c-typedef void* UHALF_PTR (* PUHALF_PTR))
;; float
(define-c-typedef float FLOAT (* PFLOAT))
;; int
(define-c-typedef int INT (* PINT) (* LPINT))
(define-c-typedef unsigned-int UINT (* PUINT) (* LPUINT))
(define-c-typedef void* INT_PTR (* PINT_PTR))
(define-c-typedef unsigned-int UINT_PTR (* PUINT_PTR))
;; dword
(define-c-typedef unsigned-long DWORD (* PDWORD) (* LPDWORD))
;; VOID
(define-c-typedef void* (* LPVOID) (* PCVOID) (LPCVOID))
;; long
(define-c-typedef long LONG (* PLONG))
(define-c-typedef void* LONG_PTR (* PLONG_PTR))
(define-c-typedef unsigned-long ULONG_PTR (* PULONG_PTR))
(define-c-typedef unsigned-long HANDLE_PTR)
(define-c-typedef ULONG_PTR SIZE_T (* PSIZE_T))
(define-c-typedef LONG_PTR SSIZE_T (* PSSIZE_T))
(define-c-typedef ULONG_PTR DWORD_PTR (* PDWORD_PTR))
(define-c-typedef int64_t LONG64 (* PLONG64))
(define-c-typedef int64_t INT64 (* PINT64))
(define-c-typedef uint64_t ULONG64 (* PULONG64))
(define-c-typedef uint64_t UINT64 (* PUINT64))
(define-c-typedef uint64_t DWORD64 (* PDWORD64))
(define-c-typedef UINT_PTR WPARAM)
(define-c-typedef LONG_PTR LPARAM LRESULT)
(define-c-typedef LONG HRESULT)
(define-c-typedef WORD ATOM)
;; i'm lazy to do this. it's the same anyway.
(define HANDLE void*)
(define HHOOK HANDLE)
(define HGLOBAL HANDLE)
(define HLOCAL HANDLE)
(define GLOBALHANDLE HANDLE)
(define LOCALHANDLE HANDLE)
(define HGDIOBJ void*)
(define HACCEL HANDLE)
(define HBITMAP HANDLE)
(define HBRUSH HANDLE)
(define HCOLORSPACE HANDLE)
(define HDC HANDLE)
(define HGLRC HANDLE)
(define HDESK HANDLE)
(define HENHMETAFILE HANDLE)
(define HFONT HANDLE)
(define HICON HANDLE)
(define HKEY HANDLE)
(define HMONITOR HANDLE)
(define HTERMINAL HANDLE)
(define HWINEVENTHOOK HANDLE)
(define PHKEY void*)
(define HMENU HANDLE)
(define HMETAFILE HANDLE)
(define HINSTANCE HANDLE)
(define HMODULE HINSTANCE)
(define HPALETTE HANDLE)
(define HPEN HANDLE)
(define HRGN HANDLE)
(define HRSRC HANDLE)
(define HSTR HANDLE)
(define HTASK HANDLE)
(define HWND HANDLE)
(define HWINSTA HANDLE)
(define HKL HANDLE)
(define HFILE int)
(define HCURSOR HICON)
(define COLORREF DWORD)
(define FARPROC callback)
(define NEARPROC callback)
(define PROC callback)
(define-c-struct RECT
(LONG left)
(LONG top)
(LONG right)
(LONG bottom))
(define PRECT void*)
(define LPRECT void*)
(define LPCRECT void*)
(define RECTL RECT)
(define PRECTL void*)
(define LPRECTL void*)
(define LPCRECTL void*)
(define-c-struct POINT
(LONG x)
(LONG y))
(define POINTL POINT)
(define PPOINT void*)
(define LPPOINT void*)
(define PPOINTL void*)
(define LPPOINTL void*)
(define-c-struct SIZE
(LONG cx)
(LONG cy))
(define SIZEL SIZE)
(define PSIZE void*)
(define LPSIZE void*)
(define PSIZEL void*)
(define LPSIZEL void*)
(define-c-struct POINTS
(SHORT x)
(SHORT y))
(define PPOINTS void*)
(define LPPOINTS void*)
) | false |
7f8f731e5876592c7a62bb25f392c6543bedfcfa | b21f59bbd4faf31159321e8d26eb170f9aa410c0 | /2.2.1-representing-sequences/mapping-over-lists.scm | de6f049b32463d7a1674615154eeabedfc07954a | []
| no_license | furkhat/sicp-practice | 4774048022718c165e0ec35602bb192241d9f97a | 301fea9ee4d6cea895cec4b618c664b48c2106f0 | refs/heads/master | 2021-06-08T06:01:01.760120 | 2016-12-11T08:11:34 | 2016-12-11T08:11:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 443 | scm | mapping-over-lists.scm | (define (square-list items)
(if (null? items)
items
(cons (square (car items)) (square-list (cdr items)))))
(define (square-list items)
(map square items))
(define (for-each proc items)
(define (iter things)
(cond ((null? things)
true)
(else
(proc (car things))
(iter (cdr things)))))
(iter items))
(for-each (lambda (x) (newline) (display x))
(list 57 321 88)) | false |
ba481f9453e6bc578556809682f3fd7bf7d90f10 | 2f88dd127122c2444597a65d8b7a23926aebbac1 | /sort.scm | 99f2cc40ce90ef341075cabc7e473472d9a21636 | [
"BSD-2-Clause"
]
| permissive | KenDickey/Crosstalk | 6f980b7188c1cc6bd176a8e0cd10b032f768b4e6 | b449fb7c711ad287f9b49e7167d8cedd514f5d81 | refs/heads/master | 2023-05-26T10:07:12.674162 | 2023-05-21T22:59:26 | 2023-05-21T22:59:26 | 58,777,987 | 11 | 1 | null | null | null | null | UTF-8 | Scheme | false | false | 3,083 | scm | sort.scm | ;;; File : sort.scm
;;; Author : Richard A. O'Keefe (based on Prolog code by D.H.D.Warren)
;;; Updated: 11 June 1991
;
; $Id$
;
; Code originally obtained from Scheme Repository, since hacked.
;
; Sort and Sort! will sort lists and vectors. The former returns a new
; data structure; the latter sorts the data structure in-place. A
; mergesort algorithm is used.
;;($$trace "sort")
; Destructive merge of two sorted lists.
(define (merge!! a b less?)
(define (loop r a b)
(if (less? (car b) (car a))
(begin (set-cdr! r b)
(if (null? (cdr b))
(set-cdr! b a)
(loop b a (cdr b)) ))
;; (car a) <= (car b)
(begin (set-cdr! r a)
(if (null? (cdr a))
(set-cdr! a b)
(loop a (cdr a) b)) )) )
(cond ((null? a) b)
((null? b) a)
((less? (car b) (car a))
(if (null? (cdr b))
(set-cdr! b a)
(loop b a (cdr b)))
b)
(else ; (car a) <= (car b)
(if (null? (cdr a))
(set-cdr! a b)
(loop a (cdr a) b))
a)))
; Sort procedure which copies the input list and then sorts the
; new list imperatively. Due to Richard O'Keefe; algorithm
; attributed to D.H.D. Warren
(define (sort!! seq less?)
(define (step n)
(cond ((> n 2)
(let* ((j (quotient n 2))
(a (step j))
(k (- n j))
(b (step k)))
(merge!! a b less?)))
((= n 2)
(let ((x (car seq))
(y (cadr seq))
(p seq))
(set! seq (cddr seq))
(if (less? y x)
(begin
(set-car! p y)
(set-car! (cdr p) x)))
(set-cdr! (cdr p) '())
p))
((= n 1)
(let ((p seq))
(set! seq (cdr seq))
(set-cdr! p '())
p))
(else
'())))
(step (length seq)))
(define (sort! seq less?)
(cond ((null? seq)
seq)
((pair? seq)
(sort!! seq less?))
((vector? seq)
(do ((l (sort!! (vector->list seq) less?) (cdr l))
(i 0 (+ i 1)))
((null? l) seq)
(vector-set! seq i (car l))))
(else
(error "sort!: not a valid sequence: " seq))))
(define (sort seq less?)
(cond ((null? seq)
seq)
((pair? seq)
(sort!! (list-copy seq) less?))
((vector? seq)
(list->vector (sort!! (vector->list seq) less?)))
(else
(error "sort: not a valid sequence: " seq))))
; Added for R6RS.
(define (list-sort less? seq)
(sort!! (list-copy seq) less?))
; R7RS adds optional start and end arguments.
(define (vector-sort less? seq . rest)
(cond ((null? rest)
(list->vector (sort!! (vector->list seq) less?)))
((null? (cdr rest))
(vector-sort less? (vector-copy seq (car rest))))
(else
(vector-sort less? (vector-copy seq (car rest) (cadr rest))))))
(define (vector-sort! less? seq . rest)
(let* ((start (if (null? rest) 0 (car rest)))
(end (if (or (null? rest) (null? (cdr rest)))
(vector-length seq)
(cadr rest)))
(v (if (null? rest) seq (vector-copy seq start end)))
(sorted (sort!! (vector->list v) less?)))
(do ((sorted sorted (cdr sorted))
(i start (+ i 1)))
((null? sorted))
(vector-set! seq i (car sorted)))))
; eof
| false |
3083454989d80efd51385c4973e921286eea89cb | 295dbd430419a7c36df8d2fd033f8e9afdc308c3 | /Computing_with_Register_Machines/ex/3.scm | a5d08fd69ab652fe9625e687e6f2fd4cb00fd97b | []
| no_license | ojima-h/sicp | f76b38a46a4f413d6a33f1ba0df4f6af28208fa1 | 4bbcd6a011076aef6fe36071958b76e05f653c75 | refs/heads/master | 2016-09-05T17:36:32.319932 | 2014-06-09T00:30:37 | 2014-06-09T00:30:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 945 | scm | 3.scm | ;; PHASE 1
(controller
(assign g (const 1.0))
test-b
(test (op good-enough?) (reg g))
(branch (label sqrt-done))
(assign t (op improve) (reg g))
(assign g (op sqrt-iter) (reg t))
(goto (label test-b))
sqrt-done)
;; PHASE 2
(controller
(assign g (const 1.0))
test-b
(assign t (op square) (reg g))
(assign t (op -) (reg t) (reg x))
(assign t (op abs) (reg t))
(test (op <) (reg t) (const 0.001))
(branch (label sqrt-done))
(assign t (op improve) (reg g))
(assign g (op sqrt-iter) (reg t))
(goto (label test-b))
sqrt-done)
;; PHASE 3
(controller
(assign g (const 1.0))
test-b
(assign t (op square) (reg g))
(assign t (op -) (reg t) (reg x))
(assign t (op abs) (reg t))
(test (op <) (reg t) (const 0.001))
(branch (label sqrt-done))
(assign t (op /) (reg x) (reg g))
(assign t (op average) (reg t) (reg g))
(assign g (op sqrt-iter) (reg t))
(goto (label test-b))
sqrt-done)
| false |
737d0417a81205b4b5efae5ae69dca0da24a4d37 | defeada37d39bca09ef76f66f38683754c0a6aa0 | /UnityEngine/jet-brains/annotations/localization-required-attribute.sls | c435491513e11f184521c13747748c1e08b60212 | []
| 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 | 719 | sls | localization-required-attribute.sls | (library (jet-brains annotations localization-required-attribute)
(export new is? localization-required-attribute? required?)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new
JetBrains.Annotations.LocalizationRequiredAttribute
a
...)))))
(define (is? a)
(clr-is JetBrains.Annotations.LocalizationRequiredAttribute a))
(define (localization-required-attribute? a)
(clr-is JetBrains.Annotations.LocalizationRequiredAttribute a))
(define-field-port
required?
#f
#f
(property:)
JetBrains.Annotations.LocalizationRequiredAttribute
Required
System.Boolean))
| true |
abc4e8b22e4008bae9aa0b65d9f77c6944fe7083 | b9eb119317d72a6742dce6db5be8c1f78c7275ad | /path-search.ss | 09e72c83c642a58c41fb8981727ae86ca5b06e51 | []
| no_license | offby1/doodles | be811b1004b262f69365d645a9ae837d87d7f707 | 316c4a0dedb8e4fde2da351a8de98a5725367901 | refs/heads/master | 2023-02-21T05:07:52.295903 | 2022-05-15T18:08:58 | 2022-05-15T18:08:58 | 512,608 | 2 | 1 | null | 2023-02-14T22:19:40 | 2010-02-11T04:24:52 | Scheme | UTF-8 | Scheme | false | false | 339 | ss | path-search.ss | #lang scheme
(define/contract (path-search name)
(string? . -> . (or/c path? #f))
(define (executable? candidate)
(and (file-exists? candidate)
(memq 'execute (file-or-directory-permissions candidate))))
(findf executable?
(map (curryr build-path name)
(regexp-split #rx":" (getenv "PATH")))))
| false |
951d707c2689e2e1f48af8539d2b9aa4edcc11b7 | 370ebaf71b077579ebfc4d97309ce879f97335f7 | /sicp/tests/ch2/rationalNumberTests.scm | a6d0e51042484e2b66d86ed539b3c2b9860dea68 | []
| no_license | jgonis/sicp | 7f14beb5b65890a86892a05ba9e7c59fc8bceb80 | fd46c80b98c408e3fd18589072f02ba444d35f53 | refs/heads/master | 2023-08-17T11:52:23.344606 | 2023-08-13T22:20:42 | 2023-08-13T22:20:42 | 376,708,557 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 3,142 | scm | rationalNumberTests.scm | (define-library (tests ch2 rationalNumberTests)
(export rational-number-tests)
(import (scheme base)
(scheme write)
(ch2 rationalNumbers)
(srfi 64))
(begin
(define rational-number-tests
(lambda ()
(rational-addition-tests)
(rational-subtraction-tests)
(rational-multiplication-tests)
(rational-division-tests)
;;If using Gauche scheme, uncomment this line to avoid the
;;test count continuing to increase
(test-runner-reset (test-runner-current))))
(define (test-func-tests)
(test-begin "test-func-tests")
(test-equal (test-func) 1)
(test-end "test-func-tests"))
(define (rational-addition-tests)
(test-begin "rational-addition-tests")
(let ((one-half (make-rational 1 2))
(one-quarter (make-rational 1 4))
(negative-one-half (make-rational -1 2))
(negative-one-quarter (make-rational -1 4)))
(test-assert (equal-rational (make-rational 3 4)
(add-rational one-half
one-quarter)))
(test-assert (equal-rational one-half
(add-rational one-quarter
one-quarter)))
(test-assert (equal-rational negative-one-quarter
(add-rational one-quarter
negative-one-half))))
(test-end "rational-addition-tests"))
(define (rational-subtraction-tests)
(test-begin "rational-subtraction-tests")
(let ((one-half (make-rational 1 2))
(three-quarters (make-rational 3 4))
(one-quarter (make-rational -1 -4))
(negative-one-quarter (make-rational -1 4))
(negative-one-half (make-rational -1 2)))
(test-assert (equal-rational one-quarter
(sub-rational three-quarters
one-half)))
(test-assert (equal-rational one-half
(sub-rational three-quarters
one-quarter)))
(test-assert (equal-rational negative-one-quarter
(sub-rational one-half
three-quarters)))
(test-assert (equal-rational one-quarter
(sub-rational negative-one-quarter
negative-one-half))))
(test-end "rational-subtraction-tests"))
(define (rational-multiplication-tests)
(test-begin "rational-multiplication-tests")
(let ((one-half (make-rational 1 2))
(one-quarter (make-rational 1 4))
(negative-one-half (make-rational -1 2))
(negative-one-quarter (make-rational -1 4)))
(test-assert (equal-rational one-quarter
(mult-rational one-half
one-half)))
(test-assert (equal-rational one-quarter
(mult-rational negative-one-half
negative-one-half)))
(test-assert (equal-rational negative-one-quarter
(mult-rational negative-one-half
one-half))))
(test-end "rational-multiplication-tests"))
(define (rational-division-tests)
(test-begin "rational-division-tests")
(let ((one-half (make-rational 1 2))
(one-quarter (make-rational 1 4))
(negative-one-half (make-rational -1 2))
(negative-one-quarter (make-rational -1 4)))
(test-assert (equal-rational (make-rational 2 1)
(div-rational one-half
one-quarter))))
(test-end "rational-division-tests"))))
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.