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