[英]unbound variable in racket macro
我正在圍繞 racket syntax-case
宏測試包裝器宏。 在第 1 步,它沒有做任何有趣的事情,只是將所有部分直接傳遞給syntax-case
,如下所示:
#lang racket
;; definition
(define-syntax guarded-syntax-case
(lambda (x)
(syntax-case x ()
((guarded-syntax-case y (literal ...) clause ...)
#'(syntax-case y (literal ...) clause ...)
))))
;; test case
(define-syntax (binop stx)
(guarded-syntax-case stx () ; *problem site*
[(_ op n1 n2) #'(op n1 n2)]))
但是這個簡單的案例失敗了,在上面代碼中標有問題站點的空括號()
處出現以下錯誤:
; ....rkt:11:27: #%app: missing procedure expression;
; probably originally (), which is an illegal empty application
; after encountering unbound identifier (which is possibly the real problem):
; guarded-syntax-case
; in: (#%app)
我不知道這個簡單的傳遞宏有什么問題。 錯誤消息似乎表明某處有一個未綁定的變量,我無法識別。 我認為literal...
應該匹配為空。
有人可以幫助解釋出了什么問題以及如何修復宏嗎?
問題是guarded-syntax-case
在正確的階段沒有被識別為宏。 特別是,當您在程序中使用(define-syntax guarded-syntax-case...)
時,您定義了在階段 0 中可用的宏guarded-syntax-case
。但是(define-syntax (binop stx)...)
必須在第一階段。
有兩種方法可以糾正錯誤。
(define-syntax guarded-syntax-case...)
包裝在begin-for-syntax
中。 但是,這樣做需要在第 2 階段提供syntax-case
和其他內容。因此您需要一個額外的(require (for-meta 2 racket/base))
。 這是完整的代碼:#lang racket
(require (for-meta 2 racket/base))
;; definition
(begin-for-syntax
(define-syntax guarded-syntax-case
(lambda (x)
(syntax-case x ()
((guarded-syntax-case y (literal ...) clause ...)
#'(syntax-case y (literal ...) clause ...))))))
;; test case
(define-syntax (binop stx)
(guarded-syntax-case stx () ; *problem site*
[(_ op n1 n2) #'(op n1 n2)]))
(binop + 1 2) ;=> 3
guarded-syntax-case
的(子)模塊,然后使用for-syntax
require
該(子)模塊。 這是完整的代碼:#lang racket
(module lib racket
(provide guarded-syntax-case)
;; definition
(define-syntax guarded-syntax-case
(lambda (x)
(syntax-case x ()
((guarded-syntax-case y (literal ...) clause ...)
#'(syntax-case y (literal ...) clause ...))))))
(require (for-syntax 'lib))
;; test case
(define-syntax (binop stx)
(guarded-syntax-case stx () ; *problem site*
[(_ op n1 n2) #'(op n1 n2)]))
(binop + 1 2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.