Skip to content

Instantly share code, notes, and snippets.

@pmatos
Created August 1, 2019 06:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmatos/c8e3e667d2e4accf3c85f745a460e3f2 to your computer and use it in GitHub Desktop.
Save pmatos/c8e3e667d2e4accf3c85f745a460e3f2 to your computer and use it in GitHub Desktop.
Optional enable Racket Contracts
#lang racket/base
;; ---------------------------------------------------------------------------------------------------
(require (for-syntax racket/base racket/string)
racket/contract
racket/require-syntax racket/provide-syntax
racket/match
racket/list
syntax/parse/define
racket/struct-info)
(provide provide/cond-contract
compiled-with-contracts?
(all-from-out racket/contract))
;; ---------------------------------------------------------------------------------------------------
;;
;; Enables contracts optionally, depending on the value of ENABLE_CONTRACTS.
;;
;; This work was based on the typed-racket implementation of optional contracts:
;; https://github.com/racket/typed-racket/blob/master/typed-racket-lib/typed-racket/utils/utils.rkt
(define-for-syntax enable-contracts?
(and (getenv "ENABLE_CONTRACTS") #true))
(begin-for-syntax
(define-syntax-class clause
#:attributes (i)
(pattern [(~datum struct) (~or nm:id (nm:id super:id)) (flds ...)]
#:with i #'(struct-out nm))
(pattern [(~datum rename) out:id in:id cnt:expr]
#:with i #'(rename-out [out in]))
(pattern [i:id cnt:expr])))
(define-syntax provide/cond-contract
(if enable-contracts?
(lambda (stx)
(syntax-parse stx
[(_ c:clause ...)
#'(provide (contract-out c ...))]))
(lambda (stx)
(syntax-parse stx
[(_ c:clause ...)
#'(provide c.i ...)]))))
(define-syntax (compiled-with-contracts? stx)
(datum->syntax stx enable-contracts?))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment