tons of progress on macros
[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 of macro functions and
402 macro arguments within a macro body, which are always expanded.
403
404 @node Macro Functions
405 @subsection Macro Functions
406
407 Macro bodies may manipulate syntax using macro functions.  Macro
408 functions accept tokens as arguments and expand to sequences of
409 characters.
410
411 The arguments to macro functions have a restricted form.  They may
412 only be a single token (such as an identifier or a string), a macro
413 argument, or a call to a macro function.  Thus, the following are
414 valid macro arguments:
415 @example
416 x    5.0    x    !1    "5 + 6"    !CONCAT(x,y)
417 @end example
418 @noindent and the following are not:
419 @example
420 x y    5+6
421 @end example
422
423 Macro functions expand to sequences of characters.  When these
424 character strings are processed further as character strings, e.g.@:
425 with @code{!LENGTH}, any character string is valid.  When they are
426 interpreted as PSPP syntax, e.g.@: when the expansion becomes part of
427 a command, they need to be valid for that purpose.  For example,
428 @code{!UNQUOTE("It's")} will yield an error if the expansion
429 @code{It's} becomes part of a PSPP command, because it contains
430 unbalanced single quotes, but @code{!LENGTH(!UNQUOTE("It's"))} expands
431 to 4.
432
433 The following macro functions are available.  Each function's
434 documentation includes examples in the form @code{@var{call}
435 @expansion{} @var{expansion}}.
436
437 @deffn {Macro Function} !BLANKS (count)
438 Expands to @var{count} unquoted spaces, where @var{count} is a
439 nonnegative integer.  Outside quotes, any positive number of spaces
440 are equivalent; for a quoted string of spaces, use
441 @code{!QUOTE(!BLANKS(@var{count}))}.
442
443 In the examples below, @samp{_} stands in for a space to make the
444 results visible.
445
446 @c Keep these examples in sync with the test for !BLANKS in
447 @c tests/language/control/define.at:
448 @example
449 !BLANKS(0)                  @expansion{} @r{empty}
450 !BLANKS(1)                  @expansion{} _
451 !BLANKS(2)                  @expansion{} __
452 !QUOTE(!BLANKS(5))          @expansion{} '_____'
453 @end example
454 @end deffn
455
456 @deffn {Macro Function} !CONCAT (arg@dots{})
457 Expands to the concatenation of all of the arguments.  Before
458 concatenation, each quoted string argument is unquoted, as if
459 @code{!UNQUOTE} were applied.  This allows for ``token pasting'',
460 combining two (or more) tokens into a single one:
461
462 @c Keep these examples in sync with the test for !CONCAT in
463 @c tests/language/control/define.at:
464 @example
465 !CONCAT(x, y)                @expansion{} xy
466 !CONCAT('x', 'y')            @expansion{} xy
467 !CONCAT(12, 34)              @expansion{} 1234
468 !CONCAT(!NULL, 123)          @expansion{} 123
469 @end example
470
471 @code{!CONCAT} is often used for constructing a series of similar
472 variable names from a prefix followed by a number and perhaps a
473 suffix.  For example:
474
475 @c Keep these examples in sync with the test for !CONCAT in
476 @c tests/language/control/define.at:
477 @example
478 !CONCAT(x, 0)                @expansion{} x0
479 !CONCAT(x, 0, y)             @expansion{} x0y
480 @end example
481
482 An identifier token must begin with a letter (or @samp{#} or
483 @samp{@@}), which means that attempting to use a number as the first
484 part of an identifier will produce a pair of distinct tokens rather
485 than a single one.  For example:
486
487 @c Keep these examples in sync with the test for !CONCAT in
488 @c tests/language/control/define.at:
489 @example
490 !CONCAT(0, x)                @expansion{} 0 x
491 !CONCAT(0, x, y)             @expansion{} 0 xy
492 @end example
493 @end deffn
494
495 @deffn {Macro Function} !EVAL (arg)
496 Expands macro calls in @var{arg}.  This is especially useful if
497 @var{arg} is the name of a macro or a macro argument that expands to
498 one, because arguments to macro functions are not expanded by default
499 (@pxref{Controlling Macro Expansion}).
500
501 The following examples assume that @code{!vars} is a macro that
502 expands to @code{a b c}:
503
504 @example
505 !vars                        @expansion{} a b c
506 !QUOTE(!vars)                @expansion{} '!vars'
507 !EVAL(!vars)                 @expansion{} a b c
508 !QUOTE(!EVAL(!vars))         @expansion{} 'a b c'
509 @end example
510
511 These examples additionally assume that argument @code{!1} has value
512 @code{!vars}:
513
514 @example
515 !1                           @expansion{} a b c
516 !QUOTE(!1)                   @expansion{} '!vars'
517 !EVAL(!1)                    @expansion{} a b c
518 !QUOTE(!EVAL(!1))            @expansion{} 'a b c'
519 @end example
520 @end deffn
521
522 @deffn {Macro Function} !HEAD (arg)
523 @deffnx {Macro Function} !TAIL (arg)
524 @code{!HEAD} expands to just the first token in an unquoted version of
525 @var{arg}, and @code{!TAIL} to all the tokens after the first.
526
527 @example
528 !HEAD('a b c')               @expansion{} a
529 !HEAD('a')                   @expansion{} a
530 !HEAD(!NULL)                 @expansion{} @r{empty}
531 !HEAD('')                    @expansion{} @r{empty}
532
533 !TAIL('a b c')               @expansion{} b c
534 !TAIL('a')                   @expansion{} @r{empty}
535 !TAIL(!NULL)                 @expansion{} @r{empty}
536 !TAIL('')                    @expansion{} @r{empty}
537 @end example
538 @end deffn
539
540 @deffn {Macro Function} !INDEX (haystack, needle)
541 Looks for @var{needle} in @var{haystack}.  If it is present, expands
542 to the 1-based index of its first occurrence; if not, expands to 0.
543
544 @example
545 !INDEX(banana, an)           @expansion{} 2
546 !INDEX(banana, nan)          @expansion{} 3
547 !INDEX(banana, apple)        @expansion{} 0
548 !INDEX("banana", nan)        @expansion{} 4
549 !INDEX("banana", "nan")      @expansion{} 0
550 !INDEX(!UNQUOTE("banana"), !UNQUOTE("nan")) @expansion{} 3
551 @end example
552 @end deffn
553
554 @deffn {Macro Function} !LENGTH (arg)
555 Expands to a number token representing the number of characters in
556 @var{arg}.
557
558 @example
559 !LENGTH(123)                 @expansion{} 3
560 !LENGTH(123.00)              @expansion{} 6
561 !LENGTH( 123 )               @expansion{} 3
562 !LENGTH("123")               @expansion{} 5
563 !LENGTH(xyzzy)               @expansion{} 5
564 !LENGTH("xyzzy")             @expansion{} 7
565 !LENGTH("xy""zzy")           @expansion{} 9
566 !LENGTH(!UNQUOTE("xyzzy"))   @expansion{} 5
567 !LENGTH(!UNQUOTE("xy""zzy")) @expansion{} 6
568 !LENGTH(!1)                  @expansion{} 5 @r{if @t{!1} is @t{a b c}}
569 !LENGTH(!1)                  @expansion{} 0 @r{if @t{!1} is empty}
570 !LENGTH(!NULL)               @expansion{} 0
571 @end example
572 @end deffn
573
574 @deffn {Macro Function} !NULL
575 Expands to an empty character sequence.
576
577 @example
578 !NULL                        @expansion{} @r{empty}
579 !QUOTE(!NULL)                @expansion{} ''
580 @end example
581 @end deffn
582
583 @deffn {Macro Function} !QUOTE (arg)
584 @deffnx {Macro Function} !UNQUOTE (arg)
585 The @code{!QUOTE} function expands to its argument surrounded by
586 apostrophes, doubling any apostrophes inside the argument to make sure
587 that it is valid PSPP syntax for a string.  If the argument was
588 already a quoted string, @code{!QUOTE} expands to it unchanged.
589
590 Given a quoted string argument, the @code{!UNQUOTED} function expands
591 to the string's contents, with the quotes removed and any doubled
592 quote marks reduced to singletons.  If the argument was not a quoted
593 string, @code{!UNQUOTE} expands to the argument unchanged.
594
595 @example
596 !QUOTE(123.0)                @expansion{} '123.0'
597 !QUOTE( 123 )                @expansion{} '123'
598 !QUOTE('a b c')              @expansion{} 'a b c'
599 !QUOTE("a b c")              @expansion{} "a b c"
600 !QUOTE(!1)                   @expansion{} 'a ''b'' c' @r{if @t{!1} is @t{a 'b' c}}
601
602 !UNQUOTE(123.0)              @expansion{} 123.0
603 !UNQUOTE( 123 )              @expansion{} 123
604 !UNQUOTE('a b c')            @expansion{} a b c
605 !UNQUOTE("a b c")            @expansion{} a b c
606 !UNQUOTE(!1)                 @expansion{} a 'b' c @r{if @t{!1} is @t{a 'b' c}}
607
608 !QUOTE(!UNQUOTE(123.0))      @expansion{} '123.0'
609 !QUOTE(!UNQUOTE( 123 ))      @expansion{} '123'
610 !QUOTE(!UNQUOTE('a b c'))    @expansion{} 'a b c'
611 !QUOTE(!UNQUOTE("a b c"))    @expansion{} 'a b c'
612 !QUOTE(!UNQUOTE(!1))         @expansion{} 'a ''b'' c' @r{if @t{!1} is @t{a 'b' c}}
613 @end example
614 @end deffn
615
616 @deffn {Macro Function} !SUBSTR (arg, start[, count])
617 Expands to a substring of @var{arg} starting from 1-based position
618 @var{start}.  If @var{count} is given, it limits the number of
619 characters in the expansion; if it is omitted, then the expansion
620 extends to the end of @var{arg}.
621
622 @example
623 !SUBSTR(banana, 3)           @expansion{} nana
624 !SUBSTR(banana, 3, 3)        @expansion{} nan
625 !SUBSTR("banana", 3)         @expansion{} @r{error (@code{anana"} is not a valid token)}
626 !SUBSTR(!UNQUOTE("banana"), 3) @expansion{} nana
627 !SUBSTR("banana", 3, 3)      @expansion{} ana
628
629 !SUBSTR(banana, 3, 0)        @expansion{} @r{empty}
630 !SUBSTR(banana, 3, 10)       @expansion{} nana
631 !SUBSTR(banana, 10, 3)       @expansion{} @r{empty}
632 @end example
633 @end deffn
634
635 @deffn {Macro Function} !UPCASE (arg)
636 Expands to an unquoted version of @var{arg} with all letters converted
637 to uppercase.
638
639 @example
640 !UPCASE(freckle)             @expansion{} FRECKLE
641 !UPCASE('freckle')           @expansion{} FRECKLE
642 !UPCASE('a b c')             @expansion{} A B C
643 !UPCASE('A B C')             @expansion{} A B C
644 @end example
645 @end deffn
646
647 @node Macro Expressions
648 @subsection Macro Expressions
649
650 Macro expressions are used in conditional expansion and loops, which
651 are described in the following sections.  A macro expression may use
652 the following operators, listed in descending order of operator
653 precedence:
654
655 @table @code
656 @item ()
657 Parentheses override the default operator precedence.
658
659 @item !EQ !NE !GT !LT !GE !LE = ~= <> > < >= <=
660 Relational operators compare their operands and yield a Boolean
661 result, either @samp{0} for false or @samp{1} for true.
662
663 These operators always compare their operands as strings.  This can be
664 surprising when the strings are numbers because, e.g.,@: @code{1 <
665 1.0} and @code{10 < 2} both evaluate to @samp{1} (true).
666
667 Comparisons are case sensitive, so that @code{a = A} evaluates to
668 @samp{0} (false).
669
670 @item !NOT ~
671 @itemx !AND &
672 @itemx !OR |
673 Logical operators interpret their operands as Boolean values, where
674 quoted or unquoted @samp{0} is false and anything else is true, and
675 yield a Boolean result, either @samp{0} for false or @samp{1} for
676 true.
677 @end table
678
679 Macro expressions do not include any arithmetic operators.
680
681 An operand in an expression may be a single token (including a macro
682 argument name) or a macro function invocation.  Either way, the
683 expression evaluator unquotes the operand, so that @code{1 = '1'} is
684 true.
685
686 @node Macro Conditional Expansion
687 @subsection Macro Conditional Expansion
688
689 The @code{!IF} construct may be used inside a macro body to allow for
690 conditional expansion.  It takes the following forms:
691
692 @example
693 !IF (@var{expression}) !THEN @var{true-expansion} !IFEND
694 !IF (@var{expression}) !THEN @var{true-expansion} !ELSE @var{false-expansion} !IFEND
695 @end example
696
697 When @var{expression} evaluates to true, the macro processor expands
698 @var{true-expansion}; otherwise, it expands @var{false-expansion}, if
699 it is present.  The macro processor considers quoted or unquoted
700 @samp{0} to be false, and anything else to be true.
701
702 @node Macro Loops
703 @subsection Macro Loops
704
705 The body of a macro may include two forms of loops: loops over
706 numerical ranges and loops over tokens.  Both forms expand a @dfn{loop
707 body} multiple times, each time setting a named @dfn{loop variable} to
708 a different value.  The loop body typically expands the loop variable
709 at least once.
710
711 The MITERATE setting (@pxref{SET MITERATE}) limits the number of
712 iterations in a loop.  This is a safety measure to ensure that macro
713 expansion terminates.  PSPP issues a warning when the MITERATE limit
714 is exceeded.
715
716 @subsubheading Loops Over Ranges
717
718 @example
719 !DO @var{!var} = @var{start} !TO @var{end} [!BY @var{step}]
720   @var{body}
721 !DOEND
722 @end example
723
724 A loop over a numerical range has the form shown above.  @var{start},
725 @var{end}, and @var{step} (if included) must be expressions with
726 numeric values.  The macro processor accepts both integers and real
727 numbers.  The macro processor expands @var{body} for each numeric
728 value from @var{start} to @var{end}, inclusive.
729
730 The default value for @var{step} is 1.  If @var{step} is positive and
731 @math{@var{first} > @var{last}}, or if @var{step} is negative and
732 @math{@var{first} < @var{last}}, then the macro processor doesn't
733 expand the body at all.  @var{step} may not be zero.
734
735 @subsubheading Loops Over Tokens
736
737 @example
738 !DO @var{!var} !IN (@var{expression})
739   @var{body}
740 !DOEND
741 @end example
742
743 A loop over tokens takes the form shown above.  The macro processor
744 evaluates @var{expression} and expands @var{body} once per token in
745 the result, substituting the token for @var{!var} each time it
746 appears.
747
748 @node Macro Variable Assignment
749 @subsection Macro Variable Assignment
750
751 The @code{!LET} construct evaluates an expression and assigns the
752 result to a macro variable.  It may create a new macro variable or
753 change the value of one created by a previous @code{!LET} or
754 @code{!DO}, but it may not change the value of a macro argument.
755 @code{!LET} has the following form:
756
757 @example
758 !LET @var{!var} = @var{expression}
759 @end example
760
761 If @var{expression} is more than one token, it must be enclosed in
762 parentheses.
763
764 @node Macro Settings
765 @subsection Macro Settings
766
767 Some macro behavior is controlled through the SET command
768 (@pxref{SET}).  This section describes these settings.
769
770 Any SET command that changes these settings within a macro body only
771 takes effect following the macro.  This is because PSPP expands a
772 macro's entire body at once, so that the SET command inside the body
773 only executes afterwards.
774
775 The MEXPAND setting (@pxref{SET MEXPAND}) controls whether macros will
776 be expanded at all.  By default, macro expansion is on.  To avoid
777 expansion of macros called within a macro body, use @code{!OFFEXPAND}
778 and @code{!ONEXPAND} (@pxref{Controlling Macro Expansion}).
779
780 When MPRINT (@pxref{SET MPRINT}) is turned on, PSPP logs an expansion
781 of each macro in the input.  This feature can be useful for debugging
782 macro definitions.
783
784 MNEST (@pxref{SET MNEST}) limits the depth of expansion of macro
785 calls, that is, the nesting level of macro expansion.  The default is
786 50.  This is mainly useful to avoid infinite expansion in the case of
787 a macro that calls itself.
788
789 MITERATE (@pxref{SET MITERATE}) limits the number of iterations in a
790 @code{!DO} construct.  The default is 1000.
791
792 PRESERVE...RESTORE
793
794 SET MEXPAND, etc. doesn't work inside macro bodies.
795
796 @node Macro Notes
797 @subsection Extra Notes
798
799 Macros in comments.
800
801 Macros in titles.
802
803 Define ``unquote.''
804
805 @node DO IF
806 @section DO IF
807 @vindex DO IF
808
809 @display
810 DO IF condition.
811         @dots{}
812 [ELSE IF condition.
813         @dots{}
814 ]@dots{}
815 [ELSE.
816         @dots{}]
817 END IF.
818 @end display
819
820 @cmd{DO IF} allows one of several sets of transformations to be
821 executed, depending on user-specified conditions.
822
823 If the specified boolean expression evaluates as true, then the block
824 of code following @cmd{DO IF} is executed.  If it evaluates as
825 missing, then
826 none of the code blocks is executed.  If it is false, then
827 the boolean expression on the first @cmd{ELSE IF}, if present, is tested in
828 turn, with the same rules applied.  If all expressions evaluate to
829 false, then the @cmd{ELSE} code block is executed, if it is present.
830
831 When @cmd{DO IF} or @cmd{ELSE IF} is specified following @cmd{TEMPORARY}
832 (@pxref{TEMPORARY}), the @cmd{LAG} function may not be used
833 (@pxref{LAG}).
834
835 @node DO REPEAT
836 @section DO REPEAT
837 @vindex DO REPEAT
838
839 @display
840 DO REPEAT dummy_name=expansion@dots{}.
841         @dots{}
842 END REPEAT [PRINT].
843
844 expansion takes one of the following forms:
845         var_list
846         num_or_range@dots{}
847         'string'@dots{}
848         ALL
849
850 num_or_range takes one of the following forms:
851         number
852         num1 TO num2
853 @end display
854
855 @cmd{DO REPEAT} repeats a block of code, textually substituting
856 different variables, numbers, or strings into the block with each
857 repetition.
858
859 Specify a dummy variable name followed by an equals sign (@samp{=})
860 and the list of replacements.  Replacements can be a list of existing
861 or new variables, numbers, strings, or @code{ALL} to specify all
862 existing variables.  When numbers are specified, runs of increasing
863 integers may be indicated as @code{@var{num1} TO @var{num2}}, so that
864 @samp{1 TO 5} is short for @samp{1 2 3 4 5}.
865
866 Multiple dummy variables can be specified.  Each
867 variable must have the same number of replacements.
868
869 The code within @cmd{DO REPEAT} is repeated as many times as there are
870 replacements for each variable.  The first time, the first value for
871 each dummy variable is substituted; the second time, the second value
872 for each dummy variable is substituted; and so on.
873
874 Dummy variable substitutions work like macros.  They take place
875 anywhere in a line that the dummy variable name occurs.  This includes
876 command and subcommand names, so command and subcommand names that
877 appear in the code block should not be used as dummy variable
878 identifiers.  Dummy variable substitutions do not occur inside quoted
879 strings, comments, unquoted strings (such as the text on the
880 @cmd{TITLE} or @cmd{DOCUMENT} command), or inside @cmd{BEGIN
881 DATA}@dots{}@cmd{END DATA}.
882
883 Substitution occurs only on whole words, so that, for example, a dummy
884 variable PRINT would not be substituted into the word PRINTOUT.
885
886 New variable names used as replacements are not automatically created
887 as variables, but only if used in the code block in a context that
888 would create them, @i{e.g.}@: on a @cmd{NUMERIC} or @cmd{STRING} command
889 or on the left side of a @cmd{COMPUTE} assignment.
890
891 Any command may appear within @subcmd{DO REPEAT}, including nested @subcmd{DO REPEAT}
892 commands.  If @cmd{INCLUDE} or @cmd{INSERT} appears within @subcmd{DO REPEAT},
893 the substitutions do not apply to the included file.
894
895 If @subcmd{PRINT} is specified on @cmd{END REPEAT}, the commands after
896 substitutions are made should be printed to the listing file, prefixed
897 by a plus sign (@samp{+}).  This feature is not yet implemented.
898
899 @node LOOP
900 @section LOOP
901 @vindex LOOP
902
903 @display
904 LOOP [@var{index_var}=@var{start} TO @var{end} [BY @var{incr}]] [IF @var{condition}].
905         @dots{}
906 END LOOP [IF @var{condition}].
907 @end display
908
909 @cmd{LOOP} iterates a group of commands.  A number of
910 termination options are offered.
911
912 Specify index_var to make that variable count from one value to
913 another by a particular increment.  @var{index_var} must be a pre-existing
914 numeric variable.  @var{start}, @var{end}, and @var{incr} are numeric expressions
915 (@pxref{Expressions}.)
916
917 During the first iteration, @var{index_var} is set to the value of @var{start}.
918 During each successive iteration, @var{index_var} is increased by the value of
919 @var{incr}.  If @var{end} > @var{start}, then the loop terminates
920 when @var{index_var} > @var{end};
921 otherwise it terminates when @var{index_var} < @var{end}.  If @var{incr} is not specified
922 then it defaults to +1 or -1 as appropriate.
923
924 If @var{end} > @var{start} and @var{incr} < 0, or if @var{end} < @var{start} and
925  @var{incr} > 0, then the
926 loop is never executed.  @var{index_var} is nevertheless set to the value of
927 start.
928
929 Modifying @var{index_var} within the loop is allowed, but it has no effect on
930 the value of @var{index_var} in the next iteration.
931
932 Specify a boolean expression for the condition on @cmd{LOOP} to
933 cause the loop to be executed only if the condition is true.  If the
934 condition is false or missing before the loop contents are executed the
935 first time, the loop contents are not executed at all.
936
937 If index and condition clauses are both present on @cmd{LOOP}, the
938 index variable is always set before the condition is evaluated.  Thus,
939 a condition that makes use of the index variable will always see the
940 index value to be used in the next execution of the body.
941
942 Specify a boolean expression for the condition on @cmd{END LOOP} to cause
943 the loop to terminate if the condition is true after the enclosed
944 code block is executed.  The condition is evaluated at the end of the
945 loop, not at the beginning, so that the body of a loop with only a
946 condition on @cmd{END LOOP} will always execute at least once.
947
948 If the index clause is not
949 present, then the loop is executed at most @var{max_loops} (@pxref{SET}) times
950 (but possibly fewer, if a condition clause evaluates to false or if
951 @cmd{BREAK} executes).
952 The default value of @var{max_loops} is 40.
953
954 @cmd{BREAK} also terminates @cmd{LOOP} execution (@pxref{BREAK}).
955
956 Loop index variables are by default reset to system-missing from one
957 case to another, not left, unless a scratch variable is used as index.
958 When loops are nested, this is usually undesired behavior, which can
959 be corrected with @cmd{LEAVE} (@pxref{LEAVE}) or by using a scratch
960 variable as the loop index.
961
962 When @cmd{LOOP} or @cmd{END LOOP} is specified following @cmd{TEMPORARY}
963 (@pxref{TEMPORARY}), the @cmd{LAG} function may not be used
964 (@pxref{LAG}).