Infinite recursion in m4

129 views Asked by At

This m4 script is intended to generate part of the argument parsing code for a shell script. Unfortunately, it does not produce the correct output:

#!/bin/m4

define(`HANDLE_CASE', ``-'substr($1,0,1)`|--'$1`) option='$1`; skip=1 ;;'')
define(`HANDLE_CASES', `ifelse(`$#'
,`0',``
-v|--version) showVersion; exit $? ;;
-h|--help) dispUsage 2>&1; exit $? ;;
--) break ;;
*) dispUsage; exit 1'',
`HANDLE_CASE($1)
HANDLE_CASES(shift($@))')')
HANDLE_CASES(timeout,delay,file)

Intended output:

-t|--timeout) option=timeout; skip=1 ;;
-d|--delay) option=delay; skip=1 ;;
-f|--file) option=file; skip=1 ;;
-h|--help) dispUsage 2>&1 ; exit $? ;;
-v|--version) showVersion; exit $? ;;
--) break ;;
*) dispUsage; exit 1

Actual output:

#!/bin/m4



-t|--timeout) option=timeout; skip=1 ;;
-d|--delay) option=delay; skip=1 ;;
-f|--file) option=file; skip=1 ;;
-|--) option=; skip=1 ;;
-|--) option=; skip=1 ;;
-|--) option=; skip=1 ;;
-|--) option=; skip=1 ;;
-|--) option=; skip=1 ;;
-|--) option=; skip=1 ;;
-|--) option=; skip=1 ;;
-|--) option=; skip=1 ;;
-|--) option=; skip=1 ;;
-|--) option=; skip=1 ;;
-|--) option=; skip=1 ;;
-|--) option=; skip=1 ;;
-|--) option=; skip=1 ;;

or, in other words, infinite recursion ( The above program was piped to head -n 20 ).

How do I terminate the recursion?

1

There are 1 answers

0
madmurphy On

Indentation is only for clarity...

#!/bin/m4

define(`HANDLE_CASE', `-substr($1,0,1)|--$1) option=$1; skip=1 ;;')

define(`HANDLE_CASES',
    `ifelse(eval(`$# > 1'), `1', `
        HANDLE_CASE($1)`'HANDLE_CASES(shift($@))', `
        -v|--version) showVersion; exit $? ;;
        -h|--help) dispUsage 2>&1; exit $? ;;
        --) break ;;
        *) dispUsage; exit 1')')

HANDLE_CASES(timeout,delay,file)