gno/usr.bin/awk/tests/sentgen2
tribby ddb82cb2e0 Remaining files for awk 2.0 that were left out of the previous checkin.
Maybe someday I'll become adept at using cvs...
1998-04-07 17:06:53 +00:00

39 lines
1.1 KiB
Plaintext

# sentgen2 - random sentence generator (nonrecursive)
# input: grammar file; sequence of nonterminals
# output: random sentences generated by the grammar
BEGIN { # read rules from grammar file
while (getline < "grammar" > 0)
if ($2 == "->") {
i = ++lhs[$1] # count lhs
rhscnt[$1, i] = NF-2 # how many in rhs
for (j = 3; j <= NF; j++) # record them
rhslist[$1, i, j-2] = $j
} else
print "illegal production: " $0
}
{ if ($1 in lhs) { # nonterminal to expand
push($1)
gen()
printf("\n")
} else
print "unknown nonterminal: " $0
}
function gen( i, j) {
while (stp >= 1) {
sym = pop()
if (sym in lhs) { # a nonterminal
i = int(lhs[sym] * rand()) + 1 # random production
for (j = rhscnt[sym, i]; j >= 1; j--) # expand rhs's
push(rhslist[sym, i, j])
} else
printf("%s ", sym)
}
}
function push(s) { stack[++stp] = s }
function pop() { return stack[stp--] }