blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
171
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0961a1eeb34185cd3b74d30801bfdcee31579fc5 | fc90b5a3938850c61bdd83719a1d90270752c0bb | /web-server-lib/web-server/lang/defun.rkt | 4c5e9e2740b47304a37ccbfbb8c8a101243335c0 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | racket/web-server | cccdf9b26d7b908701d7d05568dc6ed3ae9e705b | e321f8425e539d22412d4f7763532b3f3a65c95e | refs/heads/master | 2023-08-21T18:55:50.892000 | 2023-07-11T02:53:24 | 2023-07-11T02:53:24 | 27,431,252 | 91 | 42 | NOASSERTION | 2023-09-02T15:19:40 | 2014-12-02T12:20:26 | Racket | UTF-8 | Racket | false | false | 3,518 | rkt | defun.rkt | #lang racket/base
(require (for-template racket/base)
syntax/kerncase
racket/contract
web-server/lang/closure
(for-template web-server/lang/serial-lambda)
"util.rkt")
(provide/contract
[defun (syntax? . -> . syntax?)])
; make-new-clouse-label : (syntax -> syntax) syntax -> syntax
(define (make-new-closure-label labeling stx)
(labeling stx))
; defun : syntax[1] -> (values syntax?[2] (listof syntax?)[3])
; defunctionalizes the first syntax, returning the second and the lifted lambdas [3]
(define (defun stx)
(rearm
stx
(kernel-syntax-case
(disarm stx) (transformer?)
[(begin be ...)
(let-values ([(nbes) (defun* (syntax->list #'(be ...)))])
(quasisyntax/loc stx (begin #,@nbes)))]
[(begin0 be ...)
(let-values ([(nbes) (defun* (syntax->list #'(be ...)))])
(quasisyntax/loc stx (begin0 #,@nbes)))]
[(set! v ve)
(let-values ([(nve) (defun #'ve)])
(quasisyntax/loc stx (set! v #,nve)))]
[(let-values ([(v ...) ve] ...) be ...)
(let-values ([(nves) (defun* (syntax->list #'(ve ...)))]
[(nbes) (defun* (syntax->list #'(be ...)))])
(with-syntax ([(nve ...) nves]
[(nbe ...) nbes])
(syntax/loc stx (let-values ([(v ...) nve] ...) nbe ...))))]
[(letrec-values ([(v ...) ve] ...) be ...)
(let-values ([(nves) (defun* (syntax->list #'(ve ...)))]
[(nbes) (defun* (syntax->list #'(be ...)))])
(with-syntax ([(nve ...) nves]
[(nbe ...) nbes])
(syntax/loc stx (letrec-values ([(v ...) nve] ...) nbe ...))))]
[(#%plain-lambda formals be ...)
(let-values ([(nbes) (defun* (syntax->list #'(be ...)))])
(with-syntax ([(nbe ...) nbes])
(syntax/loc stx
(serial-lambda formals nbe ...))
#;
(make-closure
(quasisyntax/loc stx
(_ #,(make-new-closure-label (current-code-labeling) stx) (#%plain-lambda formals nbe ...))))))]
[(case-lambda [formals be ...] ...)
(let-values ([(nbes) (defun** (syntax->list #'((be ...) ...)))])
(with-syntax ([((nbe ...) ...) nbes])
(syntax/loc stx
(serial-case-lambda
[formals nbe ...]
...))
#;
(make-closure
(quasisyntax/loc stx
(_ #,(make-new-closure-label (current-code-labeling) stx) (case-lambda [formals nbe ...] ...))))))]
[(if te ce ae)
(let-values ([(es) (defun* (syntax->list #'(te ce ae)))])
(quasisyntax/loc stx (if #,@es)))]
[(quote datum)
stx]
[(quote-syntax datum)
stx]
[(with-continuation-mark ke me be)
(let-values ([(es) (defun* (list #'ke #'me #'be))])
(quasisyntax/loc stx (with-continuation-mark #,@es)))]
[(#%plain-app e ...)
(let-values ([(es) (defun* (syntax->list #'(e ...)))])
(quasisyntax/loc stx (#%plain-app #,@es)))]
[(#%top . v)
stx]
[(#%variable-reference . v)
stx]
[id (identifier? #'id)
stx]
[(#%expression d)
(let-values ([(nd) (defun #'d)])
(quasisyntax/loc stx (#%expression #,nd)))]
[_
(raise-syntax-error 'defun "Dropped through:" stx)])))
; lift defun to list of syntaxes
(define (lift-defun defun)
(lambda (stxs)
(map defun stxs)))
(define defun* (lift-defun defun))
(define defun** (lift-defun (lambda (stx) (defun* (syntax->list stx)))))
| false |
1b0a5776d11cf706cc858c3fd3de02af4c8a7dd3 | 66f1ec563c7c89f1b36974f9d7af194b4ccb3fb1 | /syntax.rkt | 44ce4174ae4602545a2e5531a2cda1c0ad7800f1 | [
"MIT"
] | permissive | Hallicopter/racket-protobuf | fb62aeb46e4815955fc45217d65f3b5e075a06b0 | 63311d4d1ab8774f94abeb7d6893204d6680f259 | refs/heads/main | 2023-03-18T20:01:08.365000 | 2021-03-14T16:16:46 | 2021-03-14T16:16:46 | 347,669,156 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 9,172 | rkt | syntax.rkt | #lang racket/base
;; This file is part of Protocol Buffers for Racket.
;; Copyright (c) 2012-2018 by Thomas C. Chust <[email protected]>
;;
;; Protocol Buffers for Racket 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.
;;
;; Protocol Buffers for Racket 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 Protocol Buffers for Racket. If not, see
;; <http://www.gnu.org/licenses/>.
(require
(for-syntax
srfi/26
racket/base
racket/list
racket/struct-info
racket/syntax)
srfi/26
racket/promise
racket/set
"encoding.rkt"
"reflection.rkt")
(define-syntax (define-primitive-type stx)
(syntax-case stx ()
[(define-primitive-type name type
reader writer)
(with-syntax ([primitive:info
(datum->syntax stx (format-symbol "primitive:~a" #'name))])
#'(define primitive:info
(primitive-info 'name 'type reader writer)))]))
(define-primitive-type int32 int*
read-int* write-int*)
(define-primitive-type int64 int*
read-int* write-int*)
(define-primitive-type uint32 int*
read-uint* write-uint*)
(define-primitive-type uint64 int*
read-uint* write-uint*)
(define (primitive:uint* max-size)
(primitive-info
'uint* 'int*
(cut read-uint* <> max-size)
(cut write-uint* <> <> max-size)))
(define-primitive-type sint32 int*
read-sint* write-sint*)
(define-primitive-type sint64 int*
read-sint* write-sint*)
(define (primitive:sint* max-size)
(primitive-info
'sint* 'int*
(cut read-sint* <> max-size)
(cut write-sint* <> <> max-size)))
(define-primitive-type fixed32 32bit
read-fixed32 write-fixed32)
(define-primitive-type fixed64 64bit
read-fixed64 write-fixed64)
(define-primitive-type sfixed32 32bit
read-sfixed32 write-sfixed32)
(define-primitive-type sfixed64 64bit
read-sfixed64 write-sfixed64)
(define-primitive-type bool int*
read-bool write-bool)
(define-primitive-type float 32bit
read-float write-float)
(define-primitive-type double 64bit
read-double write-double)
(define-primitive-type bytes sized
read-sized-bytes write-sized-bytes)
(define-primitive-type string sized
read-sized-string write-sized-string)
(provide
primitive:int32 primitive:int64
primitive:uint32 primitive:uint64 primitive:uint*
primitive:sint32 primitive:sint64 primitive:sint*
primitive:fixed32 primitive:fixed64
primitive:sfixed32 primitive:sfixed64
primitive:bool
primitive:float primitive:double
primitive:bytes primitive:string)
(define-syntax (define-enum-type stx)
(syntax-case stx ()
[(define-enum-type name
([alt tag] ...))
(with-syntax ([enum:info
(datum->syntax stx (format-symbol "enum:~a" #'name))]
[integer->enum
(datum->syntax stx (format-symbol "integer->~a" #'name))]
[enum->integer
(datum->syntax stx (format-symbol "~a->integer" #'name))])
#'(begin
(define (integer->enum i)
(case i
[(tag) 'alt] ...
[else (error 'integer->enum "unknown enumeration tag: ~e" i)]))
(define (enum->integer s)
(case s
[(alt) tag] ...
[else (error 'enum->integer "unknown enumeration value: ~e" s)]))
(define enum:info
(enum-info 'name integer->enum enum->integer))))]))
(define-syntax required-tags
(syntax-rules (required)
[(required-tags (required tag) . more)
(cons tag (required-tags . more))]
[(required-tags (_ tag) . more)
(required-tags . more)]
[(required-tags)
null]))
(define-syntax (define-message-type stx)
(syntax-case stx ()
[(define-message-type name
([label type field tag . default] ...))
(let ([fields (syntax-e #'(field ...))]
[defaults (syntax-e #'(default ...))])
(with-syntax ([nfields
(length fields)]
[(field-arg ...)
(append*
(for/list ([s (in-list fields)] [v (in-list defaults)])
(list
(string->keyword (symbol->string (syntax->datum s)))
(list s #'(void)))))]
[constructor
(datum->syntax stx (format-symbol "~a*" #'name))]
[(field-default ...)
(for/list ([v (in-list defaults)])
(if (null? (syntax->datum v)) #'((void)) v))]
[(accessor ...)
(datum->syntax
stx (map (cut format-symbol "~a-~a" #'name <>)
fields))]
[(mutator ...)
(datum->syntax
stx (map (cut format-symbol "set-~a-~a!" #'name <>)
fields))])
#'(begin
(struct name message
([field #:auto] ...)
#:transparent
#:mutable
#:auto-value (void)
#:property prop:protobuf
(delay
(message-info
'name constructor
(make-immutable-hasheqv
(list
(cons
tag
(field-info
type (memq 'label '(repeated packed)) (eq? 'label 'packed)
accessor mutator))
...))
(list->seteqv
(required-tags (label tag) ...)))))
(define constructor
(let ([make-message name])
(λ (field-arg ...)
(let ([msg (make-message (hasheqv))])
(unless (void? field) (mutator msg field)) ...
msg))))
(set! accessor
(let ([message-ref accessor]
[default-thunk
(case 'label
[(required)
(λ () (error 'accessor "missing required field"))]
[(optional)
(λ () . field-default)]
[(repeated packed)
null])])
(λ (msg [alt default-thunk])
(let ([v (message-ref msg)])
(cond
[(not (void? v)) v]
[(procedure? alt) (alt)]
[else alt])))))
...)))]))
(define-syntax (define-message-extension stx)
(syntax-case stx ()
[(define-message-type name
[label type field tag . default])
(with-syntax ([(struct:info _ message? _ _ _)
(extract-struct-info (syntax-local-value #'name))]
[field-default
(if (null? (syntax->datum #'default)) #'((void)) #'default)]
[accessor
(datum->syntax
stx (format-symbol "~a-~a" #'name #'field))]
[mutator
(datum->syntax
stx (format-symbol "set-~a-~a!" #'name #'field))])
#'(begin
(define accessor
(let ([default-thunk
(case 'label
[(required)
(λ () (error 'accessor "missing required field"))]
[(optional)
(λ () . field-default)]
[(repeated)
null])])
(λ (msg [alt default-thunk])
(unless (message? msg)
(raise-type-error 'accessor (symbol->string name) msg))
(let ([v (hash-ref (message-extensions msg) tag void)])
(cond
[(not (void? v)) v]
[(procedure? alt) (alt)]
[else alt])))))
(define (mutator msg v)
(unless (message? msg)
(raise-type-error 'mutator (symbol->string name) msg))
(set-message-extensions! msg
(hash-set (message-extensions msg) tag v)))
(let ([info (force (protobuf-ref struct:info))])
(set-message-info-fields! info
(hash-set (message-info-fields info) tag
(field-info
type (memq 'label '(repeated packed)) (eq? 'label 'packed)
accessor mutator)))
(set-message-info-required! info
(set-union
(message-info-required info)
(list->seteqv
(required-tags (label tag))))))))]))
(provide
define-enum-type
define-message-type
define-message-extension)
| true |
5e9ed4f34a9dd7a53f2b3792551ed7606f305c25 | 087c56877811a7737e9ed1ceb261ad2d9d5c65ee | /r7rs-lib/case-lambda.rkt | f8c8726c5d344c380b1afc40516fd7a6f2d604bf | [
"ISC"
] | permissive | lexi-lambda/racket-r7rs | 2a510e70155c97b3256ec23bbc4de16567f21b70 | 84be3d16aab202e08b13da2f0e7c095e03ff0895 | refs/heads/master | 2023-06-23T10:38:38.675000 | 2022-11-23T08:00:52 | 2023-06-14T16:36:04 | 44,901,769 | 107 | 15 | null | 2022-11-23T08:03:26 | 2015-10-25T08:13:35 | Racket | UTF-8 | Racket | false | false | 65 | rkt | case-lambda.rkt | #lang racket/base
(require rnrs/control-6)
(provide case-lambda)
| false |
1b0cfe20eaefe96ed636a25cf5e46b8318529fc7 | cf32cf2d0be992b2b2e727990b6462544d26a9e4 | /odysseus/tests/files_test.rkt | 402061849cfb8baff1727e883a63920ddfdbb18b | [
"MIT-0"
] | permissive | prozion/odysseus | ba4a89fd09d19ec1385a28211d2ca51857d84840 | 2afc96ba60fd8b50d54ce94eb27dd7ce92525360 | refs/heads/master | 2023-08-10T01:09:08.608000 | 2023-07-23T20:26:18 | 2023-07-23T20:26:18 | 319,242,860 | 1 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 314 | rkt | files_test.rkt | #lang racket
(require "../files.rkt")
(require rackunit)
(check-true (absolute-path? "/var/tmp/something/"))
(check-true (absolute-path? "C:/User/Users/AppData"))
(check-true (absolute-path? "C:\\User\\Users\\AppData"))
(check-false (absolute-path? "sandbox/foobar"))
(check-false (absolute-path? "foobarbaz"))
| false |
68801433364e3a60e63d43c92d30f52afb5d3ad3 | 3c2a208910579b8fa92e1b03133ed88de5fe73eb | /generic-bind/syntax-parse-utils.rkt | 0faf713ae9c47830b466033428f5e2c9cfe192bb | [] | no_license | stchang/generic-bind | cbc639b5e29f9d426a51581d46fe65a7fe6de65b | d8bd9b76b792c6ebdc32d05db9545274f2ab5053 | refs/heads/master | 2022-09-13T20:06:26.404000 | 2022-08-08T03:06:05 | 2022-08-08T03:06:05 | 11,781,825 | 4 | 2 | null | 2023-08-21T16:34:03 | 2013-07-31T03:47:06 | Racket | UTF-8 | Racket | false | false | 397 | rkt | syntax-parse-utils.rkt | #lang racket
(require (for-syntax syntax/parse))
(provide define-syntax/parse)
(define-syntax define-syntax/parse
(syntax-parser
[(_ name:id #:stx stx-arg:id option-or-clause ...)
#'(define-syntax (name stx-arg)
(syntax-parse stx-arg option-or-clause ...))]
[(_ name:id option-or-clause ...)
#'(define-syntax name
(syntax-parser option-or-clause ...))]))
| true |
defa8eb91f87c746eb9fd8a06b4eea014f400b83 | 41834d5fddf86799bdeb6ba66384236ce9e96393 | /A7/a7.rkt | b11d43f90ee1e9ab50d95844dd95e1ad9b2023c3 | [] | no_license | YantingWan/c311 | 21e010b5aeee0701135074db67bb7a0bc7de2074 | 4c8b9988018dc880ee1a90b982036c9ea6e20d2b | refs/heads/master | 2020-04-17T01:36:06.412000 | 2019-03-06T23:05:41 | 2019-03-06T23:05:41 | 166,099,041 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 8,339 | rkt | a7.rkt | #lang racket
(require rackunit)
;Part I
(define last-non-zero
(lambda (ls)
(let/cc k
(letrec
((last-non-zero
(lambda (ls)
(cond
;; fill in lines here
((null? ls) '())
((zero? (car ls)) (k (last-non-zero (cdr ls))))
(else (cons (car ls) (last-non-zero (cdr ls)))))
)))
(last-non-zero ls)))))
(check-equal? (last-non-zero '(1 0 2 3 0 4 5)) '(4 5))
(check-equal? (last-non-zero '(1 2 3 0 4 5)) '(4 5))
(check-equal? (last-non-zero '(0)) '())
(check-equal? (last-non-zero '(1 2 3 4 5)) '(1 2 3 4 5))
;Part II
(define lex
(λ (e acc)
(match e
[`,n
#:when (number? n)
`(const ,n)]
[`,y
#:when (symbol? y)
`(var ,(index-of acc y))]
[`(lambda (,x) ,body)
#:when (symbol? x)
`(lambda ,(lex body (cons x acc)))]
[`(let ((,x ,exp))
,body)
#:when (symbol? x)
`(let ,(lex exp acc)
,(lex body (cons x acc)))]
[`(let/cc ,k ,body)
`(letcc ,(lex body (cons k acc)))]
[`(throw ,e1 ,e2)
`(throw ,(lex e1 acc) ,(lex e2 acc))]
[`(sub1 ,y)
`(sub1 ,(lex y acc))]
[`(zero? ,y)
`(zero ,(lex y acc))]
[`(* ,e1 ,e2)
`(mult ,(lex e1 acc) ,(lex e2 acc))]
[`(if ,test ,conseq ,alt)
`(if ,(lex test acc)
,(lex conseq acc)
,(lex alt acc))]
[`(,rator ,rand) `(app ,(lex rator acc) ,(lex rand acc))])))
;some test cases
(check-equal? (lex '(lambda (a)
(lambda (b)
(lambda (c)
(lambda (w)
(lambda (x)
(lambda (y)
((lambda (a)
(lambda (b)
(lambda (c)
(((((a b) c) w) x) y))))
(lambda (w)
(lambda (x)
(lambda (y)
(((((a b) c) w) x) y)))))))))))
'())
'(lambda
(lambda
(lambda
(lambda
(lambda
(lambda
(app (lambda
(lambda
(lambda
(app (app (app (app (app (var 2) (var 1)) (var 0)) (var 5)) (var 4)) (var 3)))))
(lambda
(lambda
(lambda
(app (app (app (app (app (var 8) (var 7)) (var 6)) (var 2)) (var 1)) (var 0)))))))))))))
(check-equal? (lex '(let/cc k (throw k (((lambda (x) x) k) (* 5 5)))) '())
'(letcc (throw (var 0) (app (app (lambda (var 0)) (var 0)) (mult (const 5) (const 5))))))
;Part III--Final Version of value-of-cps
(define value-of-cps
(lambda (expr env-cps k)
(match expr
[`(const ,expr) (apply-k k expr)]
[`(mult ,x1 ,x2) (value-of-cps x1 env-cps (make-mult-x1-continuation x2 env-cps k))]
[`(sub1 ,x) (value-of-cps x env-cps (make-sub1-continuation k))]
[`(zero ,x) (value-of-cps x env-cps (make-zero-continuation k))]
[`(if ,test ,conseq ,alt) (value-of-cps test env-cps
(make-if-continuation conseq alt env-cps k))]
[`(letcc ,body) (value-of-cps body (extend-env k env-cps) k)]
[`(throw ,k-exp ,v-exp) (value-of-cps k-exp env-cps (make-throw-k-continuation v-exp env-cps))]
[`(let ,e ,body) (value-of-cps e env-cps (make-let-continuation body env-cps k))]
[`(var ,expr) (apply-env env-cps expr k)]
[`(lambda ,body) (apply-k k (make-closure body env-cps))]
[`(app ,rator ,rand) (value-of-cps rator env-cps (make-rator-continuation rand env-cps k))])))
(define empty-env
(lambda ()
'(empty-env)))
(define empty-k
(lambda ()
'(empty-k)))
(define make-mult-x2-continuation
(lambda (v1^ k^)
`(mult-x2-continuation ,v1^ ,k^)))
(define make-mult-x1-continuation
(lambda (x2^ env-cps^ k^)
`(mult-x1-continuation ,x2^ ,env-cps^ ,k^)))
(define make-sub1-continuation
(lambda (k^)
`(sub1-continuation ,k^)))
(define make-zero-continuation
(lambda (k^)
`(zero-continuation ,k^)))
(define make-if-continuation
(lambda (conseq^ alt^ env-cps^ k^)
`(if-continuation ,conseq^ ,alt^ ,env-cps^ ,k^)))
(define make-throw-v-continuation
(lambda (k-rator^)
`(throw-v-continuation ,k-rator^)))
(define make-throw-k-continuation
(lambda (v-exp^ env-cps^)
`(throw-k-continuation ,v-exp^ ,env-cps^)))
(define make-let-continuation
(lambda (body^ env-cps^ k^)
`(let-continuation ,body^ ,env-cps^ ,k^)))
(define make-rand-continuation
(lambda (clos^ k^)
`(rand-continuation ,clos^ ,k^)))
(define make-rator-continuation
(lambda (rand^ env-cps^ k^)
`(rator-continuation ,rand^ ,env-cps^ ,k^)))
(define apply-env
(lambda (env-cps y k)
(match env-cps
['(empty-env) (error 'value-of "unbound identifier")]
[`(env ,a^ ,env-cps^) (if (zero? y) (apply-k k a^) (apply-env env-cps^ (sub1 y) k))]
)))
(define apply-closure
(lambda (clos a k)
(match clos
[`(clos ,body ,env-cps) (value-of-cps body (extend-env a env-cps) k)]
)))
(define apply-k
(λ (k v)
(match k
['(empty-k) v]
[`(mult-x2-continuation ,v1^ ,k^) (apply-k k^ (* v1^ v))]
[`(mult-x1-continuation ,x2^ ,env-cps^ ,k^) (value-of-cps x2^ env-cps^ (make-mult-x2-continuation v k^))]
[`(sub1-continuation ,k^) (apply-k k^ (sub1 v))]
[`(zero-continuation ,k^) (apply-k k^ (zero? v))]
[`(if-continuation ,conseq^ ,alt^ ,env-cps^ ,k^) (if v
(value-of-cps conseq^ env-cps^ k^)
(value-of-cps alt^ env-cps^ k^))]
[`(throw-v-continuation ,k-rator^) (apply-k k-rator^ v)]
[`(throw-k-continuation ,v-exp^ ,env-cps^) (value-of-cps v-exp^ env-cps^ (make-throw-v-continuation v))]
[`(let-continuation ,body^ ,env-cps^ ,k^) (value-of-cps body^ (extend-env v env-cps^) k^)]
[`(rand-continuation ,clos^ ,k^) (apply-closure clos^ v k^)]
[`(rator-continuation ,rand^ ,env-cps^ ,k^) (value-of-cps rand^ env-cps^ (make-rand-continuation v k^))] ;[else (k v)]
)))
(define extend-env
(lambda (a^ env-cps^)
`(env ,a^ ,env-cps^)))
(define make-closure
(lambda (body env-cps)
`(clos ,body ,env-cps)))
;-----------------------------------TEST-------------------------------------------------------------
(check-equal? (value-of-cps '(letcc (sub1 (throw (var 0) (const 5)))) (empty-env) (empty-k))
5)
(check-equal? (value-of-cps '(letcc (throw (throw (var 0) (const 5)) (const 6))) (empty-env) (empty-k))
5)
(check-equal? (value-of-cps '(app (lambda (app (app (var 0) (var 0)) (const 2)))
(lambda
(lambda
(if (zero (var 0))
(const 1)
(app (app (var 1) (var 1)) (sub1 (var 0)))))))
(empty-env)
(empty-k))
1)
(check-equal? (value-of-cps '(mult (const 5) (let (const 5) (var 0))) (empty-env) (empty-k)) 25)
(check-equal? (value-of-cps '(if (zero (const 0)) (const 4) (app (lambda (app (var 0) (var 0))) (lambda (app (var 0) (var 0)))))
(empty-env)
(empty-k)) 4)
;----------------------brainTeasers---------------------------------------------------------------
(define-syntax cons$
(syntax-rules ()
((cons$ x y) (cons x (delay y)))))
(define car$ car)
(define cdr$
(lambda ($) (force (cdr $))))
(define take$
(lambda (n $)
(cond
((zero? n) '())
(else (cons (car$ $)
(let ((n- (sub1 n)))
(cond
((zero? n-) '())
(else (take$ n- (cdr$ $))))))))))
(define trib$
(letrec ((trib$ (lambda (a)
(lambda (b)
(lambda (c)
(cons$ a (((trib$ b) c) (+ a b c))))))))
(((trib$ 0) 1) 1)))
(check-equal? (take$ 7 trib$) '(0 1 1 2 4 7 13))
| true |
25452fb32e563e219d95db35452f87c5f5f737d6 | 82c76c05fc8ca096f2744a7423d411561b25d9bd | /typed-racket-test/optimizer/tests/unboxed-let2.rkt | 0b9b483d95f134545cd4dc8c7c0f8d4f73256030 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | racket/typed-racket | 2cde60da289399d74e945b8f86fbda662520e1ef | f3e42b3aba6ef84b01fc25d0a9ef48cd9d16a554 | refs/heads/master | 2023-09-01T23:26:03.765000 | 2023-08-09T01:22:36 | 2023-08-09T01:22:36 | 27,412,259 | 571 | 131 | NOASSERTION | 2023-08-09T01:22:41 | 2014-12-02T03:00:29 | Racket | UTF-8 | Racket | false | false | 934 | rkt | unboxed-let2.rkt | #;#;
#<<END
TR opt: unboxed-let2.rkt 2:10 (+ 1.0+2.0i 2.0+4.0i) -- unboxed binary float complex
TR opt: unboxed-let2.rkt 2:13 1.0+2.0i -- unboxed literal
TR opt: unboxed-let2.rkt 2:22 2.0+4.0i -- unboxed literal
TR opt: unboxed-let2.rkt 2:6 (t1 (+ 1.0+2.0i 2.0+4.0i)) -- unboxed let bindings
TR opt: unboxed-let2.rkt 3:10 (+ 3.0+6.0i 4.0+8.0i) -- unboxed binary float complex
TR opt: unboxed-let2.rkt 3:13 3.0+6.0i -- unboxed literal
TR opt: unboxed-let2.rkt 3:22 4.0+8.0i -- unboxed literal
TR opt: unboxed-let2.rkt 3:6 (t2 (+ 3.0+6.0i 4.0+8.0i)) -- unboxed let bindings
TR opt: unboxed-let2.rkt 4:2 (+ t1 t2) -- unboxed binary float complex
TR opt: unboxed-let2.rkt 4:5 t1 -- leave var unboxed
TR opt: unboxed-let2.rkt 4:8 t2 -- leave var unboxed
END
#<<END
10.0+20.0i
END
#lang typed/scheme
#:optimize
#reader typed-racket-test/optimizer/reset-port
(let ((t1 (+ 1.0+2.0i 2.0+4.0i))
(t2 (+ 3.0+6.0i 4.0+8.0i)))
(+ t1 t2))
| false |
086581c90d9642477ba89b71a1183d80d7301725 | 6858cbebface7beec57e60b19621120da5020a48 | /14/6/2/4.rkt | 449293a31a476ab3f684984bb7f96e59e1afb2a2 | [] | no_license | ponyatov/PLAI | a68b712d9ef85a283e35f9688068b392d3d51cb2 | 6bb25422c68c4c7717b6f0d3ceb026a520e7a0a2 | refs/heads/master | 2020-09-17T01:52:52.066000 | 2017-03-28T07:07:30 | 2017-03-28T07:07:30 | 66,084,244 | 2 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 98 | rkt | 4.rkt | (define g2 (generator (yield) (v)
(letrec ([loop (lambda (n)
(loop (+ (yield n) n)))])
(loop v)))) | false |
d2fbe0ec1b4263a142e12259d498dea6f47cec0d | b0f974ac9434f5fc93e6ea223ab75da41db74ee9 | /impress.rkt | b92d1e01eb2d530ac40278ad130dfcddf7aa7f25 | [
"Apache-2.0",
"MIT"
] | permissive | thoughtstem/website | 3416b35a542f5ee576b32c62150c7be5459a2345 | 4366ea7688467c52cac283daba4bed292a8390c8 | refs/heads/master | 2021-07-06T02:14:28.762000 | 2020-12-23T18:55:07 | 2020-12-23T18:55:07 | 215,898,845 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 3,603 | rkt | impress.rkt | #lang at-exp racket
(provide (except-out (all-from-out website) col)
include-impress-js
impress-init
impress
impress-files
impress-site
step
impress-debug
debug-impress)
(require website
racket/runtime-path)
(define-runtime-path js "impress/js")
(define-runtime-path css "impress/css")
(define impress-debug (make-parameter #f))
(define-syntax-rule (debug-impress stuff ...)
(parameterize ([impress-debug #t])
stuff ...))
(define (fix-format that)
(define v (second that))
(list-set
that
1
(cond
[(number? v)
(~r (exact->inexact v)
#:precision 3)]
[else v])))
(define (guard this that)
(if this
(fix-format that)
#f))
(define (step #:x (x #f)
#:y (y #f)
#:z (z #f)
#:rel-x (rel-x #f)
#:rel-y (rel-y #f)
#:rel-z (rel-z #f)
#:rotate-x (rotate-x #f)
#:rotate-y (rotate-y #f)
#:rotate-z (rotate-z #f)
#:scale (scale #f)
#:rotate (rotate #f)
#:autoplay (autoplay #f)
#:goto (goto #f)
#:key-list (key-list #f)
#:next-list (next-list #f)
. contents)
(apply div
(filter identity
(flatten
(list
class: "step"
(guard x (list 'data-x: x ))
(guard y (list 'data-y: y ))
(guard z (list 'data-z: z ))
(guard rel-x (list 'data-rel-x: rel-x ))
(guard rel-y (list 'data-rel-y: rel-y ))
(guard rel-z (list 'data-rel-z: rel-z ))
(guard rotate-x (list 'data-rotate-x: rotate-x ))
(guard rotate-y (list 'data-rotate-y: rotate-y ))
(guard rotate-z (list 'data-rotate-z: rotate-z ))
(guard scale (list 'data-scale: scale ))
(guard rotate (list 'data-rotate: rotate ))
(guard autoplay (list 'data-autoplay: autoplay ))
(guard goto (list 'data-goto: goto ))
(guard key-list (list 'data-goto-key-list: key-list ))
(guard next-list (list 'data-goto-next-list: next-list ))
contents
(when (impress-debug)
@div{x:@x, y:@y, scale:@scale})
)))))
(define (impress-files)
(page js/impress.js
(file->string (build-path js "impress.js"))))
(define (include-impress-js)
(list
(include-js "/js/impress.js")))
(define (impress-init)
(script "impress().init()"))
(define (impress-site
#:transition-duration (td 1000)
#:head (head-content #f) . contents)
(list
(impress-files)
(page index.html
(html
(head
head-content)
(body class: "impress-not-supported"
(impress #:transition-duration td
contents))))))
(define (impress
#:transition-duration (td 1000)
#:body-scrollbar? (body-scrollbar? #f)
. contents)
(list
(div id: "impress"
'data-transition-duration: (~a td)
contents)
(include-impress-js)
(impress-init)
;Impress hides the body scrollbar by default,
; This js line below reverses that.
(when body-scrollbar?
@script/inline{document.querySelector("body").style.overflow = "scroll"})))
| true |
6846558f47bdd9b80ac3f14524f74ddf66b29537 | 300cc032d81929bcfe93246e3f835b52af86a281 | /chapter3/letrec-lang/ntop.rkt | df7f967bc65c5344fdaf3612856e1dae2aa1a25d | [] | no_license | dannyvi/eopl-practice | 995aa243c11b0c1daa79c8f8e7521d371b63008d | e5b6d86da18d336e715b740f2c15cfa64f888fcb | refs/heads/master | 2020-04-16T09:13:18.386000 | 2019-03-02T10:06:10 | 2019-03-02T10:06:10 | 165,456,239 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 302 | rkt | ntop.rkt | (module ntop (lib "eopl.ss" "eopl")
(require "interp.scm")
(require "lang.scm")
(define run
(lambda (str)
(value-of-program (scan&parse str))))
)
;; exercise 3.30
;; What is the purpose of the call to proc-val on the next-to-last line of apply-env?
;; To be evaluated by value-of.
| false |
d0febc94e8526ddbea6e4db67c74ca92104698da | 310fec8271b09a726e9b4e5e3c0d7de0e63b620d | /badges.rkt | 40d37db798d32b561eff9fbe696a7c17148804f7 | [
"Apache-2.0",
"MIT"
] | permissive | thoughtstem/badge-bot | b649f845cdc4bf62ca6bd838f57353f8e508f1ae | e535eefac26f15061c412fd0eb5b7adee158a0bf | refs/heads/master | 2022-12-14T21:55:00.173000 | 2020-09-21T19:54:15 | 2020-09-21T19:54:15 | 265,321,144 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 5,520 | rkt | badges.rkt | #lang racket
(provide (all-from-out "badges-lang.rkt"
"./badges/scratch.rkt"
"./badges/coding-adventures.rkt"
"./badges/wescheme.rkt"
"./badges/wescheme-game-design.rkt"
"./badges/2d-drracket.rkt"
"./badges/3d-drracket.rkt"
"./badges/bonus.rkt"
"./badges/python.rkt"
"./badges/web-design.rkt"
"./badges/cpx.rkt"))
(require "badges-lang.rkt"
"images.rkt"
"./badges/coding-adventures.rkt"
"./badges/scratch.rkt"
"./badges/wescheme.rkt"
"./badges/wescheme-game-design.rkt"
"./badges/2d-drracket.rkt"
"./badges/3d-drracket.rkt"
"./badges/bonus.rkt"
"./badges/python.rkt"
"./badges/web-design.rkt"
"./badges/cpx.rkt"
)
;; DIGITAL LITERACY BADGES START
(define-colored-art-badge 'lightgreen
dl-dl-aa
"Digital Literacy Access Badge"
"https://forum.metacoders.org/t/digital-literacy-access-badge/134"
)
(define-colored-art-badge 'lightgreen
dl-ds-vc
"Digital Literacy: Zoom: Video Chat Features"
"https://forum.metacoders.org/t/digital-literacy-zoom-video-chat-features/118"
)
(define-colored-art-badge 'lightgreen
dl-ds-tc
"Digital Literacy: Zoom: Chat Hello World"
"https://forum.metacoders.org/t/digital-literacy-discord-text-channel-hello-world/129"
)
(define-colored-art-badge 'lightgreen
dl-sc-wj
"Digital Literacy: Screen Capturing: Screenshot Badge"
"https://forum.metacoders.org/t/digital-literacy-screen-capturing-screenshot-badge/110"
)
(define-colored-art-badge 'lightgreen
screenshare
"Digital Literacy: Screen Capturing: Screenshare Badge"
"https://forum.metacoders.org/t/digital-literacy-screen-capturing-screenshare-badge/390"
)
(define-colored-art-badge 'lightgreen
browser-tabs
"Digital Literacy: Operating System: Browser Tabs"
"https://forum.metacoders.org/t/digital-literacy-operating-system-browser-tabs/121"
)
(define-colored-art-badge 'lightgreen
multiple-windows
"Digital Literacy: Operating System: Multiple Windows"
"https://forum.metacoders.org/t/digital-literacy-operating-system-multiple-windows/392"
)
;;DIGITAL LITERACY BADGES END
;; TYPING BADGES BADGES START
(define-colored-art-badge 'lightgreen
dl-ts-ql
"Digital Literacy: Typing Speed - Level 1"
"https://forum.metacoders.org/t/digital-literacy-typing-speed-level-1/125"
)
#|
(define-colored-art-badge 'lightgreen
dl-ts-er
"Digital Literacy: Typing Speed: Level 2"
"https://forum.metacoders.org/t/digital-literacy-typing-speed-level-2/126"
)
(define-colored-art-badge 'lightgreen
dl-ts-vb
"Digital Literacy: Typing Speed: Level 3 "
"https://forum.metacoders.org/t/digital-literacy-typing-speed-level-3/127"
)
(define-colored-art-badge 'lightgreen
dl-ts-gh
"Digital Literacy: Typing Speed: Level 4"
"https://forum.metacoders.org/t/digital-literacy-typing-speed-level-4/128"
)
|#
;; TYPING BADGES END
;;TOUR OF LANGUAGES BADGES START
#|
(define-colored-art-badge 'lightred
dl-ll-tj
"Digital Literacy: Tour of Languages: Three.js Intro"
"https://forum.metacoders.org/t/digital-literacy-tour-of-languages-three-js-intro/150"
)
(define-colored-art-badge 'lightred
dl-ll-py
"Digital Literacy: Tour of Languages: Python Hello World"
"https://forum.metacoders.org/t/digital-literacy-tour-of-languages-python-hello-world/151"
)
(define-colored-art-badge 'lightred
dl-ll-js
"Digital Literacy: Tour of Languages: Javascript Hello World"
"https://forum.metacoders.org/t/digital-literacy-tour-of-languages-javascript-hello-world/152"
)
(define-colored-art-badge 'lightred
dl-ll-ja
"Digital Literacy: Tour of Languages: Java Hello World"
"https://forum.metacoders.org/t/digital-literacy-tour-of-languages-java-hello-world/153"
)
(define-colored-art-badge 'lightred
dl-ll-ru
"Digital Literacy: Tour of Languages: Ruby Hello World"
"https://forum.metacoders.org/t/digital-literacy-tour-of-languages-ruby-hello-world/154"
)
(define-colored-art-badge 'lightred
dl-ll-sc
"Digital Literacy: Tour of Languages: Scheme Hello World"
"https://forum.metacoders.org/t/digital-literacy-tour-of-languages-scheme-hello-world/351"
)
(define-colored-art-badge 'lightred
dl-ll-mh
"Digital Literacy: Tour of Languages: Multiple Hello Worlds"
"https://forum.metacoders.org/t/digital-literacy-tour-of-languages-multiple-hello-worlds/155"
)
|#
;;TOUR OF LANGAUGES BADGES END
;; GAME DESIGN BADGES START
(define-colored-art-badge 'lightgreen
game-design
"Game Design Access Badge"
"https://forum.metacoders.org/t/game-design-access-badge/401"
)
(define-colored-art-badge 'lightgreen
gd-dr-aa
"DrRacket Game Design"
"https://forum.metacoders.org/t/game-design-drracket-installation/236"
)
(define-colored-art-badge 'lightgreen
wescheme-gd
"WeScheme Game Design"
"https://forum.metacoders.org/t/wescheme-game-design/402"
)
(define-colored-art-badge 'lightgreen
2d-gd-aa
"2D Game Design Access Badge"
"https://forum.metacoders.org/t/2d-game-design-access-badge/237"
)
(define-colored-art-badge 'lightgreen
3d-gd-aa
"3D Game Design Access Badge"
"https://forum.metacoders.org/t/3d-game-design-access-badge/238"
)
;; GAME DESIGN BADGES END
| false |
8307cad4ed4f399b68051180b98756678fb265d8 | 2bb711eecf3d1844eb209c39e71dea21c9c13f5c | /rosette/base/unbound/function.rkt | 2ed43a42fe7f88b3d9d0973b123d022e4bf103a3 | [
"BSD-2-Clause"
] | permissive | dvvrd/rosette | 861b0c4d1430a02ffe26c6db63fd45c3be4f04ba | 82468bf97d65bde9795d82599e89b516819a648a | refs/heads/master | 2021-01-11T12:26:01.125000 | 2017-01-25T22:24:27 | 2017-01-25T22:24:37 | 76,679,540 | 2 | 0 | null | 2016-12-16T19:23:08 | 2016-12-16T19:23:07 | null | UTF-8 | Racket | false | false | 7,616 | rkt | function.rkt | #lang racket
(require
syntax/id-table
(for-syntax racket syntax/parse)
(only-in "../core/bool.rkt" with-asserts)
(only-in "../core/term.rkt"
constant constant? expression term-type
solvable-domain solvable-range
term-cache clear-terms!)
(only-in "contracts.rkt" λ/typed)
(only-in "utils.rkt" hash-values-diff+filter gensym)
(only-in "call-graph.rkt" with-call called? stack-size recursive? mutual-recursion-root?)
"mutations.rkt" "dependencies.rkt" "encoding.rkt")
(provide (for-syntax make-solvable-function) instantiate-high-order-solvable-function)
(define-for-syntax (make-solvable-function head args type body)
#`(with-handlers ([exn:fail?
(λ (err)
(λ (#,@args)
(raise err)))])
(let* ([head-syntax #,head]
[type #,type])
(λ/typed (#,@args) type
(cond
[(already-speculated? head-syntax)
(symbolize head-syntax (list #,@args))]
[(speculating-currently? head-syntax)
(symbolize-if-associated head-syntax (list #,@args))]
[else
(with-call head-syntax
(let* ([head-constant (constant (syntax->datum head-syntax) type)]
[_ (free-id-table-set! applicable-constants head-syntax head-constant)]
[_ (associate-id head-syntax head-constant)]
[arg-constants (box #f)]
[state/before (state-before-call)]
[state/middle (box #f)]
[term-cache-snapshot (box #f)]
[impl (λ ()
(cond
[(unbox state/middle)
(restore-symbolization (unbox state/middle))]
[else
(mutables:=symbolic!/track head-constant state/before)
(set-box! state/middle (create-rollback-point))])
#,@(for/list ([arg (syntax->list args)]
[i (in-naturals)])
#`(define #,arg (constant (gensym '#,arg) (i-th-member-of-domain #,i type))))
(set-box! arg-constants (list #,@args))
(unless (unbox term-cache-snapshot)
(set-box! term-cache-snapshot (hash-copy (term-cache))))
(let-values ([(term state) (speculate* (#,body))])
(cons term state)))])
(solvable-function->horn-clauses head-syntax head-constant
(list #,@args) arg-constants
impl term-cache-snapshot)))])))))
(define (i-th-member-of-domain i type)
(let ([domain (solvable-domain type)])
(if (< i (length domain))
(list-ref domain i)
(error 'define "Too many arguments!"))))
(define-syntax-rule (speculate/symbolized body head-constant)
(with-handlers ([exn:fail:syntax? raise]
[exn:fail? (λ (err)
(values
(constant (gensym '⊥) (solvable-range (term-type head-constant)))
'()
'(#f)))])
(let-values
([(pair assertions)
(with-asserts
(let-values ([(pair _) (speculate* body)])
pair))])
(values (car pair) (cdr pair) assertions))))
(define (already-speculated? id) (and (dict-has-key? applicable-constants id) (not (called? id))))
(define (speculating-currently? id) (called? id))
(define (call-tree-root?) (equal? (stack-size) 2))
(define high-order-functions (make-hash))
(define (instantiate-high-order-solvable-function id functions constructor)
(if (empty? functions)
(constructor)
; Of course comparing object-name instead of function itself can introduce collisions, but there is no other way.
(hash-ref! high-order-functions (cons id (map object-name functions)) constructor)))
(define applicable-constants (make-free-id-table))
(define delimited-encodings (make-parameter (list)))
(define current-state-before-call (make-parameter #f))
(define (state-before-call)
(when (call-tree-root?)
(current-state-before-call (create-rollback-point)))
(current-state-before-call))
(define (symbolize head args)
(let* ([head-constant (free-id-table-ref applicable-constants head)]
[read-dependencies (read-dependencies/current head-constant)]
[constants (mutables:=symbolic!/memorize (write-dependencies-states head))])
(function-application->symbolic-constant head-constant
args
read-dependencies
constants)))
(define (symbolize-if-associated head args)
(let ([head-constant (free-id-table-ref applicable-constants head)])
(if (read-dependencies-ready? head)
(let ([read-dependencies (read-dependencies/current head-constant)]
[constants (mutables:=symbolic!/memorize (write-dependencies-states head-constant))])
(expression dependent-app
(apply head-constant args)
read-dependencies
constants))
(with-call head
(apply (constant (gensym) (term-type head-constant)) args)))))
(define (solvable-function->horn-clauses head head-constant
args arg-constants
body term-cache-snapshot)
(define-values (term state/after assertions)
(speculate/symbolized (body) head-constant))
; TODO: make it more effective
(define scoped-constants (hash-values-diff+filter constant? (term-cache) (unbox term-cache-snapshot)))
(set-up-read-dependencies head-constant
term
(unbox arg-constants)
scoped-constants
state/after)
(set-up-write-dependencies head-constant state/after)
(define (delimited-encoding)
(when (recursive? head)
; For recusive functions we need second execution, because we know set of write-dependencies only now.
(set!-values (term state/after assertions) (speculate/symbolized (body) head-constant))
(set! scoped-constants (hash-values-diff+filter constant? (term-cache) (unbox term-cache-snapshot)))
(set-up-read-dependencies head-constant
term
(unbox arg-constants)
scoped-constants
state/after)
(set-up-write-dependencies head-constant state/after))
(eval/horn term
head-constant
(unbox arg-constants)
assertions))
(cond [(recursive? head)
(delimited-encodings (cons delimited-encoding (delimited-encodings)))
(cond
[(mutual-recursion-root?)
(eval-delimited-encodings head args)
(symbolize head args)]
[else
(constant (gensym) (solvable-range (term-type head-constant)))])]
[else
(delimited-encoding)
(symbolize head args)]))
(define (eval-delimited-encodings head args)
(for ([enc (reverse (delimited-encodings))]) (enc))
(delimited-encodings (list)))
| true |
71360edc26548b925a0746ea950c4af06ed77873 | d29c2c4061ea24d57d29b8fce493d116f3876bc0 | /util/syntax-quote-macros.rkt | 7aa304a6868ee5b526cece251b7d54edbf155caa | [] | no_license | jbejam/magnolisp | d7b28e273550ff0df884ecd73fb3f7ce78957d21 | 191d529486e688e5dda2be677ad8fe3b654e0d4f | refs/heads/master | 2021-01-16T19:37:23.477000 | 2016-10-01T16:02:42 | 2016-10-01T16:02:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,098 | rkt | syntax-quote-macros.rkt | #lang racket/base
#|
|#
(require "../util.rkt"
(for-syntax racket/base "syntax-quote-extras.rkt"))
(define-syntax* (quote-syntax/keep-properties stx)
(syntax-case stx ()
[(_ e #:listed (sym ...))
(syntax-preserve/loc+listed (syntax->datum #'(sym ...)) #'e)]
[(_ e #:all)
(syntax-preserve/loc+all #'e)]
[(_ e)
(syntax-preserve/loc+none #'e)]))
(module* test #f
(require racket rackunit)
(define y 7)
(define stx-for-y (quote-syntax/keep-properties y))
(check-pred syntax? stx-for-y)
(check-pred syntax-position stx-for-y)
(check-false (syntax-property stx-for-y 'paren-shape))
(check-eqv? (eval-syntax stx-for-y) y)
(define stx-for-p
(quote-syntax/keep-properties [y] #:listed (paren-shape)))
(check-pred syntax? stx-for-p)
(check-pred syntax-position stx-for-p)
(check-not-false (syntax-property stx-for-p 'paren-shape))
(define stx-for-a
(quote-syntax/keep-properties [y] #:all))
(check-pred syntax? stx-for-a)
(check-pred syntax-position stx-for-a)
(check-not-false (syntax-property stx-for-a 'paren-shape)))
| true |
4348fa5b1b26aa471e3a18a05c9fd6349f6e429e | 653a443b27ff3d39e9b6ec99f6973fc9e3d6f53c | /langs/day1.rkt | df19ec5c7096986b95625a32fb75812f0a63c02d | [] | no_license | jeapostrophe/compy | 18a3137f5665e3b986894870ee50561350216c07 | 1d0aa4eafe2f42c9d94a56c6da0a73738b88200a | refs/heads/master | 2022-12-08T07:05:10.581000 | 2022-12-02T21:18:50 | 2022-12-02T21:18:50 | 2,500,718 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,741 | rkt | day1.rkt | #lang racket/base
(require racket/contract
racket/match
(prefix-in x86: "asm.rkt"))
(struct e () #:prefab)
(struct num e (n) #:prefab)
(struct binop e (op assoc? lhs rhs) #:prefab)
(struct unaop e (op lhs) #:prefab)
(define binops
(hasheq '+ (cons x86:add #t)
'- (cons x86:sub #f)
'bitwise-and (cons x86:and #t)
'bitwise-ior (cons x86:or #t)
'bitwise-xor (cons x86:xor #t)))
(define unaops
(hasheq 'add1 x86:inc
'sub1 x86:dec
'bitwise-not x86:not))
(define parse
(match-lambda
[(list (and (? symbol?)
(app (lambda (s)
(hash-ref binops s #f))
(cons opcode assoc?)))
lhs
rhs)
(binop opcode assoc?
(parse lhs)
(parse rhs))]
[(list (and (? symbol?)
(app (lambda (s)
(hash-ref unaops s #f))
(and (not #f)
opcode)))
lhs)
(unaop opcode
(parse lhs))]
[(? byte? b)
(num b)]))
#|
We rely on the invariant that inner expression always return their
value to EAX.
|#
(define to-asm
(match-lambda
[(binop op assoc? lhs rhs)
#|
First, evaluate the LHS and save the result on the stack. Then
evaluate the RHS and move the result to EBX. Then restore the LHS
to EAX. Then do the math, storing the result in EAX.
If the operation is associative, we can get rid of one mov
|#
(x86:seqn
;; LHS -> stack
(to-asm lhs)
(x86:push x86:eax)
;; RHS -> eax
(to-asm rhs)
(if assoc?
(x86:seqn
;; LHS -> ebx
(x86:pop x86:ebx))
(x86:seqn
;; RHS -> ebx
(x86:mov x86:ebx x86:eax)
;; LHS -> eax
(x86:pop x86:eax)))
;; (op LHS RHS) -> eax
(op x86:eax x86:ebx))]
[(unaop op lhs)
(x86:seqn
;; LHS -> eax
(to-asm lhs)
;; (op LHS) -> eax
(op x86:eax))]
[(num b)
(x86:seqn
(x86:mov x86:eax b))]))
(define (x86-op->racket-op o)
(cond
[(equal? o x86:add) +]
[(equal? o x86:sub) -]
[(equal? o x86:or) bitwise-ior]
[(equal? o x86:xor) bitwise-xor]
[(equal? o x86:and) bitwise-and]
[(equal? o x86:inc) add1]
[(equal? o x86:dec) sub1]
[(equal? o x86:not) bitwise-not]))
(define interp
(match-lambda
[(binop op _ lhs rhs)
((x86-op->racket-op op)
(interp lhs)
(interp rhs))]
[(unaop op lhs)
((x86-op->racket-op op)
(interp lhs))]
[(num b)
b]))
(provide
(contract-out
[struct e ()]
[struct (num e) ([n byte?])]
[parse (-> any/c e?)]
[to-asm (-> e? x86:asm?)]
[interp (-> e? any/c)]))
| false |
b4dd5d7cdc815df060ce8399450db0ec65609dbd | 7f31e3a68cf34d3870654ffb485b9f8ec3f64ca5 | /mpi/info.rkt | 272188ddded1d91cb1539144a23b0feb5f3a5dd2 | [] | no_license | jeapostrophe/openmpi | 31ae37cc2e2f9deabb10f182017acb16a379017c | 0750c3443492b1b240fdb246dc61cee542ec7b3d | refs/heads/master | 2022-12-11T13:26:57.366000 | 2022-12-02T21:08:40 | 2022-12-02T21:08:40 | 967,673 | 2 | 1 | null | 2015-08-01T10:49:13 | 2010-10-06T21:21:50 | Racket | UTF-8 | Racket | false | false | 111 | rkt | info.rkt | #lang setup/infotab
(define name "OpenMPI")
(define scribblings '(["mpi.scrbl" (multi-page) ("Parallelism")]))
| false |
33531f4b3e92102e8fd0fd27808c4708e2ec7330 | 7b85a7cefb9bd64e9032276844e12ebac7973a69 | /unstable-test/tests/unstable/info.rkt | e21e068db841071cd37f949b8f87e6e1ba1c7f67 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | racket/unstable | 28ac91ca96a0434db99a097a6d4d2f0a1ca26f1e | 99149bf1a6a82b2309cc04e363a87ed36972b64b | refs/heads/master | 2021-03-12T21:56:07.687000 | 2019-10-24T01:04:57 | 2019-10-24T01:04:57 | 27,411,322 | 2 | 5 | NOASSERTION | 2020-06-25T19:01:26 | 2014-12-02T02:33:45 | Racket | UTF-8 | Racket | false | false | 220 | rkt | info.rkt | #lang info
(define test-responsibles '(("options.rkt" (robby chrdimo))
("logging.rkt" stamourv)
("list.rkt" jay)
("match.rkt" samth)))
| false |
3731192aefea061068715177f07e1b893bda8953 | 135420dc906c4e8bb1805c7cba71199b90e20502 | /sfont/private/ufo/ufo-read-write.rkt | 79b3e5291c0ba721446c4fd2063f393a0a61ebf6 | [
"MIT"
] | permissive | danielecapo/sfont | 067b14db062221bfda41500e9abfb888ceba49f1 | c854f9734f15f4c7cd4b98e041b8c961faa3eef2 | refs/heads/master | 2021-01-19T01:30:23.989000 | 2020-07-06T09:15:30 | 2020-07-06T09:15:30 | 12,197,113 | 25 | 3 | MIT | 2020-07-06T09:15:32 | 2013-08-18T15:21:02 | Racket | UTF-8 | Racket | false | false | 31,583 | rkt | ufo-read-write.rkt | #lang racket
(require "plists.rkt"
"ufo-def.rkt"
"names.rkt"
"../../geometry.rkt"
xml
xml/path
xml/plist)
(provide
(contract-out
[read-ufo (->* (path-string?) font?)]
[write-ufo (->* (font? path-string?)
(#:format (one-of/c 2 3)
#:overwrite boolean?)
void?)]))
(struct glif (format name advance unicodes
note image guidelines anchors
contours components lib))
; (listOf (Symbol . T)) -> (listOf keyword)
; produce a list of keywords from a key-value pairs list
(define (collect-keywords kvs)
(map (lambda (kv)
(string->keyword
(symbol->string (car kv))))
kvs))
; (listOf (Symbol . T)) -> (listOf T)
; produce a list of values from a key-value pairs list
(define (collect-values kvs)
(map cadr kvs))
; (... -> T) (listOf (Symbol . T)) -> T
; apply the procedure with the key-value pairs list as arguments
(define (apply-with-kws proc kvs)
(keyword-apply proc (collect-keywords kvs) (collect-values kvs) '()))
; ... -> Point
; produce a point from ...
(define (parse-point p)
(apply-with-kws build-point (cadr p)))
; (listOf Outlines) -> (listOf Contour) (listOf Component) (listOf Anchor)
; separate contours, components and anchors
(define (parse-outlines os)
(define (aux contours components anchors elts)
(match elts
[(list) (values contours components anchors)]
[(list-rest e elts)
(match e
[(list 'contour id (list point (list-no-order '(type "move") `(name ,name) `(x ,x) `(y ,y))))
(aux contours
components
(append anchors
(list (build-anchor #:x x #:y y #:name name)))
elts)]
[(list-rest 'contour id points)
(aux (append contours
(list (apply-with-kws
build-contour
(append id (list (list 'points (map parse-point points)))))))
components
anchors
elts)]
[(list 'component args)
(aux contours
(append components (list (apply-with-kws
build-component
args)))
anchors
elts)])]))
(aux null null null os))
; Xexpr [Symbol or False] -> Glif
; produce a Glyph from a xexpr representation, if name is not false ovveride the glyph name
(define (xexpr->glif x [name #f])
(define (aux acc elts)
(match elts
[(list) acc]
[(list-rest elt restelts)
(match elt
[(list 'advance args)
(aux (struct-copy glif acc
[advance (apply-with-kws build-advance args)])
restelts)]
[(list 'unicode (list (list 'hex hex)))
(aux (struct-copy glif acc
[unicodes (append (glif-unicodes acc) (list (string->unicode hex)))])
restelts)]
[(list 'note null n)
(aux (struct-copy glif acc [note n])
restelts)]
[(list 'image args)
(aux (struct-copy glif acc
[image (apply-with-kws build-image args)])
restelts)]
[(list 'guideline args)
(aux (struct-copy glif acc
[guidelines (cons (apply-with-kws build-guideline args)
(glif-guidelines acc))])
restelts)]
[(list 'anchor args)
(aux (struct-copy glif acc
[anchors (cons (apply-with-kws build-anchor args)
(glif-anchors acc))])
restelts)]
[(list-rest 'outline null outlines)
(let-values ([(contours components anchors) (parse-outlines outlines)])
(aux (struct-copy glif
(struct-copy glif acc [contours contours])
[components components]
[anchors (append (glif-anchors acc) anchors)])
restelts))]
[(list 'lib null d)
(aux (struct-copy glif acc
[lib (xexpr->dict d)])
restelts)]
[_ acc])]))
(aux (glif (string->number (se-path* '(glyph #:format) x))
(if name name (string->symbol (se-path* '(glyph #:name) x)))
(build-advance) null #f #f null null null null (make-immutable-hash))
(se-path*/list '(glyph) x)))
; if the value expr evaluetes to the default value produce the empty list otherwise evaluates expr
(define-syntax-rule (not-default val defaultvalue expr)
(if (equal? val defaultvalue) '() (list expr)))
; Number->String
(define (number->ufostring n)
(number->string
(if (integer? n)
(inexact->exact n)
(exact->inexact n))))
; Glif -> Xexpr
; produce an Xexpr representation of the glyph
(define (glif->xexpr g)
(letrec [(aux
(lambda (g)
(match g
[#f '()]
[(glif format name advance codes note image
guidelines anchors contours components lib)
`(glyph ((format ,(number->ufostring format))
(name ,(symbol->string name)))
,(aux advance)
,@(map (lambda (c) `(unicode ((hex ,(unicode->string c))))) codes)
,@(not-default note #f `(note () ,note))
;(if note `((note () ,note)) '())
,@(aux image)
,@(map (lambda (guideline) (aux guideline)) guidelines)
,@(map (lambda (anchor) (aux anchor)) anchors)
(outline ,@(map (lambda (contour) (aux contour)) contours)
,@(map (lambda (component) (aux component)) components))
,@(not-default lib (make-immutable-hash) `(lib () ,(dict->xexpr lib)))
)]
[(advance width height)
`(advance (,@(list `(width ,(number->ufostring width)))
,@(not-default height 0 `(width ,(number->ufostring height)))))]
[(image filename (trans-mat xs xys yxs ys xo yo) color)
`((image ((fileName ,filename)
,@(not-default xs 1 `(xScale ,(number->ufostring xs)))
,@(not-default xys 0 `(xyScale ,(number->ufostring xys)))
,@(not-default yxs 0 `(yxScale ,(number->ufostring yxs)))
,@(not-default ys 1 `(yScale ,(number->ufostring ys)))
,@(not-default xo 0 `(xOffset ,(number->ufostring xo)))
,@(not-default yo 0 `(yOffset ,(number->ufostring yo)))
,@(not-default color #f `(color ,(color->string color))))))]
[(guideline (vec x y) angle name color identifier)
`(guideline (,@(not-default x #f `(x ,(number->ufostring x)))
,@(not-default y #f `(y ,(number->ufostring y)))
,@(not-default angle #f `(angle ,(number->ufostring angle)))
,@(not-default name #f `(name ,name))
,@(not-default color #f `(color ,(color->string color)))
,@(not-default identifier #f `(identifier ,(symbol->string identifier)))))]
[(anchor (vec x y) name color identifier)
`(anchor (,@(not-default x #f `(x ,(number->ufostring x)))
,@(not-default y #f `(y ,(number->ufostring y)))
,@(not-default name #f `(name ,name))
,@(not-default color #f `(color ,(color->string color)))
,@(not-default identifier #f `(identifier ,(symbol->string identifier)))))]
[(contour id points)
`(contour (,@(not-default id #f `(identifier ,(symbol->string id))))
,@(map (lambda (p) (aux p)) points))]
[(point (vec x y) type smooth name id)
`(point ((x ,(number->ufostring x))
(y ,(number->ufostring y))
,@(not-default type 'offcurve `(type ,(symbol->string type)))
,@(not-default smooth #f `(smooth "yes"))
,@(not-default name #f `(name ,name))
,@(not-default id #f `(identifier ,(symbol->string id)))))]
[(component base (trans-mat xs xys yxs ys xo yo) id)
`(component ((base ,(symbol->string base))
,@(not-default xs 1 `(xScale ,(number->ufostring xs)))
,@(not-default xys 0 `(xyScale ,(number->ufostring xys)))
,@(not-default yxs 0 `(yxScale ,(number->ufostring yxs)))
,@(not-default ys 1 `(yScale ,(number->ufostring ys)))
,@(not-default xo 0 `(xOffset ,(number->ufostring xo)))
,@(not-default yo 0 `(yOffset ,(number->ufostring yo)))
,@(not-default id #f `(identifier ,(symbol->string id)))))]
)))]
(aux g)))
; (aux (if (= (glyph-format g) 1)
; (glyph->glyph1 g)
; (glyph->glyph2 g)))))
; String [Symbol or False] -> Glif
; produce a Glyph read from path, if name is not false ovveride the glyph name
(define (read-glif-file path [name #f])
(xexpr->glif
(xml->xexpr
((eliminate-whitespace
'(glyph advance unicode image guideline anchor
outline contour point component lib dict array)
identity)
(document-element
(call-with-input-file path read-xml))))
name))
; Glyph String -> side effects
; write the glyph to path
(define (write-glif-file g path)
(call-with-output-file
path
(lambda (o)
(parameterize ([empty-tag-shorthand 'always])
(display-xml
(document
(prolog (list (p-i (location 1 0 1)
(location 1 38 39)
'xml "version=\"1.0\" encoding=\"UTF-8\""))
#f '())
(xexpr->xml (glif->xexpr g))
'())
o)))
#:exists 'replace))
; Glif Symbol -> Layer
(define (glif->layer g n)
(match g
[(glif _ _ _ _ _ _ guidelines anchors contours components _)
(layer n guidelines anchors contours components)]))
; Glif -> Glyph
(define (glif->glyph g)
(match g
[(glif format name advance unicodes
note image _ _ _ _ lib)
(glyph name advance unicodes note image
(list (layer foreground null null null null)) lib)]))
; (listof Glyph) (listof (Cons Symbol (HashTable Symbol Glif)))
(define (add-layers-to-glyphs glyphs layer-glifs)
(map (lambda (g)
(foldl (lambda (l ga)
(let ([glifl (hash-ref (cdr l) (glyph-name g) #f)])
(if glifl
(struct-copy glyph ga
[layers (hash-set (glyph-layers ga)
(car l)
(glif->layer glifl (car l)))])
ga)))
g
layer-glifs))
glyphs))
; Glyph Symbol -> Glif
(define (glyph->glif g l format)
(let ([elts (if (get-layer g l)
(match (if (= format 1)
(layer->layer1 (get-layer g l))
(get-layer g l))
[(layer _ guidelines anchors contours components)
(list guidelines anchors contours components)])
(list null null null null))])
(match g
[(glyph name advance unicodes
note image _ lib)
(glif format name advance unicodes note image
(first elts) (second elts)
(third elts) (fourth elts)
lib)])))
;
; String (String -> T1) (String -> T2) -> UfoReader
; produce a reader for the ufo file in path
(define (reader path [proc-data identity] [proc-images identity])
(define (make-ufo-path file)
(build-path path file))
(define (read-from-plist path)
(with-handlers ([exn:fail? (lambda (e) #f)])
(if (file-exists? path)
(read-dict path)
#f)))
(define (read-from-text-file path)
(if (file-exists? path)
(call-with-input-file path port->string)
#f))
(define (read-groups)
(let ([g (read-from-plist (make-ufo-path "groups.plist"))])
(if g
(make-immutable-hash
(hash-map g (lambda (name content)
(cons name (map string->symbol content)))))
(make-immutable-hash))))
(define layers
(let ([l (read-from-plist (make-ufo-path "layercontents.plist"))])
(if l
(if (memf (lambda (la) (equal? (second la) "glyphs")) l)
(map (lambda (la) (if (equal? (second la) "glyphs")
(list "public.default" "glyphs")
la))
l)
(error "The font doesn't have the required default layer"))
(list (list "public.default" "glyphs")))))
(define (read-layerinfo glyphsdir)
(read-from-plist
(build-path (make-ufo-path glyphsdir) "layerinfo.plist")))
(define (read-layers)
(map (lambda (l)
(let* ([layer-dir (cadr l)]
[layer-name (car l)]
[info (read-layerinfo layer-dir)])
(if info
(layer-info
(string->symbol layer-name)
(if (dict-ref info 'color #f)
(ensure-color (dict-ref info 'color))
#f)
(dict-ref info 'lib (make-immutable-hash)))
(layer-info (string->symbol layer-name) #f (make-immutable-hash)))))
layers))
(define (read-layer-glifs)
(map (lambda (l) (cons (string->symbol (car l)) (read-glifs (cadr l))))
layers))
(define (read-glifs glifsdir)
(let* ([glifspath (make-ufo-path glifsdir)]
[contents (read-from-plist (build-path glifspath "contents.plist"))])
(make-hash (map (lambda (g) (cons (glif-name g) g))
(hash-map contents
(lambda (k v) (read-glif-file (build-path glifspath v) k)))))))
; (map (lambda (l)
; (layer (string->symbol (car l))
; (read-layerinfo (cadr l))
; (read-glyphs (cadr l))))
; (if layers layers (list (list "public.default" "glyphs"))))))
(define (read-glyphs)
(let* ([layer-glifs (read-layer-glifs)]
[glyphs (hash-map (dict-ref layer-glifs foreground)
(lambda (k v)
(glif->glyph v)))])
(add-layers-to-glyphs glyphs layer-glifs)))
; (let* ([glyphspath (make-ufo-path glyphsdir)]
; [contents (read-from-plist (build-path glyphspath "contents.plist"))])
; (hash-map contents
; (lambda (k v) (read-glif-file (build-path glyphspath v) k)))))
(define (read-from-directory path [proc #f])
(if (directory-exists? path)
(if proc
(proc path)
path)
#f))
(let ([s (list
(cons 'meta (lambda () (read-from-plist (make-ufo-path "metainfo.plist"))))
(cons 'info (lambda () (read-from-plist (make-ufo-path "fontinfo.plist"))))
(cons 'groups read-groups)
(cons 'kerning (lambda () (let ([k (read-from-plist (make-ufo-path "kerning.plist"))])
(if k k (make-immutable-hash)))))
(cons 'features (lambda () (read-from-text-file (make-ufo-path "features.fea"))))
(cons 'lib (lambda () (let ([l (read-from-plist (make-ufo-path "lib.plist"))])
(if l l (make-immutable-hash)))))
(cons 'layers read-layers)
(cons 'glyphs read-glyphs)
(cons 'data (lambda () (read-from-directory (make-ufo-path "data") proc-data)))
(cons 'images (lambda () (read-from-directory (make-ufo-path "images") proc-images))))])
(lambda (k) (dict-ref s k))))
; String (String -> T1) (String -> T2) -> Font
; produce a font read from ufo file in path
(define (read-ufo path )
(if (directory-exists? path)
(let* ([reader (reader path identity identity)]
[meta ((reader 'meta))]
[format (dict-ref meta 'formatVersion)]
[creator (dict-ref meta 'creator)])
(cond [(= format 2) (kern-groups2->3 (read-ufo2 creator reader))]
[(= format 3) (read-ufo3 creator reader)]
[#t (error "I can only read ufo 2 and ufo 3 fonts")]))
(error "file do not exists")))
; String UfoReader -> Font
; produce a font from an UFO2 file
(define (read-ufo2 creator reader)
(font ((reader 'info))
((reader 'groups))
((reader 'kerning))
((reader 'features))
((reader 'glyphs))
((reader 'layers))
((reader 'lib))
#f
#f))
; String UfoReader -> Font
; produce a font from an UFO3 file
(define (read-ufo3 creator reader)
(font ((reader 'info))
((reader 'groups))
((reader 'kerning))
((reader 'features))
((reader 'glyphs))
((reader 'layers))
((reader 'lib))
((reader 'data))
((reader 'images))))
(define (layer-info->hash l)
(let ([clr (if (layer-info-color l)
(list (cons 'color (color->string (layer-info-color l))))
null)]
[lib (if (layer-info-lib l)
(list (cons 'lib (layer-info-lib l)))
null)])
(make-immutable-hash (append clr lib))))
; Font String (String -> ...) (String -> ...) -> UfoWriter
; produce a writer for the ufo file in path
(define (writer f path format [proc-data #f] [proc-images #f])
(define (make-ufo-path file)
(build-path path file))
(define (write-on-plist dict path [force #f])
(when (and dict (or force (> (dict-count dict) 0)))
(write-dict dict path)))
(define (write-kerning k path)
(when (and k (> (dict-count k) 0))
(let* ([k-list (sorted-kerning-list k)]
[k-plist
(cons 'dict
(for/list ([el k-list])
`(assoc-pair ,(symbol->string (car el))
,(cons 'dict
(for/list ([el2 (cdr el)])
`(assoc-pair ,(symbol->string (car el2))
,(dict->plist (cdr el2))))))))])
(call-with-output-file path
(lambda (out)
(write-plist k-plist out))
#:exists 'replace))))
(define (write-directory dir path [proc #f])
(if dir
(if proc
(proc path)
(unless (and (directory-exists? path)
(= (file-or-directory-identity path)
(file-or-directory-identity dir)))
(begin
(when (directory-exists? path)
(delete-directory/files path))
(copy-directory/files dir path))))
(begin
(when (directory-exists? path)
(delete-directory/files path))
(make-directory path))))
(define (write-on-text-file text path)
(when text
(let ([text (string-trim text)])
(when (and (string? text) (not (string=? "" text)))
(call-with-output-file path
(lambda (o)
(write-string text o)))))))
(define (write-groups)
(write-on-plist (make-immutable-hash
(hash-map (font-groups f)
(lambda (name content)
(cons name (map symbol->string content)))))
(make-ufo-path "groups.plist")))
(define (get-layers-names)
(letrec ([aux (lambda (acc layers names)
(match layers
[(list) acc]
[(list-rest (layer-info 'public.default _ _) rest-layers)
(aux (cons (cons foreground "glyphs") acc)
rest-layers
(cons "glyphs" names))]
[(list-rest (layer-info l _ _) rest-layers)
(let ([name (namesymbol->filename l "glyphs." "" names)])
(aux (cons (cons l name) acc)
rest-layers
(cons name names)))]))])
(if (dict-has-key? (font-layers f) foreground)
(if (= format 2)
(list (cons foreground "glyphs"))
(reverse (aux '() (map cdr (font-layers f)) '())))
(error "The font doesn't have the required public.default layer"))))
(define layers-names (get-layers-names))
(define (write-glyphs l glyphsdir)
(letrec ([aux (lambda (glyphs acc names)
(match glyphs
[(list) (make-immutable-hash (reverse acc))]
[(list-rest g rest-glyphs)
(let* ([name (namesymbol->filename (glyph-name g) "" ".glif" names)]
[gl (if (get-layer g l)
(glyph->glif g l (if (= format 3) 2 1))
#f)])
(begin
(when gl (write-glif-file gl (build-path glyphsdir name)))
(aux rest-glyphs
(if gl
(cons (cons (glyph-name g) name) acc)
acc)
(cons name names))))]))])
(write-on-plist (aux (hash-values (font-glyphs f)) '() '())
(build-path glyphsdir "contents.plist")
#t)))
(define (write-layers)
(for-each (lambda (l)
(begin
(let ([dir (make-ufo-path (cdr l))]
[la (car l)])
(make-directory dir)
(write-glyphs la dir)
(when (= format 3)
(write-layerinfo la dir)))))
layers-names))
(define (write-layerinfo l dir)
(let ([li (dict-ref (font-layers f) l)])
(when (and li
(or (layer-info-color li)
(> (hash-count (layer-info-lib li)) 0)))
(write-on-plist (layer-info->hash li) (build-path dir "layerinfo.plist")))))
(define (write-layercontents)
(write-on-plist
(map (lambda (layer) (list (symbol->string (car layer)) (cdr layer)))
layers-names)
(make-ufo-path "layercontents.plist")))
(let ([s (list
(cons 'meta (lambda ()
(write-on-plist (hash 'creator sfont-creator
'formatVersion format)
(make-ufo-path "metainfo.plist"))))
(cons 'info (lambda ()
(write-on-plist (font-fontinfo f)
(make-ufo-path "fontinfo.plist"))))
(cons 'groups write-groups)
(cons 'kerning (lambda () (write-kerning (font-kerning f)
(make-ufo-path "kerning.plist"))))
(cons 'features (lambda () (write-on-text-file (font-features f)
(make-ufo-path "features.fea"))))
(cons 'lib (lambda () (write-on-plist (font-lib f)
(make-ufo-path "lib.plist"))))
(cons 'layers write-layers)
(cons 'layercontents write-layercontents)
(cons 'data (lambda () (write-directory (font-data f) (make-ufo-path "data") proc-data)))
(cons 'images (lambda () (write-directory (font-images f) (make-ufo-path "images") proc-images))))])
(lambda (k) (dict-ref s k))))
; Font String [Boolean] (String -> ...) (String -> ...) -> side effects
; write the UFO to the given path
(define (write-ufo f path #:format [format 2] #:overwrite [overwrite #t])
(unless (and (filename-extension path)
(string=? (bytes->string/utf-8 (filename-extension path))
"ufo"))
(error (format "Expected ufo extension, but given ~a" path)))
(let ([writer (writer f path format #f #f)])
(if (and (directory-exists? path) (not overwrite))
(error "The file already exists, use #:overwrite to force writing")
(begin
(if (directory-exists? path)
(clean-ufo-dir path)
(make-directory path))
(when (and (= format 2)
(directory-exists? (build-path path "images")))
(delete-directory/files (build-path path "images")))
(when (and (= format 2)
(directory-exists? (build-path path "data")))
(delete-directory/files (build-path path "data")))
(cond [(= format 2) (write-ufo2 writer)]
[(= format 3) (write-ufo3 writer)]
[#t (error "I can only write Ufo 2 and Ufo 3 files")])))))
; PathString -> Void
; Delete ufo files from ufo dir
(define (clean-ufo-dir path)
(begin
(unless (and (filename-extension path)
(string=? (bytes->string/utf-8 (filename-extension path))
"ufo"))
(error (format "Expected ufo extension, but given ~a" path)))
(unless (directory-exists? path)
(error (format "The path ~a does not exist" path)))
(let ([files (map (curry build-path path)
(list "metainfo.plist"
"fontinfo.plist"
"groups.plist"
"kerning.plist"
"features.fea"
"lib.plist"
"layercontents.plist"))]
[dirs (map (curry build-path path)
(list "glyphs"))] ;"images" "data"))]
[gdirs (map (curry build-path path)
(filter (lambda (s)
(and (> (string-length s) 7)
(string=? "glyphs."
(substring s 0 7))))
(map path->string (directory-list path))))])
(begin
(for-each (lambda (f) (when (file-exists? f)
(delete-file f)))
files)
(for-each (lambda (d) (when (directory-exists? d)
(delete-directory/files d)))
dirs)
(for-each (lambda (d) (when (directory-exists? d)
(delete-directory/files d)))
gdirs)))))
; ufoWriter -> side effects
; write an UFO2 with the UfoWriter
(define (write-ufo2 writer)
(begin
((writer 'meta))
((writer 'info))
((writer 'groups))
((writer 'kerning))
((writer 'features))
((writer 'layers))
((writer 'lib))))
; ufoWriter -> side effects
; write an UFO3 with the UfoWriter
(define (write-ufo3 writer)
(begin
((writer 'meta))
((writer 'info))
((writer 'groups))
((writer 'kerning))
((writer 'features))
((writer 'layers))
((writer 'lib))
((writer 'layercontents))
((writer 'data))
((writer 'images))))
; functions for reading data
; (String or Number) -> Number
; produce a number from a string or return the number
(define (ensure-number n)
(if (or (not n) (number? n))
n
(string->number (string-replace n "," "."))))
; (String or Symbol) -> Symbol
; produce a symbol from a string or return the symbol
(define (ensure-symbol s)
(if s
(if (symbol? s) s (string->symbol s))
s))
; ("yes" or "no" or Boolean) -> Boolean
; produce a boolean from yes/no strings or return the boolean
(define (ensure-smooth s)
(match s
[#f #f]
["no" #f]
[#t #t]
["yes" #t]
[_ (error "invalid value for smooth")]))
; (String or Color) -> Color
; produce a color from the string or return the color
(define (ensure-color c)
(if (string? c) (string->color c) c))
; String -> Unicode
; produce an Unicode from String
(define (string->unicode s)
(string->number (string-append "#x" s)))
; Unicode -> String
; produce a String from an Unicode
(define (unicode->string n)
(~r n #:base '(up 16) #:pad-string "0" #:min-width 4))
(define (build-advance #:width [width 0] #:height [height 0])
(advance (ensure-number width) (ensure-number height)))
(define (build-image #:fileName filename #:xScale [x-scale 1] #:xyScale [xy-scale 0]
#:yxScale [yx-scale 0] #:yScale [y-scale 1] #:xOffset [x-offset 0]
#:yOffset [y-offset 0] #:color [color #f])
(image filename (trans-mat (ensure-number x-scale) (ensure-number xy-scale)
(ensure-number yx-scale) (ensure-number y-scale)
(ensure-number x-offset) (ensure-number y-offset))
(ensure-color color)))
(define (build-guideline #:x x #:y y #:angle angle
#:name [name #f] #:color [color #f]
#:identifier [identifier #f])
(guideline (vec (ensure-number x) (ensure-number y)) (ensure-number angle) name
(ensure-color color) (ensure-symbol identifier)))
(define (build-anchor #:x x #:y y #:name name
#:color [color #f] #:identifier [identifier #f])
(anchor (vec (ensure-number x) (ensure-number y)) name (ensure-color color) (ensure-symbol identifier)))
(define (build-contour #:identifier [identifier #f] #:points [points null])
(contour (ensure-symbol identifier) points))
(define (build-component #:base base #:xScale [x-scale 1] #:xyScale [xy-scale 0]
#:yxScale [yx-scale 0] #:yScale [y-scale 1] #:xOffset [x-offset 0]
#:yOffset [y-offset 0] #:identifier [identifier #f])
(component (ensure-symbol base)
(trans-mat (ensure-number x-scale) (ensure-number xy-scale)
(ensure-number yx-scale) (ensure-number y-scale)
(ensure-number x-offset) (ensure-number y-offset))
(ensure-symbol identifier)))
(define (build-point #:x x #:y y #:type [type 'offcurve]
#:smooth [smooth #f] #:name [name #f] #:identifier [identifier #f])
(point (vec (ensure-number x) (ensure-number y)) (ensure-symbol type)
(ensure-smooth smooth) name (ensure-symbol identifier))) | true |
ae1e3aaf4ca12b59e3c162c806907b88f78dc94d | 8efc1131fab877289b587ce705016a74f28b3df6 | /04.06.scrbl | c2403e3123778223f5cd5a1d6c0bdcc3f7f47044 | [] | no_license | Langeeker/RacketGuideInChineseForScribble | ed484638c4e9ce0ccfa2fc7a6b303b8735eb0ddb | 4fb07d376a2391f62e411b825eb825e3388ae411 | refs/heads/master | 2023-04-18T04:37:01.206000 | 2018-02-20T15:33:02 | 2018-02-20T15:33:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 516 | scrbl | 04.06.scrbl | ;04.06.scrbl
;4.6 局部绑定
#lang scribble/doc
@(require scribble/manual
scribble/eval
"guide-utils.rkt")
@title[#:tag "let"]{局部绑定}
虽然内部@racket[define]可用于局部绑定,Racket提供了三种形式给予程序员在绑定方面的更多控制:@racket[let]、@racket[let*]和@racket[letrec]。
@include-section["04.06.01.scrbl"]
@include-section["04.06.02.scrbl"]
@include-section["04.06.03.scrbl"]
@include-section["04.06.04.scrbl"]
@include-section["04.06.05.scrbl"] | false |
c44b8188c52a83bd9e772523d2672b96f4d8c731 | 616e16afef240bf95ed7c8670035542d59cdba50 | /redex-lib/redex/private/loc-wrapper.rkt | a464e4118c728ecf8940ebcf93b664711313fbff | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | racket/redex | bd535d6075168ef7be834e7c1b9babe606d5cd34 | 8df08b313cff72d56d3c67366065c19ec0c3f7d0 | refs/heads/master | 2023-08-19T03:34:44.392000 | 2023-07-13T01:50:18 | 2023-07-13T01:50:18 | 27,412,456 | 102 | 43 | NOASSERTION | 2023-04-07T19:07:30 | 2014-12-02T03:06:03 | Racket | UTF-8 | Racket | false | false | 705 | rkt | loc-wrapper.rkt | #lang racket/base
(require racket/contract
(for-syntax racket/base)
(for-syntax "loc-wrapper-ct.rkt")
"loc-wrapper-rt.rkt")
(define-syntax (to-lw stx)
(syntax-case stx ()
[(_ stx)
(to-lw/proc #'stx)]))
(define-syntax (to-lw/uq stx)
(syntax-case stx ()
[(_ stx)
(to-lw/uq/proc #'stx)]))
(define pnum (and/c number? (or/c zero? positive?)))
(provide/contract
(struct lw ((e any/c)
(line pnum)
(line-span pnum)
(column pnum)
(column-span pnum)
(unq? boolean?)
(metafunction? boolean?))))
(provide to-lw
to-lw/uq
curly-quotes-for-strings
build-lw)
| true |
1bd30fa517a45006805b2181934138153120e6bf | 82f959faa6bf8db6a577fb169f623a175f9f8961 | /tree/project/intr.rkt | b43cd85fdc56134043fd6fd64b409c8f72ecfc01 | [] | no_license | sk1e/devtools-server | 2a2e2994101de3eb7a017720d709116cfc6e7943 | 7da58a980bb702fbf69fc75deb2b49fca8eb813d | refs/heads/master | 2021-01-21T08:15:20.816000 | 2018-01-04T15:40:53 | 2018-01-04T15:40:53 | 83,341,503 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,868 | rkt | intr.rkt | #lang racket/base
(require racket/unit
racket/contract
ss/racket/class
"descendant-sig.rkt"
"ancestor-sig.rkt"
"descendant-unit.rkt"
"ancestor-unit.rkt"
"module.rkt"
"../file.rkt"
"../ebuffer.rkt"
)
(provide intr<%>
child-directory-mixin
directory%)
(define-compound-unit/infer linked@
(import )
(export descendant^ ancestor^)
(link descendant@ ancestor@))
(define-values/invoke-unit/infer linked@)
(define intr<%>
(interface (file:intr<%> ebuffer:intr<%> descendant<%> ancestor<%>)
))
(define intr-mixin
(mixin (file:intr<%> descendant<%> ancestor<%>) (intr<%>)
(super-new)
(inherit-field children)
(define/override (pre-rename! new-name)
(for-each (λ (node)
(send node
pre-rename!
(path->string (build-path new-name
(get-field name node)))))
children))
(define/override (post-select!) (void))
(define/override (initialize-project-node!) (void))
;; (define/override (face) 'pt:intr-face)
(define/override (entered-directory) this)
))
(define child-directory-mixin
(mixin (file:ancestor<%>) ()
(super-new)
(define/override (child-directory%) directory%)))
(define-inspected-class directory% (class-from-mixins ebuffer:intr-final-sum
file:intr-sum
descendant-sum
ancestor
intr
child-directory
child-file))
;; (define-composed-mixins
;; [descendant-sum (node descendant)]
;; [root-sum (node ancestor root)]
;; [intr-sum (descendant-sum ancestor intr)]
;; [leaf-sum (descendant-sum leaf)])
;; (define-composed-mixins
;; [leaf-final-sum (ebuffer:leaf-final-sum file:leaf-sum leaf-sum)]
;; [module-leaf-final-sum (leaf-final-sum module-leaf)]
;; [intr-final-sum (ebuffer:intr-final-sum file:intr-sum intr-sum)]
;; [root-final-sum (ebuffer:quasiroot-final-sum file:intr-sum root-sum)])
;; (define-inspected-class file% (class-from-mixins leaf-final-sum))
;; (define-inspected-class module% (class-from-mixins leaf-final-sum runnable-leaf module-leaf))
;; (define-inspected-class module-test% (class-from-mixins leaf-final-sum runnable-leaf test-leaf))
;; (define-inspected-class directory% (class-from-mixins intr-final-sum))
;; (define-inspected-class root% (class-from-mixins root-final-sum))
| false |
7bdee002469bf8db00e29608fdc603cac28b19e2 | e1cc058e1d24f98ccdf112f9ccc8b90adc24401c | /ImageConvolution-20161028.rkt | ca6a83306a805caee9483340552aa84291b0e722 | [] | no_license | bctnry/RosettaCodeTasks | 09a230ee80d4200402c05da2f81a71aea2bc248c | 60762f731db539b0247814cf4f1d0c6475c397c9 | refs/heads/master | 2021-01-11T05:46:38.038000 | 2016-12-09T07:56:25 | 2016-12-09T07:56:25 | 71,572,540 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,748 | rkt | ImageConvolution-20161028.rkt | #lang racket
(require racket/draw)
(define (pixelPlus2 p1 p2)
(list (let ([a1 (car p1)] [a2 (car p2)])
(if (> a1 a2) a1 a2))
(+ (cadr p1) (cadr p2))
(+ (caddr p1) (caddr p2))
(+ (cadddr p1) (cadddr p2))))
(define (pixelPlus t)
(define (pixelPlus_ t hold)
(cond ((null? t) hold)
(else (pixelPlus_ (cdr t) (pixelPlus2 (car t) hold)))))
(pixelPlus_ t (list 0 0 0 0)))
(define (pixelScalarMult s p)
(list (first p) (* s (second p)) (* s (third p)) (* s (fourth p))))
(define (3x3window bitmap x y)
(for/list ([i (list 0 1 2 0 1 2 0 1 2)] [j (list 0 0 0 1 1 1 2 2 2)])
(let ([pixelBuffer (bytes 0 0 0 0)])
(begin (send bitmap get-argb-pixels (+ x i -1) (+ y j -1) 1 1 pixelBuffer)
; todo: find a better way to change this.
(bytes->list pixelBuffer)))))
(define (P bitmap 3x3matrix x y)
; where 3x3matrix is a list consisting of 9 numbers.
(define (safing t)
(map (λ (t) (exact-round (cond ((< t 0) 0) ((> t 255) 255) (else t)))) t))
(let ([pixels (3x3window bitmap x y)])
(list->bytes (safing
(pixelPlus (for/list ([p pixels] [k 3x3matrix]) (pixelScalarMult k p)))))))
; todo: solving the edge case.
(define (convBy matrix)
; where matrix is a list consisting of 9 numbers
(λ (bitmap)
(let* ([w (send bitmap get-width)] [h (send bitmap get-height)]
[res (make-object bitmap% w h)])
(begin
(for ([x (range 1 (- w 1))]) (for ([y (range 1 (- h 1))])
(let ([rRes (P bitmap matrix x y)])
(send res set-argb-pixels x y 1 1 rRes))))
res))))
; use it like this:
; (define m '(-1 -1 -1 -1 9 -1 -1 -1 -1))
; then:
; ((convBy m) (make-object bitmap% "A.bmp"))
| false |
ce3f3215e47c4e5f16da33215d4d9b071b5606b9 | 7d80d516cd8c303818db1970e98c92f13f9b2ccd | /src/racket/out/runtime/kernel.rkt | ec9fafa934ba3c4c615bd63bbe75d03d3919a7f2 | [] | no_license | roman01la/js-memory-usage | 30527e47447af7660b5eeaf9a2260a4d374b76ef | 04a9af6d6dd7b3fe39bb9cfb42e81460213a15cc | refs/heads/master | 2022-12-10T12:13:45.200000 | 2020-05-23T09:25:56 | 2020-05-23T09:25:56 | 95,350,292 | 61 | 4 | null | 2022-12-07T17:45:45 | 2017-06-25T09:28:52 | JavaScript | UTF-8 | Racket | false | false | 27,036 | rkt | kernel.rkt | #lang racketscript/boot
(require racketscript/interop
racket/stxparam
(for-syntax syntax/parse)
"lib.rkt")
;; ----------------------------------------------------------------------------
;; Equality
(define+provide equal? #js.Core.isEqual)
(define+provide eqv? #js.Core.isEqv)
(define+provide eq? #js.Core.isEq)
;; ----------------------------------------------------------------------------
;; Values
(define+provide values
(v-λ vals
(if (binop === #js.vals.length 1)
($ vals 0)
(#js.Values.make vals))))
(define+provide (call-with-values generator receiver)
(let ([vals (generator)])
(cond
[(#js.Values.check vals)
(#js.receiver.apply #js*.this (#js.vals.getAll))]
[(not (or (eq? vals *undefined*) (eq? vals *null*)))
(#js.receiver.apply #js*.this (array vals))])))
;; ----------------------------------------------------------------------------
;; Void
(define+provide (void) *null*)
(define+provide (void? v)
(or (binop === v *null*) (binop === v *undefined*)))
;; ----------------------------------------------------------------------------
;; Numbers
(define+provide number? #js.Core.Number.check)
(define+provide real? #js.Core.Number.check)
(define+provide integer? #js.Number.isInteger)
(define-checked+provide (zero? [v number?])
(binop === v 0))
(define-checked+provide (positive? [v real?])
(binop > v 0))
(define-checked+provide (negative? [v real?])
(binop < v 0))
(define-checked+provide (add1 [v number?])
(binop + v 1))
(define-checked+provide (sub1 [v number?])
(binop - v 1))
(define-checked+provide (quotient [dividend integer?] [divisor integer?])
(binop \| (binop / dividend divisor) 0))
(define-checked+provide (even? [v integer?])
(binop === (binop % v 2) 0))
(define-checked+provide (odd? [v integer?])
(not (binop === (binop % v 2) 0)))
(define+provide (exact-nonnegative-integer? v)
(and (#js.Number.isInteger v) (binop >= v 0)))
(define+provide (exact-integer? v)
(#js.Number.isInteger v))
(define+provide * #js.Core.Number.mul)
(define+provide / #js.Core.Number.div)
(define+provide + #js.Core.Number.add)
(define+provide - #js.Core.Number.sub)
(define+provide < #js.Core.Number.lt)
(define+provide > #js.Core.Number.gt)
(define+provide <= #js.Core.Number.lte)
(define+provide >= #js.Core.Number.gte)
(define+provide = #js.Core.Number.equals)
(define-checked+provide (floor [v real?])
(#js.Math.floor v))
(define-checked+provide (abs [v real?])
(#js.Math.abs v))
(define-checked+provide (sin [v real?])
(#js.Math.sin v))
(define-checked+provide (cos [v real?])
(#js.Math.cos v))
(define-checked+provide (tan [v real?])
(#js.Math.tan v))
(define-checked+provide (atan [v real?])
(#js.Math.atan v))
(define-checked+provide (ceiling [v real?])
(#js.Math.ceil v))
(define-checked+provide (round [v real?])
(#js.Math.round v))
(define-checked+provide (min [a real?] [b real?])
(#js.Math.min a b))
(define-checked+provide (max [a real?] [b real?])
(#js.Math.max a b))
(define-checked+provide (log [v real?])
(#js.Math.log v))
(define-checked+provide (expt [w number?] [z number?])
(#js.Math.pow w z))
(define-checked+provide (sqrt [v number?])
(#js.Math.sqrt v))
(define-checked+provide (sqr [v number?])
(* v v))
(define-checked+provide (remainder [a integer?] [b integer?])
(binop % a b))
(define-checked+provide (number->string [n number?])
(#js.n.toString))
;;TODO: Support bignums
(define+provide (inexact->exact x) x)
(define+provide (exact->inexact x) x)
;; ----------------------------------------------------------------------------
;; Booleans
(define+provide (not v)
(or (equal? v #f) #f))
(define+provide false #f)
(define+provide true #t)
(define+provide (false? v) (binop === v #f))
;; ----------------------------------------------------------------------------
;; Pairs
(define-checked+provide (car [pair pair?]) #js.pair.hd)
(define-checked+provide (cdr [pair pair?]) #js.pair.tl)
(define+provide cons #js.Pair.make)
(define+provide cons? #js.Pair.check)
(define+provide pair? #js.Pair.check)
(define-checked+provide (caar [v (check/pair-of? pair? #t)])
#js.v.hd.hd)
(define-checked+provide (cadr [v (check/pair-of? #t pair?)])
#js.v.tl.hd)
(define-checked+provide (cdar [v (check/pair-of? pair? #t)])
#js.v.hd.tl)
(define-checked+provide (cddr [v (check/pair-of? #t pair?)])
#js.v.tl.tl)
(define-checked+provide (caddr [v (check/pair-of? #t (check/pair-of? #t pair?))])
#js.v.tl.tl.hd)
(define+provide null #js.Pair.Empty)
(define+provide list #js.Pair.makeList)
(define+provide null? #js.Pair.isEmpty)
(define+provide empty? #js.Pair.isEmpty)
(define+provide length #js.Pair.listLength)
(define+provide (list? v)
(cond
[(null? v) #t]
[(cons? v) (list? ($> v (cdr)))]
[else #f]))
(define-checked+provide (reverse [lst list?])
(let loop ([lst lst]
[result '()])
(if (null? lst)
result
(loop #js.lst.tl (#js.Core.Pair.make #js.lst.hd result)))))
(define+provide (list* a0 . args)
(define lst (reverse (cons a0 args)))
(let loop ([rst (cdr lst)]
[result (car lst)])
(if (null? rst)
rst
(loop (cdr rst)
(cons (car rst) result)))))
(define+provide append
(v-λ ()
(define result '())
(define lsts arguments)
(for/array [lst lsts]
(set! result (foldr #js.Core.Pair.make lst result)))
result))
(define+provide for-each
(v-λ (lam . lsts)
(check/raise procedure? lam 0)
(#js.map.apply *null* ($> (array lam) (concat lsts)))
*null*))
;; ----------------------------------------------------------------------------
;; Mutable Pairs
(define+provide (mcons hd tl)
(#js.Core.MPair.make hd tl))
(define+provide (mpair? v)
(#js.Core.MPair.check v))
(define-checked+provide (mcar [p mpair?])
(#js.p.car))
(define-checked+provide (mcdr [p mpair?])
(#js.p.cdr))
(define+provide (set-mcar! p v)
(check/raise mpair? p 0)
(#js.p.setCar v))
(define+provide (set-mcdr! p v)
(check/raise mpair? p 0)
(#js.p.setCdr v))
;; --------------------------------------------------------------------------
;; Structs
(define+provide (make-struct-type name
super-type
init-field-count
auto-field-count
auto-v
props
inspector
proc-spec
immutables
guard
constructor-name)
(#js.Core.Struct.makeStructType
{object [name (#js.name.toString)]
[superType super-type]
[initFieldCount init-field-count]
[autoFieldCount auto-field-count]
[autoV auto-v]
[props props]
[inspector inspector]
[procSpec proc-spec]
[immutables immutables]
[guard guard]
[constructorName constructor-name]}))
(define+provide (make-struct-field-accessor ref index field-name)
(λ (s)
(ref s index)))
(define+provide (make-struct-field-mutator set index fieldName)
(λ (s v)
(set s index v)))
(define+provide (make-struct-type-property name guard supers can-impersonate?)
(#js.Core.Struct.makeStructTypeProperty
{object [name name]
[guard guard]
[supers supers]
[canImpersonate can-impersonate?]}))
(define+provide (check-struct-type name what)
(when what
(unless (#js.Core.Struct.isStructType what)
(throw (#js.Core.racketCoreError "not a struct type")))
what))
(define+provide (struct-type? v)
(#js.Core.Struct.isStructType v))
(define+provide (struct-type-info desc)
(#js.Core.Values.make (#js.Core.Struct.structTypeInfo desc)))
;; --------------------------------------------------------------------------
;; Vectors
(define+provide vector
(v-λ ()
(#js.Core.Vector.make (#js.Core.argumentsToArray arguments) #t)))
;; v is optional
(define-checked+provide (make-vector [size integer?] [v #t])
(#js.Core.Vector.makeInit size (or v 0)))
(define+provide vector? #js.Core.Vector.check)
(define-checked+provide (vector-length [v vector?])
(#js.v.length))
(define-checked+provide (vector-ref [vec vector?] [i integer?])
(#js.vec.ref i))
(define-checked+provide (vector-set! [vec vector] [i integer?] [v #t])
(#js.vec.set i v))
(define-checked+provide (vector->list [vec vector?])
(#js.Core.Pair.listFromArray #js.vec.items))
(define-checked+provide (vector->immutable-vector [vec vector?])
(#js.Core.Vector.copy vec #f))
;; --------------------------------------------------------------------------
;; Hashes
(define-syntax-rule (make-hash-contructor make)
(v-λ ()
(define kv* arguments)
(when (binop !== (binop % #js.kv*.length 2) 0)
(throw (#js.Core.racketContractError "invalid number of arguments")))
(let ([items (array)])
(loop+ [i 0 #js.kv*.length 2]
(#js.items.push (array ($ kv* i) ($ kv* (+ i 1)))))
(make items #f))))
(define+provide hash (make-hash-contructor #js.Core.Hash.makeEqual))
(define+provide hasheqv (make-hash-contructor #js.Core.Hash.makeEqv))
(define+provide hasheq (make-hash-contructor #js.Core.Hash.makeEq))
(define+provide (make-hash assocs)
(define assocs* (or assocs '()))
(#js.Core.Hash.makeFromAssocs assocs* "equal" #t))
(define+provide (make-hasheqv assocs)
(define assocs* (or assocs '()))
(#js.Core.Hash.makeFromAssocs assocs* "eqv" #t))
(define+provide (make-hasheq assocs)
(define assocs* (or assocs '()))
(#js.Core.Hash.makeFromAssocs assocs* "eq" #t))
(define+provide (make-immutable-hash assocs)
(define assocs* (or assocs '()))
(#js.Core.Hash.makeFromAssocs assocs* "equal" #f))
(define+provide (make-immutable-hasheqv assocs)
(define assocs* (or assocs '()))
(#js.Core.Hash.makeFromAssocs assocs* "eqv" #f))
(define+provide (make-immutable-hasheq assocs)
(define assocs* (or assocs '()))
(#js.Core.Hash.makeFromAssocs assocs* "eq" #f))
(define+provide (hash-ref h k fail)
(#js.h.ref k fail))
(define+provide (hash-set h k v)
(#js.h.set k v))
(define+provide (hash-set! h k v)
(#js.h.set k v))
(define+provide (hash-map h proc)
(#js.Core.Hash.map h proc))
;; --------------------------------------------------------------------------
;; Higher Order Functions
(define+provide apply
(v-λ (lam . args)
(check/raise procedure? lam 0)
(define final-args
(cond
[(zero? #js.args.length)
(throw (#js.Core.racketContractError "arity mismatch"))]
[(equal? #js.args.length 1)
(unless (null? ($ args 0))
(type-check/raise #js.Core.Pair ($ args 0)))
(#js.Core.Pair.listToArray ($ args 0))]
[else
(#js.args.concat (#js.Core.Pair.listToArray (#js.args.pop)))]))
(#js.lam.apply *null* final-args)))
(define+provide map
(v-λ (fn . lists)
(check/raise procedure? fn 0)
(when (<= #js.lists.length 0)
(error 'map "need at-least two arguments"))
(define lst-len (length ($ lists 0)))
(for/array [v lists 1]
(unless (eq? (length v) lst-len)
(error 'map "all input lists must have equal length")))
(define result (Array lst-len))
(define args (Array #js.lists.length))
(loop+ [result-i lst-len]
(for/array [(lst-j lst) lists]
(:= ($ args lst-j) #js.lst.hd)
(:= ($ lists lst-j) #js.lst.tl))
(:= ($ result result-i) (#js.fn.apply *null* args)))
(#js.Core.Pair.listFromArray result)))
(define+provide foldl
(v-λ (fn init . lists)
(check/raise procedure? fn 0)
(when (<= #js.lists.length 0)
(error 'foldl "need at-least two arguments"))
(define lst-len (length ($ lists 0)))
(for/array [v lists 1]
(unless (eq? (length v) lst-len)
(error 'foldl "all input lists must have equal length")))
(define result init)
(define args (Array (binop + #js.lists.length 1)))
(loop+ [result-i lst-len]
(for/array [(lst-j lst) lists]
(:= ($ args lst-j) #js.lst.hd)
(:= ($ lists lst-j) #js.lst.tl))
(:= ($ args #js.lists.length) result)
(set! result (#js.fn.apply *null* args)))
result))
(define+provide (_foldr fn init lists)
(cond
[(null? ($ lists 0)) init]
[else
(define args (Array (add1 #js.lists.length)))
(for/array [(ii lst) lists]
(:= ($ args ii) #js.lst.hd)
(:= ($ lists ii) #js.lst.tl))
(:= ($ args #js.lists.length) (_foldr fn init lists))
(#js.fn.apply *null* args)]))
(define+provide foldr
(v-λ (fn init . lists)
(check/raise procedure? fn 0)
(when (<= #js.lists.length 0)
(error 'foldr "need at-least two arguments"))
(define lst-len (length ($ lists 0)))
(for/array [v lists 1]
(unless (eq? (length v) lst-len)
(error 'foldr "all input lists must have equal length")))
(_foldr fn init lists)))
(define+provide range
(case-lambda
[(end) (range 0 end 1)]
[(start end) (range start end (if (< start end) 1 -1))]
[(start end step)
(define result (array))
(cond
[(and (>= step 0) (< step end))
(loop+ [i start end step]
(#js.result.push i))]
[(and (<= step 0) (< end start))
(loop+ [i (- start) (- end) (- step)]
(#js.result.push (- i)))])
(#js.Core.Pair.listFromArray result)]))
;; proc is optional
(define+provide (remove v lst proc)
(when (eq? proc *undefined*)
(set! proc #js.Core.isEqual))
(let loop ([result '()]
[lst lst])
(cond
[(null? lst) (reverse result)]
[else
(when (proc v (car lst))
(append (reverse result) (cdr lst)))
(loop (cons (car lst) result) (cdr lst))])))
(define+provide (filter fn lst)
(let loop ([result '()]
[lst lst])
(cond
[(null? lst) (reverse result)]
[(fn #js.lst.hd) (loop (#js.Core.Pair.make #js.lst.hd result)
#js.lst.tl)]
[else (loop result #js.lst.tl)])))
(define+provide ormap
(v-λ (fn . lists)
(#js.foldl.apply #js*.this
($> (array (v-λ args
(define final-arg (#js.args.pop))
(and (or final-arg
(#js.fn.apply *null* args))
#t))
#f)
(concat lists)))))
(define+provide andmap
(v-λ (fn . lists)
(#js.foldl.apply #js*.this
($> (array (v-λ args
(define final-arg (#js.args.pop))
(and final-arg
(#js.fn.apply *null* args)
#t))
#t)
(concat lists)))))
;; TODO: add optional equal? pred
(define+provide (member v lst)
(let loop ([lst lst])
(cond
[(null? lst) #f]
[(#js.Core.isEqual v #js.lst.hd) lst]
[else (loop #js.lst.tl)])))
(define+provide compose
(v-λ procs
(v-λ ()
(define result (#js.Core.argumentsToArray arguments))
(define procs* (#js.procs.reverse))
(for/array [p procs*]
(set! result (#js.p.apply *null* result))
(if (#js.Core.Values.check result)
(set! result (#js.result.getAll))
(set! result (array result))))
(if (binop === #js.result.length 1)
($ result 0)
(#js.Core.Values.make result)))))
(define+provide compose1
(v-λ procs
(λ (v)
(define result v)
(define procs* (#js.procs.reverse))
(for/array [p procs*]
(set! result (p result)))
result)))
;; Lists
(define+provide (list-ref lst pos)
(let loop ([i 0]
[lst lst])
(cond
[(null? lst) (error 'list-ref? "insufficient elements")]
[(binop === i pos) #js.lst.hd]
[else (loop (binop + i 1) #js.lst.tl)])))
(define+provide (build-list n proc)
(define arr (Array n))
(loop+ [i n]
(:= ($ arr i) (proc i)))
(#js.Core.Pair.listFromArray arr))
(define+provide (make-list n v)
(let loop ([result '()]
[i 0])
(if (binop === i n)
result
(loop (#js.Core.Pair.make v result) (binop + i 1)))))
(define+provide (flatten lst)
(cond
[(null? lst) lst]
[(pair? lst) (append (flatten #js.lst.hd) (flatten #js.lst.tl))]
[else (list lst)]))
(define+provide (assoc k lst)
(let loop ([lst lst])
(cond
[(null? lst) #f]
[(#js.Core.isEqual k #js.lst.hd.hd) #js.lst.hd]
[else (loop #js.lst.tl)])))
(define+provide memv #js.Kernel.memv)
(define+provide memq #js.Kernel.memq)
(define+provide memf #js.Kernel.memf)
(define+provide findf #js.Kernel.findf)
(define+provide sort9 #js.Kernel.sort9)
(define+provide assv #js.Kernel.assv)
(define+provide assq #js.Kernel.assq)
(define+provide assf #js.Kernel.assf)
(define+provide alt-reverse reverse)
;; --------------------------------------------------------------------------
;; Strings
;; TODO: support both mutable/immutable strings
(define+provide string (#js.String.prototype.concat.bind ""))
(define+provide ~a
(v-λ args
($> (array)
reduce
(call args
(λ (x r)
(binop + r (#js.Core.toString x)))
""))))
(define+provide string-append string)
(define+provide (string=? sa sb)
(binop === sa sb))
(define+provide (string<? sa sb)
(binop < sa sb))
(define+provide (string<=? sa sb)
(binop <= sa sb))
(define+provide (string>? sa sb)
(binop > sa sb))
(define+provide (string>=? sa sb)
(binop >= sa sb))
(define+provide (string? v)
(typeof v "string"))
(define+provide format #js.Kernel.format)
(define+provide symbol? #js.Core.Symbol.check)
(define+provide (symbol->string v)
(#js.v.toString))
(define+provide (symbol=? s v)
(#js.s.equals v))
(define+provide (string-length v)
#js.v.length)
(define+provide (string-downcase v)
(#js.v.toLowerCase v))
(define+provide (string-upcase v)
(#js.v.toUpperCase v))
;; end is optional
(define+provide (substring str start end)
(define end (or end #f))
(cond
[(not (typeof str "string"))
(throw (#js.Core.racketContractError "expected a string"))]
[(binop < start 0)
(throw (#js.Core.racketContractError "invalid start index"))]
[(and (binop !== end #f)
(or (binop < end 0) (binop > end #js.str.length)))
(throw (#js.Core.racketContractError "invalid end index"))]
[(binop === end #f)
(set! end #js.str.length)])
(#js.str.substring start end))
(define+provide (string-split str sep)
(#js.Core.Pair.listFromArray (#js.str.split sep)))
;; --------------------------------------------------------------------------
;; Box
(define+provide box #js.Core.Box.make)
(define+provide (unbox v)
(#js.v.get))
(define+provide (set-box! b v)
(#js.b.set v))
;; --------------------------------------------------------------------------
;; Properties
(define-syntax (define-property+provide stx)
(syntax-parse stx
[(_ name:id)
#`(begin
(provide name)
(define+provide name
(($ (make-struct-type-property
#,(symbol->string (syntax-e #'name))) 'getAt)
0)))]))
(provide prop:evt evt?)
(define-values (prop:evt evt?) (#js.Core.Struct.makeStructTypeProperty
{object [name "prop:evt"]}))
(define-property+provide prop:checked-procedure)
(define-property+provide prop:impersonator-of)
(define-property+provide prop:arity-string)
(define-property+provide prop:incomplete-arity)
(define-property+provide prop:method-arity-error)
(define-property+provide prop:exn:srclocs)
(define+provide prop:procedure #js.Core.Struct.propProcedure)
;; --------------------------------------------------------------------------
;; Ports + Writers
(define+provide (current-output-port)
#js.Core.Ports.standardOutputPort)
(define+provide (current-print)
(λ (p)
(when (string? p)
(display "\""))
(display p)
(when (string? p)
(display "\""))
(newline)))
(define+provide (input-port? p)
(#js.Core.Ports.checkInputPort p))
(define+provide (output-port? p)
(#js.Core.Ports.checkOutputPort p))
;; --------------------------------------------------------------------------
;; Printing
(define+provide (display v) (#js.Kernel.display v))
(define+provide (newline)
(display "\n"))
;; --------------------------------------------------------------------------
;; Errors
(define+provide error #js.Kernel.error)
;; --------------------------------------------------------------------------
;; Bytes
(define+provide (bytes? bs)
(instanceof bs Uint8Array))
(define+provide (bytes->string/utf-8 bs)
(if (bytes? bs)
(#js.String.fromCharCode.apply *null* bs)
(throw (#js.Core.racketContractError "expected bytes"))))
(define+provide (string->bytes/utf-8 str)
(if (typeof str "string")
(new (Uint8Array (#js.Array.prototype.map.call str
(λ (x) (#js.x.charCodeAt 0)))))
(throw (#js.Core.racketContractError "expected string"))))
;; --------------------------------------------------------------------------
;; Continuation Marks
(define+provide current-continuation-marks #js.Core.Marks.getContinuationMarks)
(define+provide continuation-mark-set->list #js.Core.Marks.getMarks)
(define+provide (continuation-mark-set-first mark-set key-v none-v prompt-tag)
;; TODO: implement prompt tag
(define mark-set (or mark-set (#js.Core.Marks.getContinuationMarks prompt-tag)))
(define marks (#js.Core.Marks.getMarks mark-set key-v prompt-tag))
(if (null? marks)
none-v
#js.marks.hd))
(define+provide make-parameter #js.Paramz.makeParameter)
(define+provide call-with-continuation-prompt
#js.Core.Marks.callWithContinuationPrompt)
(define+provide abort-current-continuation
(v-λ (prompt-tag . args)
(throw (new (#js.Core.Marks.AbortCurrentContinuation prompt-tag args)))))
(define+provide make-continuation-prompt-tag
#js.Core.Marks.makeContinuationPromptTag)
(define+provide default-continuation-prompt-tag
#js.Core.Marks.defaultContinuationPromptTag)
(define+provide (raise e)
(let ([abort-ccp (continuation-mark-set-first (current-continuation-marks)
#js.Paramz.ExceptionHandlerKey)])
(abort-ccp e)))
;; --------------------------------------------------------------------------
;; Not implemented/Unorganized/Dummies
(define+provide (current-inspector) #t)
(define+provide raise-argument-error error)
(define+provide (check-method) #f)
(define+provide random #js.Kernel.random)
(define+provide (current-seconds)
(#js.Math.floor (binop / (#js.Date.now) 1000)))
;; --------------------------------------------------------------------------
;; Regexp
;; TODO: both regexps and pregexps currently compile to js regexps,
;; but js doesnt support posix patterns
(define+provide (regexp? v)
(instanceof v RegExp))
(define+provide pregexp? regexp?)
(define+provide byte-regexp? regexp?)
(define+provide byte-pregexp? regexp?)
(define+provide (regexp str)
(if (typeof str "string")
(throw (#js.Core.racketContractError "expected string"))
(new (RegExp str))))
(define+provide pregexp regexp)
(define+provide (byte-regexp bs)
(if (bytes? bs)
(new (RegExp (bytes->string/utf-8 bs)))
(throw (#js.Core.racketContractError "expected bytes"))))
(define+provide byte-pregexp byte-regexp)
(define+provide (regexp-match p i)
(define rx-p? (regexp? p))
(define bytes-p? (bytes? p))
(define bytes-i? (bytes? i))
(define str-p? (binop === (typeof p) "string"))
(define str-i? (binop === (typeof i) "string"))
(when (and (not (or rx-p? bytes-p? str-p?))
(not (or bytes-i? str-i?)))
(throw
(#js.Core.racketContractError
"expected regexp, string or byte pat, and string or byte input")))
(define str (if str-i? i (bytes->string/utf-8 i)))
(define pat (cond
[rx-p? p]
[str-p? p]
[else (bytes->string/utf-8 p)]))
(define res (#js.str.match pat))
(cond
[(binop === res *null*) #f]
[(and (or str-p? rx-p?) str-i?)
(#js.Core.Pair.listFromArray
(#js.res.map (λ (x)
(if (binop === x *undefined*)
#f
x))))]
[else
(#js.Core.Pair.listFromArray
(#js.res.map (λ (x)
(if (binop === x *undefined*)
#f
(string->bytes/utf-8 x)))))]))
;; --------------------------------------------------------------------------
;; Procedures
;;TODO: Why was this prefixed with 'kernel:'???
(provide (struct-out kernel:arity-at-least))
(struct kernel:arity-at-least (value)
#:extra-constructor-name make-arity-at-least
#:transparent)
(define+provide (procedure? f)
(typeof f "function"))
(define+provide arity-at-least make-arity-at-least)
(define+provide (arity-at-least? p)
(kernel:arity-at-least? p))
(define+provide (arity-at-least-value p)
(kernel:arity-at-least-value p))
(define+provide (procedure-arity-includes? f) #t)
(define+provide (procedure-arity fn)
(define lambda-type #js.fn.__rjs_lambdaType)
(cond
[(binop === lambda-type "variadic")
(kernel:arity-at-least (or #js.fn.__rjs_arityValue #js.fn.length))]
[(binop === lambda-type "case-lambda")
(if (binop === #js.fn.__rjs_arityValue.length 1)
($ #js.fn.__rjs_arityValue 0)
(#js.Core.Pair.listFromArray #js.fn.__rjs_arityValue))]
[else #js.fn.length]))
(define+provide (procedure-arity? v)
(or (exact-nonnegative-integer? v)
(kernel:arity-at-least? v)
(ormap (λ (v)
(or (exact-nonnegative-integer? v)
(kernel:arity-at-least? v)))
v)))
(define+provide (checked-procedure-check-and-extract type v proc v1 v2)
(cond
[(and (#js.Core.Struct.check v type)
(#js.type._findProperty prop:checked-procedure))
(let* ([fn (#js.v.getField 0)]
[r1 (fn v1 v2)])
(if r1
(#js.v.getField 1)
(proc v v1 v2)))]
[else (proc v v1 v2)]))
;; --------------------------------------------------------------------------
;;
(define+provide (gensym sym)
(let ([s (or (and sym #js.sym.v) "")])
(set! __count (binop + __count 1))
(#js.Core.Symbol.makeUninterned (binop + s __count))))
(define+provide (eval-jit-enabled) #f)
(define+provide (variable-reference-constant? x) #f)
(define+provide (inspector? p)
#t)
(define+provide (make-thread-cell p) p)
(define __count 1000)
(define+provide (system-type mod)
'javascript)
(define+provide make-weak-hash make-hash)
| true |
29e977846bbdd5e53e502f5432144d3537920872 | 471a04fa9301455c51a890b8936cc60324a51f27 | /srfi-lib/srfi/%3a17.rkt | 647edac9f0aa5da9ef3ebca4145e13ca0b5615be | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] | permissive | racket/srfi | e79e012fda6d6bba1a9445bcef461930bc27fde8 | 25eb1c0e1ab8a1fa227750aa7f0689a2c531f8c8 | refs/heads/master | 2023-08-16T11:10:38.100000 | 2023-02-16T01:18:44 | 2023-02-16T12:34:27 | 27,413,027 | 10 | 10 | NOASSERTION | 2023-09-14T14:40:51 | 2014-12-02T03:22:45 | HTML | UTF-8 | Racket | false | false | 34 | rkt | %3a17.rkt | #lang s-exp srfi/provider srfi/17
| false |
c1360ad8de07f965f164307d38ce3a05fb8e1784 | 3c9983e012653583841b51ddfd82879fe82706fb | /experiments/little-smalltalk/run-SmallWorld-2015.rkt | 71769223deaa6e62d0c53889ab253a4e8f470869 | [] | no_license | spdegabrielle/smalltalk-tng | 3c3d4cffa09541b75524fb1f102c7c543a84a807 | 545343190f556edd659f6050b98036266a270763 | refs/heads/master | 2020-04-16T17:06:51.884000 | 2018-08-07T16:18:20 | 2018-08-07T16:18:20 | 165,763,183 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 10,634 | rkt | run-SmallWorld-2015.rkt | #lang racket/gui
;; Loader for images (version 1 format) from Russell Allen's 2015
;; variant of SmallWorld, a Tim Budd-authored Little Smalltalk
;; descendant.
(require racket/struct)
(require racket/bytes)
(require "object-memory.rkt")
(require "primitives.rkt")
(define-logger vm)
(struct int-VM VM (cache image-filename)
#:methods gen:vm-callback
[(define (vm-block-callback vm block)
;; Runs block in a new thread
(lambda args
(let ((ctx (clone-array block)))
(define argument-location (slotAt ctx 7))
(for [(i (in-naturals argument-location)) (arg (in-list args))]
(slotAtPut (slotAt ctx 2) i arg))
(slotAtPut ctx 3 (mkarray vm (slotCount (slotAt ctx 3))))
(slotAtPut ctx 4 (slotAt ctx 9)) ;; reset IP to correct block offset
(slotAtPut ctx 5 0) ;; zero stack-top
(slotAtPut ctx 6 (VM-nil vm)) ;; no previous context
(thread (lambda () (execute vm ctx))))))])
(define (mkarray vm count [init (VM-nil vm)])
(obj (VM-Array vm) (make-vector count init)))
(define (build-context vm previous-context args method)
(define temp-count (slotAt method 4))
(define max-stack (slotAt method 3))
(mkobj (VM-Context vm)
method
args
(mkarray vm temp-count)
(mkarray vm max-stack)
0 ;; IP
0 ;; stack top
previous-context))
(define (clone-array a [start 0] [count (- (slotCount a) start)])
(define b (obj (obj-class a) (make-vector count)))
(for [(i (in-range count))]
(slotAtPut b i (slotAt a (+ i start))))
b)
(define (lookup-method/cache vm class selector)
(define name-bytes (bv-bytes selector))
(define class-cache (hash-ref! (int-VM-cache vm) class make-weak-hash))
(hash-ref! class-cache
name-bytes
(lambda ()
(lookup-method vm class (bv-bytes selector)))))
(define (store-registers! ctx ip stack-top)
(slotAtPut ctx 4 ip)
(slotAtPut ctx 5 stack-top))
(define (send-message* vm ctx ip stack-top arguments class selector)
(store-registers! ctx ip stack-top)
(match (lookup-method/cache vm class selector)
[#f
(match (lookup-method/cache vm class (mkbv (obj-class selector) #"doesNotUnderstand:"))
[#f
(error 'send-message* "Unhandled selector ~a at class ~a" selector class)]
[dnu-method
(log-vm-warning "DNU -- arguments ~a class ~a selector ~a" arguments class selector)
(execute vm (build-context vm
ctx
(mkobj (VM-Array vm)
(slotAt arguments 0)
(mkobj (VM-Array vm)
selector
(clone-array arguments)))
dnu-method))])]
[new-method
(execute vm (build-context vm ctx arguments new-method))]))
(define (send-message vm ctx ip stack-top arguments selector)
(log-vm-debug "sending: ~a ~a" selector arguments)
(send-message* vm ctx ip stack-top arguments (obj-class* vm (slotAt arguments 0)) selector))
(define (resume-context vm ctx result)
(if (eq? (VM-nil vm) ctx)
result
(let ((stack-top (slotAt ctx 5)))
(slotAtPut (slotAt ctx 3) stack-top result)
(slotAtPut ctx 5 (+ stack-top 1))
(log-vm-debug "resuming: ~a" result)
(execute vm ctx))))
(define (execute vm ctx)
(define method (slotAt ctx 0))
(define arguments (slotAt ctx 1))
(define temporaries (slotAt ctx 2))
(define stack (slotAt ctx 3))
(define ip (slotAt ctx 4))
(define stack-top (slotAt ctx 5))
(define previous-ctx (slotAt ctx 6))
(define receiver (slotAt arguments 0))
(define bytecode (bv-bytes (slotAt method 1)))
(define literals (slotAt method 2))
(define (push! v)
(slotAtPut stack stack-top v)
(set! stack-top (+ stack-top 1)))
(define (pop!)
(set! stack-top (- stack-top 1))
(slotAt stack stack-top))
(define (peek)
(slotAt stack (- stack-top 1)))
(define (pop-multiple! count)
(set! stack-top (- stack-top count))
(clone-array stack stack-top count))
(define (continue-from next-ip)
(set! ip next-ip)
(interpret))
(define (push-and-go next-ip v)
(push! v)
(continue-from next-ip))
(define (push-and-continue v)
(push! v)
(interpret))
(define (next-byte!)
(begin0 (bytes-ref bytecode ip)
(set! ip (+ ip 1))))
(define (decode!)
(define byte (next-byte!))
(define low (bitwise-and byte #x0f))
(define high (bitwise-and (arithmetic-shift byte -4) #x0f))
(if (zero? high)
(values low (next-byte!))
(values high low)))
(define (interpret)
(define-values (high low) (decode!))
(log-vm-debug "> ~a ~a ~a" high low (vector-copy (obj-slots stack) 0 stack-top))
(match high
[1 (push-and-continue (slotAt receiver low))] ;; PushInstance
[2 (push-and-continue (slotAt arguments low))] ;; PushArgument
[3 (push-and-continue (slotAt temporaries low))] ;; PushTemporary
[4 (push-and-continue (slotAt literals low))] ;; PushLiteral
[5 (match low
[(or 0 1 2 3 4 5 6 7 8 9) (push-and-continue low)]
[10 (push-and-continue (VM-nil vm))]
[11 (push-and-continue (VM-true vm))]
[12 (push-and-continue (VM-false vm))])]
[6 (slotAtPut receiver low (peek)) (interpret)] ;; AssignInstance
[7 (slotAtPut temporaries low (peek)) (interpret)] ;; AssignTemporary
[8 (push-and-continue (pop-multiple! low))] ;; MarkArguments
[9 ;; SendMessage
(define new-arguments (pop!))
(send-message vm ctx ip stack-top new-arguments (slotAt literals low))]
[10 (match low
[0 (push-and-continue (boolean->obj vm (eq? (VM-nil vm) (pop!))))] ;; isNil
[1 (push-and-continue (boolean->obj vm (not (eq? (VM-nil vm) (pop!)))))])] ;; notNil
[11 ;; SendBinary
(define j (pop!))
(define i (pop!))
(if (and (number? i) (number? j))
(match low
[0 (push-and-continue (boolean->obj vm (< i j)))]
[1 (push-and-continue (boolean->obj vm (<= i j)))]
[2 (push-and-continue (+ i j))]) ;; TODO: overflow to bignum arithmetic
(let ((new-arguments (mkobj (VM-Array vm) i j))
(selector (match low
[0 (mkbv (VM-nil vm) #"<")]
[1 (mkbv (VM-nil vm) #"<=")]
[2 (mkbv (VM-nil vm) #"+")])))
(send-message vm ctx ip stack-top new-arguments selector)))]
[12 ;; PushBlock
(define target (next-byte!))
(log-vm-debug "pushblock; temporaries = ~a" temporaries)
(push-and-go target
(mkobj (VM-Block vm) method arguments temporaries stack ip 0 previous-ctx low ctx ip))]
[13 ;; Primitive; low = arg count; next byte = primitive number
(define primitive-number (next-byte!))
(log-vm-debug "primitive ~a (arg count = ~a)" primitive-number low)
(match primitive-number
[8 ;; block invocation
(define block (pop!))
(define argument-location (slotAt block 7))
(define argument-count (- low 1)) ;; one of the primitive args is the block itself
(for [(i argument-count)]
(slotAtPut (slotAt block 2)
(+ argument-location i)
(slotAt stack (+ (- stack-top argument-count) i))))
(set! stack-top (- stack-top argument-count))
(store-registers! ctx ip stack-top)
(execute vm (mkobj (VM-Context vm)
(slotAt block 0)
(slotAt block 1)
(slotAt block 2)
(mkarray vm (slotCount (slotAt block 3))) ;; new stack (!)
(slotAt block 9) ;; starting IP
0 ;; stack top
(slotAt ctx 6) ;; previous context
(slotAt block 7)
(slotAt block 8)
(slotAt block 9)))]
[34 (VM-nil vm)] ;; "thread kill"
[35 (push-and-continue ctx)]
[_ (define args (pop-multiple! low))
(define handler (hash-ref *primitive-handlers* primitive-number))
(push-and-continue (handler vm args))])]
[14 (push-and-continue (slotAt (obj-class* vm receiver) (+ low 5)))] ;; PushClassVariable
[15 ;; Do Special
(match low
[1 (resume-context vm previous-ctx receiver)]
[2 (resume-context vm previous-ctx (pop!))]
[3 (resume-context vm (slotAt (slotAt ctx 8) 6) (pop!))]
[4 (push-and-continue (peek))]
[5 (pop!) (interpret)]
[6 (continue-from (next-byte!))]
[7 ;; branch if true
(define target (next-byte!))
(if (eq? (pop!) (VM-true vm))
(continue-from target)
(interpret))]
[8 ;; branch if false
(define target (next-byte!))
(if (eq? (pop!) (VM-false vm))
(continue-from target)
(interpret))]
[11 ;; send to super
(define selector (slotAt literals (next-byte!)))
(define new-arguments (pop!))
(define defining-class (slotAt method 5)) ;; method's defining class
(define super (slotAt defining-class 1)) ;; defining class's superclass
(send-message* vm ctx ip stack-top new-arguments super selector)])]))
(interpret))
;;===========================================================================
(define-primitive vm [6 inner-ctx] ;; "new context execute"
(execute vm inner-ctx))
(define-primitive vm [116] (save-image-to-file vm (int-VM-image-filename vm)))
;;===========================================================================
(let* ((image-filename "SmallWorld/src/image")
(vm (call-with-input-file image-filename
(lambda (fh)
(read-image fh int-VM (list (make-weak-hasheq) image-filename))))))
(boot-image vm
(lambda (vm source)
(define args (mkobj (VM-Array vm) source))
(define doIt-method (search-class-method-dictionary (obj-class source) #"doIt"))
(when (not doIt-method) (error 'doIt "Can't find doIt method via class True etc"))
(execute vm (build-context vm (VM-nil vm) args doIt-method)))
(current-command-line-arguments)))
| false |
d6e6237813c857ea87452af12bfdb9d718f80fd1 | bd1d904e97bce2bf2d5e41eb04d07bf29cd383a1 | /src/core/regimes.rkt | 72ec96bae4c9766b8b6e992c49a625fd6543687d | [
"MIT"
] | permissive | remysucre/herbie | 17066e0f254fcf57cdebdf6442abaf4e2f9168a9 | a2b731605843c3ad39d270e6f86410a5ea5c6821 | refs/heads/master | 2020-04-18T09:28:54.902000 | 2018-10-22T22:23:41 | 2018-10-22T22:23:41 | 167,435,577 | 0 | 0 | NOASSERTION | 2019-05-03T20:49:00 | 2019-01-24T20:49:49 | Racket | UTF-8 | Racket | false | false | 13,725 | rkt | regimes.rkt | #lang racket
(require "../common.rkt")
(require "../config.rkt")
(require "../alternative.rkt")
(require "../programs.rkt")
(require "../points.rkt")
(require "../float.rkt")
(require "../syntax/syntax.rkt")
(require "matcher.rkt")
(require "localize.rkt")
(require "../type-check.rkt")
(module+ test
(require rackunit))
(provide infer-splitpoints (struct-out sp) splitpoints->point-preds)
(define (infer-splitpoints alts [axis #f])
(match alts
[(list alt)
(list (list (sp 0 0 +nan.0)) (list alt))]
[_
(debug "Finding splitpoints for:" alts #:from 'regime-changes #:depth 2)
(define options
(map (curry option-on-expr alts)
(if axis (list axis) (exprs-to-branch-on alts))))
(define best-option (argmin (compose errors-score option-errors) options))
(define splitpoints (option-splitpoints best-option))
(define altns (used-alts splitpoints alts))
(define splitpoints* (coerce-indices splitpoints))
(debug #:from 'regimes "Found splitpoints:" splitpoints* ", with alts" altns)
(list splitpoints* altns)]))
(struct option (splitpoints errors) #:transparent
#:methods gen:custom-write
[(define (write-proc opt port mode)
(display "#<option " port)
(write (option-splitpoints opt) port)
(display ">" port))])
(define (exprs-to-branch-on alts)
(if (flag-set? 'reduce 'branch-expressions)
(let ([alt-critexprs (for/list ([alt alts])
(all-critical-subexpressions (alt-program alt)))]
[critexprs (all-critical-subexpressions (*start-prog*))])
(remove-duplicates (foldr append '() (cons critexprs alt-critexprs))))
(program-variables (*start-prog*))))
;; Requires that expr is a λ expression
(define (critical-subexpression? expr subexpr)
(define crit-vars (free-variables subexpr))
(define replaced-expr (replace-expression expr subexpr 1))
(define non-crit-vars (free-variables replaced-expr))
(set-disjoint? crit-vars non-crit-vars))
;; Requires that prog is a λ expression
(define (all-critical-subexpressions prog)
(define (subexprs-in-expr expr)
(cons expr (if (list? expr) (append-map subexprs-in-expr (cdr expr)) '())))
(define prog-body (location-get (list 2) prog))
(for/list ([expr (remove-duplicates (subexprs-in-expr prog-body))]
#:when (and (not (null? (free-variables expr)))
(critical-subexpression? prog-body expr)))
expr))
(define (used-alts splitpoints all-alts)
(let ([used-indices (remove-duplicates (map sp-cidx splitpoints))])
(map (curry list-ref all-alts) used-indices)))
;; Takes a list of splitpoints, `splitpoints`, whose indices originally referred to some list of alts `alts`,
;; and changes their indices so that they are consecutive starting from zero, but all indicies that
;; previously matched still match.
(define (coerce-indices splitpoints)
(let* ([used-indices (remove-duplicates (map sp-cidx splitpoints))]
[mappings (map cons used-indices (range (length used-indices)))])
(map (λ (splitpoint)
(sp (cdr (assoc (sp-cidx splitpoint) mappings))
(sp-bexpr splitpoint)
(sp-point splitpoint)))
splitpoints)))
(define (option-on-expr alts expr)
(define vars (program-variables (*start-prog*)))
(match-define (list pts exs) (sort-context-on-expr (*pcontext*) expr vars))
(define splitvals (map (eval-prog `(λ ,vars ,expr) 'fl) pts))
(define can-split? (append (list #f) (for/list ([val (cdr splitvals)] [prev splitvals]) (< prev val))))
(define err-lsts
(parameterize ([*pcontext* (mk-pcontext pts exs)]) (map alt-errors alts)))
(define bit-err-lsts (map (curry map ulps->bits) err-lsts))
(define merged-err-lsts (map (curry merge-err-lsts pts) bit-err-lsts))
(define split-indices (err-lsts->split-indices merged-err-lsts can-split?))
(for ([pidx (map si-pidx (drop-right split-indices 1))])
(assert (> pidx 0))
(assert (list-ref can-split? pidx)))
(define split-points (sindices->spoints pts expr alts split-indices))
(assert (set=? (remove-duplicates (map (point->alt split-points) pts))
(map sp-cidx split-points)))
(option split-points (pick-errors split-points pts err-lsts)))
(module+ test
(parameterize ([*start-prog* '(λ (x) 1)]
[*pcontext* (mk-pcontext '((0.5) (4.0)) '(1.0 1.0))])
(define alts (map (λ (body) (make-alt `(λ (x) ,body))) (list '(fmin x 1) '(fmax x 1))))
;; This is a basic sanity test
(check (λ (x y) (equal? (map sp-cidx (option-splitpoints x)) y))
(option-on-expr alts 'x)
'(1 0))
;; This test ensures we handle equal points correctly. All points
;; are equal along the `1` axis, so we should only get one
;; splitpoint (the second, since it is better at the further point).
(check (λ (x y) (equal? (map sp-cidx (option-splitpoints x)) y))
(option-on-expr alts '1)
'(0))
(check (λ (x y) (equal? (map sp-cidx (option-splitpoints x)) y))
(option-on-expr alts '(if (== x 0.5) 1 +nan.0))
'(0))))
;; (pred p1) and (not (pred p2))
(define (binary-search-floats pred p1 p2)
(let ([midpoint (midpoint-float p1 p2)])
(cond [(< (bit-difference p1 p2) 48) midpoint]
[(pred midpoint) (binary-search-floats pred midpoint p2)]
[else (binary-search-floats pred p1 midpoint)])))
;; Accepts a list of sindices in one indexed form and returns the
;; proper splitpoints in float form. A crucial constraint is that the
;; float form always come from the range [f(idx1), f(idx2)). If the
;; float form of a split is f(idx2), or entirely outside that range,
;; problems may arise.
(define (sindices->spoints points expr alts sindices)
(for ([alt alts])
(assert
(set-empty? (set-intersect (free-variables expr)
(free-variables (replace-expression (alt-program alt) expr 0))))
#:extra-info (cons expr alt)))
(define eval-expr
(eval-prog `(λ ,(program-variables (alt-program (car alts))) ,expr) 'fl))
(define (sidx->spoint sidx next-sidx)
(let* ([alt1 (list-ref alts (si-cidx sidx))]
[alt2 (list-ref alts (si-cidx next-sidx))]
[p1 (eval-expr (list-ref points (si-pidx sidx)))]
[p2 (eval-expr (list-ref points (sub1 (si-pidx sidx))))]
[pred (λ (v)
(let* ([start-prog* (replace-expression (*start-prog*) expr v)]
[prog1* (replace-expression (alt-program alt1) expr v)]
[prog2* (replace-expression (alt-program alt2) expr v)]
[context
(parameterize ([*num-points* (*binary-search-test-points*)])
(prepare-points start-prog* 'TRUE))])
(< (errors-score (errors prog1* context))
(errors-score (errors prog2* context)))))])
(debug #:from 'regimes "searching between" p1 "and" p2 "on" expr)
(sp (si-cidx sidx) expr (binary-search-floats pred p2 p1))))
(append
(if (flag-set? 'reduce 'binary-search)
(map sidx->spoint
(take sindices (sub1 (length sindices)))
(drop sindices 1))
(for/list ([sindex (take sindices (sub1 (length sindices)))])
(sp (si-cidx sindex) expr (eval-expr (list-ref points (- (si-pidx sindex) 1))))))
(list (let ([last-sidx (list-ref sindices (sub1 (length sindices)))])
(sp (si-cidx last-sidx)
expr
+nan.0)))))
(define (merge-err-lsts pts errs)
(let loop ([pt (car pts)] [pts (cdr pts)] [err (car errs)] [errs (cdr errs)])
(if (null? pts)
(list err)
(if (equal? pt (car pts))
(loop pt (cdr pts) (+ err (car errs)) (cdr errs))
(cons err (loop (car pts) (cdr pts) (car errs) (cdr errs)))))))
(define (point-with-dim index point val)
(map (λ (pval pindex) (if (= pindex index) val pval))
point
(range (length point))))
(define (point->alt splitpoints)
(assert (all-equal? (map sp-bexpr splitpoints)))
(assert (nan? (sp-point (last splitpoints))))
(define expr `(λ ,(program-variables (*start-prog*)) ,(sp-bexpr (car splitpoints))))
(define prog (eval-prog expr 'fl))
(λ (pt)
(define val (prog pt))
(for/first ([right splitpoints]
#:when (or (nan? (sp-point right)) (<= val (sp-point right))))
;; Note that the last splitpoint has an sp-point of +nan.0, so we always find one
(sp-cidx right))))
(define (pick-errors splitpoints pts err-lsts)
(define which-alt (point->alt splitpoints))
(for/list ([pt pts] [errs (flip-lists err-lsts)])
(list-ref errs (which-alt pt))))
(define (with-entry idx lst item)
(if (= idx 0)
(cons item (cdr lst))
(cons (car lst) (with-entry (sub1 idx) (cdr lst) item))))
;; Takes a vector of numbers, and returns the partial sum of those numbers.
;; For example, if your vector is #(1 4 6 3 8), then this returns #(1 5 11 14 22).
(define (partial-sum vec)
(first-value
(for/fold ([res (make-vector (vector-length vec))]
[cur-psum 0])
([(el idx) (in-indexed (in-vector vec))])
(let ([new-psum (+ cur-psum el)])
(vector-set! res idx new-psum)
(values res new-psum)))))
;; Struct represeting a splitpoint
;; cidx = Candidate index: the index of the candidate program that should be used to the left of this splitpoint
;; bexpr = Branch Expression: The expression that this splitpoint should split on
;; point = Split Point: The point at which we should split.
(struct sp (cidx bexpr point) #:prefab)
;; Struct representing a splitindex
;; cidx = Candidate index: the index candidate program that should be used to the left of this splitindex
;; pidx = Point index: The index of the point to the left of which we should split.
(struct si (cidx pidx) #:prefab)
;; Struct representing a candidate set of splitpoints that we are considering.
;; cost = The total error in the region to the left of our rightmost splitpoint
;; indices = The si's we are considering in this candidate.
(struct cse (cost indices) #:transparent)
;; Given error-lsts, returns a list of sp objects representing where the optimal splitpoints are.
(define (err-lsts->split-indices err-lsts can-split-lst)
;; We have num-candidates candidates, each of whom has error lists of length num-points.
;; We keep track of the partial sums of the error lists so that we can easily find the cost of regions.
(define num-candidates (length err-lsts))
(define num-points (length (car err-lsts)))
(define min-weight num-points)
(define psums (map (compose partial-sum list->vector) err-lsts))
(define can-split? (curry vector-ref (list->vector can-split-lst)))
;; Our intermediary data is a list of cse's,
;; where each cse represents the optimal splitindices after however many passes
;; if we only consider indices to the left of that cse's index.
;; Given one of these lists, this function tries to add another splitindices to each cse.
(define (add-splitpoint sp-prev)
;; If there's not enough room to add another splitpoint, just pass the sp-prev along.
(for/list ([point-idx (in-naturals)] [point-entry (in-list sp-prev)])
;; We take the CSE corresponding to the best choice of previous split point.
;; The default, not making a new split-point, gets a bonus of min-weight
(let ([acost (- (cse-cost point-entry) min-weight)] [aest point-entry])
(for ([prev-split-idx (in-naturals)] [prev-entry (in-list (take sp-prev point-idx))]
#:when (can-split? (si-pidx (car (cse-indices prev-entry)))))
;; For each previous split point, we need the best candidate to fill the new regime
(let ([best #f] [bcost #f])
(for ([cidx (in-naturals)] [psum (in-list psums)])
(let ([cost (- (vector-ref psum point-idx)
(vector-ref psum prev-split-idx))])
(when (or (not best) (< cost bcost))
(set! bcost cost)
(set! best cidx))))
(when (and (< (+ (cse-cost prev-entry) bcost) acost))
(set! acost (+ (cse-cost prev-entry) bcost))
(set! aest (cse acost (cons (si best (+ point-idx 1))
(cse-indices prev-entry)))))))
aest)))
;; We get the initial set of cse's by, at every point-index,
;; accumulating the candidates that are the best we can do
;; by using only one candidate to the left of that point.
(define initial
(for/list ([point-idx (in-range num-points)])
(argmin cse-cost
;; Consider all the candidates we could put in this region
(map (λ (cand-idx cand-psums)
(let ([cost (vector-ref cand-psums point-idx)])
(cse cost (list (si cand-idx (+ point-idx 1))))))
(range num-candidates)
psums))))
;; We get the final splitpoints by applying add-splitpoints as many times as we want
(define final
(let loop ([prev initial])
(let ([next (add-splitpoint prev)])
(if (equal? prev next)
next
(loop next)))))
;; Extract the splitpoints from our data structure, and reverse it.
(reverse (cse-indices (last final))))
(define (splitpoints->point-preds splitpoints num-alts)
(define which-alt (point->alt splitpoints))
(for/list ([i (in-range num-alts)])
(λ (pt) (equal? (which-alt pt) i))))
(module+ test
(parameterize ([*start-prog* '(λ (x y) (/ x y))])
(define sps
(list (sp 0 '(/ y x) -inf.0)
(sp 2 '(/ y x) 0.0)
(sp 0 '(/ y x) +inf.0)
(sp 1 '(/ y x) +nan.0)))
(match-define (list p0? p1? p2?) (splitpoints->point-preds sps 3))
(check-true (p0? '(0 -1)))
(check-true (p2? '(-1 1)))
(check-true (p0? '(+1 1)))
(check-true (p1? '(0 0)))))
| false |
f1aed2b993d514343d04afe24ffcc149e7461a27 | b08b7e3160ae9947b6046123acad8f59152375c3 | /Programming Language Detection/Experiment-2/Dataset/Train/Racket/k-means++-clustering-7.rkt | f1bba1c9dd6cc2eea234f15c4108b54bff4088db | [] | no_license | dlaststark/machine-learning-projects | efb0a28c664419275e87eb612c89054164fe1eb0 | eaa0c96d4d1c15934d63035b837636a6d11736e3 | refs/heads/master | 2022-12-06T08:36:09.867000 | 2022-11-20T13:17:25 | 2022-11-20T13:17:25 | 246,379,103 | 9 | 5 | null | null | null | null | UTF-8 | Racket | false | false | 306 | rkt | k-means++-clustering-7.rkt | (module+ test
(define circle (uniform-cluster 30000))
; using k-means++ method
(show-clustering circle 6)
; using standard k-means method
(show-clustering circle 6 #:method random-choice)
; using manhattan distance
(parameterize ([metric manhattan-distance])
(show-clustering circle 6)))
| false |
e63e0ca45fa7eee70ac4a9fd7d5f0a6bca09af9b | 17126876cd4ff4847ff7c1fbe42471544323b16d | /beautiful-racket-lib/br/datum.rkt | 38e02751e56f16ecd2d461c5d0863e6500e0faee | [
"MIT"
] | permissive | zenspider/beautiful-racket | a9994ebbea0842bc09941dc6d161fd527a7f4923 | 1fe93f59a2466c8f4842f17d10c1841609cb0705 | refs/heads/master | 2020-06-18T11:47:08.444000 | 2019-07-04T23:21:02 | 2019-07-04T23:21:02 | 196,293,969 | 1 | 0 | NOASSERTION | 2019-07-11T00:47:46 | 2019-07-11T00:47:46 | null | UTF-8 | Racket | false | false | 1,827 | rkt | datum.rkt | #lang racket/base
(provide format-datum format-datums datum?)
(define (blank? str)
(for/and ([c (in-string str)])
(char-blank? c)))
;; read "foo bar" the same way as "(foo bar)"
;; otherwise "bar" is dropped, which is too astonishing
(define (string->datum str)
(unless (blank? str)
(let ([result (read (open-input-string (format "(~a)" str)))])
(if (= (length result) 1)
(car result)
result))))
(define (datum? x) (or (list? x) (symbol? x)))
(define (format-datum datum-template . args)
(unless (datum? datum-template)
(raise-argument-error 'format-datums "datum?" datum-template))
(string->datum (apply format (format "~a" datum-template)
(map (λ (arg) (if (syntax? arg)
(syntax->datum arg)
arg)) args))))
(define (format-datums datum-template . argss)
(unless (datum? datum-template)
(raise-argument-error 'format-datums "datum?" datum-template))
(apply map (λ args (apply format-datum datum-template args)) argss))
(module+ test
(require rackunit syntax/datum)
(check-equal? (string->datum "foo") 'foo)
(check-equal? (string->datum "(foo bar)") '(foo bar))
(check-equal? (string->datum "foo bar") '(foo bar))
(check-equal? (string->datum "42") 42)
(check-equal? (format-datum '(~a-bar-~a) "foo" "zam") '(foo-bar-zam))
(check-equal? (format-datum '(~a-bar-~a) #'foo #'zam) '(foo-bar-zam))
(check-equal? (format-datum (datum (~a-bar-~a)) "foo" "zam") '(foo-bar-zam))
(check-equal? (format-datum '~a "foo") 'foo)
(check-equal? (format-datum '~a "foo") 'foo)
(check-equal? (format-datum '~a "") (void))
(check-equal? (format-datum '~a " ") (void))
(check-equal? (format-datums '(put ~a) '("foo" "zam")) '((put foo) (put zam))))
| false |
End of preview. Expand
in Dataset Viewer.
This is a subset of racket code in the-stack-v2
, which contains all repos that have at least one define-syntax
.
- Downloads last month
- 41