macro: Fix crash for !QUOTE of a quoted string.
[pspp] / doc / flow-control.texi
1 @c PSPP - a program for statistical analysis.
2 @c Copyright (C) 2017, 2020 Free Software Foundation, Inc.
3 @c Permission is granted to copy, distribute and/or modify this document
4 @c under the terms of the GNU Free Documentation License, Version 1.3
5 @c or any later version published by the Free Software Foundation;
6 @c with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
7 @c A copy of the license is included in the section entitled "GNU
8 @c Free Documentation License".
9 @c
10
11 @node Conditionals and Looping
12 @chapter Conditional and Looping Constructs
13 @cindex conditionals
14 @cindex loops
15 @cindex flow of control
16 @cindex control flow
17
18 This chapter documents @pspp{} commands used for conditional execution,
19 looping, and flow of control.
20
21 @menu
22 * BREAK::                       Exit a loop.
23 * DEFINE::                      Define a macro.
24 * DO IF::                       Conditionally execute a block of code.
25 * DO REPEAT::                   Textually repeat a code block.
26 * LOOP::                        Repeat a block of code.
27 @end menu
28
29 @node BREAK
30 @section BREAK
31 @vindex BREAK
32
33 @display
34 BREAK.
35 @end display
36
37 @cmd{BREAK} terminates execution of the innermost currently executing
38 @cmd{LOOP} construct.
39
40 @cmd{BREAK} is allowed only inside @cmd{LOOP}@dots{}@cmd{END LOOP}.
41 @xref{LOOP}, for more details.
42
43 @node DEFINE
44 @section DEFINE
45 @vindex DEFINE
46 @cindex macro
47
48 @subsection Overview
49
50 @display
51 @t{DEFINE} @i{macro_name}@t{(}@r{[}@i{argument}@r{[}@t{/}@i{argument}@r{]@dots{}]}@t{)}
52 @dots{}@i{body}@dots{}
53 @t{!ENDDEFINE.}
54 @end display
55
56 Each @i{argument} takes the following form:
57 @display
58 @r{@{}@i{!arg_name} @t{=},@t{!POSITIONAL}@r{@}}
59 @r{[}@t{!DEFAULT(}@i{default}@t{)}@r{]}
60 @r{[}@t{!NOEXPAND}@r{]}
61 @r{@{}@t{!TOKENS(}@i{count}@t{)},@t{!CHAREND('}@i{token}@t{')},@t{!ENCLOSE('}@i{start}@t{','}@i{end}@t{')},@t{!CMDEND}@}
62 @end display
63
64 The following directives may be used within @i{body}:
65 @example
66 !OFFEXPAND
67 !ONEXPAND
68 @end example
69
70 The following functions may be used within the body:
71 @display
72 @t{!BLANKS(}@i{count}@t{)}
73 @t{!CONCAT(}@i{arg}@dots{}@t{)}
74 @t{!EVAL(}@i{arg}@t{)}
75 @t{!HEAD(}@i{arg}@t{)}
76 @t{!INDEX(}@i{haystack}@t{,} @i{needle}@t{)}
77 @t{!LENGTH(}@i{arg}@t{)}
78 @t{!NULL}
79 @t{!QUOTE(}@i{arg}@t{)}
80 @t{!SUBSTR(}@i{arg}@t{,} @i{start}[@t{,} @i{count}]@t{)}
81 @t{!TAIL(}@i{arg}@t{)}
82 @t{!UNQUOTE(}@i{arg}@t{)}
83 @t{!UPCASE(}@i{arg}@t{)}
84 @end display
85
86 The body may also include the following constructs:
87 @display
88 @t{!IF (}@i{condition}@t{) !THEN} @i{true-expansion} @t{!ENDIF}
89 @t{!IF (}@i{condition}@t{) !THEN} @i{true-expansion} @t{!ELSE} @i{false-expansion} @t{!ENDIF}
90
91 @t{!DO} @i{!var} @t{=} @i{start} @t{!TO} @i{end} [@t{!BY} @i{step}]
92   @i{body}
93 @t{!DOEND}
94 @t{!DO} @i{!var} @t{!IN} @t{(}@i{expression}@t{)}
95   @i{body}
96 @t{!DOEND}
97
98 @t{!LET} @i{!var} @t{=} @i{expression}
99 @end display
100
101 @subsection Introduction
102
103 The DEFINE command creates a @dfn{macro}, which is a name for a
104 fragment of PSPP syntax called the macro's @dfn{body}.  Following the
105 DEFINE command, syntax may @dfn{call} the macro by name any number of
106 times.  Each call substitutes, or @dfn{expands}, the macro's body in
107 place of the call, as if the body had been written in its place.
108
109 The following syntax defines a macro named @code{!vars} that expands
110 to the variable names @code{v1 v2 v3}.  The macro's name begins with
111 @samp{!}, which is optional for macro names.  The @code{()} following
112 the macro name are required:
113
114 @example
115 DEFINE !vars()
116 v1 v2 v3
117 !ENDDEFINE.
118 @end example
119
120 Here are two ways that @code{!vars} might be called given the
121 preceding definition:
122
123 @example
124 DESCRIPTIVES !vars.
125 FREQUENCIES /VARIABLES=!vars.
126 @end example
127
128 With macro expansion, the above calls are equivalent to the following:
129
130 @example
131 DESCRIPTIVES v1 v2 v3.
132 FREQUENCIES /VARIABLES=v1 v2 v3.
133 @end example
134
135 The @code{!vars} macro expands to a fixed body.  Macros may have more
136 sophisticated contents:
137
138 @itemize @bullet
139 @item
140 Macro @dfn{arguments} that are substituted into the body whenever they
141 are named.  The values of a macro's arguments are specified each time
142 it is called.  @xref{Macro Arguments}.
143
144 @item
145 Macro @dfn{functions}, expanded when the macro is called.  @xref{Macro
146 Functions}.
147
148 @item
149 @code{!IF} constructs, for conditional expansion.  @xref{Macro
150 Conditional Expansion}.
151
152 @item
153 Two forms of @code{!DO} construct, for looping over a numerical range
154 or a collection of tokens.  @xref{Macro Loops}.
155
156 @item
157 @code{!LET} constructs, for assigning to macro variables.  @xref{Macro
158 Variable Assignment}.
159 @end itemize
160
161 Many identifiers associated with macros begin with @samp{!}, a
162 character not normally allowed in identifiers.  These identifiers are
163 reserved only for use with macros, which helps keep them from being
164 confused with other kinds of identifiers.
165
166 The following sections provide more details on macro syntax and
167 semantics.
168
169 @node Macro Bodies
170 @subsection Macro Bodies
171
172 As previously shown, a macro body may contain a fragment of a PSPP
173 command (such as a variable name).  A macro body may also contain full
174 PSPP commands.  In the latter case, the macro body should also contain
175 the command terminators.
176
177 Most PSPP commands may occur within a macro.  The @code{DEFINE}
178 command itself is one exception, because the inner @code{!ENDDEFINE}
179 ends the outer macro definition.  For compatibility, @code{BEGIN
180 DATA}@dots{}@code{END DATA.} should not be used within a macro.
181
182 The body of a macro may call another macro.  The following shows one
183 way that could work:
184
185 @example
186 DEFINE !commands()
187 DESCRIPTIVES !vars.
188 FREQUENCIES /VARIABLES=!vars.
189 !ENDDEFINE.
190
191 DEFINE !vars() v1 v2 v3 !ENDDEFINE.
192 !commands
193
194 * We can redefine the variables macro to analyze different variables:
195 DEFINE !vars() v4 v5 !ENDDEFINE.
196 !commands
197 @end example
198
199 The @code{!commands} macro would be easier to use if it took the
200 variables to analyze as an argument rather than through another macro.
201 The following section shows how to do that.
202
203 @node Macro Arguments
204 @subsection Macro Arguments
205
206 This section explains how to use macro arguments.  As an initial
207 example, the following syntax defines a macro named @code{!analyze}
208 that takes all the syntax up to the first command terminator as an
209 argument:
210
211 @example
212 DEFINE !analyze(!POSITIONAL !CMDEND)
213 DESCRIPTIVES !1.
214 FREQUENCIES /VARIABLES=!1.
215 !ENDDEFINE.
216 @end example
217
218 @noindent When @code{!analyze} is called, it expands to a pair of analysis
219 commands with each @code{!1} in the body replaced by the argument.
220 That is, these calls:
221
222 @example
223 !analyze v1 v2 v3.
224 !analyze v4 v5.
225 @end example
226
227 @noindent act like the following:
228
229 @example
230 DESCRIPTIVES v1 v2 v3.
231 FREQUENCIES /VARIABLES=v1 v2 v3.
232 DESCRIPTIVES v4 v5.
233 FREQUENCIES /VARIABLES=v4 v5.
234 @end example
235
236 Macros may take any number of arguments, described within the
237 parentheses in the DEFINE command.  Arguments come in two varieties
238 based on how their values are specified when the macro is called:
239
240 @itemize @bullet
241 @item
242 A @dfn{positional} argument has a required value that follows the
243 macro's name.  Use the @code{!POSITIONAL} keyword to declare a
244 positional argument.
245
246 When a macro is called, the positional argument values appear in the
247 same order as their definitions, before any keyword argument values.
248
249 References to a positional argument in a macro body are numbered:
250 @code{!1} is the first positional argument, @code{!2} the second, and
251 so on.  In addition, @code{!*} expands to all of the positional
252 arguments' values, separated by spaces.
253
254 The following example uses a positional argument:
255
256 @example
257 DEFINE !analyze(!POSITIONAL !CMDEND)
258 DESCRIPTIVES !1.
259 FREQUENCIES /VARIABLES=!1.
260 !ENDDEFINE.
261
262 !analyze v1 v2 v3.
263 !analyze v4 v5.
264 @end example
265
266 @item
267 A @dfn{keyword} argument has a name.  In the macro call, its value is
268 specified with the syntax @code{@i{name}=@i{value}}.  The names allow
269 keyword argument values to take any order in the call.
270
271 In declaration and calls, a keyword argument's name may not begin with
272 @samp{!}, but references to it in the macro body do start with a
273 leading @samp{!}.
274
275 The following example uses a keyword argument that defaults to ALL if
276 the argument is not assigned a value:
277
278 @example
279 DEFINE !analyze_kw(vars=!DEFAULT(ALL) !CMDEND)
280 DESCRIPTIVES !vars.
281 FREQUENCIES /VARIABLES=!vars.
282 !ENDDEFINE.
283
284 !analyze_kw vars=v1 v2 v3.  /* Analyze specified variables.
285 !analyze_kw.                /* Analyze all variables.
286 @end example
287 @end itemize
288
289 If a macro has both positional and keyword arguments, then the
290 positional arguments must come first in the DEFINE command, and their
291 values also come first in macro calls.  A keyword argument may be
292 omitted by leaving its keyword out of the call, and a positional
293 argument may be omitted by putting a command terminator where it would
294 appear.  (The latter case also omits any following positional
295 arguments and all keyword arguments, if there are any.)  When an
296 argument is omitted, a default value is used: either the value
297 specified in @code{!DEFAULT(@i{value})}, or an empty value otherwise.
298
299 Each argument declaration specifies the form of its value:
300
301 @table @code
302 @item !TOKENS(@i{count})
303 Exactly @var{count} tokens, e.g.@: @code{!TOKENS(1)} for a single
304 token.  Each identifier, number, quoted string, operator, or
305 punctuator is a token.  @xref{Tokens}, for a complete definition.
306
307 The following variant of @code{!analyze_kw} accepts only a single
308 variable name (or @code{ALL}) as its argument:
309
310 @example
311 DEFINE !analyze_one_var(!POSITIONAL !TOKENS(1))
312 DESCRIPTIVES !1.
313 FREQUENCIES /VARIABLES=!1.
314 !ENDDEFINE.
315
316 !analyze_one_var v1.
317 @end example
318
319 @item !CHAREND('@var{token}')
320 Any number of tokens up to @var{token}, which should be an operator or
321 punctuator token such as @samp{/} or @samp{+}.  The @var{token} does
322 not become part of the value.
323
324 With the following variant of @code{!analyze_kw}, the variables must
325 be following by @samp{/}:
326
327 @example
328 DEFINE !analyze_parens(vars=!CHARNED('/'))
329 DESCRIPTIVES !vars.
330 FREQUENCIES /VARIABLES=!vars.
331 !ENDDEFINE.
332
333 !analyze_parens vars=v1 v2 v3/.
334 @end example
335
336 @item !ENCLOSE('@var{start}','@var{end}')
337 Any number of tokens enclosed between @var{start} and @var{end}, which
338 should each be operator or punctuator tokens.  For example, use
339 @code{!ENCLOSE('(',')')} for a value enclosed within parentheses.
340 (Such a value could never have right parentheses inside it, even
341 paired with left parentheses.)  The start and end tokens are not part
342 of the value.
343
344 With the following variant of @code{!analyze_kw}, the variables must
345 be specified within parentheses:
346
347 @example
348 DEFINE !analyze_parens(vars=!ENCLOSE('(',')'))
349 DESCRIPTIVES !vars.
350 FREQUENCIES /VARIABLES=!vars.
351 !ENDDEFINE.
352
353 !analyze_parens vars=(v1 v2 v3).
354 @end example
355
356 @item !CMDEND
357 Any number of tokens up to the end of the command.  This should be
358 used only for the last positional parameter, since it consumes all of
359 the tokens in the command calling the macro.
360
361 The following variant of @code{!analyze_kw} takes all the variable
362 names up to the end of the command as its argument:
363
364 @example
365 DEFINE !analyze_kw(vars=!CMDEND)
366 DESCRIPTIVES !vars.
367 FREQUENCIES /VARIABLES=!vars.
368 !ENDDEFINE.
369
370 !analyze_kw vars=v1 v2 v3.
371 @end example
372 @end table
373
374 By default, when an argument's value contains a macro call, the call
375 is expanded each time the argument appears in the macro's body.  The
376 @code{!NOEXPAND} keyword in an argument declaration suppresses this
377 expansion.  @xref{Controlling Macro Expansion}.
378
379 @node Controlling Macro Expansion
380 @subsection Controlling Macro Expansion
381
382 Multiple factors control whether macro calls are expanded in different
383 situations.  At the highest level, @code{SET MEXPAND} controls whether
384 macro calls are expanded.  By default, it is enabled.  @xref{SET
385 MEXPAND}, for details.
386
387 A macro body may contain macro calls.  By default, these are expanded.
388 If a macro body contains @code{!OFFEXPAND} or @code{!ONEXPAND}
389 directives, then @code{!OFFEXPAND} disables expansion of macro calls
390 until the following @code{!ONEXPAND}.
391
392 A macro argument's value may contain a macro call.  These macro calls
393 are expanded, unless the argument was declared with the
394 @code{!NOEXPAND} keyword.
395
396 The argument to a macro function is a special context that does not
397 expand macro calls.  For example, if @code{!vars} is the name of a
398 macro, then @code{!LENGTH(!vars)} expands to 5, as does
399 @code{!LENGTH(!1)} if positional argument 1 has value @code{!vars}.
400 To expand macros in these cases, use the @code{!EVAL} macro function,
401 e.g.@: @code{!LENGTH(!EVAL(!vars))} or @code{!LENGTH(!EVAL(!1))}.
402 @xref{Macro Functions}, for details.
403
404 These rules apply to macro calls, not to uses within a macro body of
405 macro functions, macro arguments, and macro variables created by
406 @code{!DO} or @code{!LET}, which are always expanded.
407
408 @node Macro Functions
409 @subsection Macro Functions
410
411 Macro bodies may manipulate syntax using macro functions.  Macro
412 functions accept tokens as arguments and expand to sequences of
413 characters.
414
415 The arguments to macro functions have a restricted form.  They may
416 only be a single token (such as an identifier or a string), a macro
417 argument, or a call to a macro function.  Thus, the following are
418 valid macro arguments:
419 @example
420 x    5.0    x    !1    "5 + 6"    !CONCAT(x,y)
421 @end example
422 @noindent and the following are not:
423 @example
424 x y    5+6
425 @end example
426
427 Macro functions expand to sequences of characters.  When these
428 character strings are processed further as character strings, e.g.@:
429 with @code{!LENGTH}, any character string is valid.  When they are
430 interpreted as PSPP syntax, e.g.@: when the expansion becomes part of
431 a command, they need to be valid for that purpose.  For example,
432 @code{!UNQUOTE("It's")} will yield an error if the expansion
433 @code{It's} becomes part of a PSPP command, because it contains
434 unbalanced single quotes, but @code{!LENGTH(!UNQUOTE("It's"))} expands
435 to 4.
436
437 The following macro functions are available.  Each function's
438 documentation includes examples in the form @code{@var{call}
439 @expansion{} @var{expansion}}.
440
441 @deffn {Macro Function} !BLANKS (count)
442 Expands to @var{count} unquoted spaces, where @var{count} is a
443 nonnegative integer.  Outside quotes, any positive number of spaces
444 are equivalent; for a quoted string of spaces, use
445 @code{!QUOTE(!BLANKS(@var{count}))}.
446
447 In the examples below, @samp{_} stands in for a space to make the
448 results visible.
449
450 @c Keep these examples in sync with the test for !BLANKS in
451 @c tests/language/control/define.at:
452 @example
453 !BLANKS(0)                  @expansion{} @r{empty}
454 !BLANKS(1)                  @expansion{} _
455 !BLANKS(2)                  @expansion{} __
456 !QUOTE(!BLANKS(5))          @expansion{} '_____'
457 @end example
458 @end deffn
459
460 @deffn {Macro Function} !CONCAT (arg@dots{})
461 Expands to the concatenation of all of the arguments.  Before
462 concatenation, each quoted string argument is unquoted, as if
463 @code{!UNQUOTE} were applied.  This allows for ``token pasting'',
464 combining two (or more) tokens into a single one:
465
466 @c Keep these examples in sync with the test for !CONCAT in
467 @c tests/language/control/define.at:
468 @example
469 !CONCAT(x, y)                @expansion{} xy
470 !CONCAT('x', 'y')            @expansion{} xy
471 !CONCAT(12, 34)              @expansion{} 1234
472 !CONCAT(!NULL, 123)          @expansion{} 123
473 @end example
474
475 @code{!CONCAT} is often used for constructing a series of similar
476 variable names from a prefix followed by a number and perhaps a
477 suffix.  For example:
478
479 @c Keep these examples in sync with the test for !CONCAT in
480 @c tests/language/control/define.at:
481 @example
482 !CONCAT(x, 0)                @expansion{} x0
483 !CONCAT(x, 0, y)             @expansion{} x0y
484 @end example
485
486 An identifier token must begin with a letter (or @samp{#} or
487 @samp{@@}), which means that attempting to use a number as the first
488 part of an identifier will produce a pair of distinct tokens rather
489 than a single one.  For example:
490
491 @c Keep these examples in sync with the test for !CONCAT in
492 @c tests/language/control/define.at:
493 @example
494 !CONCAT(0, x)                @expansion{} 0 x
495 !CONCAT(0, x, y)             @expansion{} 0 xy
496 @end example
497 @end deffn
498
499 @deffn {Macro Function} !EVAL (arg)
500 Expands macro calls in @var{arg}.  This is especially useful if
501 @var{arg} is the name of a macro or a macro argument that expands to
502 one, because arguments to macro functions are not expanded by default
503 (@pxref{Controlling Macro Expansion}).
504
505 The following examples assume that @code{!vars} is a macro that
506 expands to @code{a b c}:
507
508 @example
509 !vars                        @expansion{} a b c
510 !QUOTE(!vars)                @expansion{} '!vars'
511 !EVAL(!vars)                 @expansion{} a b c
512 !QUOTE(!EVAL(!vars))         @expansion{} 'a b c'
513 @end example
514
515 These examples additionally assume that argument @code{!1} has value
516 @code{!vars}:
517
518 @example
519 !1                           @expansion{} a b c
520 !QUOTE(!1)                   @expansion{} '!vars'
521 !EVAL(!1)                    @expansion{} a b c
522 !QUOTE(!EVAL(!1))            @expansion{} 'a b c'
523 @end example
524 @end deffn
525
526 @deffn {Macro Function} !HEAD (arg)
527 @deffnx {Macro Function} !TAIL (arg)
528 @code{!HEAD} expands to just the first token in an unquoted version of
529 @var{arg}, and @code{!TAIL} to all the tokens after the first.
530
531 @example
532 !HEAD('a b c')               @expansion{} a
533 !HEAD('a')                   @expansion{} a
534 !HEAD(!NULL)                 @expansion{} @r{empty}
535 !HEAD('')                    @expansion{} @r{empty}
536
537 !TAIL('a b c')               @expansion{} b c
538 !TAIL('a')                   @expansion{} @r{empty}
539 !TAIL(!NULL)                 @expansion{} @r{empty}
540 !TAIL('')                    @expansion{} @r{empty}
541 @end example
542 @end deffn
543
544 @deffn {Macro Function} !INDEX (haystack, needle)
545 Looks for @var{needle} in @var{haystack}.  If it is present, expands
546 to the 1-based index of its first occurrence; if not, expands to 0.
547
548 @example
549 !INDEX(banana, an)           @expansion{} 2
550 !INDEX(banana, nan)          @expansion{} 3
551 !INDEX(banana, apple)        @expansion{} 0
552 !INDEX("banana", nan)        @expansion{} 4
553 !INDEX("banana", "nan")      @expansion{} 0
554 !INDEX(!UNQUOTE("banana"), !UNQUOTE("nan")) @expansion{} 3
555 @end example
556 @end deffn
557
558 @deffn {Macro Function} !LENGTH (arg)
559 Expands to a number token representing the number of characters in
560 @var{arg}.
561
562 @example
563 !LENGTH(123)                 @expansion{} 3
564 !LENGTH(123.00)              @expansion{} 6
565 !LENGTH( 123 )               @expansion{} 3
566 !LENGTH("123")               @expansion{} 5
567 !LENGTH(xyzzy)               @expansion{} 5
568 !LENGTH("xyzzy")             @expansion{} 7
569 !LENGTH("xy""zzy")           @expansion{} 9
570 !LENGTH(!UNQUOTE("xyzzy"))   @expansion{} 5
571 !LENGTH(!UNQUOTE("xy""zzy")) @expansion{} 6
572 !LENGTH(!1)                  @expansion{} 5 @r{if @t{!1} is @t{a b c}}
573 !LENGTH(!1)                  @expansion{} 0 @r{if @t{!1} is empty}
574 !LENGTH(!NULL)               @expansion{} 0
575 @end example
576 @end deffn
577
578 @deffn {Macro Function} !NULL
579 Expands to an empty character sequence.
580
581 @c Keep these examples in sync with the test for !NULL in
582 @c tests/language/control/define.at:
583 @example
584 !NULL                        @expansion{} @r{empty}
585 !QUOTE(!NULL)                @expansion{} ''
586 @end example
587 @end deffn
588
589 @deffn {Macro Function} !QUOTE (arg)
590 @deffnx {Macro Function} !UNQUOTE (arg)
591 The @code{!QUOTE} function expands to its argument surrounded by
592 apostrophes, doubling any apostrophes inside the argument to make sure
593 that it is valid PSPP syntax for a string.  If the argument was
594 already a quoted string, @code{!QUOTE} expands to it unchanged.
595
596 Given a quoted string argument, the @code{!UNQUOTED} function expands
597 to the string's contents, with the quotes removed and any doubled
598 quote marks reduced to singletons.  If the argument was not a quoted
599 string, @code{!UNQUOTE} expands to the argument unchanged.
600
601 @c Keep these examples in sync with the test for !QUOTE and !UNQUOTE in
602 @c tests/language/control/define.at:
603 @example
604 !QUOTE(123.0)                @expansion{} '123.0'
605 !QUOTE( 123 )                @expansion{} '123'
606 !QUOTE('a b c')              @expansion{} 'a b c'
607 !QUOTE("a b c")              @expansion{} "a b c"
608 !QUOTE(!1)                   @expansion{} 'a ''b'' c' @r{if @t{!1} is @t{a 'b' c}}
609
610 !UNQUOTE(123.0)              @expansion{} 123.0
611 !UNQUOTE( 123 )              @expansion{} 123
612 !UNQUOTE('a b c')            @expansion{} a b c
613 !UNQUOTE("a b c")            @expansion{} a b c
614 !UNQUOTE(!1)                 @expansion{} a 'b' c @r{if @t{!1} is @t{a 'b' c}}
615
616 !QUOTE(!UNQUOTE(123.0))      @expansion{} '123.0'
617 !QUOTE(!UNQUOTE( 123 ))      @expansion{} '123'
618 !QUOTE(!UNQUOTE('a b c'))    @expansion{} 'a b c'
619 !QUOTE(!UNQUOTE("a b c"))    @expansion{} 'a b c'
620 !QUOTE(!UNQUOTE(!1))         @expansion{} 'a ''b'' c' @r{if @t{!1} is @t{a 'b' c}}
621 @end example
622 @end deffn
623
624 @deffn {Macro Function} !SUBSTR (arg, start[, count])
625 Expands to a substring of @var{arg} starting from 1-based position
626 @var{start}.  If @var{count} is given, it limits the number of
627 characters in the expansion; if it is omitted, then the expansion
628 extends to the end of @var{arg}.
629
630 @example
631 !SUBSTR(banana, 3)           @expansion{} nana
632 !SUBSTR(banana, 3, 3)        @expansion{} nan
633 !SUBSTR("banana", 1, 3)         @expansion{} @r{error (@code{"ba} is not a valid token)}
634 !SUBSTR(!UNQUOTE("banana"), 3) @expansion{} nana
635 !SUBSTR("banana", 3, 3)      @expansion{} ana
636
637 !SUBSTR(banana, 3, 0)        @expansion{} @r{empty}
638 !SUBSTR(banana, 3, 10)       @expansion{} nana
639 !SUBSTR(banana, 10, 3)       @expansion{} @r{empty}
640 @end example
641 @end deffn
642
643 @deffn {Macro Function} !UPCASE (arg)
644 Expands to an unquoted version of @var{arg} with all letters converted
645 to uppercase.
646
647 @example
648 !UPCASE(freckle)             @expansion{} FRECKLE
649 !UPCASE('freckle')           @expansion{} FRECKLE
650 !UPCASE('a b c')             @expansion{} A B C
651 !UPCASE('A B C')             @expansion{} A B C
652 @end example
653 @end deffn
654
655 @node Macro Expressions
656 @subsection Macro Expressions
657
658 Macro expressions are used in conditional expansion and loops, which
659 are described in the following sections.  A macro expression may use
660 the following operators, listed in descending order of operator
661 precedence:
662
663 @table @code
664 @item ()
665 Parentheses override the default operator precedence.
666
667 @item !EQ !NE !GT !LT !GE !LE = ~= <> > < >= <=
668 Relational operators compare their operands and yield a Boolean
669 result, either @samp{0} for false or @samp{1} for true.
670
671 These operators always compare their operands as strings.  This can be
672 surprising when the strings are numbers because, e.g.,@: @code{1 <
673 1.0} and @code{10 < 2} both evaluate to @samp{1} (true).
674
675 Comparisons are case sensitive, so that @code{a = A} evaluates to
676 @samp{0} (false).
677
678 @item !NOT ~
679 @itemx !AND &
680 @itemx !OR |
681 Logical operators interpret their operands as Boolean values, where
682 quoted or unquoted @samp{0} is false and anything else is true, and
683 yield a Boolean result, either @samp{0} for false or @samp{1} for
684 true.
685 @end table
686
687 Macro expressions do not include any arithmetic operators.
688
689 An operand in an expression may be a single token (including a macro
690 argument name) or a macro function invocation.  Either way, the
691 expression evaluator unquotes the operand, so that @code{1 = '1'} is
692 true.
693
694 @node Macro Conditional Expansion
695 @subsection Macro Conditional Expansion
696
697 The @code{!IF} construct may be used inside a macro body to allow for
698 conditional expansion.  It takes the following forms:
699
700 @example
701 !IF (@var{expression}) !THEN @var{true-expansion} !IFEND
702 !IF (@var{expression}) !THEN @var{true-expansion} !ELSE @var{false-expansion} !IFEND
703 @end example
704
705 When @var{expression} evaluates to true, the macro processor expands
706 @var{true-expansion}; otherwise, it expands @var{false-expansion}, if
707 it is present.  The macro processor considers quoted or unquoted
708 @samp{0} to be false, and anything else to be true.
709
710 @node Macro Loops
711 @subsection Macro Loops
712
713 The body of a macro may include two forms of loops: loops over
714 numerical ranges and loops over tokens.  Both forms expand a @dfn{loop
715 body} multiple times, each time setting a named @dfn{loop variable} to
716 a different value.  The loop body typically expands the loop variable
717 at least once.
718
719 The MITERATE setting (@pxref{SET MITERATE}) limits the number of
720 iterations in a loop.  This is a safety measure to ensure that macro
721 expansion terminates.  PSPP issues a warning when the MITERATE limit
722 is exceeded.
723
724 @subsubheading Loops Over Ranges
725
726 @example
727 !DO @var{!var} = @var{start} !TO @var{end} [!BY @var{step}]
728   @var{body}
729 !DOEND
730 @end example
731
732 A loop over a numerical range has the form shown above.  @var{start},
733 @var{end}, and @var{step} (if included) must be expressions with
734 numeric values.  The macro processor accepts both integers and real
735 numbers.  The macro processor expands @var{body} for each numeric
736 value from @var{start} to @var{end}, inclusive.
737
738 The default value for @var{step} is 1.  If @var{step} is positive and
739 @math{@var{first} > @var{last}}, or if @var{step} is negative and
740 @math{@var{first} < @var{last}}, then the macro processor doesn't
741 expand the body at all.  @var{step} may not be zero.
742
743 @subsubheading Loops Over Tokens
744
745 @example
746 !DO @var{!var} !IN (@var{expression})
747   @var{body}
748 !DOEND
749 @end example
750
751 A loop over tokens takes the form shown above.  The macro processor
752 evaluates @var{expression} and expands @var{body} once per token in
753 the result, substituting the token for @var{!var} each time it
754 appears.
755
756 @node Macro Variable Assignment
757 @subsection Macro Variable Assignment
758
759 The @code{!LET} construct evaluates an expression and assigns the
760 result to a macro variable.  It may create a new macro variable or
761 change the value of one created by a previous @code{!LET} or
762 @code{!DO}, but it may not change the value of a macro argument.
763 @code{!LET} has the following form:
764
765 @example
766 !LET @var{!var} = @var{expression}
767 @end example
768
769 If @var{expression} is more than one token, it must be enclosed in
770 parentheses.
771
772 @node Macro Settings
773 @subsection Macro Settings
774
775 Some macro behavior is controlled through the SET command
776 (@pxref{SET}).  This section describes these settings.
777
778 Any SET command that changes these settings within a macro body only
779 takes effect following the macro.  This is because PSPP expands a
780 macro's entire body at once, so that the SET command inside the body
781 only executes afterwards.
782
783 The MEXPAND setting (@pxref{SET MEXPAND}) controls whether macros will
784 be expanded at all.  By default, macro expansion is on.  To avoid
785 expansion of macros called within a macro body, use @code{!OFFEXPAND}
786 and @code{!ONEXPAND} (@pxref{Controlling Macro Expansion}).
787
788 When MPRINT (@pxref{SET MPRINT}) is turned on, PSPP outputs an
789 expansion of each macro called.  This feature can be useful for
790 debugging macro definitions.  For reading the expanded version, note
791 that macro expansion removes comments and standardizes white space.
792
793 MNEST (@pxref{SET MNEST}) limits the depth of expansion of macro
794 calls, that is, the nesting level of macro expansion.  The default is
795 50.  This is mainly useful to avoid infinite expansion in the case of
796 a macro that calls itself.
797
798 MITERATE (@pxref{SET MITERATE}) limits the number of iterations in a
799 @code{!DO} construct.  The default is 1000.
800
801 PRESERVE...RESTORE
802
803 SET MEXPAND, etc. doesn't work inside macro bodies.
804
805 @node Macro Notes
806 @subsection Additional Notes
807
808 @subsubsection Calling Macros from Macros
809
810 If the body of macro A includes a call to macro B, the call can use
811 macro arguments (including @code{!*}) and macro variables as part of
812 arguments to B.  For @code{!TOKENS} arguments, the argument or
813 variable name counts as one token regardless of the number that
814 expands into, for @code{!CHAREND} and @code{!ENCLOSE} arguments the
815 delimiters come only from the call, not the expansions, and
816 @code{!CMDEND} ends at the calling command, not any end of command
817 within an argument or variable.
818
819 Macro functions are not supported as part of the arguments in a macro
820 call.  To get the same effect, use @code{!LET} to define a macro
821 variable, then pass the macro variable to the macro.
822
823 When macro A calls macro B, the order of their @code{DEFINE} commands
824 doesn't matter, as long as macro B has been defined when A is called.
825
826 @subsubsection Command Terminators
827
828 Macros and command terminators require care.  Macros honor the syntax
829 differences between interactive and batch syntax (@pxref{Syntax
830 Variants}), which means that the interpretation of a macro can vary
831 depending on the syntax mode in use.  We assume here that interactive
832 mode is in use, in which @samp{.}@: at the end of a line is the
833 primary way to end a command.
834
835 The @code{DEFINE} command needs to end with @samp{.}@: following the
836 @code{!ENDDEFINE}.  The macro body may contain @samp{.}@: if it is
837 intended to expand to whole commands, but using @samp{.}@: within a
838 macro body that expands to just syntax fragments (such as a list of
839 variables) will cause syntax errors.
840
841 Macro directives such as @code{!IF} and @code{!DO} do not end with
842 @samp{.}.
843
844 @subsubsection Expansion Contexts
845
846 Macros do not expand within comments, whether introduced within a line
847 by @code{/*} or as a separate COMMENT or @samp{*} commands
848 (@pxref{COMMENT}).  (SPSS does expand macros in COMMENT and @samp{*}.)
849
850 Macros do not expand within quoted strings.
851
852 Macros are expanded in the @code{TITLE} and @code{SUBTITLE} commands
853 as long as their arguments are not quoted strings.
854
855 @subsubsection PRESERVE and RESTORE
856
857 Some macro bodies might use the SET command to change certain
858 settings.  When this is the case, consider using the PRESERVE and
859 RESTORE commands to save and then restore these settings.
860 @xref{PRESERVE and RESTORE}.
861
862 @node DO IF
863 @section DO IF
864 @vindex DO IF
865
866 @display
867 DO IF condition.
868         @dots{}
869 [ELSE IF condition.
870         @dots{}
871 ]@dots{}
872 [ELSE.
873         @dots{}]
874 END IF.
875 @end display
876
877 @cmd{DO IF} allows one of several sets of transformations to be
878 executed, depending on user-specified conditions.
879
880 If the specified boolean expression evaluates as true, then the block
881 of code following @cmd{DO IF} is executed.  If it evaluates as
882 missing, then
883 none of the code blocks is executed.  If it is false, then
884 the boolean expression on the first @cmd{ELSE IF}, if present, is tested in
885 turn, with the same rules applied.  If all expressions evaluate to
886 false, then the @cmd{ELSE} code block is executed, if it is present.
887
888 When @cmd{DO IF} or @cmd{ELSE IF} is specified following @cmd{TEMPORARY}
889 (@pxref{TEMPORARY}), the @cmd{LAG} function may not be used
890 (@pxref{LAG}).
891
892 @node DO REPEAT
893 @section DO REPEAT
894 @vindex DO REPEAT
895
896 @display
897 DO REPEAT dummy_name=expansion@dots{}.
898         @dots{}
899 END REPEAT [PRINT].
900
901 expansion takes one of the following forms:
902         var_list
903         num_or_range@dots{}
904         'string'@dots{}
905         ALL
906
907 num_or_range takes one of the following forms:
908         number
909         num1 TO num2
910 @end display
911
912 @cmd{DO REPEAT} repeats a block of code, textually substituting
913 different variables, numbers, or strings into the block with each
914 repetition.
915
916 Specify a dummy variable name followed by an equals sign (@samp{=})
917 and the list of replacements.  Replacements can be a list of existing
918 or new variables, numbers, strings, or @code{ALL} to specify all
919 existing variables.  When numbers are specified, runs of increasing
920 integers may be indicated as @code{@var{num1} TO @var{num2}}, so that
921 @samp{1 TO 5} is short for @samp{1 2 3 4 5}.
922
923 Multiple dummy variables can be specified.  Each
924 variable must have the same number of replacements.
925
926 The code within @cmd{DO REPEAT} is repeated as many times as there are
927 replacements for each variable.  The first time, the first value for
928 each dummy variable is substituted; the second time, the second value
929 for each dummy variable is substituted; and so on.
930
931 Dummy variable substitutions work like macros.  They take place
932 anywhere in a line that the dummy variable name occurs.  This includes
933 command and subcommand names, so command and subcommand names that
934 appear in the code block should not be used as dummy variable
935 identifiers.  Dummy variable substitutions do not occur inside quoted
936 strings, comments, unquoted strings (such as the text on the
937 @cmd{TITLE} or @cmd{DOCUMENT} command), or inside @cmd{BEGIN
938 DATA}@dots{}@cmd{END DATA}.
939
940 Substitution occurs only on whole words, so that, for example, a dummy
941 variable PRINT would not be substituted into the word PRINTOUT.
942
943 New variable names used as replacements are not automatically created
944 as variables, but only if used in the code block in a context that
945 would create them, @i{e.g.}@: on a @cmd{NUMERIC} or @cmd{STRING} command
946 or on the left side of a @cmd{COMPUTE} assignment.
947
948 Any command may appear within @subcmd{DO REPEAT}, including nested @subcmd{DO REPEAT}
949 commands.  If @cmd{INCLUDE} or @cmd{INSERT} appears within @subcmd{DO REPEAT},
950 the substitutions do not apply to the included file.
951
952 If @subcmd{PRINT} is specified on @cmd{END REPEAT}, the commands after
953 substitutions are made should be printed to the listing file, prefixed
954 by a plus sign (@samp{+}).  This feature is not yet implemented.
955
956 @node LOOP
957 @section LOOP
958 @vindex LOOP
959
960 @display
961 LOOP [@var{index_var}=@var{start} TO @var{end} [BY @var{incr}]] [IF @var{condition}].
962         @dots{}
963 END LOOP [IF @var{condition}].
964 @end display
965
966 @cmd{LOOP} iterates a group of commands.  A number of
967 termination options are offered.
968
969 Specify index_var to make that variable count from one value to
970 another by a particular increment.  @var{index_var} must be a pre-existing
971 numeric variable.  @var{start}, @var{end}, and @var{incr} are numeric expressions
972 (@pxref{Expressions}.)
973
974 During the first iteration, @var{index_var} is set to the value of @var{start}.
975 During each successive iteration, @var{index_var} is increased by the value of
976 @var{incr}.  If @var{end} > @var{start}, then the loop terminates
977 when @var{index_var} > @var{end};
978 otherwise it terminates when @var{index_var} < @var{end}.  If @var{incr} is not specified
979 then it defaults to +1 or -1 as appropriate.
980
981 If @var{end} > @var{start} and @var{incr} < 0, or if @var{end} < @var{start} and
982  @var{incr} > 0, then the
983 loop is never executed.  @var{index_var} is nevertheless set to the value of
984 start.
985
986 Modifying @var{index_var} within the loop is allowed, but it has no effect on
987 the value of @var{index_var} in the next iteration.
988
989 Specify a boolean expression for the condition on @cmd{LOOP} to
990 cause the loop to be executed only if the condition is true.  If the
991 condition is false or missing before the loop contents are executed the
992 first time, the loop contents are not executed at all.
993
994 If index and condition clauses are both present on @cmd{LOOP}, the
995 index variable is always set before the condition is evaluated.  Thus,
996 a condition that makes use of the index variable will always see the
997 index value to be used in the next execution of the body.
998
999 Specify a boolean expression for the condition on @cmd{END LOOP} to cause
1000 the loop to terminate if the condition is true after the enclosed
1001 code block is executed.  The condition is evaluated at the end of the
1002 loop, not at the beginning, so that the body of a loop with only a
1003 condition on @cmd{END LOOP} will always execute at least once.
1004
1005 If the index clause is not
1006 present, then the loop is executed at most @var{max_loops} (@pxref{SET}) times
1007 (but possibly fewer, if a condition clause evaluates to false or if
1008 @cmd{BREAK} executes).
1009 The default value of @var{max_loops} is 40.
1010
1011 @cmd{BREAK} also terminates @cmd{LOOP} execution (@pxref{BREAK}).
1012
1013 Loop index variables are by default reset to system-missing from one
1014 case to another, not left, unless a scratch variable is used as index.
1015 When loops are nested, this is usually undesired behavior, which can
1016 be corrected with @cmd{LEAVE} (@pxref{LEAVE}) or by using a scratch
1017 variable as the loop index.
1018
1019 When @cmd{LOOP} or @cmd{END LOOP} is specified following @cmd{TEMPORARY}
1020 (@pxref{TEMPORARY}), the @cmd{LAG} function may not be used
1021 (@pxref{LAG}).