blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
171
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
8
| license_type
stringclasses 2
values | repo_name
stringlengths 6
82
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 13
values | visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 1.59k
594M
⌀ | star_events_count
int64 0
77.1k
| fork_events_count
int64 0
33.7k
| gha_license_id
stringclasses 12
values | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_language
stringclasses 46
values | src_encoding
stringclasses 14
values | language
stringclasses 2
values | is_vendor
bool 2
classes | is_generated
bool 1
class | length_bytes
int64 4
7.87M
| extension
stringclasses 101
values | filename
stringlengths 2
149
| content
stringlengths 4
7.87M
| has_macro_def
bool 2
classes |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a3e5ca135c23d3d580899fcc7ba613751f0b212d | 25a6efe766d07c52c1994585af7d7f347553bf54 | /gui-lib/mred/private/wxcanvas.rkt | 1683f4c49ebc3e71fbd51f38ef57b0e6284344e7 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | racket/gui | 520ff8f4ae5704210822204aa7cd4b74dd4f3eef | d01d166149787e2d94176d3046764b35c7c0a876 | refs/heads/master | 2023-08-25T15:24:17.693905 | 2023-08-10T16:45:35 | 2023-08-10T16:45:35 | 27,413,435 | 72 | 96 | NOASSERTION | 2023-09-14T17:09:52 | 2014-12-02T03:35:22 | Racket | UTF-8 | Racket | false | false | 9,064 | rkt | wxcanvas.rkt | (module wxcanvas racket/base
(require racket/class
(prefix-in wx: "kernel.rkt")
(prefix-in wx: "wxme/text.rkt")
(prefix-in wx: "wxme/editor-canvas.rkt")
"lock.rkt"
"helper.rkt"
"wx.rkt"
"wxwindow.rkt"
"wxitem.rkt")
(provide (protect-out make-canvas-glue%
wx-canvas%
wx-editor-canvas%))
(define (make-canvas-glue% default-tabable? %) ; implies make-window-glue%
(class (make-window-glue% %)
(init mred proxy)
(init-rest args)
(inherit get-mred get-top-level clear-margins)
(public*
[do-on-char (lambda (e) (super on-char e))]
[do-on-event (lambda (e) (super on-event e))]
[do-on-scroll (lambda (e) (super on-scroll e))]
[do-on-paint (lambda () (super on-paint))])
(define tabable? default-tabable?)
(define on-popup-callback void)
(public*
[get-tab-focus (lambda () tabable?)]
[set-tab-focus (lambda (v) (set! tabable? v))]
[on-tab-in (lambda ()
(let ([mred (wx->mred this)])
(when mred
(send mred on-tab-in))))]
[set-on-popup (lambda (proc) (set! on-popup-callback proc))])
(override*
[gets-focus? (lambda () tabable?)]
[handles-key-code
(lambda (code alpha? meta?)
(if default-tabable?
(super handles-key-code code alpha? meta?)
(or meta? (not tabable?))))])
(define clear-and-on-paint
(lambda (mred)
(clear-margins)
(send mred on-paint)))
(override*
[on-char (entry-point
(lambda (e)
(let ([mred (get-mred)])
(if mred
(as-exit (lambda () (send mred on-char e)))
(super on-char e)))))]
[on-event (entry-point
(lambda (e)
(let ([mred (get-mred)])
(if mred
(as-exit (lambda () (send mred on-event e)))
(as-exit (lambda () (super on-event e)))))))]
;; only called for canvas%, not editor-canvas%:
[on-scroll (entry-point
(lambda (e)
(let ([mred (get-mred)])
(if mred
(as-exit (lambda () (send mred on-scroll e)))
(as-exit (lambda () (super on-scroll e)))))))]
[on-paint (entry-point
(lambda ()
(let ([mred (get-mred)])
(if mred
(as-exit (lambda () (clear-and-on-paint mred)))
(as-exit (lambda () (clear-margins) (super on-paint)))))))]
;; for 'combo canvases:
[on-popup (lambda () (on-popup-callback))])
(apply super-make-object mred proxy args)))
(define wx-canvas%
(make-canvas-glue%
#f
(class (make-control% wx:canvas% 0 0 #t #t)
(init parent x y w h style gl-config)
(inherit get-top-level)
(public*
[clear-margins (lambda () (void))]
[initialize-size (lambda () (void))])
(super-make-object style parent x y w h (cons 'deleted style) "canvas" gl-config)
(initialize-size)
(unless (memq 'deleted style)
(send (get-top-level) show-control this #t)))))
(define (make-editor-canvas% %)
(class %
(init parent x y w h name style spp init-buffer)
(inherit get-editor force-redraw
call-as-primary-owner min-height get-size
get-hard-minimum-size set-min-height
get-top-level)
(define fixed-height? #f)
(define fixed-height-lines 0)
(define orig-hard #f)
(define single-line-canvas? #f)
(define tabable? #f)
(override*
[on-container-resize (lambda ()
(let ([edit (get-editor)])
(when edit
(as-exit (lambda () (send edit on-display-size-when-ready))))))]
[on-scroll-on-change (lambda ()
(queue-window-callback
this
(lambda ()
(let ([edit (get-editor)])
(when edit
(send edit on-display-size-when-ready))))))]
[on-set-focus
(entry-point
(lambda ()
(as-exit (lambda () (super on-set-focus)))
(let ([m (get-editor)])
(when m
(let ([mred (wx->mred this)])
(when mred
(as-exit (lambda () (send m set-active-canvas mred)))))))))]
[set-editor
(letrec ([l (case-lambda
[(edit) (l edit #t)]
[(edit redraw?)
(let ([old-edit (get-editor)])
;; An exception here means we end up in a bad state:
(as-exit (lambda ()
;; set-editor can invoke callbacks:
(super set-editor edit redraw?)))
(let ([mred (wx->mred this)])
(when mred
(when old-edit
(as-exit
(lambda () (send old-edit remove-canvas mred))))
(when edit
(as-exit
(lambda () (send edit add-canvas mred))))))
(update-size)
;; force-redraw causes on-container-resize to be called,
;; but only when the size of the canvas really matters
;; (i.e., when it is shown)
(force-redraw))])])
l)]
[handles-key-code
(lambda (x alpha? meta?)
(case x
[(#\tab #\return escape) (and (not tabable?)
(not single-line-canvas?))]
[else (not meta?)]))]
[popup-for-editor (entry-point
(lambda (e m)
(let ([mwx (mred->wx m)])
(and (send mwx popup-grab e)
(as-exit (lambda () (send m on-demand) #t))
mwx))))])
(public*
[set-tabable (lambda (on?) (set! tabable? on?))]
[is-tabable? (lambda () tabable?)]
[set-single-line (lambda () (set! single-line-canvas? #t))]
[is-single-line? (lambda () single-line-canvas?)]
[set-line-count (lambda (n)
(if n
(begin
(unless orig-hard
(let-values ([(hmw hmh) (get-hard-minimum-size)])
(set! orig-hard hmh)))
(set! fixed-height? #t)
(set! fixed-height-lines n))
(when orig-hard
(set! fixed-height? #f)
(set-min-height orig-hard)))
(update-size))]
[get-line-count (lambda () (and fixed-height? fixed-height-lines))]
[update-size
(lambda ()
(let ([edit (get-editor)])
(when (and edit fixed-height?)
(let* ([top (if (is-a? edit wx:text%)
(send edit line-location 0 #t)
0)]
[bottom (if (is-a? edit wx:text%)
(send edit line-location 0 #f)
14)]
[height (- bottom top)])
(let* ([ch (box 0)]
[h (box 0)])
(call-as-primary-owner
(lambda ()
(send (send edit get-admin)
get-view #f #f #f ch)))
(get-size (box 0) h)
(let ([new-min-height (+ (* fixed-height-lines height)
(- (unbox h) (unbox ch)))])
(set-min-height (inexact->exact (round new-min-height)))
(force-redraw)))))))])
(override*
[set-y-margin (lambda (m)
(super set-y-margin m)
(when fixed-height? (update-size)))])
(super-make-object style parent x y w h (or name "") (cons 'deleted style) spp init-buffer)
(unless (memq 'deleted style)
(send (get-top-level) show-control this #t))
(when init-buffer
(let ([mred (wx->mred this)])
(when mred
(as-exit (lambda () (send init-buffer add-canvas mred))))))))
(define wx-editor-canvas%
(class (make-canvas-glue%
#t
(make-editor-canvas% (make-control% wx:editor-canvas%
0 0 #t #t)))
(inherit editor-canvas-on-scroll
set-no-expose-focus)
(define/override (on-scroll e)
(editor-canvas-on-scroll))
(super-new)
#;(set-no-expose-focus))))
| false |
880c43f6a084c4e1858d7c605d18d7c2803c94c6 | 24338514b3f72c6e6994c953a3f3d840b060b441 | /cur-lib/cur/curnel/racket-impl/environment.rkt | f9105367674d42de6fff9415f04a42f0570abd3d | [
"BSD-2-Clause"
]
| permissive | graydon/cur | 4efcaec7648e2bf6d077e9f41cd2b8ce72fa9047 | 246c8e06e245e6e09bbc471c84d69a9654ac2b0e | refs/heads/master | 2020-04-24T20:49:55.940710 | 2018-10-03T23:06:33 | 2018-10-03T23:06:33 | 172,257,266 | 1 | 0 | BSD-2-Clause | 2019-02-23T19:53:23 | 2019-02-23T19:53:23 | null | UTF-8 | Racket | false | false | 3,127 | rkt | environment.rkt | #lang racket/base
(require
racket/syntax
syntax/id-table
racket/dict
(for-template
"runtime.rkt"))
(provide
type-of-id
; type-of-constant
identifier-def
call-with-ctx
bind-ctx-in)
#|
An explicit typing environment for Cur.
We try hard to reuse Racket's environment, but the reflection API seems to make
this impossible in general.
|#
;; TODO: For future use
; Expects an identifier defined as a Cur constant, and it's argument as cur-runtime-term?s
; Returns it's type as a cur-runtime-term?
#;(define (type-of-constant name args)
; NB: eval is evil, but this is the least bad way I can figured out to store types.
(apply (constant-info-type-constr (syntax-local-eval name)) args))
;; TODO: Why is this a parameter instead of a syntax parameter? Well, it works, so...
(define current-cur-environment (make-parameter (make-immutable-free-id-table #:phase -1)))
; Expects an identifier defined as a Cur identifier
; Returns it's type as a cur-runtime-term?
(define (type-of-id name)
(identifier-info-type (dict-ref (current-cur-environment) name (lambda () (syntax-local-eval name)))))
(define (identifier-def name)
;; TODO: Catch specific error
(with-handlers ([values (lambda (_) #f)])
(identifier-info-delta-def (syntax-local-eval name))))
; Excepts an ordered list of pairs of an identifier and a type, as a cur-runtime-term, and a thunk.
; Adds a binding for each identifier to the identifier-info containing the type, within the scope of
; the thunk.
(define (call-with-ctx ctx th)
(parameterize ([current-cur-environment
(for/fold ([g (current-cur-environment)])
([name (map car ctx)]
[type (map cdr ctx)])
(dict-set g name (identifier-info type #f)))])
(th)))
;; Binds the names of ctx in an internal definition context before calling f
;; with that internal definition context and removes the new scopes
;; afterwards.
;; This does not replace call-with-ctx, which setup up the typing environment
;; and not the syntax bindings needed during macro expansion.
;; Calling this when unnecessary can really mess up internal definition contexts.
;; TODO: Make more resilient by tracking the current internal definition context manually?
(define (bind-ctx-in ctx f)
(define intdef (syntax-local-make-definition-context))
(syntax-local-bind-syntaxes (map car ctx) #f intdef)
(internal-definition-context-introduce intdef (f intdef) 'remove))
#;(define (call-with-ctx ctx th)
(define name-ls (map car ctx))
(for ([name name-ls]
[type (map cdr ctx)])
(namespace-set-variable-value! (syntax-e name) (identifier-info type #f) #f ns))
(let ([r (th)])
;; NB: Can't make a copy of of the current namespace, so need to manually clean up.
(for ([name name-ls])
;; TODO: Catch or detect the specific error;
;; NB: when dealing with lexical variables, it is normal
;; that a shadowed variable gets undefined multiple tmies.
(with-handlers ([(lambda (_) #t) (lambda (_) (void))])
(namespace-undefine-variable! (syntax-e name) ns)))
r))
| false |
ad0acb9a9536d4fc7aefa26496669cb7ff2c23e0 | 662e55de9b4213323395102bd50fb22b30eaf957 | /dissertation/scrbl/jfp-2019/data/transient/jpeg-2020-08-24.rktd | c0a17f83fd7c7fc7b351be66881ffa17ed2c2a4f | []
| no_license | bennn/dissertation | 3000f2e6e34cc208ee0a5cb47715c93a645eba11 | 779bfe6f8fee19092849b7e2cfc476df33e9357b | refs/heads/master | 2023-03-01T11:28:29.151909 | 2021-02-11T19:52:37 | 2021-02-11T19:52:37 | 267,969,820 | 7 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 11,431 | rktd | jpeg-2020-08-24.rktd | #lang gtp-measure/output/typed-untyped
("00000" ("cpu time: 313 real time: 311 gc time: 53" "cpu time: 313 real time: 315 gc time: 54" "cpu time: 320 real time: 319 gc time: 54" "cpu time: 317 real time: 314 gc time: 50" "cpu time: 316 real time: 318 gc time: 64" "cpu time: 313 real time: 311 gc time: 51" "cpu time: 310 real time: 311 gc time: 53" "cpu time: 313 real time: 313 gc time: 53"))
("00001" ("cpu time: 320 real time: 321 gc time: 53" "cpu time: 337 real time: 336 gc time: 56" "cpu time: 317 real time: 316 gc time: 53" "cpu time: 340 real time: 338 gc time: 56" "cpu time: 327 real time: 328 gc time: 53" "cpu time: 314 real time: 314 gc time: 57" "cpu time: 317 real time: 316 gc time: 57" "cpu time: 324 real time: 319 gc time: 57"))
("00010" ("cpu time: 403 real time: 402 gc time: 56" "cpu time: 420 real time: 420 gc time: 66" "cpu time: 407 real time: 409 gc time: 47" "cpu time: 417 real time: 416 gc time: 63" "cpu time: 407 real time: 402 gc time: 53" "cpu time: 397 real time: 399 gc time: 53" "cpu time: 407 real time: 404 gc time: 60" "cpu time: 417 real time: 417 gc time: 57"))
("00011" ("cpu time: 410 real time: 410 gc time: 50" "cpu time: 420 real time: 419 gc time: 53" "cpu time: 396 real time: 399 gc time: 56" "cpu time: 416 real time: 418 gc time: 56" "cpu time: 404 real time: 401 gc time: 53" "cpu time: 410 real time: 408 gc time: 64" "cpu time: 417 real time: 417 gc time: 72" "cpu time: 433 real time: 432 gc time: 63"))
("00100" ("cpu time: 360 real time: 357 gc time: 56" "cpu time: 354 real time: 354 gc time: 53" "cpu time: 367 real time: 366 gc time: 54" "cpu time: 373 real time: 372 gc time: 63" "cpu time: 363 real time: 359 gc time: 54" "cpu time: 367 real time: 368 gc time: 56" "cpu time: 357 real time: 354 gc time: 58" "cpu time: 367 real time: 366 gc time: 57"))
("00101" ("cpu time: 360 real time: 361 gc time: 53" "cpu time: 350 real time: 352 gc time: 50" "cpu time: 354 real time: 354 gc time: 60" "cpu time: 350 real time: 349 gc time: 56" "cpu time: 346 real time: 348 gc time: 59" "cpu time: 350 real time: 348 gc time: 50" "cpu time: 363 real time: 366 gc time: 56" "cpu time: 350 real time: 350 gc time: 56"))
("00110" ("cpu time: 437 real time: 433 gc time: 57" "cpu time: 440 real time: 438 gc time: 50" "cpu time: 453 real time: 455 gc time: 56" "cpu time: 447 real time: 446 gc time: 59" "cpu time: 443 real time: 443 gc time: 61" "cpu time: 444 real time: 444 gc time: 61" "cpu time: 440 real time: 438 gc time: 50" "cpu time: 454 real time: 455 gc time: 71"))
("00111" ("cpu time: 440 real time: 438 gc time: 53" "cpu time: 454 real time: 454 gc time: 53" "cpu time: 443 real time: 445 gc time: 60" "cpu time: 446 real time: 445 gc time: 61" "cpu time: 446 real time: 446 gc time: 53" "cpu time: 450 real time: 448 gc time: 54" "cpu time: 427 real time: 427 gc time: 50" "cpu time: 440 real time: 441 gc time: 57"))
("01000" ("cpu time: 317 real time: 311 gc time: 56" "cpu time: 334 real time: 333 gc time: 56" "cpu time: 313 real time: 314 gc time: 50" "cpu time: 313 real time: 310 gc time: 50" "cpu time: 310 real time: 310 gc time: 55" "cpu time: 327 real time: 324 gc time: 58" "cpu time: 310 real time: 309 gc time: 50" "cpu time: 314 real time: 312 gc time: 56"))
("01001" ("cpu time: 337 real time: 336 gc time: 73" "cpu time: 327 real time: 327 gc time: 62" "cpu time: 323 real time: 323 gc time: 50" "cpu time: 327 real time: 327 gc time: 63" "cpu time: 326 real time: 323 gc time: 56" "cpu time: 333 real time: 332 gc time: 58" "cpu time: 330 real time: 329 gc time: 63" "cpu time: 334 real time: 333 gc time: 57"))
("01010" ("cpu time: 400 real time: 398 gc time: 50" "cpu time: 410 real time: 410 gc time: 57" "cpu time: 400 real time: 397 gc time: 53" "cpu time: 403 real time: 404 gc time: 56" "cpu time: 410 real time: 411 gc time: 54" "cpu time: 413 real time: 411 gc time: 53" "cpu time: 410 real time: 409 gc time: 54" "cpu time: 416 real time: 416 gc time: 76"))
("01011" ("cpu time: 423 real time: 422 gc time: 53" "cpu time: 410 real time: 411 gc time: 50" "cpu time: 420 real time: 419 gc time: 67" "cpu time: 410 real time: 412 gc time: 50" "cpu time: 413 real time: 415 gc time: 60" "cpu time: 426 real time: 427 gc time: 54" "cpu time: 420 real time: 417 gc time: 53" "cpu time: 407 real time: 405 gc time: 53"))
("01100" ("cpu time: 356 real time: 356 gc time: 60" "cpu time: 364 real time: 362 gc time: 67" "cpu time: 347 real time: 346 gc time: 58" "cpu time: 350 real time: 350 gc time: 57" "cpu time: 360 real time: 358 gc time: 64" "cpu time: 356 real time: 359 gc time: 59" "cpu time: 360 real time: 357 gc time: 53" "cpu time: 357 real time: 354 gc time: 56"))
("01101" ("cpu time: 363 real time: 363 gc time: 57" "cpu time: 363 real time: 360 gc time: 59" "cpu time: 370 real time: 368 gc time: 63" "cpu time: 363 real time: 365 gc time: 58" "cpu time: 370 real time: 370 gc time: 59" "cpu time: 383 real time: 380 gc time: 66" "cpu time: 360 real time: 359 gc time: 53" "cpu time: 363 real time: 364 gc time: 66"))
("01110" ("cpu time: 467 real time: 463 gc time: 62" "cpu time: 440 real time: 439 gc time: 56" "cpu time: 433 real time: 432 gc time: 57" "cpu time: 444 real time: 442 gc time: 53" "cpu time: 453 real time: 450 gc time: 60" "cpu time: 450 real time: 446 gc time: 67" "cpu time: 443 real time: 440 gc time: 60" "cpu time: 446 real time: 448 gc time: 53"))
("01111" ("cpu time: 440 real time: 438 gc time: 64" "cpu time: 440 real time: 438 gc time: 54" "cpu time: 440 real time: 438 gc time: 57" "cpu time: 440 real time: 439 gc time: 53" "cpu time: 430 real time: 430 gc time: 53" "cpu time: 450 real time: 448 gc time: 50" "cpu time: 437 real time: 436 gc time: 54" "cpu time: 450 real time: 446 gc time: 56"))
("10000" ("cpu time: 403 real time: 397 gc time: 60" "cpu time: 396 real time: 397 gc time: 57" "cpu time: 390 real time: 388 gc time: 50" "cpu time: 386 real time: 387 gc time: 51" "cpu time: 393 real time: 391 gc time: 50" "cpu time: 386 real time: 385 gc time: 51" "cpu time: 397 real time: 394 gc time: 58" "cpu time: 394 real time: 392 gc time: 54"))
("10001" ("cpu time: 423 real time: 424 gc time: 71" "cpu time: 394 real time: 393 gc time: 68" "cpu time: 397 real time: 395 gc time: 61" "cpu time: 397 real time: 397 gc time: 57" "cpu time: 400 real time: 398 gc time: 53" "cpu time: 413 real time: 413 gc time: 58" "cpu time: 393 real time: 391 gc time: 53" "cpu time: 407 real time: 406 gc time: 64"))
("10010" ("cpu time: 484 real time: 482 gc time: 64" "cpu time: 480 real time: 480 gc time: 53" "cpu time: 477 real time: 476 gc time: 53" "cpu time: 477 real time: 476 gc time: 50" "cpu time: 500 real time: 495 gc time: 57" "cpu time: 490 real time: 490 gc time: 63" "cpu time: 480 real time: 481 gc time: 58" "cpu time: 484 real time: 484 gc time: 57"))
("10011" ("cpu time: 510 real time: 506 gc time: 63" "cpu time: 477 real time: 477 gc time: 50" "cpu time: 480 real time: 476 gc time: 53" "cpu time: 493 real time: 490 gc time: 53" "cpu time: 510 real time: 509 gc time: 68" "cpu time: 490 real time: 487 gc time: 54" "cpu time: 487 real time: 487 gc time: 53" "cpu time: 487 real time: 482 gc time: 57"))
("10100" ("cpu time: 430 real time: 429 gc time: 50" "cpu time: 427 real time: 426 gc time: 50" "cpu time: 427 real time: 429 gc time: 58" "cpu time: 434 real time: 432 gc time: 53" "cpu time: 450 real time: 447 gc time: 50" "cpu time: 433 real time: 431 gc time: 54" "cpu time: 430 real time: 430 gc time: 50" "cpu time: 463 real time: 459 gc time: 60"))
("10101" ("cpu time: 456 real time: 454 gc time: 57" "cpu time: 434 real time: 431 gc time: 53" "cpu time: 440 real time: 441 gc time: 53" "cpu time: 430 real time: 431 gc time: 64" "cpu time: 450 real time: 449 gc time: 71" "cpu time: 453 real time: 453 gc time: 63" "cpu time: 426 real time: 424 gc time: 60" "cpu time: 433 real time: 435 gc time: 71"))
("10110" ("cpu time: 520 real time: 517 gc time: 51" "cpu time: 523 real time: 521 gc time: 50" "cpu time: 513 real time: 512 gc time: 58" "cpu time: 520 real time: 517 gc time: 50" "cpu time: 540 real time: 539 gc time: 50" "cpu time: 523 real time: 521 gc time: 63" "cpu time: 517 real time: 515 gc time: 50" "cpu time: 517 real time: 511 gc time: 56"))
("10111" ("cpu time: 510 real time: 509 gc time: 60" "cpu time: 527 real time: 525 gc time: 53" "cpu time: 520 real time: 519 gc time: 56" "cpu time: 527 real time: 523 gc time: 53" "cpu time: 516 real time: 515 gc time: 60" "cpu time: 527 real time: 527 gc time: 57" "cpu time: 517 real time: 517 gc time: 61" "cpu time: 526 real time: 525 gc time: 56"))
("11000" ("cpu time: 390 real time: 390 gc time: 47" "cpu time: 410 real time: 406 gc time: 50" "cpu time: 397 real time: 396 gc time: 57" "cpu time: 393 real time: 393 gc time: 59" "cpu time: 400 real time: 397 gc time: 47" "cpu time: 397 real time: 395 gc time: 54" "cpu time: 400 real time: 400 gc time: 60" "cpu time: 400 real time: 402 gc time: 69"))
("11001" ("cpu time: 397 real time: 397 gc time: 60" "cpu time: 440 real time: 435 gc time: 53" "cpu time: 403 real time: 406 gc time: 66" "cpu time: 400 real time: 397 gc time: 59" "cpu time: 403 real time: 401 gc time: 53" "cpu time: 403 real time: 402 gc time: 61" "cpu time: 453 real time: 453 gc time: 60" "cpu time: 420 real time: 417 gc time: 60"))
("11010" ("cpu time: 480 real time: 477 gc time: 60" "cpu time: 480 real time: 478 gc time: 58" "cpu time: 500 real time: 501 gc time: 62" "cpu time: 503 real time: 503 gc time: 62" "cpu time: 486 real time: 484 gc time: 57" "cpu time: 480 real time: 478 gc time: 58" "cpu time: 486 real time: 484 gc time: 57" "cpu time: 480 real time: 476 gc time: 53"))
("11011" ("cpu time: 494 real time: 491 gc time: 62" "cpu time: 480 real time: 479 gc time: 56" "cpu time: 497 real time: 498 gc time: 67" "cpu time: 490 real time: 488 gc time: 66" "cpu time: 480 real time: 478 gc time: 53" "cpu time: 494 real time: 494 gc time: 50" "cpu time: 484 real time: 484 gc time: 57" "cpu time: 503 real time: 503 gc time: 75"))
("11100" ("cpu time: 433 real time: 431 gc time: 53" "cpu time: 433 real time: 432 gc time: 56" "cpu time: 433 real time: 431 gc time: 68" "cpu time: 453 real time: 450 gc time: 59" "cpu time: 433 real time: 433 gc time: 56" "cpu time: 423 real time: 422 gc time: 56" "cpu time: 434 real time: 432 gc time: 54" "cpu time: 457 real time: 456 gc time: 67"))
("11101" ("cpu time: 453 real time: 456 gc time: 53" "cpu time: 447 real time: 442 gc time: 56" "cpu time: 440 real time: 438 gc time: 57" "cpu time: 434 real time: 429 gc time: 53" "cpu time: 447 real time: 445 gc time: 66" "cpu time: 470 real time: 467 gc time: 53" "cpu time: 430 real time: 429 gc time: 65" "cpu time: 447 real time: 447 gc time: 60"))
("11110" ("cpu time: 513 real time: 513 gc time: 52" "cpu time: 520 real time: 522 gc time: 60" "cpu time: 520 real time: 520 gc time: 60" "cpu time: 513 real time: 514 gc time: 50" "cpu time: 530 real time: 529 gc time: 56" "cpu time: 517 real time: 517 gc time: 60" "cpu time: 533 real time: 531 gc time: 68" "cpu time: 520 real time: 517 gc time: 53"))
("11111" ("cpu time: 540 real time: 542 gc time: 58" "cpu time: 517 real time: 516 gc time: 57" "cpu time: 537 real time: 534 gc time: 57" "cpu time: 517 real time: 515 gc time: 64" "cpu time: 523 real time: 526 gc time: 53" "cpu time: 513 real time: 512 gc time: 70" "cpu time: 523 real time: 520 gc time: 66" "cpu time: 516 real time: 517 gc time: 60"))
| false |
d099f8c5e26c12450a19fcba3f85cac2a300a202 | b3dc4d8347689584f0d09452414ffa483cf7dcb3 | /shell-pipeline/private/subprocess-pipeline.rkt | c574bbeab6bd9fed020916dbd078164da668f4f1 | [
"MIT",
"Apache-2.0"
]
| permissive | willghatch/racket-rash | 75e336d985bf59b4adfe5d5a7bd68d31cf2fe7db | 42460a283ce2d7296257b068505cd4649052f67c | refs/heads/master | 2023-06-17T16:16:26.126945 | 2023-02-24T18:13:25 | 2023-02-24T18:17:02 | 65,781,414 | 556 | 43 | NOASSERTION | 2021-03-09T17:17:29 | 2016-08-16T02:37:13 | Racket | UTF-8 | Racket | false | false | 38,274 | rkt | subprocess-pipeline.rkt | #lang racket/base
(require racket/port)
(require racket/exn)
(require racket/list)
(require racket/format)
(require racket/contract/base)
(require syntax/parse/define)
(require "mostly-structs.rkt")
(require "misc-utils.rkt")
(require (submod "mostly-structs.rkt" internals))
(provide
(contract-out
[shellify (-> procedure?
procedure?)]
[struct alias-func ([func procedure?])]
[run-subprocess-pipeline
(->* ()
(#:in (or/c input-port? false/c path-string-symbol? special-redirect?)
#:out (or/c output-port?
false/c
path-string-symbol?
file-redirection-spec?
special-redirect?
(list/c path-string-symbol?
(or/c 'error 'append 'truncate)))
#:strictness (or/c 'strict 'lazy 'permissive)
#:lazy-timeout real?
#:background? any/c
#:err (or/c output-port?
false/c
path-string-symbol?
file-redirection-spec?
special-redirect?
(list/c path-string-symbol?
(or/c 'error 'append 'truncate)))
)
#:rest (listof (or/c list? pipeline-member-spec?))
pipeline?)]
[run-subprocess-pipeline/out
(->* ()
(#:in (or/c input-port? false/c path-string-symbol? special-redirect?)
#:strictness (or/c 'strict 'lazy 'permissive)
#:lazy-timeout real?)
#:rest (listof (or/c list? pipeline-member-spec?))
any/c)]
#;[run-pipeline/return
(->* ()
(#:in (or/c input-port? false/c path-string-symbol?)
#:out (or/c output-port? false/c path-string-symbol?
(list/c path-string-symbol?
(or/c 'error 'append 'truncate)))
#:strictness (or/c 'strict 'lazy 'permissive)
#:lazy-timeout real?
#:failure-as-exn? any/c
#:err (or/c output-port? false/c path-string-symbol?
(list/c path-string-symbol?
(or/c 'error 'append 'truncate)))
)
#:rest (listof (or/c list? pipeline-member-spec?))
any/c)]
[pipeline? (-> any/c boolean?)]
[pipeline-port-to (-> pipeline? (or/c false/c output-port?))]
[pipeline-port-from (-> pipeline? (or/c false/c input-port?))]
[pipeline-err-ports (-> pipeline? (listof (or/c false/c input-port?)))]
[pipeline-wait (-> pipeline? void?)]
[pipeline-kill (-> pipeline? void?)]
[pipeline-running? (-> pipeline? boolean?)]
[pipeline-status (-> pipeline? any/c)]
[pipeline-status/list (-> pipeline? (listof any/c))]
[pipeline-success? (-> pipeline? any/c)]
[pipeline-has-failures? (-> pipeline? any/c)]
;[pipeline-start-ms (-> pipeline? real?)]
;[pipeline-end-ms (-> pipeline? real?)]
[pipeline-error-captured-stderr (-> pipeline? (or/c #f string?))]
[pipeline-error-argl (-> pipeline? (listof any/c))]
)
(rename-out [unix-pipeline-member-spec pipeline-member-spec])
(rename-out [unix-pipeline-member-spec? pipeline-member-spec?])
path-string-symbol?
prop:alias-func
and/success
or/success
file-redirect
special-redirect?
null-redirect
stderr-capture-redirect
shared-stderr-capture-redirect
stdout-redirect
stderr-redirect
)
(module+ resolve-command-path
(provide resolve-command-path prop:alias-func?))
(define mk-pipeline-member-spec unix-pipeline-member-spec)
(define pipeline-member-spec? unix-pipeline-member-spec?)
(define (cp-spec base
#:argl [argl (pipeline-member-spec-argl base)]
#:err [err (pipeline-member-spec-port-err base)]
#:success [success (pipeline-member-spec-success-pred base)])
(unix-pipeline-member-spec argl #:err err #:success success))
;;;; Command Resolution ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (resolve-alias pm-spec)
(if (pm-spec-alias? pm-spec)
(let* ([old-argl (pipeline-member-spec-argl pm-spec)]
[old-cmd (car old-argl)]
[new-argl-or-spec (apply ({prop:alias-func-ref old-cmd} old-cmd)
(cdr old-argl))]
[new-spec (cond [(and (list? new-argl-or-spec)
(not (null? new-argl-or-spec)))
(mk-pipeline-member-spec new-argl-or-spec)]
[(pipeline-member-spec? new-argl-or-spec)
new-argl-or-spec]
[else
(error
'resolve-alias
"pipeline alias did not produce an argument list")])]
[old-err (pipeline-member-spec-port-err pm-spec)]
[use-err (if (pipeline-default-option? old-err)
(pipeline-member-spec-port-err new-spec)
old-err)]
[old-success (pipeline-member-spec-success-pred pm-spec)]
[use-success (if (pipeline-default-option? old-success)
(pipeline-member-spec-success-pred new-spec)
old-success)])
(mk-pipeline-member-spec (pipeline-member-spec-argl new-spec)
#:err use-err
#:success use-success))
pm-spec))
(define (resolve-pipeline-member-spec-path pm-spec)
(let* ([argl (pipeline-member-spec-argl pm-spec)]
[cmd (car argl)]
[cmdpath (resolve-command-path cmd)])
(if cmdpath
(cp-spec pm-spec #:argl (cons cmdpath (cdr argl)))
(error 'resolve-pipeline-member-spec-path
"Command not found: ~a" cmd))))
(define (resolve-command-path cmd)
(let ([pathstr (if (path? cmd) cmd (~a cmd))])
(or (find-executable-path pathstr)
(and (equal? 'windows (system-type 'os))
(string? pathstr)
(find-executable-path
(string-append (~a cmd) ".exe")))
(error 'resolve-command-path "can't find executable for ~s" cmd))))
(define (resolve-spec err-default)
(define (resolve-spec* pm-spec)
(define (resolve-spec-defaults spec)
(mk-pipeline-member-spec
(pipeline-member-spec-argl spec)
#:err (let ([e (pipeline-member-spec-port-err spec)])
(if (pipeline-default-option? e) err-default e))
#:success (let ([s (pipeline-member-spec-success-pred spec)])
(if (pipeline-default-option? s) #f s))))
(let* ([argl (pipeline-member-spec-argl pm-spec)]
[bad-argl? (when (or (not (list? argl))
(null? argl))
(error 'resolve-spec
"pipeline spec had an empty command/argument list"))]
[cmd (first argl)])
(cond
[(pm-spec-alias? pm-spec) (resolve-spec* (resolve-alias pm-spec))]
[(path-string-symbol? cmd)
(resolve-spec-defaults
(resolve-pipeline-member-spec-path pm-spec))]
;; Note that paths are safe from further resolution -- an alias
;; chain should always end with a path.
[else (resolve-spec-defaults pm-spec)])))
resolve-spec*)
;;;; Pipeline Members ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(struct pipeline-member
(subproc-or-thread port-err thread-ret-box thread-exn-box
argl stderr-capture-port killed-box
success-pred)
#:property prop:evt (λ (pm)
(let ([sema (make-semaphore)])
(thread (λ ()
(pipeline-member-wait pm)
(semaphore-post sema)))
(wrap-evt sema (λ _ pm)))))
(define-values (prop:alias-func
prop:alias-func?
prop:alias-func-ref)
(make-struct-type-property 'alias-func))
(struct alias-func
(func)
#:property prop:alias-func (λ (s) (alias-func-func s))
#:transparent)
(define (pm-spec-command m)
(car (pipeline-member-spec-argl m)))
(define (pm-spec-lookup? pmember)
(and (pipeline-member-spec? pmember)
(let ([cmd (car (pipeline-member-spec-argl pmember))])
(or (symbol? cmd) (string? cmd)))))
(define (pm-spec-path? pmember)
(and (pipeline-member-spec? pmember)
(let ([cmd (car (pipeline-member-spec-argl pmember))])
(or (path? cmd) (string? cmd)))))
(define (pm-spec-func? pmember)
(and (pipeline-member-spec? pmember)
(not (pm-spec-alias? pmember))
(procedure? (car (pipeline-member-spec-argl pmember)))))
(define (pm-spec-alias? pmember)
(and (pipeline-member-spec? pmember)
(prop:alias-func? (car (pipeline-member-spec-argl pmember)))))
(define (pipeline-member-process? pmember)
(and (pipeline-member? pmember)
(subprocess? (pipeline-member-subproc-or-thread pmember))))
(define (pipeline-member-thread? pmember)
(and (pipeline-member? pmember)
(thread? (pipeline-member-subproc-or-thread pmember))))
(define (pipeline-member-wait member)
(if (pipeline-member-process? member)
(subprocess-wait (pipeline-member-subproc-or-thread member))
(thread-wait (pipeline-member-subproc-or-thread member))))
(define (pipeline-member-kill m)
(if (pipeline-member-process? m)
(when (pipeline-member-running? m)
(subprocess-kill (pipeline-member-subproc-or-thread m) #t)
(set-box! (pipeline-member-killed-box m) #t))
(let ([thread (pipeline-member-subproc-or-thread m)])
(when (not (thread-dead? thread))
(kill-thread (pipeline-member-subproc-or-thread m))
(set-box! (pipeline-member-killed-box m) #t)
(set-box! (pipeline-member-thread-exn-box m) 'killed)))))
(define (pipeline-member-running? m)
(if (pipeline-member-process? m)
(equal? 'running (subprocess-status (pipeline-member-subproc-or-thread m)))
(thread-running? (pipeline-member-subproc-or-thread m))))
(define (pipeline-member-status m)
(if (pipeline-member-process? m)
(if (unbox (pipeline-member-killed-box m))
'killed
(subprocess-status (pipeline-member-subproc-or-thread m)))
(let* ([dead (thread-dead? (pipeline-member-subproc-or-thread m))]
[ret (unbox (pipeline-member-thread-ret-box m))]
[err (unbox (pipeline-member-thread-exn-box m))])
(if (not dead)
'running
(or ret err)))))
(define (pipeline-member-captured-stderr m)
(if (and (output-port? (pipeline-member-stderr-capture-port m))
(string-port? (pipeline-member-stderr-capture-port m)))
(get-output-string (pipeline-member-stderr-capture-port m))
#f))
(define (pipeline-member-success? m #:strict? [strict? #f])
(let* ([killed? (unbox (pipeline-member-killed-box m))]
[ignore-real-status (if strict? #f killed?)]
[success-pred (pipeline-member-success-pred m)]
[success-pred+ (or success-pred (λ (v) (equal? 0 v)))])
(or ignore-real-status
(if (pipeline-member-process? m)
(success-pred+ (subprocess-status (pipeline-member-subproc-or-thread m)))
(let ([no-error (not (unbox (pipeline-member-thread-exn-box m)))])
(if success-pred
(and no-error
(success-pred (unbox (pipeline-member-thread-ret-box m))))
no-error))))))
;;;; Pipelines ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(struct pipeline
(port-to port-from members start-bg? strictness
from-port-copier err-port-copiers lazy-timeout
start-ms end-ms-box cleaner default-err)
#:property prop:evt (λ (pline)
(let ([sema (make-semaphore)])
(thread (λ ()
(pipeline-wait pline)
(semaphore-post sema)))
(wrap-evt sema (λ _ pline))))
#:methods gen:custom-write
[(define (write-proc pline output-port output-mode)
(if (pipeline-running? pline)
(fprintf output-port "#<pipeline:running=#t>")
(fprintf output-port "#<pipeline:success=~a,return=~a>"
(pipeline-success? pline)
(pipeline-status pline))))]
;#:transparent
)
(define (pipeline-spec? pline)
(for/and ([m (pipeline-members pline)])
(pipeline-member-spec? m)))
(define (pipeline-err-ports pline)
(map pipeline-member-port-err (pipeline-members pline)))
(define (pipeline-end-ms pline)
(pipeline-wait pline)
(unbox (pipeline-end-ms-box pline)))
(define (pipeline-wait/end/internal pline)
(pipeline-member-wait (car (reverse (pipeline-members pline)))))
(define (pipeline-wait/all/internal pline)
(for ([m (pipeline-members pline)])
(pipeline-member-wait m)))
(define (pipeline-wait/internal pline)
(cond [(equal? (pipeline-strictness pline) 'strict)
(pipeline-wait/all/internal pline)]
[(equal? (pipeline-strictness pline) 'permissive)
(pipeline-wait/end/internal pline)]
[else
(pipeline-wait/end/internal pline)
;; wait for up to timeout msecs
(let ([alarm (alarm-evt (* 1000 (pipeline-lazy-timeout pline)))])
(let loop ([sync-res #f])
(when (not (equal? sync-res alarm))
(loop (apply sync alarm (pipeline-members pline))))))]))
(define (pipeline-wait-port-copy/end pline)
(define ts (filter thread? (list (pipeline-from-port-copier pline)
(first (reverse (pipeline-err-port-copiers pline))))))
(for ([t ts])
(thread-wait t)))
(define (pipeline-wait-port-copy/all pline)
(define ts (filter thread? (cons (pipeline-from-port-copier pline)
(pipeline-err-port-copiers pline))))
(for ([t ts])
(thread-wait t)))
(define (pipeline-wait-cleaner pline all?)
(pipeline-wait/internal pline)
(if all?
(pipeline-wait-port-copy/all pline)
(pipeline-wait-port-copy/end pline))
(thread-wait (pipeline-cleaner pline)))
(define (pipeline-wait pline)
(if (equal? (pipeline-strictness pline) 'permissive)
(pipeline-wait-cleaner pline #f)
(pipeline-wait-cleaner pline #t)))
(define (pipeline-kill pline)
(for ([m (pipeline-members pline)])
(pipeline-member-kill m)))
(define (pipeline-running? pline)
(for/or ([m (pipeline-members pline)])
(pipeline-member-running? m)))
(define (pipeline-status/list pline)
(pipeline-wait pline)
(map pipeline-member-status (pipeline-members pline)))
(define (pipeline-success? pline)
(pipeline-wait pline)
(define strictness (pipeline-strictness pline))
(define strict? (equal? strictness 'strict))
(define last-member-success?
(pipeline-member-success? #:strict? #t
(car (reverse (pipeline-members pline)))))
(if (equal? 'permissive strictness)
last-member-success?
(and
(for/and ([m (pipeline-members pline)])
(pipeline-member-success? m #:strict? strict?))
last-member-success?)))
(define ((pipeline-success-based-info-func accessor) pline)
(pipeline-wait pline)
(define strictness (pipeline-strictness pline))
(define strict? (equal? strictness 'strict))
(let ([last-status (accessor (car (reverse (pipeline-members pline))))])
(if (equal? 'permissive strictness)
last-status
(let ([pre-status
(for/or ([m (pipeline-members pline)])
(and (not (pipeline-member-success? m #:strict? strict?))
(accessor m)))])
(or pre-status last-status)))))
(define pipeline-status
(pipeline-success-based-info-func pipeline-member-status))
(define pipeline-error-captured-stderr
(pipeline-success-based-info-func pipeline-member-captured-stderr))
(define pipeline-error-argl
(pipeline-success-based-info-func pipeline-member-argl))
(define (pipeline-has-failures? pline)
(ormap (λ (m) (not (pipeline-member-success?
m #:strict? (equal? 'strict (pipeline-strictness pline)))))
(pipeline-members pline)))
(define (make-pipeline-spec #:in in
#:out out
#:strictness strictness
#:background? bg?
#:err default-err
#:lazy-timeout lazy-timeout
members)
(let* ([members1 (map (λ (m)
(if (pipeline-member-spec? m)
m
(mk-pipeline-member-spec m #:err (pipeline-default-option)
#:success (pipeline-default-option))))
members)])
(pipeline in out
members1
bg? strictness
'from-port-copier
'err-port-coper
lazy-timeout
'start-ms 'end-ms-box 'cleaner
default-err)))
(define (run-subprocess-pipeline #:in [in (current-input-port)]
#:out [out (current-output-port)]
#:strictness [strictness 'lazy]
#:background? [bg? #f]
#:err [default-err (current-error-port)]
#:lazy-timeout [lazy-timeout 1]
. members)
(let ([pline
(run-pipeline/spec
(make-pipeline-spec #:in in #:out out
#:strictness strictness
#:background? bg?
#:err default-err
#:lazy-timeout lazy-timeout
members))])
(if bg?
pline
(begin (pipeline-wait pline)
pline))))
(define (run-subprocess-pipeline/out #:strictness [strictness 'lazy]
#:lazy-timeout [lazy-timeout 1]
#:in [in (open-input-string "")]
. members)
(let* ([out (open-output-string)]
[err (open-output-string 'run-subprocess-pipeline/out_stderr)]
[pline-spec (make-pipeline-spec #:in in #:out out
#:strictness strictness
#:lazy-timeout lazy-timeout
#:background? #f
#:err err
members)]
[pline (parameterize ([current-output-port out]
[current-error-port err]
[current-input-port in])
(run-pipeline/spec pline-spec))]
[wait (pipeline-wait pline)]
[kill (pipeline-kill pline)]
[status (pipeline-status pline)])
(if (not (pipeline-success? pline))
(error 'run-subprocess-pipeline/out
"unsuccessful pipeline with return ~a and stderr: ~v"
status
(pipeline-error-captured-stderr pline))
(get-output-string out))))
#;(define (run-pipeline/return #:in [in (current-input-port)]
#:out [out (current-output-port)]
#:strictness [strictness #f]
#:lazy-timeout [lazy-timeout 1]
#:err [default-err (current-error-port)]
#:failure-as-exn? [failure-as-exn? #t]
. members)
(let ([pline (apply run-subprocess-pipeline
#:in in #:out out
#:err default-err
#:strictness strictness
#:lazy-timeout lazy-timeout
#:background? #f
members)])
(pipeline-wait pline)
(if (or (pipeline-success? pline) (not failure-as-exn?))
(pipeline-status pline)
(let ([err (pipeline-status pline)])
(if (exn? err)
(raise err)
(error 'run-pipeline/return
"pipeline unsuccessful with return ~a" err))))))
(define (run-pipeline/spec pipeline-spec)
(let* ([members-pre-resolve (pipeline-members pipeline-spec)]
[default-err (pipeline-default-err pipeline-spec)]
[members (map (resolve-spec default-err) members-pre-resolve)]
[strictness (pipeline-strictness pipeline-spec)]
[lazy-timeout (pipeline-lazy-timeout pipeline-spec)]
[bg? (pipeline-start-bg? pipeline-spec)]
[to-port (pipeline-port-to pipeline-spec)]
[to-file-port (cond [(special-redirect? to-port)
(if (equal? to-port null-redirect)
(open-input-string "")
(error
'run-pipeline
"special redirection not supported as input redirection: ~a"
(special-redirect-type to-port)))]
[(path-string-symbol? to-port)
(open-input-file (path-string-sym->path to-port))]
[else #f])]
;; re-use name...
[to-port (or to-file-port to-port)]
[to-use (cond [(and (pm-spec-path? (car members))
(port? to-port)
(not (file-stream-port? to-port)))
#f]
[else to-port])]
[from-port (pipeline-port-from pipeline-spec)]
[from-file-port (with-handlers ([(λ _ #t) (λ (e)
(when (port? to-file-port)
(close-input-port to-file-port))
(raise e))])
(let ([ffp (open-output-spec from-port)])
(if (eq? ffp from-port) #f ffp)))]
;; re-use from-port name
[from-port (or from-file-port from-port)]
[from-use (cond [(and (pm-spec-path? (car (reverse members)))
(port? from-port)
(not (file-stream-port? from-port)))
#f]
[else from-port])]
[err-ports (map pipeline-member-spec-port-err members)]
[err-ports-with-paths (map (λ (p) (cond [(path-string-symbol? p)
(path-string-sym->path p)]
[(file-redirection-spec? p)
(path-string-sym->path
(file-redirection-spec-file p))]
[(list? p)
(path-string-sym->path (car p))]
[else #f]))
err-ports)]
[shared-string-port-box (box #f)]
[err-ports-mapped-with-dup-numbers
(for/list ([p err-ports]
[epp err-ports-with-paths]
[i (in-naturals)])
(with-handlers ([(λ _ #t)(λ (e) e)])
;; if an exception is thrown, catch it and save it for later
(cond
[(equal? p null-redirect) (open-output-nowhere)]
[(equal? p stdout-redirect) 'stdout]
[(equal? p stderr-capture-redirect)
(open-output-string 'stderr-capture-redirect)]
[(equal? p shared-stderr-capture-redirect)
(or (unbox shared-string-port-box)
(let ([str-port (open-output-string
'shared-stderr-capture-redirect)])
(set-box! shared-string-port-box str-port)
str-port))]
[(special-redirect? p)
(error
'run-pipeline
"special redirect not supported for stderr: ~a"
(special-redirect-type p))]
;; If this is the second instance of the file, note the number
;; so they can share ports rather than trying to open
;; a file twice.
[(and (path? epp) (member epp (take err-ports-with-paths i)))
(- (length err-ports-with-paths)
(length (member epp err-ports-with-paths)))]
[(list? p) (open-output-file epp #:exists (second p))]
[(file-redirection-spec? p)
(open-output-file (file-redirection-spec-file p)
#:exists (file-redirection-spec-exists-flag p))]
[(path-string-symbol? p)
(open-output-file (path-string-sym->path p)
#:exists 'error)]
[else p])))]
[err-ports-mapped (map (λ (p) (if (number? p)
(list-ref err-ports-mapped-with-dup-numbers p)
p))
err-ports-mapped-with-dup-numbers)]
[err-ports-to-close (filter (λ (x) x)
(map (λ (p pstr?) (if (and (port? p) pstr?) p #f))
err-ports-mapped err-ports-with-paths))]
[err-ports-err-close-for-exn
;; ok, now that we have a reference to any opened error ports, we can
;; close them before throwing out our error.
(map (λ (p) (if (exn? p)
(begin (for ([p err-ports-to-close])
(close-output-port p))
(when from-file-port (close-output-port from-file-port))
(when to-file-port (close-input-port to-file-port))
(raise p))
#f))
err-ports-mapped)]
[members-with-m-err
(map (λ (m p) (cp-spec m #:err p))
members
err-ports-mapped)]
[run-members/ports (run-pipeline-members members-with-m-err to-use from-use)]
[run-members (first run-members/ports)]
[to-out (second run-members/ports)]
[from-out (third run-members/ports)]
[err-port-copiers (fourth run-members/ports)]
[ports-to-close (append (filter port? (list to-file-port from-file-port))
err-ports-to-close)]
[from-ret-almost (if (and from-port from-out)
(thread (λ ()
(copy-port from-out from-port)
(close-input-port from-out)))
from-out)]
[from-port-copier (if (thread? from-ret-almost)
from-ret-almost
#f)]
[from-ret (if (thread? from-ret-almost) #f from-ret-almost)]
[to-ret (if (and to-port to-out)
(begin
(thread (λ ()
;; TODO - log this somehow, don't just throw it out.
;; There seem to be occasional errors about the pipe
;; being closed in a way that copy-port is unhappy with.
(with-handlers ([(λ _ #t) (λ e (void))])
(copy-port to-port to-out))
(close-output-port to-out)))
#f)
to-out)]
[end-time-box (box #f)]
[pline (pipeline to-ret from-ret run-members bg? strictness
from-port-copier err-port-copiers lazy-timeout
(current-inexact-milliseconds) end-time-box
'cleaner-goes-here default-err)]
[cleanup-thread
(thread (λ ()
(pipeline-wait/internal pline)
(for ([p ports-to-close])
(when (output-port? p) (close-output-port p))
(when (input-port? p) (close-input-port p)))
(when (not (equal? strictness 'strict))
(pipeline-kill pline))
(set-box! end-time-box
(current-inexact-milliseconds))))]
[pline-final (struct-copy pipeline pline [cleaner cleanup-thread])])
pline-final))
(define (run-pipeline-members pipeline-member-specs to-line-port from-line-port)
#| This has to be careful about the it starts things in for proper wiring.
The important bit is that subprocesses have to be passed a file-stream-port
for each of its in/out/err ports (or #f to create one).
To facilitate this, we start the subprocess pipeline members first, using
the previous output as the input if it's a file-stream, and getting an output
for each (except maybe at the end). If a process gets its input from a thread
pipeline member, then the process needs to give us a file-stream port, which we
then use in the next pass for threads.
The second pass starts the function/thread pipeline members.
In the end there is a third pass to start any pipeline members marked to run
in the same thread, which is basically a hack, but I deemed it worth it to
let `cd` be run in a pipeline (for syntactic easiness in Rash).
TODO - this should go away! `cd` is a line macro now.
|#
(struct pmi
;; pmi for pipeline-member-intermediate -- has info important for running
;; things that I don't want to expose in the final output.
(port-to port-from port-err subproc-or-thread thread-ret-box thread-exn-box
argl capture-port-err success-pred)
#:transparent)
(define (pmi-process? pmember)
(and (pmi? pmember) (subprocess? (pmi-subproc-or-thread pmember))))
(define (pmi-thread? pmember)
(and (pmi? pmember) (thread? (pmi-subproc-or-thread pmember))))
(define pipeline-length (length pipeline-member-specs))
(define-values (r1-members-rev err-port-copy-threads-rev)
(for/fold ([m-outs '()]
[err-port-copy-threads '()])
([m pipeline-member-specs]
[i (in-range pipeline-length)])
(cond
;; leave thread starting to round 2
[(pm-spec-func? m) (values (cons m m-outs) (cons #f err-port-copy-threads))]
[else
(let* ([to-spec (cond [(null? m-outs)
to-line-port]
[(pmi-process? (car m-outs))
(pmi-port-from (car m-outs))]
[else #f])]
[from-spec (if (equal? i (sub1 pipeline-length))
from-line-port
#f)]
[err-spec (pipeline-member-spec-port-err m)]
[err-to-send (if (and (port? err-spec)
(not (file-stream-port? err-spec)))
#f
err-spec)]
[capture-err (if (and (output-port? err-spec)
(string-port? err-spec))
err-spec
#f)]
[argl (pipeline-member-spec-argl m)]
[success-pred* (pipeline-member-spec-success-pred m)]
[success-pred (cond [(list? success-pred*)
(λ (v) (or (equal? 0 v)
(member v success-pred*)))]
[(procedure? success-pred*) success-pred*]
[else #f])])
(let-values ([(sproc from to err-from)
(subprocess+ argl
#:err err-to-send
#:in to-spec
#:out from-spec)])
(when (and to-spec (> i 0)) (close-input-port to-spec))
(let ([out-member (pmi to from err-from sproc #f #f argl
capture-err success-pred)])
(values
(cons out-member m-outs)
(cons (if (and err-spec err-from)
(thread (λ ()
(with-handlers ([(λ (e) #t) (λ (e) (void))])
(copy-port err-from err-spec))
(close-input-port err-from)))
#f)
err-port-copy-threads)))))])))
(define r1-members (reverse r1-members-rev))
(define err-port-copy-threads (reverse err-port-copy-threads-rev))
(define (run-func-members members)
(for/fold ([m-outs '()])
([m members]
[i (in-range pipeline-length)])
(cond
[(pm-spec-func? m)
(let* ([prev (and (not (null? m-outs))
(car m-outs))]
[next (and (< i (sub1 pipeline-length))
(list-ref r1-members (add1 i)))]
[next-is-running? (and next (pmi? next))]
[prev-is-running? (and prev (pmi? prev))]
[err-spec (pipeline-member-spec-port-err m)]
[ret-box (box #f)]
[err-box (box #f)]
[capture-err (and (output-port? err-spec)
(string-port? err-spec)
err-spec)]
[success-pred* (pipeline-member-spec-success-pred m)]
[success-pred (cond [(list? success-pred*)
(λ (v) (member v success-pred*))]
[(procedure? success-pred*) success-pred*]
[else #f])]
[argl (pipeline-member-spec-argl m)])
(let-values ([(to-use to-ret)
(cond
[prev-is-running? (values (pmi-port-from prev) #f)]
[prev (make-pipe)]
[(and (not prev) (not to-line-port)) (make-pipe)]
[else (values (dup-input-port to-line-port) #f)])]
[(from-ret from-use)
(cond
[next-is-running? (values #f (pmi-port-to next))]
[next (make-pipe)]
[(not from-line-port) (make-pipe)]
[else (values #f (dup-output-port from-line-port))])]
[(err-ret err-use)
(cond [(output-port? err-spec)
(values #f (dup-output-port err-spec))]
[(equal? err-spec 'stdout) (values #f err-spec)]
[else (make-pipe)])])
(let* ([ret-thread
(parameterize ([current-input-port to-use]
[current-output-port from-use]
[current-error-port (if (equal? err-use 'stdout)
from-use
err-use)])
(thread (mk-run-thunk m err-box ret-box)))]
[ret-member (pmi to-ret from-ret err-ret
ret-thread ret-box err-box argl
capture-err success-pred)])
(cons ret-member m-outs))))]
[else (cons m m-outs)])))
(define (mk-run-thunk m-spec err-box ret-box)
(λ ()
(with-handlers
([(λ (exn) #t)
(λ (exn)
(set-box! err-box exn)
(eprintf "~a\n" (exn->string exn)))])
(let* ([argl (pipeline-member-spec-argl m-spec)]
[thread-ret (apply (car argl) (cdr argl))])
(set-box! ret-box thread-ret)))
(close-input-port (current-input-port))
(close-output-port (current-output-port))
(close-output-port (current-error-port))))
(define r2-members-rev (run-func-members r1-members))
(define r2-members (reverse r2-members-rev))
(define from-port (pmi-port-from (car r2-members-rev)))
(define to-port (pmi-port-to (car r2-members)))
(define (finalize-member m)
(pipeline-member
(pmi-subproc-or-thread m)
(pmi-port-err m)
(pmi-thread-ret-box m)
(pmi-thread-exn-box m)
(pmi-argl m)
(pmi-capture-port-err m)
(box #f) ; killed-box
(pmi-success-pred m)))
(define out-members (map finalize-member r2-members))
(list out-members to-port from-port err-port-copy-threads))
;;;; Misc funcs ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (shellify f)
(λ args
(let* ([in-str (begin0 (port->string (current-input-port))
(close-input-port (current-input-port)))]
[out-str (apply f in-str args)])
(display out-str)
(flush-output))))
(define (subprocess+ #:in [in #f] #:out [out #f] #:err [err #f] argv)
(when (null? argv)
(error 'subprocess+ "empty argv"))
(define cmd (car argv))
(define args (cdr argv))
(define cmdpath (resolve-command-path cmd))
(when (not cmdpath) (error 'subprocess+ "Command `~a` not in path." cmd))
(apply subprocess
(append (list out
in
err
cmdpath)
(map ~a args))))
;;;; and/or macros ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-simple-macro (and/success e ...)
(and (let ([tmp e]) (if (pipeline? tmp) (and (pipeline-success? tmp) tmp) tmp)) ...))
(define-simple-macro (or/success e ...)
(or (let ([tmp e]) (if (pipeline? tmp) (and (pipeline-success? tmp) tmp) tmp)) ...))
| false |
37ef7638161d0eef698c4ee82ad1b855eb8d0c42 | d2fc383d46303bc47223f4e4d59ed925e9b446ce | /courses/2010/fall/330/notes/1-25.rkt | faf04786a332a6a25a74dd841578401267fa8015 | []
| no_license | jeapostrophe/jeapostrophe.github.com | ce0507abc0bf3de1c513955f234e8f39b60e4d05 | 48ae350248f33f6ce27be3ce24473e2bd225f6b5 | refs/heads/master | 2022-09-29T07:38:27.529951 | 2022-09-22T10:12:04 | 2022-09-22T10:12:04 | 3,734,650 | 14 | 5 | null | 2022-03-25T14:33:29 | 2012-03-16T01:13:09 | HTML | UTF-8 | Racket | false | false | 5,142 | rkt | 1-25.rkt | #lang racket
;; The library ....
(define (show fmt a)
(printf fmt a)
(eprintf "HTTP Connection closed!"))
(define (prompt p)
(display p) (read))
(define resumer (box #f))
(define (prompt-with-stuff-after p after-fun)
(display p)
(set-box! resumer after-fun)
(eprintf "HTTP Connection closed!"))
(define (resume ans)
((unbox resumer) ans))
;; Our CPS'd program
#|
(define (where-we-start)
(prompt-with-stuff-after
"How many numbers?"
(λ (how-many)
(get-n-numbers-and-add-them/k
how-many
show-the-sum))))
; It would really be...
#;(foldr + 0
(build-list how-many
(λ (i) (prompt "Number:"))))
; in direct style
; But this is it in CPS (continuation passing style)
(define (foldr/k cons empty l k)
(if (empty? l)
(k empty)
(foldr/k cons empty (rest l)
(λ (rest)
(k (cons (first l)
rest))))))
(define (build-list/k n f/k k)
(if (zero? n)
(k empty)
(f/k n
(λ (nth-entry)
(build-list/k (sub1 n) f/k
(λ (other-entries)
(k (cons nth-entry
other-entries))))))))
(define (get-n-numbers-and-add-them/k n k)
(build-list/k n
(λ (i k)
(prompt-with-stuff-after "Number:" k))
(λ (l)
(foldr/k + 0 l k))))
(define (show-the-sum the-sum)
(show "The sum of your numbers is ~a."
the-sum))
|#
;; CPSing
(require (for-syntax syntax/parse))
(define-syntax (cps stx)
(syntax-parse
stx
#:literals (if λ prompt let zero? empty? first rest sub1 + cons show)
[(cps (let ([x e]) body))
(syntax (cps ((λ (x) body) e)))]
[(cps x:id) (syntax (λ (k) (k x)))]
[(cps x:number) (syntax (λ (k) (k x)))]
[(cps x:str) (syntax (λ (k) (k x)))]
[(cps (if e0 e1 e2))
(syntax
(λ (k)
((cps e0)
(λ (v0)
(if v0
((cps e1) k)
((cps e2) k))))))]
[(cps (λ (x ...) e))
(syntax
(λ (k-at-defn)
(k-at-defn
(λ (x ... k-at-call)
((cps e) k-at-call)))))]
[(cps (prompt str))
(syntax
(λ (k)
(prompt-with-stuff-after str k)))]
; We need to put in the transformations of calls to every primitive function
[(cps (zero? e))
(syntax (λ (k) ((cps e) (λ (v) (k (zero? v))))))]
[(cps (empty? e))
(syntax (λ (k) ((cps e) (λ (v) (k (empty? v))))))]
[(cps (first e))
(syntax (λ (k) ((cps e) (λ (v) (k (first v))))))]
[(cps (rest e))
(syntax (λ (k) ((cps e) (λ (v) (k (rest v))))))]
[(cps (sub1 e))
(syntax (λ (k) ((cps e) (λ (v) (k (sub1 v))))))]
[(cps (+ e0 e1))
(syntax (λ (k) ((cps e0) (λ (v0)
((cps e1) (λ (v1)
(k (+ v0 v1))))))))]
[(cps (cons e0 e1))
(syntax (λ (k) ((cps e0) (λ (v0)
((cps e1) (λ (v1)
(k (cons v0 v1))))))))]
[(cps (show e0 e1))
(syntax (λ (k) ((cps e0) (λ (v0)
((cps e1) (λ (v1)
(k (show v0 v1))))))))]
; Before handling other function calls
[(cps (f))
(syntax
(λ (k)
((cps f)
(λ (f/k)
(f/k k)))))]
[(cps (f e))
(syntax
(λ (k) ; e could be (prompt "Which number?")
((cps f)
(λ (f/k)
((cps e)
(λ (v)
(f/k v k)))))))]
[(cps (f e0 e1))
(syntax
(λ (k) ; e could be (prompt "Which number?")
((cps f)
(λ (f/k)
((cps e0)
(λ (v0)
((cps e1)
(λ (v1)
(f/k v0 v1 k)))))))))]
[(cps (f e0 e1 e2))
(syntax
(λ (k) ; e could be (prompt "Which number?")
((cps f)
(λ (f/k)
((cps e0)
(λ (v0)
((cps e1)
(λ (v1)
((cps e2)
(λ (v2)
(f/k v0 v1 v2 k)))))))))))]))
(define-syntax-rule
(cps-define (fun-name x ...)
e)
(define fun-name
((cps (λ (x ...) e)) (λ (c) c))))
(define-syntax-rule (cps-run e)
((cps e) (λ (x) x)))
;; Our original program
(cps-define (foldr cons-f empty-v l)
(if (empty? l)
empty-v
(cons-f (first l) (foldr cons-f empty-v (rest l)))))
(cps-define (build-list n f)
(if (zero? n)
empty
(cons (f n) (build-list (sub1 n) f))))
(cps-define (where-we-start)
(let ([how-many (prompt "How many numbers?")])
(show "The sum of your numbers is ~a."
(foldr ; We can't pass primitives as if they are values, because
; they won't be cps'd
(λ (a b) (+ a b)) 0
(build-list how-many
(λ (i) (prompt "Number:")))))))
(cps-run (where-we-start)) | true |
9776d0170628b25d2a8a8430693969ef25a036ba | 7b8ebebffd08d2a7b536560a21d62cb05d47be52 | /doc/eng/types-contracts.scrbl | b0876fe8edf2f85edbeda2ad02fa28d2b1285803 | []
| no_license | samth/formica | 2055045a3b36911d58f49553d39e441a9411c5aa | b4410b4b6da63ecb15b4c25080951a7ba4d90d2c | refs/heads/master | 2022-06-05T09:41:20.344352 | 2013-02-18T23:44:00 | 2013-02-18T23:44:00 | 107,824,463 | 0 | 0 | null | 2017-10-21T23:52:59 | 2017-10-21T23:52:58 | null | UTF-8 | Racket | false | false | 2,450 | scrbl | types-contracts.scrbl | #lang scribble/doc
@(require (for-label formica))
@(require
scribble/manual
scribble/eval)
@(define formica-eval
(let ([sandbox (make-base-eval)])
(sandbox '(require formica))
sandbox))
@title[#:tag "types:contracts"]{Contracts}
All types are defined by @emph{contracts}.
A role of a contract could play
@itemize{@item{a constant which belongs to a @tech{primitive type};}
@item{an unary predicate, describing the type;}
@item{a compound contract, constructed by @tech{contract combinators}.}}
@defproc[(Type [v Any]) Bool]
Returns @racket[#t] if @racket[_v] could be used as a contract and @racket[#f] otherwise.
Any constant which belongs to a @tech{primitive type} could be used as a contract, representing a @emph{unit type}:
@interaction[#:eval formica-eval
(is 5 Type)
(is 'abc Type)]
Any predicate could be used as a contract:
@interaction[#:eval formica-eval
(is Num Type)
(is procedure-arity? Type)
(is cons Type)]
Contracts could be constructed using @tech{contract combinators}:
@interaction[#:eval formica-eval
(Type (and/c integer? positive?))
(Type (or/c Num (cons: Num Num)))]
@defform[(is v type-pred) #:contracts ([v Any] [t Type])]
Provides safe type check. Returns @racket[#t] if @racket[_v] belongs to a type, defined by the contract @racket[_t], and @racket[#f] otherwise.
This form differs from direct contract application in following:
@itemize{@item{it allows to consider @tech{primitive types};}
@item{if application of @racket[_t] leads to exception, the @racket[is] form does not stop running the program and returns @racket[#f].}}
@interaction[#:eval formica-eval
(is 'abc Sym)
(is 'abc 'abc)
(is 1.2 odd?)]
Direct application of @racket[odd?] predicate to non-integer value leads to an error:
@interaction[#:eval formica-eval
(odd? 1.2)]
Any value may belong to unlimited number of types.
For example number @racket[5] belongs to:
@itemize{@item{the unit type @racket[5]:
@interaction[#:eval formica-eval (is 5 5)]}
@item{the numeric type:
@interaction[#:eval formica-eval (is 5 Num)]}
@item{the integer number type:
@interaction[#:eval formica-eval (is 5 integer?)]}
@item{the numeric type "odd number":
@interaction[#:eval formica-eval (is 5 odd?)]}
@item{algebraic type:
@interaction[#:eval formica-eval (is 5 (or/c 0 1 2 3 5 8 13))] and so on.}} | false |
c7c65918a9a28b8a36ee0637335d361494558a75 | 7205f4a390bb8d39d5b1d46d65ba2049d6fabf4b | /insert-mathjax.rkt | 2eb11bce1e564c0f627274fa01e5f645beda4c89 | []
| no_license | soegaard/triangle-solver | dc10fd08b06eb5e93922719607aa9e75b2ca7f90 | 85e57b5e6bb50500f4751d2ab0e7a82753ddceaa | refs/heads/master | 2019-01-02T02:35:29.893223 | 2012-07-19T15:49:56 | 2012-07-19T15:49:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,510 | rkt | insert-mathjax.rkt | #lang racket
;;;
;;; After running Whalesong on triangle-solver.rkt
;;; the resulting HTML file contains no code to
;;; run MathJax. This small script injects the
;;; piece of JavaScript in the header.
;;;
;;; The script is called from build.sh.
(define build-dir "build")
(define html-filename "triangle-solver.html")
(define tmp-filename (string-append html-filename ".tmp"))
(define html-path (build-path build-dir html-filename))
(define tmp-path (build-path build-dir tmp-filename))
;(define mathjax-script-path (build-path "mathjax-script.js"))
(define mathjax-script-path (build-path "mathjax-cdn.js"))
(define raphael-script-path (build-path "raphael-min.js"))
(define (is-title-line? line)
(regexp-match #rx".*<title>.*" line))
(define (copy-until-title-line)
(for/or ([line (in-lines)])
(displayln line)
(is-title-line? line)))
(define (insert-mathjax-script)
(with-input-from-file mathjax-script-path
(λ ()
(for ([line (in-lines)])
(displayln line)))))
(define (insert-raphael-script)
(with-input-from-file raphael-script-path
(λ ()
(for ([line (in-lines)])
(displayln line)))))
(define (copy-until-eof)
(for ([line (in-lines)])
(displayln line)))
(with-input-from-file html-path
(λ ()
(with-output-to-file tmp-path
(λ ()
(copy-until-title-line)
(insert-mathjax-script)
(insert-raphael-script)
(copy-until-eof))
#:exists 'replace)))
| false |
05146f9fd8934b5b35d73f388522b2fd3f1eb311 | 93b116bdabc5b7281c1f7bec8bbba6372310633c | /plt/tyscheme/codes/ch16/hello | 4e98385bbe6d9646ab0f846655be20c4b01ecb0b | []
| no_license | bianyali/BookList | ac84aa5931ced43f99269f881e009644ce68bb49 | ef64c71ac5da235bfab98336e2deb049e8c35b67 | refs/heads/master | 2021-01-17T10:13:20.341278 | 2015-12-29T04:45:53 | 2015-12-29T04:45:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 105 | hello | #! /usr/local/bin/racket
#lang racket
;":"; exec racket -r $0 "$@"
(display "Hello, World!")
(newline)
| false |
|
0bda379258e0b6f454b2833225064ef96e72e3d9 | 3cd9f62570c48fc4c79858bf4e2c058c4aa39248 | /plastic-exhaust.rkt | 47df7977ea3b637945defc38e41ce794ade7d70b | []
| no_license | disconcision/ductile | 34ea52ed7d76cd550875d6bc73041f1fcfcf3538 | c17f792bc2dd8be00f186c45d61f8777ae3e4bc8 | refs/heads/master | 2020-03-18T17:03:27.964995 | 2018-06-21T18:15:39 | 2018-06-21T18:15:39 | 135,003,282 | 2 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 7,724 | rkt | plastic-exhaust.rkt | #lang racket
; PATTERN MATCHING EXHAUSTIVENESS CHECKING
; following Maranget from "Warnings for pattern matching"
; first i present a simplified version of Maranget's algorithm
; thereafter follows an incomplete version of his general algo
; some utility functions
(define transpose (curry apply map list))
(define (row M) (curry list-ref M))
(define (col M) (curry list-ref (transpose M)))
#| simplifying assumptions:
0. proceed without types for now
1. all patterns are linear, so we can reduce named
pattern variables to a generic wildcard
2. we will omit or-patterns, and indeed everything
but wildcards, literals, and lists thereof
|#
; exhaustiveness:
; fixed type for now:
(define types #hash((true . Bool)
(false . Bool)
(pair . (Bool Bool → Bool))))
; utility fns:
(define constructor? (curry hash-has-key? types))
(define complete-signature (hash-keys types))
(define (num-args constructor)
(match (hash-ref types constructor)
[(? list? ls) (- (length ls) 2)]
[_ 0]))
(define (complete? signature)
(set=? signature (list->set complete-signature)))
(define (signature-in column)
(for/fold ([old-set (set)])
([pattern column])
(match pattern
[`(,constructor ,_ ...) (set-add old-set constructor)]
[_ old-set])))
; generates the 'Default Matrix' D from a matrix M
(define (D M)
(apply append
(for/list ([row M])
(match row
[`((,(? constructor?) ,rs ...) ,ps ...)
`()]
[`(_ ,ps ...)
`(,ps)]))))
; generates the 'Specialized Matrix' S from a matrix M
(define (S c M)
(apply append
(for/list ([row M])
(match row
[`(_ ,ps ...) ; note this is literal '_
`((,@(make-list (num-args c) '_) ,@ps))]
[`((,(== c) ,rs ...) ,ps ...)
`((,@rs ,@ps))]
[`((,(not (== c)) ,_ ...) ,_ ...)
`()]))))
; returns true iff M is non-exhaustive
(define (NE M)
(match M
[`() #true]
[`(() ..1) #false]
[(app transpose `(,first-col ,_ ...))
(if (complete? (signature-in first-col))
(for/or ([constructor complete-signature])
(NE (S constructor M)))
(NE (D M)))]))
; tests for exhaustiveness:
(require rackunit)
(check-equal? (NE '((_)))
#f)
(check-equal? (NE '((_ _)))
#f)
(define M1 '(( (true) )
( (pair _ _) )))
(check-equal? (D M1) '())
(check-equal? (S 'true M1) '(()))
(check-equal? (S 'pair M1) '((_ _)))
(check-equal? (S 'false M1) '())
(check-equal? (NE M1) #t)
(define M2 '(( (true) )
( (pair (true) _) )
( (pair _ (true)) )
( _ )))
(check-equal? (D M2) '(()))
(check-equal? (S 'true M2) '(() ())) ; DOUBLE CHECK THIS
(check-equal? (S 'pair M2) '(((true) _)
(_ (true))
(_ _)))
(check-equal? (S 'false M2) '(())) ; THIS TOO
(check-equal? (NE M2) #f)
(define M3 '(( (true) )
( (false) )
( (pair _ _) )))
(check-equal? (S 'true M3) '(()))
(check-equal? (S 'pair M3) '((_ _)))
(check-equal? (S 'false M3) '(()))
(check-equal? (NE M3) #f)
(check-equal? (NE '((_)))
#f)
(check-equal? (NE '(((true)
(_))))
#t)
(check-equal? (NE '(((true))))
#t)
(check-equal? (NE '(((true))
((false))))
#t)
(check-equal? (NE '(((true))
((false))
((pair (true) _))))
#t)
(check-equal? (NE '(((true))
((false))
((pair (true) _))
((pair _ (true)))))
#t)
(check-equal? (NE '(((true))
((false))
((pair (true) _))
((pair _ (true)))
(_)))
#f)
; grammar
#; (pattern ((cons pattern pattern)
(just pattern)
void
null))
#; (define constants '(cons just null void))
(define Msample '(( (cons null _) (cons (cons _ _) _) )
( (just null) (cons _ (cons null _)) )
( (cons _ _) (cons null (cons _ _)) )
( null _ )
( void _ )))
; incomplete notes on generalizing the algorithm:
(define/match (instance? pattern value)
[( '_ _ ) #true]
[( (? constructor?) (? constructor?) ) (equal? pattern value)]
[( (? list?) (? list?) ) (and (equal? (length pattern) (length value))
(andmap instance? pattern value))]
[( _ _ ) #false])
(define (M-instance? M v) (ormap (curryr instance? v) M))
(define Msample-transpose (transpose Msample))
(define (dimensions M)
`(,(length M) ,(length (first M))))
#| let M be a match matrix and q a vector of values whose
length is the same as the number of columns of M.
we want U* to satisty:
∃v (and (not (M-instance? M v)) (instance? q v)))
we attempt to implement U* as U
note important invariant:
U is invariant under reordering of rows
this will allow us to usefully decompose M
without worrying about interaction
|#
(define (U M q)
(match* (M q)
[(`() _) #true] ; empty matrix
[(`(() ...) `()) #false] ; matrix of empty rows
[(`((,x ,xs...) ...) `(,q1 ,qs ...))
(match q1
[`(,(? constructor? c) ,rs ...)
(U (S c M) (S c q))]
[`_
(if (complete? (signature-in x))
; actually maybe note that first col of M is x
(ormap (λ (c) (U (S c M) (S c q)))
(signature-in x))
#t)] ; count signature. for exhaustiveness, skip incomp case
)]
))
#|
U lets us define the following:
|#
(define (exhaustive? M)
(not (U M (make-list '_ (length (transpose M))))))
(define (redundant? M row) ; remove row from M first
(not (U M row)))
#| hints for exhaustiveness checking:
0. consider lists of patterns expressed in matrix form
1. notice that pattern variable names don't matter;
they can all be replaced by a generic wildcard
2. notice that changing pattern order doesn't affect exhaustiveness
3. consider the match matrix one column at a time.
4. following on 2, for each constructor, we can form a specialized
version of the original matrix where we eliminate any rows whose
first column begins with any other constructor. now all of these
specialized matrixes have to be exhaustive
5. notice that since each entry in the first col of these
specialized matrices has the same constructor, we can
just eliminate that constructor, and add its arguments
as columns in the specialized matrix.
|#
#| INITIAL NOTES ON EXHAUSTIVENESS
simpler if we have type decs... otherwise we need more logic to determine
which type we're trying to exhaust. for only nullary constructors: begin
with a set of all instances of the type; remove as they are seen, or
until a wildcard is found. if we reach the end of the list and the set
is non-empty, then it's not exhaustive.
for n-ary constructors:
idea 1: recursively fill initial set.
i.e. for n-ary constructors, add all variants to se
problem: recursive types (seems fatal)
the below is exhaustive:
[zero ?]
[(S zero) ?]
[(S (S zero)) ?]
[(S a) ?]
if type is recusive, seems like we'd eventually need a wildcard
non-exhaustive case: (no case for (S (S zero)))
[zero ?]
[(S zero) ?]
[(S (S (S a))) ?]
maybe restrict exhaustiveness check to non-recursive,
non-mututally-recursive types
exhaustiveness refs: TODO
|#
| false |
8feaa929f80cd30ca2fdbcd13b7245d3e52a833b | d755de283154ca271ef6b3b130909c6463f3f553 | /htdp-lib/test-engine/markup-gui.rkt | b234e9a5657194fae93e1da06274a8d66382851b | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Apache-2.0"
]
| permissive | racket/htdp | 2953ec7247b5797a4d4653130c26473525dd0d85 | 73ec2b90055f3ab66d30e54dc3463506b25e50b4 | refs/heads/master | 2023-08-19T08:11:32.889577 | 2023-08-12T15:28:33 | 2023-08-12T15:28:33 | 27,381,208 | 100 | 90 | NOASSERTION | 2023-07-08T02:13:49 | 2014-12-01T13:41:48 | Racket | UTF-8 | Racket | false | false | 7,783 | rkt | markup-gui.rkt | ; Insert markup into text% editors, making links clickable.
#lang racket/base
(require racket/contract)
(provide (contract-out
(insert-markup ((markup? (is-a?/c text%) (or/c #f (is-a?/c text%))) (boolean?) . ->* . any))))
(require (only-in racket/class send make-object is-a? new is-a?/c)
simple-tree-text-markup/data
racket/gui/base
racket/snip
framework)
; src-editor can be #f
(define (insert-srcloc-markup srcloc-markup text src-editor)
(let ((srcloc (srcloc-markup-srcloc srcloc-markup))
(start (send text get-end-position)))
(insert-markup (srcloc-markup-markup srcloc-markup) text src-editor)
(when src-editor
(send text set-clickback
start (send text get-end-position)
(lambda (t s e) (highlight-srcloc srcloc src-editor))
#f #f)
(let ([end (send text get-end-position)])
(when (color-prefs:known-color-scheme-name? 'drracket:read-eval-print-loop:value-color)
(send text change-style
(color-prefs:lookup-in-color-scheme 'drracket:read-eval-print-loop:value-color)
start end #f))
(send text change-style
(make-object style-delta% 'change-underline #t)
start end #f)))))
(define (definitions-tab definitions-text)
(and definitions-text (send definitions-text get-tab)))
(define (definitions-rep definitions-text)
(cond
((definitions-tab definitions-text) =>
(lambda (tab)
(send tab get-ints)))
(else #f)))
(define (highlight-srcloc srcloc src-editor)
(let ((current-rep (definitions-rep src-editor)))
(when (and current-rep src-editor
(is-a? src-editor text:basic<%>))
(send current-rep highlight-errors
(list srcloc) #f)
(let* ([current-tab (definitions-tab src-editor)]
[frame (send current-tab get-frame)])
(unless (send current-tab is-current-tab?)
(let loop ([tabs (send frame get-tabs)] [i 0])
(unless (null? tabs)
(if (eq? (car tabs) current-tab)
(send frame change-to-nth-tab i)
(loop (cdr tabs) (add1 i))))))
(send frame show #t)))))
; It's advisable to (send text set-styles-sticky #f) on text% editors
; that have editor:standard-style-list-mixin.
; Otherwise, framed boxes mess up the formatting.
; inline? means there might be stuff around the insert-markup, so if
; it's #t, we need to use a snip for vertical markup
(define (insert-markup markup text src-editor (inline? #t))
(cond
((string? markup)
(send text insert markup))
((empty-markup? markup) (void))
((horizontal-markup? markup)
(for-each (lambda (markup)
(insert-markup markup text src-editor))
(horizontal-markup-markups markup)))
((vertical-markup? markup)
(define (insert-vertical text)
(for-each/between
(lambda (markup) (insert-markup markup text src-editor #f))
(lambda () (send text insert #\newline))
(vertical-markup-markups markup)))
(if inline?
(send text insert (make-snip insert-vertical))
(insert-vertical text)))
((srcloc-markup? markup)
(insert-srcloc-markup markup text src-editor))
((framed-markup? markup)
(insert-framed (framed-markup-markup markup) text src-editor))
((image-markup? markup)
(let ((data (image-markup-data markup)))
(cond
((is-a? data snip%)
(send text insert data))
((is-a? data bitmap%) ;; works in other places, so include it here too
(send text insert (make-object image-snip% data)))
((record-dc-datum? data)
(cond
((record-dc-datum->bitmap data (record-dc-datum-width data) (record-dc-datum-height markup))
=> (lambda (bitmap)
(send text insert (make-object image-snip% bitmap))))
(else
(insert-markup (image-markup-alt-markup markup) text src-editor))))
(else
(insert-markup (image-markup-alt-markup markup) text src-editor)))))
[(number-markup? markup)
(send text insert
(number-snip:number->string/snip (number-markup-number markup)
#:exact-prefix (number-markup-exact-prefix markup)
#:inexact-prefix (number-markup-inexact-prefix markup)
#:fraction-view (number-markup-fraction-view markup)))]))
(define (for-each/between proc between list)
(let loop ((list list))
(cond
((null? list) (values))
((null? (cdr list))
(proc (car list)))
(else
(proc (car list))
(between)
(loop (cdr list))))))
(define (make-snip insert)
(let* ([text (new framed-text%)]
[snip (new editor-snip% [editor text] [with-border? #f])])
(send text set-styles-sticky #f)
(send snip use-style-background #t)
(insert text)
(send text lock #t)
snip))
(define (record-dc-datum->bitmap datum width height)
(with-handlers ((exn:fail? (lambda (e) #f)))
(let ((proc (recorded-datum->procedure datum))
(bitmap (make-object bitmap% width height)))
(let ((dc (new bitmap-dc% [bitmap bitmap])))
(proc dc)
bitmap))))
(define framed-text%
(text:foreground-color-mixin
(text:wide-snip-mixin
(text:basic-mixin
(editor:standard-style-list-mixin
(editor:basic-mixin
text%))))))
(define (insert-framed markup text src-editor)
(let* ([framed-text (new framed-text%)]
[snip (new editor-snip% [editor framed-text])])
(send text set-styles-sticky #f)
;; seems to prevent number-snip% from setting rogue style
(send framed-text set-styles-fixed #t)
(send snip use-style-background #t)
(insert-markup markup framed-text src-editor #f)
(when (color-prefs:known-color-scheme-name? 'drracket:read-eval-print-loop:value-color)
(send framed-text change-style
(color-prefs:lookup-in-color-scheme 'drracket:read-eval-print-loop:value-color)
0 (send framed-text get-end-position)))
(send framed-text lock #t)
(let ((before (send text get-end-position)))
(send text insert snip)
(when (color-prefs:known-color-scheme-name? 'drracket:read-eval-print-loop:out-color)
(send text change-style
(color-prefs:lookup-in-color-scheme 'drracket:read-eval-print-loop:out-color)
before (send text get-end-position))))))
;; for development
(define (display-markup markup)
(let* ((frame (new frame%
[label "Markup"]
[width 600] [height 400]))
(text (new (editor:standard-style-list-mixin
(text:basic-mixin
(editor:basic-mixin text%)))))
(canvas (new editor-canvas% [parent frame])))
(send text set-styles-sticky #t)
(send canvas set-editor text)
(insert-markup markup text text #f)
(send text lock #t)
(send frame show #t)))
(module+ test
(require rackunit
simple-tree-text-markup/construct)
(define (render-markup-via-text markup)
(let ((text (new text%)))
(insert-markup markup text #f)
(send text get-text 0 'eof #t)))
(check-equal? (render-markup-via-text "foo")
"foo"
"String via text")
(check-equal? (render-markup-via-text (horizontal "foo" (framed-markup "bar") "baz"))
"foobarbaz"
"Framed via text")
(check-equal? (render-markup-via-text (horizontal "foo" (vertical "bar" "baz") "bam"))
"foobar\nbazbam"
"Framed via text"))
| false |
bbeda49263de7cdddf5cd54b61c0a7ebe13845f0 | 812b9887a88088eb7ada037da10911e231722823 | /finite-automata/dfa/tests.rkt | 1b35a70a906d26acd4e16cbb5754e0844f0a735f | [
"Apache-2.0",
"MIT"
]
| permissive | rodrigogribeiro/automata-theory | 46481eb55c33e1ac600d81d34e3549a5ba1f13fe | ecb572fed86b84434bc0c0c82d5aa5fd895e33ff | refs/heads/master | 2023-07-11T03:05:19.310364 | 2021-08-15T22:43:50 | 2021-08-15T22:43:50 | 377,251,293 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 862 | rkt | tests.rkt | #lang racket
(require "core.rkt"
"image-builder.rkt"
"table-minimization.rkt"
"../../utils/dot.rkt")
;; simple example
(define M
(dfa s1 [s3] (s1 : 0 -> s2)
(s2 : 1 -> s2)
(s2 : 0 -> s3)
(s3 : 0 -> s3)
(s3 : 1 -> s2)))
(define even01
(dfa pp
(pp pi)
(pp : 0 -> ip)
(pp : 1 -> pi)
(ip : 0 -> pp)
(ip : 1 -> ii)
(pi : 0 -> ii)
(pi : 1 -> pp)
(ii : 0 -> pi)
(ii : 1 -> ip)))
(define mod6
(dfa st0
(st0)
(st0 : 0 -> st0)
(st0 : 1 -> st1)
(st1 : 0 -> st2)
(st1 : 1 -> st3)
(st2 : 0 -> st4)
(st2 : 1 -> st5)
(st3 : 0 -> st0)
(st3 : 1 -> st1)
(st4 : 0 -> st2)
(st4 : 1 -> st3)
(st5 : 0 -> st4)
(st5 : 1 -> st5)))
| false |
a42ed9642f66bfe9ecedda6a88a4e27b42996b97 | e553691752e4d43e92c0818e2043234e7a61c01b | /sdsl/synthcl/lang/typecheck.rkt | c6b9fdf91c25bc54ff0d85d3ed1e53b5454840e3 | [
"BSD-2-Clause"
]
| permissive | emina/rosette | 2b8c1bcf0bf744ba01ac41049a00b21d1d5d929f | 5dd348906d8bafacef6354c2e5e75a67be0bec66 | refs/heads/master | 2023-08-30T20:16:51.221490 | 2023-08-11T01:38:48 | 2023-08-11T01:38:48 | 22,478,354 | 656 | 89 | NOASSERTION | 2023-09-14T02:27:51 | 2014-07-31T17:29:18 | Racket | UTF-8 | Racket | false | false | 21,623 | rkt | typecheck.rkt | #lang rosette
(require (for-template (only-in "forms.rkt" app-or-ref)
(only-in racket quote #%app #%datum)
"types.rkt")
syntax/stx syntax/id-table
(prefix-in rosette/ (only-in rosette = <= >= ))
"env.rkt" "util.rkt" "errors.rkt" "types.rkt"
"operators.rkt" "forms.rkt" "queries.rkt")
(provide typecheck typecheck-module)
; This module implements a simple typechecker for programs
; in the OpenCL DSL. The typecheck works directly on the
; syntax object representation of a program. The typechecker
; takes as input a program fragment and returns a copy of the
; fragment with all of its subforms nnotated with their types.
; The types can be retrieved from a typecheck expression using
; the type-ref function.
; Typechecks the contents of a module, and returns two values:
; the typecheck forms (with attached type annotations) and the
; dictionary mapping all module-level identifiers to their types.
(define (typecheck-module forms)
(parameterize ([current-env (env)])
(typecheck-signatures forms)
(values (map typecheck forms) (car (current-env)))))
; Adds the signatures of all procedures and kernels in the given list to
; the current environment.
(define (typecheck-signatures forms)
(for ([stx forms])
(syntax-case stx ()
[(proc out (id [type param] ...) expr ...)
(and (identifier? #'proc)
(or (free-label-identifier=? #'proc #'procedure)
(free-label-identifier=? #'proc #'kernel)
(free-label-identifier=? #'proc #'grammar)))
(let ([out-type (identifier->type #'out stx)]
[arg-types (map (curryr identifier->type stx) (syntax->list #'(type ...)))])
(when (free-label-identifier=? #'proc #'kernel)
(check-no-conversion out-type void stx #'out))
(bind #'id (function-type arg-types out-type) stx))]
[_ #f])))
; Typechecks the given program fragment in the current environment
; and returns the result.
(define (typecheck stx)
(or (and (type-ref stx) stx)
(cond [(identifier? stx) (lookup stx)]
[(not (stx-list? stx)) (typecheck-datum stx)]
[else (typecheck-form stx)])))
; Typechecks a datum.
(define (typecheck-datum stx)
(let* ([v (syntax->datum stx)]
[t (or (real-type-of v) (and (string? v) char*))])
(unless t (raise-syntax-error #f "unrecognized literal value" stx))
(type-set stx t)))
; Typechecks a declaration of one or more variables.
(define (typecheck-declaration stx)
(syntax-case stx ()
[(: type[len] x y ...)
(and (identifier? #':) (equal? (syntax->datum #':) ':))
(let* ([vars (syntax->list #'(x y ...))]
[t (identifier->type #'type stx)]
[t (if (real-type? t)
(base->pointer-type t)
(raise-bad-type-error "real type" t stx #'type))]
[sz (typecheck #'len)])
(check-no-conversion (type-ref sz) int stx #'len)
(for ([var vars])
(unless (program-identifier? var)
(raise-syntax-error #f "not a valid identifier" stx var))
(bind var t stx))
(type-set
(quasisyntax/loc stx (: type[#,sz] #,@(map lookup vars)))
void))]
[(: type x y ...)
(and (identifier? #':) (equal? (syntax->datum #':) ':))
(let ([vars (syntax->list #'(x y ...))]
[t (identifier->type #'type stx)])
(when (equal? t void)
(raise-syntax-error #f "not a valid type" stx #'type))
(for ([var vars])
(unless (program-identifier? var)
(raise-syntax-error #f "not a valid identifier" stx var))
(bind var t stx))
(type-set
(quasisyntax/loc stx (: type #,@(map lookup vars)))
void))]
[_ (raise-bad-form-error "(: type [len] x y ...) or (: type x y ...)" stx)]))
(define (program-identifier? id)
(and (identifier? id)
(regexp-match? #px"^[a-zA-Z_]\\w*$" (symbol->string (syntax->datum id)))))
; Typechecks an assertion.
(define (typecheck-assertion stx)
(syntax-case stx ()
[(assert val)
(let ([typed-val (typecheck #'val)])
(check-implicit-conversion (type-ref typed-val) bool stx)
(type-set (quasisyntax/loc stx (assert #,typed-val)) void))]
[_ (raise-bad-form-error "(assert boolExpr)" stx)]))
; Typechecks an assignment operation (see Ch. 6.3.o of opencl-1.2 specification).
(define (typecheck-assignment stx)
(syntax-case stx ()
[(op lval expr)
(identifier? #'lval)
(let ([tl (typecheck #'lval)]
[te (typecheck #'expr)])
(check-implicit-conversion (type-ref te) (type-ref tl) stx)
(type-set (quasisyntax/loc stx (op #,tl #,te)) void))]
[(op [loc sel] expr)
(let* ([tl (typecheck #'loc)]
[t (type-ref tl)])
(cond
[(or (equal? t cl_mem) (equal? t void*))
(raise-syntax-error #f "cannot dereference a void* pointer" stx #'loc)]
[(pointer-type? t)
(let ([idx (typecheck #'sel)]
[te (typecheck #'expr)])
(check-no-conversion (type-ref idx) int stx #'sel)
(check-implicit-conversion (type-ref te) (type-base t) stx #'expr)
(type-set (quasisyntax/loc stx (op [#,tl #,idx] #,te)) void))]
[(vector-type? t)
(unless (identifier? #'loc) (raise-syntax-error #f "not an lvalue" stx #'loc))
(let* ([selector (parse-selector #f #'sel stx)]
[te (typecheck #'expr)]
[xt (type-ref te)])
(check-selector selector t stx #'sel)
(unless (and (real-type? xt)
(eq? (length selector) (real-type-length xt))
(if (scalar-type? xt)
(equal? xt (type-base t))
(equal? (type-base xt) (type-base t))))
(raise-bad-type-error (base->real-type (type-base t) (length selector)) xt stx #'expr))
(type-set (quasisyntax/loc stx (op [#,tl '#,selector] #,te)) void))]
[else (raise-bad-type-error "vector or pointer" t stx #'loc)]))]
[_ (raise-bad-form-error (format "(~a lvalue expr)" (syntax->datum #'op)) stx)]))
; Typechecks an application or a reference operation
(define (typecheck-app-or-ref stx)
(syntax-case stx ()
[(proc arg ...)
(let* ([args (syntax->list #'(arg ...))]
[typed-proc (typecheck #'proc)]
[t (type-ref typed-proc)])
(cond
[(function-type? t)
(let ([typed-args (check-function-args t args stx)])
(type-set
(quasisyntax/loc stx (#,typed-proc #,@typed-args));(app-or-ref #,typed-proc #,@typed-args))
(function-type-result t)))]
[(or (equal? t cl_mem) (or (equal? t void*)))
(raise-syntax-error #f "cannot dereference a void* pointer" stx #'proc)]
[(and (pointer-type? t) (rosette/= 1 (length args)))
(let ([typed-arg (typecheck (car args))])
(check-no-conversion (type-ref typed-arg) int stx (car args))
(type-set (quasisyntax/loc stx (app-or-ref #,typed-proc #,typed-arg)) (type-base t)))]
[(and (vector-type? t) (rosette/= 1 (length args)))
(let ([selector (parse-selector #t (car args) stx)])
(check-selector selector t stx (car args))
(type-set
(quasisyntax/loc stx (app-or-ref #,typed-proc '#,selector))
(base->real-type (type-base t) (length selector))))]
[else
(raise-bad-form-error "procedure application, or vector/pointer access" stx)]))]))
(define (check-function-args t args stx)
(let* ([arg-types (function-type-args t)]
[arg-types (if (list? arg-types) arg-types (make-list (length args) arg-types))])
(unless (rosette/= (length arg-types) (length args))
(raise-bad-form-error (format "~a arguments" (length arg-types)) stx))
(for/list ([arg-type arg-types] [arg (map typecheck args)])
(check-implicit-conversion (type-ref arg) arg-type stx arg)
arg)))
; Typechecks the locally-scoped form.
(define (typecheck-locally-scoped stx)
(syntax-case stx ()
[(locally-scoped) (type-set stx void)]
[(locally-scoped form ...)
(let* ([typed-forms (parameterize ([current-env (env)])
(map typecheck (syntax->list #'(form ...))))]
[t (type-ref (last typed-forms))])
(type-set (quasisyntax/loc stx (locally-scoped #,@typed-forms)) t))]))
; Typechecks a query declaration, which is either a range declaration
; or a regular one-variable declaration.
(define (typecheck-query-declaration stx)
(syntax-case stx ()
[(: type [expr] var) (typecheck-declaration stx)]
[(: type var) (typecheck-declaration stx)]
[(: type var in (expr ...)) (typecheck-range-declaration stx)]
[_ (raise-bad-form-error "(: type[expr] var) or (: int var in (range [start] end [step])" stx)]))
; Typechecks the verify or synthesis query statement.
(define (typecheck-query stx)
(syntax-case stx ()
[(query #:forall [decl ...] #:bitwidth bw #:grammar-depth depth #:ensure form)
(parameterize ([current-env (env)])
(with-syntax ([(typed-decl ...) (map typecheck-query-declaration (syntax->list #'(decl ...)))]
[typed-form (typecheck #'form)]
[typed-bw (typecheck #'bw)]
[typed-depth (typecheck #'depth)])
(check-no-conversion (type-ref #'typed-bw) int #'typed-bw stx)
(check-no-conversion (type-ref #'typed-depth) int #'typed-depth stx)
(type-set (syntax/loc stx (query #:forall [typed-decl ...]
#:bitwidth typed-bw
#:grammar-depth typed-depth
#:ensure typed-form))
void)))]
[(query #:forall [decl ...] #:bitwidth bw #:ensure form)
(parameterize ([current-env (env)])
(with-syntax ([(typed-decl ...) (map typecheck-query-declaration (syntax->list #'(decl ...)))]
[typed-form (typecheck #'form)]
[typed-bw (typecheck #'bw)])
(check-no-conversion (type-ref #'typed-bw) int #'typed-bw stx)
(type-set (syntax/loc stx (query #:forall [typed-decl ...]
#:bitwidth typed-bw
#:ensure typed-form))
void)))]
[(query #:forall [decl ...] #:ensure form)
(parameterize ([current-env (env)])
(with-syntax ([(typed-decl ...) (map typecheck-query-declaration (syntax->list #'(decl ...)))]
[typed-form (typecheck #'form)])
(type-set (syntax/loc stx (query #:forall [typed-decl ...] #:ensure typed-form)) void)))]
[_ (raise-bad-form-error
(format "(~a #:forall [(: type id ...+) ...+] form)" (syntax->datum #'query))
stx)]))
; Typechecks the print statement.
(define (typecheck-print stx)
(syntax-case stx ()
[(print form ...)
(let ([forms (for/list ([f (syntax->list #'(form ...))])
(let ([tf (typecheck f)])
(when (equal? void (type-ref tf))
(raise-bad-type-error "non-void type" void stx f))
tf))])
(type-set (quasisyntax/loc stx (print #,@forms)) void))]))
; Typechecks the if statement.
(define (typecheck-if-statement stx)
(syntax-case stx ()
[(if test { then ... } { else ... })
(let ([test-expr (typecheck #'test)]
[then-body (parameterize ([current-env (env)])
(map typecheck (syntax->list #'(then ...))))]
[else-body (parameterize ([current-env (env)])
(map typecheck (syntax->list #'(else ...))))])
(check-implicit-conversion (type-ref test-expr) bool stx #'test)
(type-set
(quasisyntax/loc stx
(if #,test-expr #,then-body #,else-body))
void))]
[(if test { then ... }) (typecheck-if-statement (syntax/loc stx (if test {then ...} {})))]
[_ (raise-bad-form-error "(if test { thenExpr ...}) or (if test { thenExpr ...} { elseExpr ...})" stx)]))
; Typechecks the range declaration.
(define (typecheck-range-declaration stx)
(syntax-case stx ()
[(: type var in (range arg ...))
(and (identifier? #':) (equal? (syntax->datum #':) ':)
(type-identifier? #'type) (equal? (identifier->type #'type stx) int)
(identifier? #'in) (equal? (syntax->datum #'in) 'in)
(identifier? #'range) (equal? (syntax->datum #'range) 'range)
(let ([len (length (syntax->list #'(arg ...)))])
(and (rosette/<= 1 len) (rosette/<= len 3))))
(let ([args (map typecheck (syntax->list #'(arg ...)))])
(for ([a args])
(check-no-conversion (type-ref a) int a stx))
(bind #'var int stx)
(type-set (quasisyntax/loc stx (: type #,(lookup #'var) in (range #,@args))) int))]
[_ (raise-bad-form-error "(: int var in (range [start] end [step]))" stx)]))
; Typechecks the for statement.
(define (typecheck-for-statement stx)
(syntax-case stx ()
[(for [decls ...] expr ...)
(parameterize ([current-env (env)])
(let* ([ds (map typecheck-range-declaration (syntax->list #'(decls ...)))]
[body (map typecheck (syntax->list #'(expr ...)))])
(type-set
(quasisyntax/loc stx
(for [#,@ds] #,@body))
void)))]
[_ (raise-bad-form-error "(for [(: int var in rangeExpr) ...] expr ...)" stx)]))
; Typechecks the sizeof expression.
(define (typecheck-sizeof stx)
(syntax-case stx ()
[(sizeof type)
(let ([t (identifier->type #'type stx)])
(unless (real-type? t)
(raise-bad-type-error "real type" t stx #'type))
(type-set stx int))]
[_ (raise-bad-form-error "(sizeof realType)" stx)]))
; Typechecks the addressof expression.
(define (typecheck-addressof stx)
(syntax-case stx ()
[(@ val)
(identifier? #'val)
(let* ([v (typecheck #'val)]
[t (type-ref v)])
(unless (real-type? t)
(raise-bad-type-error "real lvalue" t stx #'val))
(type-set (quasisyntax/loc stx (@ #,v)) (base->pointer-type t)))]
[_ (raise-bad-form-error "(@ identifier)" stx)]))
; Typechecks a procedure or kernel.
(define (typecheck-procedure stx)
(syntax-case stx ()
[(proc out (id [type param] ...) expr ...)
(parameterize ([current-env (env)])
(for-each typecheck (syntax->list #`([: type param] ...)))
(let ([out-type (function-type-result (type-ref (typecheck #'id)))]
[exprs (map typecheck (syntax->list #'(expr ...)))])
(if (null? exprs)
(check-no-conversion out-type void stx)
(unless (equal? out-type void)
(check-no-conversion (type-ref (last exprs)) out-type stx (last exprs))))
(type-set
(quasisyntax/loc stx
(proc out (id [type param] ...) #,@exprs))
void)))]
[_ (raise-bad-form-error (format "(~a type (id [type id] ...) expr ...)" (syntax->datum stx)) stx)]))
; Typechecks a grammar declaration.
(define (typecheck-grammar stx)
(syntax-case stx ()
[(grammar out (id [type param] ...) expr)
(parameterize ([current-env (env)])
(for-each typecheck (syntax->list #`([: type param] ...)))
(let ([out-type (function-type-result (type-ref (typecheck #'id)))]
[texpr (typecheck #'expr)])
(unless (equal? out-type void)
(check-no-conversion (type-ref texpr) out-type stx texpr))
(type-set
(quasisyntax/loc stx
(grammar out (id [type param] ...) #,texpr))
void)))]
[_ (raise-bad-form-error (format "(~a type (id [type id] ...) expr ...)" (syntax->datum stx)) stx)]))
; Typechecks the ternary selection operator.
(define (typecheck-selection stx)
(syntax-case stx ()
[(?: a b c)
(let* ([ta (typecheck #'a)]
[t0 (type-ref ta)]
[tb (typecheck #'b)]
[t1 (type-ref tb)]
[tc (typecheck #'c)]
[t2 (type-ref tc)])
(define out
(cond [(scalar-type? t0) (if (equal? t1 t2) t1 (common-real-type t1 t2))]
[(vector-type? t0) (common-real-type t0 t1 t2)]
[else (raise-syntax-error #f "not a real type" stx #'a)]))
(unless out (raise-no-common-type-error stx))
(type-set (quasisyntax/loc stx (?: #,ta #,tb #,tc)) out))]
[_ (raise-operator-arity-error "3" stx)]))
; Typechecks operators that accept operands with a common real type and
; produce that type as the output.
(define (typecheck-real-operator stx)
(syntax-case stx ()
[(op arg ...)
(let ([args (map typecheck (syntax->list #'(arg ...)))])
(define crt (apply common-real-type (map type-ref args)))
(unless crt (raise-no-common-type-error stx))
(type-set (quasisyntax/loc stx (op #,@args)) crt))]))
; Typechecks operators that accept operands with a common integer type and
; produce that type as the output.
(define (typecheck-int-operator stx)
(syntax-case stx ()
[(op arg ...)
(let ([args (map typecheck (syntax->list #'(arg ...)))])
(define crt (apply common-real-type (map type-ref args)))
(unless (and crt (or (equal? crt int) (equal? (type-base crt) int)))
(raise-no-common-type-error stx "integer"))
(type-set (quasisyntax/loc stx (op #,@args)) crt))]))
; Typechecks operators that accept bool operands and produce a bool output.
(define (typecheck-bool-operator stx)
(syntax-case stx ()
[(op arg ...)
(let ([args (map typecheck (syntax->list #'(arg ...)))])
(for ([a args])
(check-implicit-conversion (type-ref a) bool stx))
(type-set (quasisyntax/loc stx (op #,@args)) bool))]))
; Typechecks operators that accept operands with a common real type and
; produce an int type as the output.
(define (typecheck-comparison-operator stx)
(syntax-case stx ()
[(op arg ...)
(let ([args (map typecheck (syntax->list #'(arg ...)))])
(define crt (apply common-real-type (map type-ref args)))
(unless crt (raise-no-common-type-error stx))
(type-set (quasisyntax/loc stx (op #,@args))
(base->real-type int (real-type-length crt))))]))
; Typechecks a cast.
(define (typecheck-cast stx)
(syntax-case stx ()
[((type) val)
(let ([t (identifier->type #'type stx)]
[v (typecheck #'val)])
(check-implicit-conversion (type-ref v) t stx)
(type-set (quasisyntax/loc stx ((type) #,v)) t))]
[_ (raise-bad-form-error "((type) expr)" stx)]))
; Typechecks the choose expression.
(define (typecheck-choose stx)
(syntax-case stx ()
[(choose expr rest ...)
(let* ([x (typecheck #'expr)]
[t (type-ref x)]
[xs (map typecheck (syntax->list #'(rest ...)))])
(unless (andmap (compose1 (curry equal? t) type-ref) xs)
(raise-bad-type-error "choices of the same type" (cons t (map type-ref xs)) stx))
(type-set (quasisyntax/loc stx (choose #,x #,@xs)) t))]
[_ (raise-bad-form-error "(choose expr ...+)" stx)]))
; Typechecks the ?? expression.
(define (typecheck-?? stx)
(syntax-case stx ()
[(?? type)
(type-identifier? #'type)
(let ([t (identifier->type #'type stx)])
(unless (scalar-type? t)
(raise-bad-type-error "scalar type" t stx))
(type-set stx t))]
[_ (raise-bad-form-error "(?? scalarType)" stx)]))
; Typechecks a form that is not a datum or an identifier.
(define typecheck-form
(let* ([procs (make-free-id-table #:phase 10)])
(dict-set! procs #'assert typecheck-assertion)
(dict-set! procs #'verify typecheck-query)
(dict-set! procs #'synth typecheck-query)
(dict-set! procs #'choose typecheck-choose)
(dict-set! procs #'?? typecheck-??)
(dict-set! procs #'grammar typecheck-grammar)
(dict-set! procs #'procedure typecheck-procedure)
(dict-set! procs #'kernel typecheck-procedure)
(dict-set! procs #': typecheck-declaration)
(dict-set! procs #'sizeof typecheck-sizeof)
(dict-set! procs #'@ typecheck-addressof)
(dict-set! procs #'= typecheck-assignment)
(dict-set! procs #'if typecheck-if-statement)
(dict-set! procs #'for typecheck-for-statement)
(dict-set! procs #'locally-scoped typecheck-locally-scoped)
(dict-set! procs #'print typecheck-print)
(dict-set! procs #'?: typecheck-selection)
(for ([op real-operators]) (dict-set! procs op typecheck-real-operator))
(for ([op int-operators]) (dict-set! procs op typecheck-int-operator))
(for ([op bool-operators]) (dict-set! procs op typecheck-bool-operator))
(for ([op comparison-operators]) (dict-set! procs op typecheck-comparison-operator))
(lambda (stx)
(syntax-case stx ()
[((tag) _ ...) (type-identifier? #'tag)
(typecheck-cast stx)]
[(tag _ ...) (and (identifier? #'tag) (dict-has-key? procs #'tag))
((dict-ref procs #'tag) stx)]
[(_ _ ...) (typecheck-app-or-ref stx)]))))
| false |
ed490fbb40e2343547ca9974562269645ee97dd3 | 2f17124e3438460e41d3f6242b2bf047ed80fbee | /lab3/aufgabe3.12.rkt | 12dd95fdc8468e8ea64be8d58e689c00ab07a2a3 | []
| no_license | truenicfel/scheme | e5b2dbd532038c45eba464c35c33c0d4f06efe55 | babbf5d895c0817b180fb2da3c8ce0d46434cda9 | refs/heads/master | 2020-03-23T07:29:56.483376 | 2018-07-29T11:08:15 | 2018-07-29T11:08:15 | 141,275,259 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 274 | rkt | aufgabe3.12.rkt | ;;; Aufgabe 12 ;;;
(define (double f)
; return a function, that executes f twice
(lambda (n) (f (f n)))
)
; square function (for testing)
(define (square n) (* n n))
; tests
(square 1)
((double square) 1)
(square 2)
((double square) 2)
(square 3)
((double square) 3) | false |
a6e441a0e4893c571671b6036f64e8baac2b085d | c161c2096ff80424ef06d144dacdb0fc23e25635 | /chapter4/exercise/ex4.5.rkt | 747fea01f84ec28cb1dba69a5c13253197ceff20 | []
| no_license | tangshipoetry/SICP | f674e4be44dfe905da4a8fc938b0f0460e061dc8 | fae33da93746c3f1fc92e4d22ccbc1153cce6ac9 | refs/heads/master | 2020-03-10T06:55:29.711600 | 2018-07-16T00:17:08 | 2018-07-16T00:17:08 | 129,242,982 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,105 | rkt | ex4.5.rkt | #lang racket
(define (eval exp env)
(cond ((self-evaluating? exp) exp)
((variable? exp) (lookup-variable-value exp env))
((quoted? exp) (text-of-quotation exp))
((assignment? exp) (eval-assignment exp env))
((definition? exp) (eval-definition exp env))
((if? exp) (eval-if exp env))
((lambda? exp) (make-procedure (lambda-parameters exp)
(lambda-body exp)
env))
((begin? exp)
(eval-sequence (begin-actions exp) env))
((cond? exp) (eval (cond->if exp) env))
((and? exp)(eval-and exp env))
((or? exp) (eval-or exp env))
((application? exp)
(apply (eval (operator exp) env)
(list-of-values (operands exp) env)))
(else
(error "Unknown expression type: EVAL" exp))))
;cond派生
(define (cond? exp) (tagged-list? exp 'cond))
(define (cond-clauses exp) (cdr exp))
(define (cond-else-clause? clause)
(eq? (cond-predicate clause) 'else))
(define (cond-predicate clause) (car clause))
(define (cond-actions clause) (cdr clause))
(define (cond->if exp) (expand-clauses (cond-clauses exp)))
(define (expand-clauses clauses)
(if (null? clauses)
'false ; no else clause
(let ((first (car clauses))
(rest (cdr clauses)))
(if (cond-else-clause? first)
(if (null? rest)
(sequence->exp (cond-actions first))
(error "ELSE clause isn't last: COND->IF"
clauses))
(if(check? first)
(let([proc (caddr first)]
[value (car first)])
(make-if value
(proc value)
(expand-clauses rest)))
(make-if (cond-predicate first)
(sequence->exp (cond-actions first))
(expand-clauses rest)))))))
(define (check? clause)
(eq? => (cadr clause)))
(cond ((assoc 'b '((a 1) (b 2))) => cadr)
(else false))
| false |
495a393842c9c25f0bf5378d977ce9ba9ef1c834 | 359523f5cfd0856e5aef0300276c13ed3944ab32 | /scribblings/bitwise-exact-rational.scrbl | 200d03df29df8dc66141a18cf10b5de27796c121 | [
"MIT"
]
| permissive | AlexKnauth/bitwise-exact-rational | 8f70873c7d93a7ed232377bc9820fa647bbc257f | 22b56c7faae2900b19a6d5dd42de036d42b324bb | refs/heads/main | 2023-06-09T18:09:53.636020 | 2021-06-21T20:01:05 | 2021-06-21T20:01:05 | 379,049,957 | 5 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,459 | scrbl | bitwise-exact-rational.scrbl | #lang scribble/manual
@(require racket/require
scribble/example
(for-label bitwise-exact-rational
(subtract-in typed/racket/base bitwise-exact-rational)))
@title{bitwise-exact-rational}
@author{Alex Knauth}
@defmodule[bitwise-exact-rational]
@(define ev (make-base-eval #:lang 'typed/racket '(require bitwise-exact-rational)))
Bitwise operations treating exact-rational numbers as bit fields.
@defproc[(bitwise-ior [x Exact-Rational] [y Exact-Rational]) Exact-Rational]{
Produces the bitwise "inclusive or" of @racket[x] and
@racket[y] in their fully infinite two's complement
representation.
@examples[
#:eval ev
(bitwise-ior 1 2)
(bitwise-ior -32 1)
(bitwise-ior 9 (+ 5 1/4))
(bitwise-ior 64/127 1024/2047)
]
}
@defproc[(bitwise-and [x Exact-Rational] ...) Exact-Rational]{
Produces the bitwise "and" of the @racket[x]s in their fully
infinite two's complement representation.
@examples[
#:eval ev
(bitwise-and)
(bitwise-and 1 2)
(bitwise-and -32 1)
(bitwise-and (+ 9 3/4) (+ 5 1/4))
(bitwise-and 64/127 1024/2047)
]
}
@defproc[(bitwise-xor [x Exact-Rational] ...) Exact-Rational]{
Produces the bitwise "exclusive or" of the @racket[x]s in
their fully infinite two's complement representation.
@examples[
#:eval ev
(bitwise-xor)
(bitwise-xor 1 2)
(bitwise-xor 1 5)
(bitwise-xor -32 1)
(bitwise-xor -32 -1)
(bitwise-xor 9 (+ 5 1/4))
(bitwise-xor 64/127 1024/2047)
]
}
| false |
3a00c9fe418251dbb05e83cc856e88bc6316d5f8 | 3765a95a286b3a502c8a15c52f5791b3ae46caca | /module-test/zombie-test.rkt | d00a3f46cb2c7ba4266ff33b54b3bbb9cf5eab3a | []
| no_license | oplS17projects/RacketCraft | 89a788718b62e60b1e81dc78fddf6113a2309e16 | 1baec6d4af527efc2c82144e3572246aa27969e5 | refs/heads/master | 2021-01-18T21:07:21.456958 | 2017-05-01T02:06:49 | 2017-05-01T02:06:49 | 87,010,509 | 4 | 2 | null | null | null | null | UTF-8 | Racket | false | false | 3,565 | rkt | zombie-test.rkt | #lang racket/gui
(require sgl/gl)
(require (lib "gl.ss" "sgl")
(lib "gl-vectors.ss" "sgl")
"../gl-frame.rkt"
"../block.rkt"
"../input.rkt"
"../player.rkt"
"../zombie.rkt"
"../world.rkt")
(define-syntax-rule (gl-zombie-shape Vertex-Mode statement ...)
(let () (glBegin Vertex-Mode) statement ... (glEnd)))
(define (resize width height)
(glViewport 0 0 width height))
(define ZOM_SIZE 2)
(define (draw-zombie x y z)
(glClearColor 0.0 0.0 0.0 0.0)
(glEnable GL_DEPTH_TEST)
(glClear GL_COLOR_BUFFER_BIT)
(glClear GL_DEPTH_BUFFER_BIT)
(define getmax (add1 (max x y z)))
(glMatrixMode GL_PROJECTION)
(glLoadIdentity)
(glOrtho (/ (- getmax) 2) getmax (/ (- getmax) 2) getmax (/ (- getmax) 2) getmax)
(glMatrixMode GL_MODELVIEW)
(glLoadIdentity)
(glRotatef -45 1.0 0.0 0.0)
(glRotatef 45 0.0 1.0 0.0)
; random colors until textures are figured out
(define c1 (/ (random 100) 100.0))
(define c2 (/ (random 100) 100.0))
(define c3 (/ (random 100) 100.0))
(define c4 (/ (random 100) 100.0))
(define c5 (/ (random 100) 100.0))
(define c6 (/ (random 100) 100.0))
(gl-zombie-shape GL_QUADS
(glColor3f 0 c1 1)
(glVertex3d x 0.0 z)
(glVertex3d x y z)
(glVertex3d x y 0.0)
(glVertex3d x 0.0 0.0))
(gl-zombie-shape GL_QUADS
(glColor3f 1 c2 0)
(glVertex3d x 0.0 0.0)
(glVertex3d x y 0.0)
(glVertex3d 0.0 y 0.0)
(glVertex3d 0.0 0.0 0.0))
(gl-zombie-shape GL_QUADS
(glColor3f c2 c2 0)
(glVertex3d x y 0.0)
(glVertex3d x y z)
(glVertex3d 0.0 y z)
(glVertex3d 0.0 y 0.0))
(gl-zombie-shape GL_QUADS
(glColor3f 0 0 1)
(glVertex3d (+ x 1) 0.0 (+ z 1))
(glVertex3d (+ x 1) y z)
(glVertex3d (+ x 1) y 0.0)
(glVertex3d (+ x 1) 0.0 0.0))
(gl-zombie-shape GL_QUADS
(glColor3f c5 c1 c2)
(glVertex3d (+ x 1) 0.0 0.0)
(glVertex3d (+ x 1) y 0.0)
(glVertex3d 0.0 y 0.0)
(glVertex3d 0.0 0.0 0.0))
(gl-zombie-shape GL_QUADS
(glColor3f c2 c1 c1)
(glVertex3d (+ x 1) y 0.0)
(glVertex3d (+ x 1) y z)
(glVertex3d 0.0 y z)
(glVertex3d 0.0 y 0.0)))
(define zombie%
(class* canvas% ()
(inherit with-gl-context swap-gl-buffers)
(init-field (x 15) (y 15) (z 15))
(define/override (on-paint)
(with-gl-context
(lambda ()
(draw-zombie x y z)
(swap-gl-buffers))))
(super-instantiate () (style '(gl)))))
(define window (new frame% (label "Zombie") (min-width 800) (min-height 600)))
(define gl (new zombie% (parent window) (x 1) (y 1) (z 1)))
;; un-comment this frame to show custom layout above and comment the rest from below
;; (send window show #t)
; contains camera position / location
(define myPlayer (player))
(define (draw-opengl)
(glClear (+ GL_COLOR_BUFFER_BIT GL_DEPTH_BUFFER_BIT))
(glLoadIdentity)
(glRotated (myPlayer 'xrot) 1 0 0)
(glRotated (myPlayer 'yrot) 0 1 0)
(glRotated (myPlayer 'zrot) 0 0 1)
(glTranslated (myPlayer 'x) (myPlayer 'y) (myPlayer 'z))
(glBegin GL_QUADS)
((make-zombie 0 9 12 9) 'draw)
(glEnd)
)
;; Set the draw function
(set-gl-draw-fn draw-opengl)
(define win (gl-run)) | true |
f6115e9a6bdbac04990cf9cace0d15e656bf0ee8 | 976b1bdccce73f43b59474be8a7a93d18dd55a5d | /day3-crossed_wires-2.rkt | 93d718d9b6322724f6b55c8bb6c376c7abc5d300 | []
| no_license | retzkek/advent-of-code-2019 | 8fd816dbd1039e849377c8cd9f5560c6d800f5fd | 3f8dc174b88994ece3fe519486d918bf4a2a9047 | refs/heads/master | 2023-01-23T17:20:33.227820 | 2020-11-28T02:05:30 | 2020-11-28T02:05:30 | 225,521,322 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 5,070 | rkt | day3-crossed_wires-2.rkt | #lang racket
(require rackunit)
(define (x point) (first point))
(define (y point) (second point))
(define (d point) (third point))
(define (next-point point step)
(let ([dir (substring step 0 1)]
[dist (string->number (substring step 1 (string-length step)))])
(cond
[(equal? dir "R") (list (+ (x point) dist) (y point) (+ (d point) dist))]
[(equal? dir "L") (list (- (x point) dist) (y point) (+ (d point) dist))]
[(equal? dir "U") (list (x point) (+ (y point) dist) (+ (d point) dist))]
[(equal? dir "D") (list (x point) (- (y point) dist) (+ (d point) dist))]
[else point])))
(module+ test
(check-equal? (next-point '(0 0 0) "R10") '(10 0 10))
(check-equal? (next-point '(0 0 0) "L10") '(-10 0 10))
(check-equal? (next-point '(0 0 0) "U10") '(0 10 10))
(check-equal? (next-point '(0 0 0) "D10") '(0 -10 10)))
(define (steps->lines steps [last '(0 0 0)] [lines '()])
(let* ([next (next-point last (first steps))]
[line (list last next)])
(if (eq? (length steps) 1)
(cons line lines)
(steps->lines (rest steps) next (cons line lines)))))
(module+ test
(check-equal? (steps->lines '("R8" "U5" "L5" "D3"))
'(((3 5 18) (3 2 21)) ((8 5 13) (3 5 18)) ((8 0 8) (8 5 13)) ((0 0 0) (8 0 8)))))
(define (x0 line) (x (first line)))
(define (y0 line) (y (first line)))
(define (d0 line) (d (first line)))
(define (x1 line) (x (second line)))
(define (y1 line) (y (second line)))
(define (d1 line) (d (second line)))
(define (intersection l1 l2)
(cond
[(and (= (x0 l1) (x1 l1)) ; l1 vertical
(= (y0 l2) (y1 l2)) ; l2 horizontal
(or (< (y0 l1) (y0 l2) (y1 l1))
(> (y0 l1) (y0 l2) (y1 l1))) ; l1 span l2?
(or (< (x0 l2) (x0 l1) (x1 l2))
(> (x0 l2) (x0 l1) (x1 l2)))) ; l2 span l1?
(list (x0 l1) (y0 l2)
; add total delay from both lines
(+ (d0 l1)
(if (< (y0 l1) (y0 l2)) (- (y0 l2) (y0 l1)) (- (y0 l1) (y0 l2)))
(d0 l2)
(if (< (x0 l1) (x0 l2)) (- (x0 l2) (x0 l1)) (- (x0 l1) (x0 l2)))))]
[(and (= (y0 l1) (y1 l1)) ; l1 horizontal
(= (x0 l2) (x1 l2)) ; l2 vertical
(or (< (x0 l1) (x0 l2) (x1 l1))
(> (x0 l1) (x0 l2) (x1 l1))) ; l1 span l2?
(or (< (y0 l2) (y0 l1) (y1 l2))
(> (y0 l2) (y0 l1) (y1 l2)))) ; l2 span l1?
(list (x0 l2) (y0 l1)
; add total delay from both lines
(+ (d0 l1)
(if (< (x0 l1) (x0 l2)) (- (x0 l2) (x0 l1)) (- (x0 l1) (x0 l2)))
(d0 l2)
(if (< (y0 l1) (y0 l2)) (- (y0 l2) (y0 l1)) (- (y0 l1) (y0 l2)))))]
[else '()]))
(module+ test
(check-equal? (intersection '((0 0 0) (10 0 10)) '((5 -1 0) (5 1 2))) '(5 0 6))
(check-equal? (intersection '((0 0 0) (0 10 10)) '((-3 5 0) (11 5 14))) '(0 5 8))
(check-equal? (intersection '((0 0 0) (10 0 0)) '((5 2 0) (5 4 2))) '()))
(define (manhattan-distance p0 [p1 '(0 0 0)])
(+ (if (> (x p1) (x p0)) (- (x p1) (x p0)) (- (x p0) (x p1)))
(if (> (y p1) (y p0)) (- (y p1) (y p0)) (- (y p0) (y p1)))))
(module+ test
(check-eq? (manhattan-distance '(3 3 21)) 6)
(check-eq? (manhattan-distance '(-3 -3 17)) 6)
(check-eq? (manhattan-distance '(5 2 91)) 7)
(check-eq? (manhattan-distance '(2 5 88) '(-5 -2 33)) 14))
(define (min-cross [ip (current-input-port)])
(let* ([wire1 (steps->lines (string-split (read-line ip) ","))]
[wire2 (steps->lines (string-split (read-line ip) ","))]
[intersections (filter-not empty?
(for*/list ([l1 wire1]
[l2 wire2])
(intersection l1 l2)))])
;;(displayln intersections)
(first (sort (map manhattan-distance intersections) <))))
(module+ test
(check-eq? (min-cross (open-input-string "R8,U5,L5,D3
U7,R6,D4,L4")) 6)
(check-eq? (min-cross (open-input-string "R75,D30,R83,U83,L12,D49,R71,U7,L72
U62,R66,U55,R34,D71,R55,D58,R83")) 159)
(check-eq? (min-cross (open-input-string "R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51
U98,R91,D20,R16,D67,R40,U7,R15,U6,R7")) 135))
(define (min-delay [ip (current-input-port)])
(let* ([wire1 (steps->lines (string-split (read-line ip) ","))]
[wire2 (steps->lines (string-split (read-line ip) ","))]
[intersections (filter-not empty?
(for*/list ([l1 wire1]
[l2 wire2])
(intersection l1 l2)))])
;;(displayln intersections)
(first (sort (map third intersections) <))))
(module+ test
(check-eq? (min-delay (open-input-string "R8,U5,L5,D3
U7,R6,D4,L4")) 30)
(check-eq? (min-delay (open-input-string "R75,D30,R83,U83,L12,D49,R71,U7,L72
U62,R66,U55,R34,D71,R55,D58,R83")) 610)
(check-eq? (min-delay (open-input-string "R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51
U98,R91,D20,R16,D67,R40,U7,R15,U6,R7")) 410))
(module+ main (min-delay)) | false |
88d0e9873d26873d2d854ac8dadd917a6c850ba7 | 9195bf7d21642dc73960a4a6571f1319b3be8d2d | /test/run-translator | f99e78c00a2c2227b235c9b104412198a6477794 | []
| no_license | eidelmanj/concurrent-object-synthesis | 86d46417c3dad900defa44399274c584c72d1ac4 | 6978ddd6ec608656397d45fe82cf74d55c4a5896 | refs/heads/master | 2021-01-17T02:44:17.321113 | 2017-03-01T16:17:36 | 2017-03-01T16:17:36 | 58,645,368 | 2 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,544 | run-translator | #! /usr/bin/env racket
#lang racket
(require "../parser/parser.rkt"
"../program_representation/racket-synthesis.rkt"
"../program_representation/simulator-structures.rkt"
racket/port
parser-tools/lex
(prefix-in re- parser-tools/lex-sre)
parser-tools/yacc)
(define args (vector->list (current-command-line-arguments)))
(define in (open-input-file (first args)))
(define program (port->string in))
(close-input-port in)
(define lst (let*
((test-program program)
(input (open-input-string test-program)))
(translate (simple-math-parser (lex-this simple-math-lexer input)))))
;; (display (translate-to-c lst))
(define (display-each-line l)
(cond
[(empty? l) (void)]
[(Single-branch? (first l))
(display "if (") (display (Single-branch-condition (first l))) (displayln ") {")
(display-each-line (Single-branch-branch (first l)))
(displayln "}")
(display-each-line (rest l))]
[(Loop? (first l))
(display "while (") (display (Loop-condition (first l))) (displayln ") {")
(display-each-line (Loop-instr-list (first l)))
(displayln "}")
(display-each-line (rest l))]
[else
(displayln (first l))
(display-each-line (rest l))]))
(map
(lambda (l) (displayln "__________________")
(cond
[(Method? l) (display-each-line (Method-instr-list l))]
[else
(displayln "something else")])
(displayln "") (displayln ""))
lst)
| false |
|
2aca391fb00cd46002642c54afd85a64856ad582 | 1bae1698895e38bade435b1fafe6911ca6407384 | /crypto/successful_attack.rkt | 02fdcba35d9106a099d716948767831db7fd5ed4 | []
| no_license | miasantomauro/mia-isp-spring-2021 | 2f4b4801f4b81dc12c682a106438c805dd304eb2 | 93c2544072adcaecb529f7516086514cfc27346c | refs/heads/main | 2023-06-09T03:38:50.102839 | 2021-05-29T19:35:36 | 2021-05-29T19:35:36 | 332,241,930 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 12,470 | rkt | successful_attack.rkt | #lang forge
/*
Model of crypto/DS diagrams
Tim Mia Abby
Opting to build in normal Forge, not Electrum
A B
| |
|----------->|
| {foo}_B |
| |
|<-----------|
| {bar}_A |
...
time
|
v
*/
abstract sig Datum {}
sig Key extends Datum {}
sig PrivateKey extends Key {}
sig PublicKey extends Key {}
sig SymmetricKey extends Key {}
-- relation to match key pairs --
one sig KeyPairs {
pairs: set PrivateKey -> PublicKey,
owners: set PrivateKey -> Agent
}
-- t=0, t=1, ...
sig Timeslot {
next: lone Timeslot
}
-- As agents are sent messagest, they learn pieces of data --
abstract sig Agent extends Datum {
learned_times: set Datum -> Timeslot,
generated_times: set Text -> Timeslot
}
one sig Attacker extends Agent {
}
sig Ciphertext extends Datum {
encryptionKey: one Key,
-- result in concating plaintexts
plaintext: set Datum
}
-- Non-name base value (e.g., nonces)
sig Text extends Datum {}
-- {foo}_B
sig Message {
-- Support delays, non-reception
sender: one Agent,
receiver: one Agent,
sendTime: one Timeslot,
data: set Datum
}
pred wellformed {
-- Design choice: only one message event per timeslot;
-- assume we have a shared notion of time
all t: Timeslot | lone sendTime.t
-- You cannot send a message with no data
all m: Message | some m.data
-- someone cannot send a message to themselves
all m: Message | m.sender not in m.receiver
-- agents only learn information that they are explicitly sent
all d: Datum | all t: Timeslot | all a: Agent | d->t in a.learned_times iff {
-- they have not already learned the datum --
{d not in (a.learned_times).(Timeslot - t.*next)} and
-- They received the message
{{some m: Message | {d in m.data and t = m.sendTime and m.receiver = a}}
or
-- d can be the plaintext of a ciphertext encrypted using a symmetric key which the agent has access to the key
{some m: Message | {some c: Ciphertext |
m.receiver = a and
c in m.data and
m.sendTime = t and
c in (a.learned_times).(Timeslot - t.^next) and
d in c.plaintext and
c.encryptionKey in SymmetricKey and
c.encryptionKey in (a.learned_times).(Timeslot - t.^next)}}
or
-- d is a plaintext of the ciphertext which the agent has access to the key encrypted using a publicKey
{some m: Message | {some c: Ciphertext |
m.receiver = a and
c in m.data and
m.sendTime = t and
c in (a.learned_times).(Timeslot - t.^next) and
d in c.plaintext and
c.encryptionKey in PublicKey and
KeyPairs.pairs.(c.encryptionKey) in (a.learned_times).(Timeslot - t.^next)}}
or
-- Agent knows all public keys
{d in PublicKey}
or
-- Agent knows the private keys it owns
{d in PrivateKey and a = d.(KeyPairs.owners)}
or
-- Agent can encrypt things
{d in Ciphertext and
d.encryptionKey in (a.learned_times).(Timeslot - t.^next) and
{all a: d.plaintext | a not in Ciphertext} and
d.plaintext in (a.learned_times).(Timeslot - t.^next)}
or
-- Agents know their own names
{d = a}
or
-- This was a value generated by the agent in this timeslot
{d in (a.generated_times).t}
}}
-- If you generate something, you do it once only
all a: Agent | all d: Text | lone t: Timeslot | d in (a.generated_times).t
-- Messages comprise only values known by the sender
all m: Message | m.data in ((m.sender).learned_times).(Timeslot - (m.sendTime).^next)
all m: Message | m.sender = Attacker or m.receiver = Attacker
-- plaintext relation is acyclic
-- NOTE WELL: if ever add another type of datum that contains data, + inside ^.
all d: Datum | d not in d.^(plaintext)
all c: Ciphertext | some c.plaintext
(KeyPairs.pairs).PublicKey = PrivateKey
PrivateKey.(KeyPairs.pairs) = PublicKey
all privKey: PrivateKey | {one pubKey: PublicKey | privKey->pubKey in KeyPairs.pairs}
all priv1: PrivateKey | all priv2: PrivateKey - priv1 | all pub: PublicKey | priv1->pub in KeyPairs.pairs implies priv2->pub not in KeyPairs.pairs
}
-- NS AS PREDICATES STARTS HERE --
----------------------------------------------------------------------
----- PROTOCOL DEFN -----
/*
(defprotocol ns basic
(defrole init
(vars (a b name) (n1 n2 text))
(trace (send (enc n1 a (pubk b)))
(recv (enc n1 n2 (pubk a)))
(send (enc n2 (pubk b)))))
(defrole resp
(vars (a b name) (n1 n2 text))
(trace (recv (enc n1 a (pubk b)))
(send (enc n1 n2 (pubk a)))
(recv (enc n2 (pubk b))))))
*/
sig Init extends Agent {
-- variables for an init strand:
init_a, init_b: one Agent, -- alias for Name
init_n1, init_n2: one Text
}
sig Resp extends Agent {
-- variables for a resp strand:
resp_a, resp_b: one Agent, -- alias for Name
resp_n1, resp_n2: one Text
}
pred ns_execution {
-- We are conflating 'role' and 'strand' somewhat, although
-- we think it is safe, since 'role' is embodied as a sig, and
-- a strand is an atom of that role
-- ASSUMPTION: strands have exactly one role
-- ASSUMPTION: not interested in instances where protocol execution is incomplte
-- (we enforce all strands to observe their full trace)
all init: Init | {
some m0: Message |
some m1: Message - m0 |
some m2: Message - m1 - m0 | {
m1.sendTime in m0.sendTime.^next
m2.sendTime in m1.sendTime.^next
-- (trace (send (enc n1 a (pubk b)))
-- contains local values for "a" and "n1"
m0.data.plaintext = init.init_a + init.init_n1
one m0.data
-- encrypted with public key of whoever is locally "b"
-- recall "owners" takes us to private key, and then lookup in pairs
m0.data.encryptionKey = KeyPairs.pairs[KeyPairs.owners.(init.init_b)]
m0.sender = init
init.init_b not in init
init.init_a = init
-- (recv (enc n1 n2 (pubk a)))
m1.data.plaintext = init.init_n1 + init.init_n2
init.init_n1 not in init.init_n2
one m1.data
m1.data.encryptionKey = KeyPairs.pairs[KeyPairs.owners.(init.init_a)]
m1.receiver = init
-- (send (enc n2 (pubk b)))))
m2.data.plaintext = init.init_n2
one m2.data
m2.data.encryptionKey = KeyPairs.pairs[KeyPairs.owners.(init.init_b)]
m2.sender = init
}
}
all resp: Resp | {
some m0: Message |
some m1: Message - m0 |
some m2: Message - m1 - m0 | {
m1.sendTime in m0.sendTime.^next
m2.sendTime in m1.sendTime.^next
--(trace (recv (enc n1 a (pubk b)))
-- contains local values for "a" and "n1"
m0.data.plaintext = resp.resp_a + resp.resp_n1
one m0.data
-- encrypted with public key of whoever is locally "b"
-- recall "owners" takes us to private key, and then lookup in pairs
m0.data.encryptionKey = KeyPairs.pairs[KeyPairs.owners.(resp.resp_b)]
m0.receiver = resp
-- (send (enc n1 n2 (pubk a)))
m1.data.plaintext = resp.resp_n1 + resp.resp_n2
one m1.data
m1.data.encryptionKey = KeyPairs.pairs[KeyPairs.owners.(resp.resp_a)]
m1.sender = resp
-- (recv (enc n2 (pubk b))))))
m2.data.plaintext = resp.resp_n2
one m2.data
m2.data.encryptionKey = KeyPairs.pairs[KeyPairs.owners.(resp.resp_b)]
m2.receiver = resp
resp.resp_a not in resp.resp_b
}
}
}
----- SKELETON DEFNS -----
/*
(defskeleton ns
(vars (b name) (n1 text))
; ASSUME: 2nd "b" is referring to the variable declared line above
; ASSUME: 1st "b" is referring to the variable declared in defrole of protocol
;;; The initiator point-of-view
(defskeleton ns
(vars (a b name) (n1 text))
(defstrand init 3 (a a) (b b) (n1 n1))
(non-orig (privk b) (privk a))
(uniq-orig n1)
(comment "Initiator point-of-view"))
;;; The responder point-of-view
(defskeleton ns
(vars (a b name) (n2 text))
(defstrand resp 3 (a a) (b b) (n2 n2))
(non-orig (privk a) (privk b))
(uniq-orig n2)
(comment "Responder point-of-view"))
*/
-- TODO: look at defskeleton and defstrand docs
-- what is the (b b)? ANSWER: this is defining the variable b in the role to the *value* of b
-- why say "3" there if init/resp traces have 3 messages each? This is the max height. You could not put more than 3 here, but you can put less than 3
-- Assume: defskeleton ns: the strands herein are NS roles
-- Assume: defstrand init ... is talking about a specific init strand
-- First cut
abstract sig SkeletonNS {}
one sig SkeletonNS_0 extends SkeletonNS {
s0_a: one Agent,
s0_b: one Agent,
s0_n1: one Text,
strand0_0: one Init
}
one sig SkeletonNS_1 extends SkeletonNS {
s1_a: one Agent,
s1_b: one Agent,
s1_n2: one Text,
strand1_0: one Resp
}
pred constrain_skeletonNS_0 {
-- (defstrand init 3 (a a) (b b) (n1 n1))
SkeletonNS_0.strand0_0.init_a = SkeletonNS_0.s0_a
SkeletonNS_0.strand0_0.init_b = SkeletonNS_0.s0_b
SkeletonNS_0.strand0_0.init_n1 = SkeletonNS_0.s0_n1
-- (non-orig (privk b) (privk a))
-- (uniq-orig n1)
-- ASSUME: meaning of these operators is correct ; it is likely not quite
-- do we, e.g., need to also assume that the generation EXISTS for unique?
all a: Agent - SkeletonNS_0.strand0_0 |
SkeletonNS_0.s0_n1 not in a.generated_times.Timeslot
}
pred constrain_skeletonNS_1 {
-- (defstrand resp 3 (a a) (b b) (n2 n2))
SkeletonNS_1.strand1_0.resp_a = SkeletonNS_1.s1_a
SkeletonNS_1.strand1_0.resp_b = SkeletonNS_1.s1_b
SkeletonNS_1.strand1_0.resp_n2 = SkeletonNS_1.s1_n2
-- (non-orig (privk b) (privk a))
-- (uniq-orig n2)
all a: Agent - SkeletonNS_1.strand1_0 |
SkeletonNS_1.s1_n2 not in a.generated_times.Timeslot
}
-- Don't expect skeleton defns to be displayed; they are probably invisible
-- structure that constrains the instance found.
pred exploit_search {
some t: Text |
some c: Ciphertext |
some m: Message |
some t2: Text - t |
some c2: Ciphertext - c |
some m2: Message - m |
{
m.data = c and
t in c.plaintext and
t in (Attacker.learned_times).Timeslot and
m2.data = c2 and
t2 in c2.plaintext and
t2 in (Attacker.learned_times).Timeslot
}
}
pred temporary {
-- upper bounds for one sig have size > 1 at the moment; fix
one Attacker
-- for checking, debugging:
all a1, a2: Agent | {
-- If one has a key, keys are different
(some KeyPairs.owners.a1 and a1 != a2) implies
(KeyPairs.owners.a1 != KeyPairs.owners.a2)
}
all p: PrivateKey | one p.(KeyPairs.owners)
-- number of keys greater than 0
#Key > 0
}
fun subterm[supers: set Datum]: set Datum {
-- VITAL: if you add a new subterm relation, needs to be added here, too!
supers +
supers.^(plaintext) -- union on new subterm relations inside parens
}
-- Differs slightly in that a is a strand, not a node
pred originates[a: Agent, d: Datum] {
-- unsigned term t originates on n in N iff
-- term(n) is positive and
-- t subterm of term(n) and
-- whenever n' precedes n on the same strand, t is not subterm of n'
some m: sender.a | { -- messages sent by a (positive term)
d in subterm[m.data] -- d is a sub-term of m
all m2: (sender.a + receiver.a) - m | { -- everything else on the strand
-- ASSUME: messages are sent/received in same timeslot
{m2.sendTime in m.sendTime.^(~(next))}
implies
{d not in subterm[m2.data]}
}
}
/*
some m: Message |
all m2: Message - m | {m2 in sendTime.(Timeslot - m.*sendTime) and m.sender = a and m2.sender = a}
implies
{d in m and d not in m2}
*/
}
-- 2 publickey, 3 ciphertext, 3 agent
-- Sigs that we have: Datum, Key, PrivateKey, PublicKey, SymmetricKey, Agent, Attacker, Ciphertext, Text, Message, Timeslot, KeyPairs
run {
temporary
wellformed
ns_execution
constrain_skeletonNS_0
constrain_skeletonNS_1
exploit_search
} for exactly 16 Datum, exactly 6 Key,
exactly 2 SkeletonNS,
exactly 1 SkeletonNS_0,
exactly 1 SkeletonNS_1,
exactly 3 PrivateKey,
exactly 3 PublicKey,
exactly 0 SymmetricKey,
exactly 1 Init,
exactly 1 Resp,
exactly 1 Attacker,
exactly 5 Ciphertext,
exactly 2 Text,
exactly 6 Message,
exactly 6 Timeslot,
exactly 1 KeyPairs,
exactly 3 Agent for {next is linear}
| false |
baef11da498e891dbfe738920239d4114e8d4a8b | 76df16d6c3760cb415f1294caee997cc4736e09b | /rosette-benchmarks-3/rtr/benchmarks/all.rkt | c57d05f9cac2c0fad867554e04b47e9bf43ba423 | [
"MIT"
]
| permissive | uw-unsat/leanette-popl22-artifact | 70409d9cbd8921d794d27b7992bf1d9a4087e9fe | 80fea2519e61b45a283fbf7903acdf6d5528dbe7 | refs/heads/master | 2023-04-15T21:00:49.670873 | 2021-11-16T04:37:11 | 2021-11-16T04:37:11 | 414,331,908 | 6 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 2,087 | rkt | all.rkt | #lang racket
(require (only-in rosette/safe clear-state! current-solver)
rosette/solver/smt/cvc4
syntax/parse/define
syntax/location)
#;(pretty-display
(for/list ([x (in-directory ".")] #:when (and (string-suffix? (~a x) ".rkt")
(not (equal? "./all.rkt" (~a x)))))
(~s (~a x))))
(define-for-syntax all-inputs
'("./RubyMoney/translated0.rkt"
"./RubyMoney/translated1.rkt"
"./RubyMoney/translated2.rkt"
"./RubyMoney/translated3.rkt"
"./RubyMoney/translated4.rkt"
"./RubyMoney/translated5.rkt"
"./RubyMoney/translated6.rkt"
"./boxroom/translated.rkt"
"./business_time/translated0.rkt"
"./business_time/translated1.rkt"
"./business_time/translated2.rkt"
"./business_time/translated3.rkt"
"./business_time/translated4.rkt"
"./business_time/translated5.rkt"
"./business_time/translated6.rkt"
"./business_time/translated7.rkt"
"./business_time/translated8.rkt"
"./business_time/translated9.rkt"
"./geokit/translated0.rkt"
"./geokit/translated1.rkt"
"./geokit/translated2.rkt"
"./geokit/translated3.rkt"
"./geokit/translated4.rkt"
"./geokit/translated5.rkt"
"./matrix/translated0.rkt"
"./unitwise/translated0.rkt"
"./unitwise/translated1.rkt"
"./unitwise/translated2.rkt"
"./unitwise/translated3.rkt"
"./unitwise/translated4.rkt"
"./unitwise/translated5.rkt"))
(define-syntax-parser run-all-tests
[(_)
#:with (mod-id ...) (generate-temporaries all-inputs)
#:with (mod-path ...) (generate-temporaries all-inputs)
#:with (path ...) all-inputs
(syntax/loc this-syntax
(begin
(begin
(module mod-id racket
(require path))
(current-solver (cvc4))
(define mod-path (quote-module-path mod-id))
(dynamic-require mod-path #f)
(clear-state!)) ...))])
(define-syntax-parse-rule (require-all-tests)
#:with (path ...) all-inputs
(begin (require path) ...))
(run-all-tests)
(module+ line-count
(require-all-tests))
| true |
5d2832b6b50faeada341d1812cb74cac9d15f069 | e3224d588cffff24cf726752b75bdfc07234c0cf | /racket/test-httpd-utils.rkt | 9239c94cda3e8f189dbf6abb627f30fc374fc540 | [
"MIT"
]
| permissive | tonyg/scheme-httpd | 0b1fbadfcbb3d9be27a20d98ba1d5c33414def87 | c66fee88fd8a5db6b71784dbd6c79bc14a6567f3 | refs/heads/master | 2016-09-05T13:04:29.242446 | 2011-06-20T17:03:10 | 2011-06-20T17:03:10 | 349,098 | 2 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 993 | rkt | test-httpd-utils.rkt | #lang racket
(require "httpd-utils.rkt")
(require rackunit)
(display "Testing httpd-utils...")
(newline)
(check-equal? (unquote-http-url "/foo%25/") "/foo%/")
(check-equal? (unquote-http-url "/foo%22/") "/foo\"/")
(check-equal? (unquote-http-url "/foo%2b%2a/") "/foo+*/")
(check-equal? (parse-query "") '())
(check-equal? (parse-query "foo") '((foo)))
(check-equal? (parse-query "foo&bar") '((bar) (foo)))
(check-equal? (parse-query "foo&foo&bar") '((bar) (foo)))
(check-equal? (parse-query "foo&bar&foo") '((bar) (foo)))
(check-equal? (parse-query "foo=123&bar&foo") '((bar) (foo "123")))
(check-equal? (parse-query "foo=123&bar&foo=123") '((foo "123" "123") (bar)))
(check-equal? (parse-query "foo=123&bar&foo=234") '((foo "123" "234") (bar)))
(check-equal? (parse-query "foo=123&bar=234&foo") '((bar "234") (foo "123")))
(check-equal? (parse-query "foo&bar=234&foo=123") '((foo "123") (bar "234")))
(check-equal? (parse-query "foo=123&bar=234&foo=345") '((foo "123" "345") (bar "234")))
| false |
17e99e43f21658e76081a5b6ea831254a253edf2 | 49d98910cccef2fe5125f400fa4177dbdf599598 | /exercism.io/run-length-encoding/run-length-encoding.rkt | d7a0ff1150ed2c3bd9121fb966b7e9c2e8054371 | [
"MIT"
]
| permissive | lojic/LearningRacket | 0767fc1c35a2b4b9db513d1de7486357f0cfac31 | a74c3e5fc1a159eca9b2519954530a172e6f2186 | refs/heads/master | 2023-01-11T02:59:31.414847 | 2023-01-07T01:31:42 | 2023-01-07T01:31:42 | 52,466,000 | 30 | 4 | null | null | null | null | UTF-8 | Racket | false | false | 787 | rkt | run-length-encoding.rkt | #lang racket
(require "../chunk-by.rkt")
(require threading)
(provide encode decode)
(define (encode string)
(if (non-empty-string? string)
(~> string
string->list
chunk-by
(map (λ (x) (format "~a~a" (length x) (car x))) _)
(string-join ""))
""))
(define (decode string)
(cond [(non-empty-string? string)
(define (pair-up lst)
(if (null? lst)
'()
(cons (cons (string->number (list->string (car lst))) (cadr lst))
(pair-up (cddr lst)))))
(~> string
string->list
(chunk-by char-numeric?)
pair-up
(foldr (λ (a b) (string-append (make-string (car a) (cadr a)) b)) "" _))]
[else ""]))
| false |
8f4faf688650440553c266cc885c6049c98f65f9 | 925045585defcc1f71ee90cf04efb841d46e14ef | /racket/CPN98/examples/cpn98-fig3-owner-ctx.rkt | 95c753b590e2997dcb48545b829dafc910abd124 | []
| no_license | rcherrueau/APE | db095c3b6fc43776d1421a16090937a49847bdd9 | a881df53edf84d93ec0a377c2ed02c0d754f7041 | refs/heads/master | 2022-07-19T18:01:41.848025 | 2021-12-19T17:30:23 | 2021-12-19T17:30:23 | 11,178,796 | 4 | 1 | null | 2022-07-07T21:11:07 | 2013-07-04T14:12:52 | Racket | UTF-8 | Racket | false | false | 989 | rkt | cpn98-fig3-owner-ctx.rkt | #lang reader "../lang.rkt"
;; Prelude
(class X) (class Unit)
;; Figure 3: Owner Context Example
(class Link{n}
(field [next : Θ/Link{n}]) ;; `next` is owned by the same owner as
;; the instance it is enclosed in.
(field [data : n/X]) ;; data belongs to the context `n`.
(def (init [inData : n/X] -> Θ/Link{n})
(set-field! this data inData)
this))
(class XStack{m}
(field [top : rep/Link{m}])
(def (push [data : m/X] -> Unit)
(let ([newTop : rep/Link{m}
(send (new rep/Link{m}) init data)])
(set-field! newTop next top)
(set-field! this top newTop)
(new Unit)))
(def (pop -> m/X)
(let ([oldTop : rep/Link{m} top]
[top : rep/Link{m} (get-field oldTop next)])
(get-field top data))))
(let ([world-stack : XStack{world} (new XStack{world})]
[rep-stack : XStack{rep} (new XStack{rep})])
(send world-stack push (new X))
(send rep-stack push (new rep/X)))
| false |
658afb334393f1f2136878b68bef2fb919ff5d0f | 04c0a45a7f234068a8386faf9b1319fa494c3e9d | /test-booleans.rkt | 78f3c9938d92f196230bc26aedd8e9f23c04c701 | []
| no_license | joskoot/lc-with-redex | 763a1203ce9cbe0ad86ca8ce4b785a030b3ef660 | 9a7d2dcb229fb64c0612cad222829fa13d767d5f | refs/heads/master | 2021-01-11T20:19:20.986177 | 2018-06-30T18:02:48 | 2018-06-30T18:02:48 | 44,252,575 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,467 | rkt | test-booleans.rkt | #lang racket ; File test-booleans.rkt"
(require redex "booleans.rkt" "lazy-evaluator.rkt")
(printf "~a~n" "test-booleans")
(test-equal (ev ( True yes no)) 'yes)
(test-equal (ev ( False yes no)) 'no )
(test-equal (ev (Not False yes no)) 'yes)
(test-equal (ev (Not True yes no)) 'no )
(test-equal (ev (And True True yes no)) 'yes)
(test-equal (ev (And True False yes no)) 'no )
(test-equal (ev (And False True yes no)) 'no )
(test-equal (ev (And False False yes no)) 'no )
(test-equal (ev (Or True True yes no)) 'yes)
(test-equal (ev (Or True False yes no)) 'yes)
(test-equal (ev (Or False True yes no)) 'yes)
(test-equal (ev (Or False False yes no)) 'no )
(test-equal (ev (If True yes no)) 'yes)
(test-equal (ev (If False yes no)) 'no )
(test-equal (ev (If (Not False) yes no)) 'yes)
(test-equal (ev (If (Not True) yes no)) 'no )
(test-equal (ev (If (And True True) yes no)) 'yes)
(test-equal (ev (If (And True False) yes no)) 'no )
(test-equal (ev (If (And False True ) yes no)) 'no )
(test-equal (ev (If (And False False) yes no)) 'no )
(test-equal (ev (If (Or True True ) yes no)) 'yes)
(test-equal (ev (If (Or True False) yes no)) 'yes)
(test-equal (ev (If (Or False True ) yes no)) 'yes)
(test-equal (ev (If (Or False False) yes no)) 'no )
(test-results) ; Display: All 24 tests passed.
| false |
3fbc14402e23e047f79dfd9c103c913b355959b9 | 0bbf33de1afce7cace30371d43dfdeb9614be79f | /profj/comb-parsers/parser-units.rkt | d29f06da766d4032c18c12e18a02a2b831c99999 | []
| no_license | aptmcl/profj | e51e69d18c5680c89089fe725a66a3a5327bc8bd | 90f04acbc2bfeb62809234f64443adc4f6ca665a | refs/heads/master | 2021-01-21T19:19:22.866429 | 2016-01-27T20:14:16 | 2016-01-27T20:14:16 | 49,766,712 | 0 | 0 | null | 2016-01-16T09:04:05 | 2016-01-16T09:04:05 | null | UTF-8 | Racket | false | false | 55,203 | rkt | parser-units.rkt | (module parser-units racket/base
(require parser-tools/lex
racket/unit
combinator-parser/combinator-unit
#;(lib "combinator-unit.rkt" "combinator-parser")
"java-signatures.rkt"
racket/string)
(define-signature language-forms^ (program statement (recurs expression) field interact)) ;value-type method-type))
(define-signature token-proc^ (old-tokens->new))
(define-unit java-dictionary@
(import)
(export language-dictionary^
(rename language-format-parameters^
(output-map input->output-name)))
(define class-type "keyword")
(define (output-map x)
#;(printf "in output-map ~a~n" x)
(when (position-token? x)
(set! x (position-token-token x)))
(case (token-name x)
[(PIPE) "|"]
[(OR) "||"]
[(OREQUAL) "|="]
[(EQUAL) "="]
[(GT) ">"]
[(LT) "<"]
[(LTEQ) "<="]
[(GTEQ) ">="]
[(PLUS) "+"]
[(MINUS) "-"]
[(TIMES) "*"]
[(DIVIDE) "/"]
[(^T) "^"]
[(O_PAREN) "("]
[(C_PAREN) ")"]
[(O_BRACE) "{"]
[(C_BRACE) "}"]
[(O_BRACKET) "["]
[(C_BRACKET) "]"]
[(SEMI_COLON) ";"]
[(PERIOD) "."]
[(COMMA) ","]
[(NULL_LIT) "null"]
[(TRUE_LIT) "true"]
[(FALSE_LIT) "false"]
[(EOF) "end of input"]
[(caseT) "case"]
[(doT) "do"]
[(elseT) "else"]
[(ifT) "if"]
[(voidT) "void"]
[(STRING_LIT) (format "\"~a\"" (token-value x))]
[(CHAR_LIT) (format "'~a'" (token-value x))]
[(INTEGER_LIT LONG_LIT FLOAT_LIT DOUBLE_LIT) (token-value x)]
[(HEX_LIT HEXL_LIT) (format "hex formatted number ~a" (token-value x))]
[(OCT_LIT OCTL_LIT) (format "octal formatted number ~a" (token-value x))]
[(IDENTIFIER) (format "identifier ~a" (token-value x))]
[(STRING_ERROR) (format "misformatted string ~a" (token-value x))]
[else (token-name x)]))
(define (java-keyword? t)
(memq t `(? this super new instanceof while try throw synchronized switch return ifT goto for finally
elseT doT default continue catch case break voidT throws const interface implements extends
class import package EQUAL += -= *= /= &= ^= %= <<= >>= >>>=
boolean byte char double float int long short
abstract native private protected public static strictfp transient volatile)))
(define (close-to-keyword? t arg)
;(printf "close-to-keyword ~a ~a~n" t arg)
(and (string? t)
(member t (select-words (string->symbol arg)))))
(define (miscapitalized? t key)
(and (string? t)
(let ((s (string-downcase t)))
(equal? s key))))
(define misspelled-list '((import "mport" "iport" "imort" "imprt" "impot" "impor" "improt" "impourt")
(class "lass" "cass" "clss" "clas" "calss")
(abstract
"bstract" "astract" "abtract" "absract" "abstact" "abstrct" "abstrat" "abstract" "abstarct" "abstracts")
(extends "xtends" "etends" "exends" "extnds" "exteds" "extens" "extneds" "extend")
(new "nw" "ne" "nwe")
(this "his" "tis" "ths" "thi" "tihs" "thsi")
(instanceof "instancef" "instanceo" "intsanceof")
(if "fi")
(else "lse" "ese" "els" "eles" "elseif")
(return "eturn" "rturn" "reurn" "retrn" "retun" "retur" "reutrn" "retrun" "returns" "raturn")
(true "rue" "tue" "tre" "tru" "ture" "treu")
(false "flse" "fase" "fale" "fals" "flase" "fasle")
(interface
"nterface" "iterface" "inerface" "intrface" "inteface" "interace" "interfce" "interfae" "intreface")
(implements
"mplements" "iplements" "impements" "implments" "impleents" "implemnts" "implemets" "implemens"
"implement")
(void "oid" "vid" "voi" "viod" "vod")
(for "fo" "fore" "fro")
(super "uper" "sper" "supr" "supe" "supper")
(public "ublic" "pblic" "pulic" "pubic" "publc" "publi" "pubilc")
(private "rivate" "pivate" "prvate" "priate" "privte" "privae" "privat" "pravite")
(package "ackage" "pckage" "pakage" "pacage" "packge" "packae" "packag")
(protected "rotected" "portected")
(final "inal" "fnal" "fial" "finl" "finale" "fianl")
(check "chek" "cehck" "chck" "chack")
(expect "expct" "expeet" "expec" "exect")
(within "with" "withi" "withen" "wihtin")
))
(define (select-words key)
(safe-car (filter (lambda (x) (eq? (car x) key)) misspelled-list)))
(define (safe-car f)
(if (null? f) null (car f)))
(define all-words (filter string? (apply append misspelled-list)))
(define misspelled (lambda (id token-v) (if (close-to-keyword? token-v id) 1 0)))
(define misscap (lambda (id token-v) (miscapitalized? token-v id)))
(define missclass (lambda (id token-n) (and (eq? 'IDENTIFIER id) (java-keyword? token-n))))
)
(define-signature teaching-languages^
(parse-beginner parse-beginner-interactions
parse-intermediate parse-intermediate-interactions parse-intermediate+access
parse-advanced parse-advanced-interactions
old-tokens->new))
(define-signature id^ (id))
;Terminals unit
(define-unit java-terminals@
(import combinator-parser^ id^)
(export java-operators^ java-separators^ java-literals^ java-expression-keywords^
java-statement-keywords^ java-definition-keywords^
java-type-keywords^ java-reserved^ java-extras^ java-vals^ java-ids^ java-specials^)
(define-simple-terminals Operators
((PIPE "|") (OR "||") (OREQUAL "|=")
(EQUAL "=") (GT ">") (LT "<") ! ~ ? :
== (LTEQ "<=") (GTEQ ">=") != && ++ --
(PLUS "+") (MINUS "-")
(TIMES "*") (DIVIDE "/") & (^T "^") % << >> >>>
+= -= *= /= &= ^= %= <<= >>= >>>=))
(define-simple-terminals Separators
((O_PAREN "(") (C_PAREN ")") (O_BRACE "{") (C_BRACE "}")
(O_BRACKET "[") (C_BRACKET "]") (SEMI_COLON ";") (PERIOD ".") (COMMA ",")))
(define-simple-terminals EmptyLiterals ((NULL_LIT "null") (TRUE_LIT "true") (FALSE_LIT "false") EOF))
(define-simple-terminals Keywords
(abstract default (ifT "if") private this
boolean (doT "do") implements protected throw
break double import public throws
byte (elseT "else") instanceof return transient
(caseT "case") extends int short try
catch final interface static (voidT "void")
char finally long strictfp volatile
class float native super while
const for new switch
continue goto package synchronized))
(define-simple-terminals ExtraKeywords (dynamic check expect within -> ->> ->>> test tests testcase))
(define-terminals java-vals
((STRING_LIT "String literal" id) (CHAR_LIT "character" id) (INTEGER_LIT "integer" id)
(LONG_LIT "long" id) (FLOAT_LIT "float" id) (DOUBLE_LIT "double" id)
(IDENTIFIER "identifer" id) (STRING_ERROR id)
(NUMBER_ERROR id) (HEX_LIT id) (OCT_LIT id) (HEXL_LIT id) (OCTL_LIT id)))
(define-terminals special-toks ((EXAMPLE id) (TEST_SUITE id) (IMAGE_SPECIAL id) (OTHER_SPECIAL id)))
)
;---------------------------------------------------------------------------------------------------
; Types, modifiers, operators
(define-unit types@
(import combinator-parser^ java-type-keywords^ java-variables^ java-separators^ id^)
(export java-types^)
(define integer-types
(choose (byte int short long) "type"))
(define inexact-types
(choose (float double) "type"))
(define numeric-type
(choose (integer-types inexact-types) "numeric type"))
(define prim-type
(choose (boolean double byte int short char long float) "type"))
(define (other-type-base types) (choice types "type"))
(define (value+name-type base-type)
(choose (base-type name) "type"))
(define (method-type base-t)
(choose (base-t voidT) "method return"))
(define (array-type base-t)
(sequence (base-t (repeat (sequence (O_BRACKET C_BRACKET) id "array type"))) id "type"))
)
(define-unit mods@
(import combinator-parser^ java-definition-keywords^)
(export java-access^)
(define access-mods
(choose (public private protected) "access modifier"))
(define (global-mods base-mods)
(choose (base-mods static) "modifier"))
(define (method-mods base-mods)
(choose (base-mods abstract) "modifier"))
)
(define-unit operators@
(import combinator-parser^ java-operators^ java-separators^)
(export java-ops^)
(define math-ops
(choose (PLUS MINUS TIMES DIVIDE %) "binary operater"))
(define shift-ops
(choose (<< >> >>>) "shift operater"))
(define compare-ops
(choose (== GT LT LTEQ GTEQ !=) "binary operater"))
(define bool-ops
(choose (&& OR) "binary operater"))
(define bit-ops
(choose (^T PIPE &) "binary operater"))
(define assignment-ops
(choose (EQUAL OREQUAL += -= *= /= &= ^= %= <<= >>= >>>=) "assignment"))
(define (bin-ops ops)
(choice ops "binary operater"))
(define un-assignment
(choose (++ --) "unary operater"))
(define un-op
(choose (~ PLUS MINUS) "unary operater"))
)
(define-unit general@
(import combinator-parser^ java-separators^ java-operators^ java-ids^ id^)
(export general-productions^)
(define (comma-sep term name)
(sequence (term (repeat (sequence (COMMA term) id (string-append "a list of " name))))
id (string-append "a list of " name)))
(define name
(sequence (IDENTIFIER (repeat (sequence (PERIOD IDENTIFIER) id "name"))) id "name"))
)
(define-unit unqualified-java-variables@
(import combinator-parser^ general-productions^ java-separators^ java-operators^ java-ids^ id^)
(export java-variables^)
(define name IDENTIFIER)
(define identifier IDENTIFIER)
(define (variable-declaration type expr share-type? end? name)
(let* ([var-name (string-append name " declaration")]
[no-share (sequence (type (^ identifier)) id var-name)]
[init (sequence ((^ identifier) EQUAL expr) id var-name)]
[f (choose (identifier init) var-name)]
[s&e (sequence (type (comma-sep f name)) id var-name)]
[s (sequence (type (comma-sep identifier name)) id var-name)]
[e (sequence (type init) id var-name)]
[base (sequence (type (^ identifier)) id var-name)]
[decl
(cond
[(and expr share-type?) s&e #;(choose (s&e e base) var-name)]
[share-type? s]
[expr (choose (e base) var-name)]
[else base])])
(cond
[(and end? (not share-type?) expr)
(sequence ((^ no-share) (choose (SEMI_COLON (sequence (EQUAL expr SEMI_COLON) id (string-append name " initialization")))))
id var-name)]
[end? (sequence (decl SEMI_COLON) id (string-append name " definition"))]
[else decl])))
)
(define-unit expressions@
(import combinator-parser^ general-productions^ id^
java-literals^ java-expression-keywords^ java-vals^ java-ids^
java-variables^ java-separators^
java-operators^ java-extras^ language-forms^)
(export expr-lits^ expr-terms+^ expr-tails^)
(define boolean-lits
(choose (TRUE_LIT FALSE_LIT) "boolean literal"))
(define textual-lits
(choose (STRING_LIT CHAR_LIT) "literal expression"))
(define prim-numeric-lits
(choose (INTEGER_LIT LONG_LIT) "literal expression"))
(define numeric-lits
(choose (HEX_LIT HEXL_LIT OCTL_LIT OCT_LIT) "literal expression"))
(define double-lits
(choose (FLOAT_LIT DOUBLE_LIT) "literal expression"))
(define null-lit NULL_LIT)
(define (literals lits)
(choice lits "literal expression"))
(define all-literals
(choose (NULL_LIT boolean-lits textual-lits prim-numeric-lits double-lits numeric-lits)
"literal expression"))
(define new-class
(choose ((sequence (new name O_PAREN C_PAREN) id)
(sequence (new name O_PAREN (comma-sep expression@ "arguments") C_PAREN) id))
"class instantiation"))
(define (new-array type-name)
(sequence (new type-name O_BRACKET expression@ C_BRACKET
(repeat (sequence (O_BRACKET expression@ C_BRACKET) id))
(repeat (sequence (O_BRACKET C_BRACKET) id)))
id "array instantiation"))
(define field-access-end
(sequence (PERIOD identifier) id "field access"))
(define array-access-end
(sequence (O_BRACKET expression@ C_BRACKET) id "array access"))
(define (array-init-maker contents)
(sequence (O_BRACE (comma-sep contents "array elements") C_BRACE) id "array initializations"))
(define array-init
(letrec ([base-init (array-init-maker expression@)]
[simple-init (array-init-maker
(choose (expression@ base-init (eta init)) "array initializations"))]
[init (array-init-maker (choose (expression@ simple-init) "array initialization"))])
init #;(sequence (new type-name init) "array initialization")))
(define (binary-expression-end op)
(sequence (op expression@) id "binary expression"))
(define if-expr-end
(sequence (? expression@ : expression@) id "conditional expression"))
(define simple-method-call
(choose
((sequence ((^ identifier) O_PAREN C_PAREN) id)
(sequence ((^ identifier) O_PAREN (comma-sep expression@ "arguments") C_PAREN) id))
"method invocation"))
(define method-call-end
(sequence (PERIOD (^ identifier) O_PAREN (choose (C_PAREN
(sequence ((comma-sep expression@ "arguments") C_PAREN) id))))
id "method invocation")
#;(choose
((sequence (PERIOD (^ identifier) O_PAREN C_PAREN) id)
(sequence (PERIOD (^ identifier) O_PAREN (comma-sep expression@ "arguments") C_PAREN) id))
"method invocation"))
(define (assignment asignee op)
(sequence ((^ asignee) op expression@) id "assignment"))
(define unary-assignment-front
(choose ((sequence (++ expression@) id)
(sequence (-- expression@) id)) "unary modification"))
(define (unary-assignment-back base)
(choose ((sequence (base ++) id)
(sequence (base --) id)) "unary modification"))
(define (cast type)
(sequence (O_PAREN type C_PAREN expression@) id "cast expression"))
(define instanceof-back
(sequence (instanceof name) id "instanceof expression"))
(define super-ctor
(choose ((sequence (super O_PAREN C_PAREN) id)
(sequence (super O_PAREN (comma-sep expression@ "arguments") C_PAREN) id))
"super constructor call"))
(define super-call
(choose ((sequence (super PERIOD identifier O_PAREN C_PAREN) id)
(sequence (super PERIOD identifier O_PAREN (comma-sep expression@ "arguments") C_PAREN) id))
"super method invocation"))
(define checks
(choose
((sequence (check expression@ expect expression@ within expression@) id)
(sequence (check expression@ expect expression@) id))
"check expression"))
)
(define-unit statements@
(import combinator-parser^ general-productions^ id^ language-forms^
java-statement-keywords^ java-separators^ java-ids^ java-operators^)
(export statements^)
(define (if-s stmt else?)
(cond
[else?
(choose ((sequence (ifT O_PAREN expression C_PAREN stmt elseT stmt) id)
(sequence (ifT O_PAREN expression C_PAREN stmt) id)) "if statement")]
[else (sequence (ifT O_PAREN expression C_PAREN stmt elseT stmt) id "if statement")]))
(define (return-s opt?)
(cond
[opt? (choose ((sequence (return expression SEMI_COLON) id)
(sequence (return SEMI_COLON) id)) "return statement")]
[else (sequence (return expression SEMI_COLON) id "return statement")]))
(define this-call
(choose ((sequence (this O_PAREN C_PAREN SEMI_COLON) id)
(sequence (this O_PAREN (comma-sep expression@ "arguments") C_PAREN SEMI_COLON) id)) "this constructor call"))
(define super-ctor-call
(choose ((sequence (super O_PAREN C_PAREN SEMI_COLON) id)
(sequence (super O_PAREN (comma-sep expression@ "arguments") C_PAREN SEMI_COLON) id)) "super constructor call"))
(define (block repeat?)
(let ([body (if repeat? (repeat-greedy (eta statement)) (eta statement))])
(sequence (O_BRACE body C_BRACE) id "block statement")))
(define expression-stmt
(sequence (expression@ SEMI_COLON) id "statement"))
(define (while-l stmt)
(sequence (while O_PAREN expression C_PAREN stmt) id "while loop"))
(define (do-while stmt)
(sequence (doT stmt while O_PAREN expression C_PAREN SEMI_COLON) id "do loop"))
(define (for-l init i-op? t-op? update up-op? statement)
(let ([full (sequence (for O_PAREN init SEMI_COLON expression SEMI_COLON update C_PAREN statement) id "for loop")]
[no-init (sequence (for O_PAREN SEMI_COLON expression SEMI_COLON update C_PAREN statement) id "for loop")]
[no-tst (sequence (for O_PAREN init SEMI_COLON SEMI_COLON update C_PAREN statement) id "for loop")]
[no-up (sequence (for O_PAREN init SEMI_COLON expression SEMI_COLON C_PAREN statement) id "for loop")]
[no-it (sequence (for O_PAREN SEMI_COLON SEMI_COLON update C_PAREN statement) id "for loop")]
[no-iu (sequence (for O_PAREN SEMI_COLON expression SEMI_COLON C_PAREN statement) id "for loop")]
[no-tu (sequence (for O_PAREN init SEMI_COLON SEMI_COLON C_PAREN statement) id "for loop")]
[none (sequence (for O_PAREN SEMI_COLON SEMI_COLON C_PAREN statement) id "for loop")])
(cond
[(and i-op? t-op? up-op?)
(choose (full no-init no-tst no-up no-it no-iu no-tu none) "for loop")]
[(and t-op? up-op?)
(choose (full no-tst no-up no-tu) "for loop")]
[(and i-op? t-op?)
(choose (full no-init no-tst no-it) "for loop")]
[(and i-op? up-op?)
(choose (full no-init no-up no-iu) "for loop")]
[i-op? (choose (full no-init) "for loop")]
[t-op? (choose (full no-tst) "for loop")]
[up-op? (choose (full no-up) "for loop")]
[else full])))
(define (break-s label)
(cond
[label (choose ((sequence (break SEMI_COLON) id)
(sequence (break label SEMI_COLON) id)) "break statement")]
[else (sequence (break SEMI_COLON) id "break statement")]))
(define (cont-s label)
(cond
[label (choose ((sequence (continue SEMI_COLON) id)
(sequence (continue label SEMI_COLON) id)) "continue statement")]
[else (sequence (continue SEMI_COLON) id "continue statement")]))
(define init
(sequence (this PERIOD IDENTIFIER EQUAL IDENTIFIER SEMI_COLON) id "field initialization"))
)
(define-unit members@
(import combinator-parser^ general-productions^ id^ java-types^
java-separators^ java-ids^ java-definition-keywords^ java-variables^)
(export fields^ methods^ ctors^)
(define (make-field mods type expr share-types?)
(cond
[mods (sequence ((repeat-greedy mods) (variable-declaration type expr share-types? #t "field"))
id "field definition")]
[else (variable-declaration type expr share-types? #t "field")]))
(define (arg type)
(sequence (type identifier) id "argument"))
(define (args type) (comma-sep (arg type) "parameters"))
;method-signature: {U parser #f} [U parser #f] [U parser #f] bool bool parser -> parser
(define (method-signature m ret a t? n)
(let* ([method-parms (if a
(choose ((sequence (O_PAREN C_PAREN) id)
(sequence (O_PAREN a C_PAREN) id)) "method parameter list")
(sequence (O_PAREN C_PAREN) id "method parameter list"))]
[full-no-t (sequence ((repeat m) ret (^ identifier) method-parms) id "method signature")]
[full (sequence ((^ full-no-t) throws (comma-sep n "thrown types")) id "method signature")]
[no-mods (sequence (ret (^ identifier) method-parms) id "method signature")]
[no-mods-t (sequence ((^ no-mods) throws (comma-sep n "thrown types")) id "method signature")])
(cond
[(and m t?) (choose (full full-no-t) "method signature")]
[m full-no-t]
[t? (choose (no-mods-t no-mods) "method signature")]
[else no-mods])))
(define (method-header method-sig)
(sequence (method-sig SEMI_COLON) id "method declaration"))
(define (make-method signature statement)
(sequence ((^ signature) O_BRACE statement C_BRACE) id "method definition"))
(define (make-constructor mod body type)
(let ([ctor (choose
((sequence ((^ identifier) O_PAREN C_PAREN O_BRACE body C_BRACE) id)
(sequence ((^ identifier) O_PAREN (args type) C_PAREN O_BRACE body C_BRACE) id))
"constructor definition")])
(cond
[mod (sequence ((repeat mod) ctor) id "constructor definition")]
[else ctor])))
)
(define-unit interface@
(import combinator-parser^ id^ java-definition-keywords^ java-ids^ java-separators^)
(export interfaces^)
(define (interface-body members)
(repeat-greedy (choice members "interface member")))
(define (interface-def modifier extends body)
(let ([m&e (sequence ((repeat modifier) interface (^ IDENTIFIER) extends O_BRACE body C_BRACE)
id "interface definition")]
[m (sequence ((repeat modifier) interface (^ IDENTIFIER) O_BRACE body C_BRACE) id "interface definition")]
[e (sequence (interface (^ IDENTIFIER) extends O_BRACE body C_BRACE) id "interface definition")]
[always (sequence (interface (^ IDENTIFIER) O_BRACE body C_BRACE) id "interface definition")])
(cond
[(and modifier extends) (choose (m&e m) "interface definition")]
[modifier m]
[extends (choose (e always) "interface definition")]
[else always])))
)
(define-unit class@
(import combinator-parser^ id^ java-definition-keywords^ java-ids^ java-separators^)
(export classes^)
(define (class-body members)
(choice members "class member"))
(define (implements-dec name)
(sequence (implements name) id "implementation declaration"))
(define (extend-dec name)
(sequence (extends name) id "extends declaration"))
(define (class-def mods extends implements body)
(let ([e&i (sequence (class (^ IDENTIFIER) extends implements O_BRACE body C_BRACE) id "class definition")]
[e (sequence (class (^ IDENTIFIER) extends O_BRACE body C_BRACE) id "class definition")]
[i (sequence (class (^ IDENTIFIER) implements O_BRACE body C_BRACE) id "class definition")]
[base (sequence (class (^ IDENTIFIER) O_BRACE body C_BRACE) id "class definition")])
(let ([base-choice
(cond
[(and extends implements)
(choice (list e&i e i base) "class definition")]
[extends (choice (list e base) "class definition")]
[implements (choice (list i base) "class definition")]
[else base])])
(cond
[mods (choose ((sequence (mods base-choice) id) base-choice) "class definition")]
[else base-choice]))))
)
(define-unit top-forms@
(import combinator-parser^ id^ java-definition-keywords^ java-separators^
java-variables^ general-productions^)
(export top-forms^)
(define (top-member mems)
(choice mems "class or interface"))
(define import-dec
(let ([name (sequence (identifier (repeat-greedy (sequence (PERIOD identifier) id "import name")))
id "import name")])
(choose
((sequence (import name PERIOD TIMES SEMI_COLON) id)
(sequence (import name SEMI_COLON) id)) "import declaration")))
(define (make-program package import body)
(let ([p&i (sequence (package import body) id "package program")]
[p (sequence (package body) id "package program")]
[i (sequence (import body) id "program")])
(cond
[(and package import)
(choose (p&i i) "program")]
[package
(choose (p body) "program")]
[import i]
[else body])))
)
;Remembered Unsupported Features
;strictfp
;allowing static fields in interface
(define-unit beginner-grammar@
(import combinator-parser^ java-operators^ java-separators^
java-statement-keywords^ java-type-keywords^ java-ids^
java-types^ java-access^ java-ops^ general-productions^ java-variables^
expr-lits^ expr-terms+^ expr-tails^ statements^
fields^ methods^ ctors^ interfaces^ classes^ top-forms^ id^)
(export language-forms^)
(define unique-base
(choose
((literals (list boolean-lits textual-lits prim-numeric-lits double-lits))
this
identifier
new-class
simple-method-call
(sequence (O_PAREN (eta expression) C_PAREN) id "parened expression")
(sequence (! (eta expression)) id "conditional expression")
(sequence (MINUS (eta expression)) id "negation expression")
checks) "expression"))
(define unique-end
(choose (field-access-end
method-call-end
(binary-expression-end (bin-ops (list math-ops compare-ops bool-ops))))
"expression"))
(define expression
(sequence (unique-base (repeat unique-end)) id "expression"))
(define statement
(choose ((return-s #f) (if-s (block #f) #f)) "statement"))
(define field (make-field #f (value+name-type prim-type) (eta expression) #f))
(define method-sig
(method-signature #f (value+name-type prim-type) (args (value+name-type prim-type)) #f identifier))
(define method (make-method method-sig statement))
(define constructor (make-constructor #f (repeat-greedy init) (value+name-type prim-type)))
(define interface (interface-def #f #f
(repeat (sequence (method-sig SEMI_COLON) id "method signature"))))
(define class
(class-def #f #f
(implements-dec identifier)
(repeat-greedy (class-body (list field method constructor)))))
(define program
(make-program #f
(repeat-greedy import-dec)
(repeat-greedy (top-member (list class interface)))))
(define interact
(choose (field statement expression) "interactive program"))
)
(define-unit intermediate-grammar@
(import combinator-parser^ java-operators^ java-separators^ (prefix tok: java-definition-keywords^)
java-statement-keywords^ java-type-keywords^ java-ids^
java-types^ java-access^ java-ops^ general-productions^ java-variables^
expr-lits^ expr-terms+^ expr-tails^ statements^
fields^ methods^ ctors^ interfaces^ classes^ top-forms^ id^)
(export language-forms^)
(define unique-base
(choose ((literals (list null-lit boolean-lits textual-lits prim-numeric-lits double-lits))
this
identifier
new-class
simple-method-call
(sequence (O_PAREN (eta expression) C_PAREN) id "parened expression")
(sequence (! (eta expression)) id "conditional expression")
(sequence (MINUS (eta expression)) id "negation expression")
(cast (value+name-type prim-type))
super-call
checks) "expression"))
(define assignee-base
(choose (this
identifier
new-class
simple-method-call
(sequence (O_PAREN (eta expression) C_PAREN) id "parened expression")
(sequence (! (eta expression)) id "conditional expression")
(sequence (MINUS (eta expression)) id "negation expression")
(cast (value+name-type prim-type))
super-call) "assignee"))
(define unique-end
(choose (field-access-end
method-call-end
(binary-expression-end (bin-ops (list math-ops compare-ops bool-ops bit-ops)))
instanceof-back) "expression"))
(define expression
(sequence (unique-base (repeat-greedy unique-end)) id "expression"))
(define stmt-expr
(choose (#;new-class
super-call
simple-method-call
(sequence (unique-base (repeat unique-end) method-call-end) id "method call")
(assignment
(choose (identifier
(sequence (assignee-base (repeat unique-end) field-access-end) id))
"assignee")
EQUAL)) "expression"))
(define (statement-c interact?)
(if interact?
(choose ((return-s #t)
(if-s (block #t) #f)
(assignment
(choose (identifier
(sequence (unique-base (repeat unique-end) field-access-end) id))
"assignee") EQUAL)
(block #t)) "statement")
(choose ((return-s #t)
(if-s (block #t) #f)
(block #t)
(variable-declaration (value+name-type prim-type) expression #f #t "local variable")
(sequence (stmt-expr SEMI_COLON) id)) "statement")))
(define statement (statement-c #f))
(define field (make-field #f (value+name-type prim-type) (eta expression) #f))
(define method-sig-no-abs
(method-signature #f (method-type (value+name-type prim-type))
(args (value+name-type prim-type)) #f identifier))
(define method-sig-abs
(method-signature tok:abstract (method-type (value+name-type prim-type))
(args (value+name-type prim-type)) #f identifier))
(define method
(choose ((make-method method-sig-no-abs (repeat-greedy statement))
(method-header method-sig-abs)) "method definition"))
(define constructor
(make-constructor #f
(choose ((sequence (super-ctor-call (repeat-greedy statement)) id)
(repeat-greedy statement)) "constructor body")
(value+name-type prim-type)))
(define interface
(interface-def
#f
(sequence (tok:extends (comma-sep identifier "interfaces")) id "extends")
(repeat-greedy (sequence (method-sig-no-abs SEMI_COLON) id "method signature"))))
(define class
(class-def tok:abstract (extend-dec identifier)
(implements-dec (comma-sep identifier "interfaces"))
(repeat-greedy (class-body (list field method constructor)))))
(define program
(make-program #f
(repeat-greedy import-dec)
(repeat-greedy (choose (class interface) "class or interface"))))
(define interact
(choose (field
(return-s #t)
(if-s (block #t) #f)
(assignment
(choose (identifier
(sequence (unique-base (repeat unique-end) field-access-end) id))
"assignee") EQUAL)
(block #t)
expression) "interactive program"))
)
(define-unit intermediate+access-grammar@
(import combinator-parser^ java-operators^ java-separators^ (prefix tok: java-definition-keywords^)
java-statement-keywords^ java-type-keywords^ java-ids^
java-types^ java-access^ java-ops^ general-productions^ java-variables^
expr-lits^ expr-terms+^ expr-tails^ statements^
fields^ methods^ ctors^ interfaces^ classes^ top-forms^ id^)
(export language-forms^)
(define unique-base
(choose ((literals (list null-lit boolean-lits textual-lits prim-numeric-lits double-lits))
this
identifier
new-class
simple-method-call
(sequence (O_PAREN (eta expression) C_PAREN) id)
(sequence (! (eta expression)) id "conditional expression")
(sequence (MINUS (eta expression)) id "negation expression")
(cast (value+name-type prim-type))
super-call
checks) "expression"))
(define unique-end
(choose (field-access-end
method-call-end
(binary-expression-end (bin-ops (list math-ops compare-ops bool-ops bit-ops)))
instanceof-back) "expression"))
(define expression
(sequence (unique-base (repeat-greedy unique-end)) id "expression"))
(define stmt-expr
(choose (#;new-class
super-call
simple-method-call
(sequence (unique-base (repeat unique-end) method-call-end) id "method call")
(assignment
(choose (identifier
(sequence (unique-base (repeat unique-end) field-access-end) id))
"assignee")
EQUAL)) "expression"))
(define (statement-c interact?)
(if (not interact?)
(choose ((return-s #t)
(if-s (block #t) #f)
(variable-declaration (value+name-type prim-type) expression #f #t "local variable")
(block #t)
(assignment
(choose (identifier
(sequence (unique-base (repeat unique-end) field-access-end) id))
"assignee")
EQUAL)
(sequence (stmt-expr SEMI_COLON) id)) "statement")
(choose ((return-s #t)
(if-s (block #t) #f)
(block #t)) "statement")))
(define statement (statement-c #f))
(define field (make-field access-mods (value+name-type prim-type) (eta expression) #f))
(define method-sig-no-abs
(method-signature access-mods (method-type (value+name-type prim-type))
(args (value+name-type prim-type)) #f identifier))
(define method-sig-abs
(method-signature (method-mods access-mods)
(method-type (value+name-type prim-type))
(args (value+name-type prim-type)) #f identifier))
(define method
(choose ((make-method method-sig-no-abs (repeat-greedy statement))
(method-header method-sig-abs)) "method definition"))
(define constructor
(make-constructor access-mods
(choose ((sequence (super-ctor-call (repeat-greedy statement)) id)
(sequence (this-call (repeat-greedy statement)) id)
(repeat-greedy statement)) "constructor body")
(value+name-type prim-type)))
(define interface
(interface-def
#f
(sequence (tok:extends (comma-sep identifier "interfaces")) id "extends")
(repeat-greedy (sequence (method-sig-no-abs SEMI_COLON) id "method signature"))))
(define class
(class-def tok:abstract (extend-dec identifier) (implements-dec (comma-sep identifier "interfaces"))
(repeat-greedy (class-body (list field method constructor)))))
(define program
(make-program #f (repeat-greedy import-dec)
(repeat-greedy (top-member (list class interface)))))
(define interact (choose (field expression (statement-c #t)) "interactive program"))
)
(define-unit advanced-grammar@
(import combinator-parser^ java-operators^ java-separators^ (prefix tok: java-definition-keywords^)
java-statement-keywords^ java-type-keywords^ java-ids^
java-types^ java-access^ java-ops^ general-productions^ java-variables^
expr-lits^ expr-terms+^ expr-tails^ statements^
fields^ methods^ ctors^ interfaces^ classes^ top-forms^ id^)
(export language-forms^)
(define unique-base
(choose
((literals (list null-lit boolean-lits textual-lits prim-numeric-lits double-lits))
this
IDENTIFIER
new-class
simple-method-call
(new-array (value+name-type prim-type))
(sequence (O_PAREN (eta expression) C_PAREN) id)
(sequence (! (eta expression)) id "conditional expression")
(sequence (MINUS (eta expression)) id "negation exxpression")
(cast (value+name-type prim-type))
super-call
checks) "expression"))
(define unique-end
(choose (field-access-end
array-access-end
method-call-end
if-expr-end
(binary-expression-end (bin-ops (list math-ops compare-ops bool-ops bit-ops)))
instanceof-back)
"expression"))
(define expression
(sequence (unique-base (repeat-greedy unique-end)) id "expression"))
(define stmt-expr
(choose (new-class
super-call
simple-method-call
(sequence (unique-base (repeat unique-end) method-call-end) id "method call")
(assignment
(choose (identifier
(sequence (unique-base (repeat unique-end) field-access-end) id)
(sequence (unique-base (repeat unique-end) array-access-end) id))
"asignee")
assignment-ops)
(sequence (expression ++) id "unary mutation")
(sequence (expression --) id "unary mutation")
(sequence (++ expression) id "unary mutation")
(sequence (-- expression) id "unary mutation")) "expression"))
(define (statement-c interact?)
(if interact?
(choose ((return-s #t)
(if-s (eta statement) #t)
(block #t)
(for-l (choose ((variable-declaration (array-type (value+name-type prim-type)) expression #t #f "for loop variable")
(comma-sep stmt-expr "initializations")) "for loop initialization")
#t #f
(comma-sep stmt-expr "for loop increments") #t (block #t))
(while-l (block #t))
(do-while (block #t))
(break-s #f)
(cont-s #f)
(assignment
(choose (identifier
(sequence (unique-base (repeat unique-end) field-access-end) id)
(sequence (unique-base (repeat unique-end) array-access-end) id))
"asignee")
assignment-ops)
) "statement")
(choose ((return-s #t)
(if-s (eta statement) #t)
(variable-declaration (array-type (value+name-type prim-type))
(choose (expression array-init) "variable initialization") #t #t "local variable")
(block #t)
(sequence (stmt-expr SEMI_COLON) id)
(for-l (choose ((variable-declaration (array-type (value+name-type prim-type)) expression #t #f "for loop variable")
(comma-sep stmt-expr "initializations")) "for loop initialization")
#t #f
(comma-sep stmt-expr "for loop increments") #t (block #t))
(while-l (block #t))
(do-while (block #t))
(break-s #f)
(cont-s #f)) "statement")))
(define statement (statement-c #f))
(define field (make-field (global-mods access-mods)
(array-type (value+name-type prim-type))
(eta (choose (expression array-init) "field initializer")) #f))
(define method-sig-no-abs
(method-signature (global-mods access-mods)
(method-type (array-type (value+name-type prim-type)))
(args (array-type (value+name-type prim-type))) #f IDENTIFIER))
(define method-sig-abs
(method-signature (method-mods access-mods)
(method-type (array-type (value+name-type prim-type)))
(args (array-type (value+name-type prim-type))) #f IDENTIFIER))
(define method
(choose ((make-method method-sig-no-abs (repeat-greedy statement))
(method-header method-sig-abs)) "method definition"))
(define constructor
(make-constructor access-mods
(choose ((sequence (super-ctor-call (repeat-greedy statement)) id)
(sequence (this-call (repeat-greedy statement)) id)
(repeat-greedy statement)) "constructor body")
(array-type (value+name-type prim-type))))
(define interface
(interface-def
#f
(sequence (tok:extends (comma-sep IDENTIFIER "interfaces")) id "extends")
(repeat-greedy (choose ((sequence (method-sig-no-abs SEMI_COLON) id "method header")
(make-field (global-mods access-mods)
(array-type (value+name-type prim-type))
(eta expression) #f))
"interface member definition"))))
(define class
(class-def (choose (tok:abstract tok:public) "class modifier")
(extend-dec IDENTIFIER) (implements-dec (comma-sep IDENTIFIER "interfaces"))
(repeat-greedy (class-body (list field method constructor
(method-header method-sig-abs))))))
(define program
(make-program (sequence (tok:package name SEMI_COLON) id "package specification")
(repeat-greedy import-dec)
(repeat-greedy (top-member (list class interface)))))
(define interact
(choose (field expression (statement-c #t)) "interactive program"))
)
(define-unit token@
(import java-operators^ java-separators^ java-definition-keywords^
java-statement-keywords^ java-type-keywords^ java-ids^)
(export token-proc^)
(define (old-tokens->new tok-list)
#;(!!! (printf "old-tokens->new ~a~n" (map position-token-token tok-list)))
(cond
[(null? tok-list) null]
[(eq? (token-name (position-token-token (car tok-list))) 'EOF) null]
[else
(cons
(make-position-token
(case (token-name (position-token-token (car tok-list)))
[(=) (token-EQUAL)]
((<) (token-LT))
((>) (token-GT))
((<=) (token-LTEQ))
((>=) (token-GTEQ))
((+) (token-PLUS))
((-) (token-MINUS))
((*) (token-TIMES))
((/) (token-DIVIDE))
((^) (token-^T))
((if) (token-ifT))
((do) (token-doT))
((case) (token-caseT))
((else) (token-elseT))
((void) (token-voidT))
(else (position-token-token (car tok-list))))
(position-token-start-pos (car tok-list))
(position-token-end-pos (car tok-list)))
(old-tokens->new (cdr tok-list)))]))
)
(define-signature parsers^ (parse-program))
(define-unit definition-parsers@
(import language-forms^ combinator-parser^)
(export parsers^)
(define parse-program (parser program)))
(define-unit interactions-parsers@
(import language-forms^ combinator-parser^)
(export parsers^)
(define parse-program (parser interact)))
; (define-unit full-program-parsers@
; (import language-forms^ combinator-parser^)
; (export parsers^)
;
; (define parse-beginner (parser beginner-program))
; (define parse-intermediate (parser intermediate-program))
; (define parse-intermediate+access (parser intermediate+access-program))
; (define parse-advanced (parser advanced-program))
;
; )
;
; (define-unit interaction-parsers@
; (import language-forms^ combinator-parser^)
; (export parsers^)
;
; (define parse-beginner (parser (choose (beginner-expression beginner-statement beginner-field)
; "interactions program")))
;
; (define parse-intermediate (parser (choose (intermediate-expression intermediate-statement)
; "interactions program")))
; (define parse-intermediate+access parse-intermediate)
;
; (define parse-advanced
; (parser (choose (advanced-expression advanced-statement) "interactions program")))
; )
(define-unit file-constants@
(import)
(export error-format-parameters^)
(define src? #t)
(define input-type "file")
(define show-options #f)
(define max-depth 2)
(define max-choice-depth 3))
(define-unit de-constants@
(import)
(export error-format-parameters^)
(define src? #t)
(define input-type "Definitions")
(define show-options #f)
(define max-depth 1)
(define max-choice-depth 3))
(define-unit interact-constants@
(import)
(export error-format-parameters^)
(define src? #t)
(define input-type "Interactions")
(define show-options #f)
(define max-depth 0)
(define max-choice-depth 3))
(define-unit id@
(import)
(export id^)
(define (id x . args) x))
(define-compound-unit/infer beginner-file-parser@
(import)
(export parsers^ token-proc^ err^)
(link java-dictionary@ combinator-parser-tools@ file-constants@ id@
java-terminals@ types@ mods@ operators@ general@ unqualified-java-variables@
expressions@ statements@ members@ interface@ class@ top-forms@
beginner-grammar@ token@ definition-parsers@))
(define-compound-unit/infer beginner-definitions-parser@
(import)
(export parsers^ token-proc^ err^)
(link java-dictionary@ combinator-parser-tools@ de-constants@ id@
java-terminals@ types@ mods@ operators@ general@ unqualified-java-variables@
expressions@ statements@ members@ interface@ class@ top-forms@
beginner-grammar@ token@ definition-parsers@))
(define-compound-unit/infer beginner-interactions-parsers@
(import)
(export parsers^ token-proc^ err^)
(link java-dictionary@ combinator-parser-tools@ interact-constants@ id@
java-terminals@ types@ mods@ operators@ general@ unqualified-java-variables@
expressions@ statements@ members@ interface@ class@ top-forms@
beginner-grammar@ token@ interactions-parsers@))
(define-compound-unit/infer intermediate-file-parser@
(import)
(export parsers^ token-proc^ err^)
(link java-dictionary@ combinator-parser-tools@ file-constants@ id@
java-terminals@ types@ mods@ operators@ general@ unqualified-java-variables@
expressions@ statements@ members@ interface@ class@ top-forms@
intermediate-grammar@ token@ definition-parsers@))
(define-compound-unit/infer intermediate-definitions-parser@
(import)
(export parsers^ token-proc^ err^)
(link java-dictionary@ combinator-parser-tools@ de-constants@ id@
java-terminals@ types@ mods@ operators@ general@ unqualified-java-variables@
expressions@ statements@ members@ interface@ class@ top-forms@
intermediate-grammar@ token@ definition-parsers@))
(define-compound-unit/infer intermediate-interactions-parsers@
(import)
(export parsers^ token-proc^ err^)
(link java-dictionary@ combinator-parser-tools@ interact-constants@ id@
java-terminals@ types@ mods@ operators@ general@ unqualified-java-variables@
expressions@ statements@ members@ interface@ class@ top-forms@
intermediate-grammar@ token@ interactions-parsers@))
(define-compound-unit/infer intermediate+access-file-parser@
(import)
(export parsers^ token-proc^ err^)
(link java-dictionary@ combinator-parser-tools@ file-constants@ id@
java-terminals@ types@ mods@ operators@ general@ unqualified-java-variables@
expressions@ statements@ members@ interface@ class@ top-forms@
intermediate+access-grammar@ token@ definition-parsers@))
(define-compound-unit/infer intermediate+access-definitions-parser@
(import)
(export parsers^ token-proc^ err^)
(link java-dictionary@ combinator-parser-tools@ de-constants@ id@
java-terminals@ types@ mods@ operators@ general@ unqualified-java-variables@
expressions@ statements@ members@ interface@ class@ top-forms@
intermediate+access-grammar@ token@ definition-parsers@))
(define-compound-unit/infer intermediate+access-interactions-parsers@
(import)
(export parsers^ token-proc^ err^)
(link java-dictionary@ combinator-parser-tools@ interact-constants@ id@
java-terminals@ types@ mods@ operators@ general@ unqualified-java-variables@
expressions@ statements@ members@ interface@ class@ top-forms@
intermediate+access-grammar@ token@ interactions-parsers@))
(define-compound-unit/infer advanced-file-parser@
(import)
(export parsers^ token-proc^ err^)
(link java-dictionary@ combinator-parser-tools@ file-constants@ id@
java-terminals@ types@ mods@ operators@ general@ unqualified-java-variables@
expressions@ statements@ members@ interface@ class@ top-forms@
advanced-grammar@ token@ definition-parsers@))
(define-compound-unit/infer advanced-definitions-parser@
(import)
(export parsers^ token-proc^ err^)
(link java-dictionary@ combinator-parser-tools@ de-constants@ id@
java-terminals@ types@ mods@ operators@ general@ unqualified-java-variables@
expressions@ statements@ members@ interface@ class@ top-forms@
advanced-grammar@ token@ definition-parsers@))
(define-compound-unit/infer advanced-interactions-parsers@
(import)
(export parsers^ token-proc^ err^)
(link java-dictionary@ combinator-parser-tools@ interact-constants@ id@
java-terminals@ types@ mods@ operators@ general@ unqualified-java-variables@
expressions@ statements@ members@ interface@ class@ top-forms@
advanced-grammar@ token@ interactions-parsers@))
;
(provide advanced-file-parser@ advanced-definitions-parser@ advanced-interactions-parsers@
intermediate+access-file-parser@ intermediate+access-definitions-parser@ intermediate+access-interactions-parsers@
intermediate-file-parser@ intermediate-definitions-parser@ intermediate-interactions-parsers@
beginner-file-parser@ beginner-definitions-parser@ beginner-interactions-parsers@
parsers^ token-proc^)
; (define-compound-unit/infer java-file-parsers@
; (import)
; (export parsers^ token-proc^ err^)
; (link java-dictionary@ combinator-parser-tools@ file-constants@ id@
; java-terminals@ types@ mods@ operators@ general@ unqualified-java-variables@
; expressions@ statements@ members@ interface@ class@ top-forms@
; java-grammars@ full-program-parsers@))
;
; (define-compound-unit/infer java-definitions-parsers@
; (import)
; (export parsers^ token-proc^ err^)
; (link java-dictionary@ combinator-parser-tools@ de-constants@ id@
; java-terminals@ types@ mods@ operators@ general@ unqualified-java-variables@
; expressions@ statements@ members@ interface@ class@ top-forms@
; java-grammars@ full-program-parsers@))
;
; (define-compound-unit/infer java-interactions-parsers@
; (import)
; (export parsers^ token-proc^ err^)
; (link java-dictionary@ combinator-parser-tools@ interact-constants@ id@
; java-terminals@ types@ mods@ operators@ general@ unqualified-java-variables@
; expressions@ statements@ members@ interface@ class@ top-forms@
; java-grammars@ interaction-parsers@))
;
; (provide java-definitions-parsers@ java-interactions-parsers@ parsers^ token-proc^)
)
| false |
52c9c0e5343ea976045f5a64ca43157d3a1a9fe1 | 08515a0f79a475b3c6b4459c2b2f6067fd8fce1e | /Homeworks/Problem Set 7/problemSet7.rkt | 88fc232673dea0d171086bd516491a4f8b37d63b | []
| no_license | AlbMej/CSE-1729-Introduction-to-Principles-of-Programming | ce15bcc716bdcdfe72f5e894f812df844c04d683 | 49acc5b34e54eb55bc32670ce87222d71e09f071 | refs/heads/master | 2021-06-12T05:48:37.728863 | 2021-04-25T05:08:56 | 2021-04-25T05:08:56 | 172,804,634 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 5,837 | rkt | problemSet7.rkt | "Problem 1"
(define (make-tree value left right ) (list value left right ))
(define (value tree ) (car tree ))
(define (left tree ) (cadr tree ))
(define (right tree ) (caddr tree ))
(define example (list #\+ (list #\*
(list 4 '() '())
(list 5 '() '()))
(list #\+
(list #\/ (list 6 '() '()) '())
(list 7 '() '()))))
(define example2 (list #\+ (list #\*
(list 2 '() '())
(list 3 '() '()))
(list #\*
(list #\+
(list 4 '() '())
(list #\- (list 5 '() '()) '()))
(list #\/ (list 6 '() '()) '()))))
(define (nvalue T)
(cond ((null? T) (value T))
((number? (value T)) (value T))
((eq? (value T) #\+) (+ (nvalue (left T)) (nvalue (right T)) ))
((eq? (value T) #\*) (* (nvalue (left T)) (nvalue (right T)) ))
((eq? (value T) #\/) (/ (nvalue (left T))) )
((eq? (value T) #\-) (* -1 (nvalue (left T)) ))))
(nvalue example)
"Problem 2a"
(define (prepare x )
(cond ((number? x) (number->string x ))
((char? x) (string x ))))
(define (prefix T)
(if (null? T) ""
(string-append (prepare (value T))
(prefix (left T))
(prefix (right T)))))
(prefix example)
"Problem 2b"
(define (postfix T)
(if (null? T) ""
(string-append (postfix (left T))
(postfix (right T))
(prepare (value T)))))
(postfix example)
"Problem 2c"
(define (infix T)
(cond
((eq? (value T) #\/)
(string-append "(1/" (infix (left T)) ")"))
((eq? (value T) #\-)
(string-append "(-" (infix (left T)) ")"))
((eq? (value T) #\+)
(string-append "(" (infix (left T)) "+" (infix (right T)) ")"))
((eq? (value T) #\*)
(string-append "(" (infix (left T)) "*" (infix (right T)) ")"))
(else (prepare (value T)))))
(infix example)
(infix example2)
"Problem 3a"
( define testtree ( make-tree 1
( make-tree 3
( make-tree 7 '() '())
( make-tree 9 '() '()))
( make-tree 5 '() '())))
( define testtree2 ( make-tree 1
( make-tree 9
( make-tree 7 '() '())
( make-tree 10 '() '()))
( make-tree 7 '() '())))
(define (bst-element? item bs-tree)
(cond ((null? bs-tree) #f)
((string=? item (value bs-tree)) #t)
(else (or (bst-element? item (left bs-tree)) (bst-element? item (right bs-tree))) )))
;(bst-element? 60 testtree)
"Problem 3b"
(define (bst-insert item bs-tree)
(cond ((null? bs-tree) (make-tree item '() '()))
((eq? item (value bs-tree)) bs-tree)
((string<? item (value bs-tree)) (make-tree (value bs-tree)
(bst-insert item (left bs-tree))
(right bs-tree)))
((string>? item (value bs-tree)) (make-tree (value bs-tree)
(left bs-tree)
(bst-insert item (right bs-tree))))))
;(bst-insert 12 testtree)
"Problem 3c"
(define (bst-smallest bs-tree)
(cond ((null? bs-tree) 'undefined)
((null? (left bs-tree)) (value bs-tree))
(else (bst-smallest (left bs-tree)))))
(bst-smallest testtree)
"Problem 3d"
(define (bst-largest bs-tree)
(cond ((null? bs-tree) 'undefined)
((null? (right bs-tree)) (value bs-tree))
(else (bst-largest (right bs-tree)))))
(bst-largest testtree)
"Problem 3e"
(define (bst-equal? tree1 tree2)
(cond ((and (null? tree1) (null? tree2)) #t)
((or (null? tree1) (null? tree2)) #f)
(else (and (string=? (value tree1) (value tree2))
(bst-equal? (left tree1) (left tree2))
(bst-equal? (right tree1) (right tree2))))))
;(bst-equal? testtree (make-tree '() '() '()))
"Problem 3f"
(define (bst-subset? bst1 bst2)
(if (null? bst1)
#t
(and (bst-element? (value bst1) bst2)
(bst-subset? (left bst1) bst2)
(bst-subset? (right bst1) bst2))))
;(bst-subset? testtree testtree2)
"Problem 3g"
(define (bst-set-equal? bst1 bst2)
(and (bst-subset? bst1 bst2) (bst-subset? bst2 bst1)))
;(bst-set-equal? testtree testtree2)
;(bst-set-equal? (make-tree '() '() '()) testtree)
;(bst-set-equal? (make-tree '() '() '()) (make-tree '() '() '()))
;(bst-set-equal? testtree (make-tree '() '() '()))
"Problem 4a"
(define (bst-delete-min bst)
(cond ((null? bst) bst)
((null? (left bst)) (right bst) )
(else (make-tree (value bst) (bst-delete-min (left bst)) (right bst) ))))
(bst-delete-min testtree)
"Problem 4b"
(define (bst-delete-max bst)
(cond ((null? bst) bst)
((null? (right bst)) (left bst) )
(else (make-tree (value bst) (left bst) (bst-delete-max (right bst)) ))))
(bst-delete-max testtree)
"Problem 4c"
(define (bst-delete val bst)
(cond ((null? bst) '())
((and (null? (left bst)) (null? (right bst)) (string=? val (value bst))) '() )
((string>? val (value bst)) (make-tree (value bst) (left bst) (bst-delete val (right bst))))
((string<? val (value bst)) (make-tree (value bst) (bst-delete val (left bst)) (right bst)))
((string=? val (value bst)) (make-tree (bst-smallest (right bst)) (left bst) (bst-delete-min (right bst))))
(else bst)))
;(bst-delete 9 testtree)
| false |
3d555286a20175bd7df3db30241129cc042cbd35 | 0caa2ba3919d4c4572516e1df64d8e7d92ac2f3b | /private/flip-intro-scope.rkt | f946ad3b40c8b3c699c15f6af7c67dfec25f0552 | [
"MIT"
]
| permissive | michaelballantyne/ee-lib | c734e5bbb9b4da893e4a2f7c7919e7625d6a1a62 | 104af4c1daf5e61ac79593d76c9df6ea80b34ebe | refs/heads/master | 2023-07-22T01:08:48.261384 | 2023-04-19T01:35:12 | 2023-04-19T01:35:12 | 192,628,953 | 14 | 3 | MIT | 2023-07-18T22:15:07 | 2019-06-19T00:14:34 | Racket | UTF-8 | Racket | false | false | 438 | rkt | flip-intro-scope.rkt | #lang racket/base
(provide flip-intro-scope)
(require racket/private/check)
(define (make-intro-scope-introducer)
(define no-scope (datum->syntax #f 'foo))
(define intro-scope
(syntax-local-identifier-as-binding
(syntax-local-introduce
no-scope)))
(make-syntax-delta-introducer
intro-scope
no-scope))
(define/who (flip-intro-scope stx)
(check who syntax? stx)
((make-intro-scope-introducer) stx 'flip))
| false |
161f807550214286b92a7199af3a63a8a646a9d6 | ed81f401dcd2ce0399cec3a99b6e5851e62e74ca | /data/github.com/racket/scribble/b67f265b93e74a2a525173449c6febc02c04d57a/scribble-doc/scribblings/scribble/tag.scrbl | 65d8238250c3f44e1591f7290232d35e9275d6b6 | [
"MIT"
]
| permissive | smola/language-dataset | 9e2a35340d48b497cd9820fa2673bb5d482a13f7 | 4d1827d1018b922e03a48a5de5cb921a6762dda3 | refs/heads/master | 2023-03-10T12:42:04.396308 | 2022-07-15T18:05:05 | 2022-07-15T18:05:05 | 143,737,125 | 18 | 3 | MIT | 2023-03-06T05:01:14 | 2018-08-06T14:05:52 | Python | UTF-8 | Racket | false | false | 5,369 | scrbl | tag.scrbl | #lang scribble/doc
@(require scribble/manual "utils.rkt"
(for-label setup/main-collects))
@title[#:tag "tag"]{Tag Utilities}
@declare-exporting[scribble/tag scribble/base]
@defmodule*/no-declare[(scribble/tag)]{The @racketmodname[scribble/tag]
library provides utilities for constructing cross-reference
@tech{tags}. The library is re-exported by
@racketmodname[scribble/base].}
@; ------------------------------------------------------------------------
@defproc[(make-section-tag [name string?]
[#:doc doc-mod-path (or/c module-path? #f) #f]
[#:tag-prefixes tag-prefixes (or/c #f (listof string?)) #f])
tag?]{
Forms a @tech{tag} that refers to a section whose ``tag'' (as provided
by the @racket[#:tag] argument to @racket[section], for example) is
@racket[name]. If @racket[doc-mod-path] is provided, the @tech{tag}
references a section in the document implemented by
@racket[doc-mod-path] from outside the document. Additional tag
prefixes (for intermediate sections, typically) can be provided as
@racket[tag-prefixes].}
@defproc[(make-module-language-tag [lang symbol?]) tag?]{
Forms a @tech{tag} that refers to a section
that contains @racket[defmodulelang] for the language
@racket[lang].
}
@defproc[(taglet? [v any/c]) boolean?]{
Returns @racket[#t] if @racket[v] is a @tech{taglet}, @racket[#f]
otherwise.
A @deftech{taglet} is a value that can be combined with a symbol via
@racket[list] to form a @tech{tag}, but that is not a
@racket[generated-tag]. A @tech{taglet} is therefore useful as a piece
of a @tech{tag}, and specifically as a piece of a tag that can gain a
prefix (e.g., to refer to a section of a document from outside the
document).}
@defproc*[([(doc-prefix [mod-path (or/c #f module-path?)]
[taglet taglet?])
taglet?]
[(doc-prefix [mod-path (or/c #f module-path?)]
[extra-prefixes (or/c #f (listof taglet?))]
[taglet taglet?])
taglet?])]{
Converts part of a cross-reference @tech{tag} that would work within a
document implemented by @racket[mod-path] to one that works from
outside the document, assuming that @racket[mod-path] is not
@racket[#f]. That is, @racket[mod-path] is converted to a
@tech{taglet} and added as prefix to an existing @racket[taglet].
If @racket[extra-prefixes] is provided, then its content is added as a
extra prefix elements before the prefix for @racket[mod-path] is
added. A @racket[#f] value for @racket[extra-prefixes] is equivalent
to @racket['()].
If @racket[mod-path] is @racket[#f], then @racket[taglet] is returned
without a prefix (except adding @racket[extra-prefixes], if provided).}
@defproc[(module-path-prefix->string [mod-path module-path?]) string?]{
Converts a module path to a string by resolving it to a path, and
using @racket[path->main-collects-relative].}
@defproc[(module-path-index->taglet [mpi module-path-index?]) taglet?]{
Converts a module path index to a @tech{taglet}---a normalized
encoding of the path as an S-expression---that is interned via
@racket[intern-taglet].
The string form of the @tech{taglet} is used as prefix in a @tech{tag}
to form cross-references into the document that is implemented by the
module referenced by @racket[mpi].}
@defproc[(intern-taglet [v any/c]) any/c]{
Returns a value that is @racket[equal?] to @racket[v], where multiple
calls to @racket[intern-taglet] for @racket[equal?] @racket[v]s
produce the same (i.e., @racket[eq?]) value.}
@defproc[(definition-tag->class/interface-tag [definition-tag definition-tag?])
class/interface-tag?]{
Constructs a tag like @racket[definition-tag], except that
it matches documentation for the class. If @racket[definition-tag]
doesn't document a class or interface, this function still returns
the tag that the class or interface documentation would have had,
as if @racket[definition-tag] had documented a class or interface.
@history[#:added "1.11"]
}
@defproc[(class/interface-tag->constructor-tag [class/interface-tag class/interface-tag?])
constructor-tag?]{
Constructs a tag like @racket[definition-tag], except that
it matches documentation for the constructor of the class.
@history[#:added "1.11"]
}
@defproc[(get-class/interface-and-method [method-tag method-tag?])
(values symbol? symbol?)]{
Returns the class name and method name (respectively) for the method documented
by the docs at @racket[method-tag].
@history[#:added "1.11"]
}
@defproc[(definition-tag? [v any/c]) boolean?]{
Recognizes definition tags. If @racket[(definition-tag? _v)] is
@racket[#t], then so is @racket[(tag? _v)].
@history[#:added "1.11"]
}
@defproc[(class/interface-tag? [v any/c]) boolean?]{
Recognizes class or interface tags. If @racket[(class/interface-tag? _v)] is
@racket[#t], then so is @racket[(tag? _v)].
@history[#:added "1.11"]
}
@defproc[(method-tag? [v any/c]) boolean?]{
Recognizes method tags. If @racket[(method-tag? _v)] is
@racket[#t], then so is @racket[(tag? _v)].
@history[#:added "1.11"]
}
@defproc[(constructor-tag? [v any/c]) boolean?]{
Recognizes class constructor tags. If @racket[(constructor-tag? _v)] is
@racket[#t], then so is @racket[(tag? _v)].
@history[#:added "1.11"]
}
| false |
641417d7efd7178b5106778b89c77cbad1f58525 | c31f57f961c902b12c900ad16e5390eaf5c60427 | /data/programming_languages/scheme/rg.rkt | ad3f9d43b902ebafe970df2e894e2b14a5bd8cf0 | []
| no_license | klgraham/deep-learning-with-pytorch | ccc7602d9412fb335fe1411ba31641b9311a4dba | 4373f1c8be8e091ea7d4afafc81dd7011ef5ca95 | refs/heads/master | 2022-10-24T01:48:46.160478 | 2017-03-13T20:07:03 | 2017-03-13T20:07:03 | 79,877,434 | 0 | 1 | null | 2022-10-02T20:42:36 | 2017-01-24T04:12:24 | C | UTF-8 | Racket | false | false | 33,424 | rkt | rg.rkt | #lang racket/base
(require "matcher.rkt"
"lang-struct.rkt"
"reduction-semantics.rkt"
"underscore-allowed.rkt"
"error.rkt"
"struct.rkt"
"match-a-pattern.rkt"
(for-syntax "reduction-semantics.rkt")
racket/list
racket/dict
racket/contract
racket/promise
racket/unit
racket/match
mrlib/tex-table)
(define redex-pseudo-random-generator
(make-parameter (current-pseudo-random-generator)))
(define (generator-random . arg)
(parameterize ([current-pseudo-random-generator (redex-pseudo-random-generator)])
(apply random arg)))
(define (exotic-choice? [random generator-random]) (= 0 (random 5)))
(define (use-lang-literal? [random generator-random]) (= 0 (random 20)))
(define default-check-attempts (make-parameter 1000))
(define ascii-chars-threshold 1000)
(define tex-chars-threshold 1500)
(define chinese-chars-threshold 2500)
(define (pick-var lang-lits attempt [random generator-random])
(let ([length (add1 (random-natural 4/5 random))])
(string->symbol (random-string lang-lits length attempt random))))
(define (pick-char attempt [random generator-random])
(cond [(or (< attempt ascii-chars-threshold) (not (exotic-choice? random)))
(let ([i (random (add1 (- (char->integer #\z) (char->integer #\a))))]
[cap? (zero? (random 2))])
(integer->char (+ i (char->integer (if cap? #\A #\a)))))]
[(or (< attempt tex-chars-threshold) (not (exotic-choice? random)))
(let ([i (random (- #x7E #x20 1))]
[_ (- (char->integer #\_) #x20)])
(integer->char (+ #x20 (if (= i _) (add1 i) i))))]
[(or (< attempt chinese-chars-threshold) (not (exotic-choice? random)))
(car (string->list (pick-from-list (map cadr tex-shortcut-table) random)))]
[else
(integer->char (+ #x4E00 (random (- #x9FCF #x4E00))))]))
(define (random-string lang-lits length attempt [random generator-random])
(if (and (not (null? lang-lits)) (use-lang-literal? random))
(pick-from-list lang-lits random)
(list->string (build-list length (λ (_) (pick-char attempt random))))))
(define (pick-any lang sexp [random generator-random])
(if (and (> (dict-count (rg-lang-non-cross lang)) 0) (zero? (random 5)))
(let ([nts (rg-lang-non-cross lang)])
(values lang (pick-from-list (dict-map nts (λ (nt _) nt)) random)))
(values sexp 'sexp)))
(define (pick-string lang-lits attempt [random generator-random])
(random-string lang-lits (random-natural 1/5 random) attempt random))
;; next-non-terminal-decision selects a subset of a non-terminal's productions.
;; This implementation, the default, chooses them all, but many of the
;; generator's test cases restrict the productions.
(define pick-nts values)
(define (pick-from-list l [random generator-random])
(define len (length l))
(cond
[(= len 1)
;; don't invoke random in this case, so we avoid perturbing the
;; random generator's state when there are is no choice to make
(car l)]
[else (list-ref l (random len))]))
;; Chooses a random (exact) natural number from the "shifted" geometric distribution:
;; P(random-natural = k) = p(1-p)^k
;;
;; P(random-natural >= k) = (1-p)^(k+1)
;; E(random-natural) = (1-p)/p
;; Var(random-natural) = (1-p)/p^2
(define (random-natural p [random generator-random])
(sub1 (inexact->exact (ceiling (real-part (/ (log (random)) (log (- 1 p))))))))
(define (negative? random)
(zero? (random 2)))
(define (random-integer p [random generator-random])
(* (if (negative? random) -1 1) (random-natural p random)))
(define (random-rational p [random generator-random])
(/ (random-integer p random) (add1 (random-natural p random))))
(define (random-real p [random generator-random])
(* (random) 2 (random-integer p random)))
(define (random-complex p [random generator-random])
(let ([randoms (list random-integer random-rational random-real)])
(make-rectangular ((pick-from-list randoms random) p random)
((pick-from-list randoms random) p random))))
(define integer-threshold 100)
(define rational-threshold 500)
(define real-threshold 1000)
(define complex-threshold 2000)
(define default-retries 100)
(define retry-threshold (max chinese-chars-threshold complex-threshold))
(define proportion-before-threshold 9/10)
(define proportion-at-size 1/10)
(define post-threshold-incr 50)
;; Determines the parameter p for which random-natural's expected value is E
(define (expected-value->p E)
;; E = 0 => p = 1, which breaks random-natural
(/ 1 (+ (max 1 E) 1)))
; Determines a size measure for numbers, sequences, etc., using the
; attempt count.
(define default-attempt-size
(λ (n) (inexact->exact (floor (/ (log (add1 n)) (log 5))))))
(define attempt-size/c
(-> natural-number/c natural-number/c))
(define attempt->size
(make-parameter default-attempt-size))
(define (pick-number attempt #:top-threshold [top-threshold complex-threshold] [random generator-random])
(let loop ([threshold 0]
[generator random-natural]
[levels `((,integer-threshold . ,random-integer)
(,rational-threshold . ,random-rational)
(,real-threshold . ,random-real)
(,complex-threshold . ,random-complex))])
(if (or (null? levels)
(< attempt (caar levels))
(< top-threshold (caar levels))
(not (exotic-choice? random)))
(generator (expected-value->p ((attempt->size) (- attempt threshold))) random)
(loop (caar levels) (cdar levels) (cdr levels)))))
(define (pick-natural attempt [random generator-random])
(pick-number attempt #:top-threshold 0 random))
(define (pick-integer attempt [random generator-random])
(pick-number attempt #:top-threshold integer-threshold random))
(define (pick-real attempt [random generator-random])
(pick-number attempt #:top-threshold real-threshold random))
(define (pick-boolean attempt [random generator-random])
(zero? (random 2)))
(define (pick-sequence-length size)
(random-natural (expected-value->p size)))
(define (min-prods nt prods base-table)
(let* ([sizes (hash-ref base-table nt)]
[min-size (apply min/f sizes)])
(map cadr (filter (λ (x) (equal? min-size (car x))) (map list sizes prods)))))
(define-struct rg-lang (non-cross delayed-cross base-cases))
(define (rg-lang-cross x) (force (rg-lang-delayed-cross x)))
(define (prepare-lang lang)
(values lang
(map symbol->string (compiled-lang-literals lang))
(find-base-cases lang)))
(define-struct (exn:fail:redex:generation-failure exn:fail:redex) ())
(define (raise-gen-fail who what attempts)
(let ([str (format "~a: unable to generate ~a in ~a attempt~a"
who what attempts (if (= attempts 1) "" "s"))])
(raise (make-exn:fail:redex:generation-failure str (current-continuation-marks)))))
(define (compile lang what)
(define-values/invoke-unit (generation-decisions)
(import) (export decisions^))
(define (gen-nt lang name cross? retries size attempt filler)
(define productions
(hash-ref ((if cross? rg-lang-cross rg-lang-non-cross) lang) name))
(define-values (term _)
(let ([gen (pick-from-list
(if (zero? size)
(min-prods name productions
((if cross? base-cases-cross base-cases-non-cross)
(rg-lang-base-cases lang)))
((next-non-terminal-decision) productions)))])
(gen retries (max 0 (sub1 size)) attempt empty-env filler)))
term)
(define (generate/pred name gen pred init-sz init-att retries)
(define pre-threshold-incr
(ceiling
(/ (- retry-threshold init-att)
(* proportion-before-threshold (add1 retries)))))
(define (incr-size? remain)
(zero?
(modulo (sub1 remain)
(ceiling (* proportion-at-size retries)))))
(let retry ([remaining (add1 retries)]
[size init-sz]
[attempt init-att])
(if (zero? remaining)
(raise-gen-fail what (format "pattern ~s" name) retries)
(let-values ([(term env) (gen size attempt)])
(if (pred term env)
(values term env)
(retry (sub1 remaining)
(if (incr-size? remaining) (add1 size) size)
(+ attempt
(if (>= attempt retry-threshold)
post-threshold-incr
pre-threshold-incr))))))))
(define (generate/prior name env gen)
(let* ([none (gensym)]
[prior (hash-ref env name none)])
(if (eq? prior none)
(let-values ([(term env) (gen)])
(values term (hash-set env name term)))
(values prior env))))
(define (generate-sequence gen env vars length)
(define (split-environment env)
(foldl (λ (var seq-envs)
(cond
[(mismatch? var) seq-envs]
[else
(define vals (hash-ref env var #f))
(if vals
(map (λ (seq-env val) (hash-set seq-env var val)) seq-envs vals)
seq-envs)]))
(build-list length (λ (_) #hash())) vars))
(define (merge-environments seq-envs)
(foldl (λ (var env)
(define list-of-vals (map (λ (seq-env) (hash-ref seq-env var)) seq-envs))
(cond
[(mismatch? var)
(define existing (hash-ref env var '()))
(hash-set env var (apply append existing list-of-vals))]
[else
(hash-set env var list-of-vals)]))
env vars))
(define-values (seq envs)
(let recur ([envs (split-environment env)])
(if (null? envs)
(values null null)
(let*-values
([(hd env) (gen (car envs))]
[(tl envs) (recur (cdr envs))])
(values (cons hd tl) (cons env envs))))))
(values seq (merge-environments envs)))
(define ((generator/attempts g) r s a e f)
(values (g a) e))
(define (mismatches-satisfied? env)
(define groups (make-hasheq))
(define (get-group group)
(hash-ref groups group
(λ ()
(let ([vals (make-hash)])
(hash-set! groups group vals)
vals))))
(for/and ([(name val) (in-hash env)]
#:when (mismatch? name))
(= (length (remove-duplicates val))
(length val))))
(define empty-env #hash())
(define (bindings env)
(make-bindings
(for/fold ([bindings null]) ([(key val) (in-hash env)])
(if (symbol? key)
(cons (make-bind key val) bindings)
bindings))))
(define-values (langp lits lang-bases) (prepare-lang lang))
(define-values (sexpp _ sexp-bases) (prepare-lang sexp))
(define lit-syms (compiled-lang-literals lang))
(define (compile pat any?)
(define vars-table (make-hash))
(define (find-vars pat) (hash-ref vars-table pat '()))
(define-values (rewritten-pat vars)
(let loop ([pat pat])
(define (add/ret pat vars)
(hash-set! vars-table pat vars)
(values pat vars))
(match-a-pattern pat
[`any (values pat '())]
[`number (values pat '())]
[`string (values pat '())]
[`natural (values pat '())]
[`integer (values pat '())]
[`real (values pat '())]
[`boolean (values pat '())]
[`variable (values pat '())]
[`(variable-except ,vars ...) (values pat '())]
[`(variable-prefix ,var) (values pat '())]
[`variable-not-otherwise-mentioned (values pat '())]
[`hole (values pat '())]
[`(nt ,x) (values pat '())]
[`(name ,name ,p)
(define-values (p-rewritten p-names) (loop p))
(add/ret `(name ,name ,p-rewritten) (cons name p-names))]
[`(mismatch-name ,name ,p)
(define mm (make-mismatch name))
(define-values (p-rewritten p-names) (loop p))
(add/ret `(mismatch-name ,mm ,p-rewritten)
(cons mm p-names))]
[`(in-hole ,p1 ,p2)
(define-values (p1-rewritten p1-names) (loop p1))
(define-values (p2-rewritten p2-names) (loop p2))
(add/ret `(in-hole ,p1-rewritten ,p2-rewritten)
(append p1-names p2-names))]
[`(hide-hole ,p)
(define-values (p-rewritten p-names) (loop p))
(add/ret `(hide-hole ,p-rewritten) p-names)]
[`(side-condition ,p ,e ,e2)
(define-values (p-rewritten p-names) (loop p))
(add/ret `(side-condition ,p-rewritten ,e ,e2) p-names)]
[`(cross ,var) (values pat '())]
[`(list ,lpats ...)
(define-values (lpats-rewritten vars)
(for/fold ([ps-rewritten '()]
[vars '()])
([lpat (in-list lpats)])
(match lpat
[`(repeat ,p ,name ,mismatch-name)
(define l1 (if name (list name) '()))
(define mm (and mismatch-name (make-mismatch mismatch-name)))
(define l2 (if mm (cons mm l1) l1))
(define-values (p-rewritten p-vars) (loop p))
(values (cons `(repeat ,p-rewritten ,name ,mm) ps-rewritten)
(append l2 p-vars vars))]
[_
(define-values (p-rewritten p-vars) (loop lpat))
(values (cons p-rewritten ps-rewritten)
(append p-vars vars))])))
(add/ret `(list ,@(reverse lpats-rewritten))
vars)]
[(? (compose not pair?)) (values pat '())])))
(let* ([nt? (is-nt? (if any? sexpp langp))]
[mismatches? #f]
[generator
; retries size attempt env filler -> (values terms env)
;
; Patterns like (in-hole C_1 p) require constructing both an unfilled context
; (exposed via the C_1 binding) and a filled context (exposed as the result).
; A generator constructs both by constructing the context, using either
; `the-hole' or `the-not-hole' as appropriate, then filling it using `plug'.
; Before returning its result, a generator replaces occurrences of `the-not-hole'
; with `the-hole' to avoid exposing the distinction to the user, but
; `the-not-hole' remains in bindings supplied to side-condition predicates, to
; match the behavior of the matcher.
;
; Repeated traversals via `plug' are not asymptotically worse than simultaneously
; constructing the filled and unfilled pattern, due to languages like this one,
; which names contexts in a way that prevents any sharing.
; (define-language L
; (W hole
; ; extra parens to avoid matcher loop
; (in-hole (W_1) (+ natural hole))))
(let recur ([pat rewritten-pat])
(match-a-pattern pat
[`any
(λ (r s a e f)
(let*-values ([(lang nt) ((next-any-decision) langc sexpc)]
[(term) (gen-nt lang nt #f r s a the-not-hole)])
(values term e)))]
[`number (generator/attempts (λ (a) ((next-number-decision) a)))]
[`string (generator/attempts (λ (a) ((next-string-decision) lits a)))]
[`natural (generator/attempts (λ (a) ((next-natural-decision) a)))]
[`integer (generator/attempts (λ (a) ((next-integer-decision) a)))]
[`real (generator/attempts (λ (a) ((next-real-decision) a)))]
[`boolean (generator/attempts (λ (a) ((next-boolean-decision) a)))]
[`variable (generator/attempts (λ (a) ((next-variable-decision) lits a)))]
[`(variable-except ,vars ...)
(let ([g (recur 'variable)])
(λ (r s a e f)
(generate/pred pat
(λ (s a) (g r s a e f))
(λ (var _) (not (memq var vars)))
s a r)))]
[`(variable-prefix ,prefix)
(define (symbol-append prefix suffix)
(string->symbol (string-append (symbol->string prefix) (symbol->string suffix))))
(let ([g (recur 'variable)])
(λ (r s a e f)
(let-values ([(t e) (g r s a e f)])
(values (symbol-append prefix t) e))))]
[`variable-not-otherwise-mentioned
(let ([g (recur 'variable)])
(λ (r s a e f)
(generate/pred pat
(λ (s a) (g r s a e f))
(λ (var _) (not (memq var lit-syms)))
s a r)))]
[`hole (λ (r s a e f) (values f e))]
[`(nt ,nt-id)
(λ (r s a e f)
(values (gen-nt (if any? sexpc langc) nt-id #f r s a f) e))]
[`(name ,id ,p)
(let ([g (recur p)])
(λ (r s a e f)
(generate/prior id e (λ () (g r s a e f)))))]
[`(mismatch-name ,id ,pat)
(let ([g (recur pat)])
(set! mismatches? #t)
(λ (r s a e f)
(let-values ([(t e) (g r s a e f)])
(values t (hash-set e id (cons t (hash-ref e id '())))))))]
[`(in-hole ,context ,filler)
(let ([c-context (recur context)]
[c-filler (recur filler)])
(λ (r s a e f)
(let*-values ([(filler env) (c-filler r s a e f)]
[(context env) (c-context r s a env the-hole)])
(values (plug context filler) env))))]
[`(hide-hole ,pattern)
(let ([g (recur pattern)])
(λ (r s a e f)
(g r s a e the-not-hole)))]
[`(side-condition ,pat ,(? procedure? condition) ,guard-src-loc)
(let ([g (recur pat)])
(λ (r s a e f)
(generate/pred `(side-condition ,(unparse-pattern pat) ,guard-src-loc)
(λ (s a) (g r s a e f))
(λ (_ env) (condition (bindings env)))
s a r)))]
[`(cross ,(? symbol? p))
(λ (r s a e f)
(values (gen-nt (if any? sexpc langc) p #t r s a f) e))]
[`(list ,in-lpats ...)
(let loop ([lpats in-lpats])
(match lpats
[`() (λ (r s a e f) (values '() e))]
[(cons `(repeat ,sub-pat ,name ,mismatch-name) rst)
(let ([elemg (recur sub-pat)]
[tailg (loop rst)]
[vars (find-vars sub-pat)])
(when mismatch-name
(set! mismatches? #t))
(λ (r s a env0 f)
(define len
(let ([prior (and name (hash-ref env0 name #f))])
(if prior
prior
(if (zero? s) 0 ((next-sequence-decision) s)))))
(let*-values ([(seq env) (generate-sequence (λ (e) (elemg r s a e f)) env0 vars len)]
[(env) (if name (hash-set env name len) env)]
[(env) (if mismatch-name
(hash-set env mismatch-name (list len))
env)]
[(tail env) (tailg r s a env f)])
(values (append seq tail) env))))]
[(cons hdp tlp)
(let ([hdg (recur hdp)]
[tlg (loop tlp)])
(λ (r s a env f)
(let*-values
([(hd env) (hdg r s a env f)]
[(tl env) (tlg r s a env f)])
(values (cons hd tl) env))))]))]
[(? (compose not pair?))
(λ (r s a e f) (values pat e))]))])
(if mismatches?
(λ (r s a e f)
(let ([g (λ (s a) (generator r s a e f))]
[p? (λ (_ e) (mismatches-satisfied? e))])
(generate/pred (unparse-pattern pat) g p? s a r)))
generator)))
(define (compile-non-terminals nts any?)
(make-immutable-hash
(map (λ (nt) (cons (nt-name nt)
(map (λ (p) (compile (rhs-pattern p) any?))
(nt-rhs nt))))
nts)))
(define (compile-language lang bases any?)
(make-rg-lang
(compile-non-terminals (compiled-lang-lang lang) any?)
(delay (compile-non-terminals (compiled-lang-cclang lang) any?))
bases))
(define langc (compile-language langp lang-bases #f))
(define sexpc (compile-language sexpp sexp-bases #t))
(define (compile-pattern pat) (compile pat #f))
(λ (pat)
(define g (compile-pattern pat))
(λ (size attempt retries)
(define-values (t e) (g retries size attempt empty-env the-hole))
(values (let replace-the-not-hole ([t t])
(cond [(eq? t the-not-hole) the-hole]
[(list? t) (map replace-the-not-hole t)]
[else t]))
(bindings e)))))
(define-struct base-cases (delayed-cross non-cross))
(define (base-cases-cross x) (force (base-cases-delayed-cross x)))
;; find-base-cases : (list/c nt) -> base-cases
(define (find-base-cases lang)
(define nt-table (make-hash))
(define changed? #f)
(define (nt-get nt) (hash-ref nt-table nt 'inf))
(define (nt-set nt new)
(let ([old (nt-get nt)])
(unless (equal? new old)
(set! changed? #t)
(hash-set! nt-table nt new))))
(define ((process-nt cross?) nt)
(nt-set (cons cross? (nt-name nt)) (apply min/f (map process-rhs (nt-rhs nt)))))
(define (process-rhs rhs)
(let ([nts (rhs->nts (rhs-pattern rhs))])
(if (null? nts)
0
(add1/f (apply max/f (map nt-get nts))))))
;; rhs->path : pattern -> (listof (cons/c boolean symbol))
;; determines all of the non-terminals in a pattern
(define (rhs->nts pat)
(let ([nts '()])
(let loop ([pat pat])
(match-a-pattern pat
[`any (void)]
[`number (void)]
[`string (void)]
[`natural (void)]
[`integer (void)]
[`real (void)]
[`boolean (void)]
[`variable (void)]
[`(variable-except ,vars ...) (void)]
[`(variable-prefix ,var) (void)]
[`variable-not-otherwise-mentioned (void)]
[`hole (void)]
[`(nt ,var) (set! nts (cons (cons #f var) nts))]
[`(name ,n ,p) (loop p)]
[`(mismatch-name ,n ,p) (loop p)]
[`(in-hole ,p1 ,p2) (loop p1) (loop p2)]
[`(hide-hole ,p) (loop p)]
[`(side-condition ,p ,exp ,info) (loop p)]
[`(cross ,x-nt)
(set! nts (cons (cons #t x-nt) nts))]
[`(list ,lpats ...)
(for ([lpat (in-list lpats)])
(match lpat
[`(repeat ,p ,name ,mismatch?)
(loop p)]
[_ (loop lpat)]))]
[(? (compose not pair?)) (void)]))
nts))
;; build-table : (listof nt) -> hash
(define (build-table nts)
(let ([tbl (make-hasheq)])
(for-each
(λ (nt) (hash-set! tbl (nt-name nt) (map process-rhs (nt-rhs nt))))
nts)
tbl))
;; we can delay the work of computing the base cases for
;; the cross part of the language since none of the productions
;; refer to it (as that's not allowed in general and would be
;; quite confusing if it were...)
(let loop ()
(set! changed? #f)
(for-each (process-nt #f) (compiled-lang-lang lang))
(when changed?
(loop)))
(make-base-cases
(delay (begin
(let loop ()
(set! changed? #f)
(for-each (process-nt #t) (compiled-lang-cclang lang))
(when changed?
(loop)))
(build-table (compiled-lang-cclang lang))))
(build-table (compiled-lang-lang lang))))
(define min/f
(case-lambda
[(a) a]
[(a b)
(cond
[(eq? a 'inf) b]
[(eq? b 'inf) a]
[else (min a b)])]
[(a b . c) (min/f a (apply min/f b c))]))
(define max/f
(case-lambda
[(a) a]
[(a b)
(cond
[(eq? a 'inf) a]
[(eq? b 'inf) b]
[else (max a b)])]
[(a b . c) (max/f a (apply max/f b c))]))
(define (add1/f a) (if (eq? a 'inf) 'inf (+ a 1)))
;; is-nt? : compiled-lang any -> boolean
(define ((is-nt? lang) x)
(and (hash-ref (compiled-lang-ht lang) x #f) #t))
;; built-in? : any -> boolean
(define (built-in? x)
(and (memq x underscore-allowed) #t))
;; nt-by-name : lang symbol boolean -> nt
(define (nt-by-name lang name cross?)
(findf (λ (nt) (eq? name (nt-name nt)))
(if cross?
(compiled-lang-cclang lang)
(compiled-lang-lang lang))))
(define named-nt-rx #rx"^([^_]+)_[^_]*$")
(define mismatch-nt-rx #rx"([^_]+)_!_[^_]*$")
(define named-ellipsis-rx #rx"^\\.\\.\\._[^_]*$")
(define mismatch-ellipsis-rx #rx"^\\.\\.\\._!_[^_]*$")
;; symbol-match : regexp -> any -> (or/c false symbol)
;; Returns the sub-symbol matching the sub-pattern inside
;; the first capturing parens.
(define ((symbol-match rx) x)
(and (symbol? x)
(let ([match (regexp-match rx (symbol->string x))])
(and match (cadr match) (string->symbol (cadr match))))))
(define-struct class (id) #:transparent)
(define-struct mismatch (var) #:transparent)
(define-struct binder (name) #:transparent)
(define binder-pattern
(match-lambda
[(struct binder (name))
(match ((symbol-match named-nt-rx) name)
[#f name]
[p p])]))
;; name: (or/c symbol? mismatch?)
;; The generator records `name' in the environment when generating an ellipsis,
;; to enforce sequence length constraints.
;; class: class?
;; When one binding appears under two (non-nested) ellipses, the sequences generated
;; must have the same length; `class' groups ellipses to reflect this constraint.
;; var: (list/c (or/c symbol? class? mismatch? binder?))
;; the bindings within an ellipses, used to split and merge the environment before
;; and after generating an ellipsis
(define-struct ellipsis (name pattern class vars) #:inspector (make-inspector))
;; unparse-pattern: parsed-pattern -> pattern
(define unparse-pattern
(match-lambda
[(struct binder (name)) name]
[(struct mismatch (var)) var]
[(list-rest (struct ellipsis (name sub-pat _ _)) rest)
(let ([ellipsis (if (mismatch? name) (mismatch-var name) name)])
(list* (unparse-pattern sub-pat) ellipsis (unparse-pattern rest)))]
[(cons first rest)
(cons (unparse-pattern first) (unparse-pattern rest))]
[other other]))
;; class-reassignments : parsed-pattern -> hash[sym -o> sym]
(define (class-reassignments pattern)
; union-find w/o balancing or path compression (at least for now)
(define (union e f sets)
(hash-set sets (find f sets) (find e sets)))
(define (find e sets)
(let recur ([chd e] [par (hash-ref sets e #f)])
(if (and par (not (eq? chd par))) (recur par (hash-ref sets par #f)) chd)))
(let* ([last-contexts (make-hasheq)]
[assignments #hasheq()]
[record-binder
(λ (pat under)
(set! assignments
(if (null? under)
assignments
(let ([last (hash-ref last-contexts pat #f)])
(if last
(foldl (λ (cur last asgns) (union cur last asgns)) assignments under last)
(begin
(hash-set! last-contexts pat under)
assignments))))))])
(let recur ([pat pattern] [under null])
(match-a-pattern pat
[`any assignments]
[`number assignments]
[`string assignments]
[`natural assignments]
[`integer assignments]
[`real assignments]
[`boolean assignments]
[`variable assignments]
[`(variable-except ,vars ...) assignments]
[`(variable-prefix ,var) assignments]
[`variable-not-otherwise-mentioned assignments]
[`hole assignments]
[`(nt ,var) assignments]
[`(name ,var ,pat)
(record-binder var under)
(recur pat under)]
[`(mismatch-name ,var ,pat)
(recur pat under)]
[`(in-hole ,p1 ,p2)
(recur p2 under)
(recur p1 under)]
[`(hide-hole ,p)
(recur p under)]
[`(side-condition ,p ,exp ,srcloc)
(recur p under)]
[`(cross ,nt) assignments]
[`(list ,lpats ...)
(for ([lpat (in-list lpats)])
(match lpat
[`(repeat ,p ,name ,mismatch?)
(record-binder name under)
(recur p (cons (or name (gensym)) under))]
[_ (recur lpat under)]))
assignments]
[(? (compose not pair?)) assignments]))
(make-immutable-hasheq (hash-map assignments (λ (cls _) (cons cls (find cls assignments)))))))
(define (reassign-classes pattern)
(let* ([reassignments (class-reassignments pattern)]
[rewrite (λ (c) (make-class (hash-ref reassignments (class-id c) (class-id c))))])
(let recur ([pat pattern])
(match pat
#;
[`(repeat ,sub-pat ,name ,mismatch?)
`(repeat ,(recur sub-pat)
,(rewrite name)
,mismatch?)]
[(struct ellipsis (name sub-pat class vars))
(make-ellipsis name (recur sub-pat) (rewrite class)
(map (λ (v) (if (class? v) (rewrite v) v)) vars))]
[(? list?) (map recur pat)]
[_ pat]))))
;; used in generating the `any' pattern
(define-language sexp (sexp variable string number boolean (sexp ...)))
(define-signature decisions^
(next-variable-decision
next-number-decision
next-natural-decision
next-integer-decision
next-real-decision
next-boolean-decision
next-non-terminal-decision
next-sequence-decision
next-any-decision
next-string-decision))
(define random-decisions@
(unit (import) (export decisions^)
(define (next-variable-decision) pick-var)
(define (next-number-decision) pick-number)
(define (next-natural-decision) pick-natural)
(define (next-integer-decision) pick-integer)
(define (next-real-decision) pick-real)
(define (next-boolean-decision) pick-boolean)
(define (next-non-terminal-decision) pick-nts)
(define (next-sequence-decision) pick-sequence-length)
(define (next-any-decision) pick-any)
(define (next-string-decision) pick-string)))
(define generation-decisions (make-parameter random-decisions@))
(provide (struct-out ellipsis)
(struct-out class)
(struct-out binder)
(struct-out rg-lang)
(struct-out base-cases)
base-cases-cross
(struct-out exn:fail:redex:generation-failure)
raise-gen-fail)
(provide pick-from-list pick-sequence-length pick-nts
pick-char pick-var pick-string pick-any pick-boolean
pick-number pick-natural pick-integer pick-real
unparse-pattern
prepare-lang
class-reassignments reassign-classes
default-retries
default-attempt-size
default-check-attempts
attempt-size/c
proportion-at-size
retry-threshold proportion-before-threshold post-threshold-incr
is-nt? nt-by-name min-prods
generation-decisions decisions^
random-string
sexp
find-base-cases
attempt->size
redex-pseudo-random-generator)
(provide compile)
| false |
538b96e067dbf0c541d22b2e4b7a4536329e1fba | 49d98910cccef2fe5125f400fa4177dbdf599598 | /advent-of-code-2022/day01/day01.rkt | f205bc78c5ba14de44df2fd30bfddfc9d9c5450b | []
| no_license | lojic/LearningRacket | 0767fc1c35a2b4b9db513d1de7486357f0cfac31 | a74c3e5fc1a159eca9b2519954530a172e6f2186 | refs/heads/master | 2023-01-11T02:59:31.414847 | 2023-01-07T01:31:42 | 2023-01-07T01:31:42 | 52,466,000 | 30 | 4 | null | null | null | null | UTF-8 | Racket | false | false | 400 | rkt | day01.rkt | #lang racket
(require "../advent.rkt" threading)
(define in (parse-aoc 1 numbers #:sep "\n\n"))
;; Part 1 -------------------------------------------------------------------------------------
(~> (map list-sum in)
list-max)
;; Part 2 -------------------------------------------------------------------------------------
(~> (map list-sum in)
(sort _ >)
(take _ 3)
(list-sum _))
| false |
de33678df1639c6fed69d171489c6ec91444147a | 9dc73e4725583ae7af984b2e19f965bbdd023787 | /eopl-solutions/chap4/4-5.rkt | c7e1fc152b85a3e377847f7b3ae20655f7dc2edb | []
| no_license | hidaris/thinking-dumps | 2c6f7798bf51208545a08c737a588a4c0cf81923 | 05b6093c3d1239f06f3657cd3bd15bf5cd622160 | refs/heads/master | 2022-12-06T17:43:47.335583 | 2022-11-26T14:29:18 | 2022-11-26T14:29:18 | 83,424,848 | 6 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 223 | rkt | 4-5.rkt | ;; (value-of exp₁ p σ₀) = (val₁ σ₁)
;; ...
;; (value-of exp_n p σ_n-1) = (val_n σ_n)
;; ---------------------------------------
;; (value-of (list-exp exp₁ ... exp_n) p σ₀)
;; = (list-val val₁ ... val_n)
| false |
1638731056b8f873b2b1f039a0a9aef8d0ef950f | a697a74db1ff203b28b12dccee742c0278b59308 | /1. Grundlagen Raket/abs.rkt | 8c7f22a46130179c47f3932bc30713f3bffcc182 | [
"MIT"
]
| permissive | DavidStahl97/Racket | 83a471bf9133f92a06beca0a06c5b92955f2f9c9 | 08fc0b1fb51ca7ba0aca2a54152f950b30d9587e | refs/heads/main | 2023-02-05T09:27:16.608673 | 2020-12-29T11:20:09 | 2020-12-29T11:20:09 | 305,088,702 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 144 | rkt | abs.rkt | #lang racket
(define (my-abs x)
(cond
((> x 0) x)
((= x 0) 0)
((< x 0) (- x))
)
)
(define (my-abs2 x)
(if (< x 0) (- x) x)
) | false |
98dcc66ed3527c2a35c6d7556c5e49f0f5fe2242 | 23d78f4c06e9d61b7d90d8ebd035eb1958fe2348 | /racket/cps/ds.rkt | 66296ef36b32b4668701866a9839a75f887c2f3a | [
"Unlicense"
]
| permissive | seckcoder/pl_research | e9f5dbce4f56f262081318e12abadd52c79d081d | 79bb72a37d3862fb4afcf4e661ada27574db5644 | refs/heads/master | 2016-09-16T09:40:34.678436 | 2014-03-22T02:31:08 | 2014-03-22T02:31:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,335 | rkt | ds.rkt | #lang racket
(require eopl/datatype
"../base/utils.rkt"
"store.rkt"
(submod "parser.rkt" ds))
(provide (all-defined-out))
#|(define-datatype
expval expval?
(numval
(int number?))
(boolval
(bool boolean?))
(strval
(s string?))
(procval
(proc proc?))
(listval
(lst list?))
(symval
(sym symbol?))
)
(define constval
(lambda (v)
(cond ((number? v) (numval v))
((string? v) (strval v))
((boolean? v) (boolval v))
(else
(eopl:error 'constval "~s is not a const value" v)))))
(define expval->normalval
(lambda (val)
(cases expval val
(numval
(num)
num)
(boolval
(bool)
bool)
(procval
(proc)
proc)
(listval
(lst)
(map expval->normalval lst))
)))
(define expval->numval
(lambda (val)
(cases expval val
(numval
(num)
num)
(else
(eopl:error 'expval->numval "~s is not a num" val)))))
(define expval->boolval
(lambda (val)
(cases expval val
(boolval
(bool)
bool)
(else
(eopl:error 'expval->boolval "~s is not a bool" val)))))
(define expval->procval
(lambda (val)
(cases expval val
(procval
(proc)
proc)
(else
(eopl:error 'expval->procval "~s is not a proc" val)))))
(define expval->listval
(lambda (val)
(cases expval val
(listval
(lst)
lst)
(else
(eopl:error 'expval->listval "~s is not a list" val)))))|#
(define-datatype
proc proc?
(closure
(vars (list-of symbol?))
(body tfexp?)
(env environment?)))
; environment
; env := '() | (var val env)
(define-datatype
environment environment?
(empty-env)
(extend-env
(var (list-of symbol?))
(ref (list-of reference?))
(env environment?)))
(define apply-env
(lambda (env search-var)
; (println "apply env:~s ~s" env search-var)
(cases
environment env
(empty-env
()
(error "apply-env var:~s not found" search-var))
(extend-env
(vars refs inherited-env)
(let ((idx (index-of vars search-var)))
(if (< idx 0)
(apply-env inherited-env search-var)
(list-ref refs idx))))
)))
| false |
b03c9641ffe9f3438eda8cfa09e6bdf162459a2b | 3e9f044c5014959ce0e915fe1177d19f93d238ed | /racket/com-spacetimecat/edit/gui/editor.rkt | 31ba94f48530602a54116269cc73f9ddbce122a3 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"CC0-1.0",
"BSD-2-Clause"
]
| permissive | edom/work | 5e15c311dd49eb55fafbff3455cae505fa51643a | df55868caa436efc631e145a43e833220b8da1d0 | refs/heads/master | 2022-10-10T22:25:11.652701 | 2020-02-26T19:42:08 | 2020-02-26T19:44:58 | 138,504,284 | 0 | 1 | NOASSERTION | 2022-10-06T01:38:07 | 2018-06-24T18:03:16 | TeX | UTF-8 | Racket | false | false | 4,578 | rkt | editor.rkt | #lang s-exp "lang.rkt"
(require
racket/list
"buffer.rkt"
"key.rkt"
)
(provide
main-editor-area%
)
(define main-editor-area% (class tab-panel%
(super-new [choices '()]
[stretchable-width #t]
[stretchable-height #t])
(init-field control)
(define canvas (new editor-canvas% [parent this]))
(define h-panel-cmd (new horizontal-panel% [parent this] [stretchable-height #f]))
(define mode-indicator (new message% [parent h-panel-cmd] [label ""] [auto-resize #t]))
(define command-input (new text-field% [parent h-panel-cmd] [label ""]))
(define buffer (new buffer% [session control]))
(send canvas set-editor (send buffer internal-get-text%-instance))
(define/public (get-current-buffer) buffer)
(define/public (evaluate-current-buffer) (send buffer evaluate))
;; Keyboard event handling.
;; Should we use the keymap that comes with racket/gui?
(define keymap 'normal)
(define/override (on-subwindow-char r e)
(or (super on-subwindow-char r e)
(and (equal? keymap 'vi) (handle-key-event e))))
;; 2019-10-22: TODO: Perhaps move this to buffer% so that we can delete the forwarding methods?
;; But refactor session-imp.rkt before deleting the forwarding methods.
(define/public (handle-key-event e)
;; What about things like 10dw, d10w, 5h
;; We need a more sophisticated parser.
(define handled? #t)
(define (unhandled)
(set! handled? #f)
(printf "DEBUG: Unhandled key event in normal mode: ~a~n" (format-key-event e)))
(define combination (key-event->combination e))
(case mode
[(normal)
(match combination
[`(#\i) (set-mode 'insert)]
[`(#\:) (focus-on-command-input)]
[(list (or #\h 'left)) (move-cursor 'left)]
[(list (or #\j 'down)) (move-cursor 'down)]
[(list (or #\k 'up)) (move-cursor 'up)]
[(list (or #\l 'right)) (move-cursor 'right)]
[(or '(#\w) '(ctl right)) (move-to-start-of-next-word)]
[(or '(#\b) '(ctl left)) (move-to-previous-start-of-word)]
['(#\e) (move-to-next-end-of-word)]
[else (unhandled)]
)]
[(insert)
(match combination
[`(escape) (set-mode 'normal)]
[`(,c) #:when (char? c)
(case c
[(#\backspace) (handle-backspace-key)]
[(#\rubout) (handle-delete-key)]
[(#\return) (insert-char #\newline)]
[else (insert-char c)]
)
]
[`(left) (move-cursor 'left)]
[`(down) (move-cursor 'down)]
[`(up) (move-cursor 'up)]
[`(right) (move-cursor 'right)]
[_ (unhandled)]
)]
[else
(printf "handle-key-event: Invalid mode: ~v~n" mode)
(set-mode 'normal)])
handled?)
(define-property mode 'normal
#:after-change (old new ->
(send mode-indicator set-label
(string-append "-- " (string-upcase (symbol->string new)) " --"))))
;; Reactions.
(define/public (after-open-file buf path)
;; TODO: Use the short file name instead of the complete path.
;; TODO: Disambiguate between files with the same name
;; by showing the rightmost unambiguous subdirectory.
(send this append (path->string path))
(focus-on-main-editor))
(define/forward (move-cursor dir) buffer)
(define/forward (insert-char c) buffer)
(define/forward (handle-backspace-key) buffer)
(define/forward (handle-delete-key) buffer)
(define/forward (move-to-start-of-next-word) buffer)
(define/forward (move-to-previous-start-of-word) buffer)
(define/forward (move-to-next-end-of-word) buffer)
(define/public (focus-on-command-input) (send command-input focus))
(define/public (focus-on-main-editor) (send canvas focus))
;; Call listeners to initialize labels.
(define (initial-fire-listeners)
(before-mode-change mode mode)
(after-mode-change mode mode))
(initial-fire-listeners)
))
| false |
bda7d1a4124d22d54bbecd6636d5786b8c277dff | b22ff10c217f5bf48cac6488d6aecb4f185fe163 | /myvy.rkt | f116ac5ed33c9a3c9867b76a11ddd719cfb876e5 | []
| no_license | wilcoxjay/myvy | 2d63652694128f4f398e329bcdfe5adb397e867f | 8bfc4b4a49f2ec764a382dbc233ccf2c8ffdc9a0 | refs/heads/master | 2020-03-07T23:30:48.458697 | 2018-04-15T20:38:17 | 2018-04-15T20:38:17 | 127,783,458 | 0 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 48,750 | rkt | myvy.rkt | #lang racket
(require racket/sandbox)
(require "solver.rkt")
(provide (all-defined-out))
(struct type-decl (name) #:transparent)
(struct immrel-decl (name sorts) #:transparent)
(struct mutrel-decl (name sorts) #:transparent)
(struct immconst-decl (name sort) #:transparent)
(struct mutconst-decl (name sort) #:transparent)
(struct immfun-decl (name sorts sort) #:transparent)
(struct mutfun-decl (name sorts sort) #:transparent)
(struct axiom-decl (name formula) #:transparent)
(struct init-decl (name formula) #:transparent)
(struct transition-decl (name formula) #:transparent)
(struct invariant-decl (name formula) #:transparent)
(struct corollary-decl (name formula) #:transparent)
(struct labeled-formula (name formula) #:transparent)
(define decl-name
(match-lambda
[(type-decl t) t]
[(immrel-decl R _) R]
[(mutrel-decl R _) R]
[(immconst-decl C _) C]
[(mutconst-decl C _) C]
[(immfun-decl F _ _) F]
[(mutfun-decl F _ _) F]
; the ones below here are kinda bogus
[(axiom-decl name _) name]
[(init-decl name _) name]
[(transition-decl name _) name]
[(invariant-decl name _) name]
[(corollary-decl name _) name]))
(define-syntax-rule (type t) (type-decl `t))
(define-syntax-rule (immutable-relation R (args ...)) (immrel-decl `R `(args ...)))
(define-syntax-rule (mutable-relation R (args ...)) (mutrel-decl `R `(args ...)))
(define-syntax-rule (immutable-constant C t) (immconst-decl `C `t))
(define-syntax-rule (mutable-constant C t) (mutconst-decl `C `t))
(define-syntax-rule (immutable-function F (args ...) t)
(begin
(when (null? `(args ...))
(error "functions must take at least one argument; consider using a constant instead"))
(immfun-decl `F `(args ...)`t)))
(define-syntax-rule (mutable-function F (args ...) t)
(begin
(when (null? `(args ...))
(error "functions must take at least one argument; consider using a constant instead"))
(mutfun-decl `F `(args ...) `t)))
(define-syntax axiom
(syntax-rules ()
[(axiom f) (axiom-decl (symbol-append 'anonymous- (gensym)) `f)]
[(axiom name f) (axiom-decl `name `f)]))
(define-syntax init
(syntax-rules ()
[(init f) (init-decl (symbol-append 'anonymous- (gensym)) `f)]
[(init name f) (init-decl `name `f)]))
(define-syntax transition
(syntax-rules ()
[(transition f) (transition-decl (symbol-append 'anonymous- (gensym)) `f)]
[(transition name f) (transition-decl `name `f)]))
(define-syntax invariant
(syntax-rules ()
[(invariant f) (invariant-decl (symbol-append 'anonymous- (gensym)) `f)]
[(invariant name f) (invariant-decl `name `f)]))
(define-syntax corollary
(syntax-rules ()
[(corollary f) (corollary-decl (symbol-append 'anonymous- (gensym)) `f)]
[(corollary name f) (corollary-decl `name `f)]))
(define (total-order sort)
(define R (symbol-append sort '-le))
(define zero (symbol-append sort '-zero))
(list
(immutable-relation ,R (,sort ,sort))
(immutable-constant ,zero ,sort)
(axiom ,(symbol-append R '-refl)
(forall ((X ,sort))
(,R X X)))
(axiom ,(symbol-append R '-antisym)
(forall ((X1 ,sort) (X2 ,sort))
(=> (and (,R X1 X2)
(,R X2 X1))
(= X1 X2))))
(axiom ,(symbol-append R '-total)
(forall ((X1 ,sort) (X2 ,sort))
(or (,R X1 X2)
(,R X2 X1))))
(axiom ,(symbol-append R '-trans)
(forall ((X1 ,sort) (X2 ,sort) (X3 ,sort))
(=> (and (,R X1 X2)
(,R X2 X3))
(,R X1 X3))))
(axiom ,(symbol-append R '-le-zero)
(forall ((X ,sort))
(,R ,zero X)))))
(define (decl-stream decls [pred (λ (x) #t)])
(for/stream ([decl decls]
#:when (pred decl))
decl))
(define (sort-stream decls)
(decl-stream decls type-decl?))
(define (inits-as-labeled-formulas decls)
(for/stream ([decl decls] #:when (init-decl? decl))
(match decl
[(init-decl name f) (labeled-formula name f)])))
(define (invariants-as-labeled-formulas decls)
(for/stream ([decl decls] #:when (invariant-decl? decl))
(match decl
[(invariant-decl name f) (labeled-formula name f)])))
(define (corollaries-as-labeled-formulas decls)
(for/stream ([decl decls] #:when (corollary-decl? decl))
(match decl
[(corollary-decl name f) (labeled-formula name f)])))
(define (transitions-as-labeled-formulas decls)
(for/stream ([decl decls] #:when (transition-decl? decl))
(match decl
[(transition-decl name f) (labeled-formula name f)])))
(define (get-labeled-formula-by-name name lfs)
(labeled-formula-formula
(stream-first
(stream-filter (λ (lf) (equal? name (labeled-formula-name lf)))
lfs))))
(define (get-transition-by-name decls name)
(get-labeled-formula-by-name name (transitions-as-labeled-formulas decls)))
(define (get-invariant-by-name decls name)
(get-labeled-formula-by-name name (invariants-as-labeled-formulas decls)))
(define (get-corollary-by-name decls name)
(get-labeled-formula-by-name name (corollaries-as-labeled-formulas decls)))
(define (myvy-declare-globals decls)
(for ([decl decls])
(match decl
[(type-decl ty) (solver-declare-sort ty)]
[(immrel-decl R sorts) (solver-declare-fun R sorts 'Bool)]
[(immconst-decl C sort)
(solver-declare-const C sort)
#;(let ([x (gensym)])
(solver-assert `(exists ((,x ,sort)) (= ,x ,C))))]
[(immfun-decl F sorts sort)
(solver-declare-fun F sorts sort)
#;(let ([bvs (map (λ (s) (list (gensym) s)) sorts)]
[y (list (gensym) sort)])
(solver-assert `(forall ,bvs
(exists (,y)
(= (,F ,@(map car bvs)) ,(car y))))))]
[(axiom-decl name f)
(solver-assert #:label (symbol-append 'axiom- name) f)]
[_ (void)])))
(define (myvy-declare-mutable-signature-mangle decls mangle)
(for ([decl decls])
(match decl
[(mutrel-decl R sorts) (solver-declare-fun (mangle R) sorts 'Bool)]
[(mutconst-decl C sort)
(solver-declare-const (mangle C) sort)
#;(let ([x (gensym)])
(solver-assert `(exists ((,x ,sort)) (= ,x ,(mangle C)))))]
[(mutfun-decl F sorts sort)
(solver-declare-fun (mangle F) sorts sort)
#;(let ([bvs (map (λ (s) (list (gensym) s)) sorts)]
[y (list (gensym) sort)])
(solver-assert `(forall ,bvs
(exists (,y)
(= (,(mangle F) ,@(map car bvs)) ,(car y))))))]
[_ (void)])))
(define (myvy-declare-mutable-signature decls)
(myvy-declare-mutable-signature-mangle decls (λ (x) x)))
(define (myvy-assert-inits decls [mangle (λ (x) x)])
(for ([decl decls])
(match decl
[(init-decl name f) (solver-assert #:label (symbol-append 'init- name)
(myvy-mangle-formula-one-state decls mangle f))]
[_ (void)])))
(define (refers-to-mutable decls sym)
(for/or ([decl decls])
(match decl
[(mutrel-decl R _) (equal? sym R)]
[(mutconst-decl C _) (equal? sym C)]
[(mutfun-decl F _ _) (equal? sym F)]
[_ false])))
(define (myvy-mangle-formula-one-state decls mangle f)
(match f
[(? symbol? sym) (if (refers-to-mutable decls sym) (mangle sym) sym)]
[(? list? l) (map (λ (x) (myvy-mangle-formula-one-state decls mangle x)) l)]
[_ f]))
(define (model-get-elements-of-sort model sort)
; (printf "~a\n" sort)
(apply append
(for/list ([decl model])
(match decl
[`(declare-fun ,sym () ,(== sort)) (list sym)]
[_ null]))))
(define (myvy-assert-cardinality sort k)
(define bounds (for/list ([i (in-range k)]) (gensym)))
(for ([b bounds])
(solver-declare-fun b '() sort))
(define x (gensym))
(solver-assert #:label (symbol-append 'cardinality-constraint-for- sort)
`(forall ((,x ,sort))
(or
,@(for/list ([b bounds])
`(= ,x ,b))))))
; compute a minimal model by iteratively tightening cardinality
; constraints on the uninterpreted sorts.
; this function pushes a solver frame which it does not pop.
; on return, that frame contains all the cardinality constraints for the minimal model,
; and nothing else.
; caller should call (solver-pop) when they want to return to the cardinality-unconstrained
; context.
(define (myvy-get-minimal-model decls)
(match-define `(model ,model ...) (solver-get-model))
(define (update-model)
(define res (solver-check-sat))
(match res
['sat (set! model (solver-get-model))
#t]
[res #f]))
(solver-push)
(define card-map (make-hash))
(for ([sort (stream-map type-decl-name (sort-stream decls))])
(define n (length (model-get-elements-of-sort model sort)))
#;(printf "~a ~a\n" sort n)
(when (= n 1)
; (printf "asserted ~a ~a on cardinality frame\n" sort 1)
(myvy-assert-cardinality sort 1)
(hash-set! card-map sort 1))
(do ([k (- n 1) (- k 1)]
[done? #f])
((or done? (= k 0)))
(solver-push)
(myvy-assert-cardinality sort k)
#;(printf "~a ~a\n" sort k)
(set! done? (not (update-model)))
(solver-pop)
; add last known satisfiable cardinality constraint
(cond
[done?
; (printf "asserted ~a ~a on cardinality frame\n" sort (+ k 1))
(myvy-assert-cardinality sort (+ k 1))
(hash-set! card-map sort (+ k 1))]
[(= k 1)
; (printf "asserted ~a ~a on cardinality frame\n" sort k)
(myvy-assert-cardinality sort k)
(hash-set! card-map sort k)]
[else (void)])))
; call check-sat one more time just to make the model available in the context
(match (solver-check-sat)
['sat (list (solver-get-model) card-map)]))
; checks all the labeled formulas in decls.
; if all checks pass, then #f is returned and the solver context is left unchanged.
; if a check fails, no further checks are performed, and a countermodel is returned.
; in that case, the solver context is left with two additional frames on it.
; the outer frame (next-on-stack) contains (assert (not failing-invariant)).
; the inner frame (top-of-stack) contains minimal cardinality constraints for
; all the uninterpreted sorts.
;
; in other words, if this returns non-#f, the caller must call (solver-pop 2)
; after they are done interacting with the countermodel.
(define (myvy-check-labeled-formulas-mangle mapper decls mangle)
(for/or ([decl (mapper decls)])
(match decl
[(labeled-formula name f)
(printf " ~a " name)
(solver-push)
(solver-assert #:label (symbol-append 'goal- name)
(solver-not (myvy-mangle-formula-one-state decls mangle f)))
(match (solver-check-sat)
['sat
(printf "failed\n")
(define model (first (myvy-get-minimal-model decls)))
model]
['unsat (printf "ok!\n") (solver-pop) #f]
['unknown (pretty-print (solver-get-stack)) (error "Unexpected unknown")])]
[_ #f])))
(define (myvy-check-labeled-formulas mapper decls)
(myvy-check-labeled-formulas-mangle mapper decls (λ (x) x)))
(define (myvy-check-init-invariants decls)
(printf "checking initial state implies invariants\n")
(solver-push)
(myvy-declare-mutable-signature decls)
(myvy-assert-inits decls)
(let ([res (myvy-check-labeled-formulas invariants-as-labeled-formulas decls)])
(when res
(solver-pop 2))
(solver-pop)
res))
(define (myvy-assert-invs decls [mangle (λ (x) x)])
(for ([decl decls])
(match decl
[(invariant-decl inv-name f)
(solver-assert #:label (symbol-append 'hypothesis-invariant- inv-name)
(myvy-mangle-formula-one-state decls mangle f))]
[_ (void)])))
(define (number->symbol n)
(string->symbol (number->string n)))
(define (myvy-mangle-old s) (symbol-append 'old- s))
(define (myvy-mangle-new s) (symbol-append 'new- s))
(define ((myvy-mangle-i i) s)
(symbol-append 'state- (number->symbol i) '- s))
(define (myvy-mangle-formula-two-state decls mangle-old mangle-new f)
(define (go old? f)
(match f
[(? symbol? sym)
(if (refers-to-mutable decls sym)
(if old? (mangle-old sym) (mangle-new sym))
sym)]
[`(old ,f2) (if old? (error "nested old") (go true f2))]
[(? list? l) (map (λ (x) (go old? x)) l)]
[_ f]))
(go false f))
(define (myvy-frame-formula-for-modifies-clause decls mangle-old mangle-new nonce mods)
(solver-and*
(append*
(for/list ([decl decls])
(match decl
[(mutrel-decl name sorts) #:when (not (member name mods))
(let ([bounds (map (λ (s) (list (gensym) s)) sorts)])
(list (solver-label
#:label (symbol-append 'frame- nonce '- name)
(if (null? bounds)
`(= ,(mangle-old name) ,(mangle-new name))
`(forall ,bounds
(= (,(mangle-old name) ,@(map car bounds))
(,(mangle-new name) ,@(map car bounds))))))))]
[(mutconst-decl name sort) #:when (not (member name mods))
(list (solver-label #:label (symbol-append 'frame- nonce '- name)
`(= ,(mangle-old name) ,(mangle-new name))))]
[(mutfun-decl name sorts sort) #:when (not (member name mods))
(let ([bounds (map (λ (s) (list (gensym) s)) sorts)])
(list (solver-label
#:label (symbol-append 'frame- nonce '- name)
`(forall ,bounds
(= (,(mangle-old name) ,@(map car bounds))
(,(mangle-new name) ,@(map car bounds)))))))]
[_ null])))))
(define (myvy-desugar-transition-relation decls mangle-old mangle-new name formula)
(match formula
[`(modifies ,mods ,formula)
(solver-and
(myvy-frame-formula-for-modifies-clause decls mangle-old mangle-new name mods)
(myvy-desugar-transition-relation decls mangle-old mangle-new name formula))]
[_ (solver-label #:label (symbol-append 'transition-relation- name)
(myvy-mangle-formula-two-state decls mangle-old mangle-new formula))]))
(define (myvy-assert-transition-relation decls mangle-old mangle-new name formula)
(solver-assert-skolemize #:label name
(myvy-desugar-transition-relation decls mangle-old mangle-new name formula)))
(define (enumerate-relation eval model elt-map #:mangle [mangle (λ (x) x)] R sorts)
(if (null? sorts)
(list R (if (defined-in-model model (mangle R))
(eval (mangle R))
#f))
(for/list ([tuple (apply cartesian-product (map (λ (s) (hash-ref elt-map s)) sorts))])
(list (cons R tuple)
(if (defined-in-model model (mangle R))
(eval (cons (mangle R) tuple))
#f)))))
(define (enumerate-function eval model elt-map #:mangle [mangle (λ (x) x)] F sorts sort)
(for/list ([tuple (apply cartesian-product (map (λ (s) (hash-ref elt-map s)) sorts))])
(list (cons F tuple)
(if (defined-in-model model (mangle F))
(eval (cons (mangle F) tuple))
(first (hash-ref elt-map sort))))))
(define/match (myvy-expr-to-racket expr)
[(`(ite ,args ...)) `(if ,@(map myvy-expr-to-racket args))]
[(`(= ,args ...)) `(equal? ,@(map myvy-expr-to-racket args))]
[((? list? l)) (map myvy-expr-to-racket l)]
[(x) x])
(define/match (myvy-model-to-racket model)
[(`(model ,model ...))
`(begin
,@(apply append
(for/list ([decl model])
(match decl
[`(declare-fun ,nm () ,_) (list `(define ,nm ',nm))]
[`(define-fun ,nm ,args-with-sorts ,_ ,body)
(list `(define ,(if (null? args-with-sorts) nm
(cons nm (map car args-with-sorts)))
,(myvy-expr-to-racket body)))]
[_ null]))))])
(define/match (defined-in-model model name)
[(`(model ,model ...) _)
(for/or ([decl model])
(match decl
[`(define-fun ,nm ,_ ,_ ,_)
(equal? name nm)]
[_ false]))])
(define the-racket-model (void))
(define the-racket-model-decls (void))
(define the-racket-model-z3-model (void))
(define (myvy-make-evaluator-for-model racket-model)
(define e (make-evaluator 'racket/base #:allow-for-load '("/")))
#;(λ (x)
(with-handlers
([(λ (_) #t)
(λ (err)
(printf "myvy-to-racket eval failed; trying z3's eval as last-ditch effort\n")
(pretty-print err)
(newline)
(solver-eval x))])
(e x)))
(e '(define true #t))
(e '(define false #f))
(e racket-model)
e)
(define (myvy-set-up-racket-model-two-state decls model)
(set! the-racket-model (myvy-model-to-racket model))
(set! the-racket-model-decls decls)
(set! the-racket-model-z3-model model))
(define (myvy-model-elt-map decls model)
(for/hash ([sort (stream-map type-decl-name (sort-stream decls))])
(values sort (model-get-elements-of-sort model sort))))
(define (enumerate-constant eval model elt-map #:mangle [mangle (λ (x) x)] C sort)
(if (defined-in-model model (mangle C))
(list C (eval (mangle C)))
(list C (first (hash-ref elt-map sort)))))
(define (myvy-enumerate-model-one-state decls mangle model
#:only [the-thing null])
(define elt-map (myvy-model-elt-map decls model))
(define eval (myvy-make-evaluator-for-model (myvy-model-to-racket model)))
(apply append
(for/list ([decl decls]
#:when (or (null? the-thing) (equal? the-thing (decl-name decl))))
(match decl
[(immrel-decl R sorts)
(list (enumerate-relation eval model elt-map R sorts))]
[(mutrel-decl R sorts)
(list (enumerate-relation eval model elt-map #:mangle mangle R sorts))]
[(immconst-decl C sort)
(list (enumerate-constant eval model elt-map C sort))]
[(mutconst-decl C sort)
(list (enumerate-constant eval model elt-map #:mangle mangle C sort))]
[(immfun-decl F sorts sort)
(list (enumerate-function eval model elt-map F sorts sort))]
[(mutfun-decl F sorts sort)
(list (enumerate-function eval model elt-map #:mangle mangle F sorts sort))]
[_ null]))))
(define (myvy-enumerate-model-two-state decls model
#:only [the-thing null])
(define elt-map (myvy-model-elt-map decls model))
(define eval (myvy-make-evaluator-for-model (myvy-model-to-racket model)))
(apply append
(for/list ([decl decls]
#:when (or (null? the-thing) (equal? the-thing (decl-name decl))))
(match decl
[(immrel-decl R sorts)
(list (enumerate-relation eval model elt-map R sorts))]
[(mutrel-decl R sorts)
(list (enumerate-relation eval model elt-map (myvy-mangle-old R) sorts)
(enumerate-relation eval model elt-map (myvy-mangle-new R) sorts))]
[(immconst-decl C sort)
(list (enumerate-constant eval model elt-map C sort))]
[(mutconst-decl C sort)
(list
(enumerate-constant eval model elt-map (myvy-mangle-old C) sort)
(enumerate-constant eval model elt-map (myvy-mangle-new C) sort))]
[(immfun-decl F sorts sort)
(list (enumerate-function eval model elt-map F sorts sort))]
[(mutfun-decl F sorts sort)
(list
(enumerate-function eval model elt-map (myvy-mangle-old F) sorts sort)
(enumerate-function eval model elt-map (myvy-mangle-new F) sorts sort))]
[_ null]))))
(define (myvy-enumerate-the-model-two-state #:only [the-thing null])
(myvy-enumerate-model-two-state
the-racket-model-decls
the-racket-model-z3-model
#:only the-thing))
(define (myvy-check-transitions-preserve-invariants decls #:transition [the-thing null])
(printf "checking transitions preserve invariants\n")
(solver-push)
(myvy-declare-mutable-signature-mangle decls myvy-mangle-old)
(myvy-assert-invs decls myvy-mangle-old)
(myvy-declare-mutable-signature-mangle decls myvy-mangle-new)
(let ([res
(for/or ([decl decls])
(match decl
[(transition-decl name f)
(if (or (null? the-thing) (equal? the-thing name))
(begin
(printf "transition ~a:\n" name)
(solver-push)
(myvy-assert-transition-relation decls myvy-mangle-old myvy-mangle-new name f)
(let ([res (myvy-check-labeled-formulas-mangle
invariants-as-labeled-formulas
decls
myvy-mangle-new)])
(when res
(myvy-set-up-racket-model-two-state decls res)
; (pretty-print (myvy-enumerate-the-model-two-state)) (newline)
(solver-dont-pop!)
(solver-pop 2))
(solver-pop)
res))
#f)]
[_ #f]))])
(unless res
(printf "all checked transitions preserve the invariants!\n"))
(solver-pop)
res))
(define (myvy-diagram decls model [mangle (λ (x) x)])
(define elt-map (myvy-model-elt-map decls model))
(define rename-map
(for*/hash ([(sort elts) elt-map]
[e elts])
(values e (list (symbol-append sort '- (gensym)) sort))))
(define (rename s) (car (hash-ref rename-map s)))
(define vars
(for/list ([(v1 v2) rename-map])
v2))
(define distinct
(for*/list ([(sort elts) elt-map]
[e1 elts]
[e2 elts]
#:when (symbol<? e1 e2))
(solver-not `(= ,(rename e1) ,(rename e2)))))
(define enum (myvy-enumerate-model-one-state decls mangle model))
; (printf "enumeration for diagram:\n")
; (pretty-print enum)
; (newline)
(define atomic
(append*
(for/list ([sym-enum enum])
(match sym-enum
[`(,(? symbol? atom) ,value)
(if (boolean? value)
(list (if value atom (solver-not atom)))
(list `(= ,atom ,(rename value))))]
[_
(for/list ([clause sym-enum])
(match clause
[`((,R ,args ...) ,value)
(let ([atom `(,R ,@(map rename args))])
(if (boolean? value)
(if value atom (solver-not atom))
`(= ,atom ,(rename value))))]))]))))
(define (wrap cs)
(match cs
['() 'true]
[(list x) x]
[_ `(and ,@cs)]))
`(exists ,vars ,(wrap (append distinct atomic))))
(define (myvy-init decls)
(set! the-racket-model null)
(set! the-racket-model-decls null)
(set! the-racket-model-z3-model null)
(set! inductive-frame null)
(solver-init)
(solver-set-option ':auto-config 'false)
(solver-set-option ':smt.mbqi 'true)
(solver-set-option ':interactive-mode 'true)
(solver-set-option ':produce-unsat-cores 'true)
(myvy-declare-globals decls))
(define (myvy-check-corollaries decls)
(printf "checking invariants imply corollaries\n")
(solver-push)
(myvy-declare-mutable-signature decls)
(myvy-assert-invs decls)
(let ([res (myvy-check-labeled-formulas corollaries-as-labeled-formulas decls)])
(when res
(solver-pop 2))
(solver-pop)
res))
(define (solver-labeled-or #:nonce [nonce null] . args)
(define (mk-label)
(if (null? nonce)
(symbol-append 'label- (gensym))
(symbol-append 'label- (number->symbol nonce) '- (gensym))))
(solver-or* (map (λ (disjunct) (solver-and (mk-label) disjunct))
args)))
(define (solver-labeled-or* #:nonce [nonce null] l)
(apply solver-labeled-or l #:nonce nonce))
(define (solver-labels-of-labeled-or expr)
(match expr
[`(or ,disjuncts ...)
(map second disjuncts)]
[_ (list (second expr))]))
(define (myvy-disjunction-of-all-transition-relations decls nonce mangle-old mangle-new
#:include-inits? [include-inits? false])
(solver-labeled-or* #:nonce nonce
(append
(if include-inits?
(list (myvy-mangle-formula-one-state decls mangle-new
(solver-and* (stream->list (myvy-get-inits decls)))))
null)
(for/list ([decl (transitions-as-labeled-formulas decls)])
(match decl
[(labeled-formula name f)
(myvy-desugar-transition-relation decls mangle-old mangle-new
(symbol-append name '- (number->symbol nonce))
f)])))))
(define (myvy-declare-labels lbls)
(for ([lbl lbls])
(solver-declare-const lbl 'Bool)))
(define (myvy-assert-bmc decls n)
(solver-push)
(myvy-declare-mutable-signature-mangle decls (myvy-mangle-i 0))
(myvy-assert-inits decls (myvy-mangle-i 0))
(for ([i (in-range 1 (+ n 1))])
(myvy-declare-mutable-signature-mangle decls (myvy-mangle-i i))
(define t (myvy-disjunction-of-all-transition-relations
decls i
(myvy-mangle-i (- i 1))
(myvy-mangle-i i)))
(myvy-declare-labels (solver-labels-of-labeled-or t))
(solver-assert
#:label (symbol-append 'bmc-transition- (number->symbol i))
t)))
(define (myvy-bmc-no-init decls n goal)
(myvy-assert-bmc decls n)
(solver-assert #:label 'bmc-goal
(myvy-mangle-formula-one-state decls (myvy-mangle-i n) goal))
(match (solver-check-sat)
['unsat (solver-pop) 'unsat]
['sat (first (myvy-get-minimal-model decls))]
['unknown (pretty-print (solver-get-stack)) (error "Unexpected unknown")]))
(define (myvy-bmc decls n goal)
(myvy-init decls)
(myvy-bmc-no-init decls n goal))
(define (myvy-verify decls)
(myvy-init decls)
(not
(or
(myvy-check-init-invariants decls)
(myvy-check-transitions-preserve-invariants decls)
(myvy-check-corollaries decls))))
(define (myvy-updr-frame-to-formula f)
(solver-and* f))
(define (myvy-updr-check-frontier decls bad fs)
(solver-push)
(printf "checking whether frontier has any bad states: ")
(myvy-declare-mutable-signature decls)
(solver-assert #:label 'frontier-frame (myvy-updr-frame-to-formula (first fs)))
(solver-assert #:label 'bad bad)
(match (solver-check-sat)
['unsat (solver-pop) 'unsat]
[x x]))
(define (myvy-updr-analyze-counterexample decls #:may [may false] bad fs diag)
(printf "abstract counterexample found!\n")
(unless may
(pretty-print fs)
(newline))
(if may
(list 'no-universal-invariant fs (list diag))
(begin
(printf "trying bmc with ~a steps...\n" (- (length fs) 1))
(match (myvy-bmc-no-init decls (- (length fs) 1) bad)
['unsat (list 'no-universal-invariant fs (list diag))]
[model (solver-pop 2) (list 'invalid model)]))))
(define (myvy-updr-check-predecessor decls pre diag)
(solver-push)
(printf "checking whether diagram has a predecessor in prestate\n")
; (pretty-print pre)
; (newline)
(myvy-declare-mutable-signature-mangle decls myvy-mangle-old)
(myvy-declare-mutable-signature-mangle decls myvy-mangle-new)
(solver-assert #:label 'prestate-clauses
(myvy-mangle-formula-one-state decls myvy-mangle-old pre))
(solver-assert-skolemize
#:label 'diagram
(myvy-mangle-formula-one-state decls myvy-mangle-new diag))
(define t (myvy-disjunction-of-all-transition-relations
decls 0 myvy-mangle-old myvy-mangle-new
#:include-inits? true))
(myvy-declare-labels (solver-labels-of-labeled-or t))
(solver-assert #:label 'transition t)
(match (solver-check-sat)
['unsat (begin0
(list 'unsat (list (list (solver-get-stack) (solver-get-unsat-core))))
(solver-pop))]
['sat (define model (first (myvy-get-minimal-model decls)))
(begin0
(list 'sat
(myvy-diagram decls model myvy-mangle-old)
model
(myvy-enumerate-model-one-state decls myvy-mangle-old model))
; (printf "would you like the solver stack?\n")
; (match (read)
; ['no (void)]
; ('yes (pretty-print (solver-get-stack))))
; (printf "would you like the minimal model?\n")
; (match (read)
; ['no (void)]
; ('yes (pretty-print model)))
(solver-pop 2))]
['unknown (pretty-print (solver-get-stack)) (error "Unexpected unknown")])
#;(define log null)
#;(begin0
(or
(for/or ([t (transitions-as-labeled-formulas decls)])
(match t
[(labeled-formula name f)
(printf " transition ~a: " name)
(solver-push)
(myvy-assert-transition-relation decls myvy-mangle-old myvy-mangle-new name f)
(match (solver-check-sat)
['unsat (printf "unsat\n")
(set! log (cons (list (solver-get-stack)
(solver-get-unsat-core))
log))
(solver-pop)
#f]
['sat (printf "sat!\n")
(define model (myvy-get-minimal-model decls))
(begin0
(list 'sat
(myvy-diagram decls model myvy-mangle-old)
name)
; (printf "would you like the solver stack?\n")
; (match (read)
; ['no (void)]
; ('yes (pretty-print (solver-get-stack))))
; (printf "would you like the minimal model?\n")
; (match (read)
; ['no (void)]
; ('yes (pretty-print model)))
(solver-pop 2))]
['unknown (pretty-print (solver-get-stack)) (error "Unexpected unknown")])]))
(list 'unsat log))
(solver-pop)))
(define (myvy-one-state-implies decls hyps goal)
(solver-push)
(myvy-declare-mutable-signature decls)
(for ([hyp hyps])
(solver-assert #:label (symbol-append 'one-state-implies-hyp- (gensym)) hyp))
(solver-assert #:label 'one-state-implies-goal (solver-not goal))
(begin0
(match (solver-check-sat)
['sat #f]
['unsat #t]
['unknown (pretty-print (solver-get-stack)) (error "Unexpected unknown")])
(solver-pop)))
(define (myvy-updr-conjoin-frames-up-through decls j fs phi)
(define (go fs)
(match fs
['() (list 0 '())]
[(cons f fs)
(match (go fs)
[(list i fs)
(list (+ i 1)
(if (and (<= i j) (not (myvy-one-state-implies decls f phi)))
(cons (cons phi f) fs)
(cons f fs)))])]))
(match (go fs)
[(list _ fs)
; (printf "blocked. new frames\n")
; (pretty-print fs)
; (newline)
fs]))
(define (myvy-updr-minimize-diag-with-unsat-core decls unsat-log diag)
; (printf "unsat core\n")
; (pretty-print unsat-log)
; (newline)
(define core-names
(remove-duplicates
(filter (λ (x) (string-prefix? (symbol->string x) "diagram-"))
(append* (map cadr unsat-log)))))
(define named-conjuncts
(append*
(for/list ([decl (second (caar unsat-log))])
(match decl
[`(assert (! ,conjunct :named ,name))
(list (list name conjunct))]
[_ null]))))
(define (in-core formula)
(for/or ([named-conjunct named-conjuncts])
(match named-conjunct
[(list name conjunct)
(and (equal? conjunct formula)
(member name core-names))])))
(define (free-in var expr)
; note: this doesn't handle variable binding.
; it's probably fine since we gensym a lot.
(define (go expr)
(match expr
[(? symbol? v) (equal? var v)]
[(list args ...) (ormap go args)]))
(go expr))
(define (filter-free-vars-of expr bvs)
(filter (λ (bv) (free-in (first bv) expr)) bvs))
(define (reconstruct-unsat-core-diagram formula)
(match formula
[`(exists ,vars ,body)
(match (reconstruct-unsat-core-diagram body)
['() '()]
[x `(exists ,(filter-free-vars-of x vars) ,x)])]
[`(and ,body ...)
(match (filter (λ (x) (not (null? x)))
(map reconstruct-unsat-core-diagram body))
['() '()]
[x `(and ,@x)])]
[_ (if (in-core (myvy-mangle-formula-one-state decls myvy-mangle-new formula))
formula
'())]))
(reconstruct-unsat-core-diagram diag))
(define (get-frame j fs)
(list-ref fs (- (length fs) j 1)))
(define (myvy-get-inits decls)
(stream-map
labeled-formula-formula
(inits-as-labeled-formulas decls)))
(define (myvy-minimize-conj-relative-inductive decls frame expr)
(match expr
[`(forall ,bvs (or ,disjs ...))
; (printf "minimizing unsat core for relative inductiveness!\n")
; (pretty-print expr)
; (pretty-print bvs)
; (pretty-print disjs)
(unless (and (myvy-one-state-implies decls (myvy-get-inits decls) expr)
(myvy-updr-relative-inductive decls frame expr))
(printf "xxx: not starting with relative-inductive conjecture!\n"))
(define (build disjs)
`(forall ,bvs ,(solver-or* disjs)))
(define (go head tail)
(match tail
['() (reverse head)]
[(cons t tail)
(define e (build (append head tail)))
(if (and (myvy-one-state-implies decls (myvy-get-inits decls) e)
(myvy-updr-relative-inductive decls frame e))
(go head tail)
(go (cons t head) tail))]))
(define ans (build (go '() disjs)))
(when (not (equal? ans expr))
(printf "minimized conjecture!\n"))
(pretty-print ans)
ans]
[_ expr]))
(define inductive-frame (void))
(define (myvy-updr-block-diagram decls #:may [may false] bad fs diag j)
(printf "updr blocking diagram in frame ~a\n" j)
(when may (printf "note: may\n"))
(pretty-print diag)
(newline)
(if (= j 0)
(myvy-updr-analyze-counterexample decls #:may may bad fs diag)
(match (myvy-updr-check-predecessor
decls
(myvy-updr-frame-to-formula (get-frame (- j 1) fs))
diag)
[(list 'unsat log)
(printf "diagram has no predecessor, computing unsat core to block\n")
(let ([conj (solver-not (myvy-updr-minimize-diag-with-unsat-core decls log diag))])
(pretty-print conj)
(when (not (myvy-updr-relative-inductive decls (get-frame (- j 1) fs) conj))
(printf "ZZZ: unsat core is not relative inductive\n"))
(set! conj (myvy-minimize-conj-relative-inductive decls (get-frame (- j 1) fs) conj))
#;(when (and (myvy-one-state-implies decls (myvy-get-inits decls) conj)
(myvy-updr-relative-inductive decls inductive-frame conj)
(not (myvy-one-state-implies decls inductive-frame conj)))
(set! inductive-frame
(myvy-updr-simplify-frame decls (cons conj inductive-frame)))
(printf "discovered new inductive invariant\n")
(pretty-print inductive-frame)
(for ([i inductive-frame])
(set! fs (myvy-updr-conjoin-frames-up-through decls (length fs) fs i)))
(when (and (not may)
(myvy-one-state-implies decls (myvy-get-inits decls)
(solver-and* inductive-frame))
(myvy-updr-relative-inductive decls inductive-frame
(solver-and* inductive-frame))
(myvy-one-state-implies decls inductive-frame
(solver-not bad)))
(printf "WOW! inductive frame already inductive!!!\n")))
(list 'blocked (myvy-updr-conjoin-frames-up-through decls j fs conj)))]
[(list 'sat diag2 model2 enum2 #;transition-name)
(printf "diagram has predecessor\n")
(printf "recursively blocking predecessor\n")
(match (myvy-updr-block-diagram decls #:may may bad fs diag2 (- j 1))
[(list 'blocked fs) (myvy-updr-block-diagram decls #:may may bad fs diag j)]
[(list 'no-universal-invariant fs diags)
(list 'no-universal-invariant fs (cons diag diags))]
[res res])])))
#;(define (myvy-updr-simplify-frame decls f)
(match f
['() '()]
[(cons c f)
(cons c
(filter (λ (c2) (not (myvy-one-state-implies decls (list c) c2)))
(myvy-updr-simplify-frame decls f)))]))
#;(define (myvy-updr-simplify-frames2 decls fs)
(printf "simplifying frames...\n")
(for/list ([f fs])
(myvy-updr-simplify-frame decls f)))
#;(define (myvy-updr-simplify-frames decls fs)
(map reverse
(myvy-updr-simplify-frames2
decls
(map reverse (myvy-updr-simplify-frames2 decls fs)))))
(define (myvy-updr-simplify-frame decls f)
(printf "simplifying frame\n")
(solver-push)
(myvy-declare-mutable-signature decls)
(begin0
(myvy-simplify-all-in-context '() f)
(solver-pop)
(printf "done simplifying\n")))
(define (myvy-updr-simplify-frames decls fs)
(printf "simplifying frames\n")
(solver-push)
(myvy-declare-mutable-signature decls)
(begin0
(for/list ([f fs])
(myvy-simplify-all-in-context '() f))
(solver-pop)
(printf "done simplifying\n")))
(define (check-frame-implies decls hyps goals)
(solver-push)
(myvy-declare-mutable-signature decls)
(for ([hyp hyps])
(solver-assert #:label (symbol-append 'check-frame-implies-hyp- (gensym)) hyp))
(begin0
(for/and ([goal goals])
(solver-push)
(solver-assert #:label 'check-frame-implies-goal (solver-not goal))
(begin0
(match (solver-check-sat)
['sat (printf "goal not implied\n")
(pretty-print goal)
#f]
['unsat #t]
['unknown (pretty-print (solver-get-stack)) (error "Unexpected unknown")])
(solver-pop)))
(solver-pop)))
(define (myvy-updr-relative-inductive decls hyps expr)
(solver-push)
(myvy-declare-mutable-signature-mangle decls myvy-mangle-old)
(myvy-declare-mutable-signature-mangle decls myvy-mangle-new)
(for ([hyp hyps])
(solver-assert #:label (symbol-append 'relative-inductive-hyp- (gensym))
(myvy-mangle-formula-one-state decls myvy-mangle-old hyp)))
(solver-assert #:label 'relative-inductive-pre
(myvy-mangle-formula-one-state decls myvy-mangle-old expr))
(solver-assert #:label 'relative-inductive-post
(myvy-mangle-formula-one-state decls myvy-mangle-new (solver-not expr)))
(begin0
(for/and ([t (transitions-as-labeled-formulas decls)])
(match t
[(labeled-formula name f)
(solver-push)
(myvy-assert-transition-relation decls myvy-mangle-old myvy-mangle-new name f)
(begin0
(match (solver-check-sat)
['sat #f]
['unsat #t]
['unknown (pretty-print (solver-get-stack)) (error "Unexpected unknown")])
(solver-pop))]))
(solver-pop)))
(define (expr-intern expr)
(define (go env expr)
(match expr
[`(forall ,bvs ,expr)
`(forall ,(map second bvs) ,(go (append (map first bvs) env) expr))]
[`(exists ,bvs ,expr)
`(exists ,(map second bvs) ,(go (append (map first bvs) env) expr))]
[(? list? l) (map (λ (x) (go env x)) l)]
[(? symbol? sym)
(match (index-of env sym)
[#f sym]
[(? number? n) `(var ,n)])]))
(go '() expr))
(define (myvy-updr-push-forward decls f)
(partition (λ (conj) (myvy-updr-relative-inductive decls f conj)) f))
(define (myvy-updr-push-forward-all decls cache fs)
(define (go fs)
(match fs
['() '()]
[(list f) (list f)]
[(cons f fs)
(let*-values ([(fs) (go fs)]
[(success failure) (myvy-updr-push-forward decls (first fs))])
(printf "failed to push in frame ~a\n" (length fs))
(pretty-print failure)
(for/fold ([fs (cons (set-union f success) fs)])
([e failure])
(printf "trying to maybe-block failed expression\n")
(pretty-print e)
(let* ([n (- (length fs) 1)]
[e-interned (expr-intern e)]
#;[k (cons n e-interned)]
)
(if (set-member? cache e-interned)
(begin
(printf "seen this one before, skipping!\n")
fs)
(match (myvy-updr-block-diagram decls #:may true null fs (solver-not e) n)
[(list 'no-universal-invariant fs2 diags)
(set-add! cache e-interned)
fs]
[(list 'blocked fs) fs])))))]))
(printf "pushing forward lemmas...\n")
(go fs))
(define (myvy-get-safety-property-as-formula decls)
(solver-and*
(stream->list
(stream-map labeled-formula-formula
(corollaries-as-labeled-formulas decls)))))
(define (myvy-get-invariants-as-formula decls)
(solver-and*
(stream->list
(stream-map labeled-formula-formula
(invariants-as-labeled-formulas decls)))))
(define (myvy-updr decls)
(myvy-init decls)
(define inits (stream-map
labeled-formula-formula
(inits-as-labeled-formulas decls)))
(define safety (myvy-get-safety-property-as-formula decls))
(printf "checking whether initial state imilpies safety: ")
(unless (myvy-one-state-implies decls inits safety)
(error "no"))
(printf "ok!\n")
(define bad (solver-not safety))
(define push-cache (mutable-set))
(define fs (myvy-updr-push-forward-all decls push-cache
(list (list 'true) (stream->list inits))))
(printf "initializing updr with inits\n")
(pretty-print (stream->list inits))
(printf "initializing updr with bad states\n")
(pretty-print bad)
(define (go simplify? fs)
(when simplify?
(set! fs (myvy-updr-simplify-frames decls fs)))
(printf "outer updr loop considering frame ~a\n" (- (length fs) 1))
#;(pretty-print inductive-frame)
(pretty-print fs)
(newline)
(match (myvy-updr-check-frontier decls bad fs)
['unsat
(printf "frontier is safe.\n")
(printf "moving to new frame\n")
(set! fs (myvy-updr-simplify-frames decls fs))
(set! fs (myvy-updr-push-forward-all decls push-cache (cons (list 'true) fs)))
(set! fs (myvy-updr-simplify-frames decls fs))
(define I (for/or ([next fs]
[prev (rest fs)]
#:when (check-frame-implies decls next prev))
prev))
(if I
(begin
(pretty-print fs)
(list 'valid I))
(go false fs))]
['sat
(printf "frontier is not safe, blocking minimal model\n")
(let* ([model (first (myvy-get-minimal-model decls))]
[diag (myvy-diagram decls model)])
#;(pretty-print diag)
#;(newline)
(solver-pop 2)
(match (myvy-updr-block-diagram decls #:may false bad fs diag (- (length fs) 1))
[(list 'invalid cex) (list 'invalid cex)]
[(list 'no-universal-invariant fs diags)
(list 'no-universal-invariant (reverse fs) (reverse diags))]
[(list 'blocked fs) (go true fs)]))]
['unknown (pretty-print (solver-get-stack)) (error "Unexpected unknown")]))
(go true fs))
(define (myvy-sat-yes-unsat-no msg)
(printf "checking whether ~a: " msg)
(match (solver-check-sat)
['sat (displayln "yes")]
['unsat (displayln "no")]
['unknown (pretty-print (solver-get-stack)) (error "Unexpected unknown")]))
(define (myvy-updr-check-abstract-cex decls acex)
(solver-push)
(solver-push)
(myvy-declare-mutable-signature decls)
(solver-push)
(myvy-assert-inits decls)
(solver-assert #:label 'phi-0 (first acex))
(myvy-sat-yes-unsat-no "counterexample starts in initial state")
(solver-pop)
(solver-push)
(solver-assert #:label 'bad (solver-not (myvy-get-safety-property-as-formula decls)))
(solver-assert #:label 'phi-n (last acex))
(myvy-sat-yes-unsat-no "counterexample ends in bad state")
(solver-pop)
(solver-pop)
(solver-push)
(myvy-declare-mutable-signature-mangle decls myvy-mangle-old)
(myvy-declare-mutable-signature-mangle decls myvy-mangle-new)
(for ([phi-current acex]
[phi-next (rest acex)]
[i (in-naturals)])
(solver-push)
(solver-assert #:label 'phi-current
(myvy-mangle-formula-one-state decls myvy-mangle-old phi-current))
(solver-assert #:label 'phi-next
(myvy-mangle-formula-one-state decls myvy-mangle-new phi-next))
(define t (myvy-disjunction-of-all-transition-relations
decls 0 myvy-mangle-old myvy-mangle-new))
(myvy-declare-labels (solver-labels-of-labeled-or t))
(solver-assert #:label 'transition t)
(myvy-sat-yes-unsat-no (format "counterexample transition ~a is allowed" i))
;(when (= i 3)
(pretty-print phi-current)
(pretty-print t)
(pretty-print phi-next)
(pretty-print (solver-get-model))
;)
(solver-pop))
(solver-pop)
(solver-pop))
(define (solver-query #:label [label 'anonymous] e)
(solver-push)
(solver-assert #:label label (solver-not e))
(begin0
(match (solver-check-sat)
['sat #f]
['unsat #;(pretty-print (solver-get-stack)) #t]
['unknown (pretty-print (solver-get-stack)) (error "Unexpected unknown")])
(solver-pop)))
(define (myvy-with-hyps hyps f)
(solver-push)
(for ([hyp hyps])
(solver-assert #:label (symbol-append 'with-hyp- (gensym)) hyp))
(begin0
(f)
(solver-pop)))
(define (myvy-simplify-in-context hyps goal)
(define (must-be-true e) (solver-query #:label 'must-be-true e))
(define (must-be-false e) (solver-query #:label 'must-be-false (solver-not e)))
(define (declare bvs)
(for ([bv bvs])
(match bv
[(list x sort)
(solver-declare-const x sort)])))
(define (go-list exprs [f (λ (x) x)])
(match exprs
['() '()]
[(cons expr exprs)
(let ([expr (go expr)])
(solver-push)
(solver-assert #:label (symbol-append 'go-list-hyp- (gensym)) (f expr))
(begin0
(cons expr (go-list exprs f))
(solver-pop)))]))
(define (reorder-nots l)
(let-values ([(neg pos) (partition (match-lambda [`(not ,_) #t] [_ #f]) l)])
(append neg pos)))
(define (go goal)
(cond
[(must-be-true goal) 'true]
[(must-be-false goal) 'false]
[else (match goal
[`(forall ,bvs ,body)
(solver-push)
(declare bvs)
(begin0
`(forall ,bvs ,(go body))
(solver-pop))]
[`(exists ,bvs ,body)
(solver-push)
(declare bvs)
(begin0
`(exists ,bvs ,(go body))
(solver-pop))]
[`(and ,conjs ...)
(solver-and* (go-list conjs))]
[`(or ,conjs ...)
(solver-or* (go-list (reorder-nots conjs) solver-not))]
[`(=> ,P ,Q)
(go `(or (not ,P) ,Q))]
[_ goal])]))
(myvy-with-hyps hyps (λ () (go goal))))
(define (myvy-simplify-all-in-context hyps goals)
(define (go head tail)
(match tail
['() (reverse (filter (λ (x) (not (equal? 'true x))) head))]
[(cons e tail)
(go (cons (myvy-simplify-in-context (append head tail) e) head) tail)]))
(myvy-with-hyps hyps
(λ () (go '() goals))))
| true |
78507f1c5a453d35a57b2da7bf9a65e6ab471b47 | 2bee16df872240d3c389a9b08fe9a103f97a3a4f | /racket/P083.rkt | c8e35ebc1263c2c4fc40047f15959498639cab5e | []
| no_license | smrq/project-euler | 3930bd5e9b22f2cd3b802e36d75db52a874bd542 | 402419ae87b7180011466d7443ce22d010cea6d1 | refs/heads/master | 2021-01-16T18:31:42.061121 | 2016-07-29T22:23:05 | 2016-07-29T22:23:05 | 15,920,800 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 3,640 | rkt | P083.rkt | #lang racket
(require csv-reading)
(require "matrix.rkt")
(define raw-data
(let ([result null])
(define in (open-input-file "P083_matrix.txt"))
(set! result (csv->list in))
(close-input-port in)
result))
(define matrix
(list->vector (map (lambda (row) (list->vector (map string->number row)))
raw-data)))
(define matrix-size (vector-length matrix))
(define cost-matrix (make-matrix matrix-size matrix-size +inf.0))
(define visited-matrix (make-matrix matrix-size matrix-size #f))
(define end-cost +inf.0)
; https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
(define (dijkstra get-neighbors get-cost get-tentative-cost set-tentative-cost! get-visited set-visited! select-next-node)
(let loop ([current 'start] [cost 0])
(let ([neighbors (get-neighbors current)])
(for ([neighbor neighbors] #:when (not (get-visited neighbor)))
(set-tentative-cost! neighbor (min (+ cost (get-cost current neighbor)) (get-tentative-cost neighbor))))
(set-visited! current)
(let* ([next-node (select-next-node)]
[next-cost (get-tentative-cost next-node)])
(cond
[(eq? next-node 'end) next-cost]
[else (loop next-node next-cost)])))))
(define (get-neighbors node)
(cond
[(eq? node 'start) (list (cons 0 0))]
[else
(let* ([row (car node)]
[col (cdr node)]
[neighbors null]
[neighbors (if (and (= (add1 row) matrix-size)
(= (add1 col) matrix-size))
(cons 'end neighbors)
neighbors)]
[neighbors (if (or (zero? col) (matrix-ref visited-matrix row (sub1 col)))
neighbors
(cons (cons row (sub1 col)) neighbors))]
[neighbors (if (or (= (add1 col) matrix-size) (matrix-ref visited-matrix row (add1 col)))
neighbors
(cons (cons row (add1 col)) neighbors))]
[neighbors (if (or (zero? row) (matrix-ref visited-matrix (sub1 row) col))
neighbors
(cons (cons (sub1 row) col) neighbors))]
[neighbors (if (or (= (add1 row) matrix-size) (matrix-ref visited-matrix (add1 row) col))
neighbors
(cons (cons (add1 row) col) neighbors))])
neighbors)]))
(define (get-cost _ node)
(cond
[(eq? node 'end) 0]
[else (matrix-ref matrix (car node) (cdr node))]))
(define (get-tentative-cost node)
(cond
[(eq? node 'end) end-cost]
[else (matrix-ref cost-matrix (car node) (cdr node))]))
(define (set-tentative-cost! node cost)
(cond
[(eq? node 'end) (set! end-cost cost)]
[else (matrix-set! cost-matrix (car node) (cdr node) cost)]))
(define (get-visited node)
(and (not (eq? node 'end))
(matrix-ref visited-matrix (car node) (cdr node))))
(define (set-visited! node)
(when (not (eq? node 'start))
(matrix-set! visited-matrix (car node) (cdr node) #t)))
(define (select-next-node)
(let ([result 'end]
[lowest-cost end-cost])
(for* ([row (in-range matrix-size)]
[col (in-range matrix-size)])
(let* ([ijvisited (matrix-ref visited-matrix row col)]
[ijcost (matrix-ref cost-matrix row col)])
(when (and (not ijvisited)
(< ijcost lowest-cost))
(set! result (cons row col))
(set! lowest-cost ijcost))))
result))
(dijkstra get-neighbors get-cost get-tentative-cost set-tentative-cost! get-visited set-visited! select-next-node)
| false |
e3d586c5f7ad7748029338a7b8cd0cf17a6d51f1 | 72cc388b5e40b8dae679cd00286cc2ce325fb190 | /scribblings/tools.scrbl | 1c9760ce7a39658abcc4b805c726205c26afa51d | [
"MIT"
]
| permissive | johnstonskj/simple-oauth2 | 2d69d45b3b7ef6081ffac327816ecc563843bfba | b8cb40511f64dcb274e17957e6fc9ab4c8a6cbea | refs/heads/master | 2021-06-16T21:10:32.605629 | 2021-02-24T15:30:24 | 2021-02-24T15:30:24 | 167,589,021 | 13 | 4 | MIT | 2021-02-24T15:30:25 | 2019-01-25T17:49:42 | Racket | UTF-8 | Racket | false | false | 4,881 | scrbl | tools.scrbl | #lang scribble/manual
@(require racket/sandbox
scribble/core
scribble/eval
(for-label racket/base
racket/contract))
@;{============================================================================}
@(define example-eval (make-base-eval
'(require racket/string
oauth2)))
@;{============================================================================}
@title[]{Example Command Line Tools}
The following are tools to access commonly-used services that are OAuth 2.0
protected. They show how the client flows are used in a real application as well
as providing a framework for tools to use.
All tools need to determine their authorization state, which can be one of:
@itemlist[
@item{@italic{no client} - either no client stored for the service, or the
client has no @tt{id} and @tt{secret} stored.}
@item{@italic{no token} - the client is fully configured but has not been
used to fetch an authoriztion token.}
@item{@italic{authorized} - both the client and token are present in the
persistent storage.}
#:style 'ordered]
If the tools detect either of the first two states the tool will not perform
any protected calls, but force authorization. For services using code grant,
the use of the @tt{-i} and @tt{-s} flags are required. For services using
password grant the use of the @tt{-u} and @tt{-p} flags are required.
@verbatim|{
$ fitbit -i HDGGEX -s SGVsbG8gV29ybGQgZnJvbSBTaW1vbgo=
Fitbit returned authenication token: I2xhbmcgcmFja2V0L2Jhc2UKOzsKOzsg\
c2ltcGxlLW9hdXRoMiAtIHNpbXBsZS1vYXV0aDIuCjs7ICAgU2ltcGxlIE9BdXRoMiBjb\
GllbnQgYW5kIHNlcnZ
}|
All of the tools share two output formatting arguments; firstly specifying an
output format (using @tt{-f} which defaults to CSV) and output file to write
to (using @tt{-o}).
@;{============================================================================}
@section[]{Fitbit client}
This tool implements simple queries against the
@hyperlink["https://dev.fitbit.com/build/reference/web-api/"]{Fitbit API}.
Once the client has been authorized and the token stored, the tool will
perform queries against the @tt{sleep} and @tt{weight} scope. Queries support
a common set of arguments to specify either a single data (using @tt{-s}, which
defaults to the current data) or a data range (using @tt{-s} and @tt{-e}).
@verbatim|{
$ fitbit -h
fitbit [ <option> ... ] <scope>
where <option> is one of
/ -v, --verbose : Compile with verbose messages
\ -V, --very-verbose : Compile with very verbose messages
-s <start>, --start-date <start> : Start date (YYYY-MM-DD)
-e <end>, --end-date <end> : End date (YYYY-MM-DD)
-u <units>, --units <units> : Unit system (US, UK, metric)
-f <format>, --format <format> : Output format (csv)
-o <path>, --output-file <path> : Output file
--help, -h : Show this help
}|
The following example retrieves the sleep record for a data range as CSV.
@verbatim|{
$ fitbit -s 2018-07-16 -e 2018-07-21 sleep
date,start,minbefore,minasleep,minawake,minafter,efficiency,deep:min,\
deep:avg,deep:count,light:min,light:avg,light:count,rem:min,rem:avg, \
rem:count,wake:min,wake:avg,wake:count
2018-07-17,2018-07-16T23:42:00.000,0,494,40,1,97,122,0,6,197,0,21,175\
,0,6,40,0,20
}|
The following retrieves the current dates weight record formatted as an
on-screen table.
@verbatim|{
$ fitbit -f screen weight
┌───────────┬──────────┬────────┬───────┬──────────────────┐
│date │ time │ weight │ bmi │ fat │
├───────────┼──────────┼────────┼───────┼──────────────────┤
│2019-02-05 │ 15:04:16 │ 262.2 │ 35.59 │ 39.25299835205078│
└───────────┴──────────┴────────┴───────┴──────────────────┘
}|
@;{============================================================================}
@section[]{Livongo client}
This tool implements simple queries against the blood glucose @tt{readings} scope
provided by @hyperlink["https://my.livongo.com/#/dashboard"]{Livongo}.
@verbatim|{
$ livongo -h
livongo [ <option> ... ] <scope>
where <option> is one of
/ -v, --verbose : Compile with verbose messages
\ -V, --very-verbose : Compile with very verbose messages
-s <start>, --start-date <start> : Start date (YYYY-MM-DD), may include time (THH:MM:SS)
-e <end>, --end-date <end> : End date (YYYY-MM-DD), may include time (THH:MM:SS)
-f <format>, --format <format> : Output format (csv)
-o <path>, --output-file <path> : Output file
--help, -h : Show this help
}| | false |
53a44cc30498d6cc3a1226e2e932be3f6ff8bfd0 | 37858e0ed3bfe331ad7f7db424bd77bf372a7a59 | /book/1ed/08-arithmetic/divo_3_correct.rkt | 2b150a0c55b94c059368471f535f7f837cabc49e | []
| no_license | chansey97/the-reasoned-schemer | ecb6f6a128ff0ca078a45e097ddf320cd13e81bf | a6310920dde856c6c98fbecec702be0fbc4414a7 | refs/heads/main | 2023-05-13T16:23:07.738206 | 2021-06-02T22:24:51 | 2021-06-02T22:24:51 | 364,944,122 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,259 | rkt | divo_3_correct.rkt | #lang racket
(require "../libs/trs/mk.rkt")
(require "../07-arithmetic/poso.rkt")
(require "../07-arithmetic/pluso.rkt")
(require "../07-arithmetic/minuso.rkt")
(require "./mulo_2_correct.rkt")
(require "./length-comparison/eqlo.rkt")
(require "./length-comparison/ltlo.rkt")
(require "./length-comparison/ltelo_2_correct.rkt")
(require "./comparison/lto.rkt")
(require "./splito.rkt")
(provide (all-defined-out))
; 8.76.1
(define /o
(lambda (n m q r)
(condi
((== r n) (== '() q) (<o n m))
((== '(1) q) (=lo n m) (+o r m n)
(<o r m))
(else
(alli
(<lo m n)
(<o r m)
(poso q)
(fresh (nh nl qh ql qlm qlmr rr rh)
(alli
(splito n r nl nh)
(splito q r ql qh)
(conde
((== '() nh)
(== '() qh)
(-o nl r qlm)
(*o ql m qlm))
(else
(alli
(poso nh)
(*o ql m qlm)
(+o qlm r qlmr)
(-o qlmr nl rr)
(splito rr r '() rh)
(/o nh m qh rh)))))))))))
(module+ main
(require "../libs/trs/mkextraforms.rkt")
(require "../libs/test-harness.rkt")
(test-check "8.53"
(run 15 (t)
(fresh (n m q r)
(/o n m q r)
(== `(,n ,m ,q ,r) t)))
`((() (_.0 . _.1) () ())
((1) (1) (1) ())
((0 1) (1 1) () (0 1))
((0 1) (1) (0 1) ())
((1) (_.0 _.1 . _.2) () (1))
((_.0 1) (_.0 1) (1) ())
((0 _.0 1) (1 _.0 1) () (0 _.0 1))
((0 _.0 1) (_.0 1) (0 1) ())
((_.0 1) (_.1 _.2 _.3 . _.4) () (_.0 1))
((1 1) (0 1) (1) (1))
((0 0 1) (0 1 1) () (0 0 1))
((1 1) (1) (1 1) ())
((_.0 _.1 1) (_.2 _.3 _.4 _.5 . _.6) () (_.0 _.1 1))
((_.0 _.1 1) (_.0 _.1 1) (1) ())
((1 0 1) (0 1 1) () (1 0 1))))
)
| false |
351db3a03c8f15d7a10d610e55054b77e46be908 | d7c8a81db49505fa8e9d60e4fa8718f8a8a7850e | /class-tests/maze-walker.rkt | 3881f57441bc268f897592134854b42c41d6c65a | []
| no_license | KireinaHoro/scheme-assignments | 27eacedaa5183a79b6a4a8ef18b0e66211372f60 | 13a18f0a904c7f6c66059c3bdaf9a0a0fdcb8eb7 | refs/heads/master | 2020-04-10T03:15:59.469801 | 2018-06-07T08:41:36 | 2018-06-07T08:41:36 | 124,258,409 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,096 | rkt | maze-walker.rkt | #lang racket
(define N (read))
(define R #f)
(define C #f)
(define K #f)
(define (make-table r c v)
(define t (make-hash))
(for* ([x (in-range c)]
[y (in-range r)])
(table-set! t x y v))
t)
(define (table-set! t x y v)
(hash-set! t (list x y) v))
(define (table-ref t x y)
(hash-ref t (list x y) #f))
(define (get-offset s)
(case s
['u '(0 . -1)]
['d '(0 . 1)]
['l '(-1 . 0)]
['r '(1 . 0)]))
(define (transform-pos p s)
(let ([ss (get-offset s)])
(cons (+ (car p) (car ss))
(+ (cdr p) (cdr ss)))))
(define (valid-pos? p)
(let ([x (car p)]
[y (cdr p)])
(and (>= x 0) (>= y 0)
(< x C) (< y R))))
(define map #f)
(define steps #f)
(define (map-ref m p)
(table-ref m (car p) (cdr p)))
(define (map-set! m p v)
(table-set! m (car p) (cdr p) v))
(define (read-map)
(define (proc v)
(cond [(eq? v 'B) 0]
[(eq? v 'W) 100000]
[else 1]))
(set! R (read))
(set! C (read))
(set! K (read))
(set! map (make-table R C #f))
(set! steps (make-table R C 100000))
(table-set! steps 0 0 0)
(let lr ((iy 0))
(unless (= iy R)
(let lc ((ix 0))
(unless (= ix C)
(table-set! map ix iy (proc (read)))
(lc (+ ix 1))))
(lr (+ iy 1)))))
(define (walk pos)
(define (j s)
(valid-pos? (transform-pos pos s)))
(define (w s)
(define (proc-m m dst)
(- m (map-ref map dst)))
(define (proc-s s)
(+ s 1))
(let* ([newp (transform-pos pos s)]
[old-K K]
[new-K (proc-m K newp)]
[curr-s (map-ref steps pos)])
(when (and
(> (map-ref steps newp) (proc-s curr-s))
(>= (proc-m K newp) 0))
(map-set! steps newp (proc-s curr-s))
(set! K new-K)
(walk newp)
(set! K old-K))))
(for-each w (filter j '(u d l r))))
(define (run-eval)
(read-map)
(walk '(0 . 0))
(displayln
(let* ([pos (cons (- C 1) (- R 1))]
[s (map-ref steps pos)])
(if (> s 10000)
'inf
s))))
(for ([x (in-range N)])
(run-eval))
| false |
aeadd5ced51a2922a071df767400464f0e4a0a1a | 56c17ee2a6d1698ea1fab0e094bbe789a246c54f | /2016/day21/input.rkt | de2bf9cb671885f5b6c30c95c10bfc0add8e2b53 | [
"MIT"
]
| permissive | mbutterick/aoc-racket | 366f071600dfb59134abacbf1e6ca5f400ec8d4e | 14cae851fe7506b8552066fb746fa5589a6cc258 | refs/heads/master | 2022-08-07T10:28:39.784796 | 2022-07-24T01:42:43 | 2022-07-24T01:42:43 | 48,712,425 | 39 | 5 | null | 2017-01-07T07:47:43 | 2015-12-28T21:09:38 | Racket | UTF-8 | Racket | false | false | 2,948 | rkt | input.rkt | #lang reader "lang.rkt"
abcdefgh
swap position 5 with position 6
reverse positions 1 through 6
rotate right 7 steps
rotate based on position of letter c
rotate right 7 steps
reverse positions 0 through 4
swap letter f with letter h
reverse positions 1 through 2
move position 1 to position 0
rotate based on position of letter f
move position 6 to position 3
reverse positions 3 through 6
rotate based on position of letter c
rotate based on position of letter b
move position 2 to position 4
swap letter b with letter d
move position 1 to position 6
move position 7 to position 1
swap letter f with letter c
move position 2 to position 3
swap position 1 with position 7
reverse positions 3 through 5
swap position 1 with position 4
move position 4 to position 7
rotate right 4 steps
reverse positions 3 through 6
move position 0 to position 6
swap position 3 with position 5
swap letter e with letter h
rotate based on position of letter c
swap position 4 with position 7
reverse positions 0 through 5
rotate right 5 steps
rotate left 0 steps
rotate based on position of letter f
swap letter e with letter b
rotate right 2 steps
rotate based on position of letter c
swap letter a with letter e
rotate left 4 steps
rotate left 0 steps
move position 6 to position 7
rotate right 2 steps
rotate left 6 steps
rotate based on position of letter d
swap letter a with letter b
move position 5 to position 4
reverse positions 0 through 7
rotate left 3 steps
rotate based on position of letter e
rotate based on position of letter h
swap position 4 with position 6
reverse positions 4 through 5
reverse positions 5 through 7
rotate left 3 steps
move position 7 to position 2
move position 3 to position 4
swap letter b with letter d
reverse positions 3 through 4
swap letter e with letter a
rotate left 4 steps
swap position 3 with position 4
swap position 7 with position 5
rotate right 1 step
rotate based on position of letter g
reverse positions 0 through 3
swap letter g with letter b
rotate based on position of letter b
swap letter a with letter c
swap position 0 with position 2
reverse positions 1 through 3
rotate left 7 steps
swap letter f with letter a
move position 5 to position 0
reverse positions 1 through 5
rotate based on position of letter d
rotate based on position of letter c
rotate left 2 steps
swap letter b with letter a
swap letter f with letter c
swap letter h with letter f
rotate based on position of letter b
rotate left 3 steps
swap letter b with letter h
reverse positions 1 through 7
rotate based on position of letter h
swap position 1 with position 5
rotate left 1 step
rotate based on position of letter h
reverse positions 0 through 1
swap position 5 with position 7
reverse positions 0 through 2
reverse positions 1 through 3
move position 1 to position 4
reverse positions 1 through 3
rotate left 1 step
swap position 4 with position 1
move position 1 to position 3
rotate right 2 steps
move position 0 to position 5 | false |
095d02bd6d0bc0ef63732466d213de3c768f75ee | 471a04fa9301455c51a890b8936cc60324a51f27 | /srfi-test/tests/srfi/1/alist-test.rkt | 4bb0dfd13c2a0851b75e58976e7032eec0fe985f | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
]
| permissive | racket/srfi | e79e012fda6d6bba1a9445bcef461930bc27fde8 | 25eb1c0e1ab8a1fa227750aa7f0689a2c531f8c8 | refs/heads/master | 2023-08-16T11:10:38.100847 | 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 | 10,977 | rkt | alist-test.rkt | ;;;
;;; <alist-test.rkt> ---- Association list tests
;;; Time-stamp: <2008-03-07 16:36:15 nhw>
;;;
;;; Copyright (C) 2002 by Noel Welsh.
;;;
;;; This file is part of SRFI-1.
;;; SRFI-1 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 2.1 of the License, or (at your option) any later version.
;;; SRFI-1 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 SRFI-1; if not, write to the Free Software
;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
;;; Author: Noel Welsh <[email protected]>
;;
;;
;; Commentary:
;; Originally created by:
;; John David Stone
;; Department of Mathematics and Computer Science
;; Grinnell College
;; [email protected]
(module alist-test mzscheme
(require rackunit)
(require (all-except srfi/1/alist assoc)
(rename srfi/1/alist s:assoc assoc))
(provide alist-tests)
(define alist-tests
(test-suite
"Association list tests"
;; ALIST-CONS
(test-case
"alist-cons:null-list"
(check-equal? (alist-cons 'Manawa 'Manchester '())
'((Manawa . Manchester))))
(test-case
"alist-cons:singleton-list"
(let* ((base '((Manilla . Manly)))
(result (alist-cons 'Manning 'Manson base)))
(check-equal? result '((Manning . Manson)
(Manilla . Manly)))
(check-eq? (cdr result) base)))
(test-case
"alist-cons:longer-list"
(let* ((base '((Manteno . Mapleside)
(Mapleton . Maquoketa)
(Marathon . Marcus)
(Marengo . Marietta)
(Marion . Mark)))
(result (alist-cons 'Marne 'Marquette base)))
(check-equal? result
'((Marne . Marquette)
(Manteno . Mapleside)
(Mapleton . Maquoketa)
(Marathon . Marcus)
(Marengo . Marietta)
(Marion . Mark)))
(check-eq? (cdr result) base)))
(test-case
"alist-cons:longer-list-with-duplicate-key"
(let* ((base '((Marquisville . Marsh)
(Marshalltown . Martelle)
(Martensdale . Martinsburg)
(Martinstown . Marysville)
(Masonville . Massena)
(Massey . Massilon)
(Matlock . Maud)))
(result (alist-cons 'Masonville 'Maurice base)))
(check-equal? result '((Masonville . Maurice)
(Marquisville . Marsh)
(Marshalltown . Martelle)
(Martensdale . Martinsburg)
(Martinstown . Marysville)
(Masonville . Massena)
(Massey . Massilon)
(Matlock . Maud)))
(check-eq? (cdr result) base)))
;; ALIST-COPY
(test-case
"alist-copy:null-list"
(check-true (null? (alist-copy '()))))
(test-case
"alist-copy:flat-list"
(let* ((original '((Maxon . Maxwell)
(Maynard . Maysville)
(McCallsburg . McCausland)
(McClelland . McGregor)
(McIntire . McNally)))
(result (alist-copy original)))
(check-true
(and (equal? result original)
(not (eq? result original))
(not (eq? (car result) (car original)))
(not (eq? (cdr result) (cdr original)))
(not (eq? (cadr result) (cadr original)))
(not (eq? (cddr result) (cddr original)))
(not (eq? (caddr result) (caddr original)))
(not (eq? (cdddr result) (cdddr original)))
(not (eq? (cadddr result) (cadddr original)))
(not (eq? (cddddr result) (cddddr original)))
(not (eq? (car (cddddr result))
(car (cddddr original))))))))
(test-case
"alist-copy:bush"
(let* ((first '(McPaul))
(second '(McPherson
Mechanicsville
Mederville
(Mediapolis Medora)
((Mekee Melbourne Melcher))))
(third 'Melrose)
(original (list (cons 'Meltonville first)
(cons 'Melvin second)
(cons 'Menlo third)))
(result (alist-copy original)))
(check-true
(and (equal? result original)
(not (eq? result original))
(not (eq? (car result) (car original)))
(eq? (cdar result) first)
(not (eq? (cdr result) (cdr original)))
(not (eq? (cadr result) (cadr original)))
(eq? (cdadr result) second)
(not (eq? (cddr result) (cddr original)))
(not (eq? (caddr result) (caddr original)))
(eq? (cdaddr result) third)))))
;; ALIST-DELETE
(test-case
"alist-delete:null-list"
(check-true (null? (alist-delete 'Mercer '() (lambda (x y) #t)))))
(test-case
"alist-delete:singleton-list"
(check-equal?
(alist-delete 'Meriden
'((Merrill . Merrimac)))
'((Merrill . Merrimac))))
(test-case
"alist-delete:all-elements-removed"
(check-true
(null? (alist-delete 'Meservey
'((Metz . Meyer)
(Middleburg . Middletwon)
(Midvale . Midway)
(Miles . Milford)
(Miller . Millersburg))
(lambda (x y) #t)))))
(test-case
"alist-delete:some-elements-removed"
(check-equal?
(alist-delete 561
'((562 . 563)
(565 . 564)
(566 . 567)
(569 . 568)
(570 . 571))
(lambda (x y) (odd? (+ x y))))
'((565 . 564) (569 . 568))))
(test-case
"alist-delete:no-elements-removed"
(check-equal?
(alist-delete 'Millerton
'((Millman . Millnerville)
(Millville . Milo)
(Milton . Minburn)
(Minden . Mineola)
(Minerva . Mingo))
(lambda (x y) #f))
'((Millman . Millnerville)
(Millville . Milo)
(Milton . Minburn)
(Minden . Mineola)
(Minerva . Mingo))))
;; ALIST-DELETE!
;; ALIST-DELETE
(test-case
"alist-delete:null-list"
(check-true (null? (alist-delete '(Reasnor . Redding) '()))))
(test-case
"alist-delete:in-singleton-list"
(check-true (null?
(alist-delete '(Redfield . Reeceville)
'(((Redfield . Reeceville) . Reinbeck))))))
(test-case
"alist-delete:not-in-singleton-list"
(check-equal?
(alist-delete '(Rembrandt . Remsen)
'(((Renwick . Republic) . Rhodes)))
'(((Renwick . Republic) . Rhodes))))
(test-case
"alist-delete:at-beginning-of-longer-list"
(check-equal?
(alist-delete '(Riceville . Richard)
'(((Riceville . Richard) . Richfield)
((Richland . Richmond) . Rickardsville)
((Ricketts . Rider) . Ridgeport)
((Ridgeway . Riggs) . Rinard)
((Ringgold . Ringsted) . Rippey)))
'(((Richland . Richmond) . Rickardsville)
((Ricketts . Rider) . Ridgeport)
((Ridgeway . Riggs) . Rinard)
((Ringgold . Ringsted) . Rippey))))
(test-case
"alist-delete:in-middle-of-longer-list"
(check-equal?
(alist-delete '(Ritter . Riverdale)
'(((Riverside . Riverton) . Roberts)
((Robertson . Robins) . Robinson)
((Rochester . Rockdale) . Rockford)
((Rockville . Rockwell) . Rodman)
((Ritter . Riverdale) . Rodney)
((Roelyn . Rogers) . Roland)
((Rolfe . Rome) . Roscoe)))
'(((Riverside . Riverton) . Roberts)
((Robertson . Robins) . Robinson)
((Rochester . Rockdale) . Rockford)
((Rockville . Rockwell) . Rodman)
((Roelyn . Rogers) . Roland)
((Rolfe . Rome) . Roscoe))))
(test-case
"alist-delete:at-end-of-longer-list"
(check-equal?
(alist-delete '(Rose . Roselle)
'(((Roseville . Ross) . Rosserdale)
((Rossie . Rossville) . Rowan)
((Rowley . Royal) . Rubio)
((Ruble . Rudd) . Runnells)
((Rose . Roselle) . Russell)))
'(((Roseville . Ross) . Rosserdale)
((Rossie . Rossville) . Rowan)
((Rowley . Royal) . Rubio)
((Ruble . Rudd) . Runnells))))
(test-case
"alist-delete:not-in-longer-list"
(check-equal?
(alist-delete '(Ruthven . Rutland)
'(((Rutledge . Ryan) . Sabula)
((Sageville . Salem) . Salina)
((Salix . Sanborn) . Sandusky)
((Sandyville . Santiago) . Saratoga)
((Sattre . Saude) . Savannah)))
'(((Rutledge . Ryan) . Sabula)
((Sageville . Salem) . Salina)
((Salix . Sanborn) . Sandusky)
((Sandyville . Santiago) . Saratoga)
((Sattre . Saude) . Savannah))))
(test-case
"alist-delete:several-matches-in-longer-list"
(check-equal?
(alist-delete '(Sawyer . Saylor)
'(((Saylorville . Scarville) . Schaller)
((Schleswig . Schley) . Sciola)
((Sawyer . Saylor) . Scranton)
((Searsboro . Sedan) . Selma)
((Sawyer . Saylor) . Seneca)
((Seney . Sewal) . Sexton)
((Sawyer . Saylor) . Seymour)))
'(((Saylorville . Scarville) . Schaller)
((Schleswig . Schley) . Sciola)
((Searsboro . Sedan) . Selma)
((Seney . Sewal) . Sexton))))
;; ALIST-DELETE!
))
)
;;; alist-test.rkt ends here
| false |
b35b11dad203ea20c80e4212e76325c141fd94d3 | 9db1a54c264a331b41e352365e143c7b2b2e6a3e | /code/chapter_1/pascal.rkt | c814151f0acf3871f33b496dc7e688073b81b285 | []
| no_license | magic3007/sicp | 7103090baa9a52a372be360075fb86800fcadc70 | b45e691ae056410d0eab57d65c260b6e489a145b | refs/heads/master | 2021-01-27T10:20:28.743896 | 2020-06-05T15:17:10 | 2020-06-05T15:17:10 | 243,478,192 | 4 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 671 | rkt | pascal.rkt | #lang racket
(define (print list)
(if(null? list)
(newline)
(begin (display (car list)) (display " ") (print (cdr list)))
)
)
(define (scan list res)
(cond ((= (length list) 0) (begin (print res) res))
((= (length list) 1) (scan '() (cons 1 res)))
(else
(scan (cdr list)
(cons (+ (car list) (cadr list)) res)
)
)
)
)
(define (pascal n list)
(if (eq? n 0)
(void)
(pascal (- n 1) (scan list '(1)))
)
)
(define (testcase n)
(if (eq? n eof)
(void)
(begin (pascal n '()) (testcase (read)))
)
)
(testcase (read)) | false |
093ea37fa3d90798ada2b31169b47efb867112a5 | b0c07ea2a04ceaa1e988d4a0a61323cda5c43e31 | /www/notes/juvie.scrbl | 3870ffb5b2c943a7e56885f51f8d9ec1c150d869 | [
"AFL-3.0"
]
| permissive | cmsc430/www | effa48f2e69fb1fd78910227778a1eb0078e0161 | 82864f846a7f8f6645821e237de42fac94dff157 | refs/heads/main | 2023-09-03T17:40:58.733672 | 2023-08-28T15:26:33 | 2023-08-28T15:26:33 | 183,064,322 | 39 | 30 | null | 2023-08-28T15:49:59 | 2019-04-23T17:30:12 | Racket | UTF-8 | Racket | false | false | 3,162 | scrbl | juvie.scrbl | #lang scribble/manual
@(require (for-label (except-in racket ...)))
@(require redex/pict
racket/runtime-path
scribble/examples
"utils.rkt"
"ev.rkt"
"../utils.rkt")
@(define codeblock-include (make-codeblock-include #'h))
@;(for-each (λ (f) (ev `(require (file ,(path->string (build-path notes "iniquity" f))))))
@; '("interp.rkt" "ast.rkt" "parse.rkt" "compile.rkt" "asm/interp.rkt" "asm/printer.rkt"))
@(define this-lang "Juvie")
@title[#:tag this-lang]{@|this-lang|: cleaning up after your mess}
@src-code[this-lang]
@emph{Many a man fails to become a thinker for the sole reason that his memory is too good.}
@table-of-contents[]
@section[#:tag-prefix "juvie"]{Remembering to Forget}
By combining the chocolate and peanut butter of
@secref{Hustle} and @secref{Iniquity}, we have achieved a truly
powerful programming language. Indeed, we have achieved the
@emph{ultimate} power: Turing completeness. Every computable
function can be written as a program in our language. (To
convince yourself, try thinking of how you could translate
any Turing machine description into a program in your
language.) In principle, there's nothing more to do.
Pragmatically speaking, of course, there's plenty to do.
There's a reason we don't program by defining Turing
machines. But of the first pragmatic issues to grapple with
is also at the heart of the Turing machine abstraction: the
myth of the inifinite tape.
For the purposes of the theory of computation, it's
perfectly reasonable to assume you have an infinitely long
tape that serves as a model of a computer's memory. A Turing
machine never actually looks at the whole tape at once; it
just gets to see a cell at a time. So you don't actually
need to materialize an impossibly long tape. Instead, the
thinking goes, if you need more tape, more tape can be
procurred @emph{as needed}. That same idea is at play in our
language.
The run-time system allocates a fixed-size heap at start-up
and the program is handed the address of the beginning of
the heap. The program ``allocates'' memory by bumping this
address forward. It @emph{never} deallocates. Memory is only
consumed. What happens if we reach the end of the heap? Bad
things. But just like in Turing machines, we could at least
in principle make the heap bigger. You want more tape? Now
is the time to make it.
But does getting to the end of the heap really mean more
memory is needed?
Suppose for example, we had an extremely small heap that was only
capable of holding two words and that we were executing the
following, admittedly silly, program:
@#reader scribble/comment-reader
(racketblock
(let ((y (let ((x (cons 3 4)))
(+ (car x) (cdr x)))))
(cons y y))
)
The program will start by allocating two words for a
cons-cell to hold @racket[(cons 3 4)], the compute the sum
of the pair before then trying, and failing to allocate a
cons-cell for @racket[(cons 3 4)].
But it's fairly easy to see that once the inner
@racket[let]-expression is evaluated, that first cons-cell
is unreachable. And yet it will persist in the heap until
the program finishes executing. What if we could get that
memory back?
| false |
17d7d9ef3406f60866c326d121da01916114d73f | b996d458a2d96643176465220596c8b747e43b65 | /how-to-code-complex-data/problem-bank/2-one-of/merge.rkt | 48d7007adb20bdcd7e5008f7e1e72cd395846660 | [
"MIT"
]
| permissive | codingram/courses | 99286fb9550e65c6047ebd3e95eea3b5816da2e0 | 9ed3362f78a226911b71969768ba80fb1be07dea | refs/heads/master | 2023-03-21T18:46:43.393303 | 2021-03-17T13:51:52 | 2021-03-17T13:51:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,541 | rkt | merge.rkt | #lang htdp/bsl+
;; Problem:
;;
;; Design the function merge. It consumes two lists of numbers, which it assumes are
;; each sorted in ascending order. It produces a single list of all the numbers,
;; also sorted in ascending order.
;;
;; Your solution should explicitly show the cross product of type comments table,
;; filled in with the values in each case. Your final function should have a cond
;; with 3 cases. You can do this simplification using the cross product table by
;; recognizing that there are subtly equal answers.
;;
;; Hint: Think carefully about the values of both lists. You might see a way to
;; change a cell content so that 2 cells have the same value.
;; ListOfInteger ListOfInteger -> ListOfInteger
;; Merge the two given list in ascending order.
;; This is basically the merge part of the mergesort algorithm.
(define (merge lista listb)
(cond [(empty? lista) listb]
[(empty? listb) lista]
[else
(if (<= (first lista) (first listb))
(cons (first lista) (merge (rest lista) listb))
(cons (first listb) (merge lista (rest listb))))]))
;; ========
;; Tests:
(check-expect (merge empty empty) empty)
(check-expect (merge '(1 2) empty) '(1 2))
(check-expect (merge empty '(1 2)) '(1 2))
(check-expect (merge '(1) '(2)) '(1 2))
(check-expect (merge '(2) '(1)) '(1 2))
(check-expect (merge '(1 4) '(2)) '(1 2 4))
(check-expect (merge '(3 5) '(1)) '(1 3 5))
(check-expect (merge '(1 4) '(2 3 5)) '(1 2 3 4 5))
(check-expect (merge '(3 4 5) '(1 6)) '(1 3 4 5 6))
| false |
3da8682caa6fc7d16b3301c53b9c9892b401a94f | 5db3f2f9de0c6110ce08e20b6ffe17bb349418e5 | /preprocess.rkt | a45bc425407e81a857bff5210e5762eff1e02886 | []
| no_license | kiriloman/Preprocessor | 56cb3605a387eb5f6a713f04a64202f23a9cbc8b | 0e3e5f68078e610c50e0215486ab039e927f56c3 | refs/heads/master | 2020-03-15T02:08:28.605849 | 2018-05-10T19:44:30 | 2018-05-10T19:44:30 | 131,911,026 | 0 | 0 | null | 2018-05-10T19:44:30 | 2018-05-02T22:10:26 | Racket | UTF-8 | Racket | false | false | 3,920 | rkt | preprocess.rkt | #lang racket
(provide add-active-token def-active-token process-string)
(require srfi/13)
;Hashtable with tokens and associated functions
(define associations (make-hash))
;Adds a token with respective function to a hashmap for later use in process-string
(define (add-active-token token function)
(hash-set! associations token function))
;def-active-token macro
(define-syntax-rule (def-active-token token str body)
(hash-set! associations token
(lambda str body)))
;token-to-execute decides which token (if any) comes first in the given string and returns its position
;returns an empty list if no token is present
(define (token-to-execute str)
(let ([token null]
[position (string-length str)])
(for ([(key value) associations])
(let ([key-position (regexp-match-positions (string-append key "[^a-zA-Z0-9]") str)])
(cond
[(and key-position (equal? (caar key-position) 0)) (set! position 0) (set! token key)]
[else (set! key-position (regexp-match-positions (string-append "[^a-zA-Z0-9]" key "[^a-zA-Z0-9]") str))
(cond
[(and key-position (< (caar key-position) position)
(set! position (caar key-position))
(set! token key))])])))
token))
;Recursively applies first token found in a string appending the results together
(define (process-string str)
(let ([token (token-to-execute str)])
(cond
[(empty? token) str]
[else (string-append (substring str 0 (string-contains str token))
(process-string ((hash-ref associations token)
(substring str (string-contains str token)))))])))
;Tokens implementation
;Local Type Inference
(def-active-token "var" (str)
(string-append (substring str (+ (string-contains str "new ") 4) (string-contains str "("))
(substring str 3)))
;String Interpolation
(def-active-token "#" (str)
(if (not (equal? (second (string->list str)) #\"))
(string-append "\" + ("
(substring str (+ (string-contains str "{") 1) (string-contains str "}"))
") + \""
(substring str (+ (string-contains str "}") 1)))
(substring str 1)))
;Type Aliases
(def-active-token "alias" (str)
(let ([alias (string-trim-all
(substring str (+ (string-contains str "alias ") 6) (string-contains str "=")))]
[type (string-trim-all
(substring str (+ (string-contains str "=") 1) (string-contains str ";")))])
(set! str (substring str (+ (string-contains str ";") 1)))
(string-replace-substring str alias type)))
;Replace substr in str with newsubstring
(define (string-replace-substring str substr newsubstring)
(let ([regexp-substr (string-append "[^a-zA-Z0-9]" substr "[^a-zA-Z0-9]")])
(if (regexp-match-positions regexp-substr str)
(let ([fromindex (caar (regexp-match-positions regexp-substr str))]
[toindex (cdar (regexp-match-positions regexp-substr str))])
(string-append (string-append (substring str 0 (+ fromindex 1)) newsubstring)
(string-replace-substring (substring str (- toindex 1)) substr newsubstring)))
str)))
;Helpers
;Trims left side of the given string from spaces
(define (string-trim-all-left str)
(if (or (equal? (string-contains str " ") 0) (equal? (string-contains str "\n") 0) (equal? (string-contains str "\t") 0)) ;se tem espaço no inicio
(string-append (string-trim-all-left (substring str 1)))
str))
;Trims left and right side of the given string from spaces
(define (string-trim-all str)
(list->string (reverse
(string->list (string-trim-all-left (list->string (reverse
(string->list (string-trim-all-left str)))))))))
| true |
f71cf96f9d171a5903e0787a91a5a7fc06bc5e0a | 5bbc152058cea0c50b84216be04650fa8837a94b | /benchmarks/stack/typed/stack.rkt | c396f02add1bcff896361355601c898a668d224c | []
| no_license | nuprl/gradual-typing-performance | 2abd696cc90b05f19ee0432fb47ca7fab4b65808 | 35442b3221299a9cadba6810573007736b0d65d4 | refs/heads/master | 2021-01-18T15:10:01.739413 | 2018-12-15T18:44:28 | 2018-12-15T18:44:28 | 27,730,565 | 11 | 3 | null | 2018-12-01T13:54:08 | 2014-12-08T19:15:22 | Racket | UTF-8 | Racket | false | false | 210 | rkt | stack.rkt | #lang typed/racket/base
(define-type Stack (Listof Integer))
(provide
Stack
init push)
(: init (-> Stack))
(: push (Stack Integer . -> . Stack))
(define (init)
'())
(define (push st i)
(cons i st))
| false |
51210122e43e9d74568c9d5bc1bc29d33c98d879 | 7b04163039ff4cea3ac9b5b6416a134ee49ca1e4 | /try.rkt | c8cee2f0cddd5c4bead690ee309ea595e76de930 | []
| no_license | dstorrs/racket-dstorrs-libs | 4c94219baf3c643a696aa17ed0e81d4a0ab18244 | 7e816d2b5f65a92ab01b29a320cc2c71d7870dbb | refs/heads/master | 2022-08-27T22:31:38.985194 | 2022-08-05T21:35:35 | 2022-08-05T21:35:35 | 68,236,201 | 6 | 1 | null | 2018-10-19T15:37:12 | 2016-09-14T19:24:52 | Racket | UTF-8 | Racket | false | false | 7,156 | rkt | try.rkt | #lang racket/base
(require (for-syntax racket/base
syntax/parse)
racket/function)
;; PURPOSE: Racket's with-handlers has poor end weight; it puts the
;; error conditions first, distracting from the actual point of the
;; code. try/catch is a better mechanism -- the code comes first
;; with the error handling tucked out of the way where you don't need
;; to look at it unless you actually need to look at it.
;; try/catch/finally also provides an easy way to do cleanup during
;; exception handling.
;
;; USAGE:
;;
;; Standard with-handlers. (NB: functions in the body are just examples, not real)
;; (with-handlers ([exn:fail:contract? (lambda (e) ...lots of stuff...)]
;; [string? (lambda (e) ...more stuff...)]
;; [exn:fail:tcp-connect? (lambda (e) ...even more stuff...)])
;;
;; (define server-handle (or (connect-to-server) (raise "could not connect")))
;; (define user (get-user-data server-handle (get-password)))
;; ...etc...
;; )
;;
;; ;With the above code you're four lines in before you find out what
;; ;the code actually does...and that's assuming that the exception
;; ;handlers are concise, one-line things, which they might not be.
;; ;Compare to an equivalent try/catch:
;;
;; (try [
;; (define server-handle (or (connect-to-server) (raise "could not connect")))
;; (define user (get-user-data server-handle (get-password)))
;; ...etc...
;; ]
;; [catch ([exn:fail:contract? (lambda (e) ...lots of stuff...)]
;; [string? (lambda (e) ...more stuff...)]
;; [exn:fail:tcp-connect? (lambda (e) ...even more stuff...)])])
;;
;; ; With the try/catch block you immediately know that you're
;; ; dealing with something that's connecting to a server and fetching
;; ; user data. You can read the happy path first to understand
;; ; what's supposed to happen, then look in the 'catch' block to see
;; ; how it handles problems.
;;
;;
;; ; But wait, there's more! Want to have some cleanup that is
;; ; guaranteed to happen even if there's an exception? We've got you
;; ; covered
;; (try [(displayln "foo") (raise-syntax-error 'name "message")]
;; [catch (exn:fail? (lambda (e) (displayln "caught!")))]
;; [finally (displayln "finally 1") (displayln "finally 2")]
;; )
;;
;; Output:
;; foo
;; finally 1
;; finally 2
;; caught!
;;
;; ; Still not enough? How about some preflight setup that is
;; ; guaranteed to happen before the body executes, even in the
;; ; presence of jumping in and out via continuation?
;; (try [(displayln "body") (raise "foo")]
;; [pre (displayln "pre")]
;; [catch (string? (lambda (e) (displayln "caught!")))]
;; [finally (say "finally")])
;;
;; Output:
;; pre
;; body
;; finally!
;; caught!
;;
;; ; 'try' still works inside a dynamic-wind even though it generates one:
;; (dynamic-wind
;; (thunk (displayln "outer pre"))
;; (thunk (try [(displayln "body") (raise "error!")]
;; [pre (displayln "body pre")]
;; [catch (string? (lambda (e) (displayln "body catch")))]
;; [finally (displayln "body finally")]))
;; (thunk (displayln "outer finally")))
;;
;; Output:
;; outer pre
;; body pre
;; body
;; body finally
;; body catch
;; outer finally
;;
;; The return value from a try is:
;; *) If no exception raised: The result of the 'try' block
;; *) If exception raised: The result of the 'catch' block
;;
;; The following combinations are legal:
;; try ; traps anything that's raised, returns it. (i.e., defatalizes it)
;; try + catch
;; try + pre + catch
;; try + catch + finally
;; try + pre + catch + finally
(define-syntax (try stx)
(syntax-parse stx
#:datum-literals (try catch pre finally)
[(try [body0:expr body1:expr ...])
#'(with-handlers ((identity identity))
body0
body1
...
)]
[(try [body0:expr body1:expr ...]
[catch catch0:expr catch1:expr ...])
#'(with-handlers (catch0 catch1 ...)
body0
body1
...
)]
[(try [pre p0:expr p1:expr ... ]
[body0:expr body1:expr ...])
#'(with-handlers ((identity identity))
(dynamic-wind
(thunk p0 p1 ...)
(thunk body0
body1
...)
(thunk '()))
)]
[(try [pre p0:expr p1:expr ... ]
[body0:expr body1:expr ...]
[catch catch0 catch1 ...])
#'(with-handlers (catch0 catch1 ...)
(dynamic-wind
(thunk p0 p1 ...)
(thunk body0
body1
...)
(thunk '()))
)]
[(try [pre p0:expr p1:expr ... ]
[body0:expr body1:expr ...]
[finally f0 f1 ...])
#'(with-handlers ((identity identity))
(dynamic-wind
(thunk p0 p1 ...)
(thunk body0
body1
...)
(thunk f0 f1 ...))
)]
[(try [pre p0:expr p1:expr ... ]
[body0:expr body1:expr ...]
[catch catch0 catch1 ...]
[finally f0 f1 ...])
#'(with-handlers (catch0 catch1 ...)
(dynamic-wind
(thunk p0 p1 ...)
(thunk body0
body1
...)
(thunk f0 f1 ...))
)]
[(try [body0 body1 ...]
[catch catch0 catch1 ...]
[finally f0 f1 ... ])
#'(with-handlers (catch0 catch1 ...)
(dynamic-wind
(thunk '())
(thunk body0
body1
...)
(thunk f0 f1 ...)
))]
[(try [body0 body1 ...]
[finally f0 f1 ... ])
#'(with-handlers ([(lambda (x) #t) raise])
(dynamic-wind
(thunk '())
(thunk body0
body1
...)
(thunk f0 f1 ...)
))]
[(try [body0 body1 ...]
[pre p0 p1 ... ]
[finally f0 f1 ... ])
#'(with-handlers ([(lambda (x) #t) raise])
(dynamic-wind
(thunk p0 p1 ...)
(thunk body0
body1
...)
(thunk f0 f1 ...)
))]
[(try [body0 body1 ...]
[pre pre0 pre1 ...]
[catch catch0 catch1 ... ])
#'(with-handlers (catch0 catch1 ...)
(dynamic-wind
(thunk pre0 pre1 ...)
(thunk body0 body1 ...)
(thunk '())
))]
[(try [body0 body1 ...]
[pre pre0 pre1 ...]
[catch catch0 catch1 ...]
[finally f0 f1 ... ])
#'(with-handlers (catch0 catch1 ...)
(dynamic-wind
(thunk pre0 pre1 ...)
(thunk body0
body1
...)
(thunk f0 f1 ...)
))]
))
(define-syntax (defatalize stx)
(syntax-parse stx
[(defatalize body0 body1 ...)
#'(with-handlers ([exn:break? raise]
[(lambda (e) #t) identity])
body0
body1 ...)]))
(provide (all-defined-out))
| true |
9765e2619028b9d07728168080f455213bd2b67c | 20a9cc2e1884f9e3e8f953ccd7b04e3e4c820f1a | /src/patch.rkt | e8e01843174f6061eb1d6b2e0f8181db0349acae | [
"MIT"
]
| permissive | iCodeIN/herbie | 741c2b10b821041c1d234b4c4ee7b57af47a7a3a | d3249e9721223fd6acc70f4a0d21b37f8e2ecfdc | refs/heads/master | 2023-09-06T08:22:59.517664 | 2021-10-01T15:30:05 | 2021-10-01T15:30:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 12,939 | rkt | patch.rkt | #lang racket
(require "core/matcher.rkt" "core/taylor.rkt" "core/simplify.rkt"
"alternative.rkt" "common.rkt" "interface.rkt" "programs.rkt"
"timeline.rkt" "syntax/rules.rkt" "syntax/sugar.rkt")
(provide
(contract-out
[patch-table-has-expr? (-> expr? boolean?)]
[patch-table-run-simplify (-> (listof alt?) (listof alt?))]
[patch-table-run (-> (listof (cons/c (listof symbol?) expr?))
(listof (cons/c (listof symbol?) expr?))
(listof alt?))]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;; Patch table ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(struct patchtable (table queued queuedlow rewrites series final) #:mutable)
; The "patch table"
; Stores a mapping from expression to improvements (expr -> (listof exprs))
(define *patch-table* (patchtable (make-hash) '() '() #f #f #f))
; patch table may be invalidated between runs
(register-reset
(λ () (set! *patch-table* (patchtable (make-hash) '() '() #f #f #f))))
; setters / getters
(define (^queued^ [val #f])
(when val (set-patchtable-queued! *patch-table* val))
(patchtable-queued *patch-table*))
(define (^queuedlow^ [val #f])
(when val (set-patchtable-queuedlow! *patch-table* val))
(patchtable-queuedlow *patch-table*))
(define (^rewrites^ [val #f])
(when val (set-patchtable-rewrites! *patch-table* val))
(patchtable-rewrites *patch-table*))
(define (^series^ [val #f])
(when val (set-patchtable-series! *patch-table* val))
(patchtable-series *patch-table*))
(define (^final^ [val #f])
(when val (set-patchtable-final! *patch-table* val))
(patchtable-final *patch-table*))
; Adds an improvement to the patch table
; If `improve` is not provided, a key is added
; with no improvements
(define (add-patch! expr [improve #f])
(when (*use-improve-cache*)
(hash-update! (patchtable-table *patch-table*) expr
(if improve (curry cons improve) identity) (list))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;; Internals ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define transforms-to-try
(let ([invert-x (λ (x) `(/ 1 ,x))] [exp-x (λ (x) `(exp ,x))] [log-x (λ (x) `(log ,x))]
[ninvert-x (λ (x) `(/ 1 (neg ,x)))])
`((0 ,identity ,identity)
(inf ,invert-x ,invert-x)
(-inf ,ninvert-x ,ninvert-x)
#;(exp ,exp-x ,log-x)
#;(log ,log-x ,exp-x))))
;; Taylor is problematic since it doesn't know what reprs are
;; There are two types of errors that occur due to this inconsistency
;; - reduce:
;; the internal simplifier will try to desugar an subexpression
;; with an operator/precision mismatch
;; - external:
;; Taylor is successful in generating an expression but
;; external desugaring fails because of an unsupported/mismatched
;; operator
(define (taylor-fail-desugaring expr)
(λ _
(debug #:from 'progress #:depth 5 "Series expansion (desugaring failure)")
(debug #:from 'progress #:depth 5 "Problematic expression: " expr)
#f))
; taylor uses older format, resugaring and desugaring needed
; not all taylor transforms are valid in a given repr, return false on failure
(define (taylor-expr expr repr var f finv)
(define expr* (resugar-program expr repr #:full #f))
(with-handlers ([exn:fail? (const #f)]) ; in case taylor fails internally
(define genexpr (approximate expr* var #:transform (cons f finv)))
(λ (x) (desugar-program (genexpr) repr (*var-reprs*) #:full #f))))
(define (taylor-alt altn)
(define expr (program-body (alt-program altn)))
(define repr (repr-of expr (*output-repr*) (*var-reprs*)))
(define vars (free-variables expr))
(reap [sow]
(for* ([var vars] [transform-type transforms-to-try])
(match-define (list name f finv) transform-type)
(define genexpr (taylor-expr expr repr var f finv))
(cond
[genexpr ; taylor successful
#;(define pts (for/list ([(p e) (in-pcontext (*pcontext*))]) p))
(for ([i (in-range 4)])
(define expr*
(with-handlers ([exn:fail? (taylor-fail-desugaring expr)]) ; failed on desugaring
(location-do '(2) (alt-program altn) genexpr)))
(when expr*
(sow (alt expr* `(taylor ,name ,var (2)) (list altn)))))]
[else ; taylor failed
(debug #:from 'progress #:depth 5 "Series expansion (internal failure)")
(debug #:from 'progress #:depth 5 "Problematic expression: " expr)
(sow altn)]))))
(define (gen-series!)
(when (flag-set? 'generate 'taylor)
(timeline-event! 'series)
(define series-expansions
(apply append
(for/list ([altn (in-list (^queued^))] [n (in-naturals 1)])
(define expr (program-body (alt-program altn)))
(debug #:from 'progress #:depth 4 "[" n "/" (length (^queued^)) "] generating series for" expr)
(define tnow (current-inexact-milliseconds))
(begin0 (filter-not (curry alt-equal? altn) (taylor-alt altn))
(timeline-push! 'times (~a expr) (- (current-inexact-milliseconds) tnow))))))
; Probably unnecessary, at least CI passes!
(define (is-nan? x)
(and (impl-exists? x) (equal? (impl->operator x) 'NAN)))
(define series-expansions*
(filter-not
(λ (x) (expr-contains? (program-body (alt-program x)) is-nan?))
series-expansions))
; TODO: accuracy stats for timeline
(timeline-push! 'count (length (^queued^)) (length series-expansions*))
(^series^ series-expansions*))
(void))
(define (bad-alt! altn)
(define expr (program-body (alt-program altn)))
(when (expr-contains? expr rewrite-repr-op?)
(error 'bad-alt! "containg rewrite repr ~a" expr)))
(define (gen-rewrites!)
(when (and (null? (^queued^)) (null? (^queuedlow^)))
(raise-user-error 'gen-rewrites! "No expressions queued in patch table. Run `patch-table-add!`"))
(timeline-event! 'rewrite)
(define rewrite (if (flag-set? 'generate 'rr) rewrite-expression-head rewrite-expression))
(timeline-push! 'method (~a (object-name rewrite)))
(define changelists
(for/list ([altn (in-list (^queued^))] [n (in-naturals 1)])
(define expr (program-body (alt-program altn)))
(debug #:from 'progress #:depth 4 "[" n "/" (length (^queued^)) "] rewriting for" expr)
(define tnow (current-inexact-milliseconds))
(begin0 (rewrite expr (*output-repr*) #:rules (*rules*) #:root '(2))
(timeline-push! 'times (~a expr) (- (current-inexact-milliseconds) tnow)))))
(define reprchange-rules
(if (*pareto-mode*)
(filter (λ (r) (expr-contains? (rule-output r) rewrite-repr-op?)) (*rules*))
(list)))
; Empty in normal mode
(define changelists-low-locs
(for/list ([altn (in-list (^queuedlow^))] [n (in-naturals 1)])
(define expr (program-body (alt-program altn)))
(debug #:from 'progress #:depth 4 "[" n "/" (length (^queuedlow^)) "] rewriting for" expr)
(define tnow (current-inexact-milliseconds))
(begin0 (rewrite expr (*output-repr*) #:rules reprchange-rules #:root '(2))
(timeline-push! 'times (~a expr) (- (current-inexact-milliseconds) tnow)))))
(define comb-changelists (append changelists changelists-low-locs))
(define altns (append (^queued^) (^queuedlow^)))
(define rules-used
(append-map (curry map change-rule) (apply append comb-changelists)))
(define rule-counts
(for ([rgroup (group-by identity rules-used)])
(timeline-push! 'rules (~a (rule-name (first rgroup))) (length rgroup))))
(define rewritten
(for/fold ([done '()] #:result (reverse done))
([cls comb-changelists] [altn altns] #:when true [cl cls])
(let loop ([cl cl] [altn altn])
(if (null? cl)
(cons altn done)
(let ([prog* (apply-repr-change (change-apply (car cl) (alt-program altn)))])
(if (program-body prog*)
(loop (cdr cl) (alt prog* (list 'change (car cl)) (list altn)))
done))))))
(define rewritten*
(if (and (*pareto-mode*) (> (length rewritten) 1000))
(take rewritten 1000)
rewritten))
(timeline-push! 'count (length (^queued^)) (length rewritten*))
; TODO: accuracy stats for timeline
(^rewrites^ rewritten*)
(void))
(define (get-starting-expr altn)
(match (alt-event altn)
[(list 'patch) (program-body (alt-program altn))]
[_ (get-starting-expr (first (alt-prevs altn)))]))
(define (simplify!)
(unless (or (^series^) (^rewrites^))
(raise-user-error 'simplify! "No candidates generated. Run (gen-series!) or (gen-rewrites!)"))
(when (flag-set? 'generate 'simplify)
(timeline-event! 'simplify)
(define children (append (or (^series^) empty) (or (^rewrites^) empty)))
;; We want to avoid simplifying if possible, so we only
;; simplify things produced by function calls in the rule
;; pattern. This means no simplification if the rule output as
;; a whole is not a function call pattern, and no simplifying
;; subexpressions that don't correspond to function call
;; patterns.
(define locs-list
(for/list ([child (in-list children)] [n (in-naturals 1)])
(match (alt-event child)
[(list 'taylor _ _ loc) (list loc)]
[(list 'change cng)
(match-define (change rule loc _) cng)
(define pattern (rule-output rule))
(cond
[(not (list? pattern)) '()]
[else
(for/list ([pos (in-naturals 1)]
[arg-pattern (cdr pattern)] #:when (list? arg-pattern))
(append loc (list pos)))])]
[_ (list '(2))])))
(define to-simplify
(for/list ([child (in-list children)] [locs locs-list]
#:when true [loc locs])
(location-get loc (alt-program child))))
(define simplification-options
(simplify-batch to-simplify #:rules (*simplify-rules*) #:precompute true))
(define simplify-hash
(make-immutable-hash (map cons to-simplify simplification-options)))
(define simplified
(apply append
(for/list ([child (in-list children)] [locs locs-list])
(make-simplification-combinations child locs simplify-hash))))
; dedup for cache
(define simplified* (remove-duplicates simplified alt-equal?))
(unless (and (null? (^queued^)) (null? (^queuedlow^))) ; don't run for simplify-only
(for ([altn (in-list simplified*)])
(define cachable (map (compose program-body alt-program) (^queued^)))
(let ([expr0 (get-starting-expr altn)])
(when (set-member? cachable expr0)
(add-patch! (get-starting-expr altn) altn)))))
(timeline-push! 'count (length locs-list) (length simplified*))
(^final^ simplified*))
(void))
(define (patch-table-clear!)
(^queued^ '())
(^queuedlow^ '())
(^rewrites^ #f)
(^series^ #f)
(^final^ #f))
;;;;;;;;;;;;;;;;;;;;;;;;;;;; Public API ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (patch-table-has-expr? expr)
(hash-has-key? (patchtable-table *patch-table*) expr))
(define (patch-table-add! expr vars down?)
(when (patch-table-has-expr? expr)
(raise-user-error 'patch-table-add!
"attempting to add previously patched expression: ~a"
expr))
(define altn* (alt `(λ ,vars ,expr) `(patch) '()))
(if down?
(^queuedlow^ (cons altn* (^queuedlow^)))
(^queued^ (cons altn* (^queued^))))
(void))
(define (patch-table-get expr)
(hash-ref (patchtable-table *patch-table*) expr))
(define (patch-table-runnable?)
(or (not (null? (^queued^))) (not (null? (^queuedlow^)))))
(define (patch-table-run locs lowlocs)
(define cached
(for/fold ([qed '()] [ced '()]
#:result (begin0 (reverse ced) (^queued^ (reverse qed))))
([(vars expr) (in-dict locs)])
(if (patch-table-has-expr? expr)
(values qed (cons expr ced))
(let ([altn* (alt `(λ ,vars ,expr) `(patch) '())])
(values (cons altn* qed) ced)))))
(^queuedlow^
(for/list ([(vars expr) (in-dict lowlocs)])
(alt `(λ ,vars ,expr) `(patch) '())))
(cond
[(and (null? (^queued^)) ; early exit, nothing queued
(null? (^queuedlow^))
(null? cached))
'()]
[(and (null? (^queued^)) ; only fetch cache
(null? (^queuedlow^)))
(append-map patch-table-get cached)]
[else ; run patches
(debug #:from 'progress #:depth 3 "generating series expansions")
(if (null? (^queued^))
(^series^ '())
(gen-series!))
(debug #:from 'progress #:depth 3 "generating rewritten candidates")
(gen-rewrites!)
(debug #:from 'progress #:depth 3 "simplifying candidates")
(simplify!)
(begin0 (apply append (^final^) (map patch-table-get cached))
(patch-table-clear!))]))
(define (patch-table-run-simplify altns)
(^rewrites^ (append altns (if (^rewrites^) (^rewrites^) '())))
(simplify!)
(begin0 (^final^)
(patch-table-clear!)))
| false |
863ae93b8ddffeb52cb579dd0b570c7bf17bb24e | 3c6cae2786afeb3707f343ef51147d62c24cc566 | /tool.rkt | be4987484479f3c780a7de3d88ac10af3fb09ced | [
"Apache-2.0",
"MIT"
]
| permissive | Metaxal/quickscript | ddb6175d8785cdf344d12ad216ce2c3ac8665d8f | 31f731a5bc360e734f143fb3db23dab20f5669c0 | refs/heads/master | 2023-08-24T02:32:24.532721 | 2023-07-18T21:06:37 | 2023-07-18T21:06:37 | 115,353,980 | 18 | 8 | NOASSERTION | 2023-07-11T21:37:07 | 2017-12-25T17:35:37 | Racket | UTF-8 | Racket | false | false | 25,044 | rkt | tool.rkt | #lang at-exp racket/base
(require
(for-syntax racket/base) ; for help menu
drracket/tool ; necessary to build a drracket plugin
framework ; for preferences (too heavy a package?)
help/search
net/sendurl ; for the help menu
racket/class
racket/dict
racket/file
racket/gui/base
racket/list
racket/string
racket/unit
"base.rkt"
"exn-gobbler.rkt"
(prefix-in lib: "library.rkt")
"library-gui.rkt")
(provide tool@)
#|
To debug:
$ export PLTSTDERR=debug@quickscript && drracket&
If the menu takes a long time to load, it's because the scripts are not compiled.
Click on `Scripts|Manage scripts|Compile scripts and reload`.
It should then be very fast to load.
The maximize button of the frame also disappears, as if the X11 maximize property was gone
|#
(define orig-display-handler #f) ; will be set in the unit.
(define (user-script-files #:exclude? [exclude? #t])
(lib:all-files (lib:load library-file) #:exclude? exclude?))
(define (error-message-box str e)
(define sp (open-output-string))
(parameterize ([current-error-port sp])
(orig-display-handler (exn-message e) e))
(message-box "Quickscript caught an exception"
(string-append str " " (get-output-string sp))
#f '(stop ok)))
(define-syntax with-error-message-box
(syntax-rules ()
[(_ str #:error-value err-val body ...)
(with-handlers* ([(λ (e) (and (exn? e) (not (exn:break? e))))
(λ (e)
(error-message-box str e)
err-val)])
body ...)]
[(_ str body ...)
(with-error-message-box str #:error-value (void) body ...)]))
;; Shows a message box with the string of the exn-gobbler, if not empty.
(define (exn-gobbler-message-box gb title)
(unless (exn-gobbler-empty? gb)
(message-box title
(exn-gobbler->string gb)
#f
'(caution ok))))
;; -> exn-gobbler?
(define (compile-library)
(time-info "Recompiling library"
(parameterize ([error-display-handler orig-display-handler])
(compile-user-scripts (user-script-files)))))
;; -> void?
(define (compile-library/frame)
(define fr #false)
(dynamic-wind
(λ ()
(set! fr (new frame% [parent #f] [label "Recompiling quickscripts…"] [width 200] [height 50]))
(void (new message% [parent fr] [label "Recompiling quickscripts, please wait…"]))
(send fr reflow-container)
(send fr show #true))
(λ ()
(define gb (compile-library))
(exn-gobbler-message-box gb "Quickscript: Error during compilation"))
(λ () (send fr show #false))))
(define (property-dict-hook? props)
(not (prop-dict-ref props 'label)))
(define (insert-to-text text str)
; Inserts the text, possibly overwriting the selection:
(send text begin-edit-sequence)
(send text insert str)
(send text end-edit-sequence))
(define-namespace-anchor a)
(define tool@
(unit
(import drracket:tool^)
(export drracket:tool-exports^)
(set! orig-display-handler drracket:init:original-error-display-handler)
;===================;
;=== Frame mixin ===;
;===================;
(define script-menu-mixin
(mixin (drracket:unit:frame<%>) ()
(super-new)
(inherit get-button-panel
get-definitions-text
get-interactions-text
;register-toolbar-button
create-new-tab)
(define/private (get-the-text-editor)
; for a frame:text% :
;(define text (send frame get-editor))
; for DrRacket:
(define defed (get-definitions-text))
(if (send defed has-focus?)
defed
(get-interactions-text)))
(define/private (new-script)
(define name (get-text-from-user "Script name" "Enter the name of the new script:"
this
#:validate non-empty-string?
#:dialog-mixin frame:focus-table-mixin))
(when name
(define filename (string-append (string-foldcase (string-replace name " " "-")) ".rkt"))
(define file-path (build-path user-script-dir filename))
(define proc-name (string-foldcase (string-replace name " " "-")))
(define label name)
;; Make sure the directory containing the script exists
(make-directory* user-script-dir)
;; Write the script to file
(with-output-to-file file-path
(λ _
(displayln (make-simple-script-string proc-name label))))
(reload-scripts-menu)
(edit-script file-path)))
;; file: path?
(define/private (edit-script file)
(when file
; For frame:text% :
;(send (get-the-text-editor) load-file file)
; For DrRacket:
(send this open-in-new-tab file)))
(define/private (open-script)
(define file (get-file "Open a script" this user-script-dir #f #f '()
'(("Racket" "*.rkt"))))
(edit-script file))
(define/private (open-help)
(perform-search "quickscript")
; Does not seem to work well.
#;(send-main-page #:sub "quickscript/index.html"))
(define/private (bug-report)
(send-url "https://github.com/Metaxal/quickscript/issues"))
(define menu-bar (send this get-menu-bar))
(define menu-reload-count 0)
(define scripts-menu
(new menu% [parent menu-bar] [label "&Scripts"]))
;::::::::::::::::;
;:: Run Script ::;
;::::::::::::::::;
;; dict for persistent scripts:
;; the module is instanciated only once, and made available for future calls.
(define namespace-dict (make-hash))
(define/private (unload-persistent-scripts)
(set! namespace-dict (make-hash)))
;; f: path?
(define/private (run-script props
#:tab [tab #f]
#:editor [editor #f]
#:more-kwargs [more-kwargs '()])
(define name (prop-dict-ref props 'name))
(define fpath (prop-dict-ref props 'filepath))
(define output-to (prop-dict-ref props 'output-to))
(define persistent? (prop-dict-ref props 'persistent?))
(define hook? (property-dict-hook? props))
; For frame:text% :
;(define text (send frame get-editor))
; For DrRacket:
(set! tab (or tab (send this get-current-tab)))
(set! editor
(or editor
(if hook?
(send tab get-defs)
(get-the-text-editor))))
(define defs (send tab get-defs))
(define ints (send tab get-ints))
(define str (and (not hook?) ; avoid unnecessary computation
(send editor get-text
(send editor get-start-position)
(send editor get-end-position))))
; Create a namespace for the script:
(define (make-script-namespace)
(define ns (make-base-empty-namespace))
(for ([mod '(racket/class racket/gui/base drracket/tool-lib)])
(namespace-attach-module (namespace-anchor->empty-namespace a)
mod ns))
ns)
; if the script is persistent, we try to load an existing namespace, or we create one.
; if not, we always create a new namespace.
(define ns
(if persistent?
(dict-ref! namespace-dict fpath make-script-namespace)
(make-script-namespace)))
(define script-result
(with-error-message-box
(format "Run: Error in script file ~s:\n" (path->string fpath))
#:error-value #f
; See HelpDesk for "Manipulating namespaces"
(let ([f (parameterize ([current-namespace ns])
; Ensure the script is compiled for the correct version of Racket
(compile-user-script fpath)
(dynamic-require fpath name))]
[kw-dict
(append
`((#:definitions . ,defs)
(#:interactions . ,ints)
(#:editor . ,editor)
(#:file . ,(send defs get-filename))
(#:frame . ,this))
more-kwargs)])
;; f is applied *outside* the created namespace so as to make
;; all features of drracket's frame available.
;; If it were evaluated inside ns, (send fr open-in-new-tab <some-file>)
;; wouldn't work.
(let-values ([(_ kws) (procedure-keywords f)])
(let ([k-v (sort (filter-map (λ (k) (assoc k kw-dict)) kws)
keyword<? #:key car)])
(if hook?
(keyword-apply f (map car k-v) (map cdr k-v) '())
(keyword-apply f (map car k-v) (map cdr k-v) str '())))))))
(cond [hook?
;; Return the script result as is, to be used by the caller.
;; However, since multiple hooks may be called, there's usually no good way
;; to aggregate the return values, so we just return void
script-result]
[(or (string? script-result) (is-a? script-result snip%))
;; Do not modify the file if no output
(case output-to
[(new-tab)
(create-new-tab)
(define new-defs (get-definitions-text))
(send new-defs select-all) ; get the newly created text
(insert-to-text new-defs script-result)]
[(selection)
(insert-to-text editor script-result)]
[(message-box)
(when (string? script-result)
(message-box "Output" script-result this))]
[(clipboard)
(when (string? script-result)
(send the-clipboard set-clipboard-string script-result 0))])]))
;; Runs *all* scripts with the given name (identifier) that are *not* menu items.
;; TODO: Rename #:label to #:menu-label or #:entry-label for clarity?
;; Notice: the result is #<void>, and the results from the scripts are discarded.
(define/public (find-and-run-hook-scripts name
#:tab [tab #f]
#:editor [editor #f]
#:more-kwargs [more-kwargs '()])
(for ([props (in-list (hash-ref property-dicts name '()))])
(run-script props #:tab tab #:editor editor #:more-kwargs more-kwargs)))
;::::::::::::::::;
;:: Some hooks ::;
;::::::::::::::::;
;; NOTICE: If new define/pubment methods are added in drracket/private/unit.rkt,
;; then these methods must be declared also in drracket/private/interface.rkt
;; TODO: Should we have an `after-tab-change`?
(define/augment (on-tab-change tab-from tab-to)
(queue-callback
(λ () (find-and-run-hook-scripts 'on-tab-change
#:more-kwargs `((#:tab-from . ,tab-from)
(#:tab-to . ,tab-to))))))
(define/augment (on-close)
(queue-callback
(λ () (find-and-run-hook-scripts 'on-close #:more-kwargs '()))))
;; At this stage, the frame is not shown yet
(define/public (on-startup)
(queue-callback
(λ () (find-and-run-hook-scripts 'on-startup #:more-kwargs '()))))
(define/augment (after-create-new-drracket-frame show?)
(queue-callback ; TODO: should this be here or in drracket:unit?
(λ () (find-and-run-hook-scripts 'after-create-new-drracket-frame
#:more-kwargs `((#:show? . ,show?))))))
;; Specialized to only when a new empty tab is created.
;; For loading a file, see `on-load-file`.
;; If `filename` is not #f, is almost redundant with `on-load-file`, except that the latter
;; is also called (I think) when loading a file in an existing tab.
(define/augment (after-create-new-tab tab filename start-pos end-pos)
(queue-callback
(λ ()
;; #:tab and #:filename are redundant. The same information is already
;; available via #:file and #:definitions in the script function.
(if filename
(find-and-run-hook-scripts 'after-load-file
#:tab tab
#:more-kwargs `((#:in-new-tab? . #t)))
(find-and-run-hook-scripts 'after-create-new-tab
#:tab tab
#:more-kwargs `())))))
;; TODO: Add a hook for execute-callback. Maybe add a pubment method in drr:unit:frame
;; that matches the hook.
;;https://docs.racket-lang.org/tools/drracket_unit.html#%28meth._%28%28%28lib._drracket%2Ftool-lib..rkt%29._drracket~3aunit~3aframe~25%29._execute-callback%29%29
;::::::::::::::::;
;:: Properties ::;
;::::::::::::::::;
;; All menu item scripts have are at the key `#f` in property-dicts.
;; The key for other scripts (hooks, not menu entries) is the script's identifier (name).
(define property-dicts (make-hasheq))
(define/private (load-properties!)
(set! property-dicts (make-hasheq))
(define gb (make-exn-gobbler "Loading Scripts menu"))
;; Create an empty namespace to load all the scripts (in the same namespace).
(parameterize ([current-namespace (make-base-empty-namespace)]
[error-display-handler orig-display-handler])
;; For all script files in the script directory.
(for ([f (in-list (user-script-files))])
(time-info
(string-append "Loading file " (path->string f))
(with-handlers* ([exn:fail?
(λ (e)
(gobble gb e (format "Script file ~s:" (path->string f)))
'())])
(define props-list (get-property-dicts f))
(for ([props (in-list props-list)])
; Keep only the scripts that match the current os type.
(when (memq this-os-type (prop-dict-ref props 'os-types))
(define key
(if (prop-dict-ref props 'label) ; TODO: CHECK DEFAULT
#f ; This is a menu item script
(prop-dict-ref props 'name))) ; This is a hook
(hash-update! property-dicts key (λ (acc) (cons props acc)) '())))))))
; Don't display an error on menu build, as an error is already shown
; during compilation.
(log-quickscript-info (exn-gobbler->string gb))
#;(exn-gobbler-message-box gb "Quickscript: Errors while loading script properties"))
(define/private (reload-scripts-menu)
(time-info
"Building script menu"
(set! menu-reload-count (add1 menu-reload-count))
(log-quickscript-info "Script menu rebuild #~a..." menu-reload-count)
(load-properties!)
(let* ([property-dicts
;; Keep only menu entries
(hash-ref property-dicts #f '())]
[property-dicts
;; Sort the menu items lexicographically
(sort property-dicts
string<=?
#:key (λ (props)
(define menu-path (prop-dict-ref props 'menu-path))
(string-downcase
(string-replace
(string-join
(append
(if (empty? menu-path)
'("/")
menu-path)
(list (prop-dict-ref props 'label)))
"/")
"&" "" #:all? #t)))
#:cache-keys? #t)])
;; remove all scripts items, after the default ones:
(time-info
"Deleting menu items"
(for ([item (list-tail (send scripts-menu get-items) 2)])
(log-quickscript-info "Deleting menu item ~a... " (send item get-label))
(send item delete)))
;; Add script items.
(for ([props (in-list property-dicts)])
(let*([label (prop-dict-ref props 'label)]
[menu-path (prop-dict-ref props 'menu-path)]
[shortcut (prop-dict-ref props 'shortcut)]
[shortcut-prefix (or (prop-dict-ref props 'shortcut-prefix)
(get-default-shortcut-prefix))]
[help-string (prop-dict-ref props 'help-string)])
; Create the menu hierarchy if it doesn't exist.
(define parent-menu
(let loop ([menu-path menu-path] [parent scripts-menu])
(if (empty? menu-path)
parent
(let ([menu (first menu-path)])
(loop (rest menu-path)
(or (findf (λ (m) (and (is-a? m labelled-menu-item<%>)
(string=? (send m get-label) menu)))
(send parent get-items))
(new menu% [parent parent] [label menu])))))))
(new menu-item% [parent parent-menu]
[label label]
[shortcut shortcut]
[shortcut-prefix shortcut-prefix]
[help-string help-string]
[callback (λ (it ev) (run-script props))]))))))
(define manage-menu (new menu% [parent scripts-menu] [label "&Manage"]))
(for ([(lbl cbk)
(in-dict
`(("&New script…" . ,(λ () (new-script)))
("&Open script…" . ,(λ () (open-script)))
("&Disable scripts…" . ,(λ () (make-library-gui #:parent-frame this
#:drracket-parent? #t)))
(separator . #f)
("&Library…" . ,(λ () (make-library-gui #:parent-frame this
#:drracket-parent? #t)))
("&Reload menu" . ,(λ ()
(unload-persistent-scripts)
(reload-scripts-menu)))
("&Compile scripts" . ,(λ ()
(unload-persistent-scripts)
(compile-library/frame)
(reload-scripts-menu)))
("&Stop persistent scripts" . ,(λ () (unload-persistent-scripts)))
(separator . #f)
("&Help" . ,(λ () (open-help)))
("Report an &issue" . ,(λ () (bug-report)))
))])
(if (eq? lbl 'separator)
(new separator-menu-item% [parent manage-menu])
(new menu-item% [parent manage-menu] [label lbl]
[callback (λ _ (cbk))])))
(new separator-menu-item% [parent scripts-menu])
;; Show the error messages that happened during the initial compilation.
(exn-gobbler-message-box init-compile-exn-gobbler "Quickscript: Error during compilation")
(reload-scripts-menu)
(on-startup)))
;====================;
;=== Editor mixin ===;
;====================;
(define text-mixin
(mixin ((class->interface text%)) ()
(define (get-drr-frame)
(send (send this get-tab) get-frame))
(define/augment (after-load-file success?)
;; If the current definitions is not this, this means the file is loaded
;; in a new text. In this case, it it better to let `after-create-new-tab`
;; trigger an event, because it happens after the on-tab-change event,
;; that is, the #:definitions is the correct one.
(when (and success?
(eq? this (send (get-drr-frame) get-definitions-text)))
;; Callback is queue so it happens *after* the file is effectively loaded into the
;; editor.
(queue-callback
(λ () (send (get-drr-frame) find-and-run-hook-scripts
'after-load-file
;#:tab ; no need because we check above it's always the current one
#:more-kwargs `((#:in-new-tab? . #f)))))))
;; filename : path?
;; format : (or/c 'guess 'same 'copy 'standard 'text 'text-force-cr)
(define/augment (on-save-file filename fmt)
;; No queue-callback to ensure modifications to the file are performed immediately.
(send (get-drr-frame) find-and-run-hook-scripts
'on-save-file
#:tab (send this get-tab) ; TODO: What if `this` is interactions?
#:editor this
#:more-kwargs `((#:save-filename . ,filename)
(#:format . ,fmt))))
(define/augment (after-save-file success?)
(when success?
(queue-callback
(λ () (send (get-drr-frame) find-and-run-hook-scripts
'after-save-file
#:tab (send this get-tab) ; TODO: What if `this` is interactions?
#:editor this
#:more-kwargs `())))))
#;(define/override (on-focus on?) #f)
#;(define/augment (on-insert start len) #f)
#;(define/augment (after-insert start len) #f)
#;(define/augment (on-delete start len) #f)
#;(define/augment (after-delete start len) #f)
#;(define/override (on-default-char kw-evt) #f)
#;(define/override (on-default-event ms-evt) #f)
;; TODO maybe:
#;can-load-file? #;can-save-file?
#;on-edit-sequence #;after-edit-sequence
#;on-scroll-to #;after-scroll-to
#;on-change
#;on-display-size
#;on-snip-modified
(super-new)))
;=================;
;=== Tab mixin ===;
;=================;
(define tab-mixin
(mixin (drracket:unit:tab<%>) ()
(inherit get-frame)
(define/augment (on-close)
(send (get-frame) find-and-run-hook-scripts
'on-tab-close
#:tab this
#:more-kwargs `((#:tab . ,this))))
(super-new)))
; If an exception is raised during these two phases, DrRacket displays
; the error in a message box and deactivates the plugin before continuing.
(define (phase1) (void))
(define (phase2) (void))
; Silently recompile for the new version if necessary, at the start up of DrRacket.
; This must be done before building the menus.
; The compilation is done at this point so that the splash screen doesn't disappear,
; but the message box will be shown after the DrRacket frame is shown up.
(define init-compile-exn-gobbler (compile-library))
;; Search for "Extending the Existing DrRacket Classes" to see what can be extended:
(drracket:get/extend:extend-definitions-text text-mixin)
(drracket:get/extend:extend-tab tab-mixin)
(drracket:get/extend:extend-unit-frame script-menu-mixin)))
| true |
cd0f035691cb71301371a38d7e1a31a6761cd1ea | 435734fea3031191e9e00d5d54d8b14d7b01ee48 | /racket/racket/modexp.rkt | 869d1b410cc6da141a6bad83dbce9cd39c349418 | []
| no_license | sumansourabh26/everyday_codes | 1f4bc4b05fdb51512b68c37371933535d90edf10 | 2a8c097adbb64d103dc823bdb9987e99dfd9943b | refs/heads/master | 2020-05-04T15:22:13.872019 | 2014-11-05T16:11:08 | 2014-11-05T16:11:08 | 17,599,784 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 622 | rkt | modexp.rkt | (define (modexp x y n)
(cond ((= y 0) 1)
(else
(if ( even y)
(remainder (* (modexp x (quotient y 2) n)
(modexp x (quotient y 2) n))
n)
(remainder (* x
(modexp x (quotient y 2) n)
(modexp x (quotient y 2) n))
n)))))
(define (even x)
( if (= (remainder x 2)0)
#t
#f))
| false |
4da84ee7abaf09ac240a3099154e0b504209468b | 0d4287c46f85c3668a37bcb1278664d3b9a34a23 | /骆梁宸/Assignment/3/06.rkt | 3b7b75cb8a02c30c1d7d9cdee765bbef05a2d75f | []
| no_license | siriusmax/Racket-Helper | 3e55f8a69bf005b56455ab386e2f1ce09611a273 | bf85f38dd8d084db68265bb98d8c38bada6494ec | refs/heads/master | 2021-04-06T02:37:14.261338 | 2017-12-20T04:05:51 | 2017-12-20T04:05:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 940 | rkt | 06.rkt | #lang racket
(define (accumulate op init seq)
(if (null? seq)
init
(op (car seq) (accumulate op init (cdr seq)))))
(define (enumerate-interval a b)
(if (> a b)
'()
(cons a (enumerate-interval (+ a 1) b))))
(define (flatmap proc seq)
(accumulate append '() (map proc seq)))
(define (tri-num-list n s)
(define range (enumerate-interval 1 n))
(define (getPermutation size result)
(if (= size 3)
result
(getPermutation (+ 1 size) (flatmap (lambda (per) (map (lambda (i) (append per (list i))) range)) result))))
((lambda ()
(flatmap (lambda (per)
(if (and (= s (accumulate + 0 per)) (< (first per) (second per) (third per)))
(list per)
empty))
(getPermutation 0 (list empty)))))
)
(define (myloop)
(let ((n (read))
(s (read)))
(if (eq? n eof)
(void)
(begin (display (tri-num-list n s)) (newline) (myloop)))))
(myloop) | false |
eb7391a6ca3f5dba2ac82d89a15f03d8211f1a71 | 82c76c05fc8ca096f2744a7423d411561b25d9bd | /typed-racket-test/fail/require-typed-struct-renamed-field.rkt | c1309ec36da6c943dc7a25cc2a655e1354f3a7e8 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | racket/typed-racket | 2cde60da289399d74e945b8f86fbda662520e1ef | f3e42b3aba6ef84b01fc25d0a9ef48cd9d16a554 | refs/heads/master | 2023-09-01T23:26:03.765739 | 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 | 295 | rkt | require-typed-struct-renamed-field.rkt | #;
(exn-pred ".*expected field name 0 to be x, but found y.*")
#lang racket/base
(module server racket
(provide (struct-out posn))
(struct posn [x y]))
(module client typed/racket
(require/typed (submod ".." server)
(#:struct posn ((y : Integer) (x : Integer)))))
(require 'client)
| false |
534443507763dfaae4b64edb5383931203b5bcc6 | 49d98910cccef2fe5125f400fa4177dbdf599598 | /advent-of-code-2021/solutions/day04/day04.rkt | 5ca046fcbd3018638f419c83420ce8c9d9dcc74f | []
| no_license | lojic/LearningRacket | 0767fc1c35a2b4b9db513d1de7486357f0cfac31 | a74c3e5fc1a159eca9b2519954530a172e6f2186 | refs/heads/master | 2023-01-11T02:59:31.414847 | 2023-01-07T01:31:42 | 2023-01-07T01:31:42 | 52,466,000 | 30 | 4 | null | null | null | null | UTF-8 | Racket | false | false | 3,126 | rkt | day04.rkt | #lang racket
;; A functional version emphasizing readability with small, useful functions.
(require "../../advent/advent.rkt" threading)
(define input (file->lines "day04.txt"))
(define dim 5)
;; Puzzle parts
(define (part1 lines) (solve first lines))
(define (part2 lines) (solve last lines))
;; --------------------------------------------------------------------------------------------
;; Return a list of board columns
(define (cols board)
(for/list ([ col (in-range dim) ])
(for/list ([ row (in-range dim) ])
(get board row col))))
;; Return the value at board[row, col]
(define (get board row col)
(vector-ref board (+ (* row dim) col)))
;; Indicate whether the board is a winning board
(define (is-winning? board)
(ormap (curry andmap false?) (append (rows board) (cols board))))
;; Functionally mark the board by replacing any values equal to n with #f
(define (mark-board n board)
(vector-map (λ (i) (if (equal? i n) #f i)) board))
;; Return a new list of boards that have been marked
(define (mark-boards n boards)
(map (curry mark-board n) boards))
;; Return a list of boards from the input
(define (parse-boards lines)
(define (parse-board lst)
(~>> (string-join lst " ")
string-split
(map string->number)
list->vector))
(~>> (chunk (rest lines) (add1 dim))
(map (curryr drop 1))
(map parse-board)))
;; Return a list of random numbers from the input
(define (parse-random-numbers lines)
(~> (first lines)
(string-split ",")
(map string->number _)))
;; Return a list of rows from the board
(define (rows board)
(for/list ([ row (in-range dim) ])
(for/list ([ col (in-range dim) ])
(get board row col))))
;; Associate numbers with a list of boards the number caused to
;; win. Then simply choose either the first board from the first
;; number, or the last board from the last number according to the
;; part via the accessor function which is either first or last.
(define (solve accessor lines)
(match-let ([ (list n boards)
(accessor (winning-numbers (parse-random-numbers lines)
(parse-boards lines))) ])
(* n (sum-unmarked (accessor boards)))))
;; Return the sum of all unmarked positions on the board
(define (sum-unmarked board)
(for/sum ([ i (in-range (* dim dim)) ])
(or (vector-ref board i) 0)))
;; Return an associaton list of the form:
;; ( (<m> (<winning-board-m-1> <winning-board-m-2> ...))
;; (<n> (<winning-board-n-1> <winning-board-n-2> ...)) )
(define (winning-numbers numbers boards)
(if (null? numbers)
'()
(let*-values ([ (n) (first numbers) ]
[ (boards) (mark-boards n boards) ]
[ (yes no) (partition is-winning? boards) ])
(cond [ (null? yes) (winning-numbers (rest numbers) no) ]
[ else (cons (list n yes) (winning-numbers (rest numbers) no)) ]))))
;; Tests
(module+ test
(require rackunit)
(check-equal? (part1 input) 8442)
(check-equal? (part2 input) 4590))
| false |
438112df86ac1bcad02f2fea6819710438c548e8 | 061db6d37c5d05d56d4b7eedbda08568f42da533 | /examples/modal.rkt | 687f912e97835b9ba4d72fb215ed94aeb16345b6 | [
"BSD-3-Clause"
]
| permissive | DavidAlphaFox/racket-gui-easy | f2d34da14cf3c73c58119023d591f185ad63d071 | d61300c08250ca594464d5285cdfd5e2b49195fb | refs/heads/master | 2023-06-29T04:42:03.232576 | 2021-08-01T09:28:29 | 2021-08-01T09:28:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 460 | rkt | modal.rkt | #lang racket/base
(require racket/gui/easy
racket/gui/easy/operator)
(define @msg (@ "Click the button"))
(define root-renderer
(render
(window
(vpanel
(text @msg)
(button
"Display Modal"
(λ ()
(render
(dialog
#:style '(close-button)
(vpanel
(text @msg)
(input @msg (λ (_ text)
(@msg . := . text)))))
root-renderer)))))))
| false |
10b9aadadfb275cc2e436f23746654066f4fadbc | be30c5b630eb3ba070efc4a557da146505ed3422 | /lazystep-redexcheck.rkt | 8200d74e7579e8585624154e8f5a48b12403a515 | []
| no_license | stchang/betaneed | a3b40c819f831922c13807c8cbb9b025fb9d31fa | 712bf1de3c08a9361ec313577e8565eacda627bc | refs/heads/master | 2021-05-19T09:07:00.282533 | 2020-03-31T15:35:09 | 2020-03-31T15:35:09 | 251,620,338 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 5,986 | rkt | lazystep-redexcheck.rkt | #lang racket
(require redex)
(require "lazystep.rkt")
(define-metafunction lazystep
fv : e -> (x ...)
[(fv e) (remove-duplicates (fv_ e))])
(define-metafunction lazystep
fv_ : e -> (x ...)
[(fv_ x) (x)]
[(fv_ (e_1 e_2)) (∪ (fv_ e_1) (fv_ e_2))]
[(fv_ (λ x e)) (set-diff (fv_ e) (x))]
[(fv_ (lab x e)) (fv e)])
(define-metafunction lazystep
remove-duplicates : (x ...) -> (x ...)
[(remove-duplicates ()) ()]
[(remove-duplicates (x)) (x)]
[(remove-duplicates (x_1 x_2 ...)) ; x \notin (x_2 ...)
(x_1 ,@(term (remove-duplicates (x_2 ...))))
(side-condition (not (memq (term x_1) (term (x_2 ...)))))]
[(remove-duplicates (x_1 x_2 ...)) ; x \in (x_2 ...)
(remove-duplicates (x_2 ...))
(side-condition (memq (term x_1) (term (x_2 ...))))])
(define-metafunction lazystep
∪ : (x ...) ... -> (x ...)
[(∪ (x_1 ...) (x_2 ...) (x_3 ...) ...)
(∪ (x_1 ... x_2 ...) (x_3 ...) ...)]
[(∪ (x ...)) (x ...)]
[(∪) ()])
(define-metafunction lazystep
set-diff : (x ...) (x ...) -> (x ...)
[(set-diff (x ...) ()) (x ...)]
[(set-diff (x_1 ... x_2 x_3 ...) (x_2 x_4 ...))
(set-diff (x_1 ... x_3 ...) (x_4 ...))
(side-condition (not (memq (term x_2) (term (x_1 ... x_3 ...)))))]
[(set-diff (x_1 ... x_2 x_3 ...) (x_2 x_4 ...))
(set-diff (x_1 ... x_3 ...) (x_2 x_4 ...))
(side-condition (memq (term x_2) (term (x_1 ... x_3 ...))))]
[(set-diff (x_1 ...) (x_2 x_3 ...))
(set-diff (x_1 ...) (x_3 ...))
(side-condition (not (memq (term x_2) (term (x_1 ...)))))])
(define (close e)
(define (make-x i)
(string->symbol (string-append "x_" (number->string i))))
(let ([fvs (term (fv ,e))])
(let L ([e (term (rename-bound-vars ,e ,fvs))] [fvs fvs] [i 1])
(if (empty? fvs)
e
(let ([x (make-x i)])
(L (term ((λ ,(first fvs) ,e) (λ ,x ,x)))
(rest fvs) (add1 i)))))))
;; rename-bound-vars:
;; rename all bound variables in a given λ abstraction
;; the second argument is the list of existing bound variables
;;
(define-metafunction lazystep
rename-bound-vars : e (x ...) -> e
[(rename-bound-vars (λ x_1 e) (x ...))
(λ x_new (rename-bound-vars (subst e x_1 x_new) (x_new x ...)))
(where x_new ,(variable-not-in (term (x ... x_1))
(term x_1)))
#;(side-condition (when DEBUG
(printf "renaming ~a to ~a\n" (term x_1) (term x_new))))]
[(rename-bound-vars (e_1 e_2) (x ...))
((rename-bound-vars e_1 (x ...)) (rename-bound-vars e_2 (x ...)))]
[(rename-bound-vars x_1 (x ...))
x_1])
(define-metafunction lazystep
[(alpha-equiv? e_1 e_2) (alphaeq e_1 e_2 () ())])
(define-metafunction lazystep
[(alphaeq (λ x_1 e_1) (λ x_2 e_2) (x_3 ...) (x_4 ...))
(alphaeq e_1 e_2 (x_1 x_3 ...) (x_2 x_4 ...))]
[(alphaeq (e_1 e_2) (e_3 e_4) (x_1 ...) (x_2 ...))
,(and (term (alphaeq e_1 e_3 (x_1 ...) (x_2 ...)))
(term (alphaeq e_2 e_4 (x_1 ...) (x_2 ...))))]
[(alphaeq x_1 x_2 (x_3 ...) (x_4 ...))
,(= (length (member (term x_1) (term (x_3 ...))))
(length (member (term x_2) (term (x_4 ...)))))]
[(alphaeq any_1 any_2 any_3 any_4) #f])
(define-metafunction lazystep
[(extract-bindings e) (get-bindings e ())])
(define-metafunction lazystep
[(get-bindings ((λ x e_1) e_2) ((x_1 e) ...))
(get-bindings e_1 ((x e_2) (x_1 e) ...))]
[(get-bindings (λ x e) ((x_1 e_1) ...))
((x_1 e_1) ...)])
#;(define (AF-equiv? t)
(printf "checking: ~a\n" t)
(let ([res1 (apply-red-no-dups* red t)]
[res2 (apply-red-no-dups* λ-need-red-beta t)])
(and (= (length res1) 1)
(= (length res2) 1)
(redex-match λneed a (first res1))
(redex-match λ-need A (first res2))
(let ([res3 (apply-red-no-dups*
λ-need-red-nobeta (first res1))])
(and (= (length res3) 1)
(redex-match λ-need A (first res3))
(term (alpha-equiv? ,(first res2) ,(first res3)))
#;(equal? (term (extract-bindings ,(first res2)))
(term (extract-bindings ,(first res3))))))
)))
#;(define (AF-equiv-noambig? t)
(printf "~a) checking: ~a\n" n t)
(set! n (add1 n))
(let ([res1 (apply-red-no-ambig* red t)]
[res2 (apply-red-no-ambig* λ-need-red-beta t)])
(and (redex-match λneed a res1)
(redex-match λ-need A res2)
(let ([res3 (apply-red-no-ambig* λ-need-red-nobeta res1)])
(redex-match λ-need A res3)
(term (alpha-equiv? ,res2 ,res3))))))
(define (lazystep-v? t)
(printf "~a) checking: ~a\n" n t)
(set! n (add1 n))
(let loop ([t t])
(let ([res1 (apply-reduction-relation lazystep-red t)])
(cond [(null? res1) (redex-match lazystep v t)]
[(= (length res1) 1) (loop (car res1))]
[else #f]))))
#;(define (CF-CK-bisim? t)
(printf "~a) checking: ~a\n" n t)
(set! n (add1 n))
(let loop ([t (term (,t (mt)))])
(let ([res1 (apply-reduction-relation red-ck t)])
(cond
[(null? res1)
(redex-match λneed a (term (φ ,t)))]
[(= (length res1) 1)
(if (term (alpha-equiv? (φ ,(car res1)) (φ ,t)))
(loop (car res1))
(let ([res2 (apply-reduction-relation red (term (φ ,t)))])
(term (alpha-equiv? (φ ,(car res1)) ,(car res2)))))]
[else #f]))))
#;(define (gen-trace-ck t)
(define (gen-trace-ck-help t)
(let ([res (apply-reduction-relation red-ck t)])
(if (null? res)
(list t)
(cons t (gen-trace-ck-help (car res))))))
(gen-trace-ck-help (term (,t (mt)))))
(define n 1)
(define-syntax (redex-check-go stx)
(syntax-case stx ()
[(_) #'(redex-check lazystep d (lazystep-v? (term d))
#:prepare close
#:attempts 1000000)]))
(define-syntax (traces-ck stx)
(syntax-case stx ()
[(_ red t) #'(traces red (term (,t (mt))))]))
;(redex-check-go) | true |
8128b89fd936633f5051d97cf4d5f2b3da4473b0 | 8a4fa6b86242f9176b5df4b2a428b2564ccaf0d8 | /demos/circle-demo.rkt | dcc3c27607e041cfb929b24ffaca1cd5b9e44ec2 | []
| no_license | dyoo/racket_tracer | 07c5fa20634a27998b943ad8dcfd4a38e9193320 | d5d4c170311dc06a491c65d39f5111e2cf4abe0d | refs/heads/master | 2021-01-20T22:40:17.028584 | 2011-08-25T15:23:49 | 2011-08-25T15:23:49 | 1,937,637 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,274 | rkt | circle-demo.rkt | #lang planet tracer/tracer:1:2
(require htdp/image)
(define (circles ctr-x ctr-y rad depth canvas)
(cond
[(= depth 0) canvas]
[(> depth 0)
(let* ([cir (circle rad "outline" "red")]
[new-rad (/ rad 3)]
[new-depth (sub1 depth)]
[new-can (circles ctr-x (- ctr-y (* 2 rad)) new-rad new-depth
(circles ctr-x (+ ctr-y (* 2 rad)) new-rad new-depth
(circles (+ ctr-x (* 2 rad)) ctr-y new-rad new-depth
(circles (- ctr-x (* 2 rad)) ctr-y new-rad
new-depth canvas))))])
(place-image cir ctr-x (- ctr-y rad)
(place-image cir ctr-x (+ ctr-y rad)
(place-image cir (- ctr-x rad) ctr-y
(place-image cir
(+ ctr-x rad) ctr-y
new-can)))))]))
;(circles 150 150 (/ 75 2) 4 (empty-scene 300 150))
;(circles 125 125 (/ 75 2) 3 (empty-scene 250 250))
;(circles 150 150 (/ 75 2) 3 (empty-scene 300 150))
(circles 50 50 (/ 50 3) 3 (empty-scene 100 100))
| false |
991e87fda2fd6acedbbc8fdfeede2f633551ed10 | 8eb21733f83949941fadcb268dd4f0efab594b7f | /150/srfi-155/srfi/154.rkt | 239593047fa563f755aad0c03b0d2ab193d11f9b | []
| no_license | srfi-explorations/final-srfis | d0994d215490333062a43241c57d0c2391224527 | bc8e7251d5b52bf7b11d9e8ed8b6544a5d973690 | refs/heads/master | 2020-05-02T07:29:24.865266 | 2019-03-26T19:02:18 | 2019-03-26T19:02:18 | 177,819,656 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,169 | rkt | 154.rkt | ;; Copyright (C) Marc Nieper-Wißkirchen (2017). All Rights Reserved.
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without
;; restriction, including without limitation the rights to use, copy,
;; modify, merge, publish, distribute, sublicense, and/or sell copies
;; of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
#lang racket
(provide dynamic-extent?
current-dynamic-extent
with-dynamic-extent
closed-lambda)
(require srfi/9)
(define-record-type <dynamic-extent>
(make-dynamic-extent proc)
dynamic-extent?
(proc dynamic-extent-proc))
(define (current-dynamic-extent)
(call-with-current-continuation
(lambda (return)
(let-values
(((k thunk)
(call-with-current-continuation
(lambda (c)
(return
(make-dynamic-extent (lambda (thunk)
(call-with-current-continuation
(lambda (k)
(c k thunk))))))))))
(call-with-values thunk k)))))
(define (with-dynamic-extent dynamic-extent thunk)
((dynamic-extent-proc dynamic-extent) thunk))
(define-syntax closed-lambda
(syntax-rules ()
((closed-lambda formals body)
(let ((dynamic-extent (current-dynamic-extent)))
(lambda formals
(with-dynamic-extent dynamic-extent (lambda ()
body)))))))
| true |
8498fcfab23bbf0c46ef898fd24892a9ebdfe55f | 061db6d37c5d05d56d4b7eedbda08568f42da533 | /gui-easy-lib/gui/easy/font.rkt | 614d71d327ea4a6333fb52609bbed86200a5c29f | [
"BSD-3-Clause"
]
| permissive | DavidAlphaFox/racket-gui-easy | f2d34da14cf3c73c58119023d591f185ad63d071 | d61300c08250ca594464d5285cdfd5e2b49195fb | refs/heads/master | 2023-06-29T04:42:03.232576 | 2021-08-01T09:28:29 | 2021-08-01T09:28:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 908 | rkt | font.rkt | #lang racket/base
(require racket/class
racket/contract
(prefix-in gui: racket/gui))
(provide
(contract-out
[font (->* (string? (real-in 0 1024.0))
(#:family gui:font-family/c
#:style gui:font-style/c
#:weight gui:font-weight/c
#:underline? any/c
#:smoothing gui:font-smoothing/c
#:hinting gui:font-hinting/c
#:size-in-pixels? any/c)
(is-a?/c gui:font%))]))
(define (font face size
#:family [family 'default]
#:style [style 'normal]
#:weight [weight 'normal]
#:underline? [underline? #f]
#:smoothing [smoothing 'default]
#:hinting [hinting 'aligned]
#:size-in-pixels? [pixels? #f])
(make-object gui:font% size face family style weight underline? smoothing pixels? hinting))
| false |
b7b03c125c56ed02b75a7770a21f28609dabeb96 | b64657ac49fff6057c0fe9864e3f37c4b5bfd97e | /ch2/ex-01.rkt | 5267087a89dc96f7f08b59897318ae1c13ec14cb | []
| no_license | johnvtan/sicp | af779e5bf245165bdfbfe6965e290cc419cd1d1f | 8250bcc7ee4f4d551c7299643a370b44bc3f7b9d | refs/heads/master | 2022-03-09T17:30:30.469397 | 2022-02-26T20:22:24 | 2022-02-26T20:22:24 | 223,498,855 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 734 | rkt | ex-01.rkt | #!/usr/bin/racket
#lang sicp
(define (make-rat n d)
(define (gcd a b)
(if (= b 0)
a
(gcd b (remainder a b))))
; seems like remainder might do this for us?
; use abs to get this to work better?
(let [(div (abs (gcd n d)))
(sign (if (< d 0) -1 1))]
(cons (* sign (/ n div)) (* sign (/ d div)))))
; Returns the numerator of a rational number
(define (numer rat)
(car rat))
; Returns the denominator of a rational number
(define (denom rat)
(cdr rat))
(define (print-rat r)
(display (numer r)) (display "/") (display (denom r)))
(print-rat (make-rat -4 -6)) (newline)
(print-rat (make-rat -4 6)) (newline)
(print-rat (make-rat 4 6)) (newline)
(print-rat (make-rat 4 -6)) (newline)
| false |
09184b9c0ce391f5a43fd97efbf7f6e2b5463e47 | 93b116bdabc5b7281c1f7bec8bbba6372310633c | /plt/tspl/codes/ch3/Continuation-Passing-Style.rkt | 97040f391e98b82021d5891816c0d6d7e8e7158c | []
| no_license | bianyali/BookList | ac84aa5931ced43f99269f881e009644ce68bb49 | ef64c71ac5da235bfab98336e2deb049e8c35b67 | refs/heads/master | 2021-01-17T10:13:20.341278 | 2015-12-29T04:45:53 | 2015-12-29T04:45:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,980 | rkt | Continuation-Passing-Style.rkt | ; Section 3.4. Continuation Passing Style
#lang racket
; test the continuation effective field
(define hello-out (lambda ()
(define hello-inner (lambda ()
(call-with-current-continuation (lambda (k)
(k)
(display 'What-a-fuck-1)
(newline)))
(display 'what-a-fuck-2)
(newline)))
(display 'hello-world-1)
(newline)
(hello-inner)
(display 'hello-world-2)
(newline)
))
(hello-out)
; explicit continuation
; -> (d b a c)
(letrec ([f (lambda (x)
(cons 'a x))]
[g (lambda (x)
(cons 'b (f x)))]
[h (lambda (x)
(g (cons 'c x)))])
(cons 'd (h '())))
; call/cc -> continuation
(define product-with-call/cc (lambda (ls)
(call/cc (lambda (break)
(let f ([ls ls])
(cond
[(null? ls) 1]
[(= (car ls) 0) (break 0)]
[else (* (car ls)
(f (cdr ls)))]))))))
(product-with-call/cc '(1 2 3 4 5))
(define product (lambda (ls k)
(let ([break k])
(let f ([ls ls] [k k])
(cond
[(null? ls) (k 1)]
[(= (car ls) 0) (break 0)]
[else (f (cdr ls)
(lambda (x)
(k (* (car ls) x))))])))))
(product '(1 2 3 4 5) (lambda (x) x))
| false |
69b8cfcd5792d7a6d0f6c8c054a9202fc44b935c | 57e0538061720aaac9321892eb35cfeb18499059 | /unicode-linebreak/classes.rkt | 5443afa96caaecf51ff61332213c342578b88c36 | [
"MIT"
]
| permissive | mbutterick/unicode-linebreak | befbaff0c09c532925c221915920cc5982f12c8c | c88265230c9374eb2427eef6ac06d8a2d7c719d3 | refs/heads/master | 2022-07-09T08:31:42.395569 | 2022-06-29T18:37:11 | 2022-06-29T18:37:11 | 177,662,248 | 3 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,518 | rkt | classes.rkt | #lang racket/base
(provide (all-defined-out))
;; The following break classes are handled by the pair table
(define OP 0) ;; Opening punctuation
(define CL 1) ;; Closing punctuation
(define CP 2) ;; Closing parenthesis
(define QU 3) ;; Ambiguous quotation
(define GL 4) ;; Glue
(define NS 5) ;; Non-starters
(define EX 6) ;; Exclamation/Interrogation
(define SY 7) ;; Symbols allowing break after
(define IS 8) ;; Infix separator
(define PR 9) ;; Prefix
(define PO 10) ;; Postfix
(define NU 11) ;; Numeric
(define AL 12) ;; Alphabetic
(define HL 13) ;; Hebrew Letter
(define ID 14) ;; Ideographic
(define IN 15) ;; Inseparable characters
(define HY 16) ;; Hyphen
(define BA 17) ;; Break after
(define BB 18) ;; Break before
(define B2 19) ;; Break on either side (but not pair)
(define ZW 20) ;; Zero-width space
(define CM 21) ;; Combining marks
(define WJ 22) ;; Word joiner
(define H2 23) ;; Hangul LV
(define H3 24) ;; Hangul LVT
(define JL 25) ;; Hangul L Jamo
(define JV 26) ;; Hangul V Jamo
(define JT 27) ;; Hangul T Jamo
(define RI 28) ;; Regional Indicator
;; The following break classes are not handled by the pair table
(define AI 29) ;; Ambiguous (Alphabetic or Ideograph)
(define BK 30) ;; Break (mandatory)
(define CB 31) ;; Contingent break
(define CJ 32) ;; Conditional Japanese Starter
(define CR 33) ;; Carriage return
(define LF 34) ;; Line feed
(define NL 35) ;; Next line
(define SA 36) ;; South-East Asian
(define SG 37) ;; Surrogates
(define SP 38) ;; Space
(define XX 39) ;; Unknown | false |
b00aa7cd4b4cff8eb5dbbdf22324e805dd064ed9 | 804e0b7ef83b4fd12899ba472efc823a286ca52d | /peer/src/net/scurl/services/reverse-proxy-test.rkt | c89c354451ab05d0c9a8860853f5c589853c114e | []
| no_license | cha63506/CRESTaceans | 6ec436d1bcb0256e17499ea9eccd5c034e9158bf | a0d24fd3e93fc39eaf25a0b5df90ce1c4a96ec9b | refs/heads/master | 2017-05-06T16:59:57.189426 | 2013-10-17T15:22:35 | 2013-10-17T15:22:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 4,170 | rkt | reverse-proxy-test.rkt | #lang racket/base
(require racket/contract racket/list)
(require rackunit
"depends.rkt"
"reverse-proxy.rkt"
"program.rkt"
"../peer-validation/scurl.rkt")
; Main reverse-proxy-test
(define reverse-proxy-test
(test-suite
"Tests for reverse-proxy-test.rkt"
(test-case
"Check the run-rproxy-programs function."
; Test that running multiple programs returns the expected result.
(let* (; Add a program that is always run and returns not handled.
(prog-list (add-rproxy-program (new-program-list) (lambda (msg) #f)))
(ae (generate-scurl "http://www.amazon.com"
digest:sha256
pkey:rsa
(generate-key pkey:rsa 256)))
(prog-list (add-rproxy-program prog-list (lambda (msg) ae)
#:filter ".*amazon.*"
#:exclude ".*exclude.*"))
(a (generate-scurl "http://www.amazon.exclude.com"
digest:sha256
pkey:rsa
(generate-key pkey:rsa 256)))
(prog-list (add-rproxy-program prog-list (lambda (msg) a)
#:filter ".*amazon.*"))
(ee (generate-scurl "http://www.ebay.com"
digest:sha256
pkey:rsa
(generate-key pkey:rsa 256)))
(prog-list (add-rproxy-program prog-list (lambda (msg) ee)
#:filter ".*ebay.*"
#:exclude ".*exclude.*"))
(e (generate-scurl "http://www.ebay.exclude.com"
digest:sha256
pkey:rsa
(generate-key pkey:rsa 256)))
(prog-list (add-rproxy-program prog-list (lambda (msg) e)
#:filter ".*ebay.*"))
(pse (generate-scurl "http://prefix.sf.net"
digest:sha256
pkey:rsa
(generate-key pkey:rsa 256)))
(prog-list (add-rproxy-program prog-list (lambda (msg) pse)
#:prefix "http://prefix."
#:filter "^sf.*"
#:exclude ".*exclude.*"))
(ps (generate-scurl "http://prefix.sf.exclude.net"
digest:sha256
pkey:rsa
(generate-key pkey:rsa 256)))
(prog-list (add-rproxy-program prog-list (lambda (msg) ps)
#:prefix "http://prefix."
#:filter "^sf.*")))
(check-equal? (run-rproxy-programs prog-list ae (list "header" "body"))
ae
"Failed to return the amazon exclude scurl.")
(check-equal? (run-rproxy-programs prog-list a (list "header" "body"))
a
"Failed to return the amazon scurl.")
(check-equal? (run-rproxy-programs prog-list ee (list "header" "body"))
ee
"Failed to return the ebay exclude scurl.")
(check-equal? (run-rproxy-programs prog-list e (list "header" "body"))
e
"Failed to return the ebay scurl.")
(check-equal? (run-rproxy-programs prog-list pse (list "header" "body"))
pse
"Failed to return the sf exclude scurl.")
(check-equal? (run-rproxy-programs prog-list ps (list "header" "body"))
ps
"Failed to return the sf scurl.")
)
)
)
)
; Provide everything
(provide (all-defined-out))
; Uncomment to run this test from this file.
;(require rackunit/text-ui)
;(run-tests reverse-proxy-test)
| false |
1251e02f8e17372cb75bd7ae77f9bba517bc9317 | 3ac344d1cac4caa5eb4842bc0e4d61b1ae7030fb | /scribblings/commands.scrbl | 24fb6b3864441a30e15d7deb95e8677f8afe83d4 | [
"ISC"
]
| permissive | vicampo/riposte | 0c2f2a8459a2c6eee43f6f8a83f329eb9741e3fc | 73ae0b0086d3e8a8d38df095533d9f0a8ea6b31b | refs/heads/master | 2021-10-29T11:18:14.745047 | 2021-10-13T10:20:33 | 2021-10-13T10:20:33 | 151,718,283 | 42 | 5 | ISC | 2019-03-26T12:20:23 | 2018-10-05T12:35:49 | Racket | UTF-8 | Racket | false | false | 5,063 | scrbl | commands.scrbl | #lang scribble/manual
@title{Commands}
With @emph{commands}, you send out your HTTP requests.
Optionally, you can check that
@itemlist[
@item{the responses have a certain response code (200, 204, 404, etc.), and}
@item{that the whole response body satisfies a JSON Schema.}
]
Those two parts are optional; you can check the response code without specifying a schema, and you can specify a schema without saying anything about the response code. You can leave out both, or supply both.
(The Riposte langauge has a concept of an assertion, which is all about checking things. When a command includes a response code check, or a schema check, then commands has the effect of performing an assertion.)
Formally, a command has one of these these structures, depending on whether you want to check the response code and assert that the response satisfies a schema.
@verbatim{
HTTP-METHOD [ PAYLOAD "to" ] URI-TEMPLATE "times" "out"
}
This command submits an HTTP request and succeeds if the request times out. By default, Riposte does not time out waiting for a response. To control that, use the @tt{%timeout} parameter, like so:
@verbatim{
%timeout := 10 # wait at most 10 seconds for a response
}
@verbatim{
HTTP-METHOD [ PAYLOAD "to" ] URI-TEMPLATE [ "with" "headers" HEADERS ]
}
@verbatim{
HTTP-METHOD [ PAYLOAD "to" ] URI-TEMPLATE [ "with" "headers" HEADERS ] "responds" "with" HTTP-RESPONSE-CODE [ "and" "satisfies" "schema" SCHEMA ]
}
@verbatim{
HTTP-METHOD [ PAYLOAD "to" ] URI-TEMPLATE [ "with" "headers" HEADERS ] "satisfies" "schema" SCHEMA
}
A command need not be on one line.
@section{HTTP methods}
HTTP-METHOD consists of a non-empty sequence of uppercase letters. Typical examples:
@itemlist[
@item{@tt{GET}}
@item{@tt{POST}}
@item{@tt{OPTIONS}}
@item{@tt{PUT}}
@item{@tt{PATCH}}
@item{@tt{DELETE}}
]
However, you can use whatever you like, e.g., @tt{CANCEL}, @tt{BREW}, and so on.
@section{Payload}
PAYLOAD, if present, is supposed to be a variable reference or literal JSON (with variables allowed). Here's an example:
@codeblock[#:keep-lang-line? #f #:line-numbers #f]|{
#lang riposte
$payload := { "a" : 4, "b": true, "c": [] }
POST $payload to api/flub responds with 2XX
}|
When executing the command, the payload will become the request body.
@section{URI-TEMPLATE}
HTTP requests need to have a URI. (Of course.) The URI could be either fixed (that is, involve no variables)
The URI that will ultimately be built will be glommed onto whatever the base URI is. By default, there is no base URI, so your URI will be used as-is. If a base URI is specified (assign a string value to the global variable @tt{%base} for that purpose), then it will be the prefix for your specified URI. If you wish to go around the base URI, specify an absolute URI, like @tt{https://whatever.test/api/grub} or, before the command, unset @tt{%base}.
If you're not so static, the URI you give here might be built up from URI Templates. Here's a typical example:
@codeblock[#:keep-lang-line? #f #:line-numbers #f]|{
#lang riposte
$payload := { "a" : 4, "b": true, "c": [] }
$id := 1
POST $payload to api/flub/{id} responds with 2XX
}|
A URI is, at the end of the day, a kind of string. In this example, notice that we've used an integer and plugged it into the URI.
@section{HEADERS}
For a single request, one can specify headers that should be used, in just @emph{this} request, in addition to the ones that are already set. Here's a typical example:
@codeblock[#:keep-lang-line? #f #:line-numbers #f]|{
#lang riposte
$heads := { "Accept-Language": "jp" }
POST $payload to api/flub with headers $heads responds with 2XX
}|
Notice here that we use a JSON object to specify the headers. The headers that are ultimately generated are normalized. (If you have an application that is sensitive to normalization—if it behaves one way when headers are normalized and another if headers are not normalized, I'm afraid Riposte cannot currently build such HTTP requests.)
@section{HTTP-RESPONSE-CODE}
HTTP response codes are supposed to be three-digit integers. There aren't lots of possibilities.
If you don't care about the precise response code, you can use response code patterns. Example: @tt{2XX} means: any 200-class is OK. It could be 200, 201, 204, you name it. You can also say things like @tt{20X} to mean that 200, 201, … 209 would be OK, but 210 wouldn't be.
@section{SCHEMA}
There are two forms that SCHEMA can take:
@itemlist[
@item{a variable reference, or}
@item{an unquoted string.}
]
The two forms are for referring directly to a JSON Schema as a JSON value or in an external file. Here are examples of the two kinds of forms:
@codeblock[#:keep-lang-line? #f #:line-numbers #f]|{
#lang riposte
$schema := {
"type": "object",
"requiredProperties": [ "age", "weight" ]
}
POST $payload to api/flub satisfies schema $schema
}|
Example of using a schema specified in a file:
@codeblock[#:keep-lang-line? #f #:line-numbers #f]|{
#lang riposte
POST $payload to api/flub satisfies schema in schema.json
}|
| false |
b0c984b4eae7c9991d86fd524b0476cf1adf07b7 | 898dceae75025bb8eebb83f6139fa16e3590eb70 | /sem1/hw/AA-theater.rkt | b5d08c42045dc929d46216b2c6dc811ec6a2d963 | []
| no_license | atamis/prog-hw | 7616271bd4e595fe864edb9b8c87c17315b311b8 | 3defb8211a5f28030f32d6bb3334763b2a14fec2 | refs/heads/master | 2020-05-30T22:17:28.245217 | 2013-01-14T18:42:20 | 2013-01-14T18:42:20 | 2,291,884 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,827 | rkt | AA-theater.rkt | ;; The first three lines of this file were inserted by DrRacket. They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-reader.ss" "lang")((modname all_hallows_eve) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ())))
;; Unnumbered assignment
; Andrew Amis
; 10.31.11 (All Hallow's Eve)
; Handout
(define movie-cost 180) ; Flat cost of one showing of one movie
(define customer-cost 0.04) ; Cost of 1 customer of a movie
;; customers : number -> number
; Takes a number representing the cost of the ticket and returns the number of
; customers. Cost should be in $.
(define (customers price)
(+ 120 (* (/ -15 0.1) (- price 5))))
(check-expect (customers 5) 120)
(check-expect (customers 5.2) 90)
(check-expect (customers 4.5) 195)
(check-expect (customers 4) 270)
;; income : number -> number
; Takes the cost of a ticket and returns the projected gross income.
(define (income price)
(* price (customers price)))
(check-within (income 5.00) 600 0.1)
(check-within (income 5.20) 468 0.1)
(check-within (income 4.5) 877.5 0.1)
(check-within (income 4) 1080 0.1)
;; cost : number -> number
; Takes number of customers and returns the cost of the showing.
(define (cost customers)
(+ (* customer-cost customers) movie-cost))
(check-within (cost 120) 184.8 0.01)
(check-within (cost 90) 183.6 0.01)
(check-within (cost 195) 187.8 0.01)
(check-within (cost 270) 190.8 0.01)
;; profit : number -> number
; Calculates the profit for a given price.
(define (profit price)
(- (income price) (cost (customers price))))
(check-within (profit 5.00) 415.2 0.01)
(check-within (profit 5.20) 284.4 0.01)
(check-within (profit 4.50) 689.7 0.01)
(check-within (profit 4.00) 889.2 0.01) | false |
badb10bc28ab68a23a0e55c483f3864c2335ad8c | 9dc77b822eb96cd03ec549a3a71e81f640350276 | /base/generative-token.rkt | dc6201a3b18b75ad84e30c773d9109317869b75d | [
"Apache-2.0"
]
| permissive | jackfirth/rebellion | 42eadaee1d0270ad0007055cad1e0d6f9d14b5d2 | 69dce215e231e62889389bc40be11f5b4387b304 | refs/heads/master | 2023-03-09T19:44:29.168895 | 2023-02-23T05:39:33 | 2023-02-23T05:39:33 | 155,018,201 | 88 | 21 | Apache-2.0 | 2023-09-07T03:44:59 | 2018-10-27T23:18:52 | Racket | UTF-8 | Racket | false | false | 321 | rkt | generative-token.rkt | #lang racket/base
(require racket/contract/base)
(provide
(contract-out
[generative-token? (-> any/c boolean?)]
[make-generative-token (-> generative-token?)]))
;@------------------------------------------------------------------------------
(struct generative-token () #:constructor-name make-generative-token)
| false |
d18f9a6c823375d3b99e29a41da1c17705a72d7a | 1634c327ac6670a4ddaf82d5541cbea3b7de0c07 | /scripts/full_haskell_package.rkt | ecde1cebcea82558fc0b0e109ec41e9316d796e7 | []
| no_license | Warbo/theory-exploration-benchmarks | 7b04ae44f6354c698aead862b6afe4a30760fe98 | 2862edcc3584b511dc54a72ecd1a5fc12cc71ab3 | refs/heads/master | 2020-04-12T06:29:17.857981 | 2018-08-13T13:37:16 | 2018-08-13T13:37:16 | 60,284,207 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 159 | rkt | full_haskell_package.rkt | #!/usr/bin/env racket
#lang racket
(require lib/sigs)
(full-haskell-package-s (port->string (current-input-port))
(getenv "OUT_DIR"))
| false |
fdaf3b8a9d31cf1a6471b1474bd17ab9a294f379 | 32ec46d862e6433fe64d72522dacc6096489b73c | /utilities.rkt | bf5b0a309390f01924c6ced06d39b6a175b88ca7 | [
"MIT"
]
| permissive | davelab6/sfont | 627da298d2a832d8e5413a486fb9f27d4e43acc9 | f7f08d6e648d0892a7ee42a78753547d52e6389a | refs/heads/master | 2021-01-18T03:09:34.179472 | 2013-09-11T13:22:15 | 2013-09-11T13:22:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,175 | rkt | utilities.rkt | #lang racket
(provide n-groups
num->int
code+expr
square
double
°
pi/2
pi/3
pi/4
pi/6
2pi)
; n-groups
; List [Any], Natural -> List of List [Any]
; (n-groups '(a b c d e f) 2) -> '((a b) (b c) (c d) (d e) (e f))
; (n-groups '(a b c d e f g) 3) -> '((a b c) (c d e) (e f g))
(define (n-groups lst n)
(if (null? (cdr lst))
null
(let-values ([(f rest) (split-at lst (- n 1))])
(cons (append f (list (car rest)))
(n-groups rest n)))))
(define (num->int n)
(inexact->exact (floor n)))
(define-syntax code+expr
(syntax-rules ()
[(code+expr expr)
(begin
(display "The expression:")
(newline)
(display (quote expr))
(newline)
(display "evaluates to:")
(newline)
expr)]))
(define (square n) (* n n))
(define (double n) (* n 2))
(define (degree->rad angle)
(* pi (/ angle 180.0)))
; Number -> Number
; convert from degree to radians
(define (° d)
(* (/ d 180) pi))
(define pi/2 (/ pi 2))
(define pi/3 (/ pi 3))
(define pi/4 (/ pi 4))
(define pi/6 (/ pi 6))
(define 2pi (* 2 pi)) | true |
5b41cacf99e8e82f6431233e8034f5992890bcf3 | 76df16d6c3760cb415f1294caee997cc4736e09b | /diff-testing/rosette-backend.rkt | 43f34e4971ca2f0240189728090657e2ebcf6056 | [
"MIT"
]
| permissive | uw-unsat/leanette-popl22-artifact | 70409d9cbd8921d794d27b7992bf1d9a4087e9fe | 80fea2519e61b45a283fbf7903acdf6d5528dbe7 | refs/heads/master | 2023-04-15T21:00:49.670873 | 2021-11-16T04:37:11 | 2021-11-16T04:37:11 | 414,331,908 | 6 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 3,114 | rkt | rosette-backend.rkt | #lang racket
(provide (all-defined-out))
(require (prefix-in rosette: rosette)
"lib.rkt")
(define (parse-term type t)
(match* (type t)
[('int (? number?)) (values t 1)]
[('bool #true) (values #true 1)]
[('bool #false) (values #false 1)]
[(_ `(var ,x)) (values (make-symbolic-var type x) 1)]
[(_ `(ite ,c ,t ,e))
; important: we don't want to evaluate t and e under c, so
; evaluate them all first
(define-values [ec c-stat] (parse-term 'bool c))
(define-values [et t-stat] (parse-term type t))
(define-values [ee e-stat] (parse-term type e))
(values (rosette:if ec et ee) (+ c-stat t-stat e-stat 1))]
[(_ `(expr ,o ,l ,r))
(define-values [el l-stat] (parse-term 'int l))
(define-values [er r-stat] (parse-term 'int r))
(values
((match o
['add rosette:+]
['mul rosette:*]
['lt rosette:<]
['eq rosette:=])
el
er)
(+ l-stat r-stat 1))]))
(define (parse-state s)
(match-define `(state ,assumes ,asserts) s)
(define-values [assumes-val assumes-stat] (parse-term 'bool assumes))
(define-values [asserts-val asserts-stat] (parse-term 'bool asserts))
(values (state assumes-val asserts-val) (+ assumes-stat asserts-stat)))
(define (parse-union gvs)
(match gvs
[(list `(choice ,g ,v) gvs ...)
(define-values [eg _] (parse-term 'bool g))
(define ev (parse-val v))
(define gvs* (parse-union gvs))
(rosette:if eg ev gvs*)]
[(list) (undef)]))
(define (parse-list xs)
(match xs
[(list x xs ...)
(define x* (parse-val x))
(define xs* (parse-list xs))
(cons x* xs*)]
[(list) '()]))
(define (parse-var x) (string->symbol (format "x~a" x)))
(define (parse-ast t)
(match t
[`(let0 ,x ,v ,b)
`(let ([,(parse-var x) ,(parse-ast v)])
,(parse-ast b))]
[`(datum (op.lang.datum.int ,x)) x]
[`(if0 ,c ,t ,e)
`(if ,(parse-var c)
,(parse-ast t)
,(parse-ast e))]
[`(app ,o ,xs ...)
`(,o ,@(for/list ([x xs]) (parse-var x)))]
[`(call ,f ,a) `(,(parse-var f) ,(parse-var a))]
[`(var ,x) (parse-var x)]
[#t #t]
[#f #f]
[`(λ ,x ,b) `(lam ,(parse-var x) ,(parse-ast b))]
[`(make-error) `(assert #f)]
[`(make-abort) `(assume #f)]
['undef `(undef)]))
(define (parse-val v)
(match v
[`(union ,gvs ...) (parse-union gvs)]
[`(term_int ,t) (call-with-values (λ () (parse-term 'int t)) (λ (a _) a))]
[`(term_bool ,t) (call-with-values (λ () (parse-term 'bool t)) (λ (a _) a))]
[`(list ,xs ...) (parse-list xs)]
[`(clos ,x ,e (list ,env ...)) (closure values
(parse-var x)
(parse-ast e)
(parse-list env))]))
(define (parse v)
(match v
['none (values (none) 0)]
[`(halt ,state)
(define-values [val stat] (parse-state state))
(values (halt val) stat)]
[`(ans ,state ,v)
(define-values [val stat] (parse-state state))
(values (ans val (parse-val v)) stat)]))
| false |
75db0a30615e793aae1002620e91c350ecfc533a | 04c0a45a7f234068a8386faf9b1319fa494c3e9d | /shortest-paths.rkt | 1a2c177fe2fbabcc6147e16a5e5bcad93f5f6ec9 | []
| no_license | joskoot/lc-with-redex | 763a1203ce9cbe0ad86ca8ce4b785a030b3ef660 | 9a7d2dcb229fb64c0612cad222829fa13d767d5f | refs/heads/master | 2021-01-11T20:19:20.986177 | 2018-06-30T18:02:48 | 2018-06-30T18:02:48 | 44,252,575 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,165 | rkt | shortest-paths.rkt | #lang racket
;Procedure (shortest-paths S T G) -> (P ...)
;For any type N:
;S : N starting node
;T : N destination node
;G : N → (N ...) procedure representing a graph
;eq : N N → Boolean equality relation
;P : (N ...) path from S to T
(define (shortest-paths S T G)
(define H (make-hash))
(define (put! P) (hash-set! H (car P) #f))
(define (new? N) (not (hash-has-key? H N)))
(define (filtered-G N) (filter new? (G N)))
(define (extend P)
(let ((Ns (remove-duplicates (filtered-G (car P)))))
(map (lambda (N) (cons N P)) Ns)))
(define (next-F F)
(if (null? F) '( ) ; No paths found.
(let ((Ps (filter (lambda (P) (equal? (car P) T)) F)))
(if (pair? Ps) (map reverse Ps) ; The paths have been found.
(begin (for-each put! F) ; Point T has not yet been found.
(next-F (apply append (filter pair? (map extend F)))))))))
(next-F (list (list S))))
;;; test
(define (make-point x y) (list x y))
(define x-coordinate car)
(define y-coordinate cadr)
(require (only-in redex test-equal test-results))
(define (test-shortest-paths from to)
(define (G P)
(let ((x (x-coordinate P)) (y (y-coordinate P)))
(list
(make-point x (add1 y))
(make-point x (sub1 y))
(make-point (add1 x) y)
(make-point (sub1 x) y))))
(test-equal (length (shortest-paths from to G))
(let
((x (abs (- (x-coordinate from) (x-coordinate to))))
(y (abs (- (y-coordinate from) (y-coordinate to)))))
(binomial (+ x y) x))))
(define-syntax define/c
(syntax-rules ()
((_ (name arg ...) . body)
(define name
(let ((cache (make-hash)))
(lambda (arg ...)
(let ((key (list arg ...)))
(apply values
(hash-ref cache key
(lambda ()
(let ((r (call-with-values (lambda () . body) list)))
(hash-set! cache key r)
r)))))))))))
(define/c (binomial n k) (/ (factorial n) (factorial k) (factorial (- n k))))
(define/c (factorial k) (if (zero? k) 1 (* k (factorial (sub1 k)))))
(let*
((from (make-point 0 0))
(range (in-range -5 6))
(points (for*/list ((x range) (y range)) (make-point x y))))
(for ((to points)) (test-shortest-paths from to)))
(test-results)
| true |
4d1a731df58e4120339c5029a8b3b1c1e4aea75f | b0248622135fdfba7713608a8a68bed1a28c4b8a | /practice/simply-scheme/Chapter7/exercises.rkt | 46d67852b4a24dee4e90c6d287588e3958150d88 | []
| no_license | tomjkidd/racket | a3a56d5f78d6345e24521b62e903e84d81b8b4df | becd564ce704966c609677a6ca0eb15ace35eee0 | refs/heads/master | 2016-09-05T19:33:42.698426 | 2015-10-15T13:38:44 | 2015-10-15T13:38:44 | 38,984,752 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,192 | rkt | exercises.rkt | #lang racket
(require (planet dyoo/simply-scheme:2))
(define (roots a b c)
(let ((discriminant (sqrt (- (* b b) (* 4 a c))))
(minus-b (- b))
(two-a (* 2 a)))
(se (/ (+ minus-b discriminant) two-a)
(/ (- minus-b discriminant) two-a))))
(roots 1 2 3)
(define (vowel? letter)
(member? letter '(a e i o u)))
#! 7.1
(define (gertrude-repetitive wd)
(se (if (vowel? (first wd)) 'an 'a)
wd
'is
(if (vowel? (first wd)) 'an 'a)
wd
'is
(if (vowel? (first wd)) 'an 'a)
wd))
(define (gertrude wd)
(let ((a-or-an (if (vowel? (first wd)) 'an 'a))
(word-is (se wd 'is)))
(se a-or-an
word-is
a-or-an
word-is
a-or-an
wd )))
(gertrude 'rose)
(gertrude 'iguana)
#! 7.2
(let ((pi 3.14159)
(pie '(lemon meringue)))
(se '(pi is) pi '(but pie is) pie))
#! 7.3 Again with hiding a global definition (word).
(define (superlative adjective wd)
(se (word adjective 'est) wd))
(superlative 'dumb 'exercise)
#! 7.4 Renames and swaps the addition and multiplication operators
(define (sum-square a b)
(let ((+ *)
(* +))
(* (+ a a) (+ b b))))
(sum-square 3 4) | false |
a4e9afe3e15e01dfb075687dfd04a402025baca8 | ea4fc87eafa7b36a43f8f04b9585d73aeed1f036 | /laramie-test/laramie/issue-38.rkt | 1ee3c5a01799cd2805e4af4b50d61afaaad5cb24 | [
"MIT"
]
| permissive | jthodge/laramie | a58a551727aebc792bdcaa5193dff775fd9848df | 7afc9314ff1f363098efeb68ceb25e2e9c419e6e | refs/heads/master | 2023-06-19T21:19:43.308293 | 2021-07-19T05:20:01 | 2021-07-19T05:20:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 668 | rkt | issue-38.rkt | #lang racket/base
(require laramie)
(module+ test
(require rackunit))
(define document #<<DOC
<!doctype html>
<html>
<head><head>
<body>
<style>
#main_welcome
{
width:380px;
height:480px;
float:left;
}
</style>
</body>
</html>
DOC
)
(define (style-element? x)
(and (element? x)
(equal? 'style (element-local-name x))))
(define elements (filter element? (descendants (parse document))))
(define style-element (findf style-element? elements))
(module+ test
(check-not-false style-element)
(check-equal?
(element-content style-element)
(list
"\n#main_welcome\n{\n width:380px;\n height:480px;\n float:left;\n}\n")))
| false |
7b9ef8aeb1fdea5f8929332df735c68d0f55bff9 | 799b5de27cebaa6eaa49ff982110d59bbd6c6693 | /soft-contract/test/programs/safe/octy/ex-04.rkt | 988b2996a0c73419056c26e7b7d35c29b148313e | [
"MIT"
]
| permissive | philnguyen/soft-contract | 263efdbc9ca2f35234b03f0d99233a66accda78b | 13e7d99e061509f0a45605508dd1a27a51f4648e | refs/heads/master | 2021-07-11T03:45:31.435966 | 2021-04-07T06:06:25 | 2021-04-07T06:08:24 | 17,326,137 | 33 | 7 | MIT | 2021-02-19T08:15:35 | 2014-03-01T22:48:46 | Racket | UTF-8 | Racket | false | false | 228 | rkt | ex-04.rkt | #lang racket
(define (f x)
(if (number? x) (add1 x) (string-length x)))
(define (g x)
(if (or (number? x) (string? x)) (f x) 0))
(provide/contract
[f ((or/c string? number?) . -> . number?)]
[g (any/c . -> . number?)])
| false |
18af35ecf97bff255fb75dbc50728d756a126f59 | 5782922f05d284501e109c3bd2a2e4b1627041b9 | /codes/racket/racket-book-master/docs/11-server.scrbl | eb75fd4ccfed70e7340653ee3fba4b794523b82a | []
| no_license | R4mble/Notes | 428e660369ac6dc01aadc355bf31257ce83a47cb | 5bec0504d7ee3e5ef7bffbc80d50cdddfda607e6 | refs/heads/master | 2022-12-11T12:31:00.955534 | 2019-09-23T08:46:01 | 2019-09-23T08:46:01 | 192,352,520 | 0 | 0 | null | 2022-12-11T03:48:32 | 2019-06-17T13:28:24 | JavaScript | UTF-8 | Racket | false | false | 177 | scrbl | 11-server.scrbl | #lang scribble/doc
@(require (for-label racket)
scribble/manual
"../util/common.rkt")
@title[#:tag "server"]{用Racket编写服务器程序}
Hello world!
| false |
682a2246d304783fe56eb734f3cc8b5aa9ce473d | fc37300ac537d7dad85d83f08c417697366b2286 | /main.rkt | e3abc06f550b86242c917de0bf526a5968acead0 | []
| no_license | thisisjacob/arithmeticassistance | 3e0cb374fb2b9106ed8d5b546398a0446a32ca50 | 5badbf33661e8a4b16621345806a1d0e65bc281a | refs/heads/master | 2023-01-15T14:15:41.246874 | 2020-11-13T18:01:29 | 2020-11-13T18:01:29 | 298,638,502 | 0 | 1 | null | 2020-11-01T02:30:14 | 2020-09-25T17:30:00 | Racket | UTF-8 | Racket | false | false | 230 | rkt | main.rkt | ; Starts the program
#lang racket
(require racket/gui/base)
(require "ui/mainWindow.rkt")
(require "constants/userInterfaceConstants.rkt")
; creates the UI
(define game (new mainWindow% [title programTitle]))
(send game startUI)
| false |
df5f5dd08bf094d4b11a32240899611f50953381 | b3f7130055945e07cb494cb130faa4d0a537b03b | /gamble/private/mh/interfaces.rkt | 7ad4d0626f77e87ce1e419801e3d9420e484518d | [
"BSD-2-Clause"
]
| permissive | rmculpepper/gamble | 1ba0a0eb494edc33df18f62c40c1d4c1d408c022 | a5231e2eb3dc0721eedc63a77ee6d9333846323e | refs/heads/master | 2022-02-03T11:28:21.943214 | 2016-08-25T18:06:19 | 2016-08-25T18:06:19 | 17,025,132 | 39 | 10 | BSD-2-Clause | 2019-12-18T21:04:16 | 2014-02-20T15:32:20 | Racket | UTF-8 | Racket | false | false | 929 | rkt | interfaces.rkt | ;; Copyright (c) 2014 Ryan Culpepper
;; Released under the terms of the 2-clause BSD license.
;; See the file COPYRIGHT for details.
#lang racket/base
(require racket/class
"../interfaces.rkt")
(provide (all-defined-out)
Info)
;; ============================================================
(define mh-transition<%>
(interface ()
run ;; (-> A) Trace -> (cons (U Trace #f) TxInfo)
accinfo ;; -> AccInfo
))
;; A TxInfo
;; - (vector 'delta DB) -- delta db
;; - (vector 'slice Real Real) -- slice w/ interval bounds
;; - #f
;; ============================================================
(define proposal<%>
(interface ()
propose1 ;; Key Zones Dist Value -> (U (cons Value Real) #f)
propose2 ;; Key Zones Dist Dist Value -> (U (list* Value Real Real) #f)
accinfo ;; -> AccInfo
feedback ;; Key Boolean -> Void
))
(define (proposal? x)
(is-a? x proposal<%>))
| false |
fe828ee3ddf544cc214400c982d8e5fdb273a826 | 9508c612822d4211e4d3d926bbaed55e21e7bbf3 | /tests/basic-langs/expr.rkt | ef5e4c453f9bc54c7f59fb1832990fd8e34ba6a1 | [
"MIT",
"Apache-2.0"
]
| permissive | michaelballantyne/syntax-spec | 4cfb17eedba99370edc07904326e3c78ffdb0905 | f3df0c72596fce83591a8061d048ebf470d8d625 | refs/heads/main | 2023-06-20T21:50:27.017126 | 2023-05-15T19:57:55 | 2023-05-15T19:57:55 | 394,331,757 | 13 | 1 | NOASSERTION | 2023-06-19T23:18:13 | 2021-08-09T14:54:47 | Racket | UTF-8 | Racket | false | false | 926 | rkt | expr.rkt | #lang racket/base
(require "../../testing.rkt")
(syntax-spec
(binding-class var #:description "expr language variable")
(nonterminal expr
#:description "simple expr language expression"
n:number
v:var
(+ e1:expr e2:expr)
(let ([v:var e:expr] ...) b:expr)
#:binding [e {(bind v) b}]
(let* (b:binding ...) e:expr)
#:binding (nest b e))
(nonterminal/nesting binding (nested)
#:description "let* binding group"
[v:var e:expr]
#:binding [e {(bind v) nested}]))
(check-equal?
(expand-nonterminal/datum expr
(let ([x 5]) (let ([x (+ x 1)]) x)))
'(let ([x 5]) (let ([x (+ x 1)]) x)))
(check-equal?
(expand-nonterminal/datum expr
(let* ([x 5] [x (+ x 1)]) x))
'(let* ([x 5] [x (+ x 1)]) x))
(check-exn
#rx"y: not bound as expr language variable"
(lambda ()
(convert-compile-time-error
(expand-nonterminal/datum expr (let* ([x 5]) y)))))
| false |
4237f18c202e46e7919badb1ab5eb242946fd69f | 67f496ff081faaa375c5000a58dd2c69d8aeec5f | /koyo-lib/koyo/job/query.rkt | 36bd00591d0ced4e86eb5fdd61701efa85832b4c | [
"BSD-3-Clause"
]
| permissive | Bogdanp/koyo | e99143dd4ee918568ed5b5b199157cd4f87f685f | a4dc1455fb1e62984e5d52635176a1464b8753d8 | refs/heads/master | 2023-08-18T07:06:59.433041 | 2023-08-12T09:24:30 | 2023-08-12T09:24:30 | 189,833,202 | 127 | 24 | null | 2023-03-12T10:24:31 | 2019-06-02T10:32:01 | Racket | UTF-8 | Racket | false | false | 1,098 | rkt | query.rkt | #lang racket/base
(require (for-syntax racket/base
racket/syntax
syntax/parse)
db
racket/file
racket/runtime-path)
(define-runtime-path queries
(build-path "queries"))
(define (make-virtual-stmt name)
(define path (build-path queries (format "~a.sql" name)))
(virtual-statement (file->string path)))
(define-syntax (define-stmt stx)
(syntax-parse stx
[(_ name:id)
(with-syntax ([id (format-id #'name "~a-stmt" #'name)])
#'(begin
(define id (make-virtual-stmt 'name))
(provide id)))]))
;; operational ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-stmt dequeue)
(define-stmt enqueue)
(define-stmt requeue)
(define-stmt heartbeat)
(define-stmt mark-done)
(define-stmt mark-failed)
(define-stmt mark-for-retry)
(define-stmt register-worker)
(define-stmt unregister-stale-workers)
(define-stmt unregister-worker)
;; admin ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-stmt lookup-job)
(define-stmt latest-jobs)
(define-stmt delete)
| true |
1e39e38b1d4cd40891a48ecba60726abd7e08419 | a3673e4bb7fa887791beabec6fd193cf278a2f1a | /design/slideshow/isl-code.rkt | f3f831e6832350a9210ec6ec7ea121a9e112be35 | []
| no_license | FDWraith/Racket-Docs | f0be2e0beb92f5d4f8aeeca3386240045a03e336 | 7eabb5355c19a87337f13287fbe3c10e10806ae8 | refs/heads/master | 2021-01-25T10:16:51.207233 | 2018-04-16T22:28:33 | 2018-04-16T22:28:33 | 123,346,280 | 1 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 776 | rkt | isl-code.rkt | #lang htdp/isl
; [Listof Char] - All the vowels in the alphabet, in lowercase.
(define VOWELS (list #\a #\e #\i #\o #\u #\y))
; String -> String
; Removes vowels from str.
(check-expect (shorthand "") "")
(check-expect (shorthand "world") "wrld")
(check-expect (shorthand "ApPle;") "pPl;")
(define (shorthand str)
(local
[; [Listof Char] -> [Listof Char]
; Removes vowels from the character list.
(define (shorthand-chars chars)
(cond [(empty? chars) '()]
[(cons? chars)
(if (member (char-downcase (first chars)) VOWELS)
(shorthand-chars (rest chars))
(cons (first chars) (shorthand-chars (rest chars))))]))]
(list->string (shorthand-chars (string->list str)))))
(shorthand "Racket") | false |
a83ef2d2b07d30f88015bce238e24706bbfb0ec2 | 4cc0edb99a4c5d945c9c081391ae817b31fc33fd | /scribblings/games.scrbl | 710884de4486edf41dcf4020e44d547a8e931241 | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | racket/games | c8eaa92712405890cd1db19b8ba32b1620d885b8 | eba5c6fa54c524871badb8b0e205fe37640d6c3e | refs/heads/master | 2023-08-19T00:41:23.930448 | 2023-07-24T23:29:05 | 2023-07-24T23:29:05 | 27,138,761 | 54 | 33 | NOASSERTION | 2020-05-04T13:46:50 | 2014-11-25T17:59:40 | Racket | UTF-8 | Racket | false | false | 3,464 | scrbl | games.scrbl | #lang scribble/doc
@(require "common.rkt"
(for-label racket/base racket/contract
games/show-help games/show-scribbling))
@title{Games: Fun Examples}
The @exec{PLT Games} executable (or @exec{plt-games} on Unix) lets
you select one of the games distributed by PLT or other games
installed as sub-collections of the @filepath{games} collection (see
@secref["new-games"]).
@table-of-contents[]
@; ----------------------------------------------------------------------
@include-section["std-games.scrbl"]
@; ----------------------------------------------------------------------
@section[#:tag "new-games"]{Implementing New Games}
The game-starting console inspects the sub-collections of the
@filepath{games} collection. If a sub-collection has an
@filepath{info.rkt} module (see @racketmodname[info]), the
following fields of the collection's @filepath{info.rkt} file are used:
@itemize[
@item{@racketidfont{game} [required] : used as a module name in the
sub-collection to load for the game; the module must provide a
@racketidfont["game@"] unit (see @racketmodname[racket/unit]) with
no particular exports; the unit is invoked with no imports to
start the game.}
@item{@racketidfont{name} [defaults to the collection name] : used to
label the game-starting button in the game console.}
@item{@racketidfont{game-icon} [defaults to collection name with
@filepath{.png}] : used as a path to a bitmap file that is used for
the game button's label; this image should be 32 by 32 pixels and
have a mask.}
@item{@racketidfont{game-set} [defaults to @racket["Other Games"]] :
a label used to group games that declare themselves to be in the
same set.}
]
To implement card games, see @racketmodname[games/cards]. Card games
typically belong in the @racket["Cards"] game set.
@; ----------------------------------------------------------------------
@section{Showing Scribbled Help}
@defmodule[games/show-scribbling]
@defproc[(show-scribbling [mod-path module-path?]
[section-tag string?])
(-> void?)]{
Returns a thunk for opening a Scribbled section in the user's HTML
browser. The @racket[mod-path] is the document's main source module,
and @racket[section-tag] specifies the section in the document.}
@; ----------------------------------------------------------------------
@section{Showing Text Help}
@defmodule[games/show-help]
@defproc[(show-help [coll-path (listof string?)]
[frame-title string?]
[verbatim? any/c #f])
(-> any)]{
Returns a thunk for showing a help window based on plain
text. Multiple invocations of the thunk bring the same window to the
foreground (until the user closes the window).
The help window displays @filepath{doc.txt} from the collection
specified by @racket[coll-path].
The @racket[frame-title] argument is used for the help window title.
If @racket[verbatim?] is true, then @filepath{doc.txt} is displayed
verbatim, otherwise it is formatted as follows:
@itemize[
@item{Any line of the form @litchar{**}....@litchar{**} is omitted.}
@item{Any line that starts with @litchar{*} after whitespace is indented
as a bullet point.}
@item{Any line that contains only @litchar{-}s and is as long as the previous
line causes the previous line to be formatted as a title.}
@item{Other lines are paragraph-flowed to fit the window.}
]}
| false |
a579f41aacb412b818ddc063d5e15427a0736ce6 | c86a68a8b8664e6def1e072448516b13d62432c2 | /markdown/perf-test.rkt | 1b52af733f30abfe975096d7420a687005d1ea22 | [
"BSD-3-Clause",
"BSD-2-Clause"
]
| permissive | greghendershott/markdown | 97e9317aed13bfc7d48f9c88ca9b726774d7911d | 34ada7458fad51d3a5e0516352f8bd399c517140 | refs/heads/master | 2022-12-05T13:35:32.353364 | 2022-11-25T18:06:09 | 2022-11-25T18:09:38 | 8,568,669 | 89 | 27 | null | 2021-03-25T14:21:20 | 2013-03-05T00:42:54 | Racket | UTF-8 | Racket | false | false | 2,059 | rkt | perf-test.rkt | ;; Copyright (c) 2013-2022 by Greg Hendershott.
;; SPDX-License-Identifier: BSD-2-Clause
#lang at-exp racket/base
(require (for-syntax racket/base)
racket/file
racket/format
racket/string
"ci-environment.rkt")
;; A poor change to the grammar can potentially have a large
;; performance impact. Check for that.
(module+ test
(require rackunit
"main.rkt")
(require racket/runtime-path)
(define-runtime-path test.md (build-path "test" "test.md"))
(define (check-fast-enough)
(displayln "Strict mode:")
(parameterize ([current-strict-markdown? #t])
(check-fast-enough*))
(displayln "Non-strict mode (with extensions):")
(parameterize ([current-strict-markdown? #f])
(check-fast-enough*)))
(define (check-fast-enough*)
(define xs (run-times))
(define avg (/ (exact->inexact (apply + xs)) (length xs)))
(define best (apply min xs))
(define worst (apply max xs))
(displayln @~a{Timings: @(string-join (map ~a (sort xs <)) ", ") (sorted)
Average: @avg})
(check-true (< avg 170))
(check-true (< worst 200))
;; Check that best isn't _too_ good. If so, maybe test material
;; accidentally changed?
(check-false (< best 10)))
(define (run-times)
(define test-reps 5)
(define doc-reps 5)
(define doc (let ([s (file->string test.md)])
(string-join (for/list ([i doc-reps])
s)
"\n\n")))
(displayln @~a{Using @test.md
appended @doc-reps times: @(string-length doc) chars and @(length (regexp-split "\n" doc)) lines. Doing @test-reps timings...})
(for/list ([_ test-reps])
(for ([_ 3]) (collect-garbage))
(define-values (_ cpu real gc)
(time-apply parse-markdown (list doc)))
real))
;; We don't know how fast a CI environment will be, and furthermore
;; it could vary on each run. Therefore don't run this test there.
(unless ci-environment?
(check-fast-enough)))
| false |
a85d01e6d73e247b156a12e9e48e3a2fb295fdb0 | 537789710941e25231118476eb2c56ae0b745307 | /ssh/digitama/authentication/publickey.rkt | 13cf0525e4e8391da49dc717337dc978dec9aa27 | []
| no_license | wargrey/lambda-shell | 33d6df40baecdbbd32050d51c0b4d718e96094a9 | ce1feb24abb102dc74f98154ec2a92a3cd02a17e | refs/heads/master | 2023-08-16T22:44:29.151325 | 2023-08-11T05:34:08 | 2023-08-11T05:34:08 | 138,468,042 | 0 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 7,595 | rkt | publickey.rkt | #lang typed/racket/base
;;; https://tools.ietf.org/html/rfc4252#section-7
(provide (all-defined-out))
(require digimon/binscii)
(require "../userauth.rkt")
(require "../message.rkt")
(require "../diagnostics.rkt")
(require "../fsio/pem.rkt")
(require "../fsio/rsa.rkt")
(require "../fsio/authorized-keys.rkt")
(require "../algorithm/fingerprint.rkt")
(require "../algorithm/hostkey/rsa.rkt")
(require "../message/transport.rkt")
(require "../message/authentication.rkt")
(require "../../datatype.rkt")
; `define-ssh-case-messages` requires this because of Racket's phase isolated compilation model
(require (for-syntax "../message/authentication.rkt"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; https://tools.ietf.org/html/rfc4252#section-8
(define-ssh-case-messages SSH-MSG-USERAUTH-REQUEST
[PUBLICKEY #:method 'publickey ([signed? : Boolean #false] [algorithm : Symbol] [key : Bytes]) #:case signed?])
(define-ssh-case-messages SSH-MSG-USERAUTH-REQUEST-PUBLICKEY
[($) #:signed? '#true ([signature : Bytes #""])])
(define-ssh-shared-messages publickey
[SSH_MSG_USERAUTH_PK_OK 60 ([algorithm : Symbol] [key : Bytes])])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-type SSH-Userauth-Private-Key (List Symbol Bytes Path Any))
(struct ssh-publickey-userauth ssh-userauth
([keys : (Option (Listof SSH-Userauth-Private-Key))])
#:type-name SSH-Publickey-Userauth)
(define make-ssh-publickey-userauth : SSH-Userauth-Constructor
(lambda [name server?]
(ssh-publickey-userauth (super-ssh-userauth #:name name
#:request ssh-publickey-request
#:response ssh-publickey-response)
#false)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define ssh-publickey-request : SSH-Userauth-Request
(lambda [self username service response session]
(with-asserts ([self ssh-publickey-userauth?])
(define publickey-okay? (or (eq? response #true) (ssh:msg:userauth:pk:ok? response)))
(define prev-keys : (Option (Listof SSH-Userauth-Private-Key)) (ssh-publickey-userauth-keys self))
(define rest-keys : (Listof SSH-Userauth-Private-Key)
(cond [(and publickey-okay?) (or prev-keys null)]
[(pair? prev-keys) (cdr prev-keys)]
[(null? prev-keys) null]
[else (ssh-filter-keys (read-directory-private-keys))]))
(cond [(null? rest-keys) (values self #false)]
[else (values (if (eq? prev-keys rest-keys) self (struct-copy ssh-publickey-userauth self [keys rest-keys]))
(let-values ([(type pubkey src) (values (caar rest-keys) (cadar rest-keys) (caddar rest-keys))])
(if (not publickey-okay?)
(and (ssh-log-message 'debug "try public key: ~a ~a" src (ssh-fingerprint type pubkey))
(make-ssh:msg:userauth:request:publickey #:username username #:service service #:algorithm type #:key pubkey))
(let* ([key (cadddr (car rest-keys))]
[pre-request (make-ssh:msg:userauth:request:publickey$ #:username username #:service service #:algorithm type #:key pubkey)]
[message (ssh-signature-message session pre-request)])
(define signature : Bytes
(cond [(rsa-private-key? key) (rsa-make-signature key message)]
[else #| dead code |# #""]))
(define-values (sign-algname sigoff) (ssh-bytes->name signature))
(ssh-log-message 'debug "~a is accepted, use '~a' to sign and send public key: ~a" src sign-algname (ssh-fingerprint type pubkey))
(struct-copy ssh:msg:userauth:request:publickey$ pre-request
[signature signature])))))]))))
(define ssh-publickey-response : SSH-Userauth-Response
(lambda [self request username service session]
(with-handlers ([exn:fail:filesystem? (λ _ (make-ssh:msg:disconnect #:reason 'SSH-DISCONNECT-ILLEGAL-USER-NAME))])
(define authorized-keys : (Option (Immutable-HashTable Symbol (Listof SSH-Authorized-Key)))
(let ([.authorized-keys (build-path (expand-user-path (format "~~~a/.ssh/authorized_keys" username)))])
(and (file-exists? .authorized-keys)
(read-authorized-keys* .authorized-keys))))
(and authorized-keys
(ssh:msg:userauth:request:publickey? request)
(let* ([keytype (ssh:msg:userauth:request:publickey-algorithm request)]
[rawkey (ssh:msg:userauth:request:publickey-key request)]
[athkey (authorized-key-ref authorized-keys keytype rawkey)])
(and (ssh-authorized-key? athkey)
(if (not (ssh:msg:userauth:request:publickey$? request))
(and (ssh-log-message 'debug "accepted ~a, continue to verify" (ssh-fingerprint keytype rawkey))
(make-ssh:msg:userauth:pk:ok #:algorithm keytype #:key rawkey))
(let*-values ([(message) (ssh-signature-message session request)]
[(signature) (ssh:msg:userauth:request:publickey$-signature request)]
[(sigalg-name sigoff) (rsa-bytes-signature-info signature)])
(and (case sigalg-name
[(ssh-rsa rsa-sha2-256)
(let-values ([(pubkey) (rsa-bytes->public-key (ssh-authorized-key-raw athkey))])
(and (eq? keytype ssh-rsa-keyname)
(ssh-rsa-verify pubkey message signature sigoff sigalg-name)
(ssh-log-message 'debug "verified ~a, signed with '~a'" (ssh-fingerprint keytype rawkey) sigalg-name)))]
[else #false])
(or (ssh-authorized-key-options athkey) #true))))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define ssh-signature-message : (-> Bytes SSH-MSG-USERAUTH-REQUEST-PUBLICKEY Bytes)
(lambda [session message]
(bytes-append (ssh-bstring->bytes session) (ssh:msg:userauth:request:publickey->bytes message))))
(define ssh-fingerprint : (-> Symbol Bytes String)
(lambda [type key]
(ssh-key-fingerprint type key #:hash sha256-bytes #:digest base64-encode)))
(define ssh-filter-keys : (-> (Listof PEM-Key) (Listof SSH-Userauth-Private-Key))
(lambda [private-keys]
(let select-keys ([all-keys : (Listof PEM-Key) (read-directory-private-keys)]
[syek : (Listof SSH-Userauth-Private-Key) null])
(cond [(null? all-keys) (reverse syek)]
[else (case (pem-key-type (car all-keys))
[(|RSA PRIVATE KEY|)
(define key : RSA-Private-Key (unsafe-bytes->rsa-private-key* (pem-key-raw (car all-keys))))
(select-keys (cdr all-keys)
(cons (list ssh-rsa-keyname (rsa-make-public-key key) (pem-key-src (car all-keys)) key) syek))]
[else (select-keys (cdr all-keys) syek)])]))))
| false |
f48d332b392b88eff23f97ca4870e8b04625aa5b | bb6ddf239800c00988a29263947f9dc2b03b0a22 | /tests/exercise-2.1-test.rkt | b7a30f41ada38d7c69c6bb3b13eff6e2047d404e | []
| no_license | aboots/EOPL-Exercises | f81b5965f3b17f52557ffe97c0e0a9e40ec7b5b0 | 11667f1e84a1a3e300c2182630b56db3e3d9246a | refs/heads/master | 2022-05-31T21:29:23.752438 | 2018-10-05T06:38:55 | 2018-10-05T06:38:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 883 | rkt | exercise-2.1-test.rkt | #lang racket/base
(require rackunit)
(require "../solutions/exercise-2.1.rkt")
(define (is-natural n expected)
(if (zero? expected)
(is-zero? n)
(and (not (is-zero? n))
(is-natural (predecessor n) (- expected 1)))))
(define-binary-check (check-natural is-natural actual expected))
(define (from-integer-helper base n)
(if (zero? n)
base
(from-integer-helper (successor base) (- n 1))))
(define (from-integer n)
(from-integer-helper (zero) n))
(for ([i 100])
(check-natural (from-integer i) i))
(check-natural (factorial (from-integer 0)) 1)
(check-natural (factorial (from-integer 1)) 1)
(check-natural (factorial (from-integer 2)) 2)
(check-natural (factorial (from-integer 3)) 6)
(check-natural (factorial (from-integer 4)) 24)
(check-natural (factorial (from-integer 5)) 120)
(check-natural (factorial (from-integer 10)) 3628800)
| false |
56c9009376ab238c1b2697aa2c9edf1ef26300bf | fc90b5a3938850c61bdd83719a1d90270752c0bb | /web-server-lib/web-server/formlets/input.rkt | 5ae17597badbea74534b1f8bb6756e097fc28785 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | racket/web-server | cccdf9b26d7b908701d7d05568dc6ed3ae9e705b | e321f8425e539d22412d4f7763532b3f3a65c95e | refs/heads/master | 2023-08-21T18:55:50.892735 | 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 | 6,749 | rkt | input.rkt | #lang racket/base
(require racket/contract
"unsafe/input.rkt"
web-server/http
web-server/private/xexpr
(submod "lib.rkt" private)
(only-in "lib.rkt"
xexpr-forest/c
formlet/c
pure
cross))
(provide (contract-out ; Low-level
[make-input* (-> (-> string? pretty-xexpr/c)
(serial-formlet/c (listof binding?)))]
[make-input (-> (-> string? pretty-xexpr/c)
(serial-formlet/c (or/c false/c binding?)))]
; HTML Spec
[input (->* ()
(#:type string?
#:value (or/c false/c bytes? string?)
#:max-length (or/c false/c exact-nonnegative-integer?)
#:read-only? boolean?
#:attributes (listof (list/c symbol? string?)))
(serial-formlet/c (or/c false/c binding?)))]
[text-input (->* ()
(#:value (or/c false/c bytes? string?)
#:size (or/c false/c exact-nonnegative-integer?)
#:max-length (or/c false/c exact-nonnegative-integer?)
#:read-only? boolean?
#:attributes (listof (list/c symbol? string?)))
(serial-formlet/c (or/c false/c binding?)))]
[password-input (->* ()
(#:value (or/c false/c bytes? string?)
#:size (or/c false/c exact-nonnegative-integer?)
#:max-length (or/c false/c exact-nonnegative-integer?)
#:read-only? boolean?
#:attributes (listof (list/c symbol? string?)))
(serial-formlet/c (or/c false/c binding?)))]
[checkbox (->* ((or/c bytes? string?) boolean?)
(#:attributes (listof (list/c symbol? string?)))
(serial-formlet/c (or/c false/c binding?)))]
[radio (->* ((or/c bytes? string?) boolean?)
(#:attributes (listof (list/c symbol? string?)))
(serial-formlet/c (or/c false/c binding?)))]
[radio-group (->* (sequence?)
(#:attributes
(-> any/c (listof (list/c symbol? string?)))
#:checked? (any/c . -> . boolean?)
#:display (any/c . -> . pretty-xexpr/c)
#:wrap (any/c any/c . -> . xexpr-forest/c))
(serial-formlet/c any/c))]
[checkbox-group (->* (sequence?)
(#:attributes
(-> any/c (listof (list/c symbol? string?)))
#:checked? (any/c . -> . boolean?)
#:display (any/c . -> . pretty-xexpr/c)
#:wrap (any/c any/c . -> . xexpr-forest/c))
(serial-formlet/c (listof any/c)))]
[submit (->* ((or/c bytes? string?))
(#:attributes (listof (list/c symbol? string?)))
(serial-formlet/c (or/c false/c binding?)))]
[reset (->* ((or/c bytes? string?))
(#:attributes (listof (list/c symbol? string?)))
(serial-formlet/c (or/c false/c binding?)))]
[file-upload (->* ()
(#:attributes (listof (list/c symbol? string?)))
(serial-formlet/c (or/c false/c binding?)))]
[hidden (->* ((or/c bytes? string?))
(#:attributes (listof (list/c symbol? string?)))
(serial-formlet/c (or/c false/c binding?)))]
[img (->* ((or/c bytes? string?) (or/c bytes? string?))
(#:height (or/c false/c exact-nonnegative-integer?)
#:longdesc (or/c false/c (or/c bytes? string?))
#:usemap (or/c false/c (or/c bytes? string?))
#:width (or/c false/c exact-nonnegative-integer?)
#:attributes (listof (list/c symbol? string?)))
(serial-formlet/c (or/c false/c binding?)))]
[button (->* ((or/c bytes? string?) (or/c bytes? string?))
(#:disabled
boolean?
#:value (or/c false/c (or/c bytes? string?))
#:attributes (listof (list/c symbol? string?)))
(serial-formlet/c (or/c false/c binding?)))]
[multiselect-input (->* (sequence?)
(#:attributes
(listof (list/c symbol? string?))
#:multiple? boolean?
#:selected? (any/c . -> . boolean?)
#:display (any/c . -> . pretty-xexpr/c))
(serial-formlet/c (listof any/c)))]
[select-input (->* (sequence?)
(#:attributes
(listof (list/c symbol? string?))
#:selected? (any/c . -> . boolean?)
#:display (any/c . -> . pretty-xexpr/c))
(serial-formlet/c any/c))]
[textarea-input (->* ()
(#:attributes
(listof (list/c symbol? string?))
#:value (or/c false/c (or/c bytes? string?))
#:rows number?
#:cols number?)
(serial-formlet/c (or/c false/c binding?)))]
; High-level
[required (-> (formlet/c (or/c false/c binding?))
(serial-formlet/c bytes?))]
[default (-> bytes? (formlet/c (or/c false/c binding?))
(serial-formlet/c bytes?))]
[to-string (-> (formlet/c bytes?)
(serial-formlet/c string?))]
[to-number (-> (formlet/c string?)
(serial-formlet/c number?))]
[to-symbol (-> (formlet/c string?)
(serial-formlet/c symbol?))]
[to-boolean (-> (formlet/c bytes?)
(serial-formlet/c boolean?))]
;OLD
[input-string (serial-formlet/c string?)]
[input-int (serial-formlet/c number?)]
[input-symbol (serial-formlet/c symbol?)]))
| false |
b235830f099c3a7c3edf09605a6aebb1fd0786f4 | fbda1aab364cb9139b8e640d035611bfafebb511 | /scheme/build.rkt | 1b367987b0edc354939a0bf60577d58e9f8dd550 | []
| no_license | nahyde/course-latex | 976c38d47e2e93f2c5808393abb81b89bb2758b3 | ca08156868cd36c9a60ba7086b98db5dd6e5d25e | refs/heads/master | 2020-12-24T11:53:38.711830 | 2016-03-22T03:19:04 | 2016-03-22T03:19:04 | 50,130,596 | 0 | 0 | null | 2016-01-21T19:17:05 | 2016-01-21T19:17:05 | null | UTF-8 | Racket | false | false | 3,179 | rkt | build.rkt | #lang racket
(require preprocessor/mztext
preprocessor/pp-run
slatex/slatex-wrapper)
(require "env.rkt" "util.rkt")
(provide (all-defined-out))
(define web-directory (or (getenv "WEB_DIR") (format "~a/web" course-dir)))
(define output-dir (make-parameter (current-directory)))
(define file-name (make-parameter #f))
(define output-to-web (make-parameter #f))
(define output-umask (make-parameter #o007))
(define password-protect (make-parameter #f))
;; Compile the tex file file into a PDF
(define (build-tex-file name-with-mode)
(parameterize ([current-output-port (open-output-file (format "~a/~a.pdf" (output-dir) name-with-mode) #:exists 'replace)]
[current-input-port (open-input-file (format "~a.tex" name-with-mode))])
(conditional-pipe
;; Use pdftk if we need to password protect this PDF
[(password-protect) "pdftk" "-" "output" "-" "user_pw" (password-protect)]
;; Run rubber-pipe on our tex file
[#t "rubber-pipe" "--pdf" "-e" "set program pdflatex" "--texpath" latex-root "--texpath" (string-append course-dir "/latex")])))
(define (run-build doc-dir main-name doc-name mode-eval-string name-with-mode)
(define build-error (make-parameter #f))
(define name-with-mode.tex (string-append name-with-mode ".tex"))
(define doc.tex.mz main-name)
(with-cwd doc-dir
(unless (file-exists? doc.tex.mz)
(error (format "MZ file (~a) doesn't exist in directory ~a." doc.tex.mz (current-directory))))
(when (file-exists? name-with-mode.tex)
(error (format "The file ~a already exists; please delete it and run again." name-with-mode.tex)))
(with-handlers ([exn:fail? build-error])
;; Use mztext to process the file.
(with-umask #o007 ; We restrict the umask first to be safe.
(parameterize ([read-case-sensitive #t]
[current-directory doc-dir])
(add-eval (read-syntax 'command-line (open-input-string mode-eval-string)))
(add-eval (read-syntax 'command-line (open-input-string course-eval-string)))
(add-eval (read-syntax 'command-line (open-input-string cs-eval-string)))
(add-eval `(define name-with-mode ,name-with-mode))
(with-output-to-file name-with-mode.tex #:exists 'replace
(lambda () (preprocess doc.tex.mz)))))
;; Now run slatex on the generated tex file
(slatex/no-latex name-with-mode.tex)
;; We've finished preprocessing the tex file. Make the PDF.
(with-umask (output-umask)
(build-tex-file name-with-mode)))
;; Cleanup: hide the tex file, and delete rubber's temporary files
(rename-file-or-directory name-with-mode.tex (string-append "." name-with-mode.tex) #t)
(let ([rubtmp-files (find-files (lambda (pth) (regexp-match "^rubtmp*" pth)))])
(when (cons? rubtmp-files)
(make-directory* "build_files")
(map (lambda (pth) (rename-file-or-directory pth (build-path "build_files/" pth) #t)) rubtmp-files)))
(when (build-error)
(raise (build-error)))
(void)))
| false |
ba14ca281ae551d14fdfb5eafdded0b29886cb5b | f05fb2cbe45417a0017c71320608d6454681d077 | /quadwriter/string.rkt | 67e1d4ec95a37c34f4817056975243330aad7fd3 | [
"MIT"
]
| permissive | mbutterick/quad | dcca8d99aaacaea274d3636e9f02e75251664d9c | 9c6e450b0429ad535edf9480a4b76e5c23161ec0 | refs/heads/master | 2022-02-01T17:44:32.904785 | 2022-01-08T15:52:50 | 2022-01-08T15:52:50 | 26,788,024 | 142 | 9 | MIT | 2020-07-07T01:54:00 | 2014-11-18T02:21:39 | Racket | UTF-8 | Racket | false | false | 5,374 | rkt | string.rkt | #lang debug racket
(require "struct.rkt"
"font.rkt"
"attrs.rkt"
"param.rkt"
"debug.rkt"
quad/quad
quad/atomize
pitfall
quad/position
racket/unsafe/ops)
(provide (all-defined-out))
(define (convert-string-quad q)
;; need to handle casing here so that it's reflected in subsequent sizing ops
(define cased-str (match (quad-elems q)
[(cons str _)
(define proc (match (quad-ref q :font-case)
[(or "upper" "uppercase") string-upcase]
[(or "lower" "lowercase" "down" "downcase") string-downcase]
[(or "title" "titlecase") string-titlecase]
[_ values]))
(proc str)]
[_ ""])) ; a string quad should always contain a string
(quad-copy string-quad q:string
[attrs (let ([attrs (quad-attrs q)])
(hash-ref! attrs :font-size default-font-size)
attrs)]
[elems (list cased-str)]
[size (make-size-promise-for-string q cased-str)]))
(define soft-hyphen-string "\u00AD")
(define (make-size-promise-for-string q [str-arg #f])
;; we know sensible defaults for all text properties have been set up during atomization.
(delay
(define q-string-width
(let ([str (cond
[str-arg]
[else (match (quad-elems q)
[(cons q _) q]
[_ #false])])])
(cond
[(positive? (string-length str))
(define pdf (current-pdf))
(font-size pdf (quad-ref q :font-size))
(font pdf (path->string (quad-ref q font-path-key)))
(define tracking-val (quad-ref q :font-tracking 0))
(cond
[(equal? str soft-hyphen-string) tracking-val]
[else ;; `string-width` only applies tracking between glyphs.
;; we add an extra tracking-val because we want to count tracking on every glyph.
;; because at this stage, we don't know whether the quad will be freestanding or adjacent to another
;; probably adjacent. And if so, it should have half tracking on the ends, full tracking in between
(+ (string-width pdf str
#:tracking tracking-val
#:features (quad-ref q :font-features))
tracking-val)])]
[else 0])))
(list q-string-width (quad-ref q :line-height))))
(define (q:string-draw q doc
#:origin [origin-in #f]
#:text [str-in #f])
(match (or str-in (and (pair? (quad-elems q)) (unsafe-car (quad-elems q))))
[#false (void)]
[str
(font doc (path->string (quad-ref q font-path-key default-font-face)))
(font-size doc (quad-ref q :font-size default-font-size))
(fill-color doc (quad-ref q :font-color default-font-color))
(match-define (list x y) (or origin-in (quad-origin q)))
(define tracking (quad-ref q :font-tracking 0))
;; we adjust x by half tracking because by convention, string quads have half tracking at beginning & end
;; whereas PDF drawing only puts tracking between the glyphs.
(text doc str (+ x (/ tracking 2.0)) (- y (quad-ref q :font-baseline-shift 0))
#:tracking tracking
#:underline (quad-ref q :font-underline)
#:bg (quad-ref q :bg)
#:features (quad-ref q :font-features default-font-features)
#:link (quad-ref q :link))]))
(define (q:string-draw-end q doc)
(when (draw-debug-string?)
(draw-debug q doc "#99f" "#ccf")))
(define (q:string-printable? q [sig #f])
;; printable unless single space, which is not printable at start or end
(match (quad-elems q)
[(cons elem _)
(case elem
[(" " #\space) (not (memq sig '(start end)))]
[else #true])]
[_ #true]))
(define q:string (q #:type string-quad
#:from 'bo
#:to 'bi
#:tag 'str
#:printable q:string-printable?
#:draw q:string-draw
#:draw-end q:string-draw-end))
(define (consolidate-runs pcs)
(let loop ([runs empty][pcs pcs])
(match pcs
[(cons (? string-quad? strq) rest)
(define-values (run-pcs rest) (splitf-at pcs (λ (p) (same-run? strq p))))
;; run-pcs has at least one element (strq)
;; and the other members are part of the same run.
;; meaning, they share the same formatting, including character tracking.
;; we add a tracking adjustment because it only "appears"
;; once characters are consolidated
(define tracking-adjustment
(* (sub1 (length run-pcs)) (quad-ref (car run-pcs) :font-tracking 0)))
(define new-run
(quad-copy string-quad q:string
[attrs (quad-attrs strq)]
[elems (merge-adjacent-strings (apply append (map quad-elems run-pcs)))]
[size (delay (pt (sum-x run-pcs) (pt-y (size strq))))]))
(loop (cons new-run runs) rest)]
[(cons first rest) (loop (cons first runs) rest)]
[_ (reverse runs)]))) | false |
d70f04f2eb0edc20822305b596065a8dcac9c152 | 51075b127a6678c42f706bf42145a499e66984b8 | /test.rkt | aad3640aafa32e87b2617451239eecf4a243a23a | []
| no_license | zazzerino/set | 72ecb65bc311412ff89d19d16df61d6907f6c41a | eb829568078a3e4e2e5d5c9166742a72e3eae684 | refs/heads/master | 2020-03-18T02:41:15.589726 | 2018-05-22T01:34:06 | 2018-05-22T01:34:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,840 | rkt | test.rkt | #lang racket
(require rackunit
rackunit/text-ui
"prelude.rkt"
"logic.rkt")
(define-test-suite prelude-tests
(test-begin
(def apple 'banana)
(check-equal? apple 'banana)
(def ([cranberry 'dragonfruit]))
(check-equal? cranberry 'dragonfruit)
(def ([e 'frapple]
[grapefruit 'h]))
(check-equal? e 'frapple)
(check-equal? grapefruit 'h)
(def ([i 'jackfruit]
[k 'lemon]
[m 'n]))
(check-equal? i 'jackfruit)
(check-equal? k 'lemon)
(check-equal? m 'n)
(def ([o 'p]
[q 'r]
[s 't]
[u 'v]
[w 'x]))
(check-equal? o 'p)
(check-equal? q 'r)
(check-equal? s 't)
(check-equal? u 'v)
(check-equal? w 'x)
(def (foo bar)
bar)
(check-equal? (foo 'bar) 'bar)
(def (foo* [baz 'baz])
baz)
(check-equal? (foo*) 'baz)))
(define-test-suite logic-tests
(check-equal? (card 'one 'squiggle 'open 'green)
(card 'one 'squiggle 'open 'green))
(check-not-equal? (card 'one 'squiggle 'open 'green)
(card 'one 'squiggle 'open 'purple))
(check-true (= 81 (length (make-deck))))
(check-true (all-equal? '(1 1 1)))
(check-false (all-equal? '(1 2 3)))
(check-true (all-equal? (list (card 'two 'oval 'striped 'red)
(card 'two 'oval 'striped 'red))))
(check-false (all-equal? (list (card 'two 'oval 'striped 'red)
(card 'two 'diamond 'striped 'red))))
(check-true (all-distinct? '(1 2 3 0)))
(check-false (all-distinct? '(1 2 3 2)))
(check-true (all-distinct? (list (card 'two 'oval 'striped 'red)
(card 'two 'oval 'striped 'green))))
(check-false (all-distinct? (list (card 'two 'oval 'striped 'red)
(card 'two 'oval 'striped 'red))))
(check-true (potential-set? (list (card 'two 'oval 'striped 'red)
(card 'two 'oval 'striped 'green))))
(check-false (makes-set? (list (card 'two 'oval 'striped 'red)
(card 'two 'oval 'striped 'green))))
(check-true (makes-set? (list (card 'two 'oval 'striped 'red)
(card 'two 'oval 'striped 'green)
(card 'two 'oval 'striped 'purple))))
(check-true (makes-set? (list (card 'one 'squiggle 'striped 'red)
(card 'two 'oval 'solid 'green)
(card 'three 'diamond 'open 'purple))))
(check-false (makes-set? (list (card 'three 'oval 'striped 'red)
(card 'two 'oval 'striped 'green)
(card 'two 'oval 'striped 'purple)))))
(run-tests prelude-tests)
(run-tests logic-tests)
| false |
5db05ac8239add8189bebf80e164629e5fd1195a | 88790b3a7b326f506de7c7e3c4c1a8ff20f184bc | /huffman.rkt | 599c91473e5c0cecf78de0268fae1ae89c2b6cb2 | []
| no_license | ndpar/algorithms | 738bc3d2a20c240c63860e382dbd3610aee3b4c0 | 729400161c0d0fffd19eab9bb8140a3e1213c3b7 | refs/heads/master | 2021-01-23T15:15:12.978658 | 2014-12-04T01:01:10 | 2014-12-04T01:01:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 3,117 | rkt | huffman.rkt | #lang racket
;; -------------------------------------------------------------------
;; Huffman Encoding Trees
;; Adapted from SICP, chapter 2.3.4
;; https://github.com/CompSciCabal/SMRTYPRTY/blob/master/sicp/chapter-2.3/ndpar-2.3.4.scm
;; -------------------------------------------------------------------
;; Tree representation
(struct leaf (symbol weight) #:transparent)
(struct tree (left right symbols weight) #:transparent)
;; Generic procedures
(define (make-tree left right)
(tree left
right
(append (symbols left) (symbols right))
(+ (weight left) (weight right))))
(define (symbols node)
(if (leaf? node)
(list (leaf-symbol node))
(tree-symbols node)))
(define (weight node)
(if (leaf? node)
(leaf-weight node)
(tree-weight node)))
;; Building Huffman trees
(require (prefix-in h: data/heap))
(define ((& f g) x y) ; J compose
(f (g x) (g y)))
(define-syntax-rule (while test body ...)
(let loop () (when test body ... (loop))))
(define (leaves->huffman-tree leaves)
(define (pop! heap)
(let ([min (h:heap-min heap)]) (h:heap-remove-min! heap) min))
(let ([heap (h:make-heap (& <= weight))])
(h:heap-add-all! heap leaves)
(while (< 1 (h:heap-count heap))
(h:heap-add! heap (make-tree (pop! heap) (pop! heap))))
(h:heap-min heap)))
(define (map-apply f lists)
(map (curry apply f) lists))
(define (make-huffman-tree frequencies)
(leaves->huffman-tree (map-apply leaf frequencies)))
(define sample-tree
(make-huffman-tree '((A 4) (B 2) (D 1) (C 1))))
(module+ test
(require rackunit)
(check-equal?
sample-tree
(tree (leaf 'A 4) (tree (leaf 'B 2) (tree (leaf 'D 1) (leaf 'C 1) '(D C) 2) '(B D C) 4) '(A B D C) 8)))
;; Decoding messages
(define (decode tree bits)
(define (choose-branch bit branch)
(cond [(= 0 bit) (tree-left branch)]
[(= 1 bit) (tree-right branch)]
[else (error "Bad bit" bit)]))
(let iter ([bits bits] [current-branch tree])
(if (null? bits)
'()
(let ([next-branch (choose-branch (car bits) current-branch)])
(if (leaf? next-branch)
(cons (leaf-symbol next-branch)
(iter (cdr bits) tree))
(iter (cdr bits) next-branch))))))
;; Encoding messages
(define (encode tree message)
(append-map (curry encode-symbol tree) message))
(define (encode-symbol tree symbol)
(let iter ([result '()] [tree tree])
(if (leaf? tree)
(if (eq? symbol (leaf-symbol tree))
(reverse result)
(error "Unknown symbol" symbol))
; If the symbol is not in the left branch
; it has to be in the right one by tree construction
(if (member symbol (symbols (tree-left tree)))
(iter (cons 0 result) (tree-left tree))
(iter (cons 1 result) (tree-right tree))))))
;; Tests
(define sample-message '(A D A B B C A))
(define sample-bits '(0 1 1 0 0 1 0 1 0 1 1 1 0))
(module+ test
(check-equal? (decode sample-tree sample-bits) sample-message)
(check-equal? (encode sample-tree sample-message) sample-bits))
| true |
ea2dfff55bce2a9bb287d0f1a5fe9b3be5ca69d9 | 08287ef90c557186d1a1b7c0beec138715fc45f9 | /fold-map.rkt | 7fb687886c161f98793a4cce24aa94ac8fdcd288 | []
| no_license | zach-youssef/fold-map.rkt | baa9ae9d2c8d36b04e33b170fe5a82b9ce875e8a | bf967dbb7582582459d648e012d1674bd3de2ee2 | refs/heads/master | 2021-08-22T11:36:00.644392 | 2017-11-30T04:36:18 | 2017-11-30T04:36:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 772 | rkt | fold-map.rkt | #lang racket
(require (for-syntax racket/match))
(require (for-syntax racket/list))
(provide foldmapr foldmapl)
(define-syntax (foldmapr stx)
(define crunch
(λ [foldr base map lst]
(cond [(empty? lst) base]
[(cons? lst) (foldr (map (car lst)) (crunch foldr base map (cdr lst)))])))
(match (syntax->list stx) [(list fmr f-f f-b m-f lst)
(datum->syntax stx `(,crunch ,f-f ,f-b ,m-f ,lst))]))
(define-syntax (foldmapl stx)
(define (chomp foldl base map lst)
(cond
[(empty? lst) base]
[(cons? lst) (chomp foldl (foldl (map (first lst)) base) map (rest lst))]))
(match (syntax->list stx) [(list fml f-f f-b m-f lst)
(datum->syntax stx `(,chomp ,f-f ,f-b ,m-f ,lst))])) | true |
dc9e56fe2100426030aeb159319bc372aa48ab73 | 5ed81c867532c430ab594079611412350008bc79 | /Semantics/SizedOps.rkt | 7d6bae69b4a638127cfc84fbe3263c362287287e | []
| no_license | atgeller/WASM-Redex | cab2297bca992102eb6a8ed63e51584e7cdc6b02 | 81f882f9fd95b645a10baf2565f27efc8f8766e5 | refs/heads/canon | 2021-07-07T23:44:39.346526 | 2021-03-10T01:30:09 | 2021-03-10T01:30:09 | 232,643,084 | 21 | 2 | null | 2021-03-05T23:07:24 | 2020-01-08T19:35:12 | Racket | UTF-8 | Racket | false | false | 2,189 | rkt | SizedOps.rkt | #lang racket
(provide (all-defined-out))
; Racket functions to handle all of the signed and unsigned integer operations on integers of a particular size
(define (to-unsigned-sized size x)
(modulo x (expt 2 size)))
(define (to-signed-sized size x)
(let ([unsigned (to-unsigned-sized size x)])
(if (< unsigned (expt 2 (sub1 size)))
unsigned
(- unsigned (expt 2 size)))))
(define (sized-add size n1 n2)
(to-unsigned-sized size (+ n1 n2)))
(define (sized-mul size n1 n2)
(to-unsigned-sized size (* n1 n2)))
(define (sized-sub size n1 n2)
(to-unsigned-sized size (- n1 n2)))
(define (sized-unsigned-div size n1 n2)
(to-unsigned-sized size (quotient n1 n2)))
(define (sized-signed-div size n1 n2)
(to-unsigned-sized size (quotient n1 (to-signed-sized size n2))))
(define (sized-unsigned-rem size n1 n2)
(to-unsigned-sized size (modulo n1 n2)))
(define (sized-signed-rem size n1 n2)
(to-unsigned-sized size (modulo n1 (to-signed-sized size n2))))
(define (sized-shl size n1 n2)
(to-unsigned-sized size (arithmetic-shift n1 n2)))
(define (sized-unsigned-shr size n1 n2)
(to-unsigned-sized size (arithmetic-shift n1 (- n2))))
(define (sized-signed-shr size n1 n2)
(to-unsigned-sized size (arithmetic-shift (to-signed-sized size n1) (- n2))))
(define (sized-rotl size n1 n2)
(to-unsigned-sized size (bitwise-ior (arithmetic-shift n1 (modulo n2 size))
(arithmetic-shift n1 (- (modulo n2 size) size)))))
(define (sized-rotr size n1 n2)
(to-unsigned-sized size (bitwise-ior (arithmetic-shift n1 (- (modulo n2 size)))
(arithmetic-shift n1 (- size (modulo n2 size))))))
(define (sized-clz size n)
(cond
[(= size 0) 0]
[(>= n (expt 2 (sub1 size))) 0]
[else (add1 (sized-clz (sub1 size) n))]))
(define (sized-ctz size n)
(cond
[(= size 0) 0]
[(= 1 (modulo n 2)) 0]
[else (add1 (sized-ctz (sub1 size) (arithmetic-shift n -1)))]))
(define (sized-popcnt size n)
(cond
[(= size 0) 0]
[(>= n (expt 2 (sub1 size)))
(add1 (sized-popcnt (sub1 size) (- n (expt 2 (sub1 size)))))]
[else
(sized-popcnt (sub1 size) n)]))
| false |
b083539c176485093af84fc309546bd3e46fb8a3 | 6359e6a83c6e867c7ec4ee97c5b4215fe6867fdf | /survival-minecraft/examples.rkt | 41c5755e0a668d0992e5078d1696452f53582dd4 | []
| no_license | thoughtstem/TS-GE-Languages | 629cba7d38775f4b636b328dfe8297cd79b5e787 | 49a8ad283230e5bcc38d583056271876c5d6556e | refs/heads/master | 2020-04-13T21:22:38.618374 | 2020-02-03T22:44:30 | 2020-02-03T22:44:30 | 163,454,521 | 3 | 0 | null | 2020-02-03T22:44:32 | 2018-12-28T22:28:18 | Racket | UTF-8 | Racket | false | false | 6,398 | rkt | examples.rkt | #lang racket
(require ts-kata-util
"./lang/main.rkt"
;"./assets.rkt"
)
(define-example-code/from* survival/examples)
;=================================
(define-example-code
;#:with-test (test game-test)
survival-minecraft alt/avatar-2
(minecraft-game
#:skin (basic-skin #:sprite alex-sprite)))
(define-example-code
;#:with-test (test game-test)
survival-minecraft alt/avatar-3
(define (my-hero)
(basic-skin #:sprite monk-sprite))
(minecraft-game
#:skin (reduce-quality-by 3 (my-hero))))
(define-example-code
;#:with-test (test game-test)
survival-minecraft alt/avatar-4
(define (my-hero)
(basic-skin #:sprite alex-sprite
#:speed 20))
(minecraft-game
#:skin (my-hero)))
(define-example-code
;#:with-test (test game-test)
survival-minecraft alt/avatar-5
(define (my-hero)
(basic-skin #:sprite alex-sprite
#:speed 20
#:key-mode 'wasd))
(minecraft-game
#:skin (my-hero)))
(define-example-code
;#:with-test (test game-test)
survival-minecraft avatar-6
(define (my-hero)
(basic-skin
#:sprite pig-sprite
#:speed 20
#:key-mode 'wasd
#:health 200
#:max-health 200))
(minecraft-game #:skin (my-hero)))
;======================================================
(define-example-code
;#:with-test (test game-test)
survival-minecraft alt/enemy-3
(define (my-mob)
(basic-mob #:ai 'medium
#:sprite skeleton-sprite
#:amount-in-world 5))
(minecraft-game
#:mob-list (list (my-mob)))
)
(define-example-code
;#:with-test (test game-test)
survival-minecraft alt/enemy-4
(define (easy-mob)
(basic-mob #:ai 'easy
#:sprite creeper-sprite
#:amount-in-world 5))
(define (medium-mob)
(basic-mob #:ai 'medium
#:sprite skeleton-sprite
#:amount-in-world 5
#:night-only? #t))
(minecraft-game
#:mob-list (list (easy-mob) (medium-mob)))
)
(define-example-code
;#:with-test (test game-test)
survival-minecraft alt/enemy-5
(define (medium-mob)
(basic-mob #:ai 'medium
#:sprite skeleton-sprite
#:amount-in-world 3
))
(define (hard-mob)
(basic-mob #:ai 'hard
#:sprite ghast-sprite
#:amount-in-world 5
#:night-only? #t
#:weapon (fireball #:damage 50)))
(minecraft-game
#:mob-list (list (medium-mob)
(hard-mob)))
)
(define-example-code
;#:with-test (test game-test)
survival-minecraft alt/enemy-6
(define (hard-mob)
(basic-mob #:ai 'hard
#:sprite ghast-sprite
#:amount-in-world 5
#:weapon (acid-spitter #:damage 50)))
(minecraft-game
#:mob-list (list (hard-mob)))
)
;=============================================
(define-example-code
;#:with-test (test game-test)
survival-minecraft alt/coin-2
(minecraft-game
#:ore-list (list (basic-ore #:value 50)))
)
(define-example-code
;#:with-test (test game-test)
survival-minecraft alt/coin-3
(define (my-ore)
(basic-ore #:sprite goldore-sprite
#:name "Gold Ore"
#:value 200
#:amount-in-world 20))
(minecraft-game
#:ore-list (list (my-ore)))
)
(define-example-code
;#:with-test (test game-test)
survival-minecraft alt/coin-4
(define (gold-ore)
(basic-ore #:sprite goldore-sprite
#:name "Gold Ore"))
(define (diamond)
(basic-ore #:sprite diamond-sprite
#:name "Diamond"
#:value 1000
#:amount-in-world 1
#:respawn? #f))
(minecraft-game
#:ore-list (list (gold-ore)
(diamond)))
)
(define-example-code
;#:with-test (test game-test)
survival-minecraft alt/coin-5
(define (diamond)
(basic-ore #:sprite diamond-sprite
#:name "Diamond"
#:value 500
#:amount-in-world 5))
(define (mesecrystal)
(basic-ore #:sprite mesecrystal-sprite
#:name "Mese Crystal"
#:value 1000
#:amount-in-world 1
#:respawn? #f))
(minecraft-game
#:ore-list (list (diamond)
(mesecrystal)))
)
;=========================================================
#;(define-example-code
;#:with-test (test game-test)
survival-minecraft alt/npc-2
(define (my-entity)
(basic-entity
#:sprite pig-sprite
#:name "Miss Piggy"))
(minecraft-game
#:entity-list (list (my-entity))))
(define-example-code
;#:with-test (test game-test)
survival-minecraft alt/npc-3
(define (my-entity)
(basic-entity
#:sprite pig-sprite
#:name "Sir Pigsnoot"
#:tile 3
#:mode 'follow))
(minecraft-game
#:entity-list (list (my-entity))))
(define-example-code
;#:with-test (test game-test)
survival-minecraft alt/npc-4
(define (my-entity)
(basic-entity
#:dialog (list "Woah, who are you??"
"Wait, I'm a chicken..."
"I can't talk!")))
(minecraft-game
#:entity-list (list (my-entity))))
(define-example-code
;#:with-test (test game-test)
survival-minecraft alt/npc-5
(define (my-entity)
(basic-entity
#:name "Francis"
#:tile 4
#:dialog (list "Greetings!"
"Gee, you look hungry.")))
(define (another-entity)
(basic-entity
#:sprite chicken-sprite
#:name "Mr. Chick Chickenson III"
#:mode 'pace
#:dialog (list "Woah, who are you??"
"Wait, I'm a chicken..."
"I can't talk!")))
(minecraft-game
#:entity-list (list (my-entity) (another-entity))))
;====================================================
(define-example-code
;#:with-test (test game-test)
survival-minecraft alt/background-4
(define (my-biome)
(basic-biome
#:image LAVA-BG
#:rows 2
#:columns 2
#:start-tile 3
#:hd? #t))
(minecraft-game #:biome (my-biome)))
;====================================================
| false |
ff652661407652cfc5471e7d4cfe3dfe1d6abffa | a6c4b839754b01e1b94a70ec558b631313c9df34 | /generate-stags.ss | e5ae7fe68884092e8dd92c9b579164bea838216c | []
| no_license | dyoo/divascheme | b6a05f625397670b179a51e13d3cd9aac0b2e7d5 | f1a8d82989115e0d0714ce8fdbd452487de12535 | refs/heads/master | 2021-01-17T09:39:14.664809 | 2008-08-19T01:46:33 | 2008-08-19T01:46:33 | 3,205,925 | 0 | 1 | null | 2018-01-22T01:27:19 | 2012-01-18T04:11:36 | Scheme | UTF-8 | Racket | false | false | 787 | ss | generate-stags.ss | #|
Generates an TAGS.scm file suitable for divascheme tags support.
cd plt/collects; find . -name \*.ss | xargs generate-stags
This will create a file called 'STAGS', which can then be used by
divascheme. While in divascheme's command mode, hit '.' It will
prompt for an identifier's name, and then jump to the file and the
line where that name is defined.
Sun Apr 17 2005
Ported to MzScheme 299, based on a patch by Danny Yoo
Sun Nov 2 2003
Written by Guillaume Marceau ([email protected])
|#
(module generate-stags mzscheme
;; TODO: use cmdline
;; TODO: support project directories
(require "stags-lib.ss")
(with-handlers
([exn:break? (lambda (exn) (void))])
(generate-stags-file (vector->list (current-command-line-arguments)) "STAGS"))) | false |
94aecd5072163ee9c5538aadffa3cebec822d94c | d235d45a4793769dccd57413fc3e2a5ce029588c | /private/tv.rkt | ecbe7bed8a40f82edd4c31e978a74b13325764d5 | []
| no_license | rmculpepper/racket-mpict | 2199ac91e2776e64e70962a9bbdf162d81a97886 | b9e23850a3e40f267712d79985e0551c1a324ff2 | refs/heads/master | 2020-07-13T21:54:20.516674 | 2019-09-13T14:05:23 | 2019-09-13T14:05:23 | 205,162,985 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 9,476 | rkt | tv.rkt | #lang racket/base
(require (for-syntax racket/base syntax/parse syntax/transformer)
racket/match
racket/list
racket/stxparam)
(provide (except-out (all-defined-out) tv:app)
(rename-out [tv:app #%app]))
;; Idea: instead of escaping via define/unlifted, add frame annotations (cf Remora)?
;; Are there inner vs outer frame constraints?
;; fadeout : Smooth -> _
;; get0 : * -> _
;; // : * * -> _
;; share : Smooth -> _
;; cshadow : ???
;; autoinset : * -> * --- auto determines biggest bounding box (assumes Smooth max is at endpoint)
;; What would I even *expect* from (fadeout (// A B)), though?
;; A UReal is a Real in the range [0,1].
;; A NNReal is a Real >= 0.
;; ============================================================
;; An AnimatedValue[X] is one of
;; - X -- constant
;; - (av NNReal (UReal -> X) X X) -- animated for duration, then constant
(struct av (dur f v0 v1))
(define FTime (av 1 values 0 1))
(define RTime (av 1 (lambda (u) (- 1 u)) 1 0))
(define current-Time (make-parameter FTime))
(define-syntax Time (make-variable-like-transformer #'(current-Time)))
(define-syntax-parameter agravity (quote-syntax 'left)) ;; one of 'left, 'right, 'stretch
(define (-dur v)
(match v
[(? dv?) (error '-dur "expected smooth value, got: ~e" v)]
[(av dur _ _ _) dur]
[_ 0]))
;; avapply : (X ... -> Y) (List AnimatedValue[X] ...) -> AnimatedValue[Y]
(define (avapply f args)
(cond [(ormap av? args)
(define dur* (apply max (map -dur args)))
(define args* (map (lambda (a) (-timeclip dur* a)) args))
(av dur*
(lambda (u)
(parameterize ((current-Time u))
(apply f (for/list ([arg (in-list args*)]) (-get u arg)))))
(apply f (map -getA args*))
(apply f (map -getZ args*)))]
[else (apply f args)]))
;; avapp{1,2,N} : (X ... -> Y) TimedValue[X] ... -> TimedValue[Y]
(define (avapp1 f arg)
(match arg
[(av dur argf v0 v1)
(av dur (lambda (u) (f (argf u))) (f v0) (f v1))]
[v (f v)]))
(define (avapp2 f arg1 arg2)
(cond [(or (av? arg1) (av? arg2))
(define dur* (max (-dur arg1) (-dur arg2)))
(define arg1* (-timeclip dur* arg1))
(define arg2* (-timeclip dur* arg2))
(av (lambda (u) (f (-get u arg1*) (-get u arg2*)))
(f (-getA arg1*) (-getA arg2*))
(f (-getZ arg1*) (-getZ arg2*)))]
[else (f arg1 arg2)]))
(define (avappN f . args)
(avapply f args))
(define (-timescale s v)
(match v
[(? dv?) (error 'timescale "expected animated value, got: ~e" v)]
[(av dur f v0 v1) (av (* dur s) f v0 v1)]
[_ v]))
(define (-timeclip dur* v [gravity 'left])
(match v
[(? dv?) (error 'timeclip "expected animated value, got: ~e" v)]
[(av dur f v0 v1)
(define scale (/ dur* dur))
(if (= dur* dur)
v
(case gravity
[(left)
(cond [(< dur* dur)
(define (f* u) (f (* u scale)))
(av dur* f* v0 (f* 1))]
[(> dur* dur)
(define (f* u) (f (min 1 (* u scale))))
(av dur* f* v0 v1)])]
[(right)
(cond [(< dur* dur)
(define (f* u) (f (+ 1 (- scale) (* u scale))))
(av dur* f* (f* 0) v1)]
[(> dur* dur)
(define (f* u) (f (max 0 (- (* u scale) scale -1))))
(av dur* f* v0 v1)])]
[(stretch)
(av dur* f v0 v1)]))]
[_ v]))
;; -get : UReal AnimatedValue[X] -> X
(define (-get u arg)
(match arg
[(av dur f _ _) (f u)]
[v v]))
;; ============================================================
;; A TimedValue[X] is one of
;; - AnimatedValue[X]
;; - (dv (NonemptyListof TimedValue[X])) -- "discrete" time steps
(struct dv (steps))
;; Note: This allows trees of discrete-timed animations, as opposed to
;; dv containing (NEVectorof AnimatedValue[X])!
(define (dv-length v)
(match v [(dv steps) (length steps)] [_ 1]))
(define (dv-ref v k)
(match v
[(dv steps)
(if (< k (length steps)) (list-ref steps k) (-getZ (last steps)))]
[v (if (zero? k) v (-getZ v))]))
(define ->>
(case-lambda
[(v) (>>* 1 v)]
[(n v) (>>* n v)]
[(n v0 v) (>>* n v v0)]))
(define (>>* n v [v0 (-getA v)])
(match v
[(dv steps) (dv (append (make-list n v0) steps))]
[_ (dv (append (make-list n v0) (list v)))]))
(define (-// . vs)
(dv vs))
(define (-++ . vs)
(dv (apply append (map (lambda (a) (if (dv? a) (dv-steps a) (list a))) vs))))
;; tvapply : (X ... -> Y) (List TimedValue[X] ...) -> TimedValue[Y]
(define (tvapply f args)
(cond [(ormap dv? args)
(define len* (apply max (map dv-length args)))
(dv (for/list ([i (in-range len*)])
(tvapply f (map (lambda (a) (dv-ref a i)) args))))]
[else (avapply f args)]))
;; tvapp{1,2,N} : (X ... -> Y) TimedValue[X] ... -> TimedValue[Y]
(define (tvapp1 f arg)
(match arg
[(dv steps)
(dv (for/list ([step (in-list steps)])
(tvapp1 f step)))]
[else (avapp1 f arg)]))
(define (tvapp2 f arg1 arg2)
(cond [(or (dv? arg1) (dv? arg2))
(define len* (max (dv-length arg1) (dv-length arg2)))
(dv (for/list ([i (in-range len*)])
(tvapp2 f (dv-ref arg1 i) (dv-ref arg2 i))))]
[else (avapp2 f arg1 arg2)]))
(define (tvappN f . args)
(tvapply f args))
(define (const? x) (not (or (av? x) (dv? x))))
(define (smooth? x) (not (dv? x)))
;; ============================================================
;; -share : TimedValue[X] -> TimedValue[X]
;; Useful when eq?-ness is important.
(define (-share v)
(match v
[(dv steps)
(dv (map -share steps))]
[(av dur f v0 v1)
(define h (make-hasheqv))
(define (f* u) (hash-ref! h u (lambda () (f u))))
(av dur f* v0 v1)]
[_ v]))
;; -get{A,Z} : TimedValue[X] -> X
(define (-getA arg)
(match arg
[(dv (cons step1 _)) (-getA step1)]
[(av _ _ v0 _) v0]
[v v]))
(define (-getZ arg)
(match arg
[(dv steps) (-getZ (last steps))]
[(av _ _ _ v1) v1]
[v v]))
(define (-cumulative v fps)
(match v
[(av dur f v0 v1)
;; An Index is a Nat ranging from 0 to (ceiling (* dur fps))
(define h (make-hasheqv)) ;; Nat -> (Listof X)
(for/fold ([acc null]) ([i (in-range 0 (add1 (ceiling (* dur fps))))])
(define u (min 1 (/ i dur fps)))
(define acc* (cons (f u) acc))
(hash-set! h i acc*)
acc*)
(define (f* u)
(define i (inexact->exact (floor (* u dur fps))))
(hash-ref h i))
(av dur f* (f* 0) (f* 1))]
[v (list v)]))
;; ----------------------------------------
(begin-for-syntax
(define (unlifted-transformer unlifted)
(syntax-parser
[(_ arg ...)
(with-syntax ([unlifted unlifted])
(syntax/loc this-syntax (unlifted arg ...)))]
[_:id
(raise-syntax-error #f "unlifted function not in operator position" this-syntax)])))
(define-syntax define/unlifted
(syntax-parser
[(_ (f:id . formals) . body)
(with-syntax ([(unlifted-f) (generate-temporaries #'(f))])
#'(begin (define (unlifted-f . formals) . body)
(define-syntax f (unlifted-transformer (quote-syntax unlifted-f)))))]))
(define-syntax tvapp
(syntax-parser
;; functions declared with define/unlifted are macros, don't go through tvapp
[(_ f:expr) #'(#%plain-app f)]
;;[(_ f:expr arg:expr) #'(#%plain-app tvapp1 f arg)]
;;[(_ f:expr arg1:expr arg2:expr) #'(#%plain-app tvapp2 f arg1 arg2)]
[(_ f:expr arg:expr ...) #'(#%plain-app tvappN f arg ...)]
[(_ f:expr (~alt parg:expr (~seq kw:keyword kwarg:expr)) ...)
(with-syntax ([(ptmp ...) (generate-temporaries #'(parg ...))]
[(kwtmp ...) (generate-temporaries #'(kwarg ...))])
#'(tvapp (lambda (ptmp ... kwtmp ...) (f ptmp ... (~@ kw kwtmp) ...))
parg ... kwarg ...))]))
(define-syntax-parameter tv-lifting? #t)
(define-syntax tv:app
(syntax-parser
[(_ x ...)
(if (syntax-parameter-value #'tv-lifting?)
(syntax/loc this-syntax (tvapp x ...))
(syntax/loc this-syntax (#%app x ...)))]))
(define-syntax-rule (begin/lifted . body)
(syntax-parameterize ((tv-lifting? #t)) . body))
(define-syntax-rule (begin/unlifted . body)
(syntax-parameterize ((tv-lifting? #f)) . body))
(define-syntax get (unlifted-transformer #'-get))
(define-syntax getA (unlifted-transformer #'-getA))
(define-syntax getZ (unlifted-transformer #'-getZ))
(define-syntax share (unlifted-transformer #'-share))
(define-syntax // (unlifted-transformer #'-//))
(define-syntax ++ (unlifted-transformer #'-++))
(define-syntax >> (unlifted-transformer #'->>))
(define (if0 v0 velse) (av 1 (lambda (u) (if (= u 0) v0 velse)) v0 velse))
(define (if1 v1 velse) (av 1 (lambda (u) (if (= u 1) v1 velse)) velse v1))
(define-syntax-rule (let/lift ([x rhs] ...) . body)
(tvapp (lambda (x ...) . body) rhs ...))
(define (stepfun vs)
(let ([vs (list->vector vs)] [n (length vs)])
(av 1
(lambda (u) (vector-ref vs (min n (inexact->exact (floor (* n u))))))
(vector-ref vs 0)
(vector-ref vs (sub1 n)))))
(define-syntax timescale (unlifted-transformer #'-timescale))
(define-syntax timeclip (unlifted-transformer #'-timeclip))
(define-syntax cumulative (unlifted-transformer #'-cumulative))
| true |
6c91645bfc1637c0d4b50cf991ec895cf9a6dbfe | b08b7e3160ae9947b6046123acad8f59152375c3 | /Programming Language Detection/Experiment-2/Dataset/Train/Racket/bitcoin-address-validation.rkt | 15646436bbd8142463534a7baa0dfc4f6e2226fc | []
| no_license | dlaststark/machine-learning-projects | efb0a28c664419275e87eb612c89054164fe1eb0 | eaa0c96d4d1c15934d63035b837636a6d11736e3 | refs/heads/master | 2022-12-06T08:36:09.867677 | 2022-11-20T13:17:25 | 2022-11-20T13:17:25 | 246,379,103 | 9 | 5 | null | null | null | null | UTF-8 | Racket | false | false | 1,746 | rkt | bitcoin-address-validation.rkt | #lang racket/base
;; Same sha-256 interface as the same-named task
(require ffi/unsafe ffi/unsafe/define openssl/libcrypto)
(define-ffi-definer defcrypto libcrypto)
(defcrypto SHA256_Init (_fun _pointer -> _int))
(defcrypto SHA256_Update (_fun _pointer _pointer _long -> _int))
(defcrypto SHA256_Final (_fun _pointer _pointer -> _int))
(define (sha256 bytes)
(define ctx (malloc 128))
(define result (make-bytes 32))
(SHA256_Init ctx)
(SHA256_Update ctx bytes (bytes-length bytes))
(SHA256_Final result ctx)
result)
;; base58 decoding
(define base58-digits
(let ([v (make-vector 128 #f)])
(for ([i (in-naturals)]
[c "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"])
(vector-set! v (char->integer c) i))
v))
(define (base58->integer str)
(for/fold ([n 0]) ([c str])
(+ (* n 58) (vector-ref base58-digits (char->integer c)))))
(define (int->bytes n digits)
(list->bytes (let loop ([n n] [digits digits] [acc '()])
(if (zero? digits) acc
(let-values ([(q r) (quotient/remainder n 256)])
(loop q (sub1 digits) (cons r acc)))))))
(define (validate-bitcoin-address str)
(define bs (int->bytes (base58->integer str) 25))
(equal? (subbytes (sha256 (sha256 (subbytes bs 0 21))) 0 4)
(subbytes bs 21)))
;; additional tests taken from the other solutions
(validate-bitcoin-address "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i") ; => #t
(validate-bitcoin-address "1111111111111111111114oLvT2") ; => #t
(validate-bitcoin-address "17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j") ; => #t
(validate-bitcoin-address "1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9") ; => #t
(validate-bitcoin-address "1badbadbadbadbadbadbadbadbadbadbad") ; => #f
| false |
4c9ed09599c1105c39f5b2e8378f5f0897a0b4dd | 8559293672192f7adbb433ab0ea908a275dea156 | /examples/0n1.rkt | 92f27b9c4503e463a89e9c688e7f0dee1724a50a | []
| no_license | jpolitz/autogrammar | d72386ff13eba59b8ff84e574d55cdc7f5057e1b | 86c62d68768d15ccb686368627c1650e5af43a4d | refs/heads/master | 2021-01-20T19:13:31.515199 | 2012-12-04T01:57:00 | 2012-12-04T01:57:00 | 5,534,957 | 0 | 1 | null | null | null | null | UTF-8 | Racket | false | false | 52 | rkt | 0n1.rkt | #lang planet dyoo/autogrammar/lalr
rule: "0"* "1"
| false |
90f799cf31cc6e231be269c5e6836ee2a1252169 | d0820ac8fff97113bd02e544d83f2804ecbfb924 | /cache/collector-exports.rkt | c6eceee49b3482738f1aa637df6e974f2943343f | [
"MIT"
]
| permissive | salenaer/bachelor-proef | 3b71f94acbec80f06099dbc594687dba1fd53ba9 | 628db805268fc2cd8be4f1c82f676de7a2bfdf40 | refs/heads/master | 2021-01-23T07:02:42.447905 | 2015-05-16T09:31:07 | 2015-05-16T09:31:07 | 32,811,163 | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 1,541 | rkt | collector-exports.rkt | #lang scheme
(provide (all-defined-out))
(define collector:flat? false)
(define collector:alloc-flat false)
(define collector:deref false)
(define collector:cons? false)
(define collector:cons false)
(define collector:first false)
(define collector:rest false)
(define collector:set-first! false)
(define collector:set-rest! false)
(define collector:vector? false)
(define collector:make-vector false)
(define collector:vector-ref false)
(define collector:vector-set! false)
(define collector:vector-length false)
(define (set-collector:flat?! proc)
(set! collector:flat? proc))
(define (set-collector:alloc-flat! proc)
(set! collector:alloc-flat proc))
(define (set-collector:deref! proc)
(set! collector:deref proc))
(define (set-collector:cons?! proc)
(set! collector:cons? proc))
(define (set-collector:cons! proc)
(set! collector:cons proc))
(define (set-collector:first! proc)
(set! collector:first proc))
(define (set-collector:rest! proc)
(set! collector:rest proc))
(define (set-collector:set-first!! proc)
(set! collector:set-first! proc))
(define (set-collector:set-rest!! proc)
(set! collector:set-rest! proc))
(define (set-collector:vector?! proc)
(set! collector:vector? proc))
(define (set-collector:make-vector! proc)
(set! collector:make-vector proc))
(define (set-collector:vector-ref! proc)
(set! collector:vector-ref proc))
(define (set-collector:vector-set!! proc)
(set! collector:vector-set! proc))
(define (set-collector:vector-length! proc)
(set! collector:vector-length proc))
| false |
5843f33765bd29e2e7a384abe0c1a54499b5c696 | c31f57f961c902b12c900ad16e5390eaf5c60427 | /data/programming_languages/scheme/lexer-contract.rkt | 1ad6c2481d8755532a582e57b99834d19ebc5a93 | []
| no_license | klgraham/deep-learning-with-pytorch | ccc7602d9412fb335fe1411ba31641b9311a4dba | 4373f1c8be8e091ea7d4afafc81dd7011ef5ca95 | refs/heads/master | 2022-10-24T01:48:46.160478 | 2017-03-13T20:07:03 | 2017-03-13T20:07:03 | 79,877,434 | 0 | 1 | null | 2022-10-02T20:42:36 | 2017-01-24T04:12:24 | C | UTF-8 | Racket | false | false | 3,287 | rkt | lexer-contract.rkt | #lang racket/base
(require racket/contract/base
racket/contract/option)
(provide lexer/c (struct-out dont-stop))
(struct dont-stop (val) #:transparent)
(define lexer/c
(option/c
(or/c (->i ([in (and/c input-port? port-counts-lines?)])
(values [txt any/c]
[type symbol?]
[paren (or/c symbol? #f)]
[start (or/c exact-positive-integer? #f)]
[end (start type) (end/c start type)]))
(->i ([in (and/c input-port? port-counts-lines?)]
[offset exact-nonnegative-integer?]
[mode (not/c dont-stop?)])
(values [txt any/c]
[type symbol?]
[paren (or/c symbol? #f)]
[start (or/c exact-positive-integer? #f)]
[end (start type) (end/c start type)]
[backup exact-nonnegative-integer?]
[new-mode any/c])))
#:tester (λ (lexer) (try-some-random-streams lexer))))
(define (try-some-random-streams lexer)
(define 3ary-lexer
(cond
[(procedure-arity-includes? lexer 1)
(λ (in offset mode)
(define-values (txt type paren start end) (lexer in))
(values txt type paren start end 0 #f))]
[else lexer]))
(define initial-state (pseudo-random-generator->vector
(current-pseudo-random-generator)))
(with-handlers ([exn:fail?
(lambda (exn)
(raise
(make-exn
(format (string-append "try-some-random-streams:"
" random testing of lexer failed\n"
" lexer: ~e\n"
" pseudo-random state: ~s\n"
" error message: ~s")
lexer
initial-state
(exn-message exn))
(exn-continuation-marks exn))))])
(for ([x (in-range 10)])
(define size (random 100))
(define (quash-backslash-r c)
;; it isn't clear the spec is right in
;; the case of \r\n combinations, so we
;; punt for now
(if (equal? c #\return) #\newline c))
(define s (build-string
size
(λ (c)
(quash-backslash-r
(case (random 3)
[(0)
(define s " ()@{}\"λΣ\0")
(string-ref s (random (string-length s)))]
[(1 2)
(integer->char (random 255))])))))
(define in (open-input-string s))
(port-count-lines! in)
(let loop ([mode #f][offset 0])
(define-values (txt type paren start end backup new-mode)
(3ary-lexer in offset mode))
(cond
[(equal? type 'eof) #t]
[(< end size) (loop new-mode end)]
[else #f])))))
(define (end/c start type)
(cond
[(equal? 'eof type)
(or/c exact-positive-integer? #f)]
[start
(and/c exact-positive-integer?
(>/c start))]
[else
#f]))
| false |
4fa6da681960aa9ec1dd8259f3c04efabdcfecb8 | 15d1b923d6ac53f741163f7e38d8b97ab782c915 | /2017/14/14.rkt | dad58daa5be25de04dee2d9e1937d56b9a5b89a1 | []
| no_license | bennn/advent-of-code | 5e922da50fea50bc78cab14cd3263286508ce061 | 859ea1d86546d9428593d386bf33b394036f9843 | refs/heads/master | 2020-09-23T08:48:08.341242 | 2019-12-08T13:00:33 | 2019-12-08T13:00:33 | 225,456,308 | 2 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 2,538 | rkt | 14.rkt | #lang racket
(require "../10/10.rkt")
(define W 128)
(define H 128)
(define INPUT
"hxtvlmkl")
(define (make-row-str i)
(format "~a-~a" INPUT i))
(define (make-grid)
(for/list ((i (in-range H)))
(make-row-str i)))
(define (go input)
(define G (make-grid))
(define part1
(for/sum ((r (in-list G)))
(define o (knot-hash r))
(for/sum ((c (in-string o)))
(bits->num-used (hex->bits c)))))
(define part2
(count-regions
(for/vector ((r (in-list G)))
(define o (knot-hash r))
(list->vector
(append* (for/list ((c (in-string o))) (map char->10 (string->list (hex->bits c)))))))))
(printf "part 1, num used : ~a~n" part1)
(printf "part 2, num regions : ~a~n" part2)
(void))
(define (count-regions part2)
(define num-regions 0)
(define curr-id "R0")
(define (incr-id)
(set! num-regions (+ 1 num-regions))
(set! curr-id (format "R~a" num-regions))
(void))
(define I (vector-length part2))
(define J (vector-length (vector-ref part2 0)))
(define (search-from V i j x)
(unless (= i 0)
(try-set V (- i 1) j x))
(unless (= i (- I 1))
(try-set V (+ i 1) j x))
(unless (= j 0)
(try-set V i (- j 1) x))
(unless (= j (- J 1))
(try-set V i (+ j 1) x)))
(define (try-set V i j x)
(when (equal? (vector-ref** V i j) 1)
(begin
(vector-set** V i j x)
(search-from V i j x))))
(for* ((i (in-range I)) (j (in-range J)))
(if (used? (vector-ref** part2 i j))
(void)
(if (equal? 1 (vector-ref** part2 i j))
(begin
(vector-set** part2 i j curr-id)
(search-from part2 i j curr-id)
(incr-id)
(void))
(void))))
#;(for ((v (in-vector part2)))
(displayln v))
num-regions)
(define (vector-set** v i j x)
(vector-set! (vector-ref v i) j x))
(define (used? v)
(string? v))
(define (vector-ref** v i j)
(vector-ref (vector-ref v i) j))
(define (char->10 x)
(if (eq? x #\1) 1 0))
(define (hex->bits c)
(case c
((#\0) "0000")
((#\1) "0001")
((#\2) "0010")
((#\3) "0011")
((#\4) "0100")
((#\5) "0101")
((#\6) "0110")
((#\7) "0111")
((#\8) "1000")
((#\9) "1001")
((#\a) "1010")
((#\b) "1011")
((#\c) "1100")
((#\d) "1101")
((#\e) "1110")
((#\f) "1111")))
(define (bits->num-used b)
(for/sum ((c (in-string b)))
(if (eq? c #\1) 1 0)))
(module+ main
(require racket/cmdline)
(command-line
#:program "day-14"
#:args ()
(go (void))))
| false |
a55de7fe58ea65fa49299c320767f77f08ade8ad | 7ab4846887821aaa6ac2290c686a2ceb51673ec4 | /CSC431/mini-compiler/optimize/common.rkt | 380ffbe5d32429eed596e31270f312ce817a03aa | []
| no_license | baileywickham/college | 14d39bf5586a0f3c15f3461eb42ff1114c58a7d5 | 8f3bb6433ea8555f0ba73cb0db2fabd98c95d8ee | refs/heads/master | 2022-08-24T19:20:18.813089 | 2022-08-11T10:22:41 | 2022-08-11T10:22:41 | 150,782,968 | 1 | 5 | null | 2021-03-15T19:56:38 | 2018-09-28T18:56:44 | Java | UTF-8 | Racket | false | false | 1,910 | rkt | common.rkt | #lang racket
(provide (all-defined-out) (all-from-out "../util.rkt" "../ast/llvm.rkt"))
(require "../util.rkt" "../ast/llvm.rkt")
;;
(define (get-all proc blocks)
(append-map
(λ+ ((Block _ stmts)) (append-map proc stmts))
blocks))
;;
(define (stmt-writes stmt)
(match stmt
[(AssignLL res _) (list res)]
[(PhiLL id _ _) (list id)]
[_ '()]))
;;
(define (stmt-reads stmt)
(match stmt
[(AssignLL _ src) (stmt-reads src)]
[(BinaryLL _ _ op1 op2) (list op1 op2)]
[(BrCondLL cond _ _) (list cond)]
[(AllocLL _) (error 'optimize "unused values only supported in ssa")]
[(StoreLL _ val ptr) (list val ptr)]
[(LoadLL _ ptr) (list ptr)]
[(ReturnLL _ arg) (list arg)]
[(GetEltLL _ ptr _) (list ptr)]
[(CallLL _ _ (list (cons ids _) ...) _) ids]
[(CastLL _ _ value _) (list value)]
[(PhiLL _ _ (list (cons label (cons ids _)) ...)) ids]
[_ '()]))
;;
(define (ssa-reg? v)
(match v
[(IdLL _ #f) #t]
[_ #f]))
(define (subst-vars s proc)
(match s
[(AssignLL result src) (AssignLL (proc result) (subst-vars src proc))]
[(BinaryLL op ty op1 op2) (BinaryLL op ty (proc op1) (proc op2))]
[(BrLL label) (BrLL (proc label #t))]
[(BrCondLL cond iftrue iffalse) (BrCondLL (proc cond) (proc iftrue #t) (proc iffalse #t))]
[(StoreLL ty val ptr) (StoreLL ty (proc val) (proc ptr))]
[(LoadLL ty ptr) (LoadLL ty (proc ptr))]
[(ReturnLL ty arg) (ReturnLL ty (proc arg))]
[(GetEltLL ty ptr index) (GetEltLL ty (proc ptr) index)]
[(CallLL ty fn args var-args?) (CallLL ty fn (map (λ+ ((cons id ty)) (cons (proc id) ty)) args) var-args?)]
[(CastLL op ty value ty2) (CastLL op ty (proc value) ty2)]
[(PhiLL id ty args)
(PhiLL (proc id) ty
(map (λ+ ((cons label (cons id ty)))
(cons (proc label) (cons (proc id) ty))) args))]
[_ s]))
| false |
33bf96b315cd359c05f28db451b67803563d78f9 | e14718733b3c8f3fc1dba77cbae9b3e2b3356c4e | /parser/all-tests.rkt | 99da1002b0172802d0566441e5a7632afb0fc099 | []
| no_license | KrossMarian/assembler | 179d559cc6225ae592a159b759d762b343ba732e | 6b8ce46702e01d2e6077a04e4be3bf7076f3256d | refs/heads/master | 2021-01-21T00:25:05.970616 | 2010-10-14T14:06:17 | 2010-10-14T14:06:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Racket | false | false | 109 | rkt | all-tests.rkt | #lang racket/base
(require
rackunit
"parse-test.rkt")
(define/provide-test-suite all-tests
parse-tests) | false |
b146b5c92ced6e220190e276e806a628384792b3 | d2fc383d46303bc47223f4e4d59ed925e9b446ce | /courses/2011/fall/330/notes/2-24.rkt | 5b66e11d5913908f8860f4c1a2a6d01b9d2b909d | []
| no_license | jeapostrophe/jeapostrophe.github.com | ce0507abc0bf3de1c513955f234e8f39b60e4d05 | 48ae350248f33f6ce27be3ce24473e2bd225f6b5 | refs/heads/master | 2022-09-29T07:38:27.529951 | 2022-09-22T10:12:04 | 2022-09-22T10:12:04 | 3,734,650 | 14 | 5 | null | 2022-03-25T14:33:29 | 2012-03-16T01:13:09 | HTML | UTF-8 | Racket | false | false | 4,515 | rkt | 2-24.rkt | #lang racket
(define (read-from-the-user prompt v)
(printf "~a\n" prompt)
;; (read)
v)
(define (read-from-the-user/k prompt the-guy)
(printf "You are really calling the continuation one\n")
(printf "~a\n" prompt)
(the-guy (read))
(error 'read-from-the-user/k "The program has died"))
;; Add Two Numbers dot com (C code)
(let ()
(define num1 (read-from-the-user "Gimme the first number:"
10))
(define num2 (read-from-the-user "Gimme the second number:"
14))
(printf "The answer is ~a\n"
(+ num1 num2)))
;; Add Two Numbers dot com (simulated Web code)
(when #f
(let ()
(read-from-the-user/k
"Gimme the first number:"
(lambda (num1)
(read-from-the-user/k
"Gimme the second number:"
(lambda (num2)
(printf "The answer is ~a\n"
(+ num1 num2))
(error 'really-over)))))))
;; Continuation Passing Style (or CPS)
(define FINAL-COUNTDOWN
(lambda (final-ans)
(error 'dun-da-dun-dun-dun-da-da-dun-dun "The answer was ~a" final-ans)))
;; CPS : program -> program[CPS]
(require (for-syntax syntax/parse))
(define-syntax (CPS p)
(syntax-parse
p
#:literals (printf + read-from-the-user lambda)
[(CPS n:nat)
(syntax
(lambda (guy-who-wants-a-number-k)
(guy-who-wants-a-number-k n)))]
[(CPS some-string:str)
(syntax
(lambda (guy-who-wants-a-string-k)
(guy-who-wants-a-string-k some-string)))]
[(CPS read-from-the-user)
(syntax
(lambda (guy-who-wants-read-k)
(guy-who-wants-read-k
(lambda (prompt fake-value guy-who-called-read-k)
(read-from-the-user/k prompt guy-who-called-read-k)))))]
[(CPS printf)
(syntax
(lambda (guy-who-wants-printf-k)
(guy-who-wants-printf-k
(lambda (fmt arg guy-who-called-printf-k)
(guy-who-called-printf-k (printf fmt arg))))))]
;; Homework: Change names from printf to +
[(CPS +)
(syntax
(lambda (guy-who-wants-printf-k)
(guy-who-wants-printf-k
(lambda (fmt arg guy-who-called-printf-k)
(guy-who-called-printf-k (+ fmt arg))))))]
[(CPS (lambda (x ...) b))
(syntax
(lambda (guy-who-wants-a-lambda-k)
(guy-who-wants-a-lambda-k
(lambda (x ... guy-who-called-lambda-k)
((CPS b) guy-who-called-lambda-k)))))]
[(CPS (f arg0 arg1))
(syntax
(lambda (funcalls-k)
((CPS f)
(lambda (f/k)
((CPS arg0)
(lambda (arg0v)
((CPS arg1)
(lambda (arg1v)
(f/k arg0v arg1v funcalls-k)))))))))]
[(CPS (f arg0))
(syntax
(lambda (funcalls-k)
((CPS f)
(lambda (f/k)
((CPS arg0)
(lambda (arg0v)
(f/k arg0v funcalls-k)))))))]
[(CPS n:id)
(syntax
(lambda (guy-who-wants-an-id-k)
(guy-who-wants-an-id-k n)))]))
(when #f
((CPS
(printf "The answer is ~a\n"
(+ (read-from-the-user "Gimme the first number:"
10)
(read-from-the-user "Gimme the second number:"
15))))
FINAL-COUNTDOWN))
(when #f
((CPS
(printf "The answer is ~a\n"
(+ (+ (read-from-the-user "Gimme the first number:"
10)
(+ (read-from-the-user "Gimme the first number:"
10)
(read-from-the-user "Gimme the second number:"
15)))
(+ (read-from-the-user "Gimme the first number:"
10)
(+ (+ (read-from-the-user "Gimme the first number:"
10)
(read-from-the-user "Gimme the second number:"
15))
(read-from-the-user "Gimme the second number:"
15))))))
FINAL-COUNTDOWN))
((CPS
(printf "The answer is ~a\n"
;; (with (x xe) e) => ((lambda (x) e) xe)
((lambda (num1)
(+ num1
(read-from-the-user "Gimme the second number:"
15)))
(read-from-the-user "Gimme the first number:"
10))))
FINAL-COUNTDOWN)
;; XXX CPS any program
;; XXX CPS transform
;; XXX Fischer transform
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.