summaryrefslogtreecommitdiff
path: root/src/GF/Conversion/SimpleToMCFG/Coercions.hs
blob: 48b09cee23acc6da777fe14e3457d7c3b87f4209 (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
----------------------------------------------------------------------
-- |
-- Maintainer  : PL
-- Stability   : (stable)
-- Portability : (portable)
--
-- > CVS $Date: 2005/04/21 16:21:57 $ 
-- > CVS $Author: bringert $
-- > CVS $Revision: 1.4 $
--
-- Adding coercion functions to a MCFG if necessary.
-----------------------------------------------------------------------------


module GF.Conversion.SimpleToMCFG.Coercions
    (addCoercions) where

import GF.System.Tracing
import GF.Infra.Print

import GF.Formalism.Utilities
import GF.Formalism.GCFG
import GF.Formalism.MCFG
import GF.Conversion.Types 
import GF.Data.SortedList
import Data.List (groupBy)

----------------------------------------------------------------------

addCoercions :: EGrammar -> EGrammar
addCoercions rules = coercions ++ rules
    where (allHeads, allArgs) = unzip [ ((head, lbls), nubsort args) | 
					Rule (Abs head args _) (Cnc lbls _ _) <- rules ]
	  allHeadSet = nubsort allHeads
	  allArgSet  = union   allArgs <\\> map fst allHeadSet
	  coercions = tracePrt "SimpleToMCFG.Coercions - nr. MCFG coercions" (prt . length) $
		      concat $
		      tracePrt "SimpleToMCFG.Coerciions - nr. MCFG coercions per category" 
				   (prtList . map length) $
		      combineCoercions 
		        (groupBy sameECatFst allHeadSet) 
			(groupBy sameECat    allArgSet)
	  sameECatFst a b = sameECat (fst a) (fst b)


combineCoercions [] _ = []
combineCoercions _ [] = []
combineCoercions allHeads'@(heads:allHeads) allArgs'@(args:allArgs) 
    = case compare (ecat2scat $ fst $ head heads) (ecat2scat $ head args) of
        LT -> combineCoercions allHeads  allArgs'
	GT -> combineCoercions allHeads' allArgs
	EQ -> makeCoercion heads args : combineCoercions allHeads allArgs


makeCoercion heads args
    = [ Rule (Abs arg [head] coercionName) (Cnc lbls [lbls] lins)  |
	(head@(ECat _ headCns), lbls) <- heads, 
	let lins = [ Lin lbl [Cat (head, lbl, 0)] | lbl <- lbls ],
	arg@(ECat _ argCns) <- args,
	argCns `subset` headCns ]