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