summaryrefslogtreecommitdiff
path: root/src/GF/Speech/PrJSGF.hs
blob: f09d454d9d8dadc75e975d63da69d8f05b1eb047 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
----------------------------------------------------------------------
-- |
-- Module      : PrJSGF
-- Maintainer  : BB
-- Stability   : (stable)
-- Portability : (portable)
--
-- > CVS $Date: 2005/11/01 20:09:04 $ 
-- > CVS $Author: bringert $
-- > CVS $Revision: 1.16 $
--
-- This module prints a CFG as a JSGF grammar.
--
-- FIXME: remove \/ warn \/ fail if there are int \/ string literal
-- categories in the grammar
--
-- FIXME: convert to UTF-8
-----------------------------------------------------------------------------

module GF.Speech.PrJSGF (jsgfPrinter) where

import GF.Conversion.Types
import GF.Data.Utilities
import GF.Formalism.CFG
import GF.Formalism.Utilities (Symbol(..))
import GF.Infra.Ident
import GF.Infra.Print
import GF.Infra.Option
import GF.Probabilistic.Probabilistic (Probs)
import GF.Speech.SRG
import GF.Speech.RegExp

jsgfPrinter :: Ident -- ^ Grammar name
            -> String    -- ^ Start category
	    -> Options -> Maybe Probs -> CGrammar -> String
jsgfPrinter name start opts probs cfg = prJSGF srg ""
    where srg = makeSimpleSRG name start opts probs cfg

prJSGF :: SRG -> ShowS
prJSGF (SRG{grammarName=name,startCat=start,origStartCat=origStart,rules=rs})
    = header . mainCat . unlinesS (map prRule rs)
    where
    header = showString "#JSGF V1.0 UTF-8;" . nl 
	     . comments ["JSGF speech recognition grammar for " ++ name,
			 "Generated by GF"] . nl 
	     . showString ("grammar " ++ name ++ ";") . nl
	     . nl
    mainCat = comments ["Start category: " ++ origStart] . nl 
	      . showString "public <MAIN> = " . prCat start . showChar ';' . nl . nl
    prRule (SRGRule cat origCat rhs) = 
	comments [origCat] . nl
        . prCat cat . showString " = " . joinS " | " (map prAlt (ebnfSRGAlts rhs)) . nl
    -- FIXME: use the probability
    prAlt (EBnfSRGAlt mp _ rhs) = prItem rhs

prCat :: SRGCat -> ShowS
prCat c = showChar '<' . showString c . showChar '>'

prItem :: EBnfSRGItem -> ShowS
prItem = f
  where
    f (REUnion [])  = showString "<VOID>"
    f (REUnion xs)  = wrap "(" (joinS " | " (map f xs)) ")"
    f (REConcat []) = showString "<NULL>"
    f (REConcat xs) = wrap "(" (unwordsS (map f xs)) ")"
    f (RERepeat x)  = wrap "(" (f x) ")" . showString "*"
    f (RESymbol s)  = prSymbol s

prSymbol :: Symbol SRGNT Token -> ShowS
prSymbol (Cat (c,_)) = prCat c
prSymbol (Tok t) | all isPunct (prt t) = id -- removes punctuation
                 | otherwise = wrap "\"" (prtS t) "\""

isPunct :: Char -> Bool
isPunct c = c `elem` "-_.;.,?!"

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