Compare commits

..

5 Commits

@ -1,43 +0,0 @@
name: CI
on: [push, pull_request]
jobs:
run:
name: "Build using Racket '${{ matrix.racket-version }}' (${{ matrix.racket-variant }})"
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
racket-version: ["6.6", "6.7", "6.8", "6.9", "6.10.1", "6.11", "6.12", "7.0", "7.1", "7.2", "7.3", "7.4", "7.5", "7.6", "7.7", "7.8", "7.9", "current"]
racket-variant: ["BC", "CS"]
# CS builds are only provided for versions 7.4 and up so avoid
# running the job for prior versions.
exclude:
- {racket-version: "6.6", racket-variant: "CS"}
- {racket-version: "6.7", racket-variant: "CS"}
- {racket-version: "6.8", racket-variant: "CS"}
- {racket-version: "6.9", racket-variant: "CS"}
- {racket-version: "6.10.1", racket-variant: "CS"}
- {racket-version: "6.11", racket-variant: "CS"}
- {racket-version: "6.12", racket-variant: "CS"}
- {racket-version: "7.0", racket-variant: "CS"}
- {racket-version: "7.1", racket-variant: "CS"}
- {racket-version: "7.2", racket-variant: "CS"}
- {racket-version: "7.3", racket-variant: "CS"}
steps:
- name: Checkout
uses: actions/checkout@master
- uses: Bogdanp/setup-racket@v0.11
with:
distribution: 'full'
version: ${{ matrix.racket-version }}
variant: ${{ matrix.racket-variant }}
- name: Install Sugar and its dependencies
run: raco pkg install --auto --batch
- name: Run the tests
run: xvfb-run raco test -j 4 -p sugar

@ -0,0 +1,36 @@
# adapted from
# https://github.com/greghendershott/travis-racket/blob/master/.travis.yml
# Thanks Greg!
language: c
sudo: false
env:
global:
- RACKET_DIR=~/racket
matrix:
- RACKET_VERSION=6.0
- RACKET_VERSION=6.1
- RACKET_VERSION=6.2
- RACKET_VERSION=6.3
- RACKET_VERSION=HEAD
# You may want to test against certain versions of Racket, without
# having them count against the overall success/failure.
matrix:
allow_failures:
# - env: RACKET_VERSION=HEAD
# Fast finish: Overall build result is determined as soon as any of
# its rows have failed, or, all of its rows that aren't allowed to
# fail have succeeded.
fast_finish: true
before_install:
- git clone https://github.com/mbutterick/travis-racket.git
- cat travis-racket/install-racket.sh | bash # pipe to bash not sh!
- export PATH="${RACKET_DIR}/bin:${PATH}" #install-racket.sh can't set for us
script:
- cd .. # Travis did a cd into the dir. Back up, for the next:
- raco pkg install --deps search-auto --link sugar
- raco test -p sugar

@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

@ -1,9 +0,0 @@
MIT License for `sugar`
© 2014-2019 Matthew Butterick
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.

@ -1,4 +1,5 @@
## Sugar ![Build Status](https://github.com/mbutterick/sugar/workflows/CI/badge.svg)
Sugar [![Build Status](https://travis-ci.org/mbutterick/sugar.svg?branch=master)](https://travis-ci.org/mbutterick/sugar)
-----
Functions that improve the readability of Racket code in Racket 6.0+.
@ -15,12 +16,3 @@ In safe mode (with contracts):
(require (submod sugar safe))
You can [read the docs here](http://pkg-build.racket-lang.org/doc/sugar).
## License
MIT
## Project status
Complete. Maintained but no improvements planned. I dont disavow this code, exactly, and I maintain other projects that rely on it. But it arises from a more naive era of personal Racketeering. I would not necessarily recommend taking inspiration from the code herein.

@ -0,0 +1,17 @@
#lang racket/base
(require (for-syntax racket/base) "define.rkt")
(define+provide+safe (make-caching-proc base-proc)
(procedure? . -> . procedure?)
(let ([cache (make-hash)])
(make-keyword-procedure
(λ (kws kw-args . args)
(hash-ref! cache args (λ () (keyword-apply base-proc kws kw-args args)))))))
(provide+safe define/caching)
(define-syntax (define/caching stx)
(syntax-case stx ()
[(_ (name arg ... . rest-arg) body ...)
#'(define/caching name (λ(arg ... . rest-arg) body ...))]
[(_ name body ...)
#'(define name (make-caching-proc body ...))]))

@ -0,0 +1,165 @@
#lang racket/base
(require (for-syntax racket/base racket/syntax))
(require net/url racket/set racket/sequence "unstable/len.rkt" "define.rkt")
(define-syntax-rule (make-coercion-error-handler target-format x)
(λ(e) (error (string->symbol (format "->~a" target-format)) (format "Can't convert ~s to ~a" x target-format))))
(define+provide+safe (->int x)
(any/c . -> . integer?)
(with-handlers ([exn:fail? (make-coercion-error-handler 'int x)])
(cond
[(or (integer? x) (real? x)) (inexact->exact (floor x))]
[(complex? x) (->int (real-part x))]
[(string? x) (let ([strnum (string->number x)])
(if (real? strnum) (->int strnum) (error 'ineligible-string)))]
[(or (symbol? x) (path? x) (bytes? x)) (->int (->string x))]
[(char? x) (char->integer x)]
[else (len x)]))) ; covers Lengthable types
(define+provide+safe (->string x)
(any/c . -> . string?)
(if (string? x)
x ; fast exit for strings
(with-handlers ([exn:fail? (make-coercion-error-handler 'string x)])
(cond
[(or (equal? '() x) (void? x)) ""]
[(symbol? x) (symbol->string x)]
[(number? x) (number->string x)]
[(path? x) (path->string x)]
[(or (char? x) (bytes? x)) (format "~a" x)]
[(url? x) (url->string x)]
[else (error 'bad-type)]))))
;; ->symbol, ->path, and ->url are just variants on ->string
;; two advantages: return correct type, and more accurate error
;; no need for "Symbolable" type - same as Stringable
(define+provide+safe (->symbol x)
(any/c . -> . symbol?)
(if (symbol? x)
x
(with-handlers ([exn:fail? (make-coercion-error-handler 'symbol x)])
(string->symbol (->string x)))))
(define+provide+safe (->path x)
(any/c . -> . path?)
(if (path? x)
x
(with-handlers ([exn:fail? (make-coercion-error-handler 'path x)])
(cond
[(url? x) (apply build-path (map path/param-path (url-path x)))]
[else (string->path (->string x))]))))
(define+provide+safe (->url x)
(any/c . -> . url?)
(with-handlers ([exn:fail? (make-coercion-error-handler 'url x)])
(string->url (->string x))))
(define+provide+safe (->complete-path x)
(any/c . -> . complete-path?)
(with-handlers ([exn:fail? (make-coercion-error-handler 'complete-path x)])
(path->complete-path (->path x))))
(define+provide+safe (->list x)
(any/c . -> . list?)
(if (list? x)
x
(with-handlers ([exn:fail? (make-coercion-error-handler 'list x)])
(cond
[(string? x) (list x)]
[(vector? x) (for/list ([i (in-vector x)])
i)]
[(set? x) (set->list x)]
;; conditional sequencing relevant because hash also tests true for `sequence?`
[(hash? x) (hash->list x)]
[(integer? x) (list x)] ; because an integer tests #t for sequence?
[(sequence? x) (sequence->list x)]
;[(stream? x) (stream->list x)] ;; no support for streams in TR
[else (list x)]))))
(define+provide+safe (->vector x)
(any/c . -> . vector?)
(if (vector? x)
x
(with-handlers ([exn:fail? (make-coercion-error-handler 'vector x)])
(list->vector (->list x)))))
(define+provide+safe (->boolean x)
(any/c . -> . boolean?)
(and x #t))
;; coercion contracts & *ish predicates
;; only make sense in untyped code
;; thus they are here.
(define-syntax-rule (make-blame-handler try-proc expected-sym)
(λ(b)
(λ(x)
(with-handlers ([exn:fail? (λ(e)
(raise-blame-error
b x
'(expected: "~a" given: "~e")
expected-sym x))])
(try-proc x)))))
(provide+safe make-coercion-contract)
(define-syntax (make-coercion-contract stx)
(syntax-case stx ()
[(_ stem coerce-proc)
(with-syntax ([coerce/stem? (format-id stx "coerce/~a?" #'stem)]
[can-be-stem? (format-id stx "can-be-~a?" #'stem)])
#'(make-contract
#:name 'coerce/stem?
#:projection (make-blame-handler coerce-proc 'can-be-stem?)))]
[(_ stem)
(with-syntax ([->stem (format-id stx "->~a" #'stem)])
#'(make-coercion-contract stem ->stem))]))
(define-syntax (define+provide-coercion-contract stx)
(syntax-case stx ()
[(_ stem)
(with-syntax ([coerce/stem? (format-id stx "coerce/~a?" #'stem)])
#'(begin
(provide+safe coerce/stem?)
(define coerce/stem? (make-coercion-contract stem))))]))
(define+provide-coercion-contract int)
(define+provide-coercion-contract string)
(define+provide-coercion-contract symbol)
(define+provide-coercion-contract path)
(define+provide-coercion-contract boolean)
(define+provide-coercion-contract list)
(define-syntax (make-*ish-predicate stx)
(syntax-case stx ()
[(_ stem)
(with-syntax ([stemish? (format-id stx "~aish?" #'stem)]
[->stem (format-id stx "->~a" #'stem)])
#`(begin
(provide+safe stemish?)
(define (stemish? x)
(with-handlers ([exn:fail? (λ(e) #f)]) (and (->stem x) #t)))))]))
(make-*ish-predicate int)
(make-*ish-predicate string)
(make-*ish-predicate symbol)
(make-*ish-predicate url)
(make-*ish-predicate complete-path)
(make-*ish-predicate path)
(make-*ish-predicate list)
(make-*ish-predicate vector)

@ -0,0 +1,166 @@
#lang racket/base
(require (for-syntax racket/base racket/syntax) "define.rkt")
(provide+safe report report/line report/file
report* report*/line report*/file
report-apply repeat time-repeat time-repeat* compare)
(define-syntax (report stx)
(syntax-case stx ()
[(_ expr) #'(report expr expr)]
[(_ expr name)
#'(let ([expr-result expr])
(eprintf "~a = ~v\n" 'name expr-result)
expr-result)]))
(define-syntax (report/line stx)
(syntax-case stx ()
[(_ expr) #'(report/line expr expr)]
[(_ expr name)
(with-syntax ([line (syntax-line #'expr)])
#'(let ([expr-result expr])
(eprintf "~a = ~v on line ~v\n" 'name expr-result line)
expr-result))]))
(define-syntax (report/file stx)
(syntax-case stx ()
[(_ expr) #'(report/file expr expr)]
[(_ expr name)
(with-syntax ([file (syntax-source #'expr)]
[line (syntax-line #'expr)])
#'(let ([expr-result expr])
(eprintf "~a = ~v on line ~v in \"~a\"\n" 'name expr-result line 'file)
expr-result))]))
(define-syntax-rule (define-multi-version multi-name name)
(define-syntax-rule (multi-name x (... ...))
(begin (name x) (... ...))))
(define-multi-version report* report)
(define-multi-version report*/line report/line)
(define-multi-version report*/file report/file)
(define-syntax report-apply
(syntax-rules ()
[(report-apply proc expr)
(let ([lst expr])
(report (apply proc lst) (apply proc expr))
lst)]
[(report-apply proc expr #:line)
(let ([lst expr])
(report (apply proc lst) (apply proc expr) #:line)
lst)]))
#|
(define-syntax (verbalize stx)
(syntax-case stx ()
[(_ proc args ...)
(with-syntax ([proc-input (format-id stx "args to ~a" #'proc)])
#'(begin
(let () (report (list args ...) proc-input) (void))
(report (proc args ...))))]))
|#
(define-syntax-rule (repeat num expr ...)
(for/last ([i (in-range num)])
expr ...))
(define-syntax-rule (time-repeat num expr ...)
(time (repeat num expr ...)))
(define-syntax (time-repeat* stx)
(syntax-case stx ()
[(_ num expr ...)
#'(let ([n num])
(values (time-repeat n expr) ...))]))
(define-syntax (compare stx)
(syntax-case stx ()
[(_ expr id id-alt ...)
#'(values expr (let ([id id-alt]) expr) ...)]))
(module reader racket/base
(require syntax/module-reader racket/syntax version/utils)
(provide (rename-out [debug-read read]
[debug-read-syntax read-syntax]
[debug-get-info get-info]))
(define report-char #\R)
(define (make-debug-readtable [rt (current-readtable)])
(make-readtable rt report-char 'dispatch-macro report-proc))
(define (wrap-reader reader)
(define (rd . args)
(define intro (make-syntax-introducer))
(parameterize ([current-readtable (make-debug-readtable (current-readtable))]
[current-syntax-introducer intro])
(define stx (apply reader args))
(if (and (syntax? stx) (version<=? "6.2.900.4" (version)))
(intro stx)
stx)))
rd)
(define current-syntax-introducer
(make-parameter (λ (x) x)))
(define (report-proc c in src ln col pos)
(define c2 (peek-char in))
(define c3 (peek-char in 1))
(define intro (current-syntax-introducer))
(cond [(and (char=? c3 report-char) (char=? c2 report-char))
(read-char in)
(read-char in)
(define/with-syntax stx (intro (read-syntax/recursive src in)))
(intro
#'(let ()
(local-require (only-in sugar/debug [report/file report/file]))
(report/file stx)))]
[(char=? c2 report-char)
(read-char in)
(define/with-syntax stx (intro (read-syntax/recursive src in)))
(intro
#'(let ()
(local-require (only-in sugar/debug [report/line report/line]))
(report/line stx)))]
[else
(define/with-syntax stx (intro (read-syntax/recursive src in)))
(intro
#'(let ()
(local-require (only-in sugar/debug [report report]))
(report stx)))]))
(define-values (debug-read debug-read-syntax debug-get-info)
(make-meta-reader
'sugar/debug
"language path"
(lambda (bstr)
(let* ([str (bytes->string/latin-1 bstr)]
[sym (string->symbol str)])
(and (module-path? sym)
(vector
;; try submod first:
`(submod ,sym reader)
;; fall back to /lang/reader:
(string->symbol (string-append str "/lang/reader"))))))
wrap-reader
wrap-reader
(lambda (proc)
(lambda (key defval)
(define (fallback) (if proc (proc key defval) defval))
(case key
[else (fallback)]))))))

@ -0,0 +1,98 @@
#lang racket/base
(require (for-syntax racket/base))
(require racket/contract)
(provide (all-from-out racket/contract))
;; get gets of typed source file, recompile it without typing in a submodule,
;; then require those identifiers into the current level.
(define-syntax (require-via-wormhole stx)
(syntax-case stx ()
[(_ path-spec)
(let ([mod-name (gensym)])
;; need to use stx as context to get correct require behavior
(datum->syntax stx `(begin
(module mod-name typed/racket/base/no-check
(require sugar/unstable/include)
(include-without-lang-line ,(syntax->datum #'path-spec)))
(require (quote mod-name)))))]))
;; each define macro recursively converts any form of define
;; into its lambda form (define name body ...) and then operates on that.
(define-syntax (make-safe-module stx)
(syntax-case stx ()
[(_ name contract)
#'(module+ safe
(require racket/contract)
(provide (contract-out [name contract])))]
[(_ name)
#'(module+ safe
(provide name))]))
(define-syntax (define+provide+safe stx)
(syntax-case stx ()
[(_ (proc arg ... . rest-arg) contract body ...)
#'(define+provide+safe proc contract
(λ(arg ... . rest-arg) body ...))]
[(_ name contract body ...)
#'(begin
(define name body ...)
(provide name)
(make-safe-module name contract))]))
;; for previously defined identifiers
;; takes args like (provide+safe [ident contract]) or just (provide+safe ident)
;; any number of args.
(define-syntax (provide+safe stx)
(syntax-case stx ()
[(_ items ...)
(datum->syntax stx
`(begin
,@(for/list ([item (in-list (syntax->datum #'(items ...)))])
(define-values (name contract) (if (pair? item)
(values (car item) (cadr item))
(values item #f)))
`(begin
(provide ,name)
(make-safe-module ,name ,@(if contract (list contract) null))))))]))
(define-syntax (define+provide/contract stx)
(syntax-case stx ()
[(_ (proc arg ... . rest-arg) contract body ...)
#'(define+provide/contract proc contract
(λ(arg ... . rest-arg) body ...))]
[(_ name contract body ...)
#'(begin
(provide (contract-out [name contract]))
(define name body ...))]))
(define-syntax (define/contract+provide stx)
(syntax-case stx ()
[(_ (proc arg ... . rest-arg) contract body ...)
#'(define/contract+provide proc contract
(λ(arg ... . rest-arg) body ...))]
[(_ name contract body ...)
#'(begin
(provide name)
(define/contract name contract body ...))]))
(define-syntax (define+provide stx)
(syntax-case stx ()
[(_ (proc arg ... . rest-arg) body ...)
#'(define+provide proc
(λ(arg ... . rest-arg) body ...))]
[(_ name body ...)
#'(begin
(provide name)
(define name body ...))]))
(provide+safe require-via-wormhole
make-safe-module
define+provide+safe
provide+safe
define+provide/contract
define/contract+provide
define+provide)

@ -0,0 +1,58 @@
#lang racket/base
(require "define.rkt" racket/set "coerce.rkt" racket/path "unstable/string.rkt")
;; does path have a certain extension
(define+provide+safe (has-ext? x ext)
(coerce/path? coerce/string? . -> . coerce/boolean?)
(define ext-of-path (filename-extension (->path x)))
(->boolean (and ext-of-path (equal? (string-downcase (bytes->string/utf-8 ext-of-path)) (string-downcase (->string ext))))))
;; get file extension as a string, or return #f
;; (consistent with filename-extension behavior)
(define+provide+safe (get-ext x)
(coerce/path? . -> . (or/c #f string?))
(let ([fe-result (filename-extension (->path x))])
(and fe-result (bytes->string/utf-8 fe-result))))
;; todo: add extensions
(provide+safe binary-extensions)
(define binary-extensions
(map symbol->string '(gif jpg jpeg mp3 png zip pdf ico tar ai eps exe)))
(define+provide+safe (has-binary-ext? x)
(coerce/path? . -> . coerce/boolean?)
(let ([x (->path x)])
(ormap (λ(ext) (has-ext? x ext)) binary-extensions)))
;; put extension on path
;; use local contract here because this function is used within module
(define+provide+safe (add-ext x ext)
(coerce/string? coerce/string? . -> . coerce/path?)
(->path (string-append (->string x) "." (->string ext))))
;; take one extension off path
(define+provide+safe (remove-ext x)
(coerce/path? . -> . path?)
;; pass through hidden files (those starting with a dot)
(let ([x (->path x)])
(if ((->string x) . starts-with? . ".")
x
(path-replace-suffix x ""))))
;; take all extensions off path
(define+provide+safe (remove-ext* x)
(coerce/path? . -> . path?)
;; pass through hidden files (those starting with a dot)
(let ([x (->path x)])
(if ((->string x) . starts-with? . ".")
x
(let ([path-with-removed-ext (remove-ext x)])
(if (equal? x path-with-removed-ext)
x
(remove-ext* path-with-removed-ext))))))

@ -1,5 +1,7 @@
#lang info
(define collection 'multi)
(define version "0.3")
(define deps '("base"))
(define build-deps '("scribble-lib" "racket-doc" "rackunit-lib"))
(define collection "sugar")
(define version "0.1")
(define deps '("base" "rackunit-lib"))
(define build-deps '("scribble-lib" "racket-doc"))
(define scribblings '(("scribblings/sugar.scrbl" ())))
(define compile-omit-paths '("test"))

@ -0,0 +1,183 @@
#lang racket/base
(require (for-syntax racket/base) racket/list racket/set racket/function)
(require "unstable/len.rkt" "coerce.rkt" "define.rkt")
(define (list-of-lists? xs) (and (list? xs) (andmap list? xs)))
(define (index? x) (and (integer? x) (not (negative? x))))
(define increasing-nonnegative? (λ(xs) (apply < -1 xs)))
(define increasing-nonnegative-list? (and/c list? increasing-nonnegative?))
(define (integers? x) (and (list? x) (andmap integer? x)))
(define+provide+safe (trimf xs test-proc)
(list? procedure? . -> . list?)
(dropf-right (dropf xs test-proc) test-proc))
(define+provide+safe (slicef xs pred)
(list? procedure? . -> . list-of-lists?)
(define-values (last-list list-of-lists last-negating)
(for/fold ([current-list empty]
[list-of-lists empty]
[negating? #f])
([x (in-list xs)])
(define current-pred (if negating? (λ (x) (not (pred x))) pred))
(if (current-pred x)
(values (cons x current-list) list-of-lists negating?)
(values (cons x null) (if (not (empty? current-list))
(cons (reverse current-list) list-of-lists)
list-of-lists) (not negating?)))))
(reverse (cons (reverse last-list) list-of-lists)))
(define+provide+safe (slicef-at xs pred [force? #f])
((list? procedure?) (boolean?) . ->* . list-of-lists?)
(define-values (last-list list-of-lists)
(for/fold
([current-list empty][list-of-lists empty])
([x (in-list xs)])
(if (pred x)
(values (cons x null) (if (not (empty? current-list))
(cons (reverse current-list) list-of-lists)
list-of-lists))
(values (cons x current-list) list-of-lists))))
(let ([list-of-lists (reverse (if (empty? last-list)
list-of-lists
(cons (reverse last-list) list-of-lists)))])
(if (and force? (not (empty? list-of-lists)) (not (pred (caar list-of-lists))))
(cdr list-of-lists)
list-of-lists)))
(define+provide+safe (slicef-after xs pred)
(list? procedure? . -> . list-of-lists?)
(define-values (last-list list-of-lists)
(for/fold ([current-list empty][list-of-lists empty])
([x (in-list xs)])
(if (pred x)
(values empty (cons (reverse (cons x current-list)) list-of-lists))
(values (cons x current-list) list-of-lists))))
(reverse (if (empty? last-list)
list-of-lists
(cons (reverse last-list) list-of-lists))))
(define+provide+safe (slice-at xs len [force? #f])
;; with polymorphic function, use cased typing to simulate optional position arguments
((list? (and/c integer? positive?)) (boolean?) . ->* . list-of-lists?)
(define-values (last-list list-of-lists)
(for/fold ([current-list empty][list-of-lists empty])
([x (in-list xs)][i (in-naturals)])
(if (= (modulo (add1 i) len) 0)
(values empty (cons (reverse (cons x current-list)) list-of-lists))
(values (cons x current-list) list-of-lists))))
(reverse (if (or (empty? last-list) (and force? (not (= len (length last-list)))))
list-of-lists
(cons (reverse last-list) list-of-lists))))
(define+provide+safe (filter-split xs pred)
(list? predicate/c . -> . list-of-lists?)
(define-values (last-list list-of-lists)
(for/fold ([current-list empty][list-of-lists empty])
([x (in-list xs)])
(if (pred x)
(values empty (if (not (empty? current-list))
(cons (reverse current-list) list-of-lists)
list-of-lists))
(values (cons x current-list) list-of-lists))))
(reverse (if (not (empty? last-list))
(cons (reverse last-list) list-of-lists)
list-of-lists)))
(define+provide+safe (frequency-hash xs)
(list? . -> . hash?)
(define counter (make-hash))
(for ([item (in-list xs)])
(hash-update! counter item (λ(v) (add1 v)) (λ _ 0)))
counter)
(define+provide+safe (members-unique? x)
((or/c list? vector? string?) . -> . boolean?)
(cond
[(list? x) (= (len (remove-duplicates x)) (len x))]
[(vector? x) (members-unique? (->list x))]
[(string? x) (members-unique? (string->list x))]
[else (error (format "members-unique? cannot be determined for ~a" x))]))
(define+provide+safe (members-unique?/error x)
((or/c list? vector? string?) . -> . boolean?)
(define result (members-unique? x))
(if (not result)
(let* ([duplicate-keys (filter-not empty? (hash-map (frequency-hash (->list x))
(λ(element freq) (if (> freq 1) element '()))))])
(error (string-append "members-unique? failed because " (if (= (len duplicate-keys) 1)
"item isn't"
"items aren't") " unique:") duplicate-keys))
result))
(provide+safe values->list)
(define-syntax (values->list stx)
(syntax-case stx ()
[(_ values-expr) #'(call-with-values (λ () values-expr) list)]))
(define+provide+safe (sublist xs i j)
(list? index? index? . -> . list?)
(cond
[(> j (length xs)) (error 'sublist (format "ending index ~a exceeds length of list" j))]
[(>= j i) (take (drop xs i) (- j i))]
[else (error 'sublist (format "starting index ~a is larger than ending index ~a" i j))]))
(define+provide+safe (break-at xs bps)
(list? (and/c coerce/list? (or/c empty? increasing-nonnegative-list?)) . -> . list-of-lists?)
(let ([bps (if (list? bps) bps (list bps))]) ; coerce bps to list
(when (ormap (λ(bp) (>= bp (length xs))) bps)
(error 'break-at (format "breakpoint in ~v is greater than or equal to input list length = ~a" bps (length xs))))
;; easier to do back to front, because then the list index for each item won't change during the recursion
;; cons a zero onto bps (which may already start with zero) and then use that as the terminating condition
;; because breaking at zero means we've reached the start of the list
(reverse (let loop ([xs xs][bps (reverse (cons 0 bps))])
(if (= (car bps) 0)
(cons xs null) ; return whatever's left, because no more splits are possible
(let-values ([(head tail) (split-at xs (car bps))])
(cons tail (loop head (cdr bps)))))))))
(define+provide+safe (shift xs how-far [fill-item #f] [cycle #f])
((list? integer?) (any/c boolean?) . ->* . list?)
(define abs-how-far (abs how-far))
(cond
[(> abs-how-far (length xs)) (error 'shift "index is too large for list\nindex: ~a\nlist: ~v" how-far xs)]
[(= how-far 0) xs]
[(positive? how-far)
(define filler (if cycle
(take-right xs abs-how-far)
(make-list abs-how-far fill-item)))
(append filler (drop-right xs abs-how-far))]
[else ; how-far is negative
(define filler (if cycle
(take xs abs-how-far)
(make-list abs-how-far fill-item)))
(append (drop xs abs-how-far) filler)]))
(define+provide+safe (shifts xs how-fars [fill-item #f] [cycle #f])
((list? integers?) (any/c boolean?) . ->* . (listof list?))
(map (λ(how-far) (shift xs how-far fill-item cycle)) how-fars))
;; todo: can this work in typed context? couldn't figure out how to polymorphically `apply values`
;; macro doesn't work either
(define+provide+safe (shift/values xs shift-amount-or-amounts [fill-item #f] [cycle #f])
((list? (or/c integers? integer?)) (any/c boolean?) . ->* . any)
(apply values ((if (list? shift-amount-or-amounts)
shifts
shift) xs shift-amount-or-amounts fill-item cycle)))

@ -0,0 +1,17 @@
#lang racket/base
(define-syntax-rule (r+p modname)
(begin
(require modname)
(provide (all-from-out modname))
(module+ safe
(require (submod modname safe))
(provide (all-from-out (submod modname safe))))))
(r+p "cache.rkt")
(r+p "coerce.rkt")
(r+p "debug.rkt")
(r+p "define.rkt")
(r+p "file.rkt")
(r+p "list.rkt")
(r+p "test.rkt")

@ -3,7 +3,7 @@
@(require scribble/eval (for-label racket sugar))
@(define my-eval (make-base-eval))
@(my-eval `(require sugar racket/contract))
@(my-eval `(require sugar))
@title{Coercion}
@defmodule[#:multi (sugar/coerce (submod sugar/coerce safe))]

@ -8,7 +8,7 @@
@title{File extensions}
@defmodule[#:multi (sugar/file (submod sugar/file safe))]
These functions don't access the filesystem. @bold{Warning}: these functions adopt the simplifying assumption that the paths are encoded as ASCII or UTF-8. A fully precise treatment of paths would need to handle them as byte strings. If you need that, see the functions in @racketmodname[racket/path]. This library will remain naive.
These functions don't access the filesystem.
Arguments that are @racket[pathish?] can take either a string or a path. For clarity below, I've used strings.
@ -30,11 +30,10 @@ Return the last file extension of @racket[_file-path] as a string, or @racket[#f
[file-path pathish?]
[ext stringish?])
boolean?]
Return @racket[#t] if the last file extension of @racket[_file-path] is @racket[_ext], otherwise @racket[#f]. Not sensitive to case.
Return @racket[#t] if the last file extension of @racket[_file-path] is @racket[_ext], otherwise @racket[#f].
@examples[#:eval my-eval
(has-ext? "foo.txt" "txt")
(has-ext? "foo.txt" "TXT")
(has-ext? "foo.txt" "jpg")
(has-ext? "foo.jpg.txt" "jpg")]

@ -1,9 +1,9 @@
#lang scribble/manual
@(require scribble/eval (for-label racket sugar racket/function))
@(require scribble/eval (for-label racket sugar))
@(define my-eval (make-base-eval))
@(my-eval `(require sugar racket/list racket/function))
@(my-eval `(require sugar racket/list))
@title{Lists}
@defmodule[#:multi (sugar/list (submod sugar/list safe))]
@ -33,20 +33,9 @@ Like @racket[string-split], but for lists. Drop elements from anywhere in @racke
@examples[#:eval my-eval
(filter-split '(1 a b c 2 d e f 3) integer?)
(filter-split '(1 a b c 2 d e f 3) (negate integer?))]
@defproc[
(partition*
[pred procedure?]
[lst list?])
(values list? list?)]
Like @racket[partition], but contiguous groups of elements matching (or not matching) @racket[_pred] are kept together in sublists.
Same as @racket[(values (filter-split _lst _pred) (filter-split _lst (negate _pred)))], but only traverses the list once.
@examples[#:eval my-eval
(partition* integer? '(1 a b c 2 d e f 3))
(partition* (negate integer?) '(1 a b c 2 d e f 3))]
(filter-split '(1 a b c 2 d e f 3) (compose not integer?))
(filter-split '(a b c 1 2 3 d e f) integer?)
(filter-split '(a b c 1 2 3 d e f) (compose not integer?))]
@defproc[
(slice-at
@ -85,9 +74,7 @@ Divide @racket[_lst] into sublists that are homogeneously @racket[_pred] or not
[pred procedure?]
[force? boolean? #f])
(listof list?)]
Divide @racket[_lst] into sublists, each starting with an element matching @racket[_pred]. The first element of the first sublist may not match @racket[_pred]. But if you really & truly want only the sublists starting with an element matching @racket[_pred], set @racket[_force?] to @racket[#true].
If none of the elements match @racket[_pred], there is no slice to be made, and the result is the whole input list.
Divide @racket[_lst] into sublists starting with elements matching @racket[_pred]. The first element of the first sublist may not match @racket[_pred]. Or, if you really & truly want only the sublists starting with an element matching @racket[_pred], set @racket[_force?] to @racket[#t].
@examples[#:eval my-eval
(slicef-at (range 5) even?)
@ -99,17 +86,13 @@ If none of the elements match @racket[_pred], there is no slice to be made, and
@defproc[
(slicef-after
[lst list?]
[pred procedure?]
[force? boolean? #f])
[pred procedure?])
(listof list?)]
Divide @racket[_lst] into sublists, each ending with an element matching @racket[_pred]. The last element of the last sublist may not match @racket[_pred]. But if you really & truly want only the sublists ending with an element matching @racket[_pred], set @racket[_force?] to @racket[#true].
If none of the elements match @racket[_pred], there is no slice to be made, and the result is the whole input list.
Divide @racket[_lst] into sublists ending with elements matching @racket[_pred]. (Distinct from @racket[slicef-at], which gives you sublists that @italic{start} with elements matching @racket[_pred].) If none of the elements match @racket[_pred], there is no slice to be made, and the result is the whole input list.
@examples[#:eval my-eval
(slicef-after '(1 2 2 1 2) even?)
(slicef-after (range 5) odd?)
(slicef-after (range 5) odd? #true)
(slicef-after (range 5) string?)]
@ -200,7 +183,7 @@ Break @racket[_lst] into smaller lists at the index positions in @racket[_indexe
[fill-item any/c #f]
[cycle? boolean? #f])
list?]
Move the items in @racket[_lst] to the right (if @racket[_how-far] is positive) or left (if @racket[_how-far] is negative). By default, vacated spaces in the list are filled with @racket[_fill-item]. But if @racket[_cycle?] is true, elements of the list wrap around (and @racket[_fill-item] is ignored). Either way, the result list is always the same length as the input list. (If you don't care about the lengths being the same, you probably want @racket[take] or @racket[drop] instead.) If @racket[_how-far] is 0, return the original list. If @racket[_how-far] is bigger than the length of @racket[_lst], and @racket[_cycle] is not true, raise an error.
Move the items in @racket[_lst] to the right (if @racket[_how-far] is positive) or left (if @racket[_how-far] is negative). By default, vacated spaces in the list are filled with @racket[_fill-item]. But if @racket[_cycle?] is true, elements of the list wrap around (and @racket[_fill-item] is ignored). Either way, the result list is always the same length as the input list. (If you don't care about the lengths being the same, you probably want @racket[take] or @racket[drop] instead.) If @racket[_how-far] is 0, return the original list. If @racket[_how-far] is bigger than the length of @racket[_lst], raise an error.
@examples[#:eval my-eval
(define xs (range 5))
@ -212,52 +195,6 @@ Move the items in @racket[_lst] to the right (if @racket[_how-far] is positive)
(shift xs 42)
]
@defproc[
(shift-left
[lst list?]
[how-far integer?]
[fill-item any/c #f]
[cycle? boolean? #f])
list?]
Like @racket[shift], but the list is shifted left when @racket[_how-far] is positive, and right when it's negative. Otherwise identical.
@examples[#:eval my-eval
(define xs (range 5))
(shift-left xs 2)
(shift-left xs -2 0)
(shift-left xs 2 'boing)
(shift-left xs 2 'boing #t)
(shift-left xs 0)
(shift-left xs 42)
]
@deftogether[(
@defproc[
(shift-cycle
[lst list?]
[how-far integer?])
list?]
@defproc[
(shift-left-cycle
[lst list?]
[how-far integer?])
list?]
)]
Like @racket[shift] and @racket[shift-left], but automatically invokes cycle mode. @racket[_how-far] can be any size.
@examples[#:eval my-eval
(define xs (range 5))
(shift-cycle xs 2)
(shift-cycle xs -2)
(shift-cycle xs 0)
(shift-cycle xs 42)
(shift-left-cycle xs 2)
(shift-left-cycle xs -2)
(shift-left-cycle xs 0)
(shift-left-cycle xs 42)
]
@defproc[
(shifts
[lst list?]

@ -1,17 +0,0 @@
#lang racket/base
(require (for-syntax
racket/base
"private/syntax-utils.rkt")
"define.rkt")
(define+provide+safe (make-caching-proc base-proc)
(procedure? . -> . procedure?)
(let ([cache (make-hash)])
(make-keyword-procedure
(λ (kws kw-args . args)
(hash-ref! cache (list* kws kw-args args) (λ () (keyword-apply base-proc kws kw-args args)))))))
(provide+safe define/caching)
(define-syntax (define/caching stx)
(with-syntax ([(ID LAMBDA-EXPR) (lambdafy stx)])
#'(define ID (make-caching-proc LAMBDA-EXPR))))

@ -1,4 +0,0 @@
#lang racket/base
(require "private/syntax-utils.rkt")
(require+provide/safe "coerce/base.rkt" "coerce/contract.rkt")

@ -1,123 +0,0 @@
#lang racket/base
(require (for-syntax
racket/base
racket/syntax)
racket/stream
racket/generic
net/url
racket/sequence
"../unstable/len.rkt"
"../define.rkt")
(module+ safe (require racket/contract))
(define-syntax-rule (make-coercion-error-handler func funcish val)
(λ (exn) (raise-argument-error 'func (symbol->string 'funcish) val)))
(define (disjoin . preds) (λ (x) (ormap (λ (pred) (pred x)) preds)))
(define (conjoin . preds) (λ (x) (andmap (λ (pred) (pred x)) preds)))
(define-generics+provide+safe stringish
(any/c . -> . string?)
(->string stringish)
#:fast-defaults
([string? (define ->string values)]
[(disjoin null? void?) (define (->string x) "")]
[symbol? (define ->string symbol->string)]
[number? (define ->string number->string)]
[path? (define ->string path->string)]
[(disjoin char? bytes?) (define (->string x) (format "~a" x))]
[url? (define ->string url->string)]))
(define (real->int x) (inexact->exact (floor x)))
(define (string->int x) (let ([strnum (string->number x)])
(unless (real? strnum)
(raise-argument-error '->int "eligible string" x))
(real->int strnum)))
(define-generics+provide+safe intish
(any/c . -> . integer?)
(->int intish)
#:fast-defaults
([(disjoin integer? real?) (define ->int real->int)]
[complex? (define ->int (compose1 real->int real-part))]
[string? (define ->int string->int)]
[(disjoin symbol? path? bytes?) (define ->int (compose1 string->int ->string))]
[char? (define ->int char->integer)]
[lengthable? (define (->int x)
(with-handlers ([exn:fail? (make-coercion-error-handler ->int intish? x)])
(len x)))]))
(define-generics+provide+safe symbolish
(any/c . -> . symbol?)
(->symbol symbolish)
#:fast-defaults
([symbol? (define ->symbol values)]
[stringish? (define (->symbol x)
(with-handlers ([exn:fail? (make-coercion-error-handler ->symbol symbolish? x)])
(string->symbol (->string x))))]))
(define-generics+provide+safe pathish
(any/c . -> . path?)
(->path pathish)
#:fast-defaults
([path? (define ->path values)]
[stringish? (define (->path x)
(with-handlers ([exn:fail? (make-coercion-error-handler ->path pathish? x)])
(if (url? x)
(url->path x)
(string->path (->string x)))))]))
(define-generics+provide+safe urlish
(any/c . -> . url?)
(->url urlish)
#:fast-defaults
([url? (define ->url values)]
[stringish? (define (->url x)
(with-handlers ([exn:fail? (make-coercion-error-handler ->url urlish? x)])
(string->url (->string x))))]))
(define-generics+provide+safe complete-pathish
(any/c . -> . complete-path?)
(->complete-path complete-pathish)
#:fast-defaults
([(conjoin path? complete-path?)
;; caution: plain `complete-path?` returns #t for path strings,
;; so also check `path?`
(define ->complete-path values)]
[stringish? (define (->complete-path x)
(with-handlers ([exn:fail? (make-coercion-error-handler ->complete-path complete-pathish? x)])
(path->complete-path (->path x))))]))
(define-generics+provide+safe listish
(any/c . -> . list?)
(->list listish)
#:fast-defaults
([list? (define ->list values)]
[string? (define ->list list)]
[vector? (define ->list vector->list)]
[hash? (define ->list hash->list)]
[integer? (define ->list list)]
[sequence? (define ->list sequence->list)]
[stream? (define ->list stream->list)]
[(λ (x) #t) (define ->list list)]))
(define-generics+provide+safe vectorish
(any/c . -> . vector?)
(->vector vectorish)
#:fast-defaults
([vector? (define ->vector values)]
[listish? (define (->vector x)
(with-handlers ([exn:fail? (make-coercion-error-handler ->vector vectorish? x)])
(list->vector (->list x))))]))
(define+provide+safe (->boolean x)
(any/c . -> . boolean?)
(and x #t))

@ -1,46 +0,0 @@
#lang racket/base
(require (for-syntax racket/base racket/syntax) racket/contract "../define.rkt" "base.rkt")
(define-syntax-rule (make-blame-handler PROC EXPECTED)
(λ (b)
(λ (x) (with-handlers ([exn:fail? (λ (exn)
(raise-blame-error b x
'(expected: "~a" given: "~e")
EXPECTED x))])
(PROC x)))))
(provide+safe make-coercion-contract)
(define-syntax (make-coercion-contract stx)
(syntax-case stx ()
[(_ STEM COERCE-PROC)
(with-syntax ([COERCE/STEM? (format-id stx "coerce/~a?" #'STEM)]
[STEMISH? (format-id stx "~aish?" #'STEM)])
#'(make-contract
#:name 'COERCE/STEM?
#:projection (make-blame-handler COERCE-PROC 'STEMISH?)))]
[(MACRO-NAME STEM)
(with-syntax ([->STEM (format-id stx "->~a" #'STEM)])
#'(MACRO-NAME STEM ->STEM))]))
(define-syntax (define+provide-coercion-contract stx)
(syntax-case stx ()
[(_ STEM)
(with-syntax ([COERCE/STEM? (format-id stx "coerce/~a?" #'STEM)])
#'(begin
(provide+safe COERCE/STEM?)
(define COERCE/STEM? (make-coercion-contract STEM))))]))
(define-syntax-rule (define+provide-coercion-contracts STEM ...)
(begin (define+provide-coercion-contract STEM) ...))
(define+provide-coercion-contracts int
string
symbol
path
boolean
list)

@ -1,184 +0,0 @@
#lang racket/base
(require racket/string
(for-syntax racket/base)
"define.rkt")
(provide+safe report report/time time-name
report/line report/file
report* report*/line report*/file
report-apply repeat time-repeat time-repeat* time-name time-named time-avg compare)
(define (stringify-results expr-results)
(format (if (= 1 (length expr-results))
"~a"
"(values ~a)") (string-join (for/list ([r (in-list expr-results)])
(format "~v" r)) " ")))
(define-syntax (report stx)
(syntax-case stx ()
[(MACRO EXPR) #'(MACRO EXPR EXPR)]
[(_ EXPR NAME)
#'(let ([expr-results (call-with-values (λ () EXPR) list)])
(eprintf "~a = ~a\n" 'NAME (stringify-results expr-results))
(apply values expr-results))]))
(define-syntax (report/time stx)
(syntax-case stx ()
[(MACRO EXPR) #'(MACRO EXPR EXPR)]
[(_ EXPR NAME)
#'(let* ([op (open-output-string)]
[expr-results (parameterize ([current-output-port op])
(time (call-with-values (λ () EXPR) list)))])
(eprintf "~a = ~a [~a]\n" 'NAME (stringify-results expr-results) (string-trim (get-output-string op)))
(apply values expr-results))]))
(define-syntax (report/line stx)
(syntax-case stx ()
[(MACRO EXPR) #'(MACRO EXPR EXPR)]
[(_ EXPR NAME)
#`(let ([expr-results (call-with-values (λ () EXPR) list)])
(eprintf "~a = ~a on line ~a\n" 'NAME (stringify-results expr-results) #,(syntax-line #'EXPR))
(apply values expr-results))]))
(define-syntax (report/file stx)
(syntax-case stx ()
[(MACRO EXPR) #'(MACRO EXPR EXPR)]
[(_ EXPR NAME)
#`(let ([expr-results (call-with-values (λ () EXPR) list)])
(eprintf "~a = ~a on line ~a in \"~a\"\n" 'NAME (stringify-results expr-results)
#,(syntax-line #'EXPR)
'#,(syntax-source #'EXPR))
(apply values expr-results))]))
(define-syntax-rule (define-multi-version MULTI-NAME NAME)
(define-syntax-rule (MULTI-NAME x (... ...))
(begin (NAME x) (... ...))))
(define-multi-version report* report)
(define-multi-version report*/line report/line)
(define-multi-version report*/file report/file)
(define-syntax (report-apply stx)
(syntax-case stx ()
[(_ PROC EXPR)
#'(let ([lst EXPR])
(report (apply PROC lst) (apply PROC EXPR))
lst)]
[(_ PROC EXPR #:line)
#'(let ([lst EXPR])
(report (apply PROC lst) (apply PROC EXPR) #:line)
lst)]))
(define-syntax-rule (repeat NUM EXPR ...)
(for/last ([i (in-range NUM)])
EXPR ...))
(define-syntax-rule (time-repeat NUM EXPR ...)
(time (repeat NUM EXPR ...)))
(define (parse-time-str str)
(for/list ([num (in-port read (open-input-string str))]
#:when (number? num))
num))
(define-syntax-rule (time-avg NUM EXPR ...)
(let ([n NUM])
(define-values (strs results)
(for/lists (strs results)
([i n])
(let* ([op (open-output-string)]
[expr-results (parameterize ([current-output-port op])
(time (call-with-values (λ () EXPR ...) values)))])
(values (get-output-string op) expr-results))))
(displayln (apply format "~a: cpu time: ~a real time: ~a gc time: ~a (avg of ~a)"
(append
(list (car '(EXPR ...)))
(for/list ([vals (apply map list (map parse-time-str strs))])
(floor (/ (apply + vals) n)))
(list n))))
(car (reverse results))))
(define-syntax (time-repeat* stx)
(syntax-case stx ()
[(_ NUM EXPR ...)
#'(let ([n NUM])
(values (time-repeat n EXPR) ...))]))
(define-syntax (time-name stx)
(syntax-case stx ()
[(_ NAME EXPR ...)
#'(let* ([op (open-output-string)]
[expr-results (parameterize ([current-output-port op])
(time (call-with-values (λ () EXPR ...) values)))])
(display (format "~a: ~a" 'NAME (get-output-string op)))
expr-results)]))
(define-syntax (time-named stx)
(syntax-case stx ()
[(_ EXPR ...)
#'(let* ([op (open-output-string)]
[expr-results (parameterize ([current-output-port op])
(time (call-with-values (λ () EXPR ...) values)))])
(display (format "~a: ~a" (car '(EXPR ...)) (get-output-string op)))
expr-results)]))
(define-syntax (compare stx)
(syntax-case stx ()
[(_ EXPR ID ID-ALT ...)
#'(values EXPR (let ([ID ID-ALT]) EXPR) ...)]))
(module reader racket/base
(require syntax/module-reader racket/syntax version/utils)
(provide (rename-out [debug-read read]
[debug-read-syntax read-syntax]
[debug-get-info get-info]))
(define current-metalang-scope-flipper (make-parameter values))
(define (wrap-reader reader)
(λ args
(parameterize ([current-readtable (make-debug-readtable (current-readtable))]
[current-metalang-scope-flipper (make-syntax-introducer)])
(define stx (apply reader args))
(define proc (if (and (syntax? stx) (version<=? "6.2.900.4" (version)))
(current-metalang-scope-flipper)
values))
(proc stx))))
(define-values (debug-read debug-read-syntax debug-get-info)
(make-meta-reader
'sugar/debug
"language path"
(λ (bstr) ; copy of `lang-reader-module-paths`, only available since 6.7
(let* ([str (bytes->string/latin-1 bstr)]
[sym (string->symbol str)])
(and (module-path? sym)
(vector
;; try submod first:
`(submod ,sym reader)
;; fall back to /lang/reader:
(string->symbol (string-append str "/lang/reader"))))))
wrap-reader
wrap-reader
(λ (proc)
(λ (key defval)
(case key
[else (if proc (proc key defval) defval)])))))
(define report-char #\R)
(define (make-debug-readtable [rt (current-readtable)])
(make-readtable rt report-char 'dispatch-macro report-proc))
(define (another-report-char? ip) (and (char=? (peek-char ip) report-char) (read-char ip)))
(define (report-proc trigger-char ip src ln col pos)
(define flip-metalang-scope (current-metalang-scope-flipper))
(flip-metalang-scope (with-syntax ([REPORT-ID (cond
[(not (another-report-char? ip)) 'report] ; #R...
[(not (another-report-char? ip)) 'report/line] ; #RR...
[else 'report/file])] ; #RRR...
[STX (flip-metalang-scope (read-syntax/recursive src ip))])
#'(let ()
(local-require (only-in sugar/debug REPORT-ID))
(REPORT-ID STX))))))

@ -1,71 +0,0 @@
#lang racket/base
(require (for-syntax racket/base
racket/syntax
syntax/strip-context
"private/syntax-utils.rkt")
racket/contract)
(define-syntax (make-safe-module stx)
(syntax-case stx ()
[(_ [ID CONTRACT])
;; need to put `racket/contract` inside calling location's context
(with-syntax ([RACKET/CONTRACT (datum->syntax #'ID 'racket/contract)])
#'(module+ safe
(require RACKET/CONTRACT)
(provide (contract-out [ID CONTRACT]))))]
[(_ ID)
#'(module+ safe
(provide ID))]))
(define-syntax (define+provide+safe stx)
(with-syntax ([(ID CONTRACT LAMBDA-EXP) (lambdafy-with-contract stx)])
#'(begin
(define ID LAMBDA-EXP)
(provide+safe [ID CONTRACT]))))
;; for previously defined identifiers
;; takes args like (provide+safe [id contract]) or just (provide+safe id)
;; any number of args.
(define-syntax-rule (provide+safe THING ...)
(begin
(provide+safe/once THING) ...))
;; `provide+safe` might have interleaved ids or [id contract] args so handle them individually.
(define-syntax (provide+safe/once stx)
(with-syntax ([(ID MSM-ARG) (syntax-case stx ()
[(_ [ID contract])
#'(ID [ID contract])]
[(_ id)
#'(id id)])])
#'(begin
(provide ID)
(make-safe-module MSM-ARG))))
(define-syntax (define+provide/contract stx)
(with-syntax* ([(ID CONTRACT LAMBDA-EXP) (lambdafy-with-contract stx)]
[RACKET/CONTRACT (datum->syntax #'ID 'racket/contract)])
#'(begin
(require RACKET/CONTRACT)
(provide (contract-out [ID CONTRACT]))
(define ID LAMBDA-EXP))))
(define-syntax (define/contract+provide stx)
(with-syntax* ([(ID CONTRACT LAMBDA-EXP) (lambdafy-with-contract stx)]
[RACKET/CONTRACT (datum->syntax #'ID 'racket/contract)])
#'(begin
(require RACKET/CONTRACT)
(provide ID)
(define/contract ID CONTRACT LAMBDA-EXP))))
(define-syntax (define+provide stx)
(with-syntax ([(ID LAMBDA-EXP) (lambdafy stx)])
#'(begin
(provide ID)
(define ID LAMBDA-EXP))))
(provide+safe make-safe-module
define+provide+safe
provide+safe
define+provide/contract
define/contract+provide
define+provide)

@ -1,100 +0,0 @@
#lang racket/base
(require racket/list
racket/match
(except-in racket/path filename-extension)
"define.rkt"
"coerce/base.rkt")
;; this is identical to `filename-extension` in `racket/path`
;; but will not treat hidden files as an extension (which is a bug)
(define (filename-extension name)
(match (file-name-from-path name)
[(? path-for-some-system? filename)
(=> resume)
(match (regexp-match #rx#".[.]([^.]+)$" (path->bytes filename))
[(list _ second) second]
[_ (resume)])]
[_ #false]))
(module+ test
(require rackunit)
(require (prefix-in rp: racket/path))
(check-equal? (rp:filename-extension (string->path ".foo")) #"foo") ; bad behavior
(check-false (filename-extension (string->path ".foo")))) ; good behavior
;; does path have a certain extension, case-insensitively
(define+provide+safe (has-ext? x ext)
(pathish? stringish? . -> . boolean?)
(unless (pathish? x)
(raise-argument-error 'has-ext? "pathish?" x))
(unless (stringish? ext)
(raise-argument-error 'has-ext? "stringish?" ext))
(define ext-of-path (filename-extension (->path x)))
(and ext-of-path (string=? (string-downcase (bytes->string/utf-8 ext-of-path))
(string-downcase (->string ext)))))
;; get file extension as a string, or return #f
;; (consistent with filename-extension behavior)
(define+provide+safe (get-ext x)
(pathish? . -> . (or/c #f string?))
(unless (pathish? x)
(raise-argument-error 'get-ext "pathish?" x))
(cond
[(filename-extension (->path x)) => bytes->string/utf-8]
[else #false]))
;; todo: add extensions
(provide+safe binary-extensions)
(define binary-extensions
(map symbol->string '(gif jpg jpeg mp3 png zip pdf ico tar ai eps exe)))
(define+provide+safe (has-binary-ext? x)
(pathish? . -> . boolean?)
(unless (pathish? x)
(raise-argument-error 'has-binary-ext? "pathish?" x))
(for/or ([ext (in-list binary-extensions)]
#:when (has-ext? (->path x) ext))
#true))
;; put extension on path
;; use local contract here because this function is used within module
(define+provide+safe (add-ext x ext)
(stringish? stringish? . -> . pathish?)
(unless (stringish? x)
(raise-argument-error 'add-ext "stringish?" x))
(unless (stringish? ext)
(raise-argument-error 'add-ext "stringish?" ext))
(->path (string-append (->string x) "." (->string ext))))
(define (starts-with? str starter)
(define pat (regexp (format "^~a" (regexp-quote starter))))
(and (regexp-match pat str) #true))
(define (path-hidden? path)
((->string (file-name-from-path path)) . starts-with? . "."))
(define (change-hide-state new-hide-state path)
(define reversed-path-elements (reverse (explode-path path)))
(apply build-path (append (reverse (cdr reversed-path-elements))
(list (if (eq? new-hide-state 'hide)
(format ".~a" (->string (car reversed-path-elements)))
(regexp-replace #rx"^." (->string (car reversed-path-elements)) ""))))))
;; take one extension off path
(define+provide+safe (remove-ext x)
(pathish? . -> . path?)
;; `path-replace-suffix` incorrectly thinks any leading dot counts as a file extension
;; when it might be a hidden path.
;; so handle hidden paths specially.
;; this is fixed in later Racket versions with `path-replace-extension`
(match (->path x)
[(? path-hidden? path) (change-hide-state 'hide (path-replace-suffix (change-hide-state 'unhide path) ""))]
[path (path-replace-suffix path "")]))
;; take all extensions off path
(define+provide+safe (remove-ext* x)
(pathish? . -> . path?)
(let loop ([path (->path x)])
(match (remove-ext path)
[(== path) path]
[path-reduced (loop path-reduced)])))

@ -1,3 +0,0 @@
#lang info
(define scribblings '(("scribblings/sugar.scrbl" ())))
(define compile-omit-paths '("test"))

@ -1,217 +0,0 @@
#lang racket/base
(require (for-syntax
racket/base)
racket/list
racket/match
racket/function
"define.rkt")
(define (increasing-nonnegative-list? x)
(and (list? x) (or (empty? x) (apply < -1 x))))
(define+provide+safe (trimf xs test-proc)
(list? procedure? . -> . list?)
(unless (list? xs)
(raise-argument-error 'trimf "list?" xs))
(dropf-right (dropf xs test-proc) test-proc))
(define (slicef-and-filter-split-helper xs pred [separate-negated? #f])
(let loop ([xs xs][negating? #f][acc empty][negated-acc empty])
(match xs
[(? empty?) (if separate-negated?
(values (reverse acc) (reverse negated-acc))
(reverse acc))]
[(list* (? (if negating? (negate pred) pred) pred-xs) ... other-xs)
(cond
[(and negating? separate-negated?)
(loop other-xs
(not negating?)
acc
(match pred-xs
[(? empty?) negated-acc]
[_ (cons pred-xs negated-acc)]))]
[else
(loop other-xs
(not negating?)
(match pred-xs
[(? empty?) acc]
[_ (cons pred-xs acc)])
negated-acc)])])))
(define+provide+safe (slicef xs pred)
(list? procedure? . -> . (listof list?))
(unless (list? xs)
(raise-argument-error 'slicef "list?" xs))
(slicef-and-filter-split-helper xs pred))
(define+provide+safe (slicef-at xs pred [force? #f])
((list? procedure?) (boolean?) . ->* . (listof list?))
(unless (list? xs)
(raise-argument-error 'slicef-at "list?" xs))
(unless (procedure? pred)
(raise-argument-error 'slicef-at "procedure?" pred))
(let loop ([xs xs][acc empty])
(match xs
[(== empty) (reverse acc)]
[(list* (? pred pred-x) (? (negate pred) not-pred-xs) ... tail)
(loop tail (cons (cons pred-x not-pred-xs) acc))]
[(list* (? (negate pred) not-pred-xs) ... tail)
(loop tail (if force? acc (cons not-pred-xs acc)))])))
(define+provide+safe (slicef-after xs pred [force? #f])
((list? procedure?) (boolean?) . ->* . (listof list?))
(unless (list? xs)
(raise-argument-error 'slicef-after "list?" xs))
(unless (procedure? pred)
(raise-argument-error 'slicef-after "procedure?" pred))
(let loop ([xs xs][acc empty])
(match xs
[(== empty) (reverse acc)]
[(list* (? (negate pred) not-pred-xs) ... (? pred pred-x) tail)
(loop tail (cons (append not-pred-xs (list pred-x)) acc))]
[tail (loop empty (if force? acc (cons tail acc)))])))
(define+provide+safe (slice-at xs len [force? #f])
((list? exact-nonnegative-integer?) (boolean?) . ->* . (listof list?))
(unless (list? xs)
(raise-argument-error 'slice-at "list?" xs))
(unless (and (integer? len) (positive? len))
(raise-argument-error 'slice-at "positive integer for sublist length" len))
(let loop ([xs xs][slices empty])
(if (< (length xs) len)
(reverse (if (or force? (empty? xs))
slices
(cons xs slices)))
(match/values (split-at xs len)
[(subxs rest) (loop rest (cons subxs slices))]))))
(define+provide+safe (partition* pred xs)
(predicate/c list? . -> . (values list? list?))
(unless (list? xs)
(raise-argument-error 'partition* "list?" xs))
(slicef-and-filter-split-helper xs pred 'drop-negated))
(define+provide+safe (filter-split xs pred)
(list? predicate/c . -> . (listof list?))
(unless (list? xs)
(raise-argument-error 'filter-split "list?" xs))
;; same idea as slicef, but the negated items are dropped
(define-values (negated-pred-xs _) (partition* (negate pred) xs))
negated-pred-xs)
(define+provide+safe (frequency-hash xs)
(list? . -> . hash?)
(unless (list? xs)
(raise-argument-error 'frequency-hash "list?" xs))
(define counter (make-hash))
(for ([item (in-list xs)])
(hash-update! counter item add1 0))
counter)
(define (->list x)
(match x
[(? list? x) x]
[(? vector?) (vector->list x)]
[(? string?) (string->list x)]
[else (raise-argument-error '->list "item that can be converted to list" x)]))
(define+provide+safe (members-unique? x)
((or/c list? vector? string?) . -> . boolean?)
(match (->list x)
[(? list? x) (= (length (remove-duplicates x)) (length x))]
[_ (raise-argument-error 'members-unique? "list, vector, or string" x)]))
(define+provide+safe (members-unique?/error x)
((or/c list? vector? string?) . -> . boolean?)
(match (members-unique? x)
[(== #false)
(define duplicate-keys (filter values (hash-map (frequency-hash (->list x))
(λ (element freq) (and (> freq 1) element)))))
(error (string-append "members-unique? failed because " (if (= (length duplicate-keys) 1)
"item isn't"
"items aren't") " unique:") duplicate-keys)]
[result result]))
(provide+safe values->list)
(define-syntax (values->list stx)
(syntax-case stx ()
[(_ VALUES-EXPR) #'(call-with-values (λ () VALUES-EXPR) list)]))
(define+provide+safe (sublist xs i j)
(list? exact-nonnegative-integer? exact-nonnegative-integer? . -> . list?)
(unless (list? xs)
(raise-argument-error 'sublist "list?" xs))
(cond
[(> j (length xs)) (error 'sublist (format "ending index ~a exceeds length of list" j))]
[(>= j i) (for/list ([(x idx) (in-indexed xs)]
#:when (<= i idx (sub1 j)))
x)]
[else (raise-argument-error 'sublist (format "starting index larger than ending index" (list i j)))]))
(define+provide+safe (break-at xs bps-in)
(list? any/c . -> . (listof list?))
(unless (list? xs)
(raise-argument-error 'break-at "list" xs))
(define bps ((if (list? bps-in) values list) bps-in))
(when (ormap (λ (bp) (<= (length xs) bp)) bps)
(raise-argument-error 'break-at
(format "breakpoints not greater than or equal to input list length = ~a" (length xs)) bps))
(unless (increasing-nonnegative-list? bps)
(raise-argument-error 'break-at "increasing-nonnegative-list" bps))
;; easier to do back to front, because then the list index for each item won't change during the recursion
;; cons a zero onto bps (which may already start with zero) and then use that as the terminating condition
;; because breaking at zero means we've reached the start of the list
(let loop ([xs xs][bps (reverse (cons 0 bps))][acc empty])
(match bps
[(cons (? zero?) _) (cons xs acc)] ; return whatever's left, because no more splits are possible
[_ (match/values (split-at xs (car bps))
[(head tail) (loop head (cdr bps) (cons tail acc))])])))
(define (shift-base xs how-far fill-item cycle caller)
(unless (list? xs)
(raise-argument-error caller "list?" xs))
(define abs-how-far (if cycle
(modulo (abs how-far) (length xs))
(abs how-far)))
(define (make-fill thing) (if cycle thing (make-list abs-how-far fill-item)))
(cond
[(> abs-how-far (length xs))
(raise-argument-error caller
(format "index not larger than list length ~a" (length xs))
(* (if (eq? caller 'shift-left) -1 1) how-far))]
[(zero? how-far) xs]
[(positive? how-far)
(match/values (split-at-right xs abs-how-far)
[(head tail) (append (make-fill tail) head)])]
[else ; how-far is negative
(match/values (split-at xs abs-how-far)
[(head tail) (append tail (make-fill head))])]))
(define+provide+safe (shift xs how-far [fill-item #f] [cycle #f])
((list? integer?) (any/c boolean?) . ->* . list?)
(shift-base xs how-far fill-item cycle 'shift))
(define+provide+safe (shift-left xs how-far [fill-item #f] [cycle #f])
((list? integer?) (any/c boolean?) . ->* . list?)
(shift-base xs (- how-far) fill-item cycle 'shift-left))
(define+provide+safe (shift-cycle xs how-far)
(list? integer? . -> . list?)
(shift-base xs how-far #false #true 'shift-cycle))
(define+provide+safe (shift-left-cycle xs how-far)
(list? integer? . -> . list?)
(shift-base xs (- how-far) #false #true 'shift-left-cycle))
(define+provide+safe (shifts xs how-fars [fill-item #f] [cycle #f])
((list? (listof integer?)) (any/c boolean?) . ->* . (listof list?))
(unless (list? xs)
(raise-argument-error 'shifts "list?" xs))
(map (λ (how-far) (shift xs how-far fill-item cycle)) how-fars))
(define+provide+safe (shift/values xs shift-amount-or-amounts [fill-item #f] [cycle #f])
((list? (or/c (listof integer?) integer?)) (any/c boolean?) . ->* . any)
(apply values ((if (list? shift-amount-or-amounts)
shifts
shift) xs shift-amount-or-amounts fill-item cycle)))

@ -1,11 +0,0 @@
#lang racket/base
(require "private/syntax-utils.rkt")
(require+provide/safe "cache.rkt"
"coerce.rkt"
"debug.rkt"
"define.rkt"
"file.rkt"
"list.rkt"
"test.rkt"
"xml.rkt")

@ -1,42 +0,0 @@
#lang racket/base
(require (for-syntax racket/base)
syntax/define)
(provide (except-out (all-defined-out) values->list))
(define-syntax-rule (require+provide/safe MODNAME ...)
(begin
(begin
(require MODNAME)
(provide (all-from-out MODNAME))
(module+ safe
(require (submod MODNAME safe))
(provide (all-from-out (submod MODNAME safe))))) ...))
(define-syntax (values->list stx)
(syntax-case stx ()
[(_ values-expr) #'(call-with-values (λ () values-expr) list)]))
;; convert calling pattern to form (id contract body-exp)
;; hoist contract out of lambda-exp entirely
(define (lambdafy-with-contract stx)
(syntax-case stx ()
[(_ ID-EXP CONTRACT LAMBDA-EXP) ; matches exactly three args after `define`
;; `normalize-definition` can't handle the acceptable `define/contract` pattern of id, contract, lambda exp after the `define`.
;; so extract the contract, and then put id & lambda-exp back together, and let `normalize-definition` destructure as usual.
(with-syntax ([(NEW-ID NEW-LAMBDA-EXP)
(values->list (normalize-definition #'(_ ID-EXP LAMBDA-EXP) (datum->syntax stx 'λ) #t #t))])
#'(NEW-ID CONTRACT NEW-LAMBDA-EXP))]
;; matches two or more args (three-arg case handled above)
[(_ ID-EXP . BODY)
(with-syntax ([(NEW-ID (LAMBDA ARGS CONTRACT . NEW-BODY))
(values->list (normalize-definition stx (datum->syntax stx 'λ) #t #t))])
;; because the macro provides the `lambda` below, it takes the local srcloc by default
;; so `syntax/loc` applies the original srcloc (associated with args and body-exp)
#`(NEW-ID CONTRACT #,(syntax/loc #'ID-EXP (LAMBDA ARGS . NEW-BODY))))]
;; matches zero or one arguments
[_ (raise-syntax-error 'define-macro "not enough arguments")]))
(define (lambdafy stx)
(with-syntax ([(ID LAMBDA-EXP)
(values->list (normalize-definition stx (datum->syntax stx 'λ) #true #true))])
#'(ID LAMBDA-EXP)))

@ -1,44 +0,0 @@
#lang racket/base
(require (for-syntax
racket/base
racket/syntax
syntax/strip-context)
"define.rkt")
(provide+safe module-test-external
module-test-internal
module-test-internal+external)
;; tests using module-boundary contracts
(define-syntax (module-test-external stx)
(syntax-case stx ()
[(_ EXPR ...)
(replace-context
stx
(with-syntax ([MOD-NAME (syntax-e (generate-temporary))])
#'(begin
(module* MOD-NAME racket/base
(require (submod ".."))
(require rackunit)
EXPR ...)
(module+ test
(require (submod ".." MOD-NAME))))))]))
(define-syntax (module-test-internal stx)
(syntax-case stx ()
[(_ EXPR ...)
(replace-context
stx
#'(begin
(module+ test
(require rackunit)
EXPR ...)))]))
(define-syntax (module-test-internal+external stx)
(syntax-case stx ()
[(_ EXPR ...)
(replace-context
stx
#'(begin
(module-test-internal EXPR ...)
(module-test-external EXPR ...)))]))

@ -1,266 +0,0 @@
#lang racket
(require (for-syntax racket/syntax
syntax/strip-context))
(define-syntax (eval-with-and-without-contracts stx)
(syntax-case stx ()
[(_ EXPRS ...)
(with-syntax ([MODULE-WITHOUT-CONTRACTS (generate-temporary)]
[MODULE-WITH-CONTRACTS (generate-temporary)])
(replace-context stx
#'(begin
(module MODULE-WITHOUT-CONTRACTS racket
(require rackunit "../main.rkt" net/url)
EXPRS ...)
(require 'MODULE-WITHOUT-CONTRACTS)
(module MODULE-WITH-CONTRACTS racket
(require rackunit (submod "../main.rkt" safe) net/url)
EXPRS ...)
(require 'MODULE-WITH-CONTRACTS))))]))
(eval-with-and-without-contracts
(check-equal? (->int 42) 42)
(check-equal? (->int 42.1) 42)
(check-equal? (->int 42+3i) 42)
(check-equal? (->int "42") 42)
(check-equal? (->int '42) 42)
(check-equal? (->int (string->path "42")) 42)
(check-equal? (->int #\A) 65)
(check-equal? (->int (make-list 42 null)) 42)
(check-equal? (->string "foo") "foo")
(check-equal? (->string #"foo") "foo")
(check-equal? (->string '()) "")
(check-equal? (->string (void)) "")
(check-equal? (->string 'foo) "foo")
(check-equal? (->string 123) "123")
(check-equal? (->string (string->url "foo/bar.html")) "foo/bar.html")
(define file-name-as-text "foo.txt")
(check-equal? (->string (string->path file-name-as-text)) file-name-as-text)
(check-equal? (->string #\¶) "")
(check-equal? (->path "foo") (string->path "foo"))
(check-equal? (->path #"foo") (string->path "foo"))
(check-equal? (->path 'foo) (string->path "foo"))
(check-equal? (->path 123) (string->path "123"))
(check-equal? (->path (string->url "foo/bar.html")) (string->path "foo/bar.html"))
(check-equal? (->path (string->url "/foo/bar.html")) (string->path "/foo/bar.html"))
(check-equal? (->list '(1 2 3)) '(1 2 3))
(check-equal? (->list (list->vector '(1 2 3))) '(1 2 3))
(check-not-false (andmap (lambda (e) (member e '(1 2 3))) (->list (set 1 2 3))))
(check-equal? (->list "foo") (list "foo"))
(check-true (->boolean #t))
(check-false (->boolean #f))
(check-true (->boolean "#f"))
(check-true (->boolean "foo"))
(check-true (->boolean '()))
(check-true (->boolean '(1 2 3)))
(module dp racket/base
(require "../define.rkt")
(define+provide (dp-f x #:y [y 42] . zs)
(apply + x y zs)))
(require 'dp)
(check-equal? (dp-f 1 #:y 0 2 3) 6)
(module dps racket/base
(require sugar/define)
(define+provide+safe (dps-f x #:y [y 42] . zs)
((integer?) (#:y integer?) #:rest (listof integer?) . ->* . integer?)
(apply + x y zs)))
(require 'dps)
(check-equal? (dps-f 1 #:y 0 2 3) 6)
(require (prefix-in safe: (submod 'dps safe)))
(check-equal? (safe:dps-f 1 #:y 0 2 3) 6)
(check-exn exn:fail? (λ _ (safe:dps-f 'foo)))
(module dpsb racket/base
(require sugar/define)
(define+provide+safe dpsb-f
((integer?) (#:y integer?) #:rest (listof integer?) . ->* . integer?)
(λ(x #:y [y 42] . zs) (apply + x y zs))))
(require 'dpsb)
(check-equal? (dpsb-f 1 #:y 0 2 3) 6)
(require (prefix-in safe: (submod 'dpsb safe)))
(check-equal? (safe:dpsb-f 1 #:y 0 2 3) 6)
(check-exn exn:fail? (λ _ (safe:dpsb-f 'foo)))
(module ps racket/base
(require "../define.rkt")
(provide+safe [ps-f ((integer?) (#:y integer?) #:rest (listof integer?) . ->* . integer?)])
(define (ps-f x #:y [y 42] . zs)
(apply + x y zs)))
(require 'ps)
(check-equal? (ps-f 1 #:y 0 2 3) 6)
(require (prefix-in safe: (submod 'ps safe)))
(check-equal? (safe:ps-f 1 #:y 0 2 3) 6)
(check-exn exn:fail? (λ _ (safe:ps-f 'foo)))
(module dcp racket/base
(require "../define.rkt" rackunit)
(define/contract+provide (dcp-f x #:y [y 42] . zs)
((integer?) (#:y integer?) #:rest (listof integer?) . ->* . integer?)
(apply + x y zs))
(check-exn exn:fail? (λ _ (dcp-f 'foo))))
(require 'dcp)
(check-equal? (dcp-f 1 #:y 0 2 3) 6)
(check-exn exn:fail? (λ _ (dcp-f 'foo)))
(module dpc racket/base
(require "../define.rkt" rackunit)
(define+provide/contract (dpc-f x #:y [y 42] . zs)
((integer?) (#:y integer?) #:rest (listof integer?) . ->* . list?)
(list* x y zs))
(check-equal? (dpc-f 'foo) '(foo 42))) ; locally, no contract triggered
(require 'dpc)
(check-equal? (dpc-f 1) '(1 42))
(check-exn exn:fail? (λ _ (dpc-f 'foo)))
(check-true (members-unique? '(a b c)))
(check-false (members-unique? '(a b c c)))
(check-true (members-unique? "zoey"))
(check-false (members-unique? "zooey"))
(check-equal? (trimf (list 4 1 2 3 4) even?) '(1 2 3))
(check-equal? (trimf (list 1 3 2 4 5 6 8 9 13) odd?) '(2 4 5 6 8))
(check-equal? (filter-split '(1 1 2 3 4 4 5 6) even?) '((1 1)(3)(5)))
(check-equal? (let-values ([(preds not-preds) (partition* even? '(1 1 2 3 4 4 5 6))])
(list preds not-preds)) (list '((2)(4 4)(6)) '((1 1)(3)(5))))
(define foo-path-strings '("foo" "foo.txt" "foo.bar" "foo.bar.txt"))
(match-define (list foo-path foo.txt-path foo.bar-path foo.bar.txt-path) (map ->path foo-path-strings))
;; test the sample paths before using them for other tests
(define foo-paths (list foo-path foo.txt-path foo.bar-path foo.bar.txt-path))
(for-each check-equal? (map ->string foo-paths) foo-path-strings)
(check-false (has-ext? foo-path 'txt))
(check-true (foo.txt-path . has-ext? . 'txt))
(check-true ((->path "foo.TXT") . has-ext? . 'txt))
(check-true (has-ext? foo.bar.txt-path 'txt))
(check-false (foo.bar.txt-path . has-ext? . 'doc)) ; wrong extension
(check-exn exn:fail:contract? (λ () (has-ext? #f "foo")))
(check-exn exn:fail:contract? (λ () (has-ext? "foo" #f)))
(check-equal? (get-ext (->path "foo.txt")) "txt")
(check-false (get-ext "foo"))
(check-false (get-ext ".foo"))
(check-exn exn:fail:contract? (λ () (get-ext #f)))
(check-equal? (add-ext (string->path "foo") "txt") (string->path "foo.txt"))
(check-exn exn:fail:contract? (λ () (add-ext "foo" #f)))
(check-exn exn:fail:contract? (λ () (add-ext #f "foo" )))
(check-equal? (remove-ext foo-path) foo-path)
(check-equal? (remove-ext (->path ".foo.txt")) (->path ".foo"))
(check-equal? (remove-ext foo.txt-path) foo-path)
(check-equal? (remove-ext foo.bar.txt-path) foo.bar-path)
(check-not-equal? (remove-ext foo.bar.txt-path) foo-path) ; does not remove all extensions
;; test remove-ext on paths that have "." prefix
(check-equal? (remove-ext (->path "./foo.txt.bar")) (->path "./foo.txt"))
(check-equal? (remove-ext (->path "../foo.txt.bar")) (->path "../foo.txt"))
(check-equal? (remove-ext (->path "/hidden/file/.foo.txt.bar")) (->path "/hidden/file/.foo.txt"))
(check-equal? (remove-ext* foo-path) foo-path)
(check-equal? (remove-ext* foo.txt-path) foo-path)
(check-equal? (remove-ext* (->path ".foo.txt")) (->path ".foo"))
(check-not-equal? (remove-ext* foo.bar.txt-path) foo.bar-path) ; removes more than one ext
(check-equal? (remove-ext* foo.bar.txt-path) foo-path)
;; test remove-ext* on paths that have "." prefix
(check-equal? (remove-ext* (->path "./foo.txt.bar")) (->path "./foo"))
(check-equal? (remove-ext* (->path "../foo.txt.bar")) (->path "../foo"))
(check-equal? (remove-ext* (->path "/hidden/file/.foo.txt.bar")) (->path "/hidden/file/.foo"))
(check-true (has-binary-ext? "foo.MP3"))
(check-false (has-binary-ext? "foo.py"))
(check-equal? (slice-at (range 5) 1) '((0) (1) (2) (3) (4)))
(check-equal? (slice-at (range 5) 2) '((0 1) (2 3) (4)))
(check-equal? (slice-at (range 5) 2 #t) '((0 1) (2 3)))
(check-equal? (slice-at (range 5) 3) '((0 1 2) (3 4)))
(check-equal? (slice-at (range 5) 3 #t) '((0 1 2)))
(check-equal? (slicef '(0 1 2 0 0 0 3) positive?) '((0) (1 2) (0 0 0) (3)))
(check-equal? (slicef '(0 1 2 0 0 0 3) positive?) (slicef '(0 1 2 0 0 0 3) zero?))
(check-equal? (slicef '(1 (1) (1) 1 1 1 (1)) list?) '((1) ((1) (1)) (1 1 1) ((1))))
(check-equal? (slicef '(1 2 3 4 5) list?) '((1 2 3 4 5)))
(check-equal? (slicef-at (range 5) even?) '((0 1) (2 3) (4)))
(check-equal? (slicef-at (range 5) odd?) '((0) (1 2) (3 4)))
(check-equal? (slicef-at (range 5) odd? #t) '((1 2) (3 4)))
(check-equal? (slicef-at (range 5) procedure?) '((0 1 2 3 4)))
(check-equal? (slicef-at '(1 2 2 1 2) even?) '((1) (2) (2 1) (2)))
(check-equal? (slicef-at '(1 2 2 1 2) even? #t) '((2) (2 1) (2)))
(check-equal? (slicef-after (range 5) even?) '((0) (1 2) (3 4)))
(check-equal? (slicef-after (range 5) odd?) '((0 1) (2 3) (4)))
(check-equal? (slicef-after (range 5) odd? #t) '((0 1) (2 3)))
(check-equal? (slicef-after (range 5) procedure?) '((0 1 2 3 4)))
(check-equal? (slicef-after '(2 1 2 2 1) even?) '((2) (1 2) (2) (1)))
(check-equal? (slicef-after '(2 1 2 2 1) even? #t) '((2) (1 2) (2)))
(check-equal? (sublist (range 5) 0 0) '())
(check-equal? (sublist (range 5) 0 1) '(0))
(check-equal? (sublist (range 5) 0 5) '(0 1 2 3 4))
(check-equal? (break-at '(5 6 7 8) '()) '((5 6 7 8)))
(check-equal? (break-at '(5 6 7 8) '(0)) '((5 6 7 8)))
(check-equal? (break-at '(5 6 7 8) '(1 2 3)) '((5) (6) (7) (8)))
(check-equal? (break-at '(5 6 7 8) '(1 3)) '((5) (6 7) (8)))
(check-equal? (break-at '(5 6 7 8) '(1)) (break-at '(5 6 7 8) 1))
(define xs (range 5))
(check-equal? (map (λ(a b c) (list a b c)) (shift xs -1) (shift xs 0) (shift xs 1)) '((1 0 #f) (2 1 0) (3 2 1) (4 3 2) (#f 4 3)))
(check-equal? (map (λ(a b c) (list a b c)) (shift xs -1 'ignored #t) (shift xs 0 'ignored #t) (shift xs 1 'ignored #t)) '((1 0 4) (2 1 0) (3 2 1) (4 3 2) (0 4 3)))
(check-equal? (shifts xs '(-1 0 1) 'boing) `((1 2 3 4 boing) ,xs (boing 0 1 2 3)))
(check-equal? (shifts xs '(-1 0 1) 'boing #t) `((1 2 3 4 0) ,xs (4 0 1 2 3)))
(check-equal? (shift xs 5 0) (make-list 5 0))
(check-exn exn:fail? (λ() (shift xs -10)))
(check-equal? (map (λ(a b c) (list a b c)) (shift-left xs -1) (shift-left xs 0) (shift-left xs 1)) (map reverse '((1 0 #f) (2 1 0) (3 2 1) (4 3 2) (#f 4 3))))
(check-equal? (shift-cycle xs 2) '(3 4 0 1 2))
(check-equal? (shift-left-cycle xs 2) '(2 3 4 0 1))
(check-equal? (shift-cycle xs 7) '(3 4 0 1 2))
(check-equal? (shift-left-cycle xs 7) '(2 3 4 0 1))
(check-equal? (shift-cycle xs 107) '(3 4 0 1 2))
(check-equal? (shift-left-cycle xs 107) '(2 3 4 0 1))
(check-true (urlish? (->path "/Users/MB/home.html")))
(check-true (urlish? "/Users/MB/home.html?foo=bar"))
(check-true (urlish? (->symbol "/Users/MB/home")))
(check-true (pathish? (->path "/Users/MB/home")))
(check-true (pathish? "/Users/MB/home"))
(check-true (pathish? (->symbol "/Users/MB/home")))
(check-equal? (filter-split '("foo" " " "bar" "\n" "\n" "ino") (λ(x) (< (string-length x) 3))) '(("foo")("bar")("ino")))
(check-exn exn:fail? (λ _ (slice-at (range 5) 0))) ; needs a positive integer as second arg
(check-exn exn:fail? (λ _ (slicef-at (range 5) 3))) ; needs a procedure as second arg
(define ys (range 5))
(check-equal? (values->list (shift/values ys -1 'boing)) '(1 2 3 4 boing))
(check-equal? (values->list (shift/values ys '(-1 0 1) 'boing)) `((1 2 3 4 boing) ,xs (boing 0 1 2 3)))
(check-equal? "42 = 42\n" (let ([os (open-output-string)])
(parameterize ([current-error-port os])
(report 42))
(get-output-string os)))
(check-equal? "(quotient/remainder 10 3) = (values 3 1)\n" (let ([os (open-output-string)])
(parameterize ([current-error-port os])
(report (quotient/remainder 10 3))
(get-output-string os)))))

@ -1,14 +0,0 @@
#lang racket/base
(require (for-syntax racket/base racket/syntax))
(provide (all-defined-out))
;; like case but strictly uses `eq?` comparison (as opposed to `equal?`)
(define-syntax caseq (make-rename-transformer #'case))
(define-syntax casev (make-rename-transformer #'case))
(require sugar/debug)
(define-syntax (cond-report stx)
(syntax-case stx ()
[(_ [COND . BODY] ... [else . ELSE-BODY]) #'(cond [(report COND) (report (let () (void) . BODY))] ... [else . ELSE-BODY])]
[(_ [COND . BODY] ... ) #'(cond-report [COND . BODY] ... [else (void)])]))

@ -1,95 +0,0 @@
#lang racket/base
(require (for-syntax racket/base racket/syntax) racket/class)
(provide (all-defined-out))
(define string%
(class* object% (writable<%>)
(super-new)
(init-field [data #f])
(define (get-string)
(with-handlers ([exn:fail:object? (λ (exn) data)])
(send this toString)))
(define/public (custom-write port) (write (get-string) port))
(define/public (custom-display port) (display (get-string) port))))
(define mixin-tester%
(class object%
(super-new)
(define/public (addContent val) (make-object string% val))))
(define-syntax (as-method stx)
(syntax-case stx ()
[(_ ID) (with-syntax ([PRIVATE-ID (generate-temporary #'ID)])
#'(begin
(public [PRIVATE-ID ID])
(define (PRIVATE-ID . args) (apply ID this args))))]))
(define-syntax-rule (as-methods ID ...)
(begin (as-method ID) ...))
(define-syntax (define-instance stx)
(syntax-case stx ()
[(_ ID (MAKER BASE-CLASS . ARGS))
(with-syntax ([ID-CLASS (format-id stx "~a:~a" (syntax->datum #'BASE-CLASS) (syntax->datum #'ID))])
#'(define ID (let ([ID-CLASS (class BASE-CLASS (super-new))])
(MAKER ID-CLASS . ARGS))))]))
(define-syntax (define-class-predicates stx)
(syntax-case stx ()
[(_ ID)
(with-syntax ([+ID (format-id #'ID "+~a" (syntax->datum #'ID))]
[ID? (format-id #'ID "~a?" (syntax->datum #'ID))])
#'(begin (define (ID? x) (is-a? x ID))
(define (+ID . args) (apply make-object ID args))))]))
(define-syntax-rule (define-subclass*/interfaces SUPERCLASS INTERFACES (ID . INIT-ARGS) . BODY)
(begin
(define ID (class* SUPERCLASS INTERFACES (init-field . INIT-ARGS) . BODY))
(define-class-predicates ID)))
(define-syntax-rule (define-subclass/interfaces SUPERCLASS INTERFACES (ID . INIT-ARGS) . BODY)
(define-subclass*/interfaces SUPERCLASS INTERFACES (ID . INIT-ARGS) (super-new) . BODY))
(define-syntax-rule (define-subclass* SUPERCLASS (ID . INIT-ARGS) . BODY)
(define-subclass*/interfaces SUPERCLASS () (ID . INIT-ARGS) . BODY))
(define-syntax-rule (define-subclass SUPERCLASS (ID . INIT-ARGS) . BODY)
(define-subclass* SUPERCLASS (ID . INIT-ARGS) (super-new) . BODY))
(define-syntax-rule (push-field! FIELD O EXPR)
(set-field! FIELD O (cons EXPR (get-field FIELD O))))
(define-syntax-rule (push-end-field! FIELD O EXPR)
(set-field! FIELD O (append (get-field FIELD O) (list EXPR))))
(define-syntax-rule (pop-field! FIELD O)
(let ([xs (get-field FIELD O)])
(set-field! FIELD O (cdr xs))
(car xs)))
(define-syntax (increment-field! stx)
(syntax-case stx ()
[(_ FIELD O) #'(increment-field! FIELD O 1)]
[(_ FIELD O EXPR)
#'(begin (set-field! FIELD O (+ (get-field FIELD O) EXPR)) (get-field FIELD O))]))
(define-syntax (getter-field/override stx)
(syntax-case stx ()
[(_ [ID . EXPRS])
(syntax-property #'(getter-field [ID . EXPRS]) 'override #t)]))
(define-syntax (getter-field stx)
(syntax-case stx ()
[(_ [ID . EXPRS])
(with-syntax ([_ID (format-id #'ID "_~a" (syntax->datum #'ID))])
#`(begin
(field [(ID _ID) . EXPRS])
(public (_ID ID))
(#,(if (syntax-property stx 'override) #'define/override #'define) (_ID) ID)))]))

@ -1,25 +0,0 @@
#lang racket/base
(require racket/contract racket/class)
(provide (all-defined-out))
(define (option/c x) (or/c #f x))
(module+ main
(define-syntax-rule (define/public/contract (ID . ARGS) CONTRACT . BODY)
(define/public (ID . ARGS)
(define/contract (ID . ARGS)
CONTRACT . BODY)
(ID . ARGS)))
(define c% (class object%
(super-new)
(define/public/contract (add x y)
(integer? integer? . -> . integer?)
(+ x y))))
(define c (make-object c%))
(send c add 12 21))

@ -1,22 +0,0 @@
#lang racket/base
(require sugar/list)
(provide (all-defined-out))
(define (assoc? x) (and (pair? x) (not (list? x))))
(define (assocs? xs) (and (list? xs) (andmap assoc? xs)))
(define (listify kvs)
(for/list ([slice (in-list (slice-at kvs 2))])
(cons (car slice) (cadr slice))))
(define-syntax-rule (define-hashifier id hasher) (define (id . kvs) (hasher (listify kvs))))
;; like indefinite-arity `hash` but mutable
(define-hashifier mhash make-hash)
(define-hashifier mhasheq make-hasheq)
(define-hashifier mhasheqv make-hasheqv)
(module+ test
(require rackunit)
(check-equal? (mhash 'k "v") (make-hash (list (cons 'k "v")))))
(define (dictify . xs) (listify xs))

@ -1,95 +0,0 @@
#lang racket/base
(require racket/class (for-syntax racket/base racket/syntax) racket/dict)
(provide (all-defined-out))
;; js-style `push`, which appends to end of list
(define-syntax-rule (push-end! ID THING)
(set! ID (append ID (list THING))))
(define-syntax (increment! stx)
(syntax-case stx ()
[(_ ID) #'(increment! ID 1)]
[(_ ID EXPR)
#'(begin (set! ID (+ ID EXPR)) ID)]))
(module+ test
(define xs '(1 2 3))
(push-end! xs 4)
(check-equal? xs '(1 2 3 4)))
(define-syntax-rule (+= ID THING) (begin (set! ID (+ ID THING)) ID))
(define-syntax-rule (++ ID) (+= ID 1))
(define-syntax-rule (-- ID) (+= ID -1))
(define-syntax-rule (-= ID THING) (+= ID (- THING)))
;; fancy number->string. bounds are checked, inexact integers are coerced.
(define (number x #:round [round? #true])
(unless (and (number? x) (< -1e21 x 1e21))
(raise-argument-error 'number "valid number" x))
(let ([x (if round? (/ (round (* x 1e6)) 1e6) x)])
(number->string (if (integer? x)
(inexact->exact x)
x))))
(module+ test
(check-equal? (number 4.5) "4.5")
(check-equal? (number 4.0) "4")
(check-equal? (number 4) "4")
(check-equal? (number -4) "-4"))
(define ·-helper
(procedure-rename
(λ (x . refs)
(for/fold ([x x])
([ref (in-list refs)]
#:break (not x))
(cond
;; give `send` precedence (presence of method => wants runtime resolution of value)
[(and (object? x)
(memq ref (interface->method-names (object-interface x)))) (dynamic-send x ref)]
;; dict first, to catch objects that implement gen:dict
[(dict? x) (dict-ref x ref #f)]
[(object? x) (cond
[(memq ref (field-names x)) (dynamic-get-field ref x)]
[else #f])]
[else (raise-argument-error '· "object or dict" (cons x refs))]))) '·))
(define-syntax-rule (· X REF ...) (·-helper X 'REF ...))
#;(module+ test
(define c (class object%
(super-new)
(field [a 42])
(define/public (res) (hash 'res (hash 'b 43)))))
(define co (make-object c))
(define h2 (hash 'a 42 'res co))
(check-equal? (· h2 a) 42)
(check-equal? (· h2 b) 43)
(check-equal? (· co a) 42)
(check-equal? (· co b) 43))
(define-syntax-rule (·map REF XS)
(for/list ([x (in-list XS)]) (· x REF)))
(module+ test
(require rackunit)
(define C
(class object%
(super-new)
(field [foo 'field])
(define/public (bar) 'method)
(define/public (zam) (hasheq 'zoom 'hash))))
(define h (hasheq 'bam (new C) 'foo 'hashlet))
(define o (new C))
(check-equal? (· o foo) 'field)
(check-equal? (· o bar) 'method)
(check-equal? (· o zam zoom) 'hash)
(check-equal? (· h bam foo) 'field)
(check-equal? (· h bam bar) 'method)
(check-equal? (· h bam zam zoom) 'hash)
(check-equal? (·map foo (list o h)) '(field hashlet)))

@ -1,48 +0,0 @@
#lang racket/base
(require (for-syntax
racket/base
racket/syntax)
"../define.rkt"
racket/sequence
racket/generic)
(provide define-generics+provide+safe)
(define-syntax (define-generics+provide+safe stx)
(syntax-case stx ()
[(_ TYPE ID-CONTRACT (ID . ID-ARGS) . ARGS)
(with-syntax ([TYPE? (format-id stx "~a?" #'TYPE)])
#'(begin
(provide TYPE? ID)
(module+ safe
(require racket/contract)
(provide TYPE? (contract-out [ID ID-CONTRACT])))
(define-generics TYPE (ID . ID-ARGS) . ARGS)))]))
(provide len lengthable?)
(define-generics lengthable
(len lengthable)
#:fast-defaults
([list? (define len length)]
[string? (define len string-length)]
[symbol? (define len (compose1 string-length symbol->string))]
[path? (define len (compose1 string-length path->string))]
[vector? (define len vector-length)]
[hash? (define (len x) (length (hash-keys x)))]
[(λ (x) (and (sequence? x) (not (integer? x)))) (define len (compose1 length sequence->list))]))
(module+ test
(require rackunit racket/set)
(check-equal? (len '(1 2 3)) 3)
(check-not-equal? (len '(1 2)) 3) ; len 2
(check-equal? (len "foo") 3)
(check-not-equal? (len "fo") 3) ; len 2
(check-equal? (len 'foo) 3)
(check-not-equal? (len 'fo) 3) ; len 2
(check-equal? (len (list->vector '(1 2 3))) 3)
(check-not-equal? (len (list->vector '(1 2))) 3) ; len 2
(check-equal? (len (set 1 2 3)) 3)
(check-not-equal? (len (set 1 2)) 3) ; len 2
(check-equal? (len (make-hash '((a . 1) (b . 2) (c . 3)))) 3)
(check-not-equal? (len (make-hash '((a . 1) (b . 2)))) 3)) ; len 2

@ -1,27 +0,0 @@
#lang racket/base
(require racket/port)
(provide (all-defined-out) (all-from-out racket/port))
(define (port-position ip [where #f])
(cond
[where (file-position ip where)
ip]
[else (file-position ip)]))
(define (set-port-position! ip where)
(file-position ip where))
(module+ test
(require rackunit)
(define ip (open-input-bytes (bytes 1 2 3 4)))
(port-count-lines! ip)
(check-equal? (port-position ip) 0)
(check-equal? (read-byte ip) 1)
(check-equal? (port-position ip) 1)
(check-equal? (read-byte ip) 2)
(set-port-position! ip 4)
(check-equal? (port-position ip) 4)
(check-equal? (read-byte ip) eof)
(set-port-position! ip 0)
(check-equal? (port-position ip) 0)
(check-equal? (read-byte ip) 1))

@ -1,39 +0,0 @@
#lang racket/base
(require (for-syntax racket/base racket/syntax))
(provide (all-defined-out))
(begin-for-syntax
(require racket/string racket/format)
(define (make-prefix caller-stx)
(string-join (map ~a (list (syntax-source caller-stx) (syntax-line caller-stx))) ":" #:after-last ":")))
(define-syntax (define-stub-stop stx)
(syntax-case stx ()
[(_ ID)
(with-syntax ([ERROR-ID (format-id stx "~a~a:not-implemented" (make-prefix stx) (syntax->datum #'ID))])
#'(define (ID . args)
(error 'ERROR-ID)))]))
(provide (rename-out [define-stub-stop define-stub]))
(define-syntax (define-stub-go stx)
(syntax-case stx ()
[(_ ID)
(with-syntax ([ERROR-ID (format-id stx "~a~a:not-implemented" (make-prefix stx) (syntax->datum #'ID))])
#'(define (ID . args)
(displayln 'ERROR-ID)))]))
(define-syntax (define-unfinished stx)
(syntax-case stx ()
[(_ (ID . ARGS) . BODY)
(with-syntax ([ID-UNFINISHED (format-id stx "~a~a:unfinished" (make-prefix stx) (syntax->datum #'ID))])
#'(define (ID . ARGS)
(begin . BODY)
(error 'ID-UNFINISHED)))]))
(define-syntax (unfinished stx)
(syntax-case stx ()
[(_)
(with-syntax ([ID-UNFINISHED (format-id stx "~a:~a:~a" (path->string (syntax-source stx)) (syntax-line stx) (syntax->datum #'unfinished))])
#'(error 'ID-UNFINISHED))]))

@ -0,0 +1,40 @@
#lang racket/base
(require (for-syntax racket/base racket/syntax))
(require "define.rkt")
(provide+safe module-test-external module-test-internal module-test-internal+external)
;; tests using module-boundary contracts
(define-syntax (module-test-external stx)
(syntax-case stx ()
[(_ expr ...)
(let ([mod-name (syntax-e (generate-temporary))])
(datum->syntax stx
`(begin
(module* ,mod-name racket/base
(require (submod ".."))
(require rackunit)
,@(syntax->datum #'(expr ...)))
(module+ test
(require (submod ".." ,mod-name))))
stx))]))
(define-syntax (module-test-internal stx)
(syntax-case stx ()
[(_ expr ...)
(let ([exprs (syntax->datum #'(expr ...))])
(datum->syntax stx `(begin
(module+ test
(require rackunit)
,@exprs))
;; pass original stx for srcloc
;; which is not precisely accurate but
;; OK for now
stx))]))
(define-syntax (module-test-internal+external stx)
(syntax-case stx ()
[(_ expr ...)
(let ([exprs (syntax->datum #'(expr ...))])
(datum->syntax stx `(begin
(module-test-internal ,@exprs)
(module-test-external ,@exprs)) stx))]))

@ -0,0 +1,161 @@
#lang racket
(require (for-syntax racket/syntax))
(define-syntax (eval-as-untyped stx)
(syntax-case stx ()
[(_ exprs ...)
(let ([sym (generate-temporary)]
[sym2 (generate-temporary)])
(datum->syntax
stx
`(begin
(module ,sym racket
(require rackunit "../main.rkt" net/url)
,@(syntax->datum #'(exprs ...)))
(require ',sym)
(module ,sym2 racket
(require rackunit (submod "../main.rkt" safe) net/url)
,@(syntax->datum #'(exprs ...)))
(require ',sym2))))]))
(eval-as-untyped
(check-equal? (->int 42) 42)
(check-equal? (->int 42.1) 42)
(check-equal? (->int 42+3i) 42)
(check-equal? (->int "42") 42)
(check-equal? (->int '42) 42)
(check-equal? (->int (string->path "42")) 42)
(check-equal? (->int #\A) 65)
(check-equal? (->int (make-list 42 null)) 42)
(check-equal? (->string "foo") "foo")
(check-equal? (->string #"foo") "foo")
(check-equal? (->string '()) "")
(check-equal? (->string (void)) "")
(check-equal? (->string 'foo) "foo")
(check-equal? (->string 123) "123")
(check-equal? (->string (string->url "foo/bar.html")) "foo/bar.html")
(define file-name-as-text "foo.txt")
(check-equal? (->string (string->path file-name-as-text)) file-name-as-text)
(check-equal? (->string #\¶) "")
(check-equal? (->path "foo") (string->path "foo"))
(check-equal? (->path #"foo") (string->path "foo"))
(check-equal? (->path 'foo) (string->path "foo"))
(check-equal? (->path 123) (string->path "123"))
(check-equal? (->path (string->url "foo/bar.html")) (string->path "foo/bar.html"))
(check-equal? (->list '(1 2 3)) '(1 2 3))
(check-equal? (->list (list->vector '(1 2 3))) '(1 2 3))
(check-not-false (andmap (lambda (e) (member e '(1 2 3))) (->list (set 1 2 3))))
(check-equal? (->list "foo") (list "foo"))
(check-true (->boolean #t))
(check-false (->boolean #f))
(check-true (->boolean "#f"))
(check-true (->boolean "foo"))
(check-true (->boolean '()))
(check-true (->boolean '(1 2 3)))
(check-true (members-unique? '(a b c)))
(check-false (members-unique? '(a b c c)))
(check-true (members-unique? "zoey"))
(check-false (members-unique? "zooey"))
(check-equal? (trimf (list 4 1 2 3 4) even?) '(1 2 3))
(check-equal? (trimf (list 1 3 2 4 5 6 8 9 13) odd?) '(2 4 5 6 8))
(check-equal? (filter-split '(1 2 3 4 5 6) even?) '((1)(3)(5)))
(define foo-path-strings '("foo" "foo.txt" "foo.bar" "foo.bar.txt"))
(match-define (list foo-path foo.txt-path foo.bar-path foo.bar.txt-path) (map ->path foo-path-strings))
;; test the sample paths before using them for other tests
(define foo-paths (list foo-path foo.txt-path foo.bar-path foo.bar.txt-path))
(for-each check-equal? (map ->string foo-paths) foo-path-strings)
(check-false (has-ext? foo-path 'txt))
(check-true (foo.txt-path . has-ext? . 'txt))
(check-true ((->path "foo.TXT") . has-ext? . 'txt))
(check-true (has-ext? foo.bar.txt-path 'txt))
(check-false (foo.bar.txt-path . has-ext? . 'doc)) ; wrong extension
(check-equal? (get-ext (->path "foo.txt")) "txt")
(check-false (get-ext "foo"))
(check-equal? (add-ext (string->path "foo") "txt") (string->path "foo.txt"))
(check-equal? (remove-ext foo-path) foo-path)
(check-equal? (remove-ext (->path ".foo.txt")) (->path ".foo.txt"))
(check-equal? (remove-ext foo.txt-path) foo-path)
(check-equal? (remove-ext foo.bar.txt-path) foo.bar-path)
(check-not-equal? (remove-ext foo.bar.txt-path) foo-path) ; does not remove all extensions
(check-equal? (remove-ext* foo-path) foo-path)
(check-equal? (remove-ext* foo.txt-path) foo-path)
(check-equal? (remove-ext* (->path ".foo.txt")) (->path ".foo.txt"))
(check-not-equal? (remove-ext* foo.bar.txt-path) foo.bar-path) ; removes more than one ext
(check-equal? (remove-ext* foo.bar.txt-path) foo-path)
(check-true (has-binary-ext? "foo.MP3"))
(check-false (has-binary-ext? "foo.py"))
(check-equal? (slice-at (range 5) 1) '((0) (1) (2) (3) (4)))
(check-equal? (slice-at (range 5) 2) '((0 1) (2 3) (4)))
(check-equal? (slice-at (range 5) 2 #t) '((0 1) (2 3)))
(check-equal? (slice-at (range 5) 3) '((0 1 2) (3 4)))
(check-equal? (slice-at (range 5) 3 #t) '((0 1 2)))
(check-equal? (slicef '(0 1 2 0 0 0 3) positive?) '((0) (1 2) (0 0 0) (3)))
(check-equal? (slicef '(0 1 2 0 0 0 3) positive?) (slicef '(0 1 2 0 0 0 3) zero?))
(check-equal? (slicef '(1 (1) (1) 1 1 1 (1)) list?) '((1) ((1) (1)) (1 1 1) ((1))))
(check-equal? (slicef '(1 2 3 4 5) list?) '((1 2 3 4 5)))
(check-equal? (slicef-at (range 5) even?) '((0 1) (2 3) (4)))
(check-equal? (slicef-at (range 5) odd?) '((0) (1 2) (3 4)))
(check-equal? (slicef-at (range 5) odd? #t) '((1 2) (3 4)))
(check-equal? (slicef-at (range 5) procedure?) '((0 1 2 3 4)))
(check-equal? (slicef-at '(1 2 2 1 2) even?) '((1) (2) (2 1) (2)))
(check-equal? (slicef-at '(1 2 2 1 2) even? #t) '((2) (2 1) (2)))
(check-equal? (sublist (range 5) 0 0) '())
(check-equal? (sublist (range 5) 0 1) '(0))
(check-equal? (sublist (range 5) 0 5) '(0 1 2 3 4))
(check-equal? (break-at '(5 6 7 8) '()) '((5 6 7 8)))
(check-equal? (break-at '(5 6 7 8) '(0)) '((5 6 7 8)))
(check-equal? (break-at '(5 6 7 8) '(1 2 3)) '((5) (6) (7) (8)))
(check-equal? (break-at '(5 6 7 8) '(1 3)) '((5) (6 7) (8)))
(check-equal? (break-at '(5 6 7 8) '(1)) (break-at '(5 6 7 8) 1))
(define xs (range 5))
(check-equal? (map (λ(a b c) (list a b c)) (shift xs -1) (shift xs 0) (shift xs 1)) '((1 0 #f) (2 1 0) (3 2 1) (4 3 2) (#f 4 3)))
(check-equal? (map (λ(a b c) (list a b c)) (shift xs -1 'ignored #t) (shift xs 0 'ignored #t) (shift xs 1 'ignored #t)) '((1 0 4) (2 1 0) (3 2 1) (4 3 2) (0 4 3)))
(check-equal? (shifts xs '(-1 0 1) 'boing) `((1 2 3 4 boing) ,xs (boing 0 1 2 3)))
(check-equal? (shifts xs '(-1 0 1) 'boing #t) `((1 2 3 4 0) ,xs (4 0 1 2 3)))
(check-equal? (shift xs 5 0) (make-list 5 0))
(check-exn exn:fail? (λ() (shift xs -10)))
(check-true (urlish? (->path "/Users/MB/home.html")))
(check-true (urlish? "/Users/MB/home.html?foo=bar"))
(check-true (urlish? (->symbol "/Users/MB/home")))
(check-true (pathish? (->path "/Users/MB/home")))
(check-true (pathish? "/Users/MB/home"))
(check-true (pathish? (->symbol "/Users/MB/home")))
(check-equal? (filter-split '("foo" " " "bar" "\n" "\n" "ino") (λ(x) (< (string-length x) 3))) '(("foo")("bar")("ino")))
(check-exn exn:fail? (λ _ (slice-at (range 5) 0))) ; needs a positive integer as second arg
(check-exn exn:fail? (λ _ (slicef-at (range 5) 3))) ; needs a procedure as second arg
(define ys (range 5))
(check-equal? (values->list (shift/values ys -1 'boing)) '(1 2 3 4 boing))
(check-equal? (values->list (shift/values ys '(-1 0 1) 'boing)) `((1 2 3 4 boing) ,xs (boing 0 1 2 3))))
#|
;; todo: revise `check-typing-fails` to make it compatible with 6.0
(check-typing-fails (slice-at (range 5) 0)) ; needs a positive integer as second arg
(check-typing-fails (slicef-at (range 5) 3)) ; needs a procedure as second arg
|#

@ -0,0 +1,31 @@
#lang racket/base
(require "../define.rkt" racket/set racket/sequence)
(define+provide+safe (len x)
((or/c list? vector? set? sequence? string? symbol? path? hash?) . -> . integer?)
(cond
[(list? x) (length x)]
[(string? x) (string-length x)]
[(symbol? x) (len (symbol->string x))]
[(path? x) (len (path->string x))]
[(vector? x) (vector-length x)]
[(hash? x) (len (hash-keys x))]
[(set? x) (len (set->list x))]
[(and (sequence? x) (not (integer? x))) (len (sequence->list x))]
[else (error "len: can't calculate length of" x)]))
(module+ test
(require rackunit)
(check-equal? (len '(1 2 3)) 3)
(check-not-equal? (len '(1 2)) 3) ; len 2
(check-equal? (len "foo") 3)
(check-not-equal? (len "fo") 3) ; len 2
(check-equal? (len 'foo) 3)
(check-not-equal? (len 'fo) 3) ; len 2
(check-equal? (len (list->vector '(1 2 3))) 3)
(check-not-equal? (len (list->vector '(1 2))) 3) ; len 2
(check-equal? (len (set 1 2 3)) 3)
(check-not-equal? (len (set 1 2)) 3) ; len 2
(check-equal? (len (make-hash '((a . 1) (b . 2) (c . 3)))) 3)
(check-not-equal? (len (make-hash '((a . 1) (b . 2)))) 3)) ; len 2

@ -1,23 +1,15 @@
#lang racket/base
(require xml
racket/port
racket/contract
"define.rkt")
(require xml racket/port racket/contract "define.rkt")
(provide (all-defined-out))
(define+provide+safe (xml-string->xexprs str)
(string? . -> . (values xexpr? xexpr?))
(parameterize ([current-input-port (open-input-string str)]
[permissive-xexprs #true])
(define xml-doc (read-xml))
(values (xml->xexpr (document-prolog xml-doc)) (xml->xexpr (document-element xml-doc)))))
(define xml-doc (with-input-from-string str (λ _ (permissive-xexprs #t) (read-xml))))
(values (xml->xexpr (document-prolog xml-doc)) (xml->xexpr (document-element xml-doc))))
(define+provide+safe (xexprs->xml-string prolog-xexpr root-xexpr)
(xexpr? xexpr? . -> . string?)
(with-output-to-string
(λ ()
(parameterize ([permissive-xexprs #true])
(write-xml (document (xexpr->xml prolog-xexpr) (xexpr->xml root-xexpr) null))))))
(with-output-to-string (λ _ (write-xml (document (xexpr->xml prolog-xexpr) (xexpr->xml root-xexpr) null)))))
(module+ test
(require rackunit)
@ -26,4 +18,4 @@
(define-values (str-prolog str-doc) (xml-string->xexprs str))
(check-equal? str-prolog (prolog (list (p-i (location 1 0 1) (location 1 38 39) 'xml "version=\"1.0\" encoding=\"utf-8\"")) #f null))
(check-equal? str-doc '(root () "hello world"))
(check-equal? (xexprs->xml-string str-prolog str-doc) str))
(check-equal? (xexprs->xml-string str-prolog str-doc) str))
Loading…
Cancel
Save