macro: Allow macro A to use its arguments as part of call to macro B.
[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, every positional argument must be given a
247 value in the same order as the defintion.
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, and even to be
270 omitted.  When one is omitted, a default value is used: either the
271 value specified in @code{!DEFAULT(@i{value})}, or an empty value
272 otherwise.
273
274 In declaration and calls, a keyword argument's name may not begin with
275 @samp{!}, but references to it in the macro body do start with a
276 leading @samp{!}.
277
278 The following example uses a keyword argument that defaults to ALL if
279 the argument is not assigned a value:
280
281 @example
282 DEFINE !analyze_kw(vars=!DEFAULT(ALL) !CMDEND)
283 DESCRIPTIVES !vars.
284 FREQUENCIES /VARIABLES=!vars.
285 !ENDDEFINE.
286
287 !analyze_kw vars=v1 v2 v3.  /* Analyze specified variables.
288 !analyze_kw.                /* Analyze all variables.
289 @end example
290 @end itemize
291
292 If a macro has both positional and keyword arguments, then the
293 positional arguments must come first in the DEFINE command, and their
294 values also come first in macro calls.
295
296 Each argument declaration specifies the form of its value:
297
298 @table @code
299 @item !TOKENS(@i{count})
300 Exactly @var{count} tokens, e.g.@: @code{!TOKENS(1)} for a single
301 token.  Each identifier, number, quoted string, operator, or
302 punctuator is a token.  @xref{Tokens}, for a complete definition.
303
304 The following variant of @code{!analyze_kw} accepts only a single
305 variable name (or @code{ALL}) as its argument:
306
307 @example
308 DEFINE !analyze_one_var(!POSITIONAL !TOKENS(1))
309 DESCRIPTIVES !1.
310 FREQUENCIES /VARIABLES=!1.
311 !ENDDEFINE.
312
313 !analyze_one_var v1.
314 @end example
315
316 @item !CHAREND('@var{token}')
317 Any number of tokens up to @var{token}, which should be an operator or
318 punctuator token such as @samp{/} or @samp{+}.  The @var{token} does
319 not become part of the value.
320
321 With the following variant of @code{!analyze_kw}, the variables must
322 be following by @samp{/}:
323
324 @example
325 DEFINE !analyze_parens(vars=!CHARNED('/'))
326 DESCRIPTIVES !vars.
327 FREQUENCIES /VARIABLES=!vars.
328 !ENDDEFINE.
329
330 !analyze_parens vars=v1 v2 v3/.
331 @end example
332
333 @item !ENCLOSE('@var{start}','@var{end}')
334 Any number of tokens enclosed between @var{start} and @var{end}, which
335 should each be operator or punctuator tokens.  For example, use
336 @code{!ENCLOSE('(',')')} for a value enclosed within parentheses.
337 (Such a value could never have right parentheses inside it, even
338 paired with left parentheses.)  The start and end tokens are not part
339 of the value.
340
341 With the following variant of @code{!analyze_kw}, the variables must
342 be specified within parentheses:
343
344 @example
345 DEFINE !analyze_parens(vars=!ENCLOSE('(',')'))
346 DESCRIPTIVES !vars.
347 FREQUENCIES /VARIABLES=!vars.
348 !ENDDEFINE.
349
350 !analyze_parens vars=(v1 v2 v3).
351 @end example
352
353 @item !CMDEND
354 Any number of tokens up to the end of the command.  This should be
355 used only for the last positional parameter, since it consumes all of
356 the tokens in the command calling the macro.
357
358 The following variant of @code{!analyze_kw} takes all the variable
359 names up to the end of the command as its argument:
360
361 @example
362 DEFINE !analyze_kw(vars=!CMDEND)
363 DESCRIPTIVES !vars.
364 FREQUENCIES /VARIABLES=!vars.
365 !ENDDEFINE.
366
367 !analyze_kw vars=v1 v2 v3.
368 @end example
369 @end table
370
371 By default, when an argument's value contains a macro call, the call
372 is expanded each time the argument appears in the macro's body.  The
373 @code{!NOEXPAND} keyword in an argument declaration suppresses this
374 expansion.  @xref{Controlling Macro Expansion}.
375
376 @node Controlling Macro Expansion
377 @subsection Controlling Macro Expansion
378
379 Multiple factors control whether macro calls are expanded in different
380 situations.  At the highest level, @code{SET MEXPAND} controls whether
381 macro calls are expanded.  By default, it is enabled.  @xref{SET
382 MEXPAND}, for details.
383
384 A macro body may contain macro calls.  By default, these are expanded.
385 If a macro body contains @code{!OFFEXPAND} or @code{!ONEXPAND}
386 directives, then @code{!OFFEXPAND} disables expansion of macro calls
387 until the following @code{!ONEXPAND}.
388
389 A macro argument's value may contain a macro call.  These macro calls
390 are expanded, unless the argument was declared with the
391 @code{!NOEXPAND} keyword.
392
393 The argument to a macro function is a special context that does not
394 expand macro calls.  For example, if @code{!vars} is the name of a
395 macro, then @code{!LENGTH(!vars)} expands to 5, as does
396 @code{!LENGTH(!1)} if positional argument 1 has value @code{!vars}.
397 To expand macros in these cases, use the @code{!EVAL} macro function,
398 e.g.@: @code{!LENGTH(!EVAL(!vars))} or @code{!LENGTH(!EVAL(!1))}.
399 @xref{Macro Functions}, for details.
400
401 These rules apply to macro calls, not to uses within a macro body of
402 macro functions, macro arguments, and macro variables created by
403 @code{!DO} or @code{!LET}, which are always expanded.
404
405 @node Macro Functions
406 @subsection Macro Functions
407
408 Macro bodies may manipulate syntax using macro functions.  Macro
409 functions accept tokens as arguments and expand to sequences of
410 characters.
411
412 The arguments to macro functions have a restricted form.  They may
413 only be a single token (such as an identifier or a string), a macro
414 argument, or a call to a macro function.  Thus, the following are
415 valid macro arguments:
416 @example
417 x    5.0    x    !1    "5 + 6"    !CONCAT(x,y)
418 @end example
419 @noindent and the following are not:
420 @example
421 x y    5+6
422 @end example
423
424 Macro functions expand to sequences of characters.  When these
425 character strings are processed further as character strings, e.g.@:
426 with @code{!LENGTH}, any character string is valid.  When they are
427 interpreted as PSPP syntax, e.g.@: when the expansion becomes part of
428 a command, they need to be valid for that purpose.  For example,
429 @code{!UNQUOTE("It's")} will yield an error if the expansion
430 @code{It's} becomes part of a PSPP command, because it contains
431 unbalanced single quotes, but @code{!LENGTH(!UNQUOTE("It's"))} expands
432 to 4.
433
434 The following macro functions are available.  Each function's
435 documentation includes examples in the form @code{@var{call}
436 @expansion{} @var{expansion}}.
437
438 @deffn {Macro Function} !BLANKS (count)
439 Expands to @var{count} unquoted spaces, where @var{count} is a
440 nonnegative integer.  Outside quotes, any positive number of spaces
441 are equivalent; for a quoted string of spaces, use
442 @code{!QUOTE(!BLANKS(@var{count}))}.
443
444 In the examples below, @samp{_} stands in for a space to make the
445 results visible.
446
447 @c Keep these examples in sync with the test for !BLANKS in
448 @c tests/language/control/define.at:
449 @example
450 !BLANKS(0)                  @expansion{} @r{empty}
451 !BLANKS(1)                  @expansion{} _
452 !BLANKS(2)                  @expansion{} __
453 !QUOTE(!BLANKS(5))          @expansion{} '_____'
454 @end example
455 @end deffn
456
457 @deffn {Macro Function} !CONCAT (arg@dots{})
458 Expands to the concatenation of all of the arguments.  Before
459 concatenation, each quoted string argument is unquoted, as if
460 @code{!UNQUOTE} were applied.  This allows for ``token pasting'',
461 combining two (or more) tokens into a single one:
462
463 @c Keep these examples in sync with the test for !CONCAT in
464 @c tests/language/control/define.at:
465 @example
466 !CONCAT(x, y)                @expansion{} xy
467 !CONCAT('x', 'y')            @expansion{} xy
468 !CONCAT(12, 34)              @expansion{} 1234
469 !CONCAT(!NULL, 123)          @expansion{} 123
470 @end example
471
472 @code{!CONCAT} is often used for constructing a series of similar
473 variable names from a prefix followed by a number and perhaps a
474 suffix.  For example:
475
476 @c Keep these examples in sync with the test for !CONCAT in
477 @c tests/language/control/define.at:
478 @example
479 !CONCAT(x, 0)                @expansion{} x0
480 !CONCAT(x, 0, y)             @expansion{} x0y
481 @end example
482
483 An identifier token must begin with a letter (or @samp{#} or
484 @samp{@@}), which means that attempting to use a number as the first
485 part of an identifier will produce a pair of distinct tokens rather
486 than a single one.  For example:
487
488 @c Keep these examples in sync with the test for !CONCAT in
489 @c tests/language/control/define.at:
490 @example
491 !CONCAT(0, x)                @expansion{} 0 x
492 !CONCAT(0, x, y)             @expansion{} 0 xy
493 @end example
494 @end deffn
495
496 @deffn {Macro Function} !EVAL (arg)
497 Expands macro calls in @var{arg}.  This is especially useful if
498 @var{arg} is the name of a macro or a macro argument that expands to
499 one, because arguments to macro functions are not expanded by default
500 (@pxref{Controlling Macro Expansion}).
501
502 The following examples assume that @code{!vars} is a macro that
503 expands to @code{a b c}:
504
505 @example
506 !vars                        @expansion{} a b c
507 !QUOTE(!vars)                @expansion{} '!vars'
508 !EVAL(!vars)                 @expansion{} a b c
509 !QUOTE(!EVAL(!vars))         @expansion{} 'a b c'
510 @end example
511
512 These examples additionally assume that argument @code{!1} has value
513 @code{!vars}:
514
515 @example
516 !1                           @expansion{} a b c
517 !QUOTE(!1)                   @expansion{} '!vars'
518 !EVAL(!1)                    @expansion{} a b c
519 !QUOTE(!EVAL(!1))            @expansion{} 'a b c'
520 @end example
521 @end deffn
522
523 @deffn {Macro Function} !HEAD (arg)
524 @deffnx {Macro Function} !TAIL (arg)
525 @code{!HEAD} expands to just the first token in an unquoted version of
526 @var{arg}, and @code{!TAIL} to all the tokens after the first.
527
528 @example
529 !HEAD('a b c')               @expansion{} a
530 !HEAD('a')                   @expansion{} a
531 !HEAD(!NULL)                 @expansion{} @r{empty}
532 !HEAD('')                    @expansion{} @r{empty}
533
534 !TAIL('a b c')               @expansion{} b c
535 !TAIL('a')                   @expansion{} @r{empty}
536 !TAIL(!NULL)                 @expansion{} @r{empty}
537 !TAIL('')                    @expansion{} @r{empty}
538 @end example
539 @end deffn
540
541 @deffn {Macro Function} !INDEX (haystack, needle)
542 Looks for @var{needle} in @var{haystack}.  If it is present, expands
543 to the 1-based index of its first occurrence; if not, expands to 0.
544
545 @example
546 !INDEX(banana, an)           @expansion{} 2
547 !INDEX(banana, nan)          @expansion{} 3
548 !INDEX(banana, apple)        @expansion{} 0
549 !INDEX("banana", nan)        @expansion{} 4
550 !INDEX("banana", "nan")      @expansion{} 0
551 !INDEX(!UNQUOTE("banana"), !UNQUOTE("nan")) @expansion{} 3
552 @end example
553 @end deffn
554
555 @deffn {Macro Function} !LENGTH (arg)
556 Expands to a number token representing the number of characters in
557 @var{arg}.
558
559 @example
560 !LENGTH(123)                 @expansion{} 3
561 !LENGTH(123.00)              @expansion{} 6
562 !LENGTH( 123 )               @expansion{} 3
563 !LENGTH("123")               @expansion{} 5
564 !LENGTH(xyzzy)               @expansion{} 5
565 !LENGTH("xyzzy")             @expansion{} 7
566 !LENGTH("xy""zzy")           @expansion{} 9
567 !LENGTH(!UNQUOTE("xyzzy"))   @expansion{} 5
568 !LENGTH(!UNQUOTE("xy""zzy")) @expansion{} 6
569 !LENGTH(!1)                  @expansion{} 5 @r{if @t{!1} is @t{a b c}}
570 !LENGTH(!1)                  @expansion{} 0 @r{if @t{!1} is empty}
571 !LENGTH(!NULL)               @expansion{} 0
572 @end example
573 @end deffn
574
575 @deffn {Macro Function} !NULL
576 Expands to an empty character sequence.
577
578 @example
579 !NULL                        @expansion{} @r{empty}
580 !QUOTE(!NULL)                @expansion{} ''
581 @end example
582 @end deffn
583
584 @deffn {Macro Function} !QUOTE (arg)
585 @deffnx {Macro Function} !UNQUOTE (arg)
586 The @code{!QUOTE} function expands to its argument surrounded by
587 apostrophes, doubling any apostrophes inside the argument to make sure
588 that it is valid PSPP syntax for a string.  If the argument was
589 already a quoted string, @code{!QUOTE} expands to it unchanged.
590
591 Given a quoted string argument, the @code{!UNQUOTED} function expands
592 to the string's contents, with the quotes removed and any doubled
593 quote marks reduced to singletons.  If the argument was not a quoted
594 string, @code{!UNQUOTE} expands to the argument unchanged.
595
596 @example
597 !QUOTE(123.0)                @expansion{} '123.0'
598 !QUOTE( 123 )                @expansion{} '123'
599 !QUOTE('a b c')              @expansion{} 'a b c'
600 !QUOTE("a b c")              @expansion{} "a b c"
601 !QUOTE(!1)                   @expansion{} 'a ''b'' c' @r{if @t{!1} is @t{a 'b' c}}
602
603 !UNQUOTE(123.0)              @expansion{} 123.0
604 !UNQUOTE( 123 )              @expansion{} 123
605 !UNQUOTE('a b c')            @expansion{} a b c
606 !UNQUOTE("a b c")            @expansion{} a b c
607 !UNQUOTE(!1)                 @expansion{} a 'b' c @r{if @t{!1} is @t{a 'b' c}}
608
609 !QUOTE(!UNQUOTE(123.0))      @expansion{} '123.0'
610 !QUOTE(!UNQUOTE( 123 ))      @expansion{} '123'
611 !QUOTE(!UNQUOTE('a b c'))    @expansion{} 'a b c'
612 !QUOTE(!UNQUOTE("a b c"))    @expansion{} 'a b c'
613 !QUOTE(!UNQUOTE(!1))         @expansion{} 'a ''b'' c' @r{if @t{!1} is @t{a 'b' c}}
614 @end example
615 @end deffn
616
617 @deffn {Macro Function} !SUBSTR (arg, start[, count])
618 Expands to a substring of @var{arg} starting from 1-based position
619 @var{start}.  If @var{count} is given, it limits the number of
620 characters in the expansion; if it is omitted, then the expansion
621 extends to the end of @var{arg}.
622
623 @example
624 !SUBSTR(banana, 3)           @expansion{} nana
625 !SUBSTR(banana, 3, 3)        @expansion{} nan
626 !SUBSTR("banana", 1, 3)         @expansion{} @r{error (@code{"ba} is not a valid token)}
627 !SUBSTR(!UNQUOTE("banana"), 3) @expansion{} nana
628 !SUBSTR("banana", 3, 3)      @expansion{} ana
629
630 !SUBSTR(banana, 3, 0)        @expansion{} @r{empty}
631 !SUBSTR(banana, 3, 10)       @expansion{} nana
632 !SUBSTR(banana, 10, 3)       @expansion{} @r{empty}
633 @end example
634 @end deffn
635
636 @deffn {Macro Function} !UPCASE (arg)
637 Expands to an unquoted version of @var{arg} with all letters converted
638 to uppercase.
639
640 @example
641 !UPCASE(freckle)             @expansion{} FRECKLE
642 !UPCASE('freckle')           @expansion{} FRECKLE
643 !UPCASE('a b c')             @expansion{} A B C
644 !UPCASE('A B C')             @expansion{} A B C
645 @end example
646 @end deffn
647
648 @node Macro Expressions
649 @subsection Macro Expressions
650
651 Macro expressions are used in conditional expansion and loops, which
652 are described in the following sections.  A macro expression may use
653 the following operators, listed in descending order of operator
654 precedence:
655
656 @table @code
657 @item ()
658 Parentheses override the default operator precedence.
659
660 @item !EQ !NE !GT !LT !GE !LE = ~= <> > < >= <=
661 Relational operators compare their operands and yield a Boolean
662 result, either @samp{0} for false or @samp{1} for true.
663
664 These operators always compare their operands as strings.  This can be
665 surprising when the strings are numbers because, e.g.,@: @code{1 <
666 1.0} and @code{10 < 2} both evaluate to @samp{1} (true).
667
668 Comparisons are case sensitive, so that @code{a = A} evaluates to
669 @samp{0} (false).
670
671 @item !NOT ~
672 @itemx !AND &
673 @itemx !OR |
674 Logical operators interpret their operands as Boolean values, where
675 quoted or unquoted @samp{0} is false and anything else is true, and
676 yield a Boolean result, either @samp{0} for false or @samp{1} for
677 true.
678 @end table
679
680 Macro expressions do not include any arithmetic operators.
681
682 An operand in an expression may be a single token (including a macro
683 argument name) or a macro function invocation.  Either way, the
684 expression evaluator unquotes the operand, so that @code{1 = '1'} is
685 true.
686
687 @node Macro Conditional Expansion
688 @subsection Macro Conditional Expansion
689
690 The @code{!IF} construct may be used inside a macro body to allow for
691 conditional expansion.  It takes the following forms:
692
693 @example
694 !IF (@var{expression}) !THEN @var{true-expansion} !IFEND
695 !IF (@var{expression}) !THEN @var{true-expansion} !ELSE @var{false-expansion} !IFEND
696 @end example
697
698 When @var{expression} evaluates to true, the macro processor expands
699 @var{true-expansion}; otherwise, it expands @var{false-expansion}, if
700 it is present.  The macro processor considers quoted or unquoted
701 @samp{0} to be false, and anything else to be true.
702
703 @node Macro Loops
704 @subsection Macro Loops
705
706 The body of a macro may include two forms of loops: loops over
707 numerical ranges and loops over tokens.  Both forms expand a @dfn{loop
708 body} multiple times, each time setting a named @dfn{loop variable} to
709 a different value.  The loop body typically expands the loop variable
710 at least once.
711
712 The MITERATE setting (@pxref{SET MITERATE}) limits the number of
713 iterations in a loop.  This is a safety measure to ensure that macro
714 expansion terminates.  PSPP issues a warning when the MITERATE limit
715 is exceeded.
716
717 @subsubheading Loops Over Ranges
718
719 @example
720 !DO @var{!var} = @var{start} !TO @var{end} [!BY @var{step}]
721   @var{body}
722 !DOEND
723 @end example
724
725 A loop over a numerical range has the form shown above.  @var{start},
726 @var{end}, and @var{step} (if included) must be expressions with
727 numeric values.  The macro processor accepts both integers and real
728 numbers.  The macro processor expands @var{body} for each numeric
729 value from @var{start} to @var{end}, inclusive.
730
731 The default value for @var{step} is 1.  If @var{step} is positive and
732 @math{@var{first} > @var{last}}, or if @var{step} is negative and
733 @math{@var{first} < @var{last}}, then the macro processor doesn't
734 expand the body at all.  @var{step} may not be zero.
735
736 @subsubheading Loops Over Tokens
737
738 @example
739 !DO @var{!var} !IN (@var{expression})
740   @var{body}
741 !DOEND
742 @end example
743
744 A loop over tokens takes the form shown above.  The macro processor
745 evaluates @var{expression} and expands @var{body} once per token in
746 the result, substituting the token for @var{!var} each time it
747 appears.
748
749 @node Macro Variable Assignment
750 @subsection Macro Variable Assignment
751
752 The @code{!LET} construct evaluates an expression and assigns the
753 result to a macro variable.  It may create a new macro variable or
754 change the value of one created by a previous @code{!LET} or
755 @code{!DO}, but it may not change the value of a macro argument.
756 @code{!LET} has the following form:
757
758 @example
759 !LET @var{!var} = @var{expression}
760 @end example
761
762 If @var{expression} is more than one token, it must be enclosed in
763 parentheses.
764
765 @node Macro Settings
766 @subsection Macro Settings
767
768 Some macro behavior is controlled through the SET command
769 (@pxref{SET}).  This section describes these settings.
770
771 Any SET command that changes these settings within a macro body only
772 takes effect following the macro.  This is because PSPP expands a
773 macro's entire body at once, so that the SET command inside the body
774 only executes afterwards.
775
776 The MEXPAND setting (@pxref{SET MEXPAND}) controls whether macros will
777 be expanded at all.  By default, macro expansion is on.  To avoid
778 expansion of macros called within a macro body, use @code{!OFFEXPAND}
779 and @code{!ONEXPAND} (@pxref{Controlling Macro Expansion}).
780
781 When MPRINT (@pxref{SET MPRINT}) is turned on, PSPP outputs an
782 expansion of each macro called.  This feature can be useful for
783 debugging macro definitions.  For reading the expanded version, note
784 that macro expansion removes comments and standardizes white space.
785
786 MNEST (@pxref{SET MNEST}) limits the depth of expansion of macro
787 calls, that is, the nesting level of macro expansion.  The default is
788 50.  This is mainly useful to avoid infinite expansion in the case of
789 a macro that calls itself.
790
791 MITERATE (@pxref{SET MITERATE}) limits the number of iterations in a
792 @code{!DO} construct.  The default is 1000.
793
794 PRESERVE...RESTORE
795
796 SET MEXPAND, etc. doesn't work inside macro bodies.
797
798 @node Macro Notes
799 @subsection Additional Notes
800
801 @subsubsection Calling Macros from Macros
802
803 If the body of macro A includes a call to macro B, the call can use
804 macro arguments (including @code{!*}) and macro variables as part of
805 arguments to B.  For @code{!TOKENS} arguments, the argument or
806 variable name counts as one token regardless of the number that
807 expands into, for @code{!CHAREND} and @code{!ENCLOSE} arguments the
808 delimiters come only from the call, not the expansions, and
809 @code{!CMDEND} ends at the calling command, not any end of command
810 within an argument or variable.
811
812 Macro functions are not supported as part of the arguments in a macro
813 call.  To get the same effect, use @code{!LET} to define a macro
814 variable, then pass the macro variable to the macro.
815
816 When macro A calls macro B, the order of their @code{DEFINE} commands
817 doesn't matter, as long as macro B has been defined when A is called.
818
819 @subsubsection Command Terminators
820
821 Macros and command terminators require care.  Macros honor the syntax
822 differences between interactive and batch syntax (@pxref{Syntax
823 Variants}), which means that the interpretation of a macro can vary
824 depending on the syntax mode in use.  We assume here that interactive
825 mode is in use, in which @samp{.}@: at the end of a line is the
826 primary way to end a command.
827
828 The @code{DEFINE} command needs to end with @samp{.}@: following the
829 @code{!ENDDEFINE}.  The macro body may contain @samp{.}@: if it is
830 intended to expand to whole commands, but using @samp{.}@: within a
831 macro body that expands to just syntax fragments (such as a list of
832 variables) will cause syntax errors.
833
834 Macro directives such as @code{!IF} and @code{!DO} do not end with
835 @samp{.}.
836
837 @subsubsection Expansion Contexts
838
839 Macros do not expand within comments, whether introduced within a line
840 by @code{/*} or as a separate COMMENT or @samp{*} commands
841 (@pxref{COMMENT}).  (SPSS does expand macros in COMMENT and @samp{*}.)
842
843 Macros do not expand within quoted strings.
844
845 Macros are expanded in the @code{TITLE} and @code{SUBTITLE} commands
846 as long as their arguments are not quoted strings.
847
848 @subsubsection PRESERVE and RESTORE
849
850 Some macro bodies might use the SET command to change certain
851 settings.  When this is the case, consider using the PRESERVE and
852 RESTORE commands to save and then restore these settings.
853 @xref{PRESERVE and RESTORE}.
854
855 @node DO IF
856 @section DO IF
857 @vindex DO IF
858
859 @display
860 DO IF condition.
861         @dots{}
862 [ELSE IF condition.
863         @dots{}
864 ]@dots{}
865 [ELSE.
866         @dots{}]
867 END IF.
868 @end display
869
870 @cmd{DO IF} allows one of several sets of transformations to be
871 executed, depending on user-specified conditions.
872
873 If the specified boolean expression evaluates as true, then the block
874 of code following @cmd{DO IF} is executed.  If it evaluates as
875 missing, then
876 none of the code blocks is executed.  If it is false, then
877 the boolean expression on the first @cmd{ELSE IF}, if present, is tested in
878 turn, with the same rules applied.  If all expressions evaluate to
879 false, then the @cmd{ELSE} code block is executed, if it is present.
880
881 When @cmd{DO IF} or @cmd{ELSE IF} is specified following @cmd{TEMPORARY}
882 (@pxref{TEMPORARY}), the @cmd{LAG} function may not be used
883 (@pxref{LAG}).
884
885 @node DO REPEAT
886 @section DO REPEAT
887 @vindex DO REPEAT
888
889 @display
890 DO REPEAT dummy_name=expansion@dots{}.
891         @dots{}
892 END REPEAT [PRINT].
893
894 expansion takes one of the following forms:
895         var_list
896         num_or_range@dots{}
897         'string'@dots{}
898         ALL
899
900 num_or_range takes one of the following forms:
901         number
902         num1 TO num2
903 @end display
904
905 @cmd{DO REPEAT} repeats a block of code, textually substituting
906 different variables, numbers, or strings into the block with each
907 repetition.
908
909 Specify a dummy variable name followed by an equals sign (@samp{=})
910 and the list of replacements.  Replacements can be a list of existing
911 or new variables, numbers, strings, or @code{ALL} to specify all
912 existing variables.  When numbers are specified, runs of increasing
913 integers may be indicated as @code{@var{num1} TO @var{num2}}, so that
914 @samp{1 TO 5} is short for @samp{1 2 3 4 5}.
915
916 Multiple dummy variables can be specified.  Each
917 variable must have the same number of replacements.
918
919 The code within @cmd{DO REPEAT} is repeated as many times as there are
920 replacements for each variable.  The first time, the first value for
921 each dummy variable is substituted; the second time, the second value
922 for each dummy variable is substituted; and so on.
923
924 Dummy variable substitutions work like macros.  They take place
925 anywhere in a line that the dummy variable name occurs.  This includes
926 command and subcommand names, so command and subcommand names that
927 appear in the code block should not be used as dummy variable
928 identifiers.  Dummy variable substitutions do not occur inside quoted
929 strings, comments, unquoted strings (such as the text on the
930 @cmd{TITLE} or @cmd{DOCUMENT} command), or inside @cmd{BEGIN
931 DATA}@dots{}@cmd{END DATA}.
932
933 Substitution occurs only on whole words, so that, for example, a dummy
934 variable PRINT would not be substituted into the word PRINTOUT.
935
936 New variable names used as replacements are not automatically created
937 as variables, but only if used in the code block in a context that
938 would create them, @i{e.g.}@: on a @cmd{NUMERIC} or @cmd{STRING} command
939 or on the left side of a @cmd{COMPUTE} assignment.
940
941 Any command may appear within @subcmd{DO REPEAT}, including nested @subcmd{DO REPEAT}
942 commands.  If @cmd{INCLUDE} or @cmd{INSERT} appears within @subcmd{DO REPEAT},
943 the substitutions do not apply to the included file.
944
945 If @subcmd{PRINT} is specified on @cmd{END REPEAT}, the commands after
946 substitutions are made should be printed to the listing file, prefixed
947 by a plus sign (@samp{+}).  This feature is not yet implemented.
948
949 @node LOOP
950 @section LOOP
951 @vindex LOOP
952
953 @display
954 LOOP [@var{index_var}=@var{start} TO @var{end} [BY @var{incr}]] [IF @var{condition}].
955         @dots{}
956 END LOOP [IF @var{condition}].
957 @end display
958
959 @cmd{LOOP} iterates a group of commands.  A number of
960 termination options are offered.
961
962 Specify index_var to make that variable count from one value to
963 another by a particular increment.  @var{index_var} must be a pre-existing
964 numeric variable.  @var{start}, @var{end}, and @var{incr} are numeric expressions
965 (@pxref{Expressions}.)
966
967 During the first iteration, @var{index_var} is set to the value of @var{start}.
968 During each successive iteration, @var{index_var} is increased by the value of
969 @var{incr}.  If @var{end} > @var{start}, then the loop terminates
970 when @var{index_var} > @var{end};
971 otherwise it terminates when @var{index_var} < @var{end}.  If @var{incr} is not specified
972 then it defaults to +1 or -1 as appropriate.
973
974 If @var{end} > @var{start} and @var{incr} < 0, or if @var{end} < @var{start} and
975  @var{incr} > 0, then the
976 loop is never executed.  @var{index_var} is nevertheless set to the value of
977 start.
978
979 Modifying @var{index_var} within the loop is allowed, but it has no effect on
980 the value of @var{index_var} in the next iteration.
981
982 Specify a boolean expression for the condition on @cmd{LOOP} to
983 cause the loop to be executed only if the condition is true.  If the
984 condition is false or missing before the loop contents are executed the
985 first time, the loop contents are not executed at all.
986
987 If index and condition clauses are both present on @cmd{LOOP}, the
988 index variable is always set before the condition is evaluated.  Thus,
989 a condition that makes use of the index variable will always see the
990 index value to be used in the next execution of the body.
991
992 Specify a boolean expression for the condition on @cmd{END LOOP} to cause
993 the loop to terminate if the condition is true after the enclosed
994 code block is executed.  The condition is evaluated at the end of the
995 loop, not at the beginning, so that the body of a loop with only a
996 condition on @cmd{END LOOP} will always execute at least once.
997
998 If the index clause is not
999 present, then the loop is executed at most @var{max_loops} (@pxref{SET}) times
1000 (but possibly fewer, if a condition clause evaluates to false or if
1001 @cmd{BREAK} executes).
1002 The default value of @var{max_loops} is 40.
1003
1004 @cmd{BREAK} also terminates @cmd{LOOP} execution (@pxref{BREAK}).
1005
1006 Loop index variables are by default reset to system-missing from one
1007 case to another, not left, unless a scratch variable is used as index.
1008 When loops are nested, this is usually undesired behavior, which can
1009 be corrected with @cmd{LEAVE} (@pxref{LEAVE}) or by using a scratch
1010 variable as the loop index.
1011
1012 When @cmd{LOOP} or @cmd{END LOOP} is specified following @cmd{TEMPORARY}
1013 (@pxref{TEMPORARY}), the @cmd{LAG} function may not be used
1014 (@pxref{LAG}).