Created
February 24, 2021 16:19
-
-
Save 97jaz/0b631811b5819b401a5db39885ca2fff to your computer and use it in GitHub Desktop.
proof-of-concept for module aliases with `open`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang racket/base | |
(require (for-syntax racket/base | |
racket/syntax | |
racket/require-transform | |
syntax/id-table)) | |
(begin-for-syntax | |
(struct import-transformer (aliases) | |
#:property prop:require-transformer | |
(λ (tf) | |
(λ (stx) | |
(syntax-case stx () | |
[(_ alias mod) | |
(let-values ([(imports sources) (expand-import #'mod)] | |
[(aliases) (import-transformer-aliases tf)]) | |
(free-id-table-set! aliases #'alias imports) | |
(values imports sources))]))))) | |
(define-syntax for-import (import-transformer (make-free-id-table))) | |
(begin-for-syntax | |
(define (get-imports alias) | |
(free-id-table-ref | |
(import-transformer-aliases (syntax-local-value #'for-import)) | |
alias | |
(λ () (raise-syntax-error #f "no such module alias" alias))))) | |
(define-syntax (import stx) | |
(syntax-case stx (as) | |
[(_ mod as alias) | |
(let () | |
(define prefix-id (format-id stx "~a." #'alias)) | |
(define prefixed-require #`(prefix-in #,prefix-id mod)) | |
#`(require (for-import alias #,prefixed-require)))])) | |
(define-syntax (open-module stx) | |
(syntax-case stx () | |
[(_ alias body ...) | |
(let () | |
(define imports (get-imports #'alias)) | |
(define (import->binding import) | |
(list (datum->syntax stx (import-src-sym import)) | |
(make-rename-transformer (import-local-id import)))) | |
#`(let-syntax #,(map import->binding imports) body ...))])) | |
(import racket/bool as bool) | |
(println bool.false) | |
(println (bool.nor #f #f)) | |
(let ([boolean=? (λ (x y) 'nope)]) | |
(open-module bool | |
(println (boolean=? #t #t)) | |
(let ([boolean=? (λ (x y) 'okay)]) | |
(println (boolean=? #t #t))) | |
(println (nor #f #t)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment