#!/bin/bash if [[ -z "$AWK" || -z "$WORKDIR" ]]; then printf '$AWK and $WORKDIR must be set\n' >&2 exit 1 fi TEMP1=$WORKDIR/test.temp.1 TEMP2=$WORKDIR/test.temp.2 RESULT=0 fail() { echo "$1" >&2 RESULT=1 } echo T.func: test user-defined functions echo '10 2 2 10 10 10 10 1e1 1e1 9' | $AWK ' # tests whether function returns sensible type bits function assert(cond) { # assertion if (cond) print 1; else print 0 } function i(x) { return x } { m=$1; n=i($2); assert(m>n) } ' > $TEMP1 echo '1 0 0 0 1' > $TEMP2 diff $TEMP1 $TEMP2 || fail 'BAD: T.func (function return type)' echo 'data: data' > $TEMP1 $AWK ' function test1(array) { array["test"] = "data" } function test2(array) { return(array["test"]) } BEGIN { test1(foo); print "data: " test2(foo) } ' > $TEMP2 diff $TEMP1 $TEMP2 || fail 'BAD: T.func (array type)' $AWK ' BEGIN { code() } END { codeout("x") } function code() { ; } function codeout(ex) { print ex } ' /dev/null > $TEMP1 echo x > $TEMP2 diff $TEMP1 $TEMP2 || fail 'BAD: T.func (argument passing)' $AWK ' BEGIN { unireghf() } function unireghf(hfeed) { hfeed[1]=0 rcell("foo",hfeed) hfeed[1]=0 rcell("bar",hfeed) } function rcell(cellname,hfeed) { print cellname } ' > $TEMP1 echo "foo bar" > $TEMP2 diff $TEMP1 $TEMP2 || fail 'BAD: T.func (convert arg to array)' $AWK ' function f(n) { if (n <= 1) return 1 else return n * f(n-1) } { print f($1) } ' > $TEMP2 < $TEMP1 < $TEMP2 < $TEMP1 < $TEMP2 < $TEMP1 < $TEMP1 grep 'should not' $TEMP1 && fail 'BAD: T.func (return)' # this exercises multiple free of temp cells echo 'eqn eqn2' > $TEMP1 $AWK 'BEGIN { eprocess("eqn", "x", contig) process("tbl" ) eprocess("eqn" "2", "x", contig) } function eprocess(file, first, contig) { print file } function process(file) { close(file) }' > $TEMP2 diff $TEMP1 $TEMP2 || fail 'BAD: T.func (eqn)' echo 1 > $TEMP1 $AWK 'function f() { n = 1; exit } BEGIN { n = 0; f(); n = 2 }; END { print n}' > $TEMP2 diff $TEMP1 $TEMP2 || fail 'BAD: T.func (exit in function)' echo 1 > $TEMP1 $AWK ' BEGIN { n = 10 for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) x[i,j] = n * i + j for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) if ((i,j) in x) k++ print (k == n^2) } ' > $TEMP2 diff $TEMP1 $TEMP2 || fail 'BAD: T.func (multi-dim subscript)' echo '<> 0' > $TEMP1 $AWK ' function foo() { i = 0 } BEGIN { x = foo(); printf "<%s> %d\n", x, x }' > $TEMP2 diff $TEMP1 $TEMP2 || fail 'BAD: T.func (fall off end)' exit $RESULT