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
module CPC.Instrumentation
  ( startTransform, transExp, Opts )
 where


import ACSpans.AbstractCurrySpan
import AbstractCurry.Pretty (showCProg)
import ACSpans.Span         (Span)
import ACSpans.Select       (progName)
import FiniteMap            (FM,emptyFM,isEmptyFM,lookupWithDefaultFM)
import Maybe                (isJust)
import Unsafe               (unsafePerformIO)
import INS                  ( INS
                            , bindS
                            , bindS_
                            , putS
                            , returnS
                            , liftS
                            , liftS
                            , liftS2
                            , updateID
                            , mapS
                            , getS
                            , runState)
import CMeta ( BoxEntry
             , BoxLabel
             , mkExpBox
             , mkTopBox
             , mkifTBox
             , mkifFBox
             , mkGuardTBox
             , mkGuardFBox
             , mkLocBox)

import CPC.Files ( addInstSuffix )

------------------------------------------------------------------------------
initID:: Int
initID = 0
initBoxList:: [BoxEntry]
initBoxList = []

data Opts = Opts
     { optim  :: Bool
     , arityM :: FM (String, String) Int
       }

defaultOpts :: Opts
defaultOpts =
    Opts {
      optim = False
    , arityM = emptyFM (<)
      }

setOptim :: FM (String,String) Int -> Opts -> Opts
setOptim arM o = if isEmptyFM arM
                 then defaultOpts
                 else o {optim = True, arityM = arM}

------------------------------------------------------------------------------
startTransform :: Int -> CurryProg -> [String] -> Bool -> Bool
              -> (FM (String,String) Int) -> (CurryProg,(Int, [BoxEntry]))
startTransform id prog imps rename transMain arMap =
 ((CurryProg pos modname nMods t f o),(info,boxes))
  where timps mo        = if mo `elem` ["Prelude","CLib"]
                            then mo
                            else if mo `elem` imps
                                 then addInstSuffix mo
                                 else mo
        modname         = if rename then mname else mname
        impnames        = if imps==[] then m else map timps m
        nMods           = "CLib":impnames
        transProg       = transCP (setOptim arMap defaultOpts) prog
     --   repl c          = if c == '/' then '.' else c
        ((CurryProg pos mname m t f o),(info,boxes)) = if transMain
                                                         then (prog, (1,[]))
                                                         else runState
                                                              transProg (id,[])

-- CurryProg
transCP :: Opts -> CurryProg -> INS CurryProg
transCP o (CurryProg pos mname mnames tdecls fdecls odecls) =
  liftS2 ((CurryProg pos mname mnames tdecls)) transFuncs transDecls
  where transFuncs = mapS (transFunc o True) fdecls
        transDecls = transO odecls



transO :: [COpDecl] -> INS [COpDecl]
transO oDecls = returnS oDecls


-- Functions
transFunc :: Opts -> Bool -> CFuncDecl -> INS CFuncDecl
transFunc o isTop (CFunc   pos   qn@(p, qname,name) ar vis te rules) =
  let trules = (mapS (transRule o alts) rules)
      alts   = if length rules > 1 then True else False
  in  (updateID pos qn isTop)
      `bindS_` -- applyticktransformation
      (CFunc   pos   (p,(qname),name) ar vis te `liftS` trules)
transFunc o isTop (CmtFunc pos s qn@(p, qname,name) ar vis te rules) =
  let trules = (mapS (transRule o alts) rules)
      alts   = if length rules > 1 then True else False
  in  (updateID pos qn isTop) `bindS_`
      (CmtFunc pos s (p,(qname),name) ar vis te `liftS` trules)

--transRules :: [CRule] -> INS [CRule]
--transRules [] = returnS []
--transRules (rule:xs) = let tRule = `liftS` transRule rule
--                      in tRule:(transRules xs)

-- Rules
transRule :: Opts -> Bool -> CRule -> INS CRule
transRule o multipleAlts (CRule pos pats rhs) =
  let trhs = transRhs o multipleAlts rhs
  in CRule pos pats `liftS` trhs -- TODO Pats seperating

-- Rhs TODO ALTERNATIVES just one
transRhs :: Opts -> Bool -> CRhs -> INS CRhs
transRhs o multipleAlts (CSimpleRhs  pos exp  lodecls)   =
  let texp       = transExp o multipleAlts exp
      transDecls = mapS (transLocDecl o) lodecls
  in  liftS2 (CSimpleRhs  pos) texp transDecls
transRhs o           _ (CGuardedRhs pos exps lodecls)   =
  let texp = mapS (transGuard o alts) exps
      alts = if length exps > 1 then True else False
  in  liftS2 (CGuardedRhs pos) texp (mapS (transLocDecl o) lodecls) -- TODO BOOLTICKS


-- (CApply (CApply (CApply (CSymbol ("Prelude","if_then_else")) 
-- (CApply (CApply (CSymbol ("Prelude","==")) (CVar (3,"r"))) (CLit (CIntc 0)))) 

-- Guards;
transGuard :: Opts -> Bool -> (Span, CExpr, CExpr)
           -> INS (Span, CExpr, CExpr)
transGuard o multipleAlts (pos, exp1, exp2) = liftS2 ((,,) pos)
                                              ((transExp o False exp1)
                                              `bindS`
                                              applyGuardTick)
                                              (transExp o multipleAlts exp2) -- BOOL


-- Expressions
transExp :: Opts -> Bool -> CExpr -> INS CExpr
transExp _ isAlt e@(CVar pos _)               = instrument isAlt pos e
transExp _ isAlt e@(CLit pos _)               = instrument isAlt pos e
transExp _ isAlt e@(CSymbol pos _)            = instrument isAlt pos e
transExp o isAlt e@(CApply _ _ _)             = if optim o
                                                  then handleCApply' o isAlt e
                                                  else handleCApply  o isAlt  e
transExp o isAlt (CLambda pos cp exp)         = instrumentWithExp isAlt pos
                                                (((CLambda pos) cp)
                                                `liftS`
                                                (transExp o isAlt exp))
transExp o isAlt (CLetDecl pos lodecls exp)  = liftS2 (CLetDecl pos)
                                               (mapS (transLocDecl o)
                                                             lodecls)
                                               (transExp o isAlt exp)
transExp o isAlt (CDoExpr pos stmts)         = instrumentWithExp isAlt pos
                                               ((CDoExpr pos)
                                               `liftS`
                                               (mapS (transStatement o False)
                                                                               stmts))
transExp o isAlt (CListComp pos exp stmts)   = instrumentWithExp isAlt pos
                                               (liftS2 (CListComp pos)
                                               (transExp o False exp)
                                               (mapS (transStatement o False) stmts))
transExp o isAlt (CCase pos cct exp pr)      = instrumentWithExp isAlt pos
                                               (liftS2 (CCase pos cct)
                                               (transExp o isAlt exp)
                                               (mapS (transCasePat o) pr))
transExp o isAlt (CTyped pos exp txp)        = instrumentWithExp isAlt pos
                                               (liftS2 (CTyped pos)
                                               (transExp o False exp)
                                               (returnS txp)) -- typed expression
transExp o isAlt (CRecConstr pos qn fields)  = instrumentWithExp isAlt pos
                                               ((CRecConstr pos qn)
                                               `liftS`
                                               (mapS (transField o) fields))
transExp o isAlt (CRecUpdate pos exp fields) = instrumentWithExp isAlt pos
                                               (liftS2 (CRecUpdate pos)
                                               (transExp o False exp)
                                               (mapS (transField o) fields))

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

transStatement:: Opts-> Bool -> CStatement -> INS CStatement
transStatement o isAlt (CSExpr pos exp)     = (CSExpr pos)
                                              `liftS` (transExp o isAlt exp)
transStatement o isAlt (CSPat  pos pat exp) = (CSPat  pos pat)
                                               `liftS` (transExp o isAlt exp)
transStatement o _     (CSLet  pos locs)    = (CSLet  pos)     `
                                               liftS` (mapS (transLocDecl o) locs)

transField:: Opts -> (QName, CExpr) -> INS (QName, CExpr)
transField o (qn , exp) = (,) qn `liftS` (transExp o False exp)

--transBool :: CExpr -> INS CExpr
--transBool (CApply (CSymbol ("Prelude","if_then_else")) exp2) = 
-------------------------------------------------------------------------------------

-- TODO LOCALBOXES
transLocDecl :: Opts -> CLocalDecl -> INS CLocalDecl
transLocDecl o (CLocalFunc pos fdecl)   = (CLocalFunc pos)
                                          `liftS` (transFunc o False fdecl)
transLocDecl o (CLocalPat  pos pat rhs) = (CLocalPat pos pat)
                                          `liftS` (transRhs o False rhs)
transLocDecl _ (CLocalVars pos vars)    = returnS (CLocalVars pos vars)

transCasePat :: Opts -> (CPattern, CRhs) -> INS (CPattern, CRhs)
transCasePat o (pat, rhs) = (,) pat `liftS` (transRhs o True rhs)



-------------------------------------------------------------------------------------
d :: Span
d = ((1,0),(0,0))

applyTick :: Span -> Int -> CExpr -> CExpr
applyTick pos id prog = (CApply pos
                          (CApply pos
                             (CSymbol pos (pos, "CLib","tick"))
                             (CLit pos (CIntc pos id)))
                         prog)

applyBoolTick :: CExpr -> Span -> CExpr -> INS CExpr
applyBoolTick exp1 posi exp2 =
  if isIf(exp1)
    then (getS
         `bindS` \(id,boxes)->
         putS (id+2, (id, posi, mkifTBox):
         (id+1, posi, mkifFBox):boxes)
         `bindS_`
         returnS (CApply posi
                   (CApply posi
                     (CApply posi
                       (CSymbol posi (posi, "CLib","boolTick"))
                       (CLit posi (CIntc posi id)))
                     (CLit posi (CIntc posi (id+1))))
                   exp2))
    else returnS exp2
      where isIf exp = case exp of
                   (CSymbol _ (_, "Prelude","if_then_else")) -> True
                   _                                         -> False
            --pos = getPosExp exp2

applyGuardTick:: CExpr -> INS CExpr
applyGuardTick exp1 = {-returnS exp1-}
  (getS
   `bindS` \(id,boxes)->
   putS (id+2, (id, posi, mkGuardTBox):
   (id+1, posi, mkGuardFBox):boxes)
   `bindS_`
   returnS (CApply posi
              (CApply posi
                 (CApply posi
                 (CSymbol posi (posi, "CLib","boolTick"))
                 (CLit posi (CIntc posi id)))
              (CLit posi (CIntc posi (id+1))))
            exp1))
  where posi = getPosExp exp1

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

instrument:: Bool -> Span -> CExpr -> INS CExpr
instrument isAlt pos exp =   getS
                            `bindS` \(id,boxes)->
                             putS ( id+1
                                , (id, pos, mkExpBox isAlt):boxes)
                            `bindS_` returnS (applyTick pos id exp)

instrumentWithExp:: Bool -> Span -> INS CExpr -> INS CExpr
instrumentWithExp isAlt pos exp = getS
                                  `bindS` \(id,boxes)->
                                   putS ( id+1
                                       , (id, pos, mkExpBox isAlt):boxes)
                                  `bindS_` (applyTick pos id) `liftS` exp


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

getPosExp :: CExpr -> Span
getPosExp (CVar pos _)         = pos
getPosExp (CLit pos _)         = pos
getPosExp (CSymbol pos _)      = pos
getPosExp (CApply pos _ e2)    = if pos == d then getPosExp e2 else pos
getPosExp (CLambda pos _ _)    = pos
getPosExp (CLetDecl pos _ _)   = pos
getPosExp (CDoExpr pos _)      = pos
getPosExp (CListComp pos _ _)  = pos
getPosExp (CCase pos _ _ _)    = pos
getPosExp (CTyped pos _ _)     = pos
getPosExp (CRecConstr pos _ _) = pos
getPosExp (CRecUpdate pos _ _) = pos

-- applyBoolTick exp1 nm exp2 = returnS exp2

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

-- transformBack :: CurryProg -> String
--transformBack cprog =  showCProg cprog

-------------------------------------------------------------------------------
handleCApply':: Opts -> Bool -> CExpr -> INS CExpr
handleCApply' o isAlt cexp@(CApply pos _ _) =
  let flat     = (flatApply cexp [])
      flatFunc = map snd flat
      possi    = map fst flat
      poss     = tail possi
      (CSymbol _ (_,mname,qname)) = head flatFunc
      ar       = {-if isITE cexp then 3 else-} lookupWithDefaultFM (arityM o) 0 (mname,qname)
      params   = take ar (tail flatFunc)
--     (posi, noPosi)       = splitAt ar poss
      tickedParams = mapS (transExp o False) params
--     tickedNoParams = mapS (transExp o False) noParams
   in if(isITE cexp || flat == [])
       then handleCApply o isAlt cexp
       else if ar==length(tail flatFunc)
              then (getS
                   `bindS` \(id,boxes)->
                    putS (id+1, (id, pos, mkExpBox isAlt):
                                (map (dummyBoxes id) possi)++boxes)
                    `bindS_`(applyTick pos id)
                    `liftS` ((buildCApply (head flatFunc) poss)
                            `liftS` tickedParams))
        else handleCApply o isAlt cexp
handleCApply' _ _ (CSymbol _ _)                 = error "handleApply"
handleCApply' _ _ (CVar _ _)                 = error "handleApply'"
handleCApply' _ _ (CLit _ _)                 = error "handleApply'"
handleCApply' _ _ (CLambda _ _ _)            = error "handleApply'"
handleCApply' _ _ (CLetDecl _ _ _)           = error "handleApply'"
handleCApply' _ _ (CDoExpr _ _)              = error "handleApply'"
handleCApply' _ _ (CListComp _ _ _)          = error "handleApply'"
handleCApply' _ _ (CCase _ _ _ _)            = error "handleApply'"
handleCApply' _ _ (CTyped _ _ _)             = error "handleApply'"
handleCApply' _ _ (CRecConstr _ _ _)         = error "handleApply'"
handleCApply' _ _ (CRecUpdate _ _ _)         = error "handleApply'"


dummyBoxes:: Int -> Span -> (Int, Span, BoxLabel)
dummyBoxes id p = (id, p , mkExpBox False)


buildCApply:: CExpr -> [Span] -> [CExpr] -> CExpr
buildCApply sym  pos params@(_:_) =
  buildCApply (CApply (head pos) sym (head params))
              (tail pos)
              (tail params)
buildCApply sym  _             [] = sym

handleCApply:: Opts -> Bool -> CExpr -> INS CExpr
handleCApply o isAlt (CApply pos exp1 exp2) =
  instrumentWithExp isAlt pos (liftS2 (CApply pos)
                                      (transExp o False exp1)
                                      ((transExp o False exp2)
                              `bindS` (applyBoolTick exp1 posi)))
  where posi = getPosExp exp2
handleCApply _ _ (CSymbol _ _)                 = error "handleApply"
handleCApply _ _ (CVar _ _)                 = error "handleApply"
handleCApply _ _ (CLit _ _)                 = error "handleApply"
handleCApply _ _ (CLambda _ _ _)            = error "handleApply"
handleCApply _ _ (CLetDecl _ _ _)           = error "handleApply"
handleCApply _ _ (CDoExpr _ _)              = error "handleApply"
handleCApply _ _ (CListComp _ _ _)          = error "handleApply"
handleCApply _ _ (CCase _ _ _ _)            = error "handleApply"
handleCApply _ _ (CTyped _ _ _)             = error "handleApply"
handleCApply _ _ (CRecConstr _ _ _)         = error "handleApply"
handleCApply _ _ (CRecUpdate _ _ _)         = error "handleApply"


-- handleNoParams:: [CEpxr] -> [Spans] -> INS (CExpr) -> INS (CExpr)
-- handleNoParams p:params pos s =  
flatApply :: CExpr -> [(Span,CExpr)] -> [(Span,CExpr)]
flatApply (CApply pos exp1 exp2) coll  = flatApply exp1 ((pos,exp2):coll)
flatApply s@(CSymbol pos _)      coll  = (pos,s):coll
flatApply (CVar _ _) _                 = []
flatApply (CLit _ _) _                 = []
flatApply (CLambda _ _ _) _            = []
flatApply (CLetDecl _ _ _) _           = []
flatApply (CDoExpr _ _) _              = []
flatApply (CListComp _ _ _) _          = []
flatApply (CCase _ _ _ _) _            = []
flatApply (CTyped _ _ _) _             = []
flatApply (CRecConstr _ _ _) _         = []
flatApply (CRecUpdate _ _ _) _         = []


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

extractITE :: CExpr -> Maybe (CExpr, CExpr, CExpr)
extractITE e =
  case e of
     CApply _ (CApply _ (CApply _ (CSymbol _ (_,"Prelude","if_then_else"))
                         cond)
              tExp)
           fExp -> Just (cond, tExp, fExp)
     _          -> Nothing

isITE:: CExpr -> Bool
isITE cexp = isJust $ extractITE cexp