Desugar.hs 36.1 KB
Newer Older
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
{- |
    Module      :  $Header$
    Description :  Desugaring Curry Expressions
    Copyright   :  (c) 2001 - 2004 Wolfgang Lux
                                   Martin Engelke
    License     :  OtherLicense

    Maintainer  :  bjp@informatik.uni-kiel.de
    Stability   :  experimental
    Portability :  portable

   The desugaring pass removes all syntactic sugar from the module. In
   particular, the output of the desugarer will have the following
   properties.

     * All function definitions are eta-expanded.
       Note: Since this version is used as a frontend for PAKCS, the
       eta-expansion had been disabled.

     * No guarded right hand sides occur in equations, pattern
       declarations, and case alternatives. In addition, the declaration
       lists of the right hand sides are empty; local declarations are
       transformed into let expressions.

     * Patterns in equations and case alternatives are composed only of
         - literals,
         - variables,
         - constructor applications, and
         - as patterns.

     * Expressions are composed only of
         - literals,
         - variables,
         - constructors,
         - (binary) applications,
         - let expressions, and
         - case expressions.

39
     * Applications 'N x' in patterns and expressions, where 'N' is a
40
41
42
43
44
45
46
       newtype constructor, are replaced by a 'x'. Note that neither the
       newtype declaration itself nor partial applications of newtype
       constructors are changed (It were possible to replace partial
       applications of newtype constructor by 'prelude.id'.
       However, our solution yields a more accurate output when the result
       of a computation includes partial applications.).

47
     * Functional patterns are replaced by variables and are integrated
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
       in a guarded right hand side using the (=:<=) operator

     * Records, which currently must be declared using the keyword
       'type', are transformed into data types with one constructor.
       Record construction and pattern matching are represented using the
       record constructor. Selection and update are represented using selector
       and update functions which are generated for each record declaration.
       The record constructor must be entered into the type environment as well
       as the selector functions and the update functions.

   TODO: Use a different representation for the restricted code instead
   of using the syntax tree from 'CurrySyntax'.

   As we are going to insert references to real prelude entities,
   all names must be properly qualified before calling this module.
-}

module Transformations.Desugar (desugar) where

67
import           Control.Applicative
68
import           Control.Arrow              (first, second)
69
import           Control.Monad              (mplus)
70
71
72
73
74
75
76
77
78
79
import qualified Control.Monad.State as S   (State, runState, gets, modify)
import           Data.List                  ((\\), nub, tails)
import           Data.Maybe                 (fromMaybe)
import qualified Data.Set            as Set (Set, empty, member, insert)

import Curry.Base.Ident
import Curry.Base.Position hiding (first)
import Curry.Syntax

import Base.Expr
80
import Base.CurryTypes (toType, fromType)
81
82
import Base.Messages (internalError)
import Base.Types
83
import Base.TypeSubst (expandAliasType)
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
import Base.Typing
import Base.Utils (mapAccumM, concatMapM)

import Env.TypeConstructor (TCEnv, TypeInfo (..), qualLookupTC)
import Env.Value (ValueEnv, ValueInfo (..), bindFun, bindGlobalInfo
  , lookupValue, qualLookupValue)

-- New identifiers may be introduced while desugaring pattern
-- declarations, case and lambda-expressions, and list comprehensions.
-- As usual, we use a state monad transformer for generating unique
-- names. In addition, the state is also used for passing through the
-- type environment, which must be augmented with the types of these new
-- variables.

data DesugarState = DesugarState
  { moduleIdent :: ModuleIdent      -- read-only
  , extensions  :: [KnownExtension] -- read-only
  , tyConsEnv   :: TCEnv            -- read-only
  , valueEnv    :: ValueEnv
  , nextId      :: Integer     -- counter
  }

type DsM a = S.State DesugarState a

getModuleIdent :: DsM ModuleIdent
getModuleIdent = S.gets moduleIdent

negativeLiterals :: DsM Bool
negativeLiterals = S.gets (\s -> NegativeLiterals `elem` extensions s)

getTyConsEnv :: DsM TCEnv
getTyConsEnv = S.gets tyConsEnv

getValueEnv :: DsM ValueEnv
getValueEnv = S.gets valueEnv

modifyValueEnv :: (ValueEnv -> ValueEnv) -> DsM ()
modifyValueEnv f = S.modify $ \ s -> s { valueEnv = f $ valueEnv s }

getNextId :: DsM Integer
getNextId = do
  nid <- S.gets nextId
  S.modify $ \ s -> s { nextId = succ nid }
  return nid

-- ---------------------------------------------------------------------------
-- Generation of fresh names
-- ---------------------------------------------------------------------------

getTypeOf :: Typeable t => t -> DsM Type
134
135
136
137
getTypeOf t = do
  tyEnv <- getValueEnv
  tcEnv <- getTyConsEnv
  return (typeOf tyEnv tcEnv t)
138
139
140
141

freshIdent :: String -> Int -> TypeScheme -> DsM Ident
freshIdent prefix arity ty = do
  m <- getModuleIdent
142
  x <- mkName prefix <$> getNextId
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
  modifyValueEnv $ bindFun m x arity ty
  return x
  where mkName pre n = mkIdent $ pre ++ show n

freshMonoTypeVar :: Typeable t => String -> t -> DsM Ident
freshMonoTypeVar prefix t = getTypeOf t >>= \ ty ->
  freshIdent prefix (arrowArity ty) (monoType ty)

-- The desugaring phase keeps only the type, function, and value
-- declarations of the module. In the current version, record declarations
-- are transformed into data types. The remaining type declarations are
-- not desugared and cannot occur in local declaration groups.
-- They are filtered out separately.

-- In order to use records within other modules, the export specification
-- of the module has to be extended with the selector and update functions of
-- all exported labels.

-- Actually, the transformation is slightly more general than necessary
-- as it allows value declarations at the top-level of a module.

desugar :: [KnownExtension] -> ValueEnv -> TCEnv -> Module
        -> (Module, ValueEnv)
166
desugar xs tyEnv tcEnv (Module ps m es is ds)
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
  = (Module ps m es is ds', valueEnv s')
  where (ds', s') = S.runState (desugarModuleDecls ds)
                               (DesugarState m xs tcEnv tyEnv 1)

desugarModuleDecls :: [Decl] -> DsM [Decl]
desugarModuleDecls ds = do
  ds'  <- concatMapM dsRecordDecl ds -- convert record decls to data decls
  ds'' <- dsDeclGroup ds'
  return $ filter isTypeDecl ds' ++ ds''

-- Within a declaration group, all type signatures and evaluation
-- annotations are discarded. First, the patterns occurring in the left
-- hand sides are desugared. Due to lazy patterns, this may add further
-- declarations to the group that must be desugared as well.

dsDeclGroup :: [Decl] -> DsM [Decl]
dsDeclGroup ds = concatMapM dsDeclLhs valDecls >>= mapM dsDeclRhs
 where valDecls = filter isValueDecl ds

dsDeclLhs :: Decl -> DsM [Decl]
dsDeclLhs (PatternDecl p t rhs) = do
  (ds', t') <- dsPattern p [] t
  dss'      <- mapM dsDeclLhs ds'
  return $ PatternDecl p t' rhs : concat dss'
dsDeclLhs (ExternalDecl   p fs) = mapM (genForeignDecl p) fs
dsDeclLhs d                     = return [d]

genForeignDecl :: Position -> Ident -> DsM Decl
genForeignDecl p f = do
  m     <- getModuleIdent
197
  ty    <- fromType <$> (getTypeOf $ Variable $ qual m f)
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
  return $ ForeignDecl p CallConvPrimitive (Just $ idName f) f ty
  where qual m f'
         | hasGlobalScope f' = qualifyWith m f'
         | otherwise         = qualify f'

-- After desugaring its right hand side, each equation is eta-expanded
-- by adding as many variables as necessary to the argument list and
-- applying the right hand side to those variables (Note: eta-expansion
-- is disabled in the version for PAKCS).
-- Furthermore every occurrence of a record type within the type of a function
-- is simplified to the corresponding type constructor from the record
-- declaration. This is possible because currently records must not be empty
-- and a record label belongs to only one record declaration.

dsDeclRhs :: Decl -> DsM Decl
dsDeclRhs (FunctionDecl     p f eqs) =
214
  FunctionDecl p f <$> mapM dsEquation eqs
215
dsDeclRhs (PatternDecl      p t rhs) =
216
  PatternDecl p t <$> dsRhs p id rhs
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
dsDeclRhs (ForeignDecl p cc ie f ty) =
  return $ ForeignDecl p cc (ie `mplus` Just (idName f)) f ty
dsDeclRhs vars@(FreeDecl        _ _) = return vars
dsDeclRhs _ = error "Desugar.dsDeclRhs: no pattern match"

dsEquation :: Equation -> DsM Equation
dsEquation (Equation p lhs rhs) = do
  (ds1, cs1, ts1) <- dsFunctionalPatterns p     ts
  (cs2     , ts2) <- dsNonLinearity             ts1
  (ds2     , ts3) <- mapAccumM (dsPattern p) [] ts2
  rhs1            <- dsRhs p (addConstraints (cs1 ++ cs2))
                   $ addDecls (ds1 ++ ds2) $ rhs
  return $ Equation p (FunLhs f ts3) rhs1
  where (f, ts) = flatLhs lhs

-- Desugaring of non-linear pattern
-- The desugaring traverses a pattern in depth-first order and collects
-- all variables. If it encounters a variable which has been previously
-- introduced, the second occurrence is changed to a fresh variable
-- and a new pair (newvar, oldvar) is saved to generate constraints later.
-- /Note:/ Non-linear patterns in functional patterns are not desugared,
-- as this special case is handled later.
dsNonLinearity :: [Pattern] -> DsM ([Expression], [Pattern])
dsNonLinearity ts = do
  ((_, cs), ts') <- mapAccumM dsNonLinear (Set.empty, []) ts
  return (reverse cs, ts')

type NonLinearEnv = (Set.Set Ident, [Expression])

dsNonLinear :: NonLinearEnv -> Pattern -> DsM (NonLinearEnv, Pattern)
dsNonLinear env l@(LiteralPattern        _) = return (env, l)
dsNonLinear env n@(NegativePattern     _ _) = return (env, n)
dsNonLinear env t@(VariablePattern       v)
  | v `Set.member` vis = do
    v' <- freshMonoTypeVar "_#nonlinear" t
    return ((vis, (mkVar v =:= mkVar v') : ren), VariablePattern v')
  | otherwise        = return ((Set.insert v vis, ren), t)
  where (vis, ren) = env
dsNonLinear env (ConstructorPattern   c ts) = do
  (env', ts') <- mapAccumM dsNonLinear env ts
  return (env', ConstructorPattern c ts')
dsNonLinear env (InfixPattern     t1 op t2) = do
  (env1, t1') <- dsNonLinear env  t1
  (env2, t2') <- dsNonLinear env1 t2
  return (env2, InfixPattern t1' op t2')
dsNonLinear env (ParenPattern            t) = do
  (env', t') <- dsNonLinear env t
  return (env', ParenPattern t')
dsNonLinear env (TuplePattern       pos ts) = do
  (env', ts') <- mapAccumM dsNonLinear env ts
  return (env', TuplePattern pos ts')
dsNonLinear env (ListPattern        pos ts) = do
  (env', ts') <- mapAccumM dsNonLinear env ts
  return (env', ListPattern pos ts')
dsNonLinear env (AsPattern             v t) = do
  (env1, VariablePattern v') <- dsNonLinear env (VariablePattern v)
  (env2, t') <- dsNonLinear env1 t
  return (env2, AsPattern v' t')
dsNonLinear env (LazyPattern           r t) = do
  (env', t') <- dsNonLinear env t
  return (env', LazyPattern r t')
dsNonLinear env (FunctionPattern      f ts) = do
  (env', ts') <- mapAccumM dsNonLinear env ts
  return (env', FunctionPattern f ts')
dsNonLinear env (InfixFuncPattern t1 op t2) = do
  (env1, t1') <- dsNonLinear env  t1
  (env2, t2') <- dsNonLinear env1 t2
  return (env2, InfixFuncPattern t1' op t2')
dsNonLinear env (RecordPattern        fs r) = do
  (env1, fs') <- mapAccumM dsField env fs
  return (env1, RecordPattern fs' r)
  where dsField e (Field p i t) = do
          (e', t') <- dsNonLinear e t
          return (e', Field p i t')

-- The transformation of patterns is straight forward except for lazy
-- patterns. A lazy pattern '~t' is replaced by a fresh
-- variable 'v' and a new local declaration 't = v' in the
-- scope of the pattern. In addition, as-patterns 'v@t' where
-- 't' is a variable or an as-pattern are replaced by 't' in combination
-- with a local declaration for 'v'.

dsPattern :: Position -> [Decl] -> Pattern -> DsM ([Decl], Pattern)
dsPattern p ds (LiteralPattern         l) = do
  dl <- dsLiteral l
  case dl of
    Left  l'     -> return (ds, LiteralPattern l')
    Right (rs,ls) -> dsPattern p ds $ ListPattern rs $ map LiteralPattern ls
dsPattern p ds (NegativePattern      _ l) =
  dsPattern p ds (LiteralPattern (negateLiteral l))
dsPattern _ ds v@(VariablePattern      _) = return (ds, v)
dsPattern p ds (ConstructorPattern c [t]) = do
    tyEnv <- getValueEnv
310
    (if isNewtypeConstr tyEnv c then id else second (constrPat c)) <$>
311
312
313
          (dsPattern p ds t)
  where constrPat c' t' = ConstructorPattern c' [t']
dsPattern p ds (ConstructorPattern c ts) =
314
  second (ConstructorPattern c) <$> mapAccumM (dsPattern p) ds ts
315
316
317
318
319
320
321
322
dsPattern p ds (InfixPattern t1 op t2) =
  dsPattern p ds (ConstructorPattern op [t1,t2])
dsPattern p ds (ParenPattern      t) = dsPattern p ds t
dsPattern p ds (TuplePattern pos ts) =
  dsPattern p ds (ConstructorPattern (tupleConstr ts) ts)
  where tupleConstr ts' = addRef pos $
                         if null ts' then qUnitId else qTupleId (length ts')
dsPattern p ds (ListPattern pos ts) =
323
  second (dsList pos cons nil) <$> mapAccumM (dsPattern p) ds ts
324
325
  where nil  p' = ConstructorPattern (addRef p' qNilId) []
        cons p' t ts' = ConstructorPattern (addRef p' qConsId) [t,ts']
326
dsPattern p ds (AsPattern   v t) = dsAs p v <$> dsPattern p ds t
327
328
dsPattern p ds (LazyPattern r t) = dsLazy r p ds t
dsPattern p ds (FunctionPattern f ts) =
329
  second (FunctionPattern f) <$> mapAccumM (dsPattern p) ds ts
330
331
332
333
334
335
dsPattern p ds (InfixFuncPattern t1 f t2) =
  dsPattern p ds (FunctionPattern f [t1,t2])
dsPattern p ds (RecordPattern fs _)
  | null fs   = internalError "Desugar.dsPattern: empty record"
  | otherwise = do
    r   <- recordFromField (fieldLabel (head fs))
336
    fs' <- (map fst . snd) <$> lookupRecord r
337
338
339
340
341
342
    let ts = map (dsLabel (map field2Tuple fs)) fs'
    dsPattern p ds (ConstructorPattern r ts)
  where dsLabel fs' l = fromMaybe (VariablePattern anonId) (lookup l fs')

dsLiteral :: Literal -> DsM (Either Literal ([SrcRef], [Literal]))
dsLiteral c@(Char             _ _) = return $ Left c
343
344
345
346
347
348
349
dsLiteral (Int                v i) = do
  tyEnv <- getValueEnv
  tcEnv <- getTyConsEnv
  return (Left (fixType tyEnv tcEnv))
  where fixType tyEnv' tcEnv'
          | typeOf tyEnv' tcEnv' v == floatType =
              Float (srcRefOf $ idPosition v) (fromIntegral i)
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
          | otherwise = Int v i
dsLiteral f@(Float            _ _) = return $ Left f
dsLiteral (String (SrcRef [i]) cs) = return $ Right
  (consRefs i cs, zipWith (Char . SrcRef . (:[])) [i, i + 2 ..] cs)
  where consRefs r []     = [SrcRef [r]]
        consRefs r (_:xs) = let r' = r + 2
                            in  r' `seq` (SrcRef [r'] : consRefs r' xs)
dsLiteral (String is _) = internalError $
  "Desugar.dsLiteral: " ++ "wrong source ref for string "  ++ show is

dsList :: [SrcRef] -> (SrcRef -> b -> b -> b) -> (SrcRef -> b) -> [b] -> b
dsList pos cons nil xs = snd (foldr cons' nil' xs)
  where rNil : rCs = reverse pos
        nil'                 = (rCs , nil rNil)
        cons' t (rC:rCs',ts) = (rCs', cons rC t ts)
        cons' _ ([],_) = error "Desugar.dsList.cons': empty list"

dsAs :: Position -> Ident -> ([Decl], Pattern) -> ([Decl], Pattern)
dsAs p v (ds, t) = case t of
  VariablePattern v' -> (varDecl p v (mkVar v') : ds, t)
  AsPattern     v' _ -> (varDecl p v (mkVar v') : ds, t)
  _                  -> (ds, AsPattern v t)

dsLazy :: SrcRef -> Position -> [Decl] -> Pattern -> DsM ([Decl], Pattern)
dsLazy pos p ds t = case t of
  VariablePattern   _ -> return (ds, t)
  ParenPattern     t' -> dsLazy pos p ds t'
377
  AsPattern      v t' -> dsAs p v <$> dsLazy pos p ds t'
378
379
  LazyPattern pos' t' -> dsLazy pos' p ds t'
  _                   -> do
380
   v' <- addPositionIdent (AST pos) <$> freshMonoTypeVar "_#lazy" t
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
   return (patDecl p { astRef = pos } t (mkVar v') : ds, VariablePattern v')

negateLiteral :: Literal -> Literal
negateLiteral (Int    v i) = Int   v  (-i)
negateLiteral (Float p' f) = Float p' (-f)
negateLiteral _            = internalError "Desugar.negateLiteral"

-- A list of boolean guards is expanded into a nested if-then-else
-- expression, whereas a constraint guard is replaced by a case
-- expression. Note that if the guard type is 'Success' only a
-- single guard is allowed for each equation (This change was
-- introduced in version 0.8 of the Curry report.). We check for the
-- type 'Bool' of the guard because the guard's type defaults to
-- 'Success' if it is not restricted by the guard expression.

dsRhs :: Position -> (Expression -> Expression) -> Rhs -> DsM Rhs
dsRhs p f rhs = do
  e' <- expandRhs prelFailed f rhs >>= dsExpr p
  return (SimpleRhs p e' [])

expandRhs :: Expression -> (Expression -> Expression) -> Rhs -> DsM Expression
expandRhs _  f (SimpleRhs _ e ds) = return $ Let ds (f e)
403
expandRhs e0 f (GuardedRhs es ds) = (Let ds . f) <$> expandGuards e0 es
404
405
406
407

expandGuards :: Expression -> [CondExpr] -> DsM Expression
expandGuards e0 es = do
  tyEnv <- getValueEnv
408
409
  tcEnv <- getTyConsEnv
  return $ if booleanGuards tyEnv tcEnv es
410
411
412
413
414
415
416
417
418
419
420
              then foldr mkIfThenElse e0 es
              else mkCond es
  where mkIfThenElse (CondExpr p g e) = IfThenElse (srcRefOf p) g e
        mkCond       [CondExpr _ g e] = apply prelCond [g, e]
        mkCond _ = error "Desugar.expandGuards.mkCond: non-unary list"

addConstraints :: [Expression] -> Expression -> Expression
addConstraints cs e
  | null cs   = e
  | otherwise = apply prelCond [foldr1 (&) cs, e]

421
422
423
424
booleanGuards :: ValueEnv -> TCEnv -> [CondExpr] -> Bool
booleanGuards _     _     []                    = False
booleanGuards tyEnv tcEnv (CondExpr _ g _ : es) =
  not (null es) || typeOf tyEnv tcEnv g == boolType
425
426
427
428
429
430
431
432
433
434
435
436

dsExpr :: Position -> Expression -> DsM Expression
dsExpr p (Literal l) =
  dsLiteral l >>=
  either (return . Literal) (\ (pos, ls) -> dsExpr p $ List pos $ map Literal ls)
dsExpr _ var@(Variable v)
  | isAnonId (unqualify v) = return prelUnknown
      -- v' <- getValueEnv >>= freshIdent "_#anonfree" . polyType . flip typeOf var
      -- dsExpr p $ Let [ExtraVariables p [v']] $ mkVar v'
  | otherwise              = return var
dsExpr _ c@(Constructor _) = return c
dsExpr p (Paren         e) = dsExpr p e
437
dsExpr p (Typed      e ty) = Typed <$> dsExpr p e <*> dsTypeExpr ty
438
dsExpr p (Tuple    pos es) =
439
  apply (Constructor $ tupleConstr es) <$> mapM (dsExpr p) es
440
441
  where tupleConstr es1 = addRef pos $ if null es1 then qUnitId else qTupleId (length es1)
dsExpr p (List pos es) =
442
  dsList pos cons nil <$> mapM (dsExpr p) es
443
444
445
446
447
  where nil p'  = Constructor (addRef p' qNilId)
        cons p' = Apply . Apply (Constructor $ addRef p' qConsId)
dsExpr p (ListCompr r e []    ) = dsExpr p (List [r,r] [e])
dsExpr p (ListCompr r e (q:qs)) = dsQual p q (ListCompr r e qs)
dsExpr p (EnumFrom e) =
448
  Apply prelEnumFrom <$> dsExpr p e
449
dsExpr p (EnumFromThen e1 e2) =
450
  apply prelEnumFromThen <$> mapM (dsExpr p) [e1, e2]
451
dsExpr p (EnumFromTo e1 e2) =
452
  apply prelEnumFromTo <$> mapM (dsExpr p) [e1, e2]
453
dsExpr p (EnumFromThenTo e1 e2 e3) =
454
  apply prelEnumFromThenTo <$> mapM (dsExpr p) [e1, e2, e3]
455
456
457
458
459
460
dsExpr p (UnaryMinus op e) = do
  ty <- getTypeOf e
  e' <- dsExpr p e
  negativeLits <- negativeLiterals
  case e' of
    Literal l | negativeLits -> return (Literal $ negateLiteral l)
461
    _                        -> Apply (unaryMinus op ty) <$> dsExpr p e
462
463
464
465
466
467
468
  where
  unaryMinus op1 ty'
    | op1 ==  minusId = if ty' == floatType then prelNegateFloat else prelNegate
    | op1 == fminusId = prelNegateFloat
    | otherwise       = internalError "Desugar.unaryMinus"
dsExpr p (Apply (Constructor c) e) = do
  tyEnv <- getValueEnv
469
470
471
  (if isNewtypeConstr tyEnv c then id else (Apply (Constructor c))) <$>
    dsExpr p e
dsExpr p (Apply e1 e2) = Apply <$> dsExpr p e1 <*> dsExpr p e2
472
473
474
475
476
dsExpr p (InfixApply e1 op e2) = do
  op' <- dsExpr p (infixOp op)
  e1' <- dsExpr p e1
  e2' <- dsExpr p e2
  return $ apply op' [e1', e2']
477
dsExpr p (LeftSection e op) = Apply <$> dsExpr p (infixOp op) <*> dsExpr p e
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
dsExpr p (RightSection op e) = do
  op' <- dsExpr p (infixOp op)
  e' <- dsExpr p e
  return $ apply prelFlip [op', e']
dsExpr p expr@(Lambda r ts e) = do
  ty <- getTypeOf expr
  f  <- freshIdent "_#lambda" (length ts) (polyType ty)
  dsExpr p $ Let [funDecl (AST r) f ts e] $ mkVar f
dsExpr p (Let ds e) = do
  ds' <- dsDeclGroup ds
  e' <- dsExpr p e
  return (if null ds' then e' else Let ds' e')
dsExpr p (Do sts e) =
  dsExpr p (foldr desugarStmt e sts)
  where desugarStmt (StmtExpr r e1) e' = apply (prelBind_ r) [e1,e']
        desugarStmt (StmtBind r t e1) e' = apply (prelBind r) [e1,Lambda r [t] e']
        desugarStmt (StmtDecl ds) e' = Let ds e'
dsExpr p (IfThenElse r e1 e2 e3) = do
  e1' <- dsExpr p e1
  e2' <- dsExpr p e2
  e3' <- dsExpr p e3
  return (Case r Rigid e1'
          [caseAlt p truePattern e2', caseAlt p falsePattern e3'])
dsExpr p (Case r ct e alts)
  | null alts = return prelFailed
  | otherwise = do
    m  <- getModuleIdent
    e' <- dsExpr p e
    v  <- freshMonoTypeVar "_#case" e
    alts'  <- mapM dsAltLhs alts
    alts'' <- mapM (expandAlt v ct) (init (tails alts')) >>= mapM dsAltRhs
    return (mkCase m v e' alts'')
  where
  mkCase m1 v e1 alts1
    | v `elem` qfv m1 alts1 = Let [varDecl p v e1] (Case r ct (mkVar v) alts1)
    | otherwise             = Case r ct e1 alts1
dsExpr p (RecordConstr fs)
  | null fs   = internalError "Desugar.dsExpr: empty record construction"
  | otherwise = do
    r <- recordFromField (fieldLabel (head fs))
    dsRecordConstr p r (map field2Tuple fs)
dsExpr p (RecordSelection e l) = do
  m <- getModuleIdent
  r <- recordFromField l
  dsExpr p (Apply (Variable (qualRecSelectorId m r l)) e)
dsExpr p (RecordUpdate fs rexpr)
  | null fs   = internalError "Desugar.dsExpr: empty record update"
  | otherwise = do
    r <- recordFromField (fieldLabel (head fs))
    dsRecordUpdate p r rexpr (map field2Tuple fs)

529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
dsTypeExpr :: TypeExpr -> DsM TypeExpr
dsTypeExpr ty = do
  tcEnv <- getTyConsEnv
  let expType = expandType tcEnv (toType [] ty)
  return $ fromType expType

expandType :: TCEnv -> Type -> Type
expandType tcEnv (TypeConstructor tc tys) = case qualLookupTC tc tcEnv of
  [DataType     tc' _  _] -> TypeConstructor tc' tys'
  [RenamingType tc' _  _] -> TypeConstructor tc' tys'
  [AliasType    _   _ ty] -> expandAliasType tys' ty
  _ -> internalError $ "Desugar.expandType " ++ show tc
  where tys' = map (expandType tcEnv) tys
expandType _     tv@(TypeVariable      _) = tv
expandType _     tc@(TypeConstrained _ _) = tc
expandType tcEnv (TypeArrow      ty1 ty2) =
  TypeArrow (expandType tcEnv ty1) (expandType tcEnv ty2)
expandType _     ts@(TypeSkolem        _) = ts
547
548
expandType tcEnv (TypeRecord          fs) =
  TypeRecord (map (\ (l, ty) -> (l, expandType tcEnv ty)) fs)
549

550
551
552
553
554
555
556
557
558
559
560
561
562
563
-- If an alternative in a case expression has boolean guards and all of
-- these guards return 'False', the enclosing case expression does
-- not fail but continues to match the remaining alternatives against the
-- selector expression. In order to implement this semantics, which is
-- compatible with Haskell, we expand an alternative with boolean guards
-- such that it evaluates a case expression with the remaining cases that
-- are compatible with the matched pattern when the guards fail.

dsAltLhs :: Alt -> DsM Alt
dsAltLhs (Alt p t rhs) = do
  (ds', t') <- dsPattern p [] t
  return $ Alt p t' (addDecls ds' rhs)

dsAltRhs :: Alt -> DsM Alt
564
dsAltRhs (Alt p t rhs) = Alt p t <$> dsRhs p id rhs
565
566
567

expandAlt :: Ident -> CaseType -> [Alt] -> DsM Alt
expandAlt _ _  []                   = error "Desugar.expandAlt: empty list"
568
expandAlt v ct (Alt p t rhs : alts) = caseAlt p t <$> expandRhs e0 id rhs
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
  where
  e0 | ct == Flex = prelFailed
     | otherwise  = Case (srcRefOf p) ct (mkVar v)
                         (filter (isCompatible t . altPattern) alts)
  altPattern (Alt _ t1 _) = t1

isCompatible :: Pattern -> Pattern -> Bool
isCompatible (VariablePattern _) _                   = True
isCompatible _                   (VariablePattern _) = True
isCompatible (AsPattern    _ t1) t2                  = isCompatible t1 t2
isCompatible t1                  (AsPattern    _ t2) = isCompatible t1 t2
isCompatible (ConstructorPattern c1 ts1) (ConstructorPattern c2 ts2)
  = and ((c1 == c2) : zipWith isCompatible ts1 ts2)
isCompatible (LiteralPattern         l1) (LiteralPattern         l2)
  = canon l1 == canon l2
  where canon (Int _ i) = Int anonId i
        canon l         = l
isCompatible _                    _                  = False

-- The frontend provides several extensions of the Curry functionality, which
-- have to be desugared as well. This part transforms the following extensions:
-- * functional patterns
-- * records

593
594
dsFunctionalPatterns :: Position -> [Pattern]
                     -> DsM ([Decl], [Expression], [Pattern])
595
596
597
598
599
600
601
602
603
604
605
dsFunctionalPatterns p ts = do
  (bs, ts') <- mapAccumM elimFP [] ts
  let (ds, cs) = genFPExpr p (bv ts') (reverse bs)
  return (ds, cs, ts')

type LazyBinding = (Pattern, Ident)

elimFP :: [LazyBinding] -> Pattern -> DsM ([LazyBinding], Pattern)
elimFP bs p@(LiteralPattern        _) = return (bs, p)
elimFP bs p@(NegativePattern     _ _) = return (bs, p)
elimFP bs p@(VariablePattern       _) = return (bs, p)
606
607
elimFP bs (ConstructorPattern   c ts) = second (ConstructorPattern c)
                                        <$> mapAccumM elimFP bs ts
608
609
610
elimFP bs (InfixPattern     t1 op t2) = do
  (bs', [t1',t2']) <- mapAccumM elimFP bs [t1,t2]
  return (bs', InfixPattern t1' op t2')
611
612
613
614
615
616
617
elimFP bs (ParenPattern            t) = second ParenPattern <$> elimFP bs t
elimFP bs (TuplePattern       pos ts) = second (TuplePattern pos)
                                        <$> mapAccumM elimFP bs ts
elimFP bs (ListPattern        pos ts) = second (ListPattern pos)
                                        <$> mapAccumM elimFP bs ts
elimFP bs (AsPattern             v t) = second (AsPattern v) <$> elimFP bs t
elimFP bs (LazyPattern           r t) = second (LazyPattern r) <$> elimFP bs t
618
619
620
621
622
623
elimFP bs p@(FunctionPattern     _ _) = do
 v <- freshMonoTypeVar "_#funpatt" p
 return ((p, v) : bs, VariablePattern v)
elimFP bs p@(InfixFuncPattern  _ _ _) = do
 v <- freshMonoTypeVar "_#funpatt" p
 return ((p, v) : bs, VariablePattern v)
624
625
626
elimFP bs (RecordPattern        fs r) = second (flip RecordPattern r)
                                        <$> mapAccumM elimField bs fs
  where elimField b (Field p i t) = second (Field p i) <$> elimFP b t
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684

genFPExpr :: Position -> [Ident] -> [LazyBinding] -> ([Decl], [Expression])
genFPExpr p vs bs
  | null bs   = ([]               , [])
  | null free = ([]               , cs)
  | otherwise = ([FreeDecl p free], cs)
  where
  mkLB (t, v) = let (t', es) = fp2Expr t
                in  (t' =:<= mkVar v) : es
  cs       = concatMap mkLB bs
  free     = nub $ filter (not . isAnonId) $ bv (map fst bs) \\ vs

fp2Expr :: Pattern -> (Expression, [Expression])
fp2Expr (LiteralPattern          l) = (Literal l, [])
fp2Expr (NegativePattern       _ l) = (Literal (negateLiteral l), [])
fp2Expr (VariablePattern         v) = (mkVar v, [])
fp2Expr (ConstructorPattern   c ts) =
  let (ts', ess) = unzip $ map fp2Expr ts
  in  (apply (Constructor c) ts', concat ess)
fp2Expr (InfixPattern     t1 op t2) =
  let (t1', es1) = fp2Expr t1
      (t2', es2) = fp2Expr t2
  in  (InfixApply t1' (InfixConstr op) t2', es1 ++ es2)
fp2Expr (ParenPattern            t) = first Paren (fp2Expr t)
fp2Expr (TuplePattern         r ts) =
  let (ts', ess) = unzip $ map fp2Expr ts
  in  (Tuple r ts', concat ess)
fp2Expr (ListPattern         rs ts) =
  let (ts', ess) = unzip $ map fp2Expr ts
  in  (List rs ts', concat ess)
fp2Expr (FunctionPattern      f ts) =
  let (ts', ess) = unzip $ map fp2Expr ts
  in  (apply (Variable f) ts', concat ess)
fp2Expr (InfixFuncPattern t1 op t2) =
  let (t1', es1) = fp2Expr t1
      (t2', es2) = fp2Expr t2
  in  (InfixApply t1' (InfixOp op) t2', es1 ++ es2)
fp2Expr (AsPattern             v t) =
  let (t', es) = fp2Expr t
  in  (mkVar v, (t' =:<= mkVar v):es)
fp2Expr t                           = internalError $
  "Desugar.fp2Expr: Unexpected constructor term: " ++ show t

-- Desugaring of Records
-- =====================

recordFromField :: Ident -> DsM QualIdent
recordFromField lbl = do
  tyEnv <- getValueEnv
  case lookupValue lbl tyEnv of
    [Label _ r _] -> return r
    _             -> internalError $
      "Desugar.recordFromField: unknown label: " ++ show lbl

lookupRecord :: QualIdent -> DsM (Int, [(Ident, Type)])
lookupRecord r = do
  tcEnv <- getTyConsEnv
  case qualLookupTC r tcEnv of
685
    [AliasType _ n (TypeRecord fs)] -> return (n, fs)
686
687
688
689
    _                                 ->
      internalError $ "Desugar.lookupRecord: no record: " ++ show r

dsRecordDecl :: Decl -> DsM [Decl]
690
dsRecordDecl (TypeDecl p r vs (RecordType fss)) = do
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
  m     <- getModuleIdent
  let qr = qualifyWith m r
  (n, fs') <- lookupRecord qr
  let tys   = concatMap (\ (ls, ty) -> replicate (length ls) ty) fss
      --tys' = map (elimRecordTypes tyEnv) tys
      rdecl = DataDecl p r vs [ConstrDecl p [] r tys]
      rty'  = TypeConstructor qr (map TypeVariable [0 .. n - 1])
      rcts' = ForAllExist 0 n (foldr TypeArrow rty' (map snd fs'))
  rfuncs <- mapM (genRecordFuncs p qr rty' (map fst fs')) fs'
  modifyValueEnv
      (bindGlobalInfo (flip DataConstructor (length tys)) m r rcts')
  return $ rdecl : concat rfuncs
dsRecordDecl d = return [d]

genRecordFuncs :: Position -> QualIdent -> Type -> [Ident] -> (Ident, Type)
               -> DsM [Decl]
genRecordFuncs p r rty ls (l, ty) = do
  m <- getModuleIdent
  let (selId, selFunc) = genSelectFunc p r ls l
      (updId, updFunc) = genUpdateFunc p r ls l
      selType = polyType (TypeArrow rty ty)
      updType = polyType (TypeArrow rty $ TypeArrow ty rty)
  modifyValueEnv (bindFun m selId 1 selType . bindFun m updId 2 updType)
  return [selFunc, updFunc]

genSelectFunc :: Position -> QualIdent -> [Ident] -> Ident -> (Ident, Decl)
genSelectFunc p r ls l = (selId, funDecl p selId [cpatt] (mkVar l))
  where
  selId  = recSelectorId r l
  cpatt  = ConstructorPattern r (map VariablePattern ls)

genUpdateFunc :: Position -> QualIdent -> [Ident] -> Ident -> (Ident, Decl)
genUpdateFunc p r ls l = (updId, funDecl p updId [cpatt1, cpatt2] cexpr)
  where
  updId  = recUpdateId r l
  vs     = [ VariablePattern (if v == l then anonId else v) | v <- ls]
  cpatt1 = ConstructorPattern r vs
  cpatt2 = VariablePattern l
  cexpr  = apply (Constructor r) (map mkVar ls)

dsRecordConstr :: Position -> QualIdent -> [(Ident, Expression)]
               -> DsM Expression
dsRecordConstr p r fs = do
734
  fs' <- (map fst . snd) <$> lookupRecord r
735
736
737
738
739
740
741
742
743
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
775
776
777
778
  let cts = map (\ l -> fromMaybe (internalError "Desugar.dsRecordConstr")
                            (lookup l fs)) fs'
  dsExpr p (apply (Constructor r) cts)

dsRecordUpdate :: Position -> QualIdent -> Expression
               -> [(Ident, Expression)] -> DsM Expression
dsRecordUpdate p r rexpr fs = do
  m <- getModuleIdent
  dsExpr p (foldl (genRecordUpdate m r) rexpr fs)
  where
  genRecordUpdate m1 r1 rexpr1 (l,e) =
   apply (Variable $ qualRecUpdateId m1 r1 l) [rexpr1, e]

-- In general, a list comprehension of the form
-- '[e | t <- l, qs]'
-- is transformed into an expression 'foldr f [] l' where 'f'
-- is a new function defined as
--
--     f x xs =
--       case x of
--           t -> [e | qs] ++ xs
--           _ -> xs
--
-- Note that this translation evaluates the elements of 'l' rigidly,
-- whereas the translation given in the Curry report is flexible.
-- However, it does not seem very useful to have the comprehension
-- generate instances of 't' which do not contribute to the list.

-- Actually, we generate slightly better code in a few special cases.
-- When 't' is a plain variable, the 'case' expression degenerates
-- into a let-binding and the auxiliary function thus becomes an alias
-- for '(++)'. Instead of 'foldr (++)' we use the
-- equivalent prelude function 'concatMap'. In addition, if the
-- remaining list comprehension in the body of the auxiliary function has
-- no qualifiers -- i.e., if it is equivalent to '[e]' -- we
-- avoid the construction of the singleton list by calling '(:)'
-- instead of '(++)' and 'map' in place of 'concatMap', respectively.

dsQual :: Position -> Statement -> Expression -> DsM Expression
dsQual p (StmtExpr   r b) e = dsExpr p (IfThenElse r b e (List [r] []))
dsQual p (StmtDecl    ds) e = dsExpr p (Let ds e)
dsQual p (StmtBind r t l) e
  | isVarPattern t = dsExpr p (qualExpr t e l)
  | otherwise      = do
779
780
    v   <- addRefId r <$> freshMonoTypeVar "_#var" t
    l'  <- addRefId r <$> freshMonoTypeVar "_#var" e
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
    dsExpr p (apply (prelFoldr r) [foldFunct v l' e, List [r] [], l])
  where
  qualExpr v (ListCompr _ e1 []) l1
    = apply (prelMap r) [Lambda r [v] e1,l1]
  qualExpr v e1                  l1
    = apply (prelConcatMap r) [Lambda r [v] e1,l1]
  foldFunct v l1 e1
    = Lambda r (map VariablePattern [v,l1])
       (Case r Rigid (mkVar v)
          [ caseAlt p t (append e1 (mkVar l1))
          , caseAlt p (VariablePattern v) (mkVar l1)])

  append (ListCompr _ e1 []) l1 = apply (Constructor $ addRef r $ qConsId)
                                        [e1,l1]
  append e1                  l1 = apply (prelAppend r) [e1,l1]

-- ---------------------------------------------------------------------------
-- Prelude entities
-- ---------------------------------------------------------------------------

prelBind :: SrcRef -> Expression
prelBind = prel ">>="

prelBind_ :: SrcRef -> Expression
prelBind_ = prel ">>"

prelFlip :: Expression
prelFlip = Variable $ preludeIdent "flip"

prelEnumFrom :: Expression
prelEnumFrom = Variable $ preludeIdent "enumFrom"

prelEnumFromTo :: Expression
prelEnumFromTo = Variable $ preludeIdent "enumFromTo"

prelEnumFromThen :: Expression
prelEnumFromThen = Variable $ preludeIdent "enumFromThen"

prelEnumFromThenTo :: Expression
prelEnumFromThenTo = Variable $ preludeIdent "enumFromThenTo"

prelFailed :: Expression
prelFailed = Variable $ preludeIdent "failed"

prelUnknown :: Expression
prelUnknown = Variable $ preludeIdent "unknown"

prelMap :: SrcRef -> Expression
prelMap r = Variable $ addRef r $ preludeIdent "map"

prelFoldr :: SrcRef -> Expression
prelFoldr = prel "foldr"

prelAppend :: SrcRef -> Expression
prelAppend = prel "++"

prelConcatMap :: SrcRef -> Expression
prelConcatMap = prel "concatMap"

prelNegate :: Expression
prelNegate = Variable $ preludeIdent "negate"

prelNegateFloat :: Expression
prelNegateFloat = Variable $ preludeIdent "negateFloat"

prelCond :: Expression
prelCond = Variable $ preludeIdent "cond"

(=:<=) :: Expression -> Expression -> Expression
e1 =:<= e2 = apply prelFPEq [e1, e2]

prelFPEq :: Expression
prelFPEq = Variable $ preludeIdent "=:<="

prelConj :: Expression
prelConj = Variable $ preludeIdent "&"

(=:=) :: Expression -> Expression -> Expression
e1 =:= e2 = apply prelSEq [e1, e2]

prelSEq :: Expression
prelSEq = Variable $ preludeIdent "=:="

(&) :: Expression -> Expression -> Expression
e1 & e2 = apply prelConj [e1, e2]

prel :: String -> SrcRef -> Expression
prel s r = Variable $ addRef r $ preludeIdent s

truePattern :: Pattern
truePattern = ConstructorPattern qTrueId []

falsePattern :: Pattern
falsePattern = ConstructorPattern qFalseId []

preludeIdent :: String -> QualIdent
preludeIdent = qualifyWith preludeMIdent . mkIdent

-- ---------------------------------------------------------------------------
-- Auxiliary definitions
-- ---------------------------------------------------------------------------

isNewtypeConstr :: ValueEnv -> QualIdent -> Bool
isNewtypeConstr tyEnv c = case qualLookupValue c tyEnv of
  [NewtypeConstructor _ _] -> True
  [DataConstructor  _ _ _] -> False
  x -> internalError $ "Transformations.Desugar.isNewtypeConstr: "
                        ++ show c ++ " is " ++ show x

isVarPattern :: Pattern -> Bool
isVarPattern (VariablePattern _) = True
isVarPattern (ParenPattern    t) = isVarPattern t
isVarPattern (AsPattern     _ t) = isVarPattern t
isVarPattern (LazyPattern   _ _) = True
isVarPattern _                   = False

funDecl :: Position -> Ident -> [Pattern] -> Expression -> Decl
funDecl p f ts e = FunctionDecl p f
  [Equation p (FunLhs f ts) (SimpleRhs p e [])]

patDecl :: Position -> Pattern -> Expression -> Decl
patDecl p t e = PatternDecl p t (SimpleRhs p e [])

varDecl :: Position -> Ident -> Expression -> Decl
varDecl p = patDecl p . VariablePattern

addDecls :: [Decl] -> Rhs -> Rhs
addDecls ds (SimpleRhs p e ds') = SimpleRhs p e (ds ++ ds')
addDecls ds (GuardedRhs es ds') = GuardedRhs es (ds ++ ds')

caseAlt :: Position -> Pattern -> Expression -> Alt
caseAlt p t e = Alt p t (SimpleRhs p e [])

apply :: Expression -> [Expression] -> Expression
apply = foldl Apply

mkVar :: Ident -> Expression
mkVar = Variable . qualify