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