(F)SLIT -> (f)sLit in DsUtils
[ghc-hetmet.git] / compiler / deSugar / Check.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1997-1998
4 %
5 % Author: Juan J. Quintela    <quintela@krilin.dc.fi.udc.es>
6
7 \begin{code}
8 {-# OPTIONS -fno-warn-incomplete-patterns #-}
9 -- The above warning supression flag is a temporary kludge.
10 -- While working on this module you are encouraged to remove it and fix
11 -- any warnings in the module. See
12 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
13 -- for details
14
15 module Check ( check , ExhaustivePat ) where
16
17 #include "HsVersions.h"
18
19 import HsSyn            
20 import TcHsSyn
21 import DsUtils
22 import MatchLit
23 import Id
24 import DataCon
25 import Name
26 import TysWiredIn
27 import PrelNames
28 import TyCon
29 import SrcLoc
30 import UniqSet
31 import Util
32 import Outputable
33 import FastString
34 \end{code}
35
36 This module performs checks about if one list of equations are:
37 \begin{itemize}
38 \item Overlapped
39 \item Non exhaustive
40 \end{itemize}
41 To discover that we go through the list of equations in a tree-like fashion.
42
43 If you like theory, a similar algorithm is described in:
44 \begin{quotation}
45         {\em Two Techniques for Compiling Lazy Pattern Matching},
46         Luc Maranguet,
47         INRIA Rocquencourt (RR-2385, 1994)
48 \end{quotation}
49 The algorithm is based on the first technique, but there are some differences:
50 \begin{itemize}
51 \item We don't generate code
52 \item We have constructors and literals (not only literals as in the 
53           article)
54 \item We don't use directions, we must select the columns from 
55           left-to-right
56 \end{itemize}
57 (By the way the second technique is really similar to the one used in 
58  @Match.lhs@ to generate code)
59
60 This function takes the equations of a pattern and returns:
61 \begin{itemize}
62 \item The patterns that are not recognized
63 \item The equations that are not overlapped
64 \end{itemize}
65 It simplify the patterns and then call @check'@ (the same semantics), and it 
66 needs to reconstruct the patterns again ....
67
68 The problem appear with things like:
69 \begin{verbatim}
70   f [x,y]   = ....
71   f (x:xs)  = .....
72 \end{verbatim}
73 We want to put the two patterns with the same syntax, (prefix form) and 
74 then all the constructors are equal:
75 \begin{verbatim}
76   f (: x (: y []))   = ....
77   f (: x xs)         = .....
78 \end{verbatim}
79 (more about that in @simplify_eqns@)
80
81 We would prefer to have a @WarningPat@ of type @String@, but Strings and the 
82 Pretty Printer are not friends.
83
84 We use @InPat@ in @WarningPat@ instead of @OutPat@
85 because we need to print the 
86 warning messages in the same way they are introduced, i.e. if the user 
87 wrote:
88 \begin{verbatim}
89         f [x,y] = ..
90 \end{verbatim}
91 He don't want a warning message written:
92 \begin{verbatim}
93         f (: x (: y [])) ........
94 \end{verbatim}
95 Then we need to use InPats.
96 \begin{quotation}
97      Juan Quintela 5 JUL 1998\\
98           User-friendliness and compiler writers are no friends.
99 \end{quotation}
100
101 \begin{code}
102 type WarningPat = InPat Name
103 type ExhaustivePat = ([WarningPat], [(Name, [HsLit])])
104 type EqnNo  = Int
105 type EqnSet = UniqSet EqnNo
106
107
108 check :: [EquationInfo] -> ([ExhaustivePat], [EquationInfo])
109         -- Second result is the shadowed equations
110 check qs = (untidy_warns, shadowed_eqns)
111       where
112         (warns, used_nos) = check' ([1..] `zip` map simplify_eqn qs)
113         untidy_warns = map untidy_exhaustive warns 
114         shadowed_eqns = [eqn | (eqn,i) <- qs `zip` [1..], 
115                                 not (i `elementOfUniqSet` used_nos)]
116
117 untidy_exhaustive :: ExhaustivePat -> ExhaustivePat
118 untidy_exhaustive ([pat], messages) = 
119                   ([untidy_no_pars pat], map untidy_message messages)
120 untidy_exhaustive (pats, messages) = 
121                   (map untidy_pars pats, map untidy_message messages)
122
123 untidy_message :: (Name, [HsLit]) -> (Name, [HsLit])
124 untidy_message (string, lits) = (string, map untidy_lit lits)
125 \end{code}
126
127 The function @untidy@ does the reverse work of the @simplify_pat@ funcion.
128
129 \begin{code}
130
131 type NeedPars = Bool 
132
133 untidy_no_pars :: WarningPat -> WarningPat
134 untidy_no_pars p = untidy False p
135
136 untidy_pars :: WarningPat -> WarningPat
137 untidy_pars p = untidy True p
138
139 untidy :: NeedPars -> WarningPat -> WarningPat
140 untidy b (L loc p) = L loc (untidy' b p)
141   where
142     untidy' _ p@(WildPat _)          = p
143     untidy' _ p@(VarPat _)           = p
144     untidy' _ (LitPat lit)           = LitPat (untidy_lit lit)
145     untidy' _ p@(ConPatIn _ (PrefixCon [])) = p
146     untidy' b (ConPatIn name ps)     = pars b (L loc (ConPatIn name (untidy_con ps)))
147     untidy' _ (ListPat pats ty)      = ListPat (map untidy_no_pars pats) ty
148     untidy' _ (TuplePat pats box ty) = TuplePat (map untidy_no_pars pats) box ty
149     untidy' _ (PArrPat _ _)          = panic "Check.untidy: Shouldn't get a parallel array here!"
150     untidy' _ (SigPatIn _ _)         = panic "Check.untidy: SigPat"
151
152 untidy_con :: HsConPatDetails Name -> HsConPatDetails Name
153 untidy_con (PrefixCon pats) = PrefixCon (map untidy_pars pats) 
154 untidy_con (InfixCon p1 p2) = InfixCon  (untidy_pars p1) (untidy_pars p2)
155 untidy_con (RecCon (HsRecFields flds dd)) 
156   = RecCon (HsRecFields [ fld { hsRecFieldArg = untidy_pars (hsRecFieldArg fld) }
157                         | fld <- flds ] dd)
158
159 pars :: NeedPars -> WarningPat -> Pat Name
160 pars True p = ParPat p
161 pars _    p = unLoc p
162
163 untidy_lit :: HsLit -> HsLit
164 untidy_lit (HsCharPrim c) = HsChar c
165 untidy_lit lit            = lit
166 \end{code}
167
168 This equation is the same that check, the only difference is that the
169 boring work is done, that work needs to be done only once, this is
170 the reason top have two functions, check is the external interface,
171 @check'@ is called recursively.
172
173 There are several cases:
174
175 \begin{itemize} 
176 \item There are no equations: Everything is OK. 
177 \item There are only one equation, that can fail, and all the patterns are
178       variables. Then that equation is used and the same equation is 
179       non-exhaustive.
180 \item All the patterns are variables, and the match can fail, there are 
181       more equations then the results is the result of the rest of equations 
182       and this equation is used also.
183
184 \item The general case, if all the patterns are variables (here the match 
185       can't fail) then the result is that this equation is used and this 
186       equation doesn't generate non-exhaustive cases.
187
188 \item In the general case, there can exist literals ,constructors or only 
189       vars in the first column, we actuate in consequence.
190
191 \end{itemize}
192
193
194 \begin{code}
195
196 check' :: [(EqnNo, EquationInfo)] 
197         -> ([ExhaustivePat],    -- Pattern scheme that might not be matched at all
198             EqnSet)             -- Eqns that are used (others are overlapped)
199
200 check' [] = ([([],[])],emptyUniqSet)
201
202 check' ((n, EqnInfo { eqn_pats = ps, eqn_rhs = MatchResult can_fail _ }) : rs) 
203    | first_eqn_all_vars && case can_fail of { CantFail -> True; CanFail -> False }
204    = ([], unitUniqSet n)        -- One eqn, which can't fail
205
206    | first_eqn_all_vars && null rs      -- One eqn, but it can fail
207    = ([(takeList ps (repeat nlWildPat),[])], unitUniqSet n)
208
209    | first_eqn_all_vars         -- Several eqns, first can fail
210    = (pats, addOneToUniqSet indexs n)
211   where
212     first_eqn_all_vars = all_vars ps
213     (pats,indexs) = check' rs
214
215 check' qs
216    | literals     = split_by_literals qs
217    | constructors = split_by_constructor qs
218    | only_vars    = first_column_only_vars qs
219 -- FIXME: hack to get view patterns through for now
220    | otherwise    = ([([],[])],emptyUniqSet)
221 -- pprPanic "Check.check': Not implemented :-(" (ppr first_pats)
222   where
223      -- Note: RecPats will have been simplified to ConPats
224      --       at this stage.
225     first_pats   = ASSERT2( okGroup qs, pprGroup qs ) map firstPatN qs
226     constructors = any is_con first_pats
227     literals     = any is_lit first_pats
228     only_vars    = all is_var first_pats
229 \end{code}
230
231 Here begins the code to deal with literals, we need to split the matrix
232 in different matrix beginning by each literal and a last matrix with the 
233 rest of values.
234
235 \begin{code}
236 split_by_literals :: [(EqnNo, EquationInfo)] -> ([ExhaustivePat], EqnSet)
237 split_by_literals qs = process_literals used_lits qs
238            where
239              used_lits = get_used_lits qs
240 \end{code}
241
242 @process_explicit_literals@ is a function that process each literal that appears 
243 in the column of the matrix. 
244
245 \begin{code}
246 process_explicit_literals :: [HsLit] -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet)
247 process_explicit_literals lits qs = (concat pats, unionManyUniqSets indexs)
248     where                  
249       pats_indexs   = map (\x -> construct_literal_matrix x qs) lits
250       (pats,indexs) = unzip pats_indexs 
251 \end{code}
252
253
254 @process_literals@ calls @process_explicit_literals@ to deal with the literals 
255 that appears in the matrix and deal also with the rest of the cases. It 
256 must be one Variable to be complete.
257
258 \begin{code}
259
260 process_literals :: [HsLit] -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet)
261 process_literals used_lits qs 
262   | null default_eqns  = ASSERT( not (null qs) ) ([make_row_vars used_lits (head qs)] ++ pats,indexs)
263   | otherwise          = (pats_default,indexs_default)
264      where
265        (pats,indexs)   = process_explicit_literals used_lits qs
266        default_eqns    = ASSERT2( okGroup qs, pprGroup qs ) 
267                          [remove_var q | q <- qs, is_var (firstPatN q)]
268        (pats',indexs') = check' default_eqns 
269        pats_default    = [(nlWildPat:ps,constraints) | (ps,constraints) <- (pats')] ++ pats 
270        indexs_default  = unionUniqSets indexs' indexs
271 \end{code}
272
273 Here we have selected the literal and we will select all the equations that 
274 begins for that literal and create a new matrix.
275
276 \begin{code}
277 construct_literal_matrix :: HsLit -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet)
278 construct_literal_matrix lit qs =
279     (map (\ (xs,ys) -> (new_lit:xs,ys)) pats,indexs) 
280   where
281     (pats,indexs) = (check' (remove_first_column_lit lit qs)) 
282     new_lit = nlLitPat lit
283
284 remove_first_column_lit :: HsLit
285                         -> [(EqnNo, EquationInfo)] 
286                         -> [(EqnNo, EquationInfo)]
287 remove_first_column_lit lit qs
288   = ASSERT2( okGroup qs, pprGroup qs ) 
289     [(n, shift_pat eqn) | q@(n,eqn) <- qs, is_var_lit lit (firstPatN q)]
290   where
291      shift_pat eqn@(EqnInfo { eqn_pats = _:ps}) = eqn { eqn_pats = ps }
292      shift_pat _                                = panic "Check.shift_var: no patterns"
293 \end{code}
294
295 This function splits the equations @qs@ in groups that deal with the 
296 same constructor.
297
298 \begin{code}
299 split_by_constructor :: [(EqnNo, EquationInfo)] -> ([ExhaustivePat], EqnSet)
300 split_by_constructor qs 
301   | notNull unused_cons = need_default_case used_cons unused_cons qs 
302   | otherwise           = no_need_default_case used_cons qs 
303                        where 
304                           used_cons   = get_used_cons qs 
305                           unused_cons = get_unused_cons used_cons 
306 \end{code}
307
308 The first column of the patterns matrix only have vars, then there is 
309 nothing to do.
310
311 \begin{code}
312 first_column_only_vars :: [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet)
313 first_column_only_vars qs = (map (\ (xs,ys) -> (nlWildPat:xs,ys)) pats,indexs)
314                           where
315                             (pats, indexs) = check' (map remove_var qs)
316 \end{code}
317
318 This equation takes a matrix of patterns and split the equations by 
319 constructor, using all the constructors that appears in the first column 
320 of the pattern matching.
321
322 We can need a default clause or not ...., it depends if we used all the 
323 constructors or not explicitly. The reasoning is similar to @process_literals@,
324 the difference is that here the default case is not always needed.
325
326 \begin{code}
327 no_need_default_case :: [Pat Id] -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet)
328 no_need_default_case cons qs = (concat pats, unionManyUniqSets indexs)
329     where                  
330       pats_indexs   = map (\x -> construct_matrix x qs) cons
331       (pats,indexs) = unzip pats_indexs 
332
333 need_default_case :: [Pat Id] -> [DataCon] -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet)
334 need_default_case used_cons unused_cons qs 
335   | null default_eqns  = (pats_default_no_eqns,indexs)
336   | otherwise          = (pats_default,indexs_default)
337      where
338        (pats,indexs)   = no_need_default_case used_cons qs
339        default_eqns    = ASSERT2( okGroup qs, pprGroup qs ) 
340                          [remove_var q | q <- qs, is_var (firstPatN q)]
341        (pats',indexs') = check' default_eqns 
342        pats_default    = [(make_whole_con c:ps,constraints) | 
343                           c <- unused_cons, (ps,constraints) <- pats'] ++ pats
344        new_wilds       = ASSERT( not (null qs) ) make_row_vars_for_constructor (head qs)
345        pats_default_no_eqns =  [(make_whole_con c:new_wilds,[]) | c <- unused_cons] ++ pats
346        indexs_default  = unionUniqSets indexs' indexs
347
348 construct_matrix :: Pat Id -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet)
349 construct_matrix con qs =
350     (map (make_con con) pats,indexs) 
351   where
352     (pats,indexs) = (check' (remove_first_column con qs)) 
353 \end{code}
354
355 Here remove first column is more difficult that with literals due to the fact 
356 that constructors can have arguments.
357
358 For instance, the matrix
359 \begin{verbatim}
360  (: x xs) y
361  z        y
362 \end{verbatim}
363 is transformed in:
364 \begin{verbatim}
365  x xs y
366  _ _  y
367 \end{verbatim}
368
369 \begin{code}
370 remove_first_column :: Pat Id                -- Constructor 
371                     -> [(EqnNo, EquationInfo)] 
372                     -> [(EqnNo, EquationInfo)]
373 remove_first_column (ConPatOut{ pat_con = L _ con, pat_args = PrefixCon con_pats }) qs
374   = ASSERT2( okGroup qs, pprGroup qs ) 
375     [(n, shift_var eqn) | q@(n, eqn) <- qs, is_var_con con (firstPatN q)]
376   where
377      new_wilds = [WildPat (hsLPatType arg_pat) | arg_pat <- con_pats]
378      shift_var eqn@(EqnInfo { eqn_pats = ConPatOut{ pat_args = PrefixCon ps' } : ps}) 
379         = eqn { eqn_pats = map unLoc ps' ++ ps }
380      shift_var eqn@(EqnInfo { eqn_pats = WildPat _ : ps })
381         = eqn { eqn_pats = new_wilds ++ ps }
382      shift_var _ = panic "Check.Shift_var:No done"
383
384 make_row_vars :: [HsLit] -> (EqnNo, EquationInfo) -> ExhaustivePat
385 make_row_vars used_lits (_, EqnInfo { eqn_pats = pats})
386    = (nlVarPat new_var:takeList (tail pats) (repeat nlWildPat),[(new_var,used_lits)])
387   where 
388      new_var = hash_x
389
390 hash_x :: Name
391 hash_x = mkInternalName unboundKey {- doesn't matter much -}
392                      (mkVarOccFS (fsLit "#x"))
393                      noSrcSpan
394
395 make_row_vars_for_constructor :: (EqnNo, EquationInfo) -> [WarningPat]
396 make_row_vars_for_constructor (_, EqnInfo { eqn_pats = pats}) 
397   = takeList (tail pats) (repeat nlWildPat)
398
399 compare_cons :: Pat Id -> Pat Id -> Bool
400 compare_cons (ConPatOut{ pat_con = L _ id1 }) (ConPatOut { pat_con = L _ id2 }) = id1 == id2  
401
402 remove_dups :: [Pat Id] -> [Pat Id]
403 remove_dups []     = []
404 remove_dups (x:xs) | or (map (\y -> compare_cons x y) xs) = remove_dups  xs
405                    | otherwise                            = x : remove_dups xs
406
407 get_used_cons :: [(EqnNo, EquationInfo)] -> [Pat Id]
408 get_used_cons qs = remove_dups [pat | q <- qs, let pat = firstPatN q, 
409                                       isConPatOut pat]
410
411 isConPatOut :: Pat Id -> Bool
412 isConPatOut (ConPatOut {}) = True
413 isConPatOut _              = False
414
415 remove_dups' :: [HsLit] -> [HsLit] 
416 remove_dups' []                   = []
417 remove_dups' (x:xs) | x `elem` xs = remove_dups' xs
418                     | otherwise   = x : remove_dups' xs 
419
420
421 get_used_lits :: [(EqnNo, EquationInfo)] -> [HsLit]
422 get_used_lits qs = remove_dups' all_literals
423                  where
424                    all_literals = get_used_lits' qs
425
426 get_used_lits' :: [(EqnNo, EquationInfo)] -> [HsLit]
427 get_used_lits' [] = []
428 get_used_lits' (q:qs) 
429   | Just lit <- get_lit (firstPatN q) = lit : get_used_lits' qs
430   | otherwise                         = get_used_lits qs
431
432 get_lit :: Pat id -> Maybe HsLit 
433 -- Get a representative HsLit to stand for the OverLit
434 -- It doesn't matter which one, because they will only be compared
435 -- with other HsLits gotten in the same way
436 get_lit (LitPat lit)                     = Just lit
437 get_lit (NPat (HsIntegral i   _ _) mb _) = Just (HsIntPrim   (mb_neg mb i))
438 get_lit (NPat (HsFractional f _ _) mb _) = Just (HsFloatPrim (mb_neg mb f))
439 get_lit (NPat (HsIsString s   _ _)  _ _) = Just (HsStringPrim s)
440 get_lit _                                = Nothing
441
442 mb_neg :: Num a => Maybe b -> a -> a
443 mb_neg Nothing  v = v
444 mb_neg (Just _) v = -v
445
446 get_unused_cons :: [Pat Id] -> [DataCon]
447 get_unused_cons used_cons = ASSERT( not (null used_cons) ) unused_cons
448      where
449        (ConPatOut { pat_con = l_con }) = head used_cons
450        ty_con          = dataConTyCon (unLoc l_con)     -- Newtype observable
451        all_cons        = tyConDataCons ty_con
452        used_cons_as_id = map (\ (ConPatOut{ pat_con = L _ d}) -> d) used_cons
453        unused_cons     = uniqSetToList
454                          (mkUniqSet all_cons `minusUniqSet` mkUniqSet used_cons_as_id) 
455
456 all_vars :: [Pat Id] -> Bool
457 all_vars []             = True
458 all_vars (WildPat _:ps) = all_vars ps
459 all_vars _              = False
460
461 remove_var :: (EqnNo, EquationInfo) -> (EqnNo, EquationInfo)
462 remove_var (n, eqn@(EqnInfo { eqn_pats = WildPat _ : ps})) = (n, eqn { eqn_pats = ps })
463 remove_var _  = panic "Check.remove_var: equation does not begin with a variable"
464
465 -----------------------
466 eqnPats :: (EqnNo, EquationInfo) -> [Pat Id]
467 eqnPats (_, eqn) = eqn_pats eqn
468
469 okGroup :: [(EqnNo, EquationInfo)] -> Bool
470 -- True if all equations have at least one pattern, and
471 -- all have the same number of patterns
472 okGroup [] = True
473 okGroup (e:es) = n_pats > 0 && and [length (eqnPats e) == n_pats | e <- es]
474                where
475                  n_pats = length (eqnPats e)
476
477 -- Half-baked print
478 pprGroup :: [(EqnNo, EquationInfo)] -> SDoc
479 pprEqnInfo :: (EqnNo, EquationInfo) -> SDoc
480 pprGroup es = vcat (map pprEqnInfo es)
481 pprEqnInfo e = ppr (eqnPats e)
482
483
484 firstPatN :: (EqnNo, EquationInfo) -> Pat Id
485 firstPatN (_, eqn) = firstPat eqn
486
487 is_con :: Pat Id -> Bool
488 is_con (ConPatOut {}) = True
489 is_con _              = False
490
491 is_lit :: Pat Id -> Bool
492 is_lit (LitPat _)      = True
493 is_lit (NPat _ _ _)  = True
494 is_lit _               = False
495
496 is_var :: Pat Id -> Bool
497 is_var (WildPat _) = True
498 is_var _           = False
499
500 is_var_con :: DataCon -> Pat Id -> Bool
501 is_var_con _   (WildPat _)                                 = True
502 is_var_con con (ConPatOut{ pat_con = L _ id }) | id == con = True
503 is_var_con _   _                                           = False
504
505 is_var_lit :: HsLit -> Pat Id -> Bool
506 is_var_lit _   (WildPat _)   = True
507 is_var_lit lit pat 
508   | Just lit' <- get_lit pat = lit == lit'
509   | otherwise                = False
510 \end{code}
511
512 The difference beteewn @make_con@ and @make_whole_con@ is that
513 @make_wole_con@ creates a new constructor with all their arguments, and
514 @make_con@ takes a list of argumntes, creates the contructor getting their
515 arguments from the list. See where \fbox{\ ???\ } are used for details.
516
517 We need to reconstruct the patterns (make the constructors infix and
518 similar) at the same time that we create the constructors.
519
520 You can tell tuple constructors using
521 \begin{verbatim}
522         Id.isTupleCon
523 \end{verbatim}
524 You can see if one constructor is infix with this clearer code :-))))))))))
525 \begin{verbatim}
526         Lex.isLexConSym (Name.occNameString (Name.getOccName con))
527 \end{verbatim}
528
529        Rather clumsy but it works. (Simon Peyton Jones)
530
531
532 We don't mind the @nilDataCon@ because it doesn't change the way to
533 print the messsage, we are searching only for things like: @[1,2,3]@,
534 not @x:xs@ ....
535
536 In @reconstruct_pat@ we want to ``undo'' the work
537 that we have done in @simplify_pat@.
538 In particular:
539 \begin{tabular}{lll}
540         @((,) x y)@   & returns to be & @(x, y)@
541 \\      @((:) x xs)@  & returns to be & @(x:xs)@
542 \\      @(x:(...:[])@ & returns to be & @[x,...]@
543 \end{tabular}
544 %
545 The difficult case is the third one becouse we need to follow all the
546 contructors until the @[]@ to know that we need to use the second case,
547 not the second. \fbox{\ ???\ }
548 %
549 \begin{code}
550 isInfixCon :: DataCon -> Bool
551 isInfixCon con = isDataSymOcc (getOccName con)
552
553 is_nil :: Pat Name -> Bool
554 is_nil (ConPatIn con (PrefixCon [])) = unLoc con == getName nilDataCon
555 is_nil _                             = False
556
557 is_list :: Pat Name -> Bool
558 is_list (ListPat _ _) = True
559 is_list _             = False
560
561 return_list :: DataCon -> Pat Name -> Bool
562 return_list id q = id == consDataCon && (is_nil q || is_list q) 
563
564 make_list :: LPat Name -> Pat Name -> Pat Name
565 make_list p q | is_nil q    = ListPat [p] placeHolderType
566 make_list p (ListPat ps ty) = ListPat (p:ps) ty
567 make_list _ _               = panic "Check.make_list: Invalid argument"
568
569 make_con :: Pat Id -> ExhaustivePat -> ExhaustivePat           
570 make_con (ConPatOut{ pat_con = L _ id }) (lp:lq:ps, constraints) 
571      | return_list id q = (noLoc (make_list lp q) : ps, constraints)
572      | isInfixCon id    = (nlInfixConPat (getName id) lp lq : ps, constraints) 
573    where q  = unLoc lq  
574
575 make_con (ConPatOut{ pat_con = L _ id, pat_args = PrefixCon pats, pat_ty = ty }) (ps, constraints) 
576       | isTupleTyCon tc  = (noLoc (TuplePat pats_con (tupleTyConBoxity tc) ty) : rest_pats, constraints) 
577       | isPArrFakeCon id = (noLoc (PArrPat pats_con placeHolderType)           : rest_pats, constraints) 
578       | otherwise        = (nlConPat name pats_con      : rest_pats, constraints)
579     where 
580         name                  = getName id
581         (pats_con, rest_pats) = splitAtList pats ps
582         tc                    = dataConTyCon id
583
584 -- reconstruct parallel array pattern
585 --
586 --  * don't check for the type only; we need to make sure that we are really
587 --   dealing with one of the fake constructors and not with the real
588 --   representation 
589
590 make_whole_con :: DataCon -> WarningPat
591 make_whole_con con | isInfixCon con = nlInfixConPat name nlWildPat nlWildPat
592                    | otherwise      = nlConPat name pats
593                 where 
594                   name   = getName con
595                   pats   = [nlWildPat | _ <- dataConOrigArgTys con]
596 \end{code}
597
598 This equation makes the same thing as @tidy@ in @Match.lhs@, the
599 difference is that here we can do all the tidy in one place and in the
600 @Match@ tidy it must be done one column each time due to bookkeeping 
601 constraints.
602
603 \begin{code}
604
605 simplify_eqn :: EquationInfo -> EquationInfo
606 simplify_eqn eqn = eqn { eqn_pats = map simplify_pat (eqn_pats eqn), 
607                          eqn_rhs  = simplify_rhs (eqn_rhs eqn) }
608   where
609         -- Horrible hack.  The simplify_pat stuff converts NPlusK pats to WildPats
610         -- which of course loses the info that they can fail to match.  So we 
611         -- stick in a CanFail as if it were a guard.
612         -- The Right Thing to do is for the whole system to treat NPlusK pats properly
613     simplify_rhs (MatchResult can_fail body)
614         | any has_nplusk_pat (eqn_pats eqn) = MatchResult CanFail body
615         | otherwise                         = MatchResult can_fail body
616
617 has_nplusk_lpat :: LPat Id -> Bool
618 has_nplusk_lpat (L _ p) = has_nplusk_pat p
619
620 has_nplusk_pat :: Pat Id -> Bool
621 has_nplusk_pat (NPlusKPat _ _ _ _)           = True
622 has_nplusk_pat (ParPat p)                    = has_nplusk_lpat p
623 has_nplusk_pat (AsPat _ p)                   = has_nplusk_lpat p
624 has_nplusk_pat (ViewPat _ p _)               = has_nplusk_lpat p
625 has_nplusk_pat (SigPatOut p _ )              = has_nplusk_lpat p
626 has_nplusk_pat (ListPat ps _)                = any has_nplusk_lpat ps
627 has_nplusk_pat (TuplePat ps _ _)             = any has_nplusk_lpat ps
628 has_nplusk_pat (PArrPat ps _)                = any has_nplusk_lpat ps
629 has_nplusk_pat (LazyPat _)                   = False    -- Why?
630 has_nplusk_pat (BangPat p)                   = has_nplusk_lpat p        -- I think
631 has_nplusk_pat (ConPatOut { pat_args = ps }) = any has_nplusk_lpat (hsConPatArgs ps)
632 has_nplusk_pat _                             = False -- VarPat, VarPatOut, WildPat, LitPat, NPat, TypePat
633
634 simplify_lpat :: LPat Id -> LPat Id  
635 simplify_lpat p = fmap simplify_pat p
636
637 simplify_pat :: Pat Id -> Pat Id
638 simplify_pat pat@(WildPat _)  = pat
639 simplify_pat (VarPat id)      = WildPat (idType id) 
640 simplify_pat (VarPatOut id _) = WildPat (idType id)     -- Ignore the bindings
641 simplify_pat (ParPat p)       = unLoc (simplify_lpat p)
642 simplify_pat (LazyPat p)      = WildPat (hsLPatType p)  -- For overlap and exhaustiveness checking
643                                                         -- purposes, a ~pat is like a wildcard
644 simplify_pat (BangPat p)      = unLoc (simplify_lpat p)
645 simplify_pat (AsPat _ p)      = unLoc (simplify_lpat p)
646
647 simplify_pat (ViewPat expr p ty)     = ViewPat expr (simplify_lpat p) ty
648
649 simplify_pat (SigPatOut p _)  = unLoc (simplify_lpat p) -- I'm not sure this is right
650
651 simplify_pat pat@(ConPatOut { pat_con = L _ id, pat_args = ps })
652   = pat { pat_args = simplify_con id ps }
653
654 simplify_pat (ListPat ps ty) = 
655   unLoc $ foldr (\ x y -> mkPrefixConPat consDataCon [x,y] list_ty)
656                                   (mkNilPat list_ty)
657                                   (map simplify_lpat ps)
658          where list_ty = mkListTy ty
659
660 -- introduce fake parallel array constructors to be able to handle parallel
661 -- arrays with the existing machinery for constructor pattern
662 --
663 simplify_pat (PArrPat ps ty)
664   = unLoc $ mkPrefixConPat (parrFakeCon (length ps))
665                            (map simplify_lpat ps) 
666                            (mkPArrTy ty)
667
668 simplify_pat (TuplePat ps boxity ty)
669   = unLoc $ mkPrefixConPat (tupleCon boxity arity)
670                            (map simplify_lpat ps) ty
671   where
672     arity = length ps
673
674 -- unpack string patterns fully, so we can see when they overlap with
675 -- each other, or even explicit lists of Chars.
676 simplify_pat (LitPat (HsString s)) =
677    unLoc $ foldr (\c pat -> mkPrefixConPat consDataCon [mk_char_lit c, pat] stringTy)
678                  (mkPrefixConPat nilDataCon [] stringTy) (unpackFS s)
679   where
680     mk_char_lit c = mkPrefixConPat charDataCon [nlLitPat (HsCharPrim c)] charTy
681
682 simplify_pat (LitPat lit)                = tidyLitPat lit 
683 simplify_pat (NPat lit mb_neg eq) = tidyNPat lit mb_neg eq
684
685 simplify_pat (NPlusKPat id _ _ _)
686    = WildPat (idType (unLoc id))
687
688 simplify_pat (CoPat _ pat _) = simplify_pat pat
689
690 -----------------
691 simplify_con :: DataCon -> HsConPatDetails Id -> HsConPatDetails Id
692 simplify_con _   (PrefixCon ps)   = PrefixCon (map simplify_lpat ps)
693 simplify_con _   (InfixCon p1 p2) = PrefixCon [simplify_lpat p1, simplify_lpat p2]
694 simplify_con con (RecCon (HsRecFields fs _))      
695   | null fs   = PrefixCon [nlWildPat | _ <- dataConOrigArgTys con]
696                 -- Special case for null patterns; maybe not a record at all
697   | otherwise = PrefixCon (map (simplify_lpat.snd) all_pats)
698   where
699      -- pad out all the missing fields with WildPats.
700     field_pats = map (\ f -> (f, nlWildPat)) (dataConFieldLabels con)
701     all_pats = foldr (\(HsRecField id p _) acc -> insertNm (getName (unLoc id)) p acc)
702                      field_pats fs
703        
704     insertNm nm p [] = [(nm,p)]
705     insertNm nm p (x@(n,_):xs)
706       | nm == n    = (nm,p):xs
707       | otherwise  = x : insertNm nm p xs
708 \end{code}