2 The Redex Reference
Alternatively, use the redex/reduction-semantics and redex/pict modules, which provide only non-GUI functionality (i.e., everything except redex/gui), making them suitable for programs which should not depend on racket/gui/base.
2.1 Patterns
(require redex/reduction-semantics) |
This section covers Redex’s pattern language, used in many of Redex’s forms.
Note that pattern matching is caching (including caching the results of side-conditions). This means that once a pattern has matched a given term, Redex assumes that it will always match that term.
This is the grammar for the Redex pattern language. Non-terminal references are wrapped with angle brackets; otherwise identifiers in the grammar are terminals.
pattern | = | any | ||
| | number | |||
| | natural | |||
| | integer | |||
| | real | |||
| | string | |||
| | boolean | |||
| | variable | |||
| | (variable-except <id> ...) | |||
| | (variable-prefix <id>) | |||
| | variable-not-otherwise-mentioned | |||
| | hole | |||
| | symbol | |||
| | (name <id> <pattern>) | |||
| | (in-hole <pattern> <pattern>) | |||
| | (hide-hole <pattern>) | |||
| | (side-condition <pattern> guard) | |||
| | (cross <id>) | |||
| | (<pattern-sequence> ...) | |||
| | <racket-constant> | |||
pattern-sequence | = | <pattern> | ||
| | ... ; literal ellipsis | |||
| | ..._id |
The any pattern matches any sexpression. This pattern may also be suffixed with an underscore and another identifier, in which case they bind the full name (as if it were an implicit name pattern) and match the portion before the underscore.
The number pattern matches any number. This pattern may also be suffixed with an underscore and another identifier, in which case they bind the full name (as if it were an implicit name pattern) and match the portion before the underscore.
The natural pattern matches any exact non-negative integer. This pattern may also be suffixed with an underscore and another identifier, in which case they bind the full name (as if it were an implicit name pattern) and match the portion before the underscore.
The integer pattern matches any exact integer. This pattern may also be suffixed with an underscore and another identifier, in which case they bind the full name (as if it were an implicit name pattern) and match the portion before the underscore.
The real pattern matches any real number. This pattern may also be suffixed with an underscore and another identifier, in which case they bind the full name (as if it were an implicit name pattern) and match the portion before the underscore.
The string pattern matches any string. This pattern may also be suffixed with an underscore and another identifier, in which case they bind the full name (as if it were an implicit name pattern) and match the portion before the underscore.
The boolean pattern matches #true and #false (which are the same as #t and #f, respectively). This pattern may also be suffixed with an underscore and another identifier, in which case they bind the full name (as if it were an implicit name pattern) and match the portion before the underscore.
The variable pattern matches any symbol. This pattern may also be suffixed with an underscore and another identifier, in which case they bind the full name (as if it were an implicit name pattern) and match the portion before the underscore.
The variable-except pattern matches any symbol except those listed in its argument. This is useful for ensuring that keywords in the language are not accidentally captured by variables.
The variable-prefix pattern matches any symbol that begins with the given prefix.
The variable-not-otherwise-mentioned pattern matches any symbol except those that are used as literals elsewhere in the language.
The hole pattern matches anything when inside the first argument to an in-hole pattern. Otherwise, it matches only a hole.
The symbol pattern stands for a literal symbol that must match exactly, unless it is the name of a non-terminal in a relevant language or contains an underscore.
If it is a non-terminal, it matches any of the right-hand sides of that non-terminal. If the non-terminal appears twice in a single pattern, then the match is constrained to expressions that are the same, unless the pattern is part of a grammar, in which case there is no constraint.
If the symbol is a non-terminal followed by an underscore, for example e_1, it is implicitly the same as a name pattern that matches only the non-terminal, (name e_1 e) for the example. Accordingly, repeated uses of the same name are constrainted to match the same expression.
If the symbol is a non-terminal followed by _!_, for example e_!_1, it is also treated as a pattern, but repeated uses of the same pattern are constrained to be different. For example, this pattern:
(e_!_1 e_!_1 e_!_1)
matches lists of three es, but where all three of them are distinct.
Unlike a _ pattern, the _!_ patterns do not bind names.
If _ names and _!_ are mixed, they are treated as separate. That is, this pattern (e_1 e_!_1) matches just the same things as (e e), but the second doesn’t bind any variables.
If the symbol otherwise has an underscore, it is an error.
The pattern (name symbol pattern) matches pattern and binds using it to the name symbol.
The (in-hole pattern pattern) pattern matches the first pattern. This match must include exactly one match against the second pattern. If there are zero matches or more than one match, an exception is raised.
When matching the first argument of in-hole, the hole pattern matches any sexpression. Then, the sexpression that matched the hole pattern is used to match against the second pattern.
The (hide-hole pattern) pattern matches what the embedded pattern matches but if the pattern matcher is looking for a decomposition, it ignores any holes found in that pattern.
The (side-condition pattern guard) pattern matches what the embedded pattern matches, and then the guard expression is evaluated. If it returns #f, the pattern fails to match, and if it returns anything else, the pattern matches. Any occurrences of name in the pattern (including those implicitly there via _ pattersn) are bound using term-let in the guard.
The (cross symbol) pattern is used for the compatible closure functions. If the language contains a non-terminal with the same name as symbol, the pattern (cross symbol) matches the context that corresponds to the compatible closure of that non-terminal.
The (pattern-sequence ...) pattern matches a sexpression list, where each pattern-sequence element matches an element of the list. In addition, if a list pattern contains an ellipsis, the ellipsis is not treated as a literal, instead it matches any number of duplications of the pattern that came before the ellipses (including 0). Furthermore, each (name symbol pattern) in the duplicated pattern binds a list of matches to symbol, instead of a single match. (A nested duplicated pattern creates a list of list matches, etc.) Ellipses may be placed anywhere inside the row of patterns, except in the first position or immediately after another ellipses.
Multiple ellipses are allowed. For example, this pattern:
matches this sexpression:
(term (a a))
three different ways. One where the first a in the pattern matches nothing, and the second matches both of the occurrences of a, one where each named pattern matches a single a and one where the first matches both and the second matches nothing.
If the ellipses is named (ie, has an underscore and a name following it, like a variable may), the pattern matcher records the length of the list and ensures that any other occurrences of the same named ellipses must have the same length.
As an example, this pattern:
((name x a) ..._1 (name y a) ..._1)
only matches this sexpression:
(term (a a))
one way, with each named pattern matching a single a. Unlike the above, the two patterns with mismatched lengths is ruled out, due to the underscores following the ellipses.
Also, like underscore patterns above, if an underscore pattern begins with ..._!_, then the lengths must be different.
Thus, with the pattern:
((name x a) ..._!_1 (name y a) ..._!_1)
and the expression
(term (a a))
two matches occur, one where x is bound to '() and y is bound to '(a a) and one where x is bound to '(a a) and y is bound to '().
syntax
(redex-match lang pattern any)
(redex-match lang pattern)
If redex-match receives only two arguments, it builds a procedure for efficiently testing if expressions match the pattern, using the language lang. The procedures accepts a single expression and if the expresion matches, it returns a list of match structures describing the matches. If the match fails, the procedure returns #f.
Examples: | |||||||||||||||||||||
|
syntax
(redex-match? lang pattern any)
(redex-match? lang pattern)
Examples: | ||||||||||||||||
|
procedure
(match-bindings m) → (listof bind?)
m : match?
parameter
(caching-enabled? on?) → void? on? : boolean?
Caching should be disabled when matching a pattern that depends on values other than the in-scope pattern variables or evaluating a metafunction that reads or writes mutable external state.
procedure
(set-cache-size! size) → void?
size : positive-integer?
The default size is 350.
parameter
(check-redudancy check?) → void? check? : boolean?
2.2 Terms
Object language expressions in Redex are written using term. It is similar to Racket’s quote (in many cases it is identical) in that it constructs lists as the visible representation of terms.
The grammar of terms is (note that an ellipsis stands for repetition unless otherwise indicated):
term | = | identifier | ||
| | (term-sequence ...) | |||
| | ,racket-expression | |||
| | (in-hole term term) | |||
| | hole | |||
| | #t | |||
| | #f | |||
| | string | |||
term-sequence | = | term | ||
| | ,@racket-expression | |||
| | ... ; literal ellipsis |
A term written identifier is equivalent to the corresponding symbol, unless the identifier is bound by term-let, define-term, or a pattern variable or the identifier is hole (as below).
A term written (term-sequence ...) constructs a list of the terms constructed by the sequence elements.
A term written ,racket-expression evaluates the racket-expression and substitutes its value into the term at that point.
A term written ,@racket-expression evaluates the racket-expression, which must produce a list. It then splices the contents of the list into the expression at that point in the sequence.
A term written (in-hole tttterm tttterm) is the dual to the pattern in-hole – it accepts a context and an expression and uses plug to combine them.
A term written hole produces a hole.
A term written as a literal boolean or a string produces the boolean or the string.
It behaves similarly to quasiquote, except for a few special forms that are recognized (listed below) and that names bound by term-let are implicitly substituted with the values that those names were bound to, expanding ellipses as in-place sublists (in the same manner as syntax-case patterns).
The optional #:lang keyword must supply an identifier bound by define-language, and adds a check that any symbol containing an underscore in term could have been bound by a pattern in the language referenced by lang-id. In practice, this means that the underscore must be preceded by a non-terminal in that langauge or a built-in pattern such as number. This form of term is used internally by default, so this check is applied to terms that are constructed by Redex forms such as reduction-relation and define-metafunction.
For example,
(term-let ([body '(+ x 1)] [(expr ...) '(+ - (values * /))] [((id ...) ...) '((a) (b) (c d))]) (term (let-values ([(id ...) expr] ...) body)))
evaluates to
'(let-values ([(a) +] [(b) -] [(c d) (values * /)]) (+ x 1))
It is an error for a term variable to appear in an expression with an ellipsis-depth different from the depth with which it was bound by term-let. It is also an error for two term-let-bound identifiers bound to lists of different lengths to appear together inside an ellipsis.
syntax
syntax
syntax
(term-let ([tl-pat expr] ...) body)
tl-pat = identifier | (tl-pat-ele ...) tl-pat-ele = tl-pat | tl-pat ... ; a literal ellipsis
Note that each ellipsis should be the literal symbol consisting of three dots (and the ... elsewhere indicates repetition as usual). If tl-pat is an identifier, it matches any value and binds it to the identifier, for use inside term. If it is a list, it matches only if the value being matched is a list value and only if every subpattern recursively matches the corresponding list element. There may be a single ellipsis in any list pattern; if one is present, the pattern before the ellipses may match multiple adjacent elements in the list value (possibly none).
This form is a lower-level form in Redex, and not really designed to be used directly. For let-like forms that use Redex’s full pattern matching facilities, see redex-let, redex-let*, term-match, term-match/single.
This form raises an exception recognized by exn:fail:redex? if any right-hand side does not match its left-hand side in exactly one way.
In some contexts, it may be more efficient to use term-match/single (lifted out of the context).
syntax
(redex-let* language ([pattern expression] ...) body ...+)
syntax
(define-term identifier term)
syntax
(term-match language [pattern expression] ...)
When evaluating a term-match expression, the patterns are compiled in an effort to speed up matching. Using the procedural result multiple times to avoid compiling the patterns multiple times.
syntax
(term-match/single language [pattern expression] ...)
Raises an exception recognized by exn:fail:redex? if no clauses match or if one of the clauses matches multiple ways.
When evaluating a term-match/single expression, the patterns are compiled in an effort to speed up matching. Using the procedural result multiple times to avoid compiling the patterns multiple times.
procedure
(variable-not-in t var) → symbol?
t : any/c var : symbol?
Does not expect the input symbols to be distinct, but does produce variables that are always distinct.
procedure
(exn:fail:redex? v) → boolean?
v : any/c
2.3 Languages
syntax
(define-language lang-name non-terminal-def ...)
non-terminal-def = (non-terminal-name ...+ ::= pattern ...+) | (non-terminal-name pattern ...+) | ((non-terminal-name ...+) pattern ...+)
A non-terminal-def comprises one or more non-terminal names (considered aliases) followed by one or more productions.
For example, the following defines lc-lang as the grammar of the λ-calculus:
(define-language lc-lang (e (e e ...) x v) (c (v ... c e ...) hole) (v (λ (x ...) e)) (x variable-not-otherwise-mentioned))
with non-terminals e for the expression language, x for variables, c for the evaluation contexts and v for values.
syntax
syntax
(define-extended-language extended-lang base-lang non-terminal-def ...)
non-terminal-def = (non-terminal-name ...+ ::= pattern ...+) | (non-terminal-name pattern ...+) | ((non-terminal-name ...+) pattern ...+)
(define-extended-language lc-num-lang lc-lang (v .... ; extend the previous `v' non-terminal number +) (x (variable-except λ +)))
extends lc-lang with two new alternatives (+ and number) for the v non-terminal, carries forward the e and c non-terminals, and replaces the x non-terminal with a new one (which happens to be equivalent to the one that would have been inherited).
The four-period ellipses indicates that the new language’s non-terminal has all of the alternatives from the original language’s non-terminal, as well as any new ones. If a non-terminal occurs in both the base language and the extension, the extension’s non-terminal replaces the originals. If a non-terminal only occurs in either the base language, then it is carried forward into the extension. And, of course, extend-language lets you add new non-terminals to the language.
If a language is has a group of multiple non-terminals defined together, extending any one of those non-terminals extends all of them.
syntax
(define-union-language L base/prefix-lang ...)
base/prefix-lang = lang-id | (prefix lang-id)
If a language has a prefix, then all of the non-terminals from that language have the corresponding prefix in the union language. The prefix helps avoid collisions between the constituent language’s non-terminals (which is illegal).
(define-language UT (e (e e) (λ (x) e) x)) (define-language WT (e (e e) (λ (x t) e) x) (t (→ t t) num))
(define-union-language B (ut. UT) (wt. WT))
procedure
(language-nts lang) → (listof symbol?)
lang : compiled-lang?
procedure
(compiled-lang? l) → boolean?
l : any/c
2.4 Reduction Relations
syntax
(reduction-relation language domain base-arrow reduction-case ... shortcuts)
domain =
| #:domain pattern base-arrow =
| #:arrow base-arrow-name reduction-case = (arrow-name pattern term red-extras ...) red-extras = rule-name | (fresh fresh-clause ...) | (side-condition racket-expression) | (where pattern term) | (judgment-holds (judgment-form-id pat/term ...)) | (side-condition/hidden racket-expression) | (where/hidden pattern term) shortcuts =
| with shortcut ... shortcut =
[(old-arrow-name pattern term) (new-arrow-name identifier identifier)] rule-name = identifier | string | (computed-name racket-expression) fresh-clause = var | ((var1 ...) (var2 ...)) pat/term = pattern | term
The optional domain clause provides a contract for the relation, in the form of a pattern that defines the relation’s domain and codomain.
The arrow-name in each reduction-case clause is either base-arrow-name (default -->) or an arrow name defined by shortcuts (described below). In either case, the pattern refers to language and binds variables in the corresponding term. Following the pattern and term can be the name of the reduction rule and declarations of fresh variables and side-conditions.
For example, the expression
(reduction-relation lc-lang (--> (in-hole c_1 ((λ (variable_i ...) e_body) v_i ...)) (in-hole c_1 ,(foldl lc-subst (term e_body) (term (v_i ...)) (term (variable_i ...)))) beta-v))
defines a reduction relation for the lc-lang grammar.
A rule’s name (used in typesetting, the stepper, traces, and apply-reduction-relation/tag-with-names) can be given as a literal (an identifier or a string) or as an expression that computes a name using the values of the bound pattern variables (much like the rule’s right-hand side). Some operations require literal names, so a rule definition may provide both a literal name and a computed name. In particular, only rules that include a literal name may be replaced using extend-reduction-relation, used as breakpoints in the stepper, and selected using render-reduction-relation-rules. The output of apply-reduction-relation/tag-with-names, traces, and the stepper prefers the computed name, if it exists. Typesetting a rule with a computed name shows the expression that computes the name only when the rule has no literal name or when it would not typeset in pink due to with-unquote-rewriters in the context; otherwise, the literal name (or nothing) is shown.
Fresh variable clauses generate variables that do not occur in the term being reduced. If the fresh-clause is a variable, that variable is used both as a binding in the term and as the prefix for the freshly generated variable. (The variable does not have to be a non-terminal in the language of the reduction relation.)
The second form of fresh-clauses generates a sequence of variables. In that case, the ellipses are literal ellipses; that is, you must actually write ellipses in your rule. The variable var1 is like the variable in first case of a fresh-clause; namely it is used to determine the prefix of the generated variables and it is bound in the right-hand side of the reduction rule, but unlike the single-variable fresh clause, it is bound to a sequence of variables. The variable var2 is used to determine the number of variables generated and var2 must be bound by the left-hand side of the rule.
The expressions within side-condition clauses and side-condition/hidden clauses are collected with and and used as guards on the case being matched. The argument to each side-condition should be a Racket expression, and the pattern variables in the pattern are bound in that expression. A side-condition/hidden clause is the same as a side-condition clause, except that the condition is not rendered when typesetting via redex/pict.
Each where clause acts as a side condition requiring a successful pattern match, and it can bind pattern variables in the side-conditions (and where clauses) that follow and in the metafunction result. The bindings are the same as bindings in a term-let expression. A where/hidden clause is the same as a where clause, but the clause is not rendered when typesetting via redex/pict.
Each judgment-holds clause acts like a where clause, where the left-hand side pattern incorporates each of the patterns used in the judgment form’s output positions.
Each shortcut clause defines arrow names in terms of base-arrow-name and earlier shortcut definitions. The left- and right-hand sides of a shortcut definition are identifiers, not patterns and terms. These identifiers need not correspond to non-terminals in language.
For example, this expression
(reduction-relation lc-num-lang (==> ((λ (variable_i ...) e_body) v_i ...) ,(foldl lc-subst (term e_body) (term (v_i ...)) (term (variable_i ...)))) (==> (+ number_1 ...) ,(apply + (term (number_1 ...)))) with [(--> (in-hole c_1 a) (in-hole c_1 b)) (==> a b)])
defines reductions for the λ-calculus with numbers, where the ==> shortcut is defined by reducing in the context c.
A fresh clause in reduction-case defined by shortcut refers to the entire term, not just the portion matched by the left-hand side of shortcut’s use.
syntax
(extend-reduction-relation reduction-relation language more ...)
If the original reduction-relation has a rule with the same name as one of the rules specified in the extension, the old rule is removed.
procedure
(union-reduction-relations r ...) → reduction-relation?
r : reduction-relation?
procedure
r : reduction-relation?
syntax
(compatible-closure reduction-relation lang non-terminal)
syntax
(context-closure reduction-relation lang pattern)
procedure
(reduction-relation? v) → boolean?
v : any/c
procedure
(apply-reduction-relation r t) → (listof any/c)
r : reduction-relation? t : any/c
procedure
(apply-reduction-relation/tag-with-names r t) → (listof (list/c (union false/c string?) any/c)) r : reduction-relation? t : any/c
procedure
(apply-reduction-relation* r t [ #:cache-all? cache-all? #:stop-when stop-when]) → (listof any/c) r : reduction-relation? t : any/c cache-all? : boolean? = (current-cache-all?) stop-when : (-> any/c any) = (λ (x) #f)
If the cache-all? argument is #t, then apply-reduction-relation* keeps a cache of all visited terms when traversing the graph and does not revisit any of them. This cache can, in some cases, use a lot of memory, so it is off by default and the cycle checking happens by keeping track only of the current path it is traversing through the reduction graph.
The stop-when argument controls the stopping criterion. Specifically, it is called with each term that apply-reduction-relation* encounters. If it ever returns a true value (anything except #f), then apply-reduction-relation* considers the term to be irreducible (and so returns it and does not try to reduce it further).
parameter
(current-cache-all? cache-all?) → void? cache-all? : boolean?
Examples: | |||||||||||||||||
|
syntax
syntax
syntax
2.5 Other Relations
syntax
(define-metafunction language metafunction-contract [(name pattern ...) term metafunction-extras ...] ...)
metafunction-contract =
| id : pattern ... -> range range = pattern | pattern or range | pattern ∨ range | pattern ∪ range metafunction-extras = (side-condition racket-expression) | (side-condition/hidden racket-expression) | (where pat term) | (where/hidden pat term) |
(judgment-holds (judgment-form-id pat/term ...))
The side-condition, hidden-side-condition, where, and where/hidden clauses behave as in the reduction-relation form.
Raises an exception recognized by exn:fail:redex? if no clauses match, if one of the clauses matches multiple ways (and that leads to different results for the different matches), or if the contract is violated.
Note that metafunctions are assumed to always return the same results for the same inputs, and their results are cached, unless caching-enabled? is set to #f. Accordingly, if a metafunction is called with the same inputs twice, then its body is only evaluated a single time.
As an example, these metafunctions finds the free variables in an expression in the lc-lang above:
(define-metafunction lc-lang free-vars : e -> (x ...) [(free-vars (e_1 e_2 ...)) (∪ (free-vars e_1) (free-vars e_2) ...)] [(free-vars x) (x)] [(free-vars (λ (x ...) e)) (- (free-vars e) (x ...))])
The first argument to define-metafunction is the grammar (defined above). Following that are three cases, one for each variation of expressions (e in lc-lang). The free variables of an application are the free variables of each of the subterms; the free variables of a variable is just the variable itself, and the free variables of a λ expression are the free variables of the body, minus the bound parameters.
Here are the helper metafunctions used above.
(define-metafunction lc-lang ∪ : (x ...) ... -> (x ...) [(∪ (x_1 ...) (x_2 ...) (x_3 ...) ...) (∪ (x_1 ... x_2 ...) (x_3 ...) ...)] [(∪ (x_1 ...)) (x_1 ...)] [(∪) ()]) (define-metafunction lc-lang - : (x ...) (x ...) -> (x ...) [(- (x ...) ()) (x ...)] [(- (x_1 ... x_2 x_3 ...) (x_2 x_4 ...)) (- (x_1 ... x_3 ...) (x_2 x_4 ...)) (side-condition (not (memq (term x_2) (term (x_3 ...)))))] [(- (x_1 ...) (x_2 x_3 ...)) (- (x_1 ...) (x_3 ...))])
Note the side-condition in the second case of -. It ensures that there is a unique match for that case. Without it, (term (- (x x) x)) would lead to an ambiguous match.
syntax
(define-metafunction/extension f language metafunction-contract [(g pattern ...) term metafunction-extras ...] ...)
For example, define-metafunction/extension may be used to extend the free-vars function above to the forms introduced by the language lc-num-lang.
(define-metafunction/extension free-vars lc-num-lang free-vars-num : e -> (x ...) [(free-vars-num number) ()] [(free-vars-num (+ e_1 e_2)) (∪ (free-vars-num e_1) (free-vars-num e_2))])
syntax
(in-domain? (metafunction-name term ...))
syntax
(define-judgment-form language mode-spec contract-spec rule rule ...)
mode-spec = #:mode (form-id pos-use ...) contract-spec =
| #:contract (form-id pattern ...) pos-use = I | O rule =
[premise ... dashes rule-name conclusion] |
[conclusion premise ... rule-name] conclusion = (form-id pat/term ...) premise = (judgment-form-id pat/term ...) maybe-ellipsis | (where pattern term) | (where/hidden pattern term) | (side-condition term) | (side-condition/hidden term) rule-name =
| string | non-ellipsis-non-hypens-var pat/term = pattern | term maybe-ellipsis =
| ... dashes = --- | ---- | ----- | etc.
> (define-language nats (n ::= z (s n)))
> (define-judgment-form nats #:mode (sum I I O) #:contract (sum n n n) [----------- "zero" (sum z n n)] [(sum n_1 n_2 n_3) ------------------------- "add1" (sum (s n_1) n_2 (s n_3))])
Examples: | ||||||
|
Examples: | ||||||
|
> (define-judgment-form nats #:mode (sumr O O I) #:contract (sumr n n n) [------------ (sumr z n n)] [(sumr n_1 n_2 n_3) -------------------------- (sumr (s n_1) n_2 (s n_3))])
> (judgment-holds (sumr n_1 n_2 (s (s z))) (n_1 n_2)) '(((s (s z)) z) ((s z) (s z)) (z (s (s z))))
Examples: | |||||||||||||||||||||||||||||||||
|
A rule’s side-condition and side-condition/hidden premises are similar to those in reduction-relation and define-metafunction, except that they do not implicitly unquote their right-hand sides. In other words, a premise of the form (side-condition term) is equivalent to the premise (where #t term), except it does not typeset with the “#t = ”, as that would.
Examples: | ||||||||||||||||||||||||||
|
> (define-language vertices (v a b c))
> (define-judgment-form vertices #:mode (edge I O) #:contract (edge v v) [(edge a b)] [(edge b c)])
> (define-judgment-form vertices #:mode (path I I) #:contract (path v v) [---------- (path v v)] [(path v_2 v_1) -------------- (path v_1 v_2)] [(edge v_1 v_2) (path v_2 v_3) -------------- (path v_1 v_3)])
> (judgment-holds (path a c))
"typing-rules.rkt" —
defines a type system in a way that supports mechanized typesetting. When a typing judgment form can be given a mode, it can also be encoded as a metafunction using where clauses as premises, but Redex cannot typeset that encoding as inference rules. "sos.rkt" —
defines an SOS-style semantics in a way that supports mechanized typesetting. "multi-val.rkt" —
defines a judgment form that serves as a multi-valued metafunction.
syntax
(define-extended-judgment-form language judgment-form-id option ... rule ...)
The mode specification in this judgment form and the original must be the same.
syntax
(judgment-holds judgment)
(judgment-holds judgment term)
judgment = (judgment-form-id pat/term ...)
syntax
(build-derivations judgment)
Example: | |||||||
|
struct
(struct derivation (term name subs) #:extra-constructor-name make-derivation) term : any/c name : (or/c string? #f) subs : (listof derivation?)
The term field holds an s-expression based rendering of the conclusion of the derivation, the name field holds the name of the clause with term as the conclusion, and subs contains the sub-derivations.
See also build-derivations.
syntax
syntax
syntax
(define-relation language relation-contract [(name pattern ...) term ... metafunction-extras ...] ...)
relation-contract =
| form-id ⊂ pattern x ... x pattern | form-id ⊆ pattern × ... × pattern
The contract specification for a relation restricts the patterns that can be used as input to a relation. For each argument to the relation, there should be a single pattern, using x or × to separate the argument contracts.
Examples: | |||||||||||||||||||||||
|
parameter
(current-traced-metafunctions) → (or/c 'all (listof symbol?))
(current-traced-metafunctions traced-metafunctions) → void? traced-metafunctions : (or/c 'all (listof symbol?))
The tracing looks just like the tracing done by the racket/trace library, except that the first column printed by each traced call indicate if this call to the metafunction is cached. Specifically, a c is printed in the first column if the result is just returned from the cache and a space is printed if the metafunction call is actually performed.
Defaults to '().
2.6 Testing
syntax
(test-equal e1 e2)
syntax
(test-->> rel-expr option ... e1-expr e2-expr ...)
option = #:cycles-ok | #:equiv pred-expr | #:pred pred-expr
rel-expr : reduction-relation?
pred-expr : (--> any/c any)
e1-expr : any/c
e2-expr : any/c
If #:pred is specified, it is applied to each reachable term until one of the terms fails to satify the predicate (i.e., the predicate returns #f). If that happens, then the test fails and a message is printed with the term that failed to satisfy the predicate.
This test uses apply-reduction-relation*, so it does not terminate when the resulting reduction graph is infinite, although it does terminate if there are cycles in the (finite) graph.
If #:cycles-ok is not supplied then any cycles detected are treated as a test failure. If a pred-expr is supplied, then it is used to compare the expected and actual results.
syntax
(test--> rel-expr option ... e1-expr e2-expr ...)
option = #:equiv pred-expr
rel-expr : reduction-relation?
pred-expr : (--> any/c any/c any/c)
e1-expr : any/c
e2-expr : any/c
Examples: | |||||||||||||||||||||||||||||||||
|
syntax
(test-->>∃ option ... rel-expr start-expr goal-expr)
option = #:steps steps-expr
rel-expr : reduction-relation?
start-expr : any/c
goal-expr :
(or/c (-> any/c any/c) (not/c procedure?))
steps-expr : (or/c natural-number/c +inf.0)
syntax
Examples: | ||||||||||||||||||||||||||||||||||
|
syntax
(test-predicate p? e)
procedure
(test-results) → void?
syntax
(make-coverage subject)
subject = metafunction | relation-expr
parameter
(relation-coverage) → (listof coverage?)
(relation-coverage tracked) → void? tracked : (listof coverage?)
procedure
(covered-cases c) → (listof (cons/c string? natural-number/c))
c : coverage?
Examples: | ||||||||||||||||||||||||||||||||
|
syntax
(generate-term term-spec size-expr kw-args ...)
(generate-term term-spec)
term-spec = language pattern | language #:satisfying (judgment-form-id pattern ...) | language #:satisfying (metafunction-id pattern ...) = pattern | #:source metafunction | #:source relation-expr kw-args = #:attempt-num attempts-expr | #:retries retries-expr
size-expr : natural-number/c
attempt-num-expr : natural-number/c
retries-expr : natural-number/c
In the first term-spec case, the produced term matches the given pattern (interpreted according to the definition of the given language).
In the second case, the expression produced is the quoted form of a use of the judgment-form or #f, if Redex cannot find one.
The third cases generates a random term that satsifies the call to the metafunction with the given result or #f, if Redex cannot find one.
In the last two cases, the produced term matches one of the clauses of the specified metafunction or reduction relation.
In generate-term’s second form, it produces a procedure for constructing terms according to term-spec. This procedure expects size-expr (below) as its sole positional argument and allows the same optional keyword arguments as the first form. The second form may be more efficient when generating many terms.
The argument size-expr bounds the height of the generated term (measured as the height of its parse tree).
Examples: | |||||||||||||||||||||||||||||||||||||
|
The optional keyword argument attempt-num-expr (default 1) provides coarse grained control over the random decisions made during generation; increasing attempt-num-expr tends to increase the complexity of the result. For example, the absolute values of numbers chosen for integer patterns increase with attempt-num-expr.
The random generation process does not actively consider the constraints imposed by side-condition or _!_ patterns; instead, it uses a “guess and check” strategy in which it freely generates candidate terms then tests whether they happen to satisfy the constraints, repeating as necessary. The optional keyword argument retries-expr (default 100) bounds the number of times that generate-term retries the generation of any pattern. If generate-term is unable to produce a satisfying term after retries-expr attempts, it raises an exception recognized by exn:fail:redex:generation-failure?.
syntax
(redex-check language pattern property-expr kw-arg ...)
kw-arg = #:attempts attempts-expr | #:source metafunction | #:source relation-expr | #:retries retries-expr | #:print? print?-expr | #:attempt-size attempt-size-expr | #:prepare prepare-expr
property-expr : any/c
attempts-expr : natural-number/c
relation-expr : reduction-relation?
retries-expr : natural-number/c
print?-expr : any/c
attempt-size-expr : (-> natural-number/c natural-number/c)
prepare-expr : (-> any/c any/c)
redex-check generates at most attempts-expr (default (default-check-attempts)) random terms in its search. The size and complexity of these terms tend to increase with each failed attempt. The #:attempt-size keyword determines the rate at which terms grow by supplying a function that bounds term size based on the number of failed attempts (see generate-term’s size-expr argument). By default, the bound grows according to the default-attempt-size function.
returning a counterexample structure when the test reveals a counterexample,
returning #t when all tests pass, or
raising a exn:fail:redex:test when checking the property raises an exception.
The optional #:prepare keyword supplies a function that transforms each generated example before redex-check checks property-expr. This keyword may be useful when property-expr takes the form of a conditional, and a term chosen freely from the grammar is unlikely to satisfy the conditional’s hypothesis. In some such cases, the prepare keyword can be used to increase the probability that an example satifies the hypothesis.
When passed a metafunction or reduction relation via the optional #:source argument, redex-check distributes its attempts across the left-hand sides of that metafunction/relation by using those patterns, rather than pattern, as the basis of its generation. It is an error if any left-hand side generates a term that does not match pattern.
Examples: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
syntax
(redex-generator language-id satisfying size-expr)
satisfying = (judgment-form-id pattern ...) | (metafunction-id pattern ...) = pattern
size-expr : natural-number/c
Returns a thunk that, each time it is called, either generates a random s-expression based on satisfying or fails to (and returns #f). The terms returned by a particular thunk are guaranteed to be distinct.
Examples: | |||||||||||
|
struct
(struct counterexample (term) #:extra-constructor-name make-counterexample #:transparent) term : any/c
struct
(struct exn:fail:redex:test exn:fail:redex (source term) #:extra-constructor-name make-exn:fail:redex:test) source : exn:fail? term : any/c
syntax
(check-reduction-relation relation property kw-args ...)
kw-arg = #:attempts attempts-expr | #:retries retries-expr | #:print? print?-expr | #:attempt-size attempt-size-expr | #:prepare prepare-expr
property : (-> any/c any/c)
attempts-expr : natural-number/c
retries-expr : natural-number/c
print?-expr : any/c
attempt-size-expr : (-> natural-number/c natural-number/c)
prepare-expr : (-> any/c any/c)
(redex-check L any (property (term any)) #:attempts (* n attempts) #:source relation)
syntax
(check-metafunction metafunction property kw-args ...)
kw-arg = #:attempts attempts-expr | #:retries retries-expr | #:print? print?-expr | #:attempt-size attempt-size-expr | #:prepare prepare-expr
property : (-> (listof any/c) any/c)
attempts-expr : natural-number/c
retries-expr : natural-number/c
print?-expr : any/c
attempt-size-expr : (-> natural-number/c natural-number/c)
prepare-expr : (-> (listof any/c) (listof any/c))
Examples: | ||||||||||||||||||||||||||
|
procedure
n : natural-number/c
parameter
(default-check-attempts attempts) → void? attempts : natural-number/c
parameter
(redex-pseudo-random-generator generator) → void? generator : pseudo-random-generator?
procedure
v : any/c
It is easy to write grammars and reduction rules that are subtly wrong. Typically such mistakes result in examples that get stuck when viewed in a traces window.
The best way to debug such programs is to find an expression that looks like it should reduce, but doesn’t, then try to find out which pattern is failing to match. To do so, use the redex-match form.
In particular, first check if the term in question matches the your system’s main non-terminal (typically the expression or program non-terminal). If it does not match, simplify the term piece by piece to determine whether the problem is in the term or the grammar.
If the term does match your system’s main non-terminal, determine by inspection which reduction rules should apply. For each such rule, repeat the above term-pattern debugging procedure, this time using the rule’s left-hand side pattern instead of the system’s main non-terminal. In addition to simplifying the term, also consider simplifying the pattern.
If the term matches the left-hand side, but the rule does not apply, then one of the rule’s side-condition or where clauses is not satisfied. Using the bindings reported by redex-match, check each side-condition expression and each where pattern-match to discover which clause is preventing the rule’s application.
2.7 GUI
(require redex/gui) |
This section describes the GUI tools that Redex provides for exploring reduction sequences.
procedure
(traces reductions expr [ #:multiple? multiple? #:pred pred #:pp pp #:colors colors #:racket-colors? racket-colors? #:scheme-colors? scheme-colors? #:filter term-filter #:x-spacing x-spacing #:y-spacing y-spacing #:layout layout #:edge-labels? edge-labels? #:edge-label-font edge-label-font #:graph-pasteboard-mixin graph-pasteboard-mixin]) → void? reductions : reduction-relation? expr : (or/c any/c (listof any/c)) multiple? : boolean? = #f
pred :
(or/c (-> sexp any) (-> sexp term-node? any)) = (λ (x) #t)
pp :
(or/c (any -> string) (any output-port number (is-a?/c text%) -> void)) = default-pretty-printer
colors :
(listof (cons/c string? (and/c (listof (or/c string? (is-a?/c color%))) (λ (x) (<= 0 (length x) 6))))) = '() racket-colors? : boolean? = #t scheme-colors? : boolean? = racket-colors?
term-filter : (-> any/c (or/c #f string?) any/c) = (λ (x y) #t) x-spacing : number? = 15 y-spacing : number? = 15 layout : (-> (listof term-node?) void?) = void edge-labels? : boolean? = #t edge-label-font : (or/c #f (is-a?/c font%)) = #f
graph-pasteboard-mixin : (make-mixin-contract graph-pasteboard<%>) = values
The pred function indicates if a term has a particular property. If it returns #f, the term is displayed with a pink background. If it returns a string or a color% object, the term is displayed with a background of that color (using the-color-database to map the string to a color). If it returns any other value, the term is displayed normally. If the pred function accepts two arguments, a term-node corresponding to the term is passed to the predicate. This lets the predicate function explore the (names of the) reductions that led to this term, using term-node-children, term-node-parents, and term-node-labels.
The pred function may be called more than once per node. In particular, it is called each time an edge is added to a node. The latest value returned determines the color.
The pp function is used to specially print expressions. It must either accept one or four arguments. If it accepts one argument, it will be passed each term and is expected to return a string to display the term.
If the pp function takes four arguments, it should render its first argument into the port (its second argument) with width at most given by the number (its third argument). The final argument is the text where the port is connected – characters written to the port go to the end of the editor.
The colors argument, if provided, specifies a list of reduction-name/color-list pairs. The traces gui will color arrows drawn because of the given reduction name with the given color instead of using the default color.
The cdr of each of the elements of colors is a list of colors, organized in pairs. The first two colors cover the colors of the line and the border around the arrow head, the first when the mouse is over a graph node that is connected to that arrow, and the second for when the mouse is not over that arrow. Similarly, the next colors are for the text drawn on the arrow and the last two are for the color that fills the arrow head. If fewer than six colors are specified, the specified colors are used and then defaults are filled in for the remaining colors.
The racket-colors? argument (along with scheme-colors?, retained for backward compatibility), controls the coloring of each window. When racket-colors? is #t (and scheme-colors? is #t too), traces colors the contents according to DrRacket’s Racket-mode color scheme; otherwise, traces uses a black color scheme.
The term-filter function is called each time a new node is about to be inserted into the graph. If the filter returns false, the node is not inserted into the graph.
The x-spacing and y-spacing control the amount of space put between the snips in the default layout.
The layout argument is called (with all of the terms) when new terms are inserted into the window. In general, it is called after new terms are inserted in response to the user clicking on the reduce button, and after the initial set of terms is inserted. See also term-node-set-position!.
If edge-labels? is #t (the default), then edge labels are drawn; otherwise not.
The edge-label-font argument is used as the font on the edge labels. If #f is suppled, the dc<%> object’s default font is used.
The traces library uses an instance of the mrlib/graph library’s graph-pasteboard<%> interface to layout the graphs. Sometimes, overriding one of its methods can help give finer-grained control over the layout, so the graph-pasteboard-mixin is applied to the class before it is instantiated. Also note that all of the snips inserted into the editor by this library have a get-term-node method which returns the snip’s term-node.
procedure
(traces/ps reductions expr file [ #:multiple? multiple? #:pred pred #:pp pp #:colors colors #:filter term-filter #:layout layout #:x-spacing x-spacing #:y-spacing y-spacing #:edge-labels? edge-labels? #:edge-label-font edge-label-font #:graph-pasteboard-mixin graph-pasteboard-mixin] #:post-process post-process) → void? reductions : reduction-relation? expr : (or/c any/c (listof any/c)) file : (or/c path-string? path?) multiple? : boolean? = #f
pred :
(or/c (-> sexp any) (-> sexp term-node? any)) = (λ (x) #t)
pp :
(or/c (any -> string) (any output-port number (is-a?/c text%) -> void)) = default-pretty-printer
colors :
(listof (cons/c string? (and/c (listof (or/c string? (is-a?/c color%))) (λ (x) (<= 0 (length x) 6))))) = '()
term-filter : (-> any/c (or/c #f string?) any/c) = (λ (x y) #t) layout : (-> (listof term-node?) void?) = void x-spacing : number? = 15 y-spacing : number? = 15 edge-labels? : boolean? = #t edge-label-font : (or/c #f (is-a?/c font%)) = #f
graph-pasteboard-mixin : (make-mixin-contract graph-pasteboard<%>) = values post-process : (-> (is-a?/c graph-pasteboard<%>) any/c)
All of the arguments behave like the arguments to traces, with the exception of the post-process argument. It is called just before the PostScript is created with the graph pasteboard.
procedure
reductions : reduction-relation? t : any/c
pp :
(or/c (any -> string) (any output-port number (is-a?/c text%) -> void)) = default-pretty-printer
The pp argument is the same as to the traces function but is here for backwards compatibility only and should not be changed for most uses, but instead adjusted with pretty-print-parameters. Specifically, the highlighting shown in the stepper window can be wrong if default-pretty-printer does not print sufficiently similarly to how pretty-print prints (when adjusted by pretty-print-parameters’s behavior, of course).
procedure
(stepper/seed reductions seed [pp]) → void?
reductions : reduction-relation? seed : (cons/c any/c (listof any/c))
pp :
(or/c (any -> string) (any output-port number (is-a?/c text%) -> void)) = default-pretty-printer
procedure
(show-derivations derivations [ #:pp pp #:racket-colors? racket-colors? #:init-derivation init-derivation]) → any derivations : (cons/c derivation? (listof derivation?))
pp :
(or/c (any -> string) (any output-port number (is-a?/c text%) -> void)) = default-pretty-printer racket-colors? : boolean? = #f init-derivation : exact-nonnegative-integer? = 0
The pp and racket-colors? arguments are like those to traces.
The initial derivation shown in the window is chosen by init-derivation, used as an index into derivations.
procedure
(derivation/ps derivation filename [ #:pp pp #:racket-colors? racket-colors?] #:post-process post-process) → void? derivation : derivation? filename : path-string?
pp :
(or/c (any -> string) (any output-port number (is-a?/c text%) -> void)) = default-pretty-printer racket-colors? : boolean? = #f post-process : (-> (is-a?/c pasteboard%) any)
procedure
(term-node-children tn) → (listof term-node?)
tn : term-node?
Note that this function does not return all terms that this term reduces to – only those that are currently in the graph.
procedure
(term-node-parents tn) → (listof term-node?)
tn : term-node?
procedure
(term-node-labels tn) → (listof (or/c false/c string?))
tn : term-node?
procedure
(term-node-set-color! tn color) → void?
tn : term-node? color : (or/c string? (is-a?/c color%) false/c)
procedure
(term-node-color tn) → (or/c string? (is-a?/c color%) false/c)
tn : term-node?
procedure
(term-node-set-red! tn red?) → void?
tn : term-node? red? : boolean?
procedure
(term-node-expr tn) → any
tn : term-node?
procedure
(term-node-set-position! tn x y) → void?
tn : term-node? x : (and/c real? positive?) y : (and/c real? positive?)
procedure
(term-node-x tn) → real?
tn : term-node?
procedure
(term-node-y tn) → real?
tn : term-node?
procedure
(term-node-width tn) → real?
tn : term-node?
procedure
(term-node-height tn) → real?
tn : term-node?
procedure
(term-node? v) → boolean?
v : any/c
parameter
(reduction-steps-cutoff cutoff) → void? cutoff : number?
parameter
(initial-font-size size) → void? size : number?
If its value is a number, then the number is used as the width for every term. If its value is a function, then the function is called with each term and the resulting number is used as the width.
parameter
(dark-pen-color) → (or/c string? (is-a?/c color<%>))
(dark-pen-color color) → void? color : (or/c string? (is-a?/c color<%>))
parameter
(dark-brush-color) → (or/c string? (is-a?/c color<%>))
(dark-brush-color color) → void? color : (or/c string? (is-a?/c color<%>))
parameter
(light-pen-color) → (or/c string? (is-a?/c color<%>))
(light-pen-color color) → void? color : (or/c string? (is-a?/c color<%>))
parameter
(light-brush-color) → (or/c string? (is-a?/c color<%>))
(light-brush-color color) → void? color : (or/c string? (is-a?/c color<%>))
parameter
(dark-text-color) → (or/c string? (is-a?/c color<%>))
(dark-text-color color) → void? color : (or/c string? (is-a?/c color<%>))
parameter
(light-text-color) → (or/c string? (is-a?/c color<%>))
(light-text-color color) → void? color : (or/c string? (is-a?/c color<%>))
The dark colors are used when the mouse is over one of the nodes that is connected to this edge. The light colors are used when it isn’t.
The pen colors control the color of the line. The brush colors control the color used to fill the arrowhead and the text colors control the color used to draw the label on the edge.
parameter
(pretty-print-parameters) → (-> (-> any/c) any/c)
(pretty-print-parameters f) → void? f : (-> (-> any/c) any/c)
Specifically, whenever default-pretty-printer prints something it calls f with a thunk that does the actual printing. Thus, f can adjust pretty-print’s parameters to adjust how printing happens.
procedure
(default-pretty-printer v port width text) → void?
v : any/c port : output-port? width : exact-nonnegative-integer? text : (is-a?/c text%)
This function uses the value of pretty-print-parameters to adjust how it prints.
It sets the pretty-print-columns parameter to width, and it sets pretty-print-size-hook and pretty-print-print-hook to print holes and the symbol 'hole to match the way they are input in a term expression.
2.8 Typesetting
(require redex/pict) |
The redex/pict library provides functions designed to automatically typeset grammars, reduction relations, and metafunction written with plt redex.
Each grammar, reduction relation, and metafunction can be saved in a .ps file (as encapsulated postscript), or can be turned into a pict for viewing in the REPL or using with Slideshow (see Slideshow: Figure and Presentation Tools).
2.8.1 Picts, PDF, & PostScript
This section documents two classes of operations, one for direct use of creating postscript figures for use in papers and for use in DrRacket to easily adjust the typesetting: render-term, render-language, render-reduction-relation, render-relation, render-judgment-form, render-metafunctions, and render-lw, and one for use in combination with other libraries that operate on picts term->pict, language->pict, reduction-relation->pict, relation->pict, judgment-form->pict, metafunction->pict, and lw->pict. The primary difference between these functions is that the former list sets dc-for-text-size and the latter does not.
syntax
(render-term lang term)
(render-term lang term file)
(define-language L) (define x (term (+ 1 2))) (render-term L x)
See render-language for more details on the construction of the pict.
syntax
(term->pict lang term)
The first argument is expected to be a compiled-language? and the second argument is expected to be a term (without the term wrapper). The formatting in the term argument is used to determine how the resulting pict will look.
This function is primarily designed to be used with Slideshow or with other tools that combine picts together.
procedure
(render-term/pretty-write lang term filename #:width width) → void? lang : compiled-lang? term : any/c filename : path-string? width : #f
procedure
(term->pict/pretty-write lang term filename #:width width) → pict? lang : compiled-lang? term : any/c filename : (or/c path-string? #f) width : #f
procedure
(render-language lang [file #:nts nts]) → (if file void? pict?)
lang : compiled-lang? file : (or/c false/c path-string?) = #f
nts : (or/c false/c (listof (or/c string? symbol?))) = (render-language-nts)
This function parameterizes dc-for-text-size to install a relevant dc: a bitmap-dc% or a post-script-dc%, depending on whether file is a path.
See language->pict if you are using Slideshow or are otherwise setting dc-for-text-size.
procedure
(language->pict lang [#:nts nts]) → pict?
lang : compiled-lang?
nts : (or/c false/c (listof (or/c string? symbol?))) = (render-language-nts)
This function is primarily designed to be used with Slideshow or with other tools that combine picts together.
procedure
(render-reduction-relation rel [ file #:style style]) → (if file void? pict?) rel : reduction-relation? file : (or/c false/c path-string?) = #f style : reduction-rule-style/c = (rule-pict-style)
This function parameterizes dc-for-text-size to install a relevant dc: a bitmap-dc% or a post-script-dc%, depending on whether file is a path. See also reduction-relation->pict.
The following forms of arrows can be typeset:
--> -+> ==> -> => ..> >-> ~~> ~> :-> :–> c-> –>> >– –< >>– –<<
procedure
(reduction-relation->pict r [#:style style]) → pict?
r : reduction-relation? style : reduction-rule-style/c = (rule-pict-style)
This function is primarily designed to be used with Slideshow or with other tools that combine picts together.
syntax
(render-metafunction metafunction-name)
syntax
(render-metafunction metafunction-name filename)
syntax
(render-metafunctions metafunction-name ...)
syntax
(render-metafunctions metafunction-name ... #:file filename)
Similarly, render-metafunctions accepts multiple metafunctions and renders them together, lining up all of the clauses together.
This function sets dc-for-text-size. See also metafunction->pict and metafunctions->pict.
syntax
(metafunction->pict metafunction-name)
syntax
(metafunctions->pict metafunction-name ...)
syntax
(render-relation relation-name)
syntax
(render-relation relation-name filename)
This function sets dc-for-text-size. See also relation->pict.
syntax
(render-judgment-form judgment-form-name)
syntax
(render-judgment-form judgment-form-name filename)
This function sets dc-for-text-size. See also judgment-form->pict.
syntax
(relation->pict relation-name)
syntax
(judgment-form->pict judgment-form-name)
2.8.2 Customization
parameter
(render-language-nts) → (or/c false/c (listof symbol?))
(render-language-nts nts) → void? nts : (or/c false/c (listof symbol?))
See also language-nts.
parameter
(extend-language-show-union show?) → void? show? : boolean?
Defaults to #f.
Note that the #t variant can look a little bit strange if .... are used and the original version of the language has multi-line right-hand sides.
parameter
→
(or/c false/c (listof (or/c symbol? string? exact-nonnegative-integer?))) (render-reduction-relation-rules rules) → void?
rules :
(or/c false/c (listof (or/c symbol? string? exact-nonnegative-integer?)))
parameter
(rule-pict-style style) → void? style : reduction-rule-style/c
(symbols 'vertical 'compact-vertical 'vertical-overlapping-side-conditions 'horizontal)
parameter
(arrow-space space) → void? space : natural-number/c
parameter
(label-space space) → void? space : natural-number/c
parameter
→
(or/c 'left-right 'up-down 'left-right/vertical-side-conditions 'up-down/vertical-side-conditions 'left-right/compact-side-conditions 'up-down/compact-side-conditions 'left-right/beside-side-conditions) (metafunction-pict-style style) → void?
style :
(or/c 'left-right 'up-down 'left-right/vertical-side-conditions 'up-down/vertical-side-conditions 'left-right/compact-side-conditions 'up-down/compact-side-conditions 'left-right/beside-side-conditions)
The 'left-right/vertical-side-conditions and 'up-down/vertical-side-conditions variants format side conditions each on a separate line, instead of all on the same line.
The 'left-right/compact-side-conditions and 'up-down/compact-side-conditions variants move side conditions to separate lines to avoid making the rendered form wider than it would be otherwise.
The 'left-right/beside-side-conditions variant is like 'left-right, except it puts the side-conditions on the same line, instead of on a new line below the case.
parameter
(delimit-ellipsis-arguments? delimit?) → void? delimit? : any/c
parameter
(linebreaks) → (or/c #f (listof boolean?))
(linebreaks breaks) → void? breaks : (or/c #f (listof boolean?))
If its value is a list, the length of the list must match the number of cases and each boolean indicates if that case has a linebreak or not.
This influences the 'left/right styles only.
parameter
→
(or/c #f (and/c (listof (and/c integer? (or/c zero? positive?))) pair?)) (metafunction-cases cases) → void?
cases :
(or/c #f (and/c (listof (and/c integer? (or/c zero? positive?))) pair?))
This parameter also controls how which clauses in judgment forms are rendered, but only in the case that judgment-form-cases is #f.
parameter
→
(or/c #f (and/c (listof (or/c exact-nonnegative-integer? string?)) pair?)) (judgment-form-cases cases) → void?
cases :
(or/c #f (and/c (listof (or/c exact-nonnegative-integer? string?)) pair?))
parameter
(label-style style) → void? style : text-style/c
parameter
(grammar-style style) → void? style : text-style/c
parameter
(paren-style style) → void? style : text-style/c
parameter
(literal-style style) → void? style : text-style/c
parameter
(metafunction-style style) → void? style : text-style/c
parameter
(non-terminal-style style) → void? style : text-style/c
parameter
(non-terminal-subscript-style style) → void? style : text-style/c
parameter
(non-terminal-superscript-style style) → void? style : text-style/c
parameter
(default-style style) → void? style : text-style/c
The label-style is used for the reduction rule label names. The literal-style is used for names that aren’t non-terminals that appear in patterns. The metafunction-style is used for the names of metafunctions. The paren-style is used for the parentheses (including “[”, “]”, “{”, and “}”, as well as “(” and “)”), but not for the square brackets used for in-hole decompositions, which use the default-style. The grammar-style is used for the “::=” and “|” in grammars.
The non-terminal-style parameter is used for the names of non-terminals. Two parameters style the text in the (optional) "underscore" component of a non-terminal reference. The first, non-terminal-subscript-style, applies to the segment between the underscore and the first caret (^) to follow it; the second, non-terminal-superscript-style, applies to the segment following that caret. For example, in the non-terminal reference x_y^z, x has style non-terminal-style, y has style non-terminal-subscript-style, and z has style non-terminal-superscript-style.
The default-style is used for parenthesis, the dot in dotted lists, spaces, the "where" and "fresh" in side-conditions, and other places where the other parameters aren’t used.
parameter
(label-font-size) → (and/c (between/c 1 255) integer?)
(label-font-size size) → void? size : (and/c (between/c 1 255) integer?)
parameter
(metafunction-font-size) →
(and/c (between/c 1 255) integer?) (metafunction-font-size size) → void?
size :
(and/c (between/c 1 255) integer?)
parameter
(default-font-size) → (and/c (between/c 1 255) integer?)
(default-font-size size) → void? size : (and/c (between/c 1 255) integer?)
parameter
→ (parameter/c (and/c integer? positive? exact?)) (reduction-relation-rule-separation sep) → void? sep : (parameter/c (and/c integer? positive? exact?))
parameter
(curly-quotes-for-strings on?) → void? on? : boolean?
Defaults to #t.
parameter
(current-text proc) → void? proc : (-> string? text-style/c number? pict?)
procedure
(arrow->pict arrow) → pict?
arrow : symbol?
procedure
(set-arrow-pict! arrow proc) → void?
arrow : symbol? proc : (-> pict?)
parameter
→ (-> string? number? (values number? number? number? number?)) (white-bracket-sizing proc) → void? proc : (-> string? number? (values number? number? number? number?))
The procedure accepts a string that is either "[" or "]", and returns four numbers. The first two numbers determine the offset (from the left and from the right respectively) for the second square bracket, and the second two two numbers determine the extra space added (to the left and to the right respectively).
(λ (str size) (let ([inset-amt (floor/even (max 4 (* size 1/2)))]) (cond [(equal? str "[") (values inset-amt 0 0 (/ inset-amt 2))] [else (values 0 inset-amt (/ inset-amt 2) 0)])))
where floor/even returns the nearest even number below its argument. This means that for sizes 9, 10, and 11, inset-amt will be 4, and for 12, 13, 14, and 15, inset-amt will be 6.
parameter
→ (parameter/c exact-nonnegative-integer?) (horizontal-bar-spacing space) → void? space : (parameter/c exact-nonnegative-integer?)
parameter
→ (parameter/c (-> (listof pict?) pict?)) (relation-clauses-combine combine) → void? combine : (parameter/c (-> (listof pict?) pict?))
2.8.3 Removing the Pink Background
When reduction rules, a metafunction, or a grammar contains unquoted Racket code or side-conditions, they are rendered with a pink background as a guide to help find them and provide an alternative typesetting for them. In general, a good goal for a PLT Redex program that you intend to typeset is to only include such things when they correspond to standard mathematical operations, and the Racket code is an implementation of those operations.
To replace the pink code, use:
syntax
(with-unquote-rewriter proc expression)
The proc should be a function of one argument. It receives a lw struct as an argument and should return another lw that contains a rewritten version of the code.
syntax
(with-atomic-rewriter name-symbol string-or-thunk-returning-pict expression)
name-symbol is expected to evaluate to a symbol. The value of string-or-thunk-returning-pict is used whever the symbol appears in a pattern.
syntax
(with-compound-rewriter name-symbol proc expression)
name-symbol is expected to evaluate to a symbol. The value of proc is called with a (listof lw), and is expected to return a new (listof (or/c lw? string? pict?)), rewritten appropriately.
The list passed to the rewriter corresponds to the lw for the sequence that has name-symbol’s value at its head.
The result list is constrained to have at most 2 adjacent non-lws. That list is then transformed by adding lw structs for each of the non-lws in the list (see the text just below the description of lw for a explanation of logical space):
If there are two adjacent lws, then the logical space between them is filled with whitespace.
If there is a pair of lws with just a single non-lw between them, a lw will be created (containing the non-lw) that uses all of the available logical space between the lws.
If there are two adjacent non-lws between two lws, the first non-lw is rendered right after the first lw with a logical space of zero, and the second is rendered right before the last lw also with a logical space of zero, and the logical space between the two lws is absorbed by a new lw that renders using no actual space in the typeset version.
One useful way to take advantage of with-compound-rewriters is to return a list that begins and ends with "" (the empty string). In that situation, any extra logical space that would have been just outside the sequence is replaced with an lw that does not draw anything at all.
syntax
(with-compound-rewriters ([name-symbol proc] ...) expression)
struct
(struct lw ( e line line-span column column-span unq? metafunction?) #:constructor-name make-lw #:mutable)
e :
(or/c string? symbol? pict? (listof (or/c (symbols 'spring) lw?))) line : exact-positive-integer? line-span : exact-positive-integer? column : exact-positive-integer? column-span : exact-positive-integer? unq? : boolean? metafunction? : boolean?
The values of the unq? and metafunction? fields, respectively, indicate whether the lw represents an unquoted expression or a metafunction application. See to-lw for the meanings of the other fields.
procedure
e :
(or/c string? symbol? pict? (listof (or/c (symbols 'spring) lw?))) line : exact-positive-integer? line-span : exact-positive-integer? column : exact-positive-integer? column-span : exact-positive-integer?
syntax
(to-lw arg)
Each sub-expression corresponds to its own lw, and the element indicates what kind of subexpression it is. If the element is a list, then the lw corresponds to a parenthesized sequence, and the list contains a lw for the open paren, one lw for each component of the sequence and then a lw for the close parenthesis. In the case of a dotted list, there will also be a lw in the third-to-last position for the dot.
For example, this expression:
(a)
becomes this lw (assuming the above expression appears as the first thing in the file):
(build-lw (list (build-lw "(" 0 0 0 1) (build-lw 'a 0 0 1 1) (build-lw ")" 0 0 2 1)) 0 0 0 3)
If there is some whitespace in the sequence, like this one:
(a b)
then there is no lw that corresponds to that whitespace; instead there is a logical gap between the lws.
(build-lw (list (build-lw "(" 0 0 0 1) (build-lw 'a 0 0 1 1) (build-lw 'b 0 0 3 1) (build-lw ")" 0 0 4 1)) 0 0 0 5)
In general, identifiers are represented with symbols and parenthesis are represented with strings and picts can be inserted to render arbitrary pictures.
The line, line-span, column, and column-span correspond to the logical spacing for the redex program, not the actual spacing that will be used when they are rendered. The logical spacing is only used when determining where to place typeset portions of the program. In the absence of any rewriters, these numbers correspond to the line and column numbers in the original program.
The line and column are absolute numbers from the beginning of the file containing the expression. The column number is not necessarily the column of the open parenthesis in a sequence – it is the leftmost column that is occupied by anything in the sequence. The line-span is the number of lines, and the column span is the number of columns on the last line (not the total width).
When there are multiple lines, lines are aligned based on the logical space (ie, the line/column & line-span/column-span) fields of the lws. As an example, if this is the original pattern:
(all good boys deserve fudge)
then the leftmost edges of the words "good" and "deserve" will be lined up underneath each other, but the relative positions of "boys" and "fudge" will be determined by the natural size of the words as they rendered in the appropriate font.
When 'spring appears in the list in the e field of a lw struct, then it absorbs all of the space around it. It is also used by to-lw when constructing the picts for unquoted strings. For example, this expression
,x
corresponds to these structs:
(build-lw (list (build-lw "" 1 0 9 0) 'spring (build-lw x 1 0 10 1)) 1 0 9 2)
and the 'spring causes there to be no space between the empty string and the x in the typeset output.
procedure
language/nts : (or/c (listof symbol?) compiled-lang?) lw : lw?
This function sets dc-for-text-size. See also lw->pict.
procedure
language/ntw : (or/c (listof symbol?) compiled-lang?) lw : lw?
This does not set the dc-for-text-size parameter. See also render-lw.
procedure
(just-before stuff lw) → lw?
stuff : (or/c pict? string? symbol?) lw : lw?
procedure
(just-after stuff lw) → lw?
stuff : (or/c pict? string? symbol?) lw : lw?