CurryToHaskell.hs 44.3 KB
Newer Older
bbr's avatar
bbr committed
1
2
module CurryToHaskell where 

3
4
import List
import Char
5
6
import System 
import System.FilePath 
7

8
9
import MetaProgramming.FlatCurry 
import MetaProgramming.FlatCurryGoodies hiding (consName)
bbr's avatar
bbr committed
10
11
12
import qualified FunctionalProg as C
import ShowFunctionalProg
import PreTrans hiding (nub,pre)
bbr's avatar
bbr committed
13
import Simplification ( simplifyProg )
bbr's avatar
bbr committed
14
15
16
17
import Maybe
import SafeCalls
import Brace
import Config
18
import Names (modName,dbgModName,funcHsName,externalSpecName,
bbr's avatar
bbr committed
19
20
21
22
              elimInfix,funName,functionName,constructorName)
import qualified Names as N
import Monad

23
24
--import Debug.Trace
--trace' x = trace (show x) x
bbr's avatar
bbr committed
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

-------------------------------
-- main compilation routine
-------------------------------

-- call this function to start compilation
-- arguments: record of Type Options as defined 
-- in Config.hs 

startCompilations :: Options -> [String] -> IO [String]
startCompilations _ [] = return []
startCompilations opts fs = 
  compilations fs opts{done=[],mainModule=head fs}

compilations ::  [String] -> Options -> IO [String]
compilations [] opts = return (done opts)
compilations (f:fs) opts = 
  safe (startCompilation opts{filename=f}) >>=
  compilations fs . maybe opts id

startCompilation :: Options -> Safe IO Options
startCompilation opts = do 
bbr's avatar
bbr committed
47
  put 2 opts "calling frontend"
bbr's avatar
bbr committed
48
49
  newOpts <- callFrontend opts 
  visited <- compile newOpts >>= return . done 
bbr's avatar
bbr committed
50
  put 2 opts "calling ghc"
bbr's avatar
bbr committed
51
52
53
54
55
56
57
58
59
60
61
  ghcProgram False newOpts (funcHsName (filename newOpts))
  return newOpts{done=visited}

-- compile not only returns the current Options 
-- but also a flag whether no significant changes
-- have been made. A significant change forces
-- recompilation of dependent modules.
compile :: Options -> Safe IO Options
compile opts = do
  newOpts <- getFlatCurryFileName opts
  old <- notUptodate newOpts
62
63
  if old || force opts || executable opts 
   -- possible improvement: generate only Main.hs if up-to-date
bbr's avatar
bbr committed
64
65
66
67
68
   then process newOpts >>= makeImports 
   else skip    newOpts >>= makeImports 

process :: Options -> Safe IO (String,[String],Options)
process opts0@(Opts{filename=fn}) = do
69
  prog <- safeReadFlat opts0 (replaceExtension fn ".fcy")
bbr's avatar
bbr committed
70
71
  unless (executable opts0)  
         (put 1 opts0 ("processing: "++progName prog))
bbr's avatar
bbr committed
72
  opts <- readExternalSpec opts0 fn
73
74
75
76
77
78
  unless (null $ extData  opts) 
         (put 5 opts "external data declarations found")
  unless (null $ extInsts opts) 
         (put 5 opts "external instance declarations found")
  unless (null $ extFuncs opts) 
         (put 5 opts "external function declarations found")
bbr's avatar
bbr committed
79
80
81
82
83
84
  applyFlatTransformations opts prog >>= generateHaskellFiles opts
  return (progName prog,progImports prog,opts0)

-- only read beginning of interface file, return name and list of imports 
skip :: Options -> Safe IO (String,[String],Options)
skip opts = do
bbr's avatar
bbr committed
85
    let fname = if doNotUseInterface opts 
86
87
                then replaceExtension (filename opts) ".fcy"
                else replaceExtension (filename opts) ".fint"
bbr's avatar
bbr committed
88
    fn <- safeIO (findFileInPath fname (libpath opts)) >>=
bbr's avatar
bbr committed
89
          warning (filename opts) (cmdLibpath opts) 
Bernd Brassel's avatar
Bernd Brassel committed
90
    cont <- safeIOSeq (readModule fn)
bbr's avatar
bbr committed
91
92
93
    let [("Prog",rest)] = lex cont
        [(name,rest')]  = reads rest
        [(imps,_)]      = reads rest'
bbr's avatar
bbr committed
94
    put 3 opts ("up-to-date: "++name)
bbr's avatar
bbr committed
95
96
97
98
99
100
101
102
103
104
105
106
    return (name,imps,opts)

makeImports :: (String,[String],Options) -> Safe IO Options
makeImports (name,imps,opts@(Opts{filename=fn})) = do
  impOpts <- foldCompile imps opts{executable=False}
  return impOpts{done=name : done impOpts}

---------------------------------------------------------------------------------
-- sub routines of compilation
---------------------------------------------------------------------------------

callFrontend opts@(Opts{filename=givenFile}) = do
107
108
  let lib = libpath opts
  foundCurry <- safeIO (findFileInPath (replaceExtension givenFile ".curry") lib)
bbr's avatar
bbr committed
109
  foundSources <- if null foundCurry 
110
                   then safeIO (findFileInPath (replaceExtension givenFile ".lcurry") lib)
bbr's avatar
bbr committed
111
                   else return foundCurry
bbr's avatar
bbr committed
112
113
114
  unless (null foundSources) (if   debug opts 
                              then prophecy opts 
                              else cymake opts)
Bernd Brassel's avatar
Bernd Brassel committed
115
  return (if debug opts then opts{filename=dbgModName givenFile} else opts)
bbr's avatar
bbr committed
116
117
118

getFlatCurryFileName opts@(Opts{filename=basename}) = do
  let lib = libpath opts
119
  foundFiles <- safeIO (findFileInPath (replaceExtension basename ".fcy") lib)
Bernd Brassel's avatar
Bernd Brassel committed
120
  foundFile <- warning basename (toPathList lib) foundFiles
Bernd Brassel's avatar
Bernd Brassel committed
121
  let foundBasename = dropExtensions foundFile
bbr's avatar
bbr committed
122
123
124
  return (opts{filename=foundBasename})

notUptodate opts@(Opts{filename=foundBasename}) = do
125
126
127
128
129
  tSource1     <- getModTime (replaceExtension foundBasename ".fcy")
  tSource2     <- getExternalSpecModTime opts foundBasename
  let destination = inModuleSubdir (inKicsSubdir (funcHsName foundBasename))
  tDestination <- getModTime destination
  return (tSource1 > tDestination || tSource2 > tDestination)
bbr's avatar
bbr committed
130
131
132
133
134
135

applyFlatTransformations opts prog = do
  let auxNames = generateAuxNames (progFuncs prog)
      mexprog = if executable opts then addExec auxNames opts prog 
                                   else Left prog
  exprog <- either return fail mexprog 
136
137
138
  let suffix = flip replaceExtension $ if doNotUseInterface opts
               then ".fcy"
               else ".fint"
bbr's avatar
bbr committed
139
140
  interfaces <- mapM (safeReadFlat opts . suffix) (progImports exprog) 
  (globals,locProg) <- safeIOSeq (return (splitGlobals exprog))
bbr's avatar
bbr committed
141
  let liftedProg = noCharCase (liftCases True (simplifyProg locProg))
bbr's avatar
bbr committed
142
  --disAmb <- disambiguate interfaces ceprog
143
144
145
  unless (null globals) 
         (put 5 opts 
            ("module contains "++show (length globals)
146
                               ++" global declaration(s)"))
bbr's avatar
bbr committed
147
  return (globals,liftedProg,interfaces,auxNames)
bbr's avatar
bbr committed
148

bbr's avatar
bbr committed
149
generateHaskellFiles opts (globals,prog,interfaces,auxNames) = do
bbr's avatar
bbr committed
150
  let typeMapping = makeTypeMap (prog:interfaces)
bbr's avatar
bbr committed
151
      modules = transform typeMapping auxNames opts prog
bbr's avatar
bbr committed
152
  put 3 opts "generating Haskell"
bbr's avatar
bbr committed
153
  mapM  (writeProgram opts) (addGlobalDefs opts globals modules)
bbr's avatar
bbr committed
154
155
  return (haskellFiles opts (progName prog))

Bernd Brassel's avatar
Bernd Brassel committed
156
writeProgram opts (fn,unqualified,prog) = do
157
158
  let fn' = inModuleSubdir (inKicsSubdir fn)
  put 3 opts ("writing "++ fn')
Bernd Brassel's avatar
Bernd Brassel committed
159
  let printOpts = defaultPrintOptions{unqual=unqualified,include=toInclude opts}
160
161
  safeIO (writeKicsFile (fn/="Main.hs") fn (showProgOpt printOpts prog))
  put 3 opts (fn'++" written")
bbr's avatar
bbr committed
162
163
164
165
166
167
168
  return fn


ghcProgram skipping opts fn = 
  unless (eval opts && executable opts)  $ do
      found <- safeIO (findFileInPath fn (libpath opts))
      let hsFile = head found
bbr's avatar
bbr committed
169
          ghc    = safeSystem (verbosity opts >= 2) 
170
                     (ghcCall opts{make=True,filename=hsFile,target=""})
bbr's avatar
bbr committed
171
172
173
174
175
176
          shFile = drop 2 (reverse hsFile)
          oFile  = reverse ('o':shFile)
          hiFile = reverse ('i':'h':shFile)
      unless (null found) $
         if skipping 
           then do
Bernd Brassel's avatar
Bernd Brassel committed
177
                  ex <- safeIO (mapM doesModuleExist [oFile,hiFile])
bbr's avatar
bbr committed
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
                  unless (and ex) ghc
           else ghc

foldCompile :: [String] -> Options -> Safe IO Options
foldCompile [] opts     = return opts
foldCompile (f:fs) opts 
  | elem f (done opts) = foldCompile fs opts
  | otherwise          = compile (opts{filename=f}) >>=
                         foldCompile fs


------------------------------------------------------
-- auxiliary functions
------------------------------------------------------

-- names of all haskell files associated with program
haskellFiles :: Options -> String -> [String]
Bernd Brassel's avatar
Bernd Brassel committed
195
haskellFiles opts name = [funcHsName name]
bbr's avatar
bbr committed
196
197
198
199
200
201
202
203
204
205
206

------------------------------------------------------
-- basic transformation
------------------------------------------------------
-- for a given module up to three haskell modules are generated:
    -- one for the functions,
    -- one for the data declarations (possibly empty)
    -- one "Main"-module to generate executables, 
    --   if the executable flag is set in the options
-- introduce Modules CallTime/RunTimeChoice 
transform typeMapping aux opts0 (Prog name imports types funcs _)
bbr's avatar
bbr committed
207
208
  = (if executable opts then [(mainFileName,False,mainModule)] else [])
     ++ modules
bbr's avatar
bbr committed
209
210
211
212
213

  where
    opts = opts0{hasData=hasInternalData}
    hasInternalData      = not $ null $ filter (not . isExternalType) types

Bernd Brassel's avatar
Bernd Brassel committed
214
    modules = [allinclusiveProg]
bbr's avatar
bbr committed
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235

    -- filename, flag and module definitions
    allinclusiveProg = (funcHsName (filename opts),False,allinclusive)


    modul mName mImports mExports mTypes mInsts mFuncs =  
      C.Prog mName mImports mExports mTypes mInsts mFuncs []

    allinclusive   = modul funcName allIImports allIExports dataTypes instances functions

    -- the module names are:
    funcName = modName name

    mainModuleName = "Main"

    -- the file names of these modules are:
    funcFileName = funcHsName (filename opts)
    mainFileName = "Main.hs"

    -- import lists
    newImports = map modName imports
236
    allIImports = [curryModule] ++ newImports
Bernd Brassel's avatar
Bernd Brassel committed
237
238

    {-
bbr's avatar
bbr committed
239
240
241
242
243
    -- this is the only special prelude treatment:
    instImportName 
      | name=="Prelude" = instName ++ " hiding ("++opsUsedInInstances++")"
      | otherwise       = instName
    opsUsedInInstances = "op_38_38"
Bernd Brassel's avatar
Bernd Brassel committed
244
245
    -}

bbr's avatar
bbr committed
246
    -- export lists
Bernd Brassel's avatar
Bernd Brassel committed
247
    allIExports = []
bbr's avatar
bbr committed
248
249
250
 
    -- the generated types, instances and functions
    dataTypes = map (transTypeDecl opts{consUse=DataDef}) 
bbr's avatar
bbr committed
251
                    (typeSyns++filter isToTransform typeDecls)
bbr's avatar
bbr committed
252
253
254
255
256
257
258
259
260
    instances =  genInstances BaseCurry baseCurryInstance opts typeDecls
              ++ genInstances Curry     curryInstance     opts typeDecls
              ++ genInstances Show      showInstance      opts typeDecls
              ++ genInstances Read      readInstance      opts typeDecls
    functions = map (transFunc opts typeMapping) funcs

    mainModule = mainMod aux funcName opts
 
    -- information about original module 
bbr's avatar
bbr committed
261
262
    (typeSyns,typeDecls) = partition isTypeSyn $ 
                           filter (\t->  not (elem (snd $ typeName t) (extData opts))) types
bbr's avatar
bbr committed
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
    isToTransform t = case lookup (snd $ typeName t) (extInsts opts) of
      Nothing -> True
      Just is -> not (elem Declaration is)


--------------------------------------------------------
-- adding main function for executables
--------------------------------------------------------

generateAuxNames fs = (genNewName "aux1" fns,genNewName "aux2" fns)
  where 
    fns = map (snd . funcName) fs

    genNewName s ts = if elem s ts then genNewName ('a':s) ts else s
    

mainMod (_,aux2) m opts = let aux = (m,snd (funName ("",aux2))) in
280
  C.Prog "Main" [curryModule,modName "Prelude",m]
bbr's avatar
bbr committed
281
282
283
284
285
     [] [] [] 
     [C.Func (m,"main") public untyped 
        (Just  [C.Rule [] 
          (noguard $ fapp (hasPresym ">>") 
                       [app (setProg opts) (C.String (mainModule opts)),
bbr's avatar
bbr committed
286
                        app (C.Symbol (modName "Prelude","curryIOVoid"))
bbr's avatar
bbr committed
287
288
289
290
291
292
293
294
295
296
                            (sym aux)]) []])]
     []
  where
    setProg Opts{cm=OrBased} = cusym "setProgNameAndOrBased"
    setProg _                = cusym "setProgName"

addExec (aux1,aux2) opts (Prog m is ts funcs ops) = 
  case lookup (mainFunc opts) lfs of
    Just f@(Func n a vis t (Rule vs e)) 
     | t == ioT unitT -> prog False
bbr's avatar
bbr committed
297
       [Func a2 0 vis t (Rule [] (flatApp n []))]
bbr's avatar
bbr committed
298
     | isIOType t -> prog True
bbr's avatar
bbr committed
299
       [Func a1 0 vis (monomorph t) (Rule [] (flatApp n [])),
bbr's avatar
bbr committed
300
        Func a2 0 vis (ioT unitT) (Rule [] (flatApp printIO [calla1 t True]))]
bbr's avatar
bbr committed
301
     |  isFuncType t && not (debug opts) -- && not (isFuncType (range t)))
bbr's avatar
bbr committed
302
          -> Right (mainFunc opts++" is no constant")
bbr's avatar
bbr committed
303
     | debug opts -> prog False
bbr's avatar
bbr committed
304
305
       [Func a1 1 vis (monomorph t) (Rule [0] (flatApp n [Var 0])),
        Func a2 0 vis (ioT unitT) (Rule [] 
bbr's avatar
bbr committed
306
307
308
          (calla1 t (isFuncType (range t) && 
                     isFuncType (range (range t)) && 
                     isIOType (range (range (range t))))))]
bbr's avatar
bbr committed
309
     | otherwise -> prog True
bbr's avatar
bbr committed
310
311
       [Func a1 0 vis (monomorph t) (Rule [] (flatApp n [])),
        Func a2 0 vis (ioT unitT) (Rule [] 
bbr's avatar
bbr committed
312
          (flatBind (flatGst (calla1 t True)) (startFunc opts)))]
bbr's avatar
bbr committed
313
314
315
316
    _ -> Right (mainFunc opts++" undefined")
  where
    a1 = (m,aux1)
    a2 = (m,aux2)
bbr's avatar
bbr committed
317
318
319
320
    calla1 t orc = if debug opts 
                   then Comb FuncCall ("Oracle","oracle"++if orc then "IO" else "") 
                             [Comb (FuncPartCall 1) a1 []]
                   else Comb FuncCall a1 []
bbr's avatar
bbr committed
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
    printIO = ("Interactive","printIO")
    lfs = zip (map (snd . funcName) funcs) funcs
  
    startFunc Opts{pm=Interactive DF} = ask ... df 
    startFunc Opts{pm=Interactive BF} = ask ... bf 
    startFunc Opts{pm=All DF}         = pr  ... df
    startFunc Opts{pm=All BF}         = pr  ... bf 
    startFunc Opts{pm=First DF}       = ap_ pr $ hd ... df
    startFunc Opts{pm=First BF}       = ap_ pr $ hd ... bf
    startFunc Opts{pm=ST}             = Comb (FuncPartCall 1) pr []
  
    monomorph (TVar _) = unitT
    monomorph (TCons n args) = TCons n (map monomorph args)
    monomorph (FuncType t1 t2) = FuncType (monomorph t1) (monomorph t2)

    prog addInt fs =  Left (Prog m (if addInt then "Interactive":is else is)
                                 ts (fs++funcs) ops)

ask = ("Interactive","interactiveSols")
df  = ("Prelude","allValuesD")
bf  = ("Prelude","allValuesB")
pr  = ("Interactive","printTerm")
hd  = ("Prelude","head")
344
f ... g = Comb FuncCall  (addPre ".") 
bbr's avatar
bbr committed
345
            [Comb (FuncPartCall 1) f [],Comb (FuncPartCall 1) g []]
346
ap_ f e = Comb FuncCall  (addPre ".") [Comb (FuncPartCall 1) f [],e]
bbr's avatar
bbr committed
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

------------------------------------------------------
-- transformation of type declarations
------------------------------------------------------

-- each type declaration has to derive instances for Show and Read
-- moreover, new constructors for logical variables, ors and fails 
-- have to be added.

transTypeDecl :: Options -> TypeDecl -> C.TypeDecl
transTypeDecl opts (Type name vis vars consdecls) 
  = C.Type (consName opts name) (transvis vis) (map (varName "t") vars) 
           (map (transConsdecls opts) consdecls ++
            newConsDecls (consName opts name) vars)
           []
transTypeDecl opts (TypeSyn name vis vars t) 
  = C.TypeSyn (consName opts name) (transvis vis) (map (varName "t") vars) 
              (transTypeExpr opts t)

transConsdecls :: Options -> ConsDecl -> C.ConsDecl
transConsdecls opts (Cons name arity vis ts) 
  = C.Cons (consName opts name) arity (transvis vis) False 
           (map (transTypeExprF opts) ts)

transTypeExpr, transTypeExprF :: Options -> TypeExpr -> C.TypeExpr
transTypeExpr _ (TVar n) = toTVar n
transTypeExpr opts (FuncType t1 t2) = 
  C.FuncType (transTypeExprF opts t1) (transTypeExpr opts t2)
transTypeExpr opts (TCons name ts) 
  = C.TCons (consName opts name) (map (transTypeExprF opts) ts)

transTypeExprF _ (TVar n) = toTVar n
transTypeExprF opts (FuncType t1 t2) = 
      C.TCons (consName opts{extCons=True} (addPre "Prim"))
        [addStateType (C.FuncType (transTypeExprF opts t1) (transTypeExprF opts t2))]
transTypeExprF opts (TCons name ts) 
 = C.TCons (consName opts name) (map (transTypeExprF opts) ts)

newConsDecls (m,n) vs 
bbr's avatar
bbr committed
386
  = [C.Cons (m,n++"Fail") 0 private  False [tExceptions],
bbr's avatar
bbr committed
387
     C.Cons (m,n++"Or") 2 private False 
bbr's avatar
bbr committed
388
        [tOrRef, tBranches newT]] 
bbr's avatar
bbr committed
389
390
391
392
393
394
395
396
397
398
399
400
401
402
  where
    newT = C.TCons (m,n) (map toTVar vs)


-------------------------------------------
-- generating instances
-------------------------------------------

inst newModName name vars classname =  
  C.Instance (map (\v -> C.TypeClass (cu classname) [toTVar v]) vars) 
             (C.TypeClass (cu classname) 
                          [C.TCons (newModName,name) (map toTVar vars)])


bbr's avatar
bbr committed
403
curryInstance opts t@(Type origName vis vars consdecls) 
404
  = inst newModName name vars curryClass 
bbr's avatar
bbr committed
405
         [strEq,eq,propagate,foldCurry,typeName,showFunction True opts t] --toTerm,fromTerm
bbr's avatar
bbr committed
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
  where
    (newModName,name) = consName opts origName 

    origMod = fst origName
  
    isPrelude = origMod=="Prelude"

    strEq = C.Func (newModName,"strEq") (transvis vis) untyped 
                  (Just  
                    (map strEqRule consdecls++
                    [C.Rule [_x,toPVar 0,_x]
                           (noguard $ 
                              fapp (extInstPresym isPrelude "strEqFail")
                                   [fapp (extInstPresym isPrelude "typeName") [toVar 0]]) []]))

    strEqRule (Cons cname arity _ _) =
      rule  [C.PComb (consName opts cname) (map toPVar [1..arity]),
             C.PComb (consName opts cname) (map (toPVar' "y") [1..arity])]
            (noguard $ if arity==0 then (extInstPresym isPrelude "strEqSuccess")
425
426
                         else foldr1 (\ e es -> fapp (extInstPresym isPrelude "concAnd") 
                                                     (addStateArg [e,es]))
bbr's avatar
bbr committed
427
428
                                 (map sEq [1..arity])) []
       where
bbr's avatar
bbr committed
429
         sEq i = fapp (extInstPresym isPrelude "genStrEq") (addStateArg [toVar i,toVar' "y" i])
bbr's avatar
bbr committed
430
431
432
433

    eq = C.Func (newModName,"eq") (transvis vis) untyped 
               (Just  
                       (map eqRule consdecls
434
                         ++otherwiseExp 3 (concupresym opts "False")))
bbr's avatar
bbr committed
435
436
437
438

    eqRule (Cons cname arity _ _) =
      rule  [C.PComb (consName opts cname) (map toPVar [1..arity]),
             C.PComb (consName opts cname) (map (toPVar' "y") [1..arity])]
439
440
             (noguard $ if arity==0 then concupresym opts "True"
                         else foldr1 (\ e es -> fapp (funcupresym "&&") (addStateArg [e,es]))
bbr's avatar
bbr committed
441
442
                                (map eqArgs [1..arity])) []
       where
bbr's avatar
bbr committed
443
         eqArgs i = fapp (extInstPresym isPrelude "genEq") (addStateArg [toVar i,toVar' "y" i])
bbr's avatar
bbr committed
444
445
446
447
448
449

    propagate = C.Func (newModName,"propagate") (transvis vis) untyped 
                       (Just  (map propRule consdecls))
                       

    propRule (Cons cname arity _ _) =
450
451
      C.Rule (addStatePat [C.PVar "f",C.PComb (consName opts cname) 
                                              (map toPVar [1..arity])])
bbr's avatar
bbr committed
452
             (noguard $ fapp (sym (consName opts cname))
453
                             (map propCall [1 .. arity])) []
bbr's avatar
bbr committed
454
      where propCall i = fapp (C.Var "f") (addStateArg [toHInt (i-1),toVar i])
bbr's avatar
bbr committed
455
456
457
458
459

    foldCurry = C.Func (newModName,"foldCurry") (transvis vis) untyped 
                       (Just  (map foldRule consdecls))
                       
    foldRule (Cons cname arity _ _) =
460
461
      C.Rule (addStatePat [C.PVar "f",C.PVar "c",C.PComb (consName opts cname) 
                                                         (map toPVar [1..arity])])
bbr's avatar
bbr committed
462
463
464
             (noguard $ foldr appFold (C.Var "c") (map toVar [1 .. arity])) []
       where
         appFold v e = fapp (C.Var "f") (addStateArg [v,e])
bbr's avatar
bbr committed
465
466
467
468
469
470
471
472
473
474

    typeName =  C.Func (newModName,"typeName") (transvis vis) untyped 
                  (Just  [C.Rule [_x] 
                                 (noguard $ C.String (snd origName)) []])

    toTerm = C.Func (newModName,"toC_Term") (transvis vis) untyped 
                  (Just  
                    (map toTermRule (zip [1..] consdecls) ++
                    [C.Rule [_x,_x,
                             C.PComb (newModName,name++"FreeVar") [C.PVar "r"]] 
475
476
                            (noguard $ app (cupresym "C_Free") 
                                        (app c_int
bbr's avatar
bbr committed
477
478
479
480
481
482
                                          (app (hasPresym "toInteger")
                                               (C.Var "r")))) []]))

    toTermRule (nr,(Cons cname arity _ _)) =
      C.Rule [C.PVar "mode",C.PVar "store",
              C.PComb (consName opts cname) (map toPVar [1..arity])]             
483
             (noguard $ fapp (cupresym "C_Data") 
bbr's avatar
bbr committed
484
                             [toInt nr,c_string_ origMod (snd cname),
485
                              dList isPrelude (map su [1..arity])]) []
bbr's avatar
bbr committed
486
       where
487
488
         su i = fapp (cusym "ctcStore") 
                     [C.Var "mode",app (cusym "toC_Term") (C.Var "mode"),
bbr's avatar
bbr committed
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
                      C.Var "store",toVar i]

    fromTerm = C.Func (newModName,"fromC_Term") (transvis vis) untyped 
                  (Just  
                    (concatMap fromTermRule (zip [1..] consdecls) ++
                    [C.Rule [C.PComb (baseType isPrelude "C_Free") 
                               [C.PComb (baseType isPrelude "C_Int") 
                                    [C.PVar "r"]]] 
                            (noguard $ app (sym (newModName,name++"FreeVar"))
                                           (app (hasPresym "fromInteger")
                                               (C.Var "r"))) []]))

    fromTermRule (nr,(Cons cname arity _ _)) =
      [rule "C_Data"     [pnr,_x,pts],
       rule "C_Data"     [pfree,pname,pts]]
       where
         pnr = toPInt opts nr
         pfree = C.PComb (baseType isPrelude "C_IntFreeVar") [_x]
         pname = dpList isPrelude (map (toPChar opts) (snd cname))
         pts = dpList isPrelude (map toPVar [1..arity])
509
         e = noguard $ fapp (sym (consName opts cname)) 
510
                            (map (app (cusym "fromC_Term") . toVar) [1..arity])
bbr's avatar
bbr committed
511
512
513
514
515
516
         rule c args = C.Rule [C.PComb (baseType isPrelude c) args] e []


baseCurryInstance opts (Type origName vis vars consdecls) 
  = inst newModName name vars "BaseCurry" 
       [nf False, nf True, 
bbr's avatar
bbr committed
517
      	free "generator" "generator",failed,branching,
bbr's avatar
bbr committed
518
      	consKind,
bbr's avatar
bbr committed
519
      	exceptions,orRef,branches]
bbr's avatar
bbr committed
520
521
522
523
524
525
526
527
528
529
  where
    (newModName,name) = consName opts origName 

    origMod = fst origName
  
    isPrelude = origMod=="Prelude"

    nf gr = C.Func (newModName,if gr then "gnf" else "nf") (transvis vis) untyped 
                  (Just  
            (concatMap (nfrule gr) (filter ((1<=) . consArity) consdecls) ++
bbr's avatar
bbr committed
530
531
             [C.Rule (addStatePat [C.PVar "f",C.PVar "x"])
                     (noguard (fapp (C.Var "f") (addStateArg [C.Var "x"]))) []]))
bbr's avatar
bbr committed
532
533

    nfrule gr (Cons cname arity _ _)
bbr's avatar
bbr committed
534
535
536
      =  [C.Rule [C.PVar "f",
                  C.PComb (consName opts cname) (map toPVar [1..arity]),
                  C.PVar "state0"]
bbr's avatar
bbr committed
537
538
                 (noguard $ foldr (nflambda gr)
                             (fapp (C.Var "f") 
bbr's avatar
bbr committed
539
540
541
                                [fapp (sym $ consName opts cname) 
                                        (map (toVar' "v") [1..arity]),
                                 toVar' "state" arity])
bbr's avatar
bbr committed
542
543
544
                             [1..arity]) []]

    nflambda gr i e = 
545
      fapp (cusym (if gr then "gnfCTC" else "nfCTC")) 
bbr's avatar
bbr committed
546
        [C.Lambda [toPVar' "v" i,toPVar' "state" i] e,toVar i,toVar' "state" (i-1)]
bbr's avatar
bbr committed
547
548

    free s t = C.Func (newModName,s) (transvis vis) untyped 
bbr's avatar
bbr committed
549
            (Just [C.Rule [C.PVar "i"] (noguard $ 
550
             fapp (cusym "withRef") [
bbr's avatar
bbr committed
551
552
             C.Lambda [C.PVar "r"] $
             fapp (sym (orName opts origName)) 
553
             [fapp (cusym "mkRef") [C.Var "r",maxAr,C.Var "i"],
bbr's avatar
bbr committed
554
555
              list_ (map freeCons consdecls)],
             maxAr]) []])
bbr's avatar
bbr committed
556
      where
bbr's avatar
bbr committed
557
        maxAr = C.Var (show (foldr max 0 (map consArity consdecls)))
bbr's avatar
bbr committed
558
559
        freeCons (Cons cname arity _ _) = 
          fapp (sym (consName opts cname)) 
560
               (snd $ foldr addOne (0,[]) (replicate arity (app (cusym t))))
bbr's avatar
bbr committed
561
562
        addOne e (n,es) = 
          (n+1,e (fapp (hasPresym "+") [C.Var "r",toHInt n]):es)
bbr's avatar
bbr committed
563
564
565
566
567
568
569
570
571
 
    failed = constructor "failed" failName 
    freeVarFunc = constructor "freeVar" freeVarName 
    branching = constructor "branching" orName 
    suspend = constructor "suspend" suspName 


    consKind = C.Func (newModName,"consKind") (transvis vis) untyped 
                  (Just  
bbr's avatar
bbr committed
572
573
                    (map tester [(orName, 2, "Branching"),
                                 (failName, 1, "Failed")] ++
bbr's avatar
bbr committed
574
                    [C.Rule [_x]
575
                           (noguard $ (cusym "Val")) []]))
bbr's avatar
bbr committed
576
577
578

    tester (namer,arity,nameTest)  = 
       C.Rule [C.PComb (namer opts origName) (take arity (repeat (_x)))]
579
              (noguard (cusym nameTest)) []
bbr's avatar
bbr committed
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

    selector nameSel namer arity number =
       C.Func (newModName,nameSel) (transvis vis) untyped 
         (Just [C.Rule [C.PComb (namer opts origName) 
                          (underscores (number-1)++[C.PVar "x"]++
                           underscores (arity-number))]
                       (noguard (C.Var "x")) []])

    constructor nameConstr namer = 
      C.Func (newModName,nameConstr) (transvis vis) untyped 
         (Just  [C.Rule []
                  (noguard $ sym (namer opts origName)) []])

    exceptions = selector "exceptions" failName 1 1
    freeVarRef = selector "freeVarRef" freeVarName 1 1
                     
    orRef    = selector "orRef" orName 2 1
    branches = selector "branches" orName 2 2

    suspRef  = selector "suspRef" suspName 2 1
    suspCont = selector "suspCont" suspName 2 2


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


   
------------------------------------------------------
-- transformation of functions and expressions
------------------------------------------------------

transFunc :: Options -> (QName -> QName) -> FuncDecl -> C.FuncDecl
transFunc opts typeMapping (Func fname arity vis t (Rule lhs rhs))
  = C.Func newFName (transvis vis) 
           (transFType opts arity t) crules
    where
      newFName = funName fname
      f = (modName (fst fname),auxName newFName) 
      trhs = transExpr opts rhs

      crules = case rhs of
        Case ct (Var n) bs -> Just (transBranching ct (break (==n) lhs) 
                                                   opts f typeMapping fname bs)
        Case ct _       bs -> error "case not normalized"
        _                  -> Just [rule (map toPVar lhs) (noguard trhs) []]

      auxName (_,name) = 
        if isInfixOpName name 
          then elimInfix name
          else name

transFunc opts _ (Func (m,fname) arity vis t (External _)) = 
 C.Func (funName (m,fname)) (transvis vis) (transFType opts arity t)
     (Just  [rule (map toPVar [1..arity])  
635
                 (noguard (fapp (C.Symbol (modName m,fname)) 
bbr's avatar
bbr committed
636
                                (addStateArg (map toVar [1..arity])))) []])
bbr's avatar
bbr committed
637
638
639
640
641
642
643
644


transFType :: Options -> Int -> TypeExpr -> Maybe C.TypeExpr
-- the first line is for transformations too lazy to compute correct type
transFType _ _ (TVar (-42)) = Nothing 
transFType opts arity t = Just $
  C.TConstr 
    [C.TypeClass c [toTVar tv] | tv <- nub (allVarsInTypeExpr t),
645
                                  c <- [(curryModule,"Curry")]]
bbr's avatar
bbr committed
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
    (addStateType (transFTypeExpr opts arity t))

transFTypeExpr opts 0 t = transTypeExprF opts t
transFTypeExpr opts (n+1) (FuncType t1 t2)
  = C.FuncType (transTypeExprF opts t1) (transFTypeExpr opts n t2)

transvis x | x==Private = C.Private
           | x==Public  = C.Public

transExpr :: Options -> Expr -> C.Expr
transExpr opts (Var n) = toVar n
transExpr opts (Lit l) = transLit opts l
transExpr opts (Free [] e) = transExpr opts e
transExpr opts (Free (v:vs) e) 
  = app freeCall (C.Lambda [toPVar v] (transExpr opts (Free vs e)))
transExpr opts (Or e1 e2) = fapp orSym (map (transExpr opts) [e1, e2])
transExpr opts (Let vbs e) = 
  C.LetDecl (map locdecl vbs) (transExpr opts e)
  where
    locdecl (v,b) = C.LocalPat (toPVar v) (transExpr opts b) []
bbr's avatar
bbr committed
666
667
668
transExpr opts (Comb FuncCall fn@("Global","global") args) =
  C.LetDecl [C.LocalPat (C.PVar "st") (hasPresym "Nothing") []] 
            (fapp (C.Symbol (funName fn)) (map (transExpr opts) args))
bbr's avatar
bbr committed
669
670
671
672
673
674
675
transExpr opts (Comb combType fname args) 
  = newExpr
  where
    newArgs = map (transExpr opts) args

    call = case combType of 
              ConsCall       -> symApp (consName opts fname) newArgs
bbr's avatar
bbr committed
676
              FuncCall       -> symApp (funName fname)       (addStateArg newArgs)
677
678
              FuncPartCall i -> symApp (funName fname)       newArgs
              ConsPartCall i -> symApp (consName opts fname) newArgs 
bbr's avatar
bbr committed
679
680
681
682
683
684

    symApp s xs = fapp (C.Symbol s) xs

    newExpr = case combType of 
                ConsCall       -> call
                FuncCall       -> call
685
686
                FuncPartCall i -> pf opts i call
                ConsPartCall i -> pc opts i call
bbr's avatar
bbr committed
687
688
689
690
691
692
transExpr _ (Case _ _ _) = error "unlifted case"


transLit :: Options -> Literal -> C.Expr
transLit opts (Charc c)  = toChar opts c
transLit opts (Floatc f) = toFloat opts f
bbr's avatar
bbr committed
693
transLit opts (Intc i)   = toInt i
bbr's avatar
bbr committed
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709


transBranching :: CaseType -> ([VarIndex],[VarIndex]) -> Options -> QName -> 
  (QName -> QName) -> QName -> [BranchExpr] -> [C.Rule]
transBranching caseMode vs@(as,v:bs) opts f tm oName branches
  = oldRules++newRules
  where
    oldRules = map (transRule vs opts) branches
    typeName = case (\ (Branch p _) -> p) (head branches) of
      Pattern c _ -> tm c
      LPattern l  -> ("Prelude",case l of {Intc _->"Int";Charc _->"Char"})

    freePat = C.AsPat "x" (C.PComb (freeVarName opts typeName) [C.PVar "ref"])
    orPat   = C.PComb (orName opts typeName) [C.PVar "i",C.PVar "xs"]
    suspPat = C.PComb (suspName opts typeName) [C.PVar "ref",C.PVar "susp"]

bbr's avatar
bbr committed
710
    isOracleMod = debug opts && take 11 (fst f)=="CurryOracle" && length (fst f) > 11
bbr's avatar
bbr committed
711

712
713
    refVar = 1 --if null (as++bs) then error $ "where is the ref?" ++ show f
               --               else last (as++bs)
714
    applyf b = C.Lambda (addStatePat (if b then [toPVar refVar,C.PVar "x"]
bbr's avatar
bbr committed
715
716
717
718
                                           else [C.PVar "x"]))
                      (fapp (sym f) 
                            (addStateArg (map toVar as ++ 
                                          C.Var "x" : map toVar bs)))
bbr's avatar
bbr committed
719
720
721

    newLhs p e = rule (map toPVar as ++ (p:map toPVar bs)) e []
    newRules = 
bbr's avatar
bbr committed
722
           [newLhs orPat
bbr's avatar
bbr committed
723
             (noguard ((if isOracleMod
bbr's avatar
bbr committed
724
                        then fapp (sym (funName ("CEventOracle","onBranches"))) .
725
                             (toVar refVar :)
bbr's avatar
bbr committed
726
                        else fapp (cusym "mapOr"))
bbr's avatar
bbr committed
727
                       (addStateArg [applyf isOracleMod,
bbr's avatar
bbr committed
728
                                     C.Var "i",C.Var "xs"])))
bbr's avatar
bbr committed
729
           ,newLhs (C.PVar "x")
bbr's avatar
bbr committed
730
731
732
                   (noguard $ (if isOracleMod then closeRef refVar else id)
                            $ fapp (cusym "patternFail") 
                                  [qname_ oName,C.Var "x"])]
bbr's avatar
bbr committed
733
734


bbr's avatar
bbr committed
735
736
737
    closeRef i e = fapp (sym $ funName ("CEventOracle","closeRef")) $
                        addStateArg [toVar i,e]

bbr's avatar
bbr committed
738
739
740
741
742
transRule :: ([VarIndex],[VarIndex]) -> Options -> BranchExpr -> C.Rule 
transRule (as,v:bs) opts (Branch (LPattern l@(Charc _)) e) 
  = rule ps (C.GuardedExpr [(guard,transExpr opts e)]) []
  where
    guard = app (extInstPresym False "isC_True")
743
                (fapp (funcupresym "===") [toVar v,toLit opts l])
bbr's avatar
bbr committed
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
    ps    = map toPVar as ++ toPVar v : map toPVar bs
transRule (as,v:bs) opts (Branch (LPattern l) e) 
  = rule ps (noguard (transExpr opts e)) []
  where
    ps  = map toPVar as ++ C.AsPat (xvar v) (toPLit opts l) : map toPVar bs
transRule (as,v:bs) opts (Branch (Pattern name args) e) 
  = rule ps (noguard (transExpr opts e)) []
  where
    ps = map toPVar as ++ (if elem v args then id else C.AsPat (xvar v)) 
                          (C.PComb (consName opts name) (map toPVar args)) 
                        : map toPVar bs


rule ps = C.Rule (addStatePat ps)

transOp (Op name InfixOp p)  = C.Op (funName name) C.InfixOp  p
transOp (Op name InfixlOp p) = C.Op (funName name) C.InfixlOp p
transOp (Op name InfixrOp p) = C.Op (funName name) C.InfixrOp p


----------------------------------------------------------------
-- generating instances for read and show
----------------------------------------------------------------

genInstances _ _ _ [] = []
genInstances cl genFunc opts (t:ts) 
  | maybe False (elem cl) (lookup (snd $ typeName t) (extInsts opts)) 
  = genInstances cl genFunc opts ts
  | otherwise = genFunc opts{consUse=InstanceDef} t : 
                genInstances cl genFunc opts ts

bbr's avatar
bbr committed
775
showInstance opts t@(Type origName vis vars consdecls) =
776
777
 C.Instance (map (\v -> C.TypeClass (addPre "Show") [toTVar v]) vars)
   (C.TypeClass (addPre "Show") [C.TCons (newModName,name) (map toTVar vars)])
bbr's avatar
bbr committed
778
   [showFunction False opts t]
bbr's avatar
bbr committed
779
780
781
782
 where
   (newModName,name) = consName opts origName


bbr's avatar
bbr committed
783
784
785
786

showFunction showQ opts t@(Type origName vis vars consdecls) 
  | maybe False (elem Show) (lookup (snd $ typeName t) (extInsts opts)) 
  = showsPrec [C.Rule [] (C.SimpleExpr (hasPresym "showsPrec")) []]
bbr's avatar
bbr committed
787
  | otherwise = showsPrec (map showsPrecRule consdecls
bbr's avatar
bbr committed
788
              ++[showGenerator])
bbr's avatar
bbr committed
789
 where
bbr's avatar
bbr committed
790
791
   showParenArg (_,'(':_) = hasPresym "True"
   showParenArg _         = if showQ then hasPresym "True" else lt (C.Var "d") app_prec
bbr's avatar
bbr committed
792
793
794
   showsPrecName = if showQ then "showQ" else "showsPrec"
   showsPrecSym  = (if showQ then extInstPresym (fst origName=="Prelude") 
                             else hasPresym) showsPrecName
bbr's avatar
bbr committed
795
796
797
798
799
800
801
802
803

   identifier (_,"()") = "()"
   identifier (cm,cn)  = if showQ then cm++"."++cn else cn

   opening (_,'(':_) = ""
   opening cmn       = identifier cmn ++ " "

   separator (_,'(':_) = ','
   separator _         = ' '
bbr's avatar
bbr committed
804
805
806
807
808
809
810
811

   showsPrec rs = C.Func (newModName,showsPrecName) 
                         (transvis vis) untyped 
                         (Just rs)

   (newModName,name) = consName opts origName

   showsPrecRule (Cons cname 0 _ []) = 
bbr's avatar
bbr committed
812
813
      C.Rule [_x, C.PComb (consName opts cname) []]
         (C.SimpleExpr 
bbr's avatar
bbr committed
814
815
            (app (hasPresym "showString") (string_ (identifier cname)))) []
   showsPrecRule (Cons cname arity _ args) = 
bbr's avatar
bbr committed
816
817
     C.Rule [C.PVar "d", C.PComb (consName opts cname) (map toPVar [1..arity])]
            (C.SimpleExpr (fapp (hasPresym "showParen") 
bbr's avatar
bbr committed
818
                             [showParenArg cname,sym ("","showStr")]))
bbr's avatar
bbr committed
819
820
821
            [C.LocalFunc (C.Func ("","showStr") (transvis vis) untyped 
                  (Just [C.Rule [] (C.SimpleExpr showStr) []]))]
      where
bbr's avatar
bbr committed
822
        showStr = points (app (hasPresym "showString") (string_ (opening cname)):
bbr's avatar
bbr committed
823
                          intersperse 
bbr's avatar
bbr committed
824
                            (app (hasPresym "showChar") (char_ (separator cname)))
bbr's avatar
bbr committed
825
                            (map callShowsPrec [1..arity]))
bbr's avatar
bbr committed
826
                             
bbr's avatar
bbr committed
827

bbr's avatar
bbr committed
828
        callShowsPrec i = fapp showsPrecSym [add_prec cname,toVar i]
bbr's avatar
bbr committed
829
830
831
832
833
834

        points = foldr1 point 

        point x y = fapp (hasPresym ".") [x,y]


bbr's avatar
bbr committed
835
   showTuple = C.Func (newModName,showsPrecName) (transvis vis) untyped 
bbr's avatar
bbr committed
836
                  (Just (map showTupleRule consdecls++[showGenerator]))
bbr's avatar
bbr committed
837
838

   showTupleRule (Cons cname arity _ args) = 
bbr's avatar
bbr committed
839
     C.Rule [C.PVar "d", C.PComb (consName opts cname) (map toPVar [1..arity])]
bbr's avatar
bbr committed
840
841
842
843
844
            (C.SimpleExpr (app (hasPresym "showString") 
                             (app (hasPresym "show") 
                               (fapp (sym ("",snd cname)) 
                                    (map toVar [1..arity]))))) []

bbr's avatar
bbr committed
845
846
847
848
849
850
851
852
853
   showGenerator = C.Rule [_x, 
                         C.PComb (newModName,name++"Or") [C.PVar "r",_x]]
                   (C.SimpleExpr 
                       (app (hasPresym "showString") 
                            (cons_ (char_ '_') 
                                   (app (hasPresym "show") 
                                        (app (cusym "deref")
                                             (C.Var "r")))))) []

854
readInstance :: Config.Options -> TypeDecl -> C.InstanceDecl
bbr's avatar
bbr committed
855
readInstance opts (Type origName@(modName,name) vis vars consdecls) =
856
857
 C.Instance (map (\v -> C.TypeClass (addPre "Read") [toTVar v]) vars)
   (C.TypeClass (addPre "Read") [C.TCons (newModName,newName) (map toTVar vars)])
bbr's avatar
bbr committed
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
   [if isTuple (snd origName) then readTuple else readsPrec]
 where
   c@(newModName,newName) = consName opts origName

   readsPrec = C.Func (newModName,"readsPrec") (transvis vis) untyped 
                  (Just [C.Rule [C.PVar "d",C.PVar "r"] 
                          (C.SimpleExpr (plusplus (map read consdecls))) []])

   plusplus = foldr1 (\x y->fapp (hasPresym "++") [x,y])

   read cons@(Cons _ 0 _ []) = 
     fapp (hasPresym "readParen") [hasPresym "False",lamb cons,C.Var "r"]
   read cons = 
     fapp (hasPresym "readParen") [lt (C.Var "d") app_prec,lamb cons,C.Var "r"]

873
   lamb (Cons cn@(cmodName,cname) arity _ args) = C.Lambda [C.PVar "r"] 
bbr's avatar
bbr committed
874
875
876
877
     (C.ListComp (fapp (sym ("","(,)")) 
                     [fapp (sym newC) 
                           (map toVar [1..arity]),
                      toVar' "r" arity ])
878
879
        (C.SPat (pair (C.PVar "_") (toPVar' "r" 0)) 
              (fapp (cusym "readQualified") [string_ cmodName,string_ cname,C.Var "r"]):
bbr's avatar
bbr committed
880
881
882
883
884
885
886
         map readArg [1..arity]))

     where
       newC@(newMod,newCName) = consName opts cn
    
   readArg i = C.SPat (pair  (toPVar' "x" i) (toPVar' "r" i))
                      (fapp (hasPresym "readsPrec") 
bbr's avatar
bbr committed
887
                           [add_prec ("",""),
bbr's avatar
bbr committed
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
                            toVar' "r" (i-1)])

   readTuple = C.Func (newModName,"readsPrec") (transvis vis) untyped 
                  (Just (map readTupleRule consdecls))

   readTupleRule (Cons t@(_,tup) arity _ args) =
     C.Rule [C.PVar "d",C.PVar "r"] 
       (C.SimpleExpr 
          (fapp (hasPresym "map") [sym ("","readTup"),
                                   fapp (hasPresym "readsPrec") 
                                        [C.Var "d",C.Var "r"]])) 
       [C.LocalFunc (C.Func ("","readTup") (transvis vis) untyped 
          (Just [C.Rule [pair (C.PComb ("",tup) (map toPVar [1..arity])) 
                              (C.PVar "s")] 
                   (C.SimpleExpr   
                      (fapp (sym ("","(,)"))
                         [fapp (sym (consName opts t)) (map toVar [1..arity]),
                          C.Var "s"])) []]))]
        
   pair x y = C.PComb ("","(,)") [x,y]


bbr's avatar
bbr committed
910
911
912
add_prec (_,'(':_) = cusym "zero"
add_prec _         = cusym "eleven"

bbr's avatar
bbr committed
913
914
915
916
917
918
919
920
921
922
923
924
app_prec = cusym "ten"

lt x y = fapp (hasPresym ">") [x,y]

int i = app (hasPresym "fromInteger") (C.Lit (C.Intc i))


--------------------------
-- naming conventions
--------------------------

consName,freeVarName,failName,orName,suspName :: Options -> QName -> QName
Bernd Brassel's avatar
Bernd Brassel committed
925
consName opts (m,n) = (modName m,cn)
bbr's avatar
bbr committed
926
927
928
929
930
931
932
933
934
  where
    cn | extCons opts = n
       | otherwise    = constructorName n
    
freeVarName opts = N.freeVarName . consName opts
failName    opts = N.failName    . consName opts
orName      opts = N.orName      . consName opts
suspName    opts = N.suspName    . consName opts

935
curryName s = (curryModule,s)
bbr's avatar
bbr committed
936
937
938
curryTCons = C.TCons . curryName

----------------------------------------
bbr's avatar
bbr committed
939
-- treating the additional state argument
bbr's avatar
bbr committed
940
941
942
943
944
945
----------------------------------------

stateTypeName :: String
stateTypeName = "State"

addStateType :: C.TypeExpr -> C.TypeExpr
bbr's avatar
bbr committed
946
947
948
addStateType t@(C.TVar _) = C.FuncType (curryTCons stateTypeName []) t
addStateType t@(C.TCons _ _) = C.FuncType (curryTCons stateTypeName []) t
addStateType (C.FuncType t1 t2) = C.FuncType t1 (addStateType t2)
bbr's avatar
bbr committed
949
950

addStatePat :: [C.Pattern] -> [C.Pattern]
bbr's avatar
bbr committed
951
952
953
954
addStatePat = (++[C.PVar "st"])

addStateArg :: [C.Expr] -> [C.Expr]
addStateArg = (++[C.Var "st"])
bbr's avatar
bbr committed
955

bbr's avatar
bbr committed
956
957
958
959
960
961
962
963
964
965
966
-- global definitions must not have a state argument
addGlobalDefs :: Options -> [FuncDecl] -> [(String,Bool,C.Prog)] -> [(String,Bool,C.Prog)]
addGlobalDefs opts gs (x:xs@(_:_)) = x : addGlobalDefs opts gs xs
addGlobalDefs opts gs [(s,b,prog)] = [(s,b,prog{C.funcDecls=gs'++C.funcDecls prog})]
  where 
    gs' = map transformGlobal gs
    transformGlobal (Func n 0 vis t (Rule [] e)) = 
      C.Func (funName n) (transvis vis) (transFType opts 0 t) 
        (Just [C.Rule [] 
                 (C.SimpleExpr (transExpr opts e)) []])

bbr's avatar
bbr committed
967
968
969
970
----------------------------------------------------------------
-- constants and abbreviations for flat, resp. abstract curry
----------------------------------------------------------------

971
972
973
974
975
976
977
978
979
980
-- prelude symbols
sym = C.Symbol 
prelude   = "Prelude"
addPre    = (,) prelude
hasPresym = sym . addPre
cupresym  = sym . (,) (modName prelude)
funcupresym = sym . funName . addPre
concupresym opts = sym . consName opts . addPre

-- symbols from Curry library
981
982
curryModule = "Curry.RunTimeSystem"
curryClass  = "Curry"
983
984
985
cu          = (,) curryModule
cusym       = sym . cu

986
987
988
989
990
991
992
993
994
995
part opts i e = 
  if i<2
   then primValue opts (C.Lambda (addStatePat [toPVar' "v" 1]) e)
   else primValue opts (C.Lambda [toPVar' "v" i, _x] (part opts (i-1) e))

isPrelude :: Options -> Bool
isPrelude opts = currentModule opts=="Prelude" 

-- partial function call, one argument missing
pf :: Options -> Int -> C.Expr -> C.Expr
Bernd Brassel's avatar
Bernd Brassel committed
996
pf opts = app . partial opts (fapp (cupresym "pf"))
997
998
999

-- partial constructor call, one argument missing
pc :: Options -> Int -> C.Expr -> C.Expr
Bernd Brassel's avatar
Bernd Brassel committed
1000
pc opts = app . partial opts (fapp (cupresym "pc"))
1001
1002
1003

-- partial application, more than one argument
pa :: Options -> [C.Expr] -> C.Expr
Bernd Brassel's avatar
Bernd Brassel committed
1004
pa opts = fapp (cupresym "pa")
1005
1006
1007

-- function compostition (.)
cp :: Options -> [C.Expr] -> C.Expr
Bernd Brassel's avatar
Bernd Brassel committed
1008
cp opts = fapp (cupresym "cp")
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021

partial :: Options -> ([C.Expr] -> C.Expr) -> Int -> C.Expr
partial opts part n
  = foldr1 (\f g -> cp opts [f,g])
  . map (\ (k,p) -> dotted opts (k-1) (p [])) 
  $ reverse (zip (reverse [1..n]) (part:repeat (pa opts)))

-- add a lot of dots to compose part call functions
dotted :: Options -> Int -> C.Expr -> C.Expr
dotted opts n p
  | n == 0    = p
  | otherwise = dotted opts (n-1) (cp opts [p])

1022
prelPCons opts s = C.PComb (consName opts (addPre s))
bbr's avatar
bbr committed
1023

1024
1025
1026
pO opts x = prelPCons opts "O"   [x]
pI opts x = prelPCons opts "I"   [x]
pIHi opts = prelPCons opts "IHi" []
bbr's avatar
bbr committed
1027

1028
1029
1030
p0 opts     = prelPCons opts "Zero" []
pPos opts x = prelPCons opts "Pos" [x]
pNeg opts x = prelPCons opts "Neg" [x]
bbr's avatar
bbr committed
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049

public = C.Public

isMain (_,fname) = fname=="main"

isFirst (_,fname) = fname=="first"

cunit opts = sym (consName opts{extCons=True} $ addPre "T0")

-- types

tFreeVarRef t = curryTCons "FreeVarRef" [t]

tOrRef = curryTCons "OrRef" []

tExceptions = curryTCons "C_Exceptions" []

tSuspRef = curryTCons "SuspRef" []

Bernd Brassel's avatar
Bernd Brassel committed
1050
tList a = C.TCons (addPre "[]") [a]
bbr's avatar
bbr committed
1051
1052
c_tList a = curryTCons "List" [a]

Bernd Brassel's avatar
Bernd Brassel committed
1053
tPair a b = C.TCons (addPre "(,)") [a,b]
bbr's avatar
bbr committed
1054

Bernd Brassel's avatar
Bernd Brassel committed
1055
tMaybe a = C.TCons (addPre "Maybe") [a]
bbr's avatar
bbr committed
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078

tBranches x = curryTCons "Branches" [x]

tSusp x = curryTCons "SuspCont" [x]

private = C.Private

untyped = Nothing

noguard e = C.SimpleExpr e

freeCall = cusym "freeF"

orSym = cusym "orF"

app a b = C.Apply a b

app2 a b c = app (app a b) c

fapp x xs = foldl C.Apply x xs

flatApp = Comb FuncCall 

Bernd Brassel's avatar
Bernd Brassel committed
1079
flatBind x y = Comb FuncCall (addPre ">>=") [x,y]
bbr's avatar
bbr committed
1080

Bernd Brassel's avatar
Bernd Brassel committed
1081
flatEq x y = Comb FuncCall (addPre "===") [x,y]
bbr's avatar
bbr committed
1082

Bernd Brassel's avatar
Bernd Brassel committed
1083
flatGst x = Comb FuncCall (addPre "getSearchTree") [x]
bbr's avatar
bbr committed
1084
1085
1086

mid = hasPresym "id"

Bernd Brassel's avatar
Bernd Brassel committed
1087
baseType _ s = addPre s
bbr's avatar
bbr committed
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118

toVar i = C.Var (xvar i)

toVar' s i = C.Var (varName s i)

xvar = varName "x"

varName s i = s++show i

toPVar i = C.PVar (varName "x" i)

toPVar' s i = C.PVar (varName s i)

toTVar i = C.TVar (varName "t" i)

primValue opts v = 
  app (sym $ consName opts{extCons=True} (addPre "PrimValue")) v


toList [] = C.Symbol ("","[]")
toList (x:xs) = app2 (C.Symbol ("",":")) x (toList xs)

toPList [] = C.PComb ("","[]") []
toPList (x:xs) = C.PComb ("",":") [x,toPList xs] 

toPLit opts (Intc i) = toPInt opts i
toPLit opts (Charc c) = toPChar opts c
toPLit opts (Floatc f) = toPFloat opts f

toPInt opts n 
  | n>0  = pPos opts (toPNat opts n)
1119
  | n<0  = pNeg opts (toPNat opts (negate n))
bbr's avatar
bbr committed
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
  | n==0 = p0 opts

toPNat opts n 
  | d==0 = pIHi opts
  | m==1 = pI opts (toPNat opts d)
  | m==0 = pO opts (toPNat opts d)
  where
    d = div n 2
    m = mod n 2

toPChar opts c 
1131
  | currentModule opts=="Prelude" = C.PComb (modName "Prelude","C_Char") [C.PLit (C.Charc c)]
bbr's avatar
bbr committed
1132
1133
1134
1135
1136
1137
  | otherwise = C.PComb (modName "Prelude","C_Char") [C.PLit (C.Charc c)]

toPFloat opts n = primPValue opts (C.PLit (C.Floatc n))

primPValue opts p =  C.PComb (consName opts{extCons=True} (addPre "PrimValue")) [p]

bbr's avatar
bbr committed
1138
toLit opts (Intc i) = toInt i
bbr's avatar
bbr committed
1139
1140
1141
toLit opts (Charc c) = toChar opts c
toLit opts (Floatc f) = toFloat opts f

bbr's avatar
bbr committed
1142
1143
toInt n  = C.Lit (C.Intc (toInteger n))
toHInt n = C.Lit (C.HasIntc (toInteger n))
bbr's avatar
bbr committed
1144

1145
c_int =  cupresym "C_Int"
bbr's avatar
bbr committed
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172

toChar opts c = app (sym (consName opts ("Prelude","Char"))) (C.Lit (C.Charc c))
toFloat opts f = primValue opts (C.Lit (C.Floatc f))



otherwiseExp n e = [C.Rule (map C.PVar (take n (repeat "_")))
                           (noguard e) []]

ioT x = TCons ("Prelude","IO") [x]
unitT = TCons ("Prelude","()") []

hasUnit = sym ("","()")

hasBind x y = fapp (hasPresym ">>=") [x,y]
hasReturn x = app (hasPresym "return") x

char_ c = C.Lit (C.Charc c)

list_ [] = nil 
list_ (x:xs) = cons_ x (list_ xs)

cons_ x xs = fapp (sym ("",":")) [x,xs]
nil = sym ("","[]")

string_ n = list_ (map char_ n)

1173
c_char_ c = fapp (cusym "C_Char") [C.Lit (C.Charc c)]
bbr's avatar
bbr committed
1174
1175
1176
1177

c_list_ [] = c_nil
c_list_ (x:xs) = c_cons_ x (c_list_ xs)

1178
1179
c_cons_ x xs = fapp (cupresym ":<") [x,xs]
c_nil = cupresym "List"
bbr's avatar
bbr committed
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189

bc_list_ [] = bc_nil
bc_list_ (x:xs) = bc_cons_ x (bc_list_ xs)

dList True  = bc_list_
dList False = c_list_

dpList True  = bc_plist_
dpList False = c_plist_

1190
1191
bc_cons_ x xs = fapp (cupresym ":<") [x,xs]
bc_nil = cupresym "List"
bbr's avatar
bbr committed
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206

c_string_ "Prelude" n = bc_list_ (map c_char_ n)
c_string_ _         n =  c_list_ (map c_char_ n)

pchar_ c = C.PLit (C.Charc c)

plist_ [] = pnil 
plist_ (x:xs) = pcons_ x (plist_ xs)

pcons_ x xs = C.PComb ("",":") [x,xs]
pnil = C.PComb ("","[]") []

c_plist_ [] = c_pnil 
c_plist_ (x:xs) = c_pcons_ x (c_plist_ xs)

1207
1208
c_pcons_ x xs = C.PComb (addPre ":<") [x,xs]
c_pnil = C.PComb (addPre "List") []
bbr's avatar
bbr committed
1209
1210
1211
1212

bc_plist_ [] = bc_pnil 
bc_plist_ (x:xs) = bc_pcons_ x (bc_plist_ xs)

1213
1214
bc_pcons_ x xs = C.PComb (addPre ":<") [x,xs]
bc_pnil = C.PComb (addPre "List") []
bbr's avatar
bbr committed
1215
1216
1217
1218
1219
1220
1221
1222


pstring_ n = plist_ (map pchar_ n)

underscores i = replicate i (_x)

qname_ (m,f) = string_ (m++'.':f)

Bernd Brassel's avatar
Bernd Brassel committed
1223
extInstPresym _ s = sym (modName "Prelude",s)
bbr's avatar
bbr committed
1224

Bernd Brassel's avatar
Bernd Brassel committed
1225
extFuncPresym opts s = sym (modName "Prelude",s)
1226
1227


bbr's avatar
bbr committed
1228
1229
1230
1231
_x = C.PVar "_"

st = C.Var "st"