| 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
 | 
module CPP.Contracts ( main, translateContracts )
  where
import Control.Monad                 ( when, unless )
import Curry.Compiler.Distribution   ( installDir )
import Data.Char
import Data.List
import System.Environment            ( getArgs )
import AbstractCurry.Types
import AbstractCurry.Files
import AbstractCurry.Pretty
import AbstractCurry.Build
import AbstractCurry.Select
import AbstractCurry.Transform
import Contract.Names
import Contract.Usage   ( checkContractUsage )
import FlatCurry.Files  ( readFlatCurry )
import qualified FlatCurry.Goodies as FCG
import System.CurryPath ( lookupModuleSourceInLoadPath, modNameToPath
                        , stripCurrySuffix )
import System.Directory
import System.FilePath  ( takeDirectory )
import System.Process   ( system )
import Analysis.ProgInfo      ( ProgInfo, lookupProgInfo )
import Analysis.Deterministic ( Deterministic(..), nondetAnalysis )
import CASS.Server            ( analyzeGeneric )
import SimplifyPostConds
import TheoremUsage
import CPP.CompileWithFrontend ( compileImportedModule )
import CPP.Helpers             ( checkRequiredImport, setFunMod )
banner :: String
banner = unlines [bannerLine,bannerText,bannerLine]
 where
   bannerText = "Contract Transformation Tool (Version of 01/11/21)"
   bannerLine = take (length bannerText) (repeat '=')
translateContracts :: Int -> [String] -> String -> String -> CurryProg
                   -> IO (Maybe CurryProg)
translateContracts verb moreopts modname srcprog inputProg = do
  when (verb>1) $ putStr banner
  opts <- processOpts defaultOptions moreopts
  transformCProg verb opts modname srcprog inputProg (progName inputProg)
 where
  processOpts opts ppopts = case ppopts of
    []          -> return opts
    ("-e":more) -> processOpts (opts { withEncapsulate   = True }) more
    ("-t":more) -> processOpts (opts { topLevelContracts = True }) more
    _           -> showError
   where
    showError = do
      putStrLn $ "Unknown options (ignored): " ++ show (unwords ppopts)
      return opts
data Options = Options
  { 
    withEncapsulate   :: Bool
    
    
  , topLevelContracts :: Bool
    
  , executeProg       :: Bool
  }
defaultOptions :: Options
defaultOptions = Options
  { withEncapsulate   = False
  , topLevelContracts = False
  , executeProg       = False
  }
main :: IO ()
main = do
  putStrLn banner
  args <- getArgs
  processArgs defaultOptions args
 where
  processArgs opts args = case args of
     ("-e":margs) -> processArgs (opts { withEncapsulate   = True }) margs
     ("-t":margs) -> processArgs (opts { topLevelContracts = True }) margs
     ("-r":margs) -> processArgs (opts { executeProg       = True }) margs
     [mnamec]        -> let mname = stripCurrySuffix mnamec
                         in transformStandalone opts mname
                                      (transformedModName mname ++ ".curry")
     _ -> putStrLn $ unlines $
           ["ERROR: Illegal arguments for transformation: " ++ unwords args
           ,""
           ,"Usage: cwrapper [-e] [-t] [-r] <module_name>"
           ,"-e   : encapsulate nondeterminism of assertions"
           ,"-t   : assert contracts only to top-level (not recursive) calls"
           ,"-r   : load the transformed program into Curry system"
           ]
transformStandalone :: Options -> String -> String -> IO ()
transformStandalone opts modname outfile = do
  mmodsrc <- lookupModuleSourceInLoadPath modname
  srcprog <- case mmodsrc of
               Nothing -> error $
                            "Source code of module '"++modname++"' not found!"
               Just (_,progname) -> readFile progname
  let acyfile = abstractCurryFileName modname
  doesFileExist acyfile >>= \b -> if b then removeFile acyfile else return ()
  prog <- readCurry modname
  doesFileExist acyfile >>= \b -> if b then return ()
                                       else error "Source program incorrect"
  let outmodname = transformedModName modname
  newprog <- transformCProg 1 opts modname srcprog prog outmodname
  writeFile outfile (showCProg (maybe prog id newprog) ++ "\n")
  when (executeProg opts) $ loadIntoCurry outmodname
transformedModName :: String -> String
transformedModName m = m++"C"
loadIntoCurry :: String -> IO ()
loadIntoCurry m = do
  putStrLn $ "\nStarting Curry system and loading module '"++m++"'..."
  system $ installDir++"/bin/curry :l "++m
  return ()
transformCProg :: Int -> Options -> String -> String -> CurryProg -> String
               -> IO (Maybe CurryProg)
transformCProg verb opts modname srctxt orgprog outmodname = do
  fcyprog <- readFlatCurry modname
  let usageerrors = checkContractUsage modname
                      (map (\fd -> (snd (FCG.funcName fd), FCG.funcType fd))
                           (FCG.progFuncs fcyprog))
  unless (null usageerrors) $ do
    putStr (unlines $ "ERROR: ILLEGAL USE OF CONTRACTS:" :
               map (\ ((mn,fn),err) -> fn ++ " (module " ++ mn ++ "): " ++ err)
                   usageerrors)
    error "Contract transformation aborted"
  let prog         = addCmtFuncInProg orgprog 
      funposs      = linesOfFDecls srctxt prog
      fdecls       = functions prog
      funspecs     = getFunDeclsWith isSpecName prog
      specnames    = map (fromSpecName . snd . funcName) funspecs
      preconds     = getFunDeclsWith isPreCondName prog
      prenames     = map (fromPreCondName  . snd . funcName) preconds
      opostconds   = getFunDeclsWith isPostCondName prog
  
  theofuncs <- getTheoremFunctions
                (takeDirectory (modNameToPath (progName prog))) prog
  postconds <- simplifyPostConditionsWithTheorems verb theofuncs opostconds
  let postnames = map (fromPostCondName  . snd . funcName) postconds
      checkfuns = union specnames (union prenames postnames)
  if null checkfuns
   then do
     when (verb>1) $
       putStrLn "Contract transformation not required since no contracts found!"
     return Nothing
   else do
     when (verb>0) $
       putStrLn $ "Adding contract checking to: " ++ unwords checkfuns
     detinfo <- analyzeGeneric nondetAnalysis (progName prog)
                                              >>= return . either id error
     newprog <- transformProgram verb opts funposs fdecls detinfo
                                 funspecs preconds postconds prog
     return (Just (renameCurryModule outmodname newprog))
getFunDeclsWith :: (String -> Bool) -> CurryProg -> [CFuncDecl]
getFunDeclsWith pred prog = filter (pred . snd . funcName) (functions prog)
transformProgram :: Int -> Options -> [(QName,Int)]-> [CFuncDecl]
                 -> ProgInfo Deterministic -> [CFuncDecl]
                 -> [CFuncDecl] -> [CFuncDecl] -> CurryProg -> IO CurryProg
transformProgram verb opts funposs allfdecls detinfo
  specdecls predecls postdecls
  (CurryProg mname imps dfltdecl clsdecls instdecls tdecls
             orgfdecls opdecls) = do
  let 
      fdecls = filter (\fd -> funcName fd `notElem` map funcName postdecls)
                      orgfdecls ++ postdecls
      newpostconds = concatMap
                       (genPostCond4Spec opts allfdecls detinfo postdecls)
                       specdecls
      newfunnames  = map (snd . funcName) newpostconds
      
      
      wonewfuns    = filter (\fd -> snd (funcName fd) `notElem` newfunnames)
                            fdecls
      
      contractpcs  = postdecls++newpostconds
  checkRequiredImport mname contractMod imps
  checkRequiredImport mname setFunMod imps
  unless (contractMod `elem` imps) $ compileImportedModule verb contractMod
  unless (setFunMod   `elem` imps) $ compileImportedModule verb setFunMod
  return $ CurryProg
    mname (nub (contractMod : setFunMod : imps))
    dfltdecl clsdecls instdecls tdecls
    (map deleteCmtIfEmpty
        (concatMap (addContract opts funposs allfdecls predecls contractpcs)
                   wonewfuns ++ newpostconds))
    opdecls
addCmtFuncInProg :: CurryProg -> CurryProg
addCmtFuncInProg
  (CurryProg mname imps dfltdecl clsdecls instdecls tdecls fdecls opdecls) =
   CurryProg mname imps dfltdecl clsdecls instdecls tdecls
             (map addCmtFunc fdecls) opdecls
 where
  addCmtFunc (CFunc qn ar vis texp rs) = CmtFunc "" qn ar vis texp rs
  addCmtFunc (CmtFunc cmt qn ar vis texp rs) = CmtFunc cmt qn ar vis texp rs
genPostCond4Spec :: Options -> [CFuncDecl] -> ProgInfo Deterministic
                 -> [CFuncDecl] -> CFuncDecl -> [CFuncDecl]
genPostCond4Spec _ _ _ _ (CFunc _ _ _ _ _) = error "genPostCond4Spec"
genPostCond4Spec _ allfdecls detinfo postdecls
               (CmtFunc _ (m,f) ar vis (CQualType (CContext clscons) texp) _) =
 let fname     = fromSpecName f
     
     detspec   = maybe False (== Det) (lookupProgInfo (m,f) detinfo)
     fpostname = toPostCondName fname
     fpgenname = fpostname++"'generic"
     oldfpostc = filter (\fd -> snd (funcName fd) == fpostname) postdecls
     oldcmt    = if null oldfpostc then ""
                                   else '\n' : funcComment (head oldfpostc)
     varg      = (0,"g")
     argvars   = map (\i -> (i,"x"++show i)) [1..(ar+1)]
     spargvars = take ar argvars
     resultvar = last argvars
     gtype     = CTVar (0,"grt") 
     varz      = (ar+2,"z")
     obsfun    = maybe (pre "id")
                       funcName
                       (find (\fd -> snd (funcName fd) == fpostname++"'observe")
                             allfdecls)
     gspecname = (m,f++"'g")
     gspec     = cfunc gspecname ar Private
                  (CQualType (CContext ((pre "Eq", gtype) : clscons))
                   ((resultType texp ~> gtype) ~> replaceResultType texp gtype))
                  [let gsargvars = map (\i -> (i,"x"++show i)) [1..ar]
                   in  simpleRule (CPVar varg : map CPVar gsargvars)
                                  (CApply (CVar varg)
                                          (applyF (m,f) (map CVar gsargvars)))]
     postcheck =
       CLetDecl
         [CLocalPat (CPVar varz)
                    (CSimpleRhs (CApply (CVar varg) (CVar resultvar)) [])]
         (if detspec
            then applyF (pre "==")
                   [CVar varz, applyF gspecname (map CVar (varg : spargvars))]
            else applyF (pre "&&")
                   [applyF (pre "==") [CVar varz, CVar varz],
                    applyF (sfMod "valueOf")
                      [CVar varz,
                       
                       
                       
                       
                       
                       applyF (sfMod $ "set" ++ show ar)
                         (applyF gspecname [CVar varg] : map CVar spargvars)]])
     rename qf = if qf == (m,fpostname) then (m,fpostname++"'org") else qf
  in [cmtfunc
       ("Parametric postcondition for '"++fname++
        "' (generated from specification). "++oldcmt)
       (m,fpgenname) (ar+2) Private
       (CQualType (CContext ((pre "Eq", gtype) : clscons))
                  ((resultType texp ~> gtype) ~> extendFuncType texp boolType))
       [if null oldfpostc
        then simpleRule (map CPVar (varg:argvars)) postcheck
        else simpleRuleWithLocals
                (map CPVar (varg:argvars))
                (applyF (pre "&&")
                             [applyF (rename (funcName (head oldfpostc)))
                                     (map CVar argvars),
                              postcheck])
                [updQNamesInCLocalDecl rename
                        (CLocalFunc (deleteCmt (head oldfpostc)))]]
     ,gspec
     ,cmtfunc
       ("Postcondition for '"++fname++"' (generated from specification). "++
        oldcmt)
       (m,fpostname) (ar+1) vis
       (CQualType
          (CContext (union (type2EqConstraints (resultType texp)) clscons))
          (extendFuncType texp boolType))
       [simpleRule (map CPVar argvars)
                   (applyF (m,fpgenname)
                           (constF obsfun : map CVar argvars))]
     ]
type2EqConstraints :: CTypeExpr -> [CConstraint]
type2EqConstraints texp =
  map (\tv -> (pre "Eq",CTVar tv)) (nub (tvarsOfType texp))
type2ShowConstraints :: CTypeExpr -> [CConstraint]
type2ShowConstraints texp =
  map (\tv -> (pre "Show",CTVar tv)) (nub (tvarsOfType texp))
addEqShowConstraints :: CQualTypeExpr -> CQualTypeExpr
addEqShowConstraints (CQualType (CContext clscons) texp) =
  CQualType (CContext (union (type2EqConstraints (resultType texp))
                             (union (type2ShowConstraints texp) clscons)))
            texp
addContract :: Options -> [(QName,Int)] -> [CFuncDecl] -> [CFuncDecl]
            -> [CFuncDecl] -> CFuncDecl -> [CFuncDecl]
addContract _ _ _ _ _ (CFunc _ _ _ _ _) =
  error "Internal error in addContract: CFunc occurred"
addContract opts funposs allfdecls predecls postdecls
            orgfdecl@(CmtFunc cmt qn@(m,f) ar vis qtype _) =
 let argvars     = map (\i -> (i,"x"++show i)) [1..ar]
     encapsSuf   = if withEncapsulate opts then "ND" else ""
     encaps fn n = if withEncapsulate opts then setFun n fn []
                                           else constF fn
     
     fref      = string2ac $ "'" ++ f ++ "' (module " ++ m ++
                             maybe ")"
                                   (\l -> ", line " ++ show l ++ ")")
                                   (lookup qn funposs)
     
     obsfunexp = constF $
                  maybe (pre "id")
                       funcName
                       (find (\fd -> snd (funcName fd) == f++"'post'observe")
                             allfdecls)
     ctexp = addEqShowConstraints qtype
     fdecl = setTypeInFuncDecl ctexp orgfdecl
     
     (precheck,woprefdecl) =
        maybe ([],fdecl)
          (\predecl ->
            let prename = funcName predecl
                rename = updateFunc id qn (withSuffix qn "'WithoutPreCondCheck")
            in ([cmtfunc cmt (m,f) ar vis ctexp
                   [simpleRule (map CPVar argvars)
                      (applyF (cMod $ "withPreContract" ++ show ar ++ encapsSuf)
                         ([fref, encaps prename ar, constF (rename qn)] ++
                          map CVar argvars))]],
                addCmtLine "Without precondition checking!" $
                           rnmFDecl rename fdecl))
          (find (\fd -> fromPreCondName (snd (funcName fd)) == f) predecls)
     
     (postcheck,wopostfdecl) =
        maybe ([],woprefdecl)
          (\postdecl ->
            let postname = funcName postdecl
                qnp      = funcName woprefdecl
                rename   = updateFunc id qnp
                                      (withSuffix qnp "'WithoutPostCondCheck")
            in ([cmtfunc (funcComment woprefdecl) qnp ar vis ctexp
                 [simpleRule (map CPVar argvars)
                    (applyF (cMod $ "withPostContract" ++ show ar ++ encapsSuf)
                      ([fref, encaps postname (ar+1), obsfunexp,
                        constF (rename qnp)] ++
                       map CVar argvars))]],
                 setPrivate $ addCmtLine "Without postcondition checking!" $
                              rnmFDecl rename woprefdecl))
          (find (\fd-> fromPostCondName (snd (funcName fd)) == f) postdecls)
     rnmFDecl rnm fdcl = if topLevelContracts opts
                           then updQNamesInCFuncDecl rnm fdcl
                           else renameFDecl rnm fdcl
  in precheck ++ postcheck ++ [wopostfdecl]
updateFunc :: Eq a => (a -> b) -> a -> b -> (a -> b)
updateFunc f x v y = if y==x then v else f y
setPrivate :: CFuncDecl -> CFuncDecl
setPrivate = updCFuncDecl id id id (const Private) id id
setTypeInFuncDecl :: CQualTypeExpr -> CFuncDecl -> CFuncDecl
setTypeInFuncDecl texp = updCFuncDecl id id id id (const texp) id
withSuffix :: QName -> String -> QName
withSuffix (m,f) s = (m, f ++ s)
replaceResultType :: CTypeExpr -> CTypeExpr -> CTypeExpr
replaceResultType texp ntype =
  case texp of CFuncType t1 t2 -> CFuncType t1 (replaceResultType t2 ntype)
               _               -> ntype
extendFuncType :: CTypeExpr -> CTypeExpr -> CTypeExpr
extendFuncType t texp = case t of
  CFuncType t1 t2 -> t1 ~> (extendFuncType t2 texp)
  _               -> t ~> texp
renameFDecl :: (QName -> QName) -> CFuncDecl -> CFuncDecl
renameFDecl rn (CFunc qn ar vis texp rules) = CFunc (rn qn) ar vis texp rules
renameFDecl rn (CmtFunc cmt qn ar vis texp rules) =
  CmtFunc cmt (rn qn) ar vis texp rules
addCmtLine :: String -> CFuncDecl -> CFuncDecl
addCmtLine s (CFunc     qn ar vis texp rules) =
  CmtFunc s qn ar vis texp rules
addCmtLine s (CmtFunc cmt qn ar vis texp rules) =
  CmtFunc (if null cmt then s else unlines [cmt,s]) qn ar vis texp rules
deleteCmt :: CFuncDecl -> CFuncDecl
deleteCmt (CFunc     qn ar vis texp rules) = CFunc qn ar vis texp rules
deleteCmt (CmtFunc _ qn ar vis texp rules) = CFunc qn ar vis texp rules
deleteCmtIfEmpty :: CFuncDecl -> CFuncDecl
deleteCmtIfEmpty (CFunc qn ar vis texp rules)     = CFunc qn ar vis texp rules
deleteCmtIfEmpty (CmtFunc cmt qn ar vis texp rules) =
  if null cmt then CFunc qn ar vis texp rules
              else CmtFunc cmt qn ar vis texp rules
linesOfFDecls :: String -> CurryProg -> [(QName,Int)]
linesOfFDecls srctxt prog =
  map (addSourceLineNumber (map firstId (lines srctxt)))
      (map funcName (functions prog))
 where
  addSourceLineNumber ids qn = (qn, maybe 0 (+1) (elemIndex (snd qn) ids))
firstId :: String -> String
firstId [] = ""
firstId (c:cs)
  | isAlpha c = takeWhile isIdChar (c:cs)
  | c == '('  = let bracketid = takeWhile (/=')') cs
                 in if all (`elem` infixIDs) bracketid
                    then bracketid
                    else ""
  | otherwise = ""
isIdChar :: Char -> Bool
isIdChar c = isAlphaNum c || c == '_' || c == '\''
infixIDs :: String
infixIDs =  "~!@#$%^&*+-=<>?./|\\:"
sfMod :: String -> QName
sfMod f = (setFunMod,f)
setFun :: Int -> QName -> [CExpr] -> CExpr
setFun n qn args = applyF (sfMod $ "set" ++ show n) (constF qn : args)
contractMod :: String
contractMod = "Test.Contract"
cMod :: String -> QName
cMod f = (contractMod,f)
 |