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