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