8.2.6 Experimental: Contracts on macro sub-expressions

► |  | Syntax: Meta-Programming Helpers

1 | Syntax Object Helpers
2 | Module-Processing Helpers
3 | Macro Transformer Helpers
4 | Reader Helpers
5 | Non-Module Compilation And Expansion
6 | Trusting Standard Recertifying Transformers
7 | Attaching Documentation to Exports
8 | Parsing and specifying syntax
| Index

► | 8 | Parsing and specifying syntax

8.1 | Introduction
8.2 | Examples
8.3 | Parsing syntax
8.4 | Specifying syntax with syntax classes
8.5 | Syntax patterns
8.6 | Literal sets and Conventions
8.7 | Library syntax classes and literal sets
8.8 | Debugging and inspection tools
8.9 | Experimental

▼ | 8.2 | Examples

8.2.1 | Modules and reusable syntax classes
8.2.2 | Optional keyword arguments
8.2.3 | Variants with uniform meanings
8.2.4 | Variants with varied meanings
8.2.5 | More keyword arguments
8.2.6 | Experimental: Contracts on macro sub-expressions

top← prev up next →

##### 8.2.6`` Experimental: Contracts on macro sub-expressions

This section involves facilities that are experimental and subject to change.

Just as procedures often expect certain kinds of values as arguments, macros often have expectations about the expressions they are given. And just as procedures express those expectations via contracts, so can macros, using the expr/c syntax class.

For example, here is a macro myparameterize that behaves like parameterize but enforces the parameter? contract on the parameter expressions.

> ( define-syntax (myparameterize stx)
( syntax-parse stx
[(_ ((p v:expr) ...) body:expr)
#:declare p ( expr/c #' parameter?
#:name "parameter argument")
#'( parameterize ((p.c v) ...) body)]))

> (myparameterize (( current-input-port
( open-input-string "(1 2 3)")))
( read))

'(1 2 3)

> (myparameterize (('whoops 'something))
'whatever)

eval:100.0: 'program broke the contract parameter? on
parameter argument of myparameterize
; expected <parameter?>, given: 'whoops

Important: Make sure when using expr/c to use the c attribute. If the macro above had used p in the template, the expansion would have used the raw, unchecked expressions. The expr/c syntax class does not change how pattern variables are bound; it only computes an attribute that represents the checked expression.

top← prev up next →