----------------------------------------------------------------------
-- |
-- Module      : PrGSL
-- Maintainer  : BB
-- Stability   : (stable)
-- Portability : (portable)
--
-- > CVS $Date: 2005/02/18 19:21:21 $ 
-- > CVS $Author: peb $
-- > CVS $Revision: 1.10 $
--
-- This module prints a CFG as a Nuance GSL 2.0 grammar.
--
-- FIXME: remove \/ warn \/ fail if there are int \/ string literal
-- categories in the grammar
-----------------------------------------------------------------------------

module PrGSL (gslPrinter) where

import SRG
import Ident
import CFGrammar
import Parser (Symbol(..))
import GrammarTypes
import PrintParser
import Option

import Data.Char (toUpper,toLower)

gslPrinter :: Ident -- ^ Grammar name
	   -> Options -> CFGrammar -> String
gslPrinter name opts cfg = prGSL srg ""
    where srg = makeSRG name opts cfg

prGSL :: SRG -> ShowS
prGSL (SRG{grammarName=name,startCat=start,origStartCat=origStart,rules=rs})
    = header . mainCat . unlinesS (map prRule rs)
    where
    header = showString ";GSL2.0" . nl 
	     . comments ["Nuance speech recognition grammar for " ++ name,
			 "Generated by GF"] . nl . nl
    mainCat = showString ("; Start category: " ++ origStart) . nl 
	      . showString ".MAIN " . prCat start . nl . nl
    prRule (SRGRule cat origCat rhs) = 
	showString "; " . prtS origCat . nl
        . prCat cat . sp . wrap "[" (unwordsS (map prAlt rhs)) "]" . nl
    prAlt rhs = wrap "(" (unwordsS (map prSymbol rhs')) ")"
		   where rhs' = rmPunct rhs
    prSymbol (Cat c) = prCat c
    prSymbol (Tok t) = wrap "\"" (showString (showToken t)) "\""
    -- GSL requires an upper case letter in category names
    prCat c = showString (firstToUpper c)

firstToUpper :: String -> String
firstToUpper [] = []
firstToUpper (x:xs) = toUpper x : xs

rmPunct :: [Symbol String Token] -> [Symbol String Token] 
rmPunct [] = []
rmPunct (Tok t:ss) | all isPunct (prt t) = rmPunct ss
rmPunct (s:ss) = s : rmPunct ss

-- Nuance does not like upper case characters in tokens
showToken :: Token -> String
showToken t = map toLower (prt t)

isPunct :: Char -> Bool
isPunct c = c `elem` "-_.;.,?!()[]{}"

comments :: [String] -> ShowS
comments = unlinesS . map (showString . ("; " ++))
