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