4.3BSD/usr/contrib/icon/src/cmd/csgen.icn

#	CSGEN(1)
#
#	Generate instances of sentences defined by context-sensitive
#	grammars
#
#	Ralph E. Griswold
#
#	Last modified 4/27/83
#

global xlist

procedure main(x)
   local line, goal, count, s
   while line := read() do		#  read in grammar
      if xpairs(line) then next
      else {
         line ? (goal := move(1),move(1),count := (0 < integer(tab(0))))
         break
         }
   every 1 to count do {		#  generate sentences
      s := goal
      while upto(&ucase,s) do {		#  test for nonterminal
         if x[1] == "-t" then write(&errout,s)
					#  quit on deadlock
         if not(s ? replace(!xlist)) then break next
         until s ?:= replace(?xlist)	#  make replacement
         }
      write(s)
      }
end

#  replace left hand side by right hand side
#
procedure replace(a)
   suspend tab(find(a[1])) || (move(*a[1]),a[2]) || tab(0)
end

#  enter rewriting rule
#
procedure xpairs(s)
   local i, a
   initial xlist := []
   if s ? {
				#  handle optional replication factor
      i := 1(0 < integer(tab(upto(':'))),move(1)) | 1 &
      a := [tab(find("->")),(move(2),tab(0))]
      }
   then {
      every 1 to i do put(xlist,a)
      return
      }
end