我想通过测试语法异常的宏来扩展srfi-78。我想要这样的东西:
#! /usr/bin/env scheme-script
#!r6rs
(import (rnrs) (srfi :78 lightweight-testing))
; the macros I want to test
(define-syntax some-macros
(syntax-rules ()
[(_) 'ok]))
; the extension to srfi-78
(define-syntax check-exception
(syntax-rules ()
; ... some code ...
))
; tests
; prints "correct" or someting like that
(check (some-macros) => 'ok)
; should print "correct" (i. e. the test passed)
(check-exception (some-macros 'arg))
; should print "error"
; (i. e. the exception was not thrown as expected)
(check-exception (some-macros))
有可能吗?如果没有,你会如何为宏编写测试?
我从srfi-64了解test-read-eval-string
。它接受一个字符串,将其转换为一个表单并在初始环境中评估该表单。我想要一个宏来评估当前环境中给定的表单并捕获异常。
答案 0 :(得分:3)
唯一可行的方法是通过eval调用代码,并将其包装在一个警卫中。
例如:
(define (safe-eval code env)
(guard [e [(syntax-violation? e) (display e)]]
(eval code env)))
用法:
> (safe-eval '(let a v) (environment '(rnrs)))
&who: let
&message: "invalid syntax"
&syntax:
form: (let a v)
subform: #f