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