Previous: Other tokens, Up: Syntax


2.5 How m4 copies input to output

As m4 reads the input token by token, it will copy each token directly to the output immediately.

The exception is when it finds a word with a macro definition. In that case m4 will calculate the macro's expansion, possibly reading more input to get the arguments. It then inserts the expansion in front of the remaining input. In other words, the resulting text from a macro call will be read and parsed into tokens again.

m4 expands a macro as soon as possible. If it finds a macro call when collecting the arguments to another, it will expand the second call first. For a running example, examine how m4 handles this input:

     format(`Result is %d', eval(`2**15'))

First, m4 sees that the token `format' is a macro name, so it collects the tokens `(', ``Result is %d'', `,', and ` ', before encountering another potential macro. Sure enough, `eval' is a macro name, so the nested argument collection picks up `(', ``2**15'', and `)', invoking the eval macro with the lone argument of `2**15'. The expansion of `eval(2**15)' is `32768', which is then rescanned as the five tokens `3', `2', `7', `6', and `8'; and combined with the next `)', the format macro now has all its arguments, as if the user had typed:

     format(`Result is %d', 32768)

The format macro expands to `Result is 32768', and we have another round of scanning for the tokens `Result', ` ', `is', ` ', `3', `2', `7', `6', and `8'. None of these are macros, so the final output is

     =>Result is 32768

The order in which m4 expands the macros can be explored using the Trace facilities of GNU m4.

This process continues until there are no more macro calls to expand and all the input has been consumed.