WarnCheck.hs 27.2 KB
Newer Older
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
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
{- |WarnCheck - Searches for potentially irregular code and generates
                warning messages

    February 2006,
    Martin Engelke (men@informatik.uni-kiel.de)
-}
module Check.WarnCheck (warnCheck) where

import Control.Monad.State (State, execState, filterM, gets, modify, unless, when)
import qualified Data.Map as Map (empty, insert, lookup)
import Data.List (intersect, intersectBy, unionBy)

import Curry.Base.Ident
import Curry.Base.Position
import Curry.Base.MessageMonad
import Curry.Syntax

import Base.Value (ValueEnv, ValueInfo (..), qualLookupValue)
import Env.TopEnv
import qualified Env.ScopeEnv as ScopeEnv
import Env.ScopeEnv (ScopeEnv)


-- Data type for representing the current state of generating warnings.
-- The monadic representation of the state allows the usage of monadic
-- syntax (do expression) for dealing easier and safer with its
-- contents.
type CheckState = State CState

data CState = CState
31
  { messages  :: [Message]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
32
33
34
35
36
37
38
39
40
  , scope     :: ScopeEnv QualIdent IdInfo
  , values    :: ValueEnv
  , moduleId  :: ModuleIdent
  }

emptyState :: CState
emptyState = CState [] ScopeEnv.new emptyTopEnv (mkMIdent [])

-- |Run a 'CheckState' action and return the list of messages
41
run ::  CheckState a -> [Message]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
42
43
44
45
46
47
48
49
50
run f = reverse (messages (execState f emptyState))

-- Find potentially incorrect code in a Curry program and generate
-- the following warnings for:
--    - unreferenced variables
--    - shadowing variables
--    - idle case alternatives
--    - overlapping case alternatives
--    - function rules which are not together
51
warnCheck :: ModuleIdent -> ValueEnv -> [Decl] -> [Decl] -> [Message]
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
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
warnCheck mid vals imports decls = run $ do
  addImportedValues vals
  addModuleId mid
  checkImports imports
  foldM' insertDecl decls
  foldM' (checkDecl mid) decls
  checkDeclOccurrences decls

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

--
checkDecl :: ModuleIdent -> Decl -> CheckState ()
checkDecl mid (DataDecl _ _ params cdecls)
   = do beginScope
	foldM' insertTypeVar params
	foldM' (checkConstrDecl mid) cdecls
	params' <- filterM isUnrefTypeVar params
	when (not (null params'))
	     (foldM' genWarning' (map unrefTypeVar params'))
	endScope
checkDecl mid (TypeDecl _ _ params texpr)
   = do beginScope
	foldM' insertTypeVar params
	checkTypeExpr mid texpr
	params' <- filterM isUnrefTypeVar params
	when (not (null params'))
	     (foldM' genWarning'  (map unrefTypeVar params'))
	endScope
checkDecl mid (FunctionDecl _ ident equs)
   = do beginScope
	foldM' (checkEquation mid) equs
	c <- isConsId ident
	idents' <- returnUnrefVars
	when (not (c || null idents'))
             (foldM' genWarning' (map unrefVar idents'))
	endScope
checkDecl mid (PatternDecl _ cterm rhs)
   = do checkConstrTerm mid cterm
	checkRhs mid rhs
checkDecl _ _ = return ()

-- Checks locally declared identifiers (i.e. functions and logic variables)
-- for shadowing
checkLocalDecl :: Decl -> CheckState ()
checkLocalDecl (FunctionDecl _ ident _)
   = do s <- isShadowingVar ident
	when s (genWarning' (shadowingVar ident))
checkLocalDecl (ExtraVariables _ idents)
   = do idents' <- filterM isShadowingVar idents
	when (not (null idents'))
	     (foldM' genWarning' (map shadowingVar idents'))
checkLocalDecl (PatternDecl _ constrTerm _)
   = checkConstrTerm (mkMIdent []) constrTerm
checkLocalDecl _ = return ()

--
checkConstrDecl :: ModuleIdent -> ConstrDecl -> CheckState ()
checkConstrDecl mid (ConstrDecl _ _ ident texprs)
   = do visitId ident
	foldM' (checkTypeExpr mid) texprs
checkConstrDecl mid (ConOpDecl _ _ texpr1 ident texpr2)
   = do visitId ident
	checkTypeExpr mid texpr1
	checkTypeExpr mid texpr2


checkTypeExpr :: ModuleIdent -> TypeExpr -> CheckState ()
checkTypeExpr mid (ConstructorType qid texprs)
   = do maybe (return ()) visitTypeId (localIdent mid qid)
	foldM' (checkTypeExpr mid ) texprs
checkTypeExpr _  (VariableType ident)
   = visitTypeId ident
checkTypeExpr mid  (TupleType texprs)
   = foldM' (checkTypeExpr mid ) texprs
checkTypeExpr mid  (ListType texpr)
   = checkTypeExpr mid  texpr
checkTypeExpr mid  (ArrowType texpr1 texpr2)
   = do checkTypeExpr mid  texpr1
	checkTypeExpr mid  texpr2
checkTypeExpr mid  (RecordType fields restr)
   = do foldM' (checkTypeExpr mid ) (map snd fields)
	maybe (return ()) (checkTypeExpr mid ) restr

--
checkEquation :: ModuleIdent -> Equation -> CheckState ()
checkEquation mid (Equation _ lhs rhs)
   = do checkLhs mid lhs
	checkRhs mid rhs

--
checkLhs :: ModuleIdent -> Lhs -> CheckState ()
checkLhs mid (FunLhs ident cterms)
   = do visitId ident
	foldM' (checkConstrTerm mid) cterms
	foldM' (insertConstrTerm False) cterms
checkLhs mid (OpLhs cterm1 ident cterm2)
   = checkLhs mid (FunLhs ident [cterm1, cterm2])
checkLhs mid (ApLhs lhs cterms)
   = do checkLhs mid lhs
	foldM' (checkConstrTerm mid ) cterms
	foldM' (insertConstrTerm False) cterms

--
checkRhs :: ModuleIdent -> Rhs -> CheckState ()
checkRhs mid (SimpleRhs _ expr decls)
   = do beginScope  -- function arguments can be overwritten by local decls
	foldM' checkLocalDecl decls
	foldM' insertDecl decls
	foldM' (checkDecl mid) decls
	checkDeclOccurrences decls
	checkExpression mid expr
	idents' <- returnUnrefVars
	when (not (null idents'))
	     (foldM' genWarning' (map unrefVar idents'))
	endScope
checkRhs mid (GuardedRhs cexprs decls)
   = do beginScope
	foldM' checkLocalDecl decls
	foldM' insertDecl decls
	foldM' (checkDecl mid) decls
	checkDeclOccurrences decls
	foldM' (checkCondExpr mid) cexprs
	idents' <- returnUnrefVars
	when (not (null idents'))
	     (foldM' genWarning' (map unrefVar idents'))
	endScope


--
checkCondExpr :: ModuleIdent -> CondExpr -> CheckState ()
checkCondExpr mid (CondExpr _ cond expr)
   = do checkExpression mid cond
	checkExpression mid expr

--
checkConstrTerm :: ModuleIdent -> ConstrTerm -> CheckState ()
checkConstrTerm _ (VariablePattern ident)
   = do s <- isShadowingVar ident
	when s (genWarning' (shadowingVar ident))
checkConstrTerm mid (ConstructorPattern _ cterms)
   = foldM' (checkConstrTerm mid ) cterms
checkConstrTerm mid (InfixPattern cterm1 qident cterm2)
   = checkConstrTerm mid (ConstructorPattern qident [cterm1, cterm2])
checkConstrTerm mid (ParenPattern cterm)
   = checkConstrTerm mid cterm
checkConstrTerm mid (TuplePattern _ cterms)
   = foldM' (checkConstrTerm mid ) cterms
checkConstrTerm mid (ListPattern _ cterms)
   = foldM' (checkConstrTerm mid ) cterms
checkConstrTerm mid (AsPattern ident cterm)
   = do s <- isShadowingVar ident
	when s (genWarning' (shadowingVar ident))
	checkConstrTerm mid cterm
checkConstrTerm mid (LazyPattern _ cterm)
   = checkConstrTerm mid cterm
checkConstrTerm mid (FunctionPattern _ cterms)
   = foldM' (checkConstrTerm mid ) cterms
checkConstrTerm mid  (InfixFuncPattern cterm1 qident cterm2)
   = checkConstrTerm mid  (FunctionPattern qident [cterm1, cterm2])
checkConstrTerm mid  (RecordPattern fields restr)
   = do foldM' (checkFieldPattern mid) fields
	maybe (return ()) (checkConstrTerm mid ) restr
checkConstrTerm _ _ = return ()

--
checkExpression :: ModuleIdent -> Expression -> CheckState ()
checkExpression mid (Variable qident)
   = maybe (return ()) visitId (localIdent mid qident)
checkExpression mid (Paren expr)
   = checkExpression mid expr
checkExpression mid (Typed expr _)
   = checkExpression mid expr
checkExpression mid (Tuple _ exprs)
   = foldM' (checkExpression mid ) exprs
checkExpression mid (List _ exprs)
   = foldM' (checkExpression mid ) exprs
checkExpression mid (ListCompr _ expr stmts)
   = do beginScope
	foldM' (checkStatement mid ) stmts
	checkExpression mid expr
	idents' <- returnUnrefVars
	when (not (null idents'))
	     (foldM' genWarning' (map unrefVar idents'))
	endScope
checkExpression mid  (EnumFrom expr)
   = checkExpression mid  expr
checkExpression mid  (EnumFromThen expr1 expr2)
   = foldM' (checkExpression mid ) [expr1, expr2]
checkExpression mid  (EnumFromTo expr1 expr2)
   = foldM' (checkExpression mid ) [expr1, expr2]
checkExpression mid  (EnumFromThenTo expr1 expr2 expr3)
   = foldM' (checkExpression mid ) [expr1, expr2, expr3]
checkExpression mid  (UnaryMinus _ expr)
   = checkExpression mid  expr
checkExpression mid  (Apply expr1 expr2)
   = foldM' (checkExpression mid ) [expr1, expr2]
checkExpression mid  (InfixApply expr1 op expr2)
   = do maybe (return ()) (visitId) (localIdent mid (opName op))
	foldM' (checkExpression mid ) [expr1, expr2]
checkExpression mid  (LeftSection expr _)
   = checkExpression mid  expr
checkExpression mid  (RightSection _ expr)
   = checkExpression mid  expr
checkExpression mid  (Lambda _ cterms expr)
   = do beginScope
	foldM' (checkConstrTerm mid ) cterms
	foldM' (insertConstrTerm False) cterms
	checkExpression mid expr
	idents' <- returnUnrefVars
	when (not (null idents'))
	     (foldM' genWarning' (map unrefVar idents'))
	endScope
checkExpression mid  (Let decls expr)
   = do beginScope
	foldM' checkLocalDecl decls
	foldM' insertDecl decls
	foldM' (checkDecl mid) decls
	checkDeclOccurrences decls
	checkExpression mid  expr
	idents' <- returnUnrefVars
	when (not (null idents'))
	     (foldM' genWarning' (map unrefVar idents'))
	endScope
checkExpression mid  (Do stmts expr)
   = do beginScope
	foldM' (checkStatement mid ) stmts
	checkExpression mid  expr
	idents' <- returnUnrefVars
	when (not (null idents'))
	     (foldM' genWarning' (map unrefVar idents'))
	endScope
checkExpression mid  (IfThenElse _ expr1 expr2 expr3)
   = foldM' (checkExpression mid ) [expr1, expr2, expr3]
checkExpression mid  (Case _ expr alts)
   = do checkExpression mid  expr
	foldM' (checkAlt mid) alts
	checkCaseAlternatives mid alts
checkExpression mid (RecordConstr fields)
   = foldM' (checkFieldExpression mid) fields
checkExpression mid (RecordSelection expr _)
   = checkExpression mid expr -- Hier auch "visitId ident" ?
checkExpression mid (RecordUpdate fields expr)
   = do foldM' (checkFieldExpression mid) fields
	checkExpression mid expr
checkExpression _ _  = return ()

--
checkStatement :: ModuleIdent -> Statement -> CheckState ()
checkStatement mid (StmtExpr _ expr)
   = checkExpression mid expr
checkStatement mid (StmtDecl decls)
   = do foldM' checkLocalDecl decls
	foldM' insertDecl decls
	foldM' (checkDecl mid) decls
	checkDeclOccurrences decls
checkStatement mid (StmtBind _ cterm expr)
   = do checkConstrTerm mid cterm
	insertConstrTerm False cterm
	checkExpression mid expr

--
checkAlt :: ModuleIdent -> Alt -> CheckState ()
checkAlt mid (Alt _ cterm rhs)
   = do beginScope
	checkConstrTerm mid  cterm
	insertConstrTerm False cterm
	checkRhs mid rhs
	idents' <-  returnUnrefVars
	when (not (null idents'))
	     (foldM' genWarning' (map unrefVar idents'))
	endScope

--
checkFieldExpression :: ModuleIdent -> Field Expression -> CheckState ()
checkFieldExpression mid (Field _ _ expr)
   = checkExpression mid expr -- Hier auch "visitId ident" ?

--
checkFieldPattern :: ModuleIdent -> Field ConstrTerm -> CheckState ()
checkFieldPattern mid (Field _ _ cterm)
   = checkConstrTerm mid  cterm

-- Check for idle and overlapping case alternatives
checkCaseAlternatives :: ModuleIdent -> [Alt] -> CheckState ()
checkCaseAlternatives mid alts
   = do checkIdleAlts mid alts
	checkOverlappingAlts mid alts

--
-- FIXME this looks buggy: is alts' required to be non-null or not? (hsi)
checkIdleAlts :: ModuleIdent -> [Alt] -> CheckState ()
checkIdleAlts _ alts
   = do alts' <- dropUnless' isVarAlt alts
	let idles = tail_ [] alts'
	    (Alt pos _ _) = head idles
	unless (null idles) (genWarning pos idleCaseAlts)
 where
 isVarAlt (Alt _ (VariablePattern ident) _)
    = isVarId ident
 isVarAlt (Alt _ (ParenPattern (VariablePattern ident)) _)
    = isVarId ident
 isVarAlt (Alt _ (AsPattern _ (VariablePattern ident)) _)
    = isVarId ident
 isVarAlt _ = return False

--
checkOverlappingAlts :: ModuleIdent -> [Alt] -> CheckState ()
checkOverlappingAlts _ [] = return ()
checkOverlappingAlts mid (alt:alts)
   = do (altsr, alts') <- partition' (equalAlts alt) alts
        mapM_ (\ (Alt pos _ _) -> genWarning pos overlappingCaseAlt) altsr
	checkOverlappingAlts mid alts'
 where
 equalAlts (Alt _ cterm1 _) (Alt _ cterm2 _) = equalConstrTerms cterm1 cterm2

 equalConstrTerms (LiteralPattern l1) (LiteralPattern l2)
    = return (l1 == l2)
 equalConstrTerms (NegativePattern id1 l1) (NegativePattern id2 l2)
    = return (id1 == id2 && l1 == l2)
 equalConstrTerms (VariablePattern id1) (VariablePattern id2)
    = do p <- isConsId id1
	 return (p && id1 == id2)
 equalConstrTerms (ConstructorPattern qid1 cs1)
		  (ConstructorPattern qid2 cs2)
    = if qid1 == qid2
      then all' (\ (c1,c2) -> equalConstrTerms c1 c2) (zip cs1 cs2)
      else return False
 equalConstrTerms (InfixPattern lcs1 qid1 rcs1)
		  (InfixPattern lcs2 qid2 rcs2)
    = equalConstrTerms (ConstructorPattern qid1 [lcs1, rcs1])
                       (ConstructorPattern qid2 [lcs2, rcs2])
 equalConstrTerms (ParenPattern cterm1) (ParenPattern cterm2)
    = equalConstrTerms cterm1 cterm2
 equalConstrTerms (TuplePattern _ cs1) (TuplePattern _ cs2)
    = equalConstrTerms (ConstructorPattern (qTupleId 2) cs1)
                       (ConstructorPattern (qTupleId 2) cs2)
 equalConstrTerms (ListPattern _ cs1) (ListPattern _ cs2)
    = cmpListM equalConstrTerms cs1 cs2
 equalConstrTerms (AsPattern _ cterm1) (AsPattern _ cterm2)
    = equalConstrTerms cterm1 cterm2
 equalConstrTerms (LazyPattern _ cterm1) (LazyPattern _ cterm2)
    = equalConstrTerms cterm1 cterm2
 equalConstrTerms _ _ = return False


-- Find function rules which are not together
checkDeclOccurrences :: [Decl] -> CheckState ()
checkDeclOccurrences decls = checkDO (mkIdent "") Map.empty decls
 where
 checkDO _ _ [] = return ()
 checkDO prevId env ((FunctionDecl pos ident _):decls')
    = do c <- isConsId ident
	 if not (c || prevId == ident)
          then (maybe (checkDO ident (Map.insert ident pos env) decls')
	              (\pos' -> genWarning' (rulesNotTogether ident pos')
		                >> checkDO ident env decls')
	              (Map.lookup ident env))
	  else checkDO ident env decls'
 checkDO _ env (_:decls')
    = checkDO (mkIdent "") env decls'


-- check import declarations for multiply imported modules
checkImports :: [Decl] -> CheckState ()
checkImports imps = checkImps Map.empty imps
 where
 checkImps _ [] = return ()
 checkImps env ((ImportDecl pos mid _ _ spec):imps')
    | mid /= preludeMIdent
      = maybe (checkImps (Map.insert mid (fromImpSpec spec) env) imps')
              (\ishs -> checkImpSpec env pos mid ishs spec
	                >>= (\env' -> checkImps env' imps'))
	      (Map.lookup mid env)
    | otherwise
      = checkImps env imps'
 checkImps env (_:imps') = checkImps env imps'

 checkImpSpec env _ mid (_,_) Nothing
    = genWarning' (multiplyImportedModule mid) >> return env
 checkImpSpec env _ mid (is,hs) (Just (Importing _ is'))
    | null is && any (\i' -> notElem i' hs) is'
      = do genWarning' (multiplyImportedModule mid)
	   return (Map.insert mid (is',hs) env)
    | null iis
      = return (Map.insert mid (is' ++ is,hs) env)
    | otherwise
      = do foldM' genWarning'
		  (map ((multiplyImportedSymbol mid) . impName) iis)
	   return (Map.insert mid (unionBy cmpImport is' is,hs) env)
  where iis = intersectBy cmpImport is' is
 checkImpSpec env _ mid (is,hs) (Just (Hiding _ hs'))
    | null ihs
      = return (Map.insert mid (is,hs' ++ hs) env)
    | otherwise
      = do foldM' genWarning'
		  (map ((multiplyHiddenSymbol mid) . impName) ihs)
	   return (Map.insert mid (is,unionBy cmpImport hs' hs) env)
  where ihs = intersectBy cmpImport hs' hs

 cmpImport (ImportTypeWith id1 cs1) (ImportTypeWith id2 cs2)
    = id1 == id2 && null (intersect cs1 cs2)
 cmpImport i1 i2 = (impName i1) == (impName i2)

 impName (Import ident)           = ident
 impName (ImportTypeAll ident)    = ident
 impName (ImportTypeWith ident _) = ident

 fromImpSpec Nothing                 = ([],[])
 fromImpSpec (Just (Importing _ is)) = (is,[])
 fromImpSpec (Just (Hiding _ hs))    = ([],hs)


-------------------------------------------------------------------------------
-- For detecting unreferenced variables, the following functions updates the
-- current check state by adding identifiers occuring in declaration left hand
-- sides.

--
insertDecl :: Decl -> CheckState ()
insertDecl (DataDecl _ ident _ cdecls)
   = do insertTypeConsId ident
	foldM' insertConstrDecl cdecls
insertDecl (TypeDecl _ ident _ texpr)
   = do insertTypeConsId ident
	insertTypeExpr texpr
insertDecl (FunctionDecl _ ident _)
   = do c <- isConsId ident
	unless c (insertVar ident)
insertDecl (ExternalDecl _ _ _ ident _)
   = insertVar ident
insertDecl (FlatExternalDecl _ idents)
   = foldM' insertVar idents
insertDecl (PatternDecl _ cterm _)
   = insertConstrTerm False cterm
insertDecl (ExtraVariables _ idents)
   = foldM' insertVar idents
insertDecl _ = return ()

--
insertTypeExpr :: TypeExpr -> CheckState ()
insertTypeExpr (VariableType _) = return ()
insertTypeExpr (ConstructorType _ texprs)
   = foldM' insertTypeExpr texprs
insertTypeExpr (TupleType texprs)
   = foldM' insertTypeExpr texprs
insertTypeExpr (ListType texpr)
   = insertTypeExpr texpr
insertTypeExpr (ArrowType texpr1 texpr2)
   = foldM' insertTypeExpr [texpr1,texpr2]
insertTypeExpr (RecordType _ restr)
   = do --foldM' insertVar (concatMap fst fields)
	maybe (return ()) insertTypeExpr restr

--
insertConstrDecl :: ConstrDecl -> CheckState ()
insertConstrDecl (ConstrDecl _ _ ident _)
   = insertConsId ident
insertConstrDecl (ConOpDecl _ _ _ ident _)
   = insertConsId ident

-- Notes:
--    - 'fp' indicates whether 'checkConstrTerm' deals with the arguments
--      of a function pattern or not.
--    - Since function patterns are not recognized before syntax check, it is
--      necessary to determine, whether a constructor pattern represents a
--      constructor or a function.
insertConstrTerm :: Bool -> ConstrTerm -> CheckState ()
insertConstrTerm fp (VariablePattern ident)
   | fp        = do c <- isConsId ident
		    v <- isVarId ident
		    unless c (if (name ident) /= "_" && v
			         then visitId ident
			         else insertVar ident)
   | otherwise = do c <- isConsId ident
	            unless c (insertVar ident)
insertConstrTerm fp (ConstructorPattern qident cterms)
   = do c <- isQualConsId qident
	if c then foldM' (insertConstrTerm fp) cterms
	     else foldM' (insertConstrTerm True) cterms
insertConstrTerm fp (InfixPattern cterm1 qident cterm2)
   = insertConstrTerm fp (ConstructorPattern qident [cterm1, cterm2])
insertConstrTerm fp (ParenPattern cterm)
   = insertConstrTerm fp cterm
insertConstrTerm fp (TuplePattern _ cterms)
   = foldM' (insertConstrTerm fp) cterms
insertConstrTerm fp (ListPattern _ cterms)
   = foldM' (insertConstrTerm fp) cterms
insertConstrTerm fp (AsPattern ident cterm)
   = do insertVar ident
	insertConstrTerm fp cterm
insertConstrTerm fp (LazyPattern _ cterm)
   = insertConstrTerm fp cterm
insertConstrTerm _ (FunctionPattern _ cterms)
   = foldM' (insertConstrTerm True) cterms
insertConstrTerm _ (InfixFuncPattern cterm1 qident cterm2)
   = insertConstrTerm True (FunctionPattern qident [cterm1, cterm2])
insertConstrTerm fp (RecordPattern fields restr)
   = do foldM' (insertFieldPattern fp) fields
	maybe (return ()) (insertConstrTerm fp) restr
insertConstrTerm _ _ = return ()

--
insertFieldPattern :: Bool -> Field ConstrTerm -> CheckState ()
insertFieldPattern fp (Field _ _ cterm)
   = insertConstrTerm fp cterm

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

-- Data type for distinguishing identifiers as either (type) constructors or
-- (type) variables (including functions).
-- The Boolean flag in 'VarInfo' is used to mark variables when they are used
-- within expressions.
data IdInfo = ConsInfo | VarInfo Bool deriving Show

--
isVariable :: IdInfo -> Bool
isVariable (VarInfo _) = True
isVariable _           = False

--
isConstructor :: IdInfo -> Bool
isConstructor ConsInfo = True
isConstructor _        = False

--
variableVisited :: IdInfo -> Bool
variableVisited (VarInfo v) = v
variableVisited _           = True

--
visitVariable :: IdInfo -> IdInfo
visitVariable info = case info of
		       VarInfo _ -> VarInfo True
		       _         -> info


--
modifyScope :: (ScopeEnv QualIdent IdInfo -> ScopeEnv QualIdent IdInfo)
	       -> CState -> CState
modifyScope f state = state{ scope = f (scope state) }


--
genWarning :: Position -> String -> CheckState ()
genWarning pos msg
   = modify (\state -> state{ messages = warnMsg:(messages state) })
599
 where warnMsg = Message (Just pos) msg
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
600
601
602
603

genWarning' :: (Position, String) -> CheckState ()
genWarning' (pos, msg)
   = modify (\state -> state{ messages = warnMsg:(messages state) })
604
    where warnMsg = Message (Just pos) msg
Bjoern Peemoeller's avatar
Bjoern Peemoeller committed
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
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
779
780
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

--
insertVar :: Ident -> CheckState ()
insertVar ident
   | isAnnonId ident = return ()
   | otherwise
     = modify
         (\state -> modifyScope
	              (ScopeEnv.insert (commonId ident) (VarInfo False)) state)

--
insertTypeVar :: Ident -> CheckState ()
insertTypeVar ident
   | isAnnonId ident = return ()
   | otherwise
     = modify
         (\state -> modifyScope
	              (ScopeEnv.insert (typeId ident) (VarInfo False)) state)

--
insertConsId :: Ident -> CheckState ()
insertConsId ident
   = modify
       (\state -> modifyScope (ScopeEnv.insert (commonId ident) ConsInfo) state)

--
insertTypeConsId :: Ident -> CheckState ()
insertTypeConsId ident
   = modify
       (\state -> modifyScope (ScopeEnv.insert (typeId ident) ConsInfo) state)

--
isVarId :: Ident -> CheckState Bool
isVarId ident
   = gets (\state -> isVar state (commonId ident))

--
isConsId :: Ident -> CheckState Bool
isConsId ident
   = gets (\state -> isCons state (qualify ident))

--
isQualConsId :: QualIdent -> CheckState Bool
isQualConsId qid
   = gets (\state -> isCons state qid)

--
isShadowingVar :: Ident -> CheckState Bool
isShadowingVar ident
   = gets (\state -> isShadowing state (commonId ident))

--
visitId :: Ident -> CheckState ()
visitId ident
   = modify
       (\state -> modifyScope
	            (ScopeEnv.modify visitVariable (commonId ident)) state)

--
visitTypeId :: Ident -> CheckState ()
visitTypeId ident
   = modify
       (\state -> modifyScope
	            (ScopeEnv.modify visitVariable (typeId ident)) state)

--
isUnrefTypeVar :: Ident -> CheckState Bool
isUnrefTypeVar ident
   = gets (\state -> isUnref state (typeId ident))

--
returnUnrefVars :: CheckState [Ident]
returnUnrefVars
   = gets (\state ->
	   	    let ids    = map fst (ScopeEnv.toLevelList (scope state))
                        unrefs = filter (isUnref state) ids
	            in  map unqualify unrefs )

--
addModuleId :: ModuleIdent -> CheckState ()
addModuleId mid = modify (\state -> state{ moduleId = mid })

--

-- withScope :: CheckState a -> CheckState ()
-- withScope m = beginScope >> m >> endScope

--
beginScope :: CheckState ()
beginScope = modify (\state -> modifyScope ScopeEnv.beginScope state)

--
endScope :: CheckState ()
endScope = modify (\state -> modifyScope ScopeEnv.endScopeUp state)


-- Adds the content of a value environment to the state
addImportedValues :: ValueEnv -> CheckState ()
addImportedValues vals = modify (\state -> state{ values = vals })

--
foldM' :: (a -> CheckState ()) -> [a] -> CheckState ()
foldM' _ [] = return ()
foldM' f (x:xs) = f x >> foldM' f xs

--
dropUnless' :: (a -> CheckState Bool) -> [a] -> CheckState [a]
dropUnless' _ [] = return []
dropUnless' mpred (x:xs)
   = do p <- mpred x
	if p then return (x:xs) else dropUnless' mpred xs

--
partition' :: (a -> CheckState Bool) -> [a] -> CheckState ([a],[a])
partition' mpred xs' = part mpred [] [] xs'
 where
 part _ ts fs [] = return (reverse ts, reverse fs)
 part mpred' ts fs (x:xs)
   = do p <- mpred' x
	if p then part mpred' (x:ts) fs xs
	     else part mpred' ts (x:fs) xs

--
all' :: (a -> CheckState Bool) -> [a] -> CheckState Bool
all' _ [] = return True
all' mpred (x:xs)
   = do p <- mpred x
	if p then all' mpred xs else return False



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

--
isShadowing :: CState -> QualIdent -> Bool
isShadowing state qid
   = let sc = scope state
     in  maybe False isVariable (ScopeEnv.lookup qid sc)
	 && ScopeEnv.level qid sc < ScopeEnv.currentLevel sc

--
isUnref :: CState -> QualIdent -> Bool
isUnref state qid
   = let sc = scope state
     in  maybe False (not . variableVisited) (ScopeEnv.lookup qid sc)
         && ScopeEnv.level qid sc == ScopeEnv.currentLevel sc

--
isVar :: CState -> QualIdent -> Bool
isVar state qid = maybe (isAnnonId (unqualify qid))
	           isVariable
		   (ScopeEnv.lookup qid (scope state))

--
isCons :: CState -> QualIdent -> Bool
isCons state qid = maybe (isImportedCons state qid)
		         isConstructor
			 (ScopeEnv.lookup qid (scope state))
 where
 isImportedCons state' qid'
    = case (qualLookupValue qid' (values state')) of
        (DataConstructor _ _):_    -> True
        (NewtypeConstructor _ _):_ -> True
        _                          -> False


--
isAnnonId :: Ident -> Bool
isAnnonId ident = (name ident) == "_"


-- Since type identifiers and normal identifiers (e.g. functions, variables
-- or constructors) don't share the same namespace, it is necessary
-- to distinguish them in the scope environment of the check state.
-- For this reason type identifiers are annotated with 1 and normal
-- identifiers are annotated with 0.
--
commonId :: Ident -> QualIdent
commonId ident = qualify (unRenameIdent ident)

--
typeId :: Ident -> QualIdent
typeId ident = qualify (renameIdent ident 1)


-------------------------------------------------------------------------------
-- Warnings...

unrefTypeVar :: Ident -> (Position, String)
unrefTypeVar ident =
  (positionOfIdent ident,
   "unreferenced type variable \"" ++ show ident ++ "\"")

unrefVar :: Ident -> (Position, String)
unrefVar ident =
  (positionOfIdent ident,
   "unused declaration of variable \"" ++ show ident ++ "\"")

shadowingVar :: Ident -> (Position, String)
shadowingVar ident =
  (positionOfIdent ident,
   "shadowing symbol \"" ++ show ident ++ "\"")

idleCaseAlts :: String
idleCaseAlts = "idle case alternative(s)"

overlappingCaseAlt :: String
overlappingCaseAlt = "redundant overlapping case alternative"

rulesNotTogether :: Ident -> Position -> (Position, String)
rulesNotTogether ident pos
  = (positionOfIdent ident,
     "rules for function \"" ++ show ident ++ "\" "
     ++ "are not together "
     ++ "(first occurrence at "
     ++ show (line pos) ++ "." ++ show (column pos) ++ ")")

multiplyImportedModule :: ModuleIdent -> (Position, String)
multiplyImportedModule mid
  = (positionOfModuleIdent mid,
     "module \"" ++ show mid ++ "\" was imported more than once")

multiplyImportedSymbol :: ModuleIdent -> Ident -> (Position, String)
multiplyImportedSymbol mid ident
  = (positionOfIdent ident,
     "symbol \"" ++ show ident ++ "\" was imported from module \""
     ++ show mid ++ "\" more than once")

multiplyHiddenSymbol :: ModuleIdent -> Ident -> (Position, String)
multiplyHiddenSymbol mid ident
  = (positionOfIdent ident,
     "symbol \"" ++ show ident ++ "\" from module \"" ++ show mid
     ++ "\" was hidden more than once")


-------------------------------------------------------------------------------
-- Miscellaneous

-- safer versions of 'tail' and 'head'
tail_ :: [a] -> [a] -> [a]
tail_ alt []     = alt
tail_ _   (_:xs) = xs


--
cmpListM :: Monad m => (a -> a -> m Bool) -> [a] -> [a] -> m Bool
cmpListM _ []     []     = return True
cmpListM cmpM (x:xs) (y:ys) = do c <- cmpM x y
				 if c then cmpListM cmpM xs ys
				      else return False
cmpListM _ _      _      = return False