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