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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
|
{-# OPTIONS_CYMAKE -Wno-incomplete-patterns -Wno-overlapping #-}
module CHR(CHR,Goal,(/\), (<=>), (==>), (|>), (\\),
true, false, andCHR, allCHR, chrsToGoal,
toGoal1, toGoal2, toGoal3, toGoal4, toGoal5, toGoal6,
(.=.), (./=.), (.<=.), (.>=.), (.>.), (.<.),
nonvar, ground, anyPrim,
solveCHR, runCHR, runCHRwithTrace,
compileCHR, chr2curry
) where
import Prelude hiding ( empty )
import Data.Char
import Data.List
import System.IO.Unsafe
import Control.Findall ( rewriteSome )
import Data.Set.RBTree ( SetRBT, member, empty, insert )
import FlatCurry.Types
import FlatCurry.Files
import FlatCurry.Goodies
import FlatCurry.Pretty ( defaultOptions, ppTypeExp )
import Language.Prolog.Types
import Language.Prolog.Goodies ( plList )
import Language.Prolog.Show ( showPlClause, showPlGoals )
import Text.Pretty ( showWidth )
import XML
infix 5 .=., ./=., .<=., .>=., .>., .<.
infixr 4 /\
infix 3 <=>
infix 3 ==>
infix 2 \\
infix 1 |>
data CHR dom chr =
SimplRule [chr] [PrimConstraint dom] (Goal dom chr)
| PropaRule [chr] [PrimConstraint dom] (Goal dom chr)
| SimpaRule [chr] [chr] [PrimConstraint dom] (Goal dom chr)
(<=>) :: Goal dom chr -> Goal dom chr -> CHR dom chr
g1 <=> g2 =
if null (primsOfGoal g1)
then SimplRule (uchrOfGoal g1) [] g2
else error "Rule with primitive constraint on the left-hand side!"
(==>) :: Goal dom chr -> Goal dom chr -> CHR dom chr
g1 ==> g2 =
if null (primsOfGoal g1)
then PropaRule (uchrOfGoal g1) [] g2
else error "Rule with primitive constraint on the left-hand side!"
(\\) :: Goal dom chr -> CHR dom chr -> CHR dom chr
g1 \\ (SimplRule lchrs guard rcs)
| not (null (primsOfGoal g1))
= error "Simpagation rule with primitive kept constraints!"
| null keptcs
= SimplRule lchrs guard rcs
| null lchrs
= PropaRule keptcs guard rcs
| otherwise = SimpaRule keptcs lchrs guard rcs
where
keptcs = uchrOfGoal g1
(|>) :: CHR dom chr -> Goal dom chr -> CHR dom chr
rule |> g3 = attachGuard rule
where
attachGuard (SimplRule lcs guard rcs) =
if null (uchrOfGoal rcs)
then SimplRule lcs (guard ++ primsOfGoal rcs) g3
else error "Rule contains a guard with non-primitive constraints!"
attachGuard (PropaRule lcs guard rcs) =
if null (uchrOfGoal rcs)
then PropaRule lcs (guard ++ primsOfGoal rcs) g3
else error "Rule contains a guard with non-primitive constraints!"
attachGuard (SimpaRule h1 h2 guard rcs) =
if null (uchrOfGoal rcs)
then SimpaRule h1 h2 (guard ++ primsOfGoal rcs) g3
else error "Rule contains a guard with non-primitive constraints!"
data CHRconstr dom chr = PrimCHR (PrimConstraint dom) | UserCHR chr
data Goal dom chr = Goal [CHRconstr dom chr]
(/\) :: Goal dom chr -> Goal dom chr -> Goal dom chr
(/\) (Goal c1) (Goal c2) = Goal (c1 ++ c2)
true :: Goal dom chr
true = Goal []
false :: Goal dom chr
false = primToGoal Fail
andCHR :: [Goal dom chr] -> Goal dom chr
andCHR = foldr (/\) true
allCHR :: (a -> Goal dom chr) -> [a] -> Goal dom chr
allCHR fc = andCHR . map fc
uchrOfGoal :: Goal dom chr -> [chr]
uchrOfGoal (Goal cs) = concatMap uchr cs
where uchr (PrimCHR _) = []
uchr (UserCHR c) = [c]
primsOfGoal :: Goal dom chr -> [PrimConstraint dom]
primsOfGoal (Goal cs) = concatMap prim cs
where prim (PrimCHR c) = [c]
prim (UserCHR _) = []
chrsToGoal :: [chr] -> Goal dom chr
chrsToGoal cs = Goal (map UserCHR cs)
toGoal1 :: (a -> chr) -> a -> Goal dom chr
toGoal1 c x = Goal [UserCHR (c x)]
toGoal2 :: (a -> b -> chr) -> a -> b -> Goal dom chr
toGoal2 c x y = Goal [UserCHR (c x y)]
toGoal3 :: (a -> b -> c -> chr) -> a -> b -> c -> Goal dom chr
toGoal3 c x y z = Goal [UserCHR (c x y z)]
toGoal4 :: (a -> b -> c -> d -> chr)
-> a -> b -> c -> d -> Goal dom chr
toGoal4 con a b c d = Goal [UserCHR (con a b c d)]
toGoal5 :: (a -> b -> c -> d -> e -> chr)
-> a -> b -> c -> d -> e -> Goal dom chr
toGoal5 con a b c d e = Goal [UserCHR (con a b c d e)]
toGoal6 :: (a -> b -> c -> d -> e -> f -> chr)
-> a -> b -> c -> d -> e -> f -> Goal dom chr
toGoal6 con a b c d e f = Goal [UserCHR (con a b c d e f)]
data PrimConstraint a = Eq a a
| Neq a a
| Fail
| Compare (a -> a -> Bool) a a
| Ground a
| Nonvar a
| AnyPrim (() -> Bool)
primToGoal :: PrimConstraint dom -> Goal dom chr
primToGoal pc = Goal [PrimCHR pc]
(.=.) :: dom -> dom -> Goal dom chr
x .=. y = primToGoal (Eq x y)
(./=.) :: dom -> dom -> Goal dom chr
x ./=. y = primToGoal (Neq x y)
(.<=.) :: Ord dom => dom -> dom -> Goal dom chr
x .<=. y = primToGoal (Compare (<=) x y)
(.>=.) :: Ord dom => dom -> dom -> Goal dom chr
x .>=. y = primToGoal (Compare (>=) x y)
(.<.) :: Ord dom => dom -> dom -> Goal dom chr
x .<. y = primToGoal (Compare (<) x y)
(.>.) :: Ord dom => dom -> dom -> Goal dom chr
x .>. y = primToGoal (Compare (>) x y)
ground :: dom -> Goal dom chr
ground x = primToGoal (Ground x)
nonvar :: dom -> Goal dom chr
nonvar x = primToGoal (Nonvar x)
anyPrim :: (() -> Bool) -> Goal dom chr
anyPrim cf = primToGoal (AnyPrim cf)
evalPrimCHR :: (Data a, Eq a) => PrimConstraint a -> Bool
evalPrimCHR (Eq x y) = x=:=y
evalPrimCHR (Neq x y) = (x==y) =:= False
evalPrimCHR Fail = failed
evalPrimCHR (Compare cmp x y) = (cmp x y) =:= True
evalPrimCHR (Nonvar x) = System.IO.Unsafe.isVar x =:= False
evalPrimCHR (Ground x) = System.IO.Unsafe.isGround x =:= True
evalPrimCHR (AnyPrim cf) = cf ()
solveCHR :: (Data dom, Data chr, Eq dom, Show chr) =>
[[dom] -> CHR dom chr] -> Goal dom chr -> Bool
solveCHR prules goal =
let residual = runCHR prules goal
in if null residual
then True
else trace ("WARNING: residual CHR constraints: "++show residual++"\n")
True
type History = SetRBT ([Int],Int)
emptyHistory :: Ord a => SetRBT a
emptyHistory = empty (<=)
extendHistory :: Ord a => a -> SetRBT a -> SetRBT a
extendHistory = insert
inHistory :: Ord a => a -> SetRBT a -> Bool
inHistory = member
runCHR :: (Data dom, Data chr, Eq dom) =>
[[dom] -> CHR dom chr] -> Goal dom chr -> [chr]
runCHR prules goal = evalCHR False prules goal
runCHRwithTrace :: (Data dom, Data chr, Eq dom) =>
[[dom] -> CHR dom chr] -> Goal dom chr -> [chr]
runCHRwithTrace prules goal = evalCHR True prules goal
evalCHR :: (Data dom, Data chr, Eq dom) =>
Bool -> [[dom] -> CHR dom chr] -> Goal dom chr -> [chr]
evalCHR withtrace urules (Goal goal)
| evalConstr gidx emptyHistory chrgoal [] result
= map snd result
where
tracing s = if withtrace then trace s else id
result free
rules = zip [1..] urules
(gidx,chrgoal) = numberCHR 0 goal
solvePrims = all evalPrimCHR
evalConstr gi hist gl cstore finalcs = tracing (showAnyTerm (gl,cstore)) $
evalC gl cstore finalcs
where
evalC [] cs rcs = cs =:= rcs
evalC (PrimCHR pc : gs) cs rcs =
tracing ("Evaluate primitive: " ++ showAnyTerm pc) $
evalPrimCHR pc & evalConstr gi hist (map UserCHR cs ++ gs) [] rcs
evalC (UserCHR c : gs) cs rcs =
(normalForm c)
`seq` tryRules gi hist rules c gs cs rcs
tryRules gi hs [] c gs cs rcs =
maybe (tracing "Suspend constraint" $
evalConstr gi hs gs (c:cs) rcs)
(\ (pc,mgs) -> tracing ("Evaluate primitive: " ++ showAnyTerm pc) $
evalPrimCHR pc &
evalConstr gi hs (map UserCHR (c:cs) ++ mgs) [] rcs)
(extractPrim gs)
tryRules gi hist ((ri,r) : rs) c gs cs rcs =
maybe (tryRules gi hist rs c gs cs rcs)
(\ (newcs,newgs,remcs,is) ->
if (is,ri) `inHistory` hist
then tryRules gi hist rs c gs cs rcs
else
let (gj,inewcs) = numberCHR gi newcs
in tracing ("Apply rule " ++ show ri) $
evalConstr gj
(if null is then hist
else extendHistory (is,ri) hist)
(inewcs++newgs)
remcs rcs)
(rewriteSome (applyRule (r unknown) c gs cs))
applyRule (SimplRule lchrs guard (Goal rchrs)) (_,c) gs cs
| deleteSome c lchrs =:= lhs & findDelete lhs cs =:= (delcs,remcs)
&> solvePrims guard
= (rchrs,gs,remcs,[]) where lhs,delcs,remcs free
applyRule (PropaRule lchrs guard (Goal rchrs)) (i,c) gs cs
| deleteSome c lchrs =:= lhs & findDelete lhs cs =:= (delcs,_)
&> solvePrims guard
= (rchrs, UserCHR (i,c) : gs, cs, i : map fst delcs) where lhs,delcs free
applyRule (SimpaRule kept lchrs guard (Goal rchrs)) (_,c) gs cs
| deleteSome c lchrs =:= lhs & findDelete (kept++lhs) cs =:= (delcs,remcs)
&> solvePrims guard
= (rchrs, gs, take (length kept) delcs ++ remcs, [])
where lhs,delcs,remcs free
applyRule (SimpaRule kept lchrs guard (Goal rchrs)) (i,c) gs cs
| deleteSome c kept =:= kc & findDelete (kc++lchrs) cs =:= (delcs,remcs)
&> solvePrims guard
= (rchrs, UserCHR (i,c) : gs, take (length kc) delcs ++ remcs, [])
where kc,delcs,remcs free
findDelete :: Data a => [a] -> [(Int,a)] -> ([(Int,a)],[(Int,a)])
findDelete [] cs = ([],cs)
findDelete (x:xs) cs = let (z,ds) = del x cs
(zs,es) = findDelete xs ds
in (z:zs,es)
where
del e (z:zs) | e=:=snd z = (z,zs)
del e (z:zs) = let (y,ys) = del e zs in (y, z:ys)
deleteSome :: Data a => a -> [a] -> [a]
deleteSome e (z:zs) | e=:=z = zs
deleteSome e (z:zs) = z : deleteSome e zs
extractPrim :: [CHRconstr dom chr]
-> Maybe (PrimConstraint dom, [CHRconstr dom chr])
[] = Nothing
extractPrim (PrimCHR pc : cs) = Just (pc, cs)
extractPrim (UserCHR c : cs) =
maybe Nothing
(\ (pc,rcs) -> Just (pc, UserCHR c : rcs))
(extractPrim cs)
numberCHR :: Int -> [CHRconstr dom chr] -> (Int, [CHRconstr dom (Int,chr)])
numberCHR i [] = (i,[])
numberCHR i (PrimCHR pc : cs) =
let (j,ics) = numberCHR i cs in (j, PrimCHR pc : ics)
numberCHR i (UserCHR c : cs) =
let (j,ics) = numberCHR (i+1) cs in (j, UserCHR (i,c) : ics)
compileCHR :: String -> String -> [[dom] -> CHR dom chr] -> IO ()
compileCHR currymod sourcemodname rules
| null rids = putStrLn "No CHR rules to compile."
| otherwise = compileRules sourcemodname currymod rids
where
rids = map ruleId rules
ruleId :: ([dom] -> CHR dom chr) -> String
ruleId rule =
let rcallstring = showAnyExpression rule
in takeWhile (not . isSpace) (drop (length "(partcall 1 ") rcallstring)
rnmCHR :: String -> [QName] -> QName -> QName
rnmCHR chrmodname allchrids qn@(_,fn)
| qn `elem` allchrids = (chrmodname, fn ++ "$CHR")
| otherwise = qn
compileRules :: String -> String -> [String] -> IO ()
compileRules modname chrmodname rids = do
(Prog _ _ _ fdecls opdecls) <- readFlatCurry modname
let getftype = getFuncType fdecls
rdefs = filter (\ (Func fname _ _ _ _) -> snd fname `elem` rids) fdecls
(chrs,_) = unzip (map (compileRule getftype id []) (map funcRule rdefs))
allchrs = nub (concat chrs)
rnmchr = rnmCHR chrmodname (map fst allchrs)
(_,trules) = unzip (map (compileRule getftype rnmchr allchrs)
(map funcRule rdefs))
allchrtypes = zip allchrs (map getftype (map fst allchrs))
curryprog = showCHRModule modname chrmodname opdecls allchrtypes
prologprog = unlines $
map showPlClause
([PlDirective [PlLit "use_module"
[PlStruct "library" [PlAtom "chr"]]]] ++
map (\ (p,a) ->
PlDirective
[PlLit "chr_constraint"
[PlStruct "/" [PlAtom (showPlName (rnmchr p)),
PlInt a]]])
allchrs) ++
["","% CHR rules:"] ++ trules ++ ["","% Curry/Prolog interface:"] ++
map (showPlClause . chrPrologPrimDefinition chrmodname rnmchr) allchrs ++
["","% Auxiliary predicates:",
"sunif(X,Y) :- user:evalToken(E), user:hnf('Prelude.constrEq'(X,Y),_,E,_).",
"eval(X) :- user:evalToken(E), user:hnf(X,_,E,_)."]
writeFile (chrmodname ++ ".curry") curryprog
writeFile (chrmodname ++ ".pakcs.pl") prologprog
putStrLn $ "Curry interface to CHR(Prolog) written to "++chrmodname++".curry"
getFuncType :: [FuncDecl] -> (String,String) -> TypeExpr
getFuncType fdecls qfname =
maybe (error $ showQName qfname ++ " not found!")
(stripForall . funcType)
(find (\ (Func qf _ _ _ _) -> qf == qfname) fdecls)
where
stripForall te = case te of ForallType _ t -> t
_ -> te
chrPrologPrimDefinition :: String -> (QName -> QName) -> (QName,Int) -> PlClause
chrPrologPrimDefinition chrmodname rnmchr (qcname,carity) =
PlClause
(chrmodname ++ "." ++ showCName ("prim_"++snd qcname))
(map PlVar (map (\i->"X"++show i) [1..carity] ++ ["R"]))
[PlLit (showPlName (rnmchr qcname))
(map (\i -> PlVar ("X" ++ show i)) [1 .. carity]),
PlLit "=" [PlVar "R", PlAtom "Prelude.True"]]
showCHRModule :: String -> String -> [OpDecl] ->
[((QName,Int),TypeExpr)] -> String
showCHRModule orgmod chrmod opdecls constraints = unlines $
["module "++chrmod++exports++" where","",
"import qualified CHR(chr2curry)",
"import CHRcompiled",
"import qualified "++orgmod,""] ++
map showOpDecl chropdecls ++ [""] ++
map showCurryConstraint constraints
where
exports = "(module CHRcompiled" ++
concatMap (',':) (map (showCName . snd) chrqnames) ++ ")"
chrqnames = map (fst . fst) constraints
chropdecls = filter (\ (Op qop _ _) -> qop `elem` chrqnames) opdecls
showOpDecl :: OpDecl -> String
showOpDecl (Op op fixity prec) = unwords [showFixity fixity,show prec,showOp op]
where
showFixity InfixOp = "infix"
showFixity InfixlOp = "infixl"
showFixity InfixrOp = "infixr"
showOp (_,on) = if isAlpha (head on) then '`':on++"`" else on
showCurryConstraint :: ((QName,Int),TypeExpr) -> String
showCurryConstraint (((_,cname),carity),ctype) =
let cargtypes = argTypes carity ctype in
showCName cname ++" :: "++ concatMap (++" -> ") cargtypes
++"Goal "++ showCurryType (resultType carity ctype) ++"\n"++
showCName cname ++ concatMap (\i->" x"++show i) [1..carity] ++ " = Goal " ++
take carity (repeat '(') ++
showCName ("prim_"++cname) ++
concatMap (\i->" $!! x"++show i++")") [1..carity] ++ "\n\n" ++
showCName ("prim_"++cname) ++ " :: " ++
concatMap (++" -> ") cargtypes ++ "Bool\n" ++
showCName ("prim_"++cname) ++ " external\n"
where
resultType arity tp =
if arity==0 then let TCons _ [_,chrtype] = tp
in chrtype
else let FuncType _ rtype = tp
in resultType (arity-1) rtype
argTypes arity ftype = if arity==0 then [] else
let FuncType atype rtype = ftype
in showCurryType atype : argTypes (arity-1) rtype
constraints2xml :: String -> [(QName,Int)] -> XmlExp
constraints2xml prologmod constraints =
xml "primitives" (map constraint2xml constraints)
where
constraint2xml ((_,cname),carity) =
XElem "primitive" [("name",showCName ("prim_"++cname)),
("arity",show carity)]
[xml "library" [xtxt prologmod],
xml "entry" [xtxt (showCName ("prim_"++cname))]]
compileRule :: (QName -> TypeExpr) -> (QName -> QName) -> [(QName,Int)] -> Rule
-> ([(QName,Int)],String)
compileRule _ _ _ (External _) = error "CHR.compileRule: external rule"
compileRule getftype rnmchr chrs (Rule _ rhs) =
let (_,rchrs,trule) = exp2CHR 100 (firstBranch rhs)
in (rchrs, trule ++ ".")
where
exp2CHR i exp = case exp of
Comb FuncCall qf [a1,a2]
| qf == (chrMod,"<=>") -> let (j, chrs1,tgoal1) = transGoal i a1
(k,_,tgoal2) = transGoal j a2
in (k, chrs1, sg tgoal1 ++" <=> "++ sg tgoal2)
| qf == (chrMod,"==>") -> let (j,chrs1,tgoal1) = transGoal i a1
(k,_,tgoal2) = transGoal j a2
in (k, chrs1, sg tgoal1 ++" ==> "++ sg tgoal2)
| qf == (chrMod,"\\\\") -> let (j,chrs1,tgoal1) = transGoal i a1
(k,chrs2,trule2) = exp2CHR j a2
in (k, chrs1++chrs2, sg tgoal1 ++" \\ "++ trule2)
| qf == (chrMod,"|>") -> let (j,chrs1,trule1) = exp2CHR i a1
(k,_,tgoal2) = transGoal j a2
in (k, chrs1, trule1 ++" | "++ sg tgoal2)
_ -> error ("Cannot translate CHR rule: " ++ show exp)
where sg = showPlGoals
transGoal i exp = case reduceApply exp of
Comb FuncCall qf args -> if fst qf == chrMod then transCHRPred i qf args
else transUserPred i qf args
_ -> error ("Cannot translate CHR literal: " ++ show exp)
transCHRPred i (_,cname) args
| cname=="/\\" =
let (j,chrs1,tgoal1) = transGoal i (args!!0)
(k,chrs2,tgoal2) = transGoal j (args!!1)
in (k, chrs1++chrs2, tgoal1 ++ tgoal2)
| cname=="nonvar" = (i, [], [PlLit "nonvar" [transArg (args!!0)]])
| cname=="ground" = (i, [], [PlLit "ground" [transArg (args!!0)]])
| cname=="true" = (i, [], [PlLit "true" []])
| cname=="false" = (i, [], [PlLit "fail" []])
| otherwise = maybe (error $ "Illegal CHR constraint: CHR."++cname)
(\chr2pl -> (i, [], [chr2pl (map transArg args)]))
(lookup cname chrPrims)
transUserPred i qf args =
let (j,plits,plit) = flattenLiteral i (rnmchr qf) args
fplit = if qf `elem` map fst chrs
then plit
else if isCHRType (getftype qf)
then let PlLit pn pargs = plit
in PlLit "eval" [PlStruct "CHR.chr2curry"
[PlStruct pn pargs]]
else error ("Operation '"++snd qf++
"' is not a CHR constraint!")
in (j, [(qf, length args)], plits ++ [fplit])
isCHRType :: TypeExpr -> Bool
isCHRType texp = case texp of
FuncType _ rt -> isCHRType rt
TCons qtc _ -> qtc == (chrMod,"Goal")
_ -> False
firstBranch :: Expr -> Expr
firstBranch exp = case exp of
Case _ _ (Branch _ bexp : brs) ->
if null brs
then firstBranch bexp
else error ("CHR rule with more than one branch: "++show exp)
Free _ fexp -> firstBranch fexp
_ -> exp
reduceApply :: Expr -> Expr
reduceApply exp = case exp of
Comb FuncCall ("Prelude","apply") [a1,a2] ->
let ra1 = reduceApply a1 in
case ra1 of
Comb FuncCall qf fargs -> Comb FuncCall qf (fargs++[a2])
_ -> Comb FuncCall ("Prelude","apply") [ra1,a2]
_ -> exp
chrPrims :: [(String,[PlTerm] -> PlGoal)]
chrPrims =
[(".=." , \args -> PlLit "sunif" args),
("./=.", \args -> PlLit "sunif" [relApply "Prelude.==" args, pfalse]),
(".>=.", \args -> PlLit "sunif" [relApply "Prelude.>=" args, ptrue]),
(".<=.", \args -> PlLit "sunif" [relApply "Prelude.<=" args, ptrue]),
(".>.", \args -> PlLit "sunif" [relApply "Prelude.>" args, ptrue]),
(".<.", \args -> PlLit "sunif" [relApply "Prelude.<" args, ptrue])]
where
ptrue = PlAtom "Prelude.True"
pfalse = PlAtom "Prelude.False"
relApply rel args = foldl (\f x -> PlStruct "Prelude.apply" [f,x])
(PlStruct rel [head args])
(tail args)
transArgs :: [Expr] -> [PlTerm]
transArgs [] = []
transArgs (e:es) = case e of
Comb (FuncPartCall 1) qn [] -> case es of
[] -> [transArg e]
e1:e1s -> transArgs (Comb FuncCall qn [e1] : e1s)
_ -> transArg e : transArgs es
transArg :: Expr -> PlTerm
transArg e = case e of
Lit (Intc i) -> PlInt i
Lit (Floatc f) -> PlFloat f
Var i -> PlVar ('X' : show i)
Comb ct qf args -> case ct of
FuncCall -> PlStruct (showPlName qf) (map transArg args)
ConsCall -> PlStruct (showPlName qf) (map transArg args)
FuncPartCall m -> genPartCall m qf args
ConsPartCall m -> genPartCall m qf args
_ -> error $ "Not yet translatable argument: " ++ show e
where
genPartCall m qf args =
PlStruct "partcall" [PlInt m, PlStruct (showPlName qf) [],
plList (map transArg args)]
flattenLiteral :: Int -> QName -> [Expr] -> (Int,[PlGoal],PlGoal)
flattenLiteral i qf args =
let (j,flits,fargs) = flattenArgs i args
in (j, flits, PlLit (showPlName qf) (map transArg fargs))
flattenArgs :: Int -> [Expr] -> (Int,[PlGoal],[Expr])
flattenArgs i [] = (i,[],[])
flattenArgs i (arg:args) =
if funcArg arg
then let (j,flits,fargs) = flattenArgs (i+1) args
in (j, PlLit "sunif" [PlVar ("X"++show i), transArg arg] : flits,
Var i:fargs)
else let (j,flits,fargs) = flattenArgs i args
in (j, flits, arg : fargs)
where
funcArg e = case e of
Lit _ -> False
Var _ -> False
Comb ConsCall _ cargs -> any funcArg cargs
_ -> True
showQName :: QName -> String
showQName (mname,fname) = mname++"."++fname
showCName :: String -> String
showCName s
| all (\c -> isAlphaNum c || c=='_') s = s
| isAlpha (head s) = concatMap (\c -> if isAlphaNum c || c=='_'
then [c]
else 'X':show (ord c))
s
| otherwise = "("++s++")"
showPlName :: QName -> String
showPlName qn@(mn,fn)
| qn == ("Prelude","[]") = "[]"
| qn == ("Prelude",":") = "."
| all (\c -> isAlphaNum c || c=='_') fn = showQName qn
| length fn > 1 && head fn == '_' = mn ++ '.' : concatMap encodeChar fn
| otherwise = showQName qn
where
encodeChar c = if isAlphaNum c || c=='_' || c=='.'
then [c]
else let oc = ord c
in ['\'',intToDigit (oc `div` 16),
intToDigit (oc `mod` 16)]
chrMod :: String
chrMod = "CHR"
chr2curry :: (Data dom, Eq dom) => CHR.Goal dom chr -> Bool
chr2curry (CHR.Goal c) = case c of
[CHR.PrimCHR pc] -> CHR.evalPrimCHR pc
_ -> error "CHRcompiled.chr2curry: unexpected argument!"
showCurryType :: TypeExpr -> String
showCurryType te = '(' : showWidth 78 (ppTypeExp defaultOptions te) ++ ")"
|