SyntaxCheck.lhs 43.1 KB
Newer Older
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
1
2
3
4
5
6
% $Id: SyntaxCheck.lhs,v 1.53 2004/02/15 22:10:37 wlux Exp $
%
% Copyright (c) 1999-2004, Wolfgang Lux
% See LICENSE for the full license.
%
% Modified by Martin Engelke (men@informatik.uni-kiel.de)
Björn Peemöller 's avatar
Björn Peemöller committed
7
% Modified by Björn Peemöller (bjp@informatik.uni-kiel.de)
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
%
\nwfilename{SyntaxCheck.lhs}
\section{Syntax Checks}
After the type declarations have been checked, the compiler performs a
syntax check on the remaining declarations. This check disambiguates
nullary data constructors and variables which -- in contrast to
Haskell -- is not possible on purely syntactic criteria. In addition,
this pass checks for undefined as well as ambiguous variables and
constructors. In order to allow lifting of local definitions in
later phases, all local variables are renamed by adding a unique
key.\footnote{Actually, all variables defined in the same scope share
the same key.} Finally, all (adjacent) equations of a function are
merged into a single definition.
\begin{verbatim}

Björn Peemöller 's avatar
Björn Peemöller committed
23
> module Checks.SyntaxCheck (syntaxCheck) where
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
24

25
> import Control.Monad (liftM, liftM2, liftM3, unless, when)
Björn Peemöller 's avatar
Björn Peemöller committed
26
> import qualified Control.Monad.State as S (State, runState, gets, modify)
27
> import Data.List ((\\), insertBy, partition)
Björn Peemöller 's avatar
Björn Peemöller committed
28
> import Data.Maybe (fromJust, isJust, isNothing, maybeToList)
Björn Peemöller 's avatar
Björn Peemöller committed
29
> import qualified Data.Set as Set (empty, insert, member)
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
30
31

> import Curry.Base.Ident
Björn Peemöller 's avatar
Björn Peemöller committed
32
> import Curry.Base.Position
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
33
34
> import Curry.Syntax

35
> import Base.Expr
Björn Peemöller 's avatar
Björn Peemöller committed
36
> import Base.Messages (Message, toMessage, internalError, posErr, qposErr)
Björn Peemöller 's avatar
Björn Peemöller committed
37
> import Base.NestEnv
Björn Peemöller 's avatar
Björn Peemöller committed
38
> import Base.Types
Björn Peemöller 's avatar
Björn Peemöller committed
39
> import Base.Utils ((++!), findDouble, findMultiples)
Björn Peemöller 's avatar
Björn Peemöller committed
40

41
> import Env.TypeConstructor (TCEnv, TypeInfo (..), qualLookupTC)
Björn Peemöller 's avatar
Björn Peemöller committed
42
> import Env.Value (ValueEnv, ValueInfo (..))
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
43

Björn Peemöller 's avatar
Björn Peemöller committed
44
45
> import CompilerOpts

Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
46
47
48
49
\end{verbatim}
The syntax checking proceeds as follows. First, the compiler extracts
information about all imported values and data constructors from the
imported (type) environments. Next, the data constructors defined in
Björn Peemöller 's avatar
Björn Peemöller committed
50
the current module are entered into this environment. After this,
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
51
52
53
54
55
56
57
all record labels are entered into the environment too. If a record
identifier is already assigned to a constructor, then an error will be
generated. Finally, all
declarations are checked within the resulting environment. In
addition, this process will also rename the local variables.
\begin{verbatim}

58
59
60
> syntaxCheck :: Options -> ModuleIdent -> ValueEnv -> TCEnv -> [Decl]
>             -> ([Decl], [Message])
> syntaxCheck opts m tyEnv tcEnv decls =
Björn Peemöller 's avatar
Björn Peemöller committed
61
62
63
64
65
>   case findMultiples $ concatMap constrs tds of
>     []  -> runSC (checkModule decls) initState
>     css -> (decls, map errMultipleDataConstructor css)
>   where
>     tds        = filter isTypeDecl decls
66
>     rEnv       = globalEnv $ fmap (renameInfo tcEnv) tyEnv
Björn Peemöller 's avatar
Björn Peemöller committed
67
>     initState  = SCState (optExtensions opts) m rEnv globalKey []
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
68
69
70
71
72
73

\end{verbatim}
A global state transformer is used for generating fresh integer keys
by which the variables get renamed.
\begin{verbatim}

Björn Peemöller 's avatar
Björn Peemöller committed
74
75
76
77
78
79
80
81
82
83
84
85
> data SCState = SCState
>   { extensions  :: [Extension]
>   , moduleIdent :: ModuleIdent
>   , renameEnv   :: RenameEnv
>   , currentId   :: Integer
>   , errors      :: [Message]
>   }

> globalKey :: Integer
> globalKey = uniqueId (mkIdent "")

> type SCM = S.State SCState -- the Syntax Check Monad
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
86

Björn Peemöller 's avatar
Björn Peemöller committed
87
88
> runSC :: SCM a -> SCState -> (a, [Message])
> runSC scm s = let (a, s') = S.runState scm s in (a, reverse $ errors s')
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
89

Björn Peemöller 's avatar
Björn Peemöller committed
90
91
> hasExtension :: Extension -> SCM Bool
> hasExtension ext = S.gets (elem ext . extensions)
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
92

Björn Peemöller 's avatar
Björn Peemöller committed
93
94
95
96
97
98
99
100
101
> getModuleIdent :: SCM ModuleIdent
> getModuleIdent = S.gets moduleIdent

> getRenameEnv :: SCM RenameEnv
> getRenameEnv = S.gets renameEnv

> modifyRenameEnv :: (RenameEnv -> RenameEnv) -> SCM ()
> modifyRenameEnv f = S.modify $ \ s -> s { renameEnv = f $ renameEnv s }

102
103
104
105
106
107
108
109
110
> incId :: SCM ()
> incId = S.modify $ \ s -> s { currentId = succ $ currentId s }

> getCurrentId :: SCM Integer
> getCurrentId = S.gets currentId

> newId :: SCM Integer
> newId = incId >> getCurrentId

Björn Peemöller 's avatar
Björn Peemöller committed
111
112
113
114
> inNestedEnv :: SCM a -> SCM a
> inNestedEnv act = do
>   oldEnv <- getRenameEnv
>   modifyRenameEnv nestEnv
115
>   incId
Björn Peemöller 's avatar
Björn Peemöller committed
116
117
118
119
120
121
>   res <- act
>   modifyRenameEnv $ const oldEnv
>   return res

> report :: Message -> SCM ()
> report msg = S.modify $ \ s -> s { errors = msg : errors s }
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
122

Björn Peemöller 's avatar
Björn Peemöller committed
123
\end{verbatim}
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
A nested environment is used for recording information about the data
constructors and variables in the module. For every data constructor
its arity is saved. This is used for checking that all constructor
applications in patterns are saturated. For local variables the
environment records the new name of the variable after renaming.
Global variables are recorded with qualified identifiers in order
to distinguish multiply declared entities.

Currently records must explicitly be declared together with their labels.
When constructing or updating a record, it is necessary to compute
all its labels using just one of them. Thus for each label
the record identifier and all its labels are entered into the environment

\em{Note:} the function \texttt{qualLookupVar} has been extended to
allow the usage of the qualified list constructor \texttt{(prelude.:)}.
\begin{verbatim}

> type RenameEnv = NestEnv RenameInfo

Björn Peemöller 's avatar
Björn Peemöller committed
143
144
145
146
147
148
> data RenameInfo
>   = Constr Int                    -- arity of data constructor
>   | RecordLabel QualIdent [Ident] -- record type and all labels for a single record label
>   | GlobalVar Int QualIdent       -- arity of global function
>   | LocalVar Int Ident            -- arity of local function
>     deriving (Eq, Show)
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
149

150
151
152
153
154
> renameInfo :: TCEnv -> ValueInfo -> RenameInfo
> renameInfo _     (DataConstructor  _ a _) = Constr $ a
> renameInfo _     (NewtypeConstructor _ _) = Constr 1
> renameInfo _     (Value          qid a _) = GlobalVar a qid
> renameInfo tcEnv (Label            _ r _) = case qualLookupTC r tcEnv of
Björn Peemöller 's avatar
Björn Peemöller committed
155
156
>   [AliasType _ _ (TypeRecord fs _)] -> RecordLabel r $ map fst fs
>   _ -> internalError "SyntaxCheck.renameInfo: no unambiguous record"
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
157
158
159
160
161
162
163
164

\end{verbatim}
Since record types are currently translated into data types, it is
necessary to ensure that all identifiers for records and constructors
are different. Furthermore it is not allowed to declare a label more
than once.
\begin{verbatim}

Björn Peemöller 's avatar
Björn Peemöller committed
165
166
167
168
169
170
171
172
173
> bindGlobal :: ModuleIdent -> Ident -> RenameInfo -> RenameEnv -> RenameEnv
> bindGlobal m c r = bindNestEnv c r . qualBindNestEnv (qualifyWith m c) r

> bindLocal :: Ident -> RenameInfo -> RenameEnv -> RenameEnv
> bindLocal = bindNestEnv

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

> -- Binding type constructor information
Björn Peemöller 's avatar
Björn Peemöller committed
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
> bindTypeDecl :: Decl -> SCM ()
> bindTypeDecl (DataDecl    _ _ _ cs) = mapM_ bindConstr cs
> bindTypeDecl (NewtypeDecl _ _ _ nc) = bindNewConstr nc
> bindTypeDecl (TypeDecl _ t _ (RecordType fs _)) = do
>   m <- getModuleIdent
>   others <- qualLookupVar (qualifyWith m t) `liftM` getRenameEnv
>   when (any isConstr others) $ report $ errIllegalRecordId t
>   mapM_ (bindRecordLabel t allLabels) allLabels
>   where allLabels = concatMap fst fs
> bindTypeDecl _ = return ()

> bindConstr :: ConstrDecl -> SCM ()
> bindConstr (ConstrDecl _ _ c tys) = do
>   m <- getModuleIdent
>   modifyRenameEnv $ bindGlobal m c (Constr $ length tys)
> bindConstr (ConOpDecl _ _ _ op _) = do
>   m <- getModuleIdent
>   modifyRenameEnv $ bindGlobal m op (Constr 2)

> bindNewConstr :: NewConstrDecl -> SCM ()
> bindNewConstr (NewConstrDecl _ _ c _) = do
>   m <- getModuleIdent
>   modifyRenameEnv $ bindGlobal m c (Constr 1)

> bindRecordLabel :: Ident -> [Ident] -> Ident -> SCM ()
> bindRecordLabel t allLabels l = do
>   m <- getModuleIdent
>   new <- (null . lookupVar l) `liftM` getRenameEnv
>   unless new $ report $ errDuplicateDefinition l
>   modifyRenameEnv $ bindGlobal m l (RecordLabel (qualifyWith m t) allLabels)
Björn Peemöller 's avatar
Björn Peemöller committed
204
205
206
207

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

> -- |Bind a global function declaration in the 'RenameEnv'
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
208
209
> bindFuncDecl :: ModuleIdent -> Decl -> RenameEnv -> RenameEnv
> bindFuncDecl m (FunctionDecl _ ident equs) env
Björn Peemöller 's avatar
Björn Peemöller committed
210
211
212
213
>   | null equs = internalError "SyntaxCheck.bindFuncDecl: no equations"
>   | otherwise = let arty = length $ snd $ getFlatLhs $ head equs
>                     qid  = qualifyWith m ident
>                 in  bindGlobal m ident (GlobalVar arty qid) env
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
214
> bindFuncDecl m (ExternalDecl _ _ _ ident texpr) env
Björn Peemöller 's avatar
Björn Peemöller committed
215
216
217
>   = let arty = typeArity texpr
>         qid  = qualifyWith m ident
>     in bindGlobal m ident (GlobalVar arty qid) env
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
218
> bindFuncDecl m (TypeSig _ ids texpr) env
Björn Peemöller 's avatar
Björn Peemöller committed
219
>   = foldr bindTS env $ map (qualifyWith m) ids
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
220
221
>  where
>  bindTS qid env'
Björn Peemöller 's avatar
Björn Peemöller committed
222
>     | null $ qualLookupVar qid env'
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
223
224
225
226
227
>       = bindGlobal m (unqualify qid) (GlobalVar (typeArity texpr) qid) env'
>     | otherwise
>       = env'
> bindFuncDecl _ _ env = env

Björn Peemöller 's avatar
Björn Peemöller committed
228
229
230
------------------------------------------------------------------------------

> -- |Bind a local declaration (function, variables) in the 'RenameEnv'
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
231
232
> bindVarDecl :: Decl -> RenameEnv -> RenameEnv
> bindVarDecl (FunctionDecl _ ident equs) env
Björn Peemöller 's avatar
Björn Peemöller committed
233
234
235
236
237
238
>   | null equs = internalError "SyntaxCheck.bindVarDecl: no equations"
>   | otherwise = let arty = length $ snd $ getFlatLhs $ head equs
>                 in  bindLocal (unRenameIdent ident) (LocalVar arty ident) env
> bindVarDecl (PatternDecl         _ t _) env = foldr bindVar env (bv t)
> bindVarDecl (ExtraVariables       _ vs) env = foldr bindVar env vs
> bindVarDecl _                           env = env
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
239
240
241
242

> bindVar :: Ident -> RenameEnv -> RenameEnv
> bindVar v env
>   | v' == anonId = env
Björn Peemöller 's avatar
Björn Peemöller committed
243
>   | otherwise    = bindLocal v' (LocalVar 0 v) env
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
244
245
246
247
248
249
>   where v' = unRenameIdent v

> lookupVar :: Ident -> RenameEnv -> [RenameInfo]
> lookupVar v env = lookupNestEnv v env ++! lookupTupleConstr v

> qualLookupVar :: QualIdent -> RenameEnv -> [RenameInfo]
Björn Peemöller 's avatar
Björn Peemöller committed
250
251
252
> qualLookupVar v env =  qualLookupNestEnv v env
>                    ++! qualLookupListCons v env
>                    ++! lookupTupleConstr (unqualify v)
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
253
254
255

> lookupTupleConstr :: Ident -> [RenameInfo]
> lookupTupleConstr v
Björn Peemöller 's avatar
Björn Peemöller committed
256
257
258
259
260
261
262
263
264
>   | isTupleId v = [Constr $ tupleArity v]
>   | otherwise   = []

> qualLookupListCons :: QualIdent -> RenameEnv -> [RenameInfo]
> qualLookupListCons v env
>   | v == qualifyWith preludeMIdent consId
>   = qualLookupNestEnv (qualify $ qualidId v) env
>   | otherwise
>   = []
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
265
266
267
268
269
270
271
272

\end{verbatim}
When a module is checked, the global declaration group is checked. The
resulting renaming environment can be discarded. The same is true for
a goal. Note that all declarations in the goal must be considered as
local declarations.
\begin{verbatim}

Björn Peemöller 's avatar
Björn Peemöller committed
273
> checkModule :: [Decl] -> SCM [Decl]
Björn Peemöller 's avatar
Björn Peemöller committed
274
275
276
> checkModule decls = do
>   mapM_ bindTypeDecl (rds ++ dds)
>   liftM2 (++) (mapM checkTypeDecl tds) (checkTopDecls vds)
Björn Peemöller 's avatar
Björn Peemöller committed
277
>   where (tds, vds) = partition isTypeDecl decls
Björn Peemöller 's avatar
Björn Peemöller committed
278
>         (rds, dds) = partition isRecordDecl tds
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
279

Björn Peemöller 's avatar
Björn Peemöller committed
280
281
282
283
284
285
286
287
> checkTypeDecl :: Decl -> SCM Decl
> checkTypeDecl rec@(TypeDecl _ r _ (RecordType fs rty)) = do
>   checkRecordExtension $ positionOfIdent r
>   when (isJust  rty) $ internalError
>                          "SyntaxCheck.checkTypeDecl: illegal record type"
>   when (null     fs) $ report $ errEmptyRecord $ positionOfIdent r
>   return rec
> checkTypeDecl d = return d
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
288

Björn Peemöller 's avatar
Björn Peemöller committed
289
290
291
292
> checkTopDecls :: [Decl] -> SCM [Decl]
> checkTopDecls decls = do
>   m <- getModuleIdent
>   checkDeclGroup (bindFuncDecl m) decls
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310

\end{verbatim}
Each declaration group opens a new scope and uses a distinct key
for renaming the variables in this scope. In a declaration group,
first the left hand sides of all declarations are checked, next the
compiler checks that there is a definition for every type signature
and evaluation annotation in this group. Finally, the right hand sides
are checked and adjacent equations for the same function are merged
into a single definition.

The function \texttt{checkDeclLhs} also handles the case where a
pattern declaration is recognized as a function declaration by the
parser. This happens, e.g., for the declaration \verb|where Just x = y|
because the parser cannot distinguish nullary constructors and
functions. Note that pattern declarations are not allowed on the
top-level.
\begin{verbatim}

Björn Peemöller 's avatar
Björn Peemöller committed
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
> checkDeclGroup :: (Decl -> RenameEnv -> RenameEnv) -> [Decl] -> SCM [Decl]
> checkDeclGroup bindDecl ds = do
>   checkedLhs <- mapM checkDeclLhs $ sortFuncDecls ds
>   joinEquations checkedLhs >>= checkDecls bindDecl

> checkDeclLhs :: Decl -> SCM Decl
> checkDeclLhs (InfixDecl   p fix' pr ops) = do
>   k <- getCurrentId
>   return $ InfixDecl p fix' pr $ map (flip renameIdent k) ops
> checkDeclLhs (TypeSig           p vs ty) = do
>   vs' <- mapM (checkVar "type signature") vs
>   return $ TypeSig p vs' ty
> checkDeclLhs (EvalAnnot         p fs ev) = do
>   fs' <- mapM (checkVar "evaluation annotation") fs
>   return $ EvalAnnot p fs' ev
> checkDeclLhs (FunctionDecl      p _ eqs) = checkEquationLhs p eqs
> checkDeclLhs (ExternalDecl p cc ie f ty) = do
>   f' <- checkVar "external declaration" f
>   return $ ExternalDecl p cc ie f' ty
> checkDeclLhs (FlatExternalDecl     p fs) = do
>   fs' <- mapM (checkVar "flat external declaration") fs
>   return $ FlatExternalDecl p fs'
> checkDeclLhs (PatternDecl       p t rhs) = do
>     t' <- checkConstrTerm p t
>     return $ PatternDecl p t' rhs
> checkDeclLhs (ExtraVariables       p vs) = do
>   vs' <- mapM (checkVar "free variables declaration") vs
>   return $ ExtraVariables p vs'
> checkDeclLhs d                           = return d

> checkVar :: String -> Ident -> SCM Ident
> checkVar _what v = do
>   -- isDC <- S.gets (isDataConstr v . renameEnv)
>   -- when isDC $ report $ nonVariable what v -- TODO Why is this disabled?
>   renameIdent v `liftM` getCurrentId

> checkEquationLhs :: Position -> [Equation] -> SCM Decl
> checkEquationLhs p [Equation p' lhs rhs] = do
>   lhs' <- checkEqLhs p' lhs
>   case lhs' of
>     Left  l -> return $ funDecl l
>     Right r -> patDecl r >>= checkDeclLhs
>   where funDecl (f, lhs')  = FunctionDecl p f [Equation p' lhs' rhs]
>         patDecl t = do
>           k <- getCurrentId
>           when (k == globalKey) $ report $ errToplevelPattern p
>           return $ PatternDecl p' t rhs
> checkEquationLhs _ _ = internalError "SyntaxCheck.checkEquationLhs"

> checkEqLhs :: Position -> Lhs -> SCM (Either (Ident, Lhs) ConstrTerm)
> checkEqLhs p toplhs = do
>   m   <- getModuleIdent
>   k   <- getCurrentId
>   env <- getRenameEnv
>   case toplhs of
>     FunLhs f ts
>       | not $ isDataConstr f env -> return left
>       | k /= globalKey           -> return right
>       | null infos               -> return left
>       | otherwise                -> do report $ errToplevelPattern p
>                                        return right
>       where f'    = renameIdent f k
>             infos = qualLookupVar (qualifyWith m f) env
>             left  = Left  (f', FunLhs f' ts)
>             right = Right $ ConstructorPattern (qualify f) ts
>     OpLhs t1 op t2
>       | not $ isDataConstr op env -> return left
>       | k /= globalKey            -> return right
>       | null infos                -> return left
>       | otherwise                 -> do report $ errToplevelPattern p
>                                         return right
>       where op'   = renameIdent op k
>             infos = qualLookupVar (qualifyWith m op) env
>             left  = Left (op', OpLhs t1 op' t2)
>             right = checkOpLhs k env (infixPattern t1 (qualify op)) t2
>             infixPattern (InfixPattern t1' op1 t2') op2 t3 =
>               InfixPattern t1' op1 (infixPattern t2' op2 t3)
>             infixPattern t1' op1 t2' = InfixPattern t1' op1 t2'
>     ApLhs lhs ts -> do
>       checked <- checkEqLhs p lhs
>       case checked of
>         Left (f', lhs') -> return $ Left (f', ApLhs lhs' ts)
>         r               -> do report $ errNonVariable "curried definition" f
>                               return $ r
>         where (f, _) = flatLhs lhs
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
396

Björn Peemöller 's avatar
Björn Peemöller committed
397
> checkOpLhs :: Integer -> RenameEnv -> (ConstrTerm -> ConstrTerm) -> ConstrTerm
Björn Peemöller 's avatar
Björn Peemöller committed
398
>            -> Either (Ident, Lhs) ConstrTerm
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
399
> checkOpLhs k env f (InfixPattern t1 op t2)
Björn Peemöller 's avatar
Björn Peemöller committed
400
401
402
403
>   | isJust m || isDataConstr op' env
>   = checkOpLhs k env (f . InfixPattern t1 op) t2
>   | otherwise
>   = Left (op'', OpLhs (f t1) op'' t2)
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
404
>   where (m,op') = (qualidMod op, qualidId op)
Björn Peemöller 's avatar
Björn Peemöller committed
405
>         op''    = renameIdent op' k
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
406
407
> checkOpLhs _ _ f t = Right (f t)

Björn Peemöller 's avatar
Björn Peemöller committed
408
409
410
411
-- ---------------------------------------------------------------------------

> joinEquations :: [Decl] -> SCM [Decl]
> joinEquations [] = return []
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
412
> joinEquations (FunctionDecl p f eqs : FunctionDecl _ f' [eq] : ds)
Björn Peemöller 's avatar
Björn Peemöller committed
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
>   | f == f' = do
>     when (getArity (head eqs) /= getArity eq) $ report
>                                                 $ errDifferentArity f
>     joinEquations (FunctionDecl p f (eqs ++ [eq]) : ds)
>   where getArity = length . snd . getFlatLhs
> joinEquations (d : ds) = (d :) `liftM` joinEquations ds

> checkDecls :: (Decl -> RenameEnv -> RenameEnv) -> [Decl]
>            -> SCM [Decl]
> checkDecls bindDecl ds = do
>   onJust (report . errDuplicateDefinition) $ findDouble bvs
>   onJust (report . errDuplicateTypeSig   ) $ findDouble tys
>   onJust (report . errDuplicateEvalAnnot ) $ findDouble evs
>   case filter (`notElem` tys) fs of
>     f : _ -> report $ errNoTypeSig f
>     _     -> return ()
>   modifyRenameEnv $ \env -> foldr bindDecl env (tds ++ vds)
>   mapM (checkDeclRhs bvs) ds
>   where vds   = filter isValueDecl ds
>         tds   = filter isTypeSig ds
>         bvs   = concatMap vars vds
>         tys   = concatMap vars tds
>         evs   = concatMap vars $ filter isEvalAnnot ds
>         fs    = [f | FlatExternalDecl _ fs' <- ds, f <- fs']
>         onJust _ Nothing  = return ()
>         onJust f (Just v) = f v

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

> checkDeclRhs :: [Ident] -> Decl -> SCM Decl
> checkDeclRhs bvs (TypeSig      p vs ty) = do
>   vs' <- mapM (checkLocalVar bvs) vs
>   return $ TypeSig p vs' ty
> checkDeclRhs bvs (EvalAnnot    p vs ev) = do
>   vs' <- mapM (checkLocalVar bvs) vs
>   return $ EvalAnnot p vs' ev
> checkDeclRhs _   (FunctionDecl p f eqs) =
>   FunctionDecl p f `liftM` mapM checkEquation eqs
> checkDeclRhs _   (PatternDecl  p t rhs) =
>   PatternDecl p t `liftM` checkRhs rhs
> checkDeclRhs _   d                      = return d

> checkLocalVar :: [Ident] -> Ident -> SCM Ident
> checkLocalVar bvs v = do
>   when (v `notElem` bvs) $ report $ errNoBody v
>   return v

> checkEquation :: Equation -> SCM Equation
> checkEquation (Equation p lhs rhs) = inNestedEnv $ do
>   lhs' <- checkLhs p lhs
>   checkExprVariables lhs'
>   rhs' <- checkRhs rhs
>   return $ Equation p lhs' rhs'

> checkLhs :: Position -> Lhs -> SCM Lhs
> checkLhs p (FunLhs    f ts) = FunLhs f `liftM` mapM (checkConstrTerm p) ts
> checkLhs p (OpLhs t1 op t2) = do
>   let wrongCalls = concatMap (checkParenConstrTerm (Just $ qualify op)) [t1,t2]
>   when (not $ null wrongCalls) $ report $ errInfixWithoutParens
>     (positionOfIdent op) wrongCalls
>   liftM2 (flip OpLhs op) (checkConstrTerm p t1) (checkConstrTerm p t2)
> checkLhs p (ApLhs   lhs ts) =
>   liftM2 ApLhs (checkLhs p lhs) (mapM (checkConstrTerm p) ts)
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
476

Björn Peemöller 's avatar
Björn Peemöller committed
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
checkParen
@param Aufrufende InfixFunktion
@param ConstrTerm
@return Liste mit fehlerhaften Funktionsaufrufen
\begin{verbatim}

> checkParenConstrTerm :: (Maybe QualIdent) -> ConstrTerm -> [(QualIdent,QualIdent)]
> checkParenConstrTerm _ (LiteralPattern          _) = []
> checkParenConstrTerm _ (NegativePattern       _ _) = []
> checkParenConstrTerm _ (VariablePattern         _) = []
> checkParenConstrTerm _ (ConstructorPattern   _ cs) =
>   concatMap (checkParenConstrTerm Nothing) cs
> checkParenConstrTerm o (InfixPattern     t1 op t2) =
>   maybe [] (\c -> [(c, op)]) o
>   ++ checkParenConstrTerm Nothing t1 ++ checkParenConstrTerm Nothing t2
> checkParenConstrTerm _ (ParenPattern            t) =
>   checkParenConstrTerm Nothing t
> checkParenConstrTerm _ (TuplePattern         _ ts) =
>   concatMap (checkParenConstrTerm Nothing) ts
> checkParenConstrTerm _ (ListPattern          _ ts) =
>   concatMap (checkParenConstrTerm Nothing) ts
> checkParenConstrTerm o (AsPattern             _ t) =
>   checkParenConstrTerm o t
> checkParenConstrTerm o (LazyPattern           _ t) =
>   checkParenConstrTerm o t
> checkParenConstrTerm _ (FunctionPattern      _ ts) =
>   concatMap (checkParenConstrTerm Nothing) ts
> checkParenConstrTerm o (InfixFuncPattern t1 op t2) =
>   maybe [] (\c -> [(c, op)]) o
>   ++ checkParenConstrTerm Nothing t1 ++ checkParenConstrTerm Nothing t2
> checkParenConstrTerm _ (RecordPattern        fs t) =
>     maybe [] (checkParenConstrTerm Nothing) t
>     ++ concatMap (\(Field _ _ t') -> checkParenConstrTerm Nothing t') fs

> checkConstrTerm :: Position -> ConstrTerm -> SCM ConstrTerm
> checkConstrTerm _ (LiteralPattern        l) =
>   LiteralPattern `liftM` renameLiteral l
> checkConstrTerm _ (NegativePattern    op l) =
>   NegativePattern op `liftM` renameLiteral l
> checkConstrTerm p (VariablePattern       v)
>   | v == anonId = (VariablePattern . renameIdent v) `liftM` newId
>   | otherwise   = checkConstructorPattern p (qualify v) []
> checkConstrTerm p (ConstructorPattern c ts) =
>   checkConstructorPattern p c ts
> checkConstrTerm p (InfixPattern   t1 op t2) =
>   checkInfixPattern p t1 op t2
> checkConstrTerm p (ParenPattern          t) =
>   ParenPattern `liftM` checkConstrTerm p t
> checkConstrTerm p (TuplePattern     pos ts) =
>   TuplePattern pos `liftM` mapM (checkConstrTerm p) ts
> checkConstrTerm p (ListPattern      pos ts) =
>   ListPattern pos `liftM` mapM (checkConstrTerm p) ts
> checkConstrTerm p (AsPattern           v t) = do
>   liftM2 AsPattern (checkVar "@ pattern" v) (checkConstrTerm p t)
> checkConstrTerm p (LazyPattern       pos t) =
>   LazyPattern pos `liftM` checkConstrTerm p t
> checkConstrTerm p (RecordPattern      fs t) =
>   checkRecordPattern p fs t
> checkConstrTerm _ (FunctionPattern     _ _) = error $
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
536
>   "SyntaxCheck.checkConstrTerm: function pattern not defined"
Björn Peemöller 's avatar
Björn Peemöller committed
537
> checkConstrTerm _ (InfixFuncPattern  _ _ _) = error $
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
538
539
>   "SyntaxCheck.checkConstrTerm: infix function pattern not defined"

Björn Peemöller 's avatar
Björn Peemöller committed
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
> checkConstructorPattern :: Position -> QualIdent -> [ConstrTerm]
>                         -> SCM ConstrTerm
> checkConstructorPattern p c ts = do
>   env <- getRenameEnv
>   m <- getModuleIdent
>   k <- getCurrentId
>   case qualLookupVar c env of
>     [Constr n] -> do
>       when (n /= n') $ report $ errWrongArity c n n'
>       ConstructorPattern c `liftM` mapM (checkConstrTerm p) ts
>     [r] -> do
>       let n = arity r
>       if null ts && not (isQualified c)
>         then return $ VariablePattern $ renameIdent (varIdent r) k
>         else do
>           checkFuncPatsExtension p
>           ts' <- mapM (checkConstrTerm p) ts
>           if n' > n
>             then let (ts1, ts2) = splitAt n ts'
>                in  return $ genFuncPattAppl
>                      (FunctionPattern (qualVarIdent r) ts1) ts2
>             else return $ FunctionPattern (qualVarIdent r) ts'
>     rs -> case qualLookupVar (qualQualify m c) env of
>       [Constr n] -> do
>         when (n /= n') $ report $ errWrongArity c n n'
>         ConstructorPattern (qualQualify m c) `liftM` mapM (checkConstrTerm p) ts
>       [r] -> do
>         let n = arity r
>         if null ts && not (isQualified c)
>           then return $ VariablePattern $ renameIdent (varIdent r) k
>           else do
>             checkFuncPatsExtension p
>             ts' <- mapM (checkConstrTerm p) ts
>             if n' > n
>               then let (ts1,ts2) = splitAt n ts'
>                    in  return $ genFuncPattAppl
>                          (FunctionPattern (qualVarIdent r) ts1) ts2
>               else return $ FunctionPattern (qualVarIdent r) ts'
>       []
>         | null ts && not (isQualified c) ->
>             return (VariablePattern (renameIdent (unqualify c) k))
>         | null rs -> do
>             report $ errUndefinedData c
>             return $ ConstructorPattern c ts
>       _ -> do report $ errAmbiguousData c
>               return $ ConstructorPattern c ts
>   where n' = length ts

> checkInfixPattern :: Position -> ConstrTerm -> QualIdent -> ConstrTerm
>                   -> SCM ConstrTerm
> checkInfixPattern p t1 op t2 = do
>   m <- getModuleIdent
>   env <- getRenameEnv
>   case qualLookupVar op env of
>     [Constr n] -> do
>       when (n /= 2) $ report $ errWrongArity op n 2
>       liftM2 (flip InfixPattern op)
>              (checkConstrTerm p t1) (checkConstrTerm p t2)
>     [_] -> do
>       checkFuncPatsExtension p
>       liftM2 (flip InfixFuncPattern op)
>              (checkConstrTerm p t1) (checkConstrTerm p t2)
>     rs -> case qualLookupVar (qualQualify m op) env of
>       [Constr n] -> do
>         when (n /= 2) $ report $ errWrongArity op n 2
>         liftM2 (flip InfixPattern (qualQualify m op))
>                (checkConstrTerm p t1) (checkConstrTerm p t2)
>       [_] -> do
>         checkFuncPatsExtension p
>         liftM2 (flip InfixFuncPattern (qualQualify m op))
>                (checkConstrTerm p t1) (checkConstrTerm p t2)
>       [] | null rs -> do
>              report $ errUndefinedData op
>              return $ InfixPattern t1 op t2
>       _ -> do
>              report $ errAmbiguousData op
>              return $ InfixPattern t1 op t2

> checkRecordPattern :: Position -> [Field ConstrTerm] -> (Maybe ConstrTerm)
>                    -> SCM ConstrTerm
> checkRecordPattern p fs t = do
>   checkRecordExtension p
>   case fs of
>     [] -> report (errEmptyRecord p) >> return (RecordPattern fs t)
>     (Field _ l _ : _) -> do
>     env <- getRenameEnv
>     case lookupVar l env of
>       [RecordLabel r ls] -> do
>         when (isJust duplicate) $ report $ errDuplicateLabel
>                                               $ fromJust duplicate
>         if isNothing t
>           then do
>             when (not $ null missings) $ report $ errMissingLabel
>               (positionOfIdent l) (head missings) r "record pattern"
>             flip RecordPattern t `liftM` mapM (checkFieldPatt r) fs
>           else if t == Just (VariablePattern anonId)
>             then liftM2 RecordPattern
>                         (mapM (checkFieldPatt r) fs)
>                         (Just `liftM` checkConstrTerm p (fromJust t))
>             else do report (errIllegalRecordPattern p)
>                     return $ RecordPattern fs t
>         where ls'       = map fieldLabel fs
>               duplicate = findDouble ls'
>               missings  = ls \\ ls'
>       [] -> report (errUndefinedLabel l) >> return (RecordPattern fs t)
>       [_] -> report (errNotALabel l) >> return (RecordPattern fs t)
>       _   -> report (errDuplicateDefinition l) >> return (RecordPattern fs t)

> checkFieldPatt :: QualIdent -> Field ConstrTerm -> SCM (Field ConstrTerm)
> checkFieldPatt r (Field p l t) = do
>   env <- getRenameEnv
>   case lookupVar l env of
>     [RecordLabel r' _] -> when (r /= r') $ report $ errIllegalLabel l r
>     []  -> report $ errUndefinedLabel l
>     [_] -> report $ errNotALabel l
>     _   -> report $ errDuplicateDefinition l
>   Field p l `liftM` checkConstrTerm (positionOfIdent l) t

> -- Note: process decls first
> checkRhs :: Rhs -> SCM Rhs
> checkRhs (SimpleRhs p e ds) = inNestedEnv $ liftM2 (flip (SimpleRhs p))
>   (checkDeclGroup bindVarDecl ds) (checkExpr p e)
> checkRhs (GuardedRhs es ds) = inNestedEnv $ liftM2 (flip GuardedRhs)
>   (checkDeclGroup bindVarDecl ds) (mapM checkCondExpr es)

> checkCondExpr :: CondExpr -> SCM CondExpr
> checkCondExpr (CondExpr p g e) =
>   liftM2 (CondExpr p) (checkExpr p g) (checkExpr p e)

> checkExpr :: Position -> Expression -> SCM Expression
> checkExpr _ (Literal     l) = Literal       `liftM` renameLiteral l
> checkExpr _ (Variable    v) = checkVariable v
> checkExpr _ (Constructor c) = checkVariable c
> checkExpr p (Paren       e) = Paren         `liftM` checkExpr p e
> checkExpr p (Typed    e ty) = flip Typed ty `liftM` checkExpr p e
> checkExpr p (Tuple  pos es) = Tuple pos     `liftM` mapM (checkExpr p) es
> checkExpr p (List   pos es) = List pos      `liftM` mapM (checkExpr p) es
> checkExpr p (ListCompr      pos e qs) = inNestedEnv $
>   -- Note: must be flipped to insert qs into RenameEnv first
>   liftM2 (flip (ListCompr pos)) (mapM (checkStatement p) qs) (checkExpr p e)
> checkExpr p (EnumFrom              e) = EnumFrom `liftM` checkExpr p e
> checkExpr p (EnumFromThen      e1 e2) =
>   liftM2 EnumFromThen (checkExpr p e1) (checkExpr p e2)
> checkExpr p (EnumFromTo        e1 e2) =
>   liftM2 EnumFromTo (checkExpr p e1) (checkExpr p e2)
> checkExpr p (EnumFromThenTo e1 e2 e3) =
>   liftM3 EnumFromThenTo (checkExpr p e1) (checkExpr p e2) (checkExpr p e3)
> checkExpr p (UnaryMinus         op e) = UnaryMinus op `liftM` checkExpr p e
> checkExpr p (Apply             e1 e2) =
>   liftM2 Apply (checkExpr p e1) (checkExpr p e2)
> checkExpr p (InfixApply     e1 op e2) =
>   liftM3 InfixApply (checkExpr p e1) (checkOp op) (checkExpr p e2)
> checkExpr p (LeftSection        e op) =
>   liftM2 LeftSection (checkExpr p e) (checkOp op)
> checkExpr p (RightSection       op e) =
>   liftM2 RightSection (checkOp op) (checkExpr p e)
> checkExpr p (Lambda           r ts e) = inNestedEnv $
>   liftM2 (Lambda r) (mapM (checkArg p) ts) (checkExpr p e)
> checkExpr p (Let                ds e) = inNestedEnv $
>   liftM2 Let (checkDeclGroup bindVarDecl ds) (checkExpr p e)
> checkExpr p (Do                sts e) = inNestedEnv $
>   liftM2 Do (mapM (checkStatement p) sts) (checkExpr p e)
> checkExpr p (IfThenElse r e1 e2 e3) =
>   liftM3 (IfThenElse r) (checkExpr p e1) (checkExpr p e2) (checkExpr p e3)
> checkExpr p (Case r e alts) =
>   liftM2 (Case r) (checkExpr p e) (mapM checkAlt alts)
> checkExpr p rec@(RecordConstr   fs) = do
>   checkRecordExtension p
>   env <- getRenameEnv
>   case fs of
>     []              -> report (errEmptyRecord p) >> return rec
>     Field _ l _ : _ -> case lookupVar l env of
>       [RecordLabel r ls] -> do
>         when (not $ null duplicates) $ report $ errDuplicateLabel
>                                                    $ head duplicates
>         when (not $ null missings)   $ report $ errMissingLabel
>              (positionOfIdent l) (head missings) r "record construction"
>         RecordConstr `liftM` mapM (checkFieldExpr r) fs
>         where ls' = map fieldLabel fs
>               duplicates = maybeToList (findDouble ls')
>               missings = ls \\ ls'
>       []  -> report (errUndefinedLabel l)      >> return rec
>       [_] -> report (errNotALabel l)           >> return rec
>       _   -> report (errDuplicateDefinition l) >> return rec

> checkExpr p (RecordSelection e l) = do
>   checkRecordExtension p
>   env <- getRenameEnv
>   case lookupVar l env of
>     [RecordLabel _ _] -> return ()
>     []                -> report $ errUndefinedLabel l
>     [_]               -> report $ errNotALabel l
>     _                 -> report $ errDuplicateDefinition l
>   flip RecordSelection l `liftM` checkExpr p e
> checkExpr p rec@(RecordUpdate fs e) = do
>   checkRecordExtension p
>   env <- getRenameEnv
>   case fs of
>     []              -> report (errEmptyRecord p) >> return rec
>     Field _ l _ : _ -> case lookupVar l env of
>       [RecordLabel r _] -> do
>         when (not $ null duplicates) $ report $ errDuplicateLabel
>                                                    $ head duplicates
>         liftM2 RecordUpdate (mapM (checkFieldExpr r) fs)
>                             (checkExpr (positionOfIdent l) e)
>         where duplicates = maybeToList $ findDouble $ map fieldLabel fs
>       []  -> report (errUndefinedLabel l)      >> return rec
>       [_] -> report (errNotALabel l)           >> return rec
>       _   -> report (errDuplicateDefinition l) >> return rec

> checkVariable :: QualIdent -> SCM Expression
> checkVariable v
752
753
754
>   | unqualify v == anonId = do
>     checkAnonFreeVarsExtension $ positionOfQualIdent v
>     return $ Variable v
Björn Peemöller 's avatar
Björn Peemöller committed
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
>   | otherwise             = do
>     env <- getRenameEnv
>     case qualLookupVar v env of
>       []              -> do report $ errUndefinedVariable v
>                             return $ Variable v
>       [Constr _]      -> return $ Constructor v
>       [GlobalVar _ _] -> return $ Variable v
>       [LocalVar _ v'] -> return $ Variable $ qualify v'
>       rs -> do
>         m <- getModuleIdent
>         case qualLookupVar (qualQualify m v) env of
>           []              -> do report $ errAmbiguousIdent rs v
>                                 return $ Variable v
>           [Constr _]      -> return $ Constructor v
>           [GlobalVar _ _] -> return $ Variable v
>           [LocalVar _ v'] -> return $ Variable $ qualify v'
>           rs'             -> do report $ errAmbiguousIdent rs' v
>                                 return $ Variable v

> checkStatement :: Position -> Statement -> SCM Statement
> checkStatement p (StmtExpr   pos e) = StmtExpr pos `liftM` checkExpr p e
> checkStatement p (StmtBind pos t e) =
>   liftM2 (flip (StmtBind pos)) (checkExpr p e) (checkArg p t)
> checkStatement _ (StmtDecl      ds) =
>   StmtDecl `liftM` checkDeclGroup bindVarDecl ds

> checkArg :: Position -> ConstrTerm -> SCM ConstrTerm
> checkArg p t = do
>   t' <- checkConstrTerm p t
>   checkExprVariables t'
>   return t'

> checkOp :: InfixOp -> SCM InfixOp
> checkOp op = do
>   env <- getRenameEnv
>   case qualLookupVar v env of
>     []              -> report (errUndefinedVariable v) >> return op
>     [Constr _]      -> return $ InfixConstr v
>     [GlobalVar _ _] -> return $ InfixOp v
>     [LocalVar _ v'] -> return $ InfixOp $ qualify v'
>     rs              -> do
>       m <- getModuleIdent
>       case qualLookupVar (qualQualify m v) env of
>         []              -> report (errAmbiguousIdent rs v) >> return op
>         [Constr _]      -> return $ InfixConstr v
>         [GlobalVar _ _] -> return $ InfixOp v
>         [LocalVar _ v'] -> return $ InfixOp $ qualify v'
>         rs'             -> report (errAmbiguousIdent rs' v) >> return op
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
803
804
>   where v = opName op

Björn Peemöller 's avatar
Björn Peemöller committed
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
> checkAlt :: Alt -> SCM Alt
> checkAlt (Alt p t rhs) = inNestedEnv $
>   liftM2 (Alt p) (checkArg p t) (checkRhs rhs)

> checkExprVariables :: QuantExpr t => t -> SCM ()
> checkExprVariables ts = case findDouble bvs of
>   Nothing -> modifyRenameEnv $ \ env -> foldr bindVar env bvs
>   Just v  -> report $ errDuplicateVariable v
>   where bvs = bv ts

> checkFieldExpr :: QualIdent -> Field Expression -> SCM (Field Expression)
> checkFieldExpr r (Field p l e) = do
>   env <- getRenameEnv
>   case lookupVar l env of
>     [RecordLabel r' _] -> when (r /= r') $ report $ errIllegalLabel l r
>     []                 -> report $ errUndefinedLabel l
>     [_]                -> report $ errNotALabel l
>     _                  -> report $ errDuplicateDefinition l
>   Field p l `liftM` checkExpr (positionOfIdent l) e

Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
825
826
827
828
829
830
\end{verbatim}
Auxiliary definitions.
\begin{verbatim}

> constrs :: Decl -> [Ident]
> constrs (DataDecl _ _ _ cs) = map constr cs
Björn Peemöller 's avatar
Björn Peemöller committed
831
>   where constr (ConstrDecl   _ _ c _) = c
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
832
833
834
835
836
>         constr (ConOpDecl _ _ _ op _) = op
> constrs (NewtypeDecl _ _ _ (NewConstrDecl _ _ c _)) = [c]
> constrs _ = []

> vars :: Decl -> [Ident]
Björn Peemöller 's avatar
Björn Peemöller committed
837
838
839
> vars (TypeSig         _ fs _) = fs
> vars (EvalAnnot       _ fs _) = fs
> vars (FunctionDecl     _ f _) = [f]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
840
> vars (ExternalDecl _ _ _ f _) = [f]
Björn Peemöller 's avatar
Björn Peemöller committed
841
842
843
> vars (FlatExternalDecl  _ fs) = fs
> vars (PatternDecl      _ t _) = (bv t)
> vars (ExtraVariables    _ vs) = vs
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
844
845
> vars _ = []

Björn Peemöller 's avatar
Björn Peemöller committed
846
> renameLiteral :: Literal -> SCM Literal
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
847
848
849
850
851
852
853
> renameLiteral (Int v i) = liftM (flip Int i . renameIdent v) newId
> renameLiteral l = return l

Since the compiler expects all rules of the same function to be together,
it is necessary to sort the list of declarations.

> sortFuncDecls :: [Decl] -> [Decl]
Björn Peemöller 's avatar
Björn Peemöller committed
854
> sortFuncDecls decls = sortFD Set.empty [] decls
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
855
>  where
Björn Peemöller 's avatar
Björn Peemöller committed
856
857
858
859
860
861
862
863
>  sortFD _   res []              = reverse res
>  sortFD env res (decl : decls') = case decl of
>    FunctionDecl _ ident _
>     | ident `Set.member` env
>     -> sortFD env (insertBy cmpFuncDecl decl res) decls'
>     | otherwise
>     -> sortFD (Set.insert ident env) (decl:res) decls'
>    _    -> sortFD env (decl:res) decls'
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
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

> cmpFuncDecl :: Decl -> Decl -> Ordering
> cmpFuncDecl (FunctionDecl _ id1 _) (FunctionDecl _ id2 _)
>    | id1 == id2 = EQ
>    | otherwise  = GT
> cmpFuncDecl _ _ = GT

\end{verbatim}
Due to the lack of a capitalization convention in Curry, it is
possible that an identifier may ambiguously refer to a data
constructor and a function provided that both are imported from some
other module. When checking whether an identifier denotes a
constructor there are two options with regard to ambiguous
identifiers:
\begin{enumerate}
\item Handle the identifier as a data constructor if at least one of
  the imported names is a data constructor.
\item Handle the identifier as a data constructor only if all imported
  entities are data constructors.
\end{enumerate}
We choose the first possibility here because in the second case a
redefinition of a constructor can magically become possible if a
function with the same name is imported. It seems better to warn
the user about the fact that the identifier is ambiguous.
\begin{verbatim}

> isDataConstr :: Ident -> RenameEnv -> Bool
> isDataConstr v = any isConstr . lookupVar v . globalEnv . toplevelEnv

> isConstr :: RenameInfo -> Bool
Björn Peemöller 's avatar
Björn Peemöller committed
894
895
896
> isConstr (Constr        _) = True
> isConstr (GlobalVar   _ _) = False
> isConstr (LocalVar    _ _) = False
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
897
898
899
900
> isConstr (RecordLabel _ _) = False

> varIdent :: RenameInfo -> Ident
> varIdent (GlobalVar _ v) = unqualify v
Björn Peemöller 's avatar
Björn Peemöller committed
901
902
> varIdent (LocalVar  _ v) =  v
> varIdent _ = internalError "SyntaxCheck.varIdent: no variable"
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
903
904
905

> qualVarIdent :: RenameInfo -> QualIdent
> qualVarIdent (GlobalVar _ v) = v
Björn Peemöller 's avatar
Björn Peemöller committed
906
907
> qualVarIdent (LocalVar  _ v) = qualify v
> qualVarIdent _ = internalError "SyntaxCheck.qualVarIdent: no variable"
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
908
909

> arity :: RenameInfo -> Int
Björn Peemöller 's avatar
Björn Peemöller committed
910
911
912
> arity (Constr         n) = n
> arity (GlobalVar   n  _) = n
> arity (LocalVar    n  _) = n
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
913
914
915
916
> arity (RecordLabel _ ls) = length ls

\end{verbatim}
Unlike expressions, constructor terms have no possibility to represent
Björn Peemöller 's avatar
Björn Peemöller committed
917
over-applications in functional patterns. Therefore it is necessary to
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
918
919
920
921
922
923
924
transform them to nested
function patterns using the prelude function \texttt{apply}. E.g. the
the function pattern \texttt{(id id 10)} is transformed to
\texttt{(apply (id id) 10)}
\begin{verbatim}

> genFuncPattAppl :: ConstrTerm -> [ConstrTerm] -> ConstrTerm
Björn Peemöller 's avatar
Björn Peemöller committed
925
> genFuncPattAppl term []     = term
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
926
927
928
929
930
931
932
933
934
> genFuncPattAppl term (t:ts)
>    = FunctionPattern qApplyId [genFuncPattAppl term ts, t]
>  where
>  qApplyId = qualifyWith preludeMIdent (mkIdent "apply")

\end{verbatim}
Miscellaneous functions.
\begin{verbatim}

Björn Peemöller 's avatar
Björn Peemöller committed
935
936
937
> checkFuncPatsExtension :: Position -> SCM ()
> checkFuncPatsExtension p = do
>   funcPats <- hasExtension FunctionalPatterns
938
939
>   unless funcPats $ report $ errMissingLanguageExtension p
>     "Functional Patterns" FunctionalPatterns
Björn Peemöller 's avatar
Björn Peemöller committed
940
941
942
943

> checkRecordExtension :: Position -> SCM ()
> checkRecordExtension p = do
>   records <- hasExtension Records
944
945
946
947
948
949
950
951
>   unless records $ report $ errMissingLanguageExtension p
>     "Records" Records

> checkAnonFreeVarsExtension :: Position -> SCM ()
> checkAnonFreeVarsExtension p = do
>   anonFreeVars <- hasExtension AnonFreeVars
>   unless anonFreeVars $ report $ errMissingLanguageExtension p
>     "Anonymous free variables" AnonFreeVars
Björn Peemöller 's avatar
Björn Peemöller committed
952

Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
953
954
955
956
> typeArity :: TypeExpr -> Int
> typeArity (ArrowType _ t2) = 1 + typeArity t2
> typeArity _                = 0

Björn Peemöller 's avatar
Björn Peemöller committed
957
> getFlatLhs :: Equation -> (Ident, [ConstrTerm])
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
958
959
960
961
962
963
> getFlatLhs (Equation  _ lhs _) = flatLhs lhs

\end{verbatim}
Error messages.
\begin{verbatim}

Björn Peemöller 's avatar
Björn Peemöller committed
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
> errUndefinedVariable :: QualIdent -> Message
> errUndefinedVariable v = qposErr v $ qualName v ++ " is undefined"

> errUndefinedData :: QualIdent -> Message
> errUndefinedData c = qposErr c $ "Undefined data constructor " ++ qualName c

> errUndefinedLabel :: Ident -> Message
> errUndefinedLabel l = posErr l $ "Undefined record label `" ++ name l ++ "`"

> errAmbiguousIdent :: [RenameInfo] -> QualIdent -> Message
> errAmbiguousIdent rs
>   | any isConstr rs = errAmbiguousData
>   | otherwise       = errAmbiguousVariable

> errAmbiguousVariable :: QualIdent -> Message
> errAmbiguousVariable v = qposErr v $ "Ambiguous variable " ++ qualName v

> errAmbiguousData :: QualIdent -> Message
> errAmbiguousData c = qposErr c $ "Ambiguous data constructor " ++ qualName c

> errDuplicateDefinition :: Ident -> Message
> errDuplicateDefinition v = posErr v $
>   "More than one definition for `" ++ name v ++ "`"

> errDuplicateVariable :: Ident -> Message
> errDuplicateVariable v = posErr v $
>   name v ++ " occurs more than once in pattern"

> errMultipleDataConstructor :: [Ident] -> Message
> errMultipleDataConstructor [] = internalError
>   "SyntaxCheck.errMultipleDataDeclaration: empty list"
> errMultipleDataConstructor (i:is) = posErr i $
>   "Multiple definitions for data constructor `" ++ name i ++ "` at:\n"
>   ++ unlines (map showPos (i:is))
>   where showPos = ("    " ++) . showLine . positionOfIdent

> errDuplicateTypeSig :: Ident -> Message
> errDuplicateTypeSig v = posErr v $
>   "More than one type signature for `" ++ name v ++ "`"

> errDuplicateEvalAnnot :: Ident -> Message
> errDuplicateEvalAnnot v = posErr v $
>   "More than one eval annotation for `" ++ name v ++ "`"

> errDuplicateLabel :: Ident -> Message
> errDuplicateLabel l = posErr l $
>   "Multiple occurrence of record label `" ++ name l ++ "`"

> errMissingLabel :: Position -> Ident -> QualIdent -> String -> Message
> errMissingLabel p l r what = toMessage p $
>   "Missing label `" ++ name l
>   ++ "` in the " ++ what ++ " of `" ++ name (unqualify r) ++ "`"

> errIllegalLabel :: Ident -> QualIdent -> Message
> errIllegalLabel l r = posErr l $
>   "Label `" ++ name l ++ "` is not defined in record `"
Björn Peemöller 's avatar
Björn Peemöller committed
1020
>   ++ name (unqualify r) ++ "`"
Björn Peemöller 's avatar
Björn Peemöller committed
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049

> errIllegalRecordId :: Ident -> Message
> errIllegalRecordId r = posErr r $ "Record identifier `" ++ name r
>     ++ "` already assigned to a data constructor"

> errNonVariable :: String -> Ident -> Message
> errNonVariable what c = posErr c $
>   "Data constructor `" ++ name c ++ "` in left hand side of " ++ what

> errNoBody :: Ident -> Message
> errNoBody v = posErr v $ "No body for `" ++ name v ++ "`"

> errNoTypeSig :: Ident -> Message
> errNoTypeSig f = posErr f $
>   "No type signature for external function `" ++ name f ++ "`"

> errToplevelPattern :: Position -> Message
> errToplevelPattern p = toMessage p
>   "Pattern declaration not allowed at top-level"

> errNotALabel :: Ident -> Message
> errNotALabel l = posErr l $ "`" ++ name l ++ "` is not a record label"

> errDifferentArity :: Ident -> Message
> errDifferentArity f = posErr f $
>   "Equations for `" ++ name f ++ "` have different arities"

> errWrongArity :: QualIdent -> Int -> Int -> Message
> errWrongArity c arity' argc = qposErr c $
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
1050
>   "Data constructor " ++ qualName c ++ " expects " ++ arguments arity' ++
Björn Peemöller 's avatar
Björn Peemöller committed
1051
>   " but is applied to " ++ show argc
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
1052
1053
1054
1055
>   where arguments 0 = "no arguments"
>         arguments 1 = "1 argument"
>         arguments n = show n ++ " arguments"

Björn Peemöller 's avatar
Björn Peemöller committed
1056
1057
1058
1059
> errIllegalRecordPattern :: Position -> Message
> errIllegalRecordPattern p = toMessage p
>   "Expexting `_` after `|` in the record pattern"

1060
1061
1062
1063
> errMissingLanguageExtension :: Position -> String -> Extension -> Message
> errMissingLanguageExtension p what ext = toMessage p $
>   what ++ " are not supported in standard Curry."
>   ++ "\n  Use flag -e or -X" ++ show ext ++ " to enable this extension."
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
1064

Björn Peemöller 's avatar
Björn Peemöller committed
1065
1066
> errEmptyRecord :: Position -> Message
> errEmptyRecord p = toMessage p "empty records are not allowed"
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
1067

Björn Peemöller 's avatar
Björn Peemöller committed
1068
1069
1070
1071
1072
1073
> errInfixWithoutParens :: Position -> [(QualIdent, QualIdent)] -> Message
> errInfixWithoutParens p calls = toMessage p $
>   "Missing parens in infix patterns: \n" ++ unlines (map showCall calls)
>   where showCall (q1, q2) =
>           show q1 ++ " " ++ showLine (positionOfQualIdent q1)
>           ++ "calls " ++ show q2 ++ " " ++ showLine (positionOfQualIdent q2)
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
1074
1075

\end{verbatim}