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