ApiAnnotations: Make all RdrName occurences Located
[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 this 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 The @check@ 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 shadowed or 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 this 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' _ (NPat {}) = panic "Check.untidy: NPat"
157 untidy' _ (NPlusKPat {}) = panic "Check.untidy: NPlusKPat"
158 untidy' _ (SigPatOut {}) = panic "Check.untidy: SigPatOut"
159 untidy' _ (CoPat {}) = panic "Check.untidy: CoPat"
160
161 untidy_con :: HsConPatDetails Name -> HsConPatDetails Name
162 untidy_con (PrefixCon pats) = PrefixCon (map untidy_pars pats)
163 untidy_con (InfixCon p1 p2) = InfixCon (untidy_pars p1) (untidy_pars p2)
164 untidy_con (RecCon (HsRecFields flds dd))
165 = RecCon (HsRecFields [ L l (fld { hsRecFieldArg
166 = untidy_pars (hsRecFieldArg fld) })
167 | L l fld <- flds ] dd)
168
169 pars :: NeedPars -> WarningPat -> Pat Name
170 pars True p = ParPat p
171 pars _ p = unLoc p
172
173 untidy_lit :: HsLit -> HsLit
174 untidy_lit (HsCharPrim src c) = HsChar src c
175 untidy_lit lit = lit
176
177 {-
178 @check@ is the external interface, boring work (tidy, untidy) is done
179 in this as it needs to be done only once.
180 @check'@ is called recursively, this is the reason to have two functions.
181
182 These are the several cases handled in @check'@:
183
184 \begin{itemize}
185 \item There are no equations: Everything is OK.
186
187 \item If all the patterns are variables and the match can't fail
188 then this equation is used and it doesn't generate non-exhaustive cases.
189
190 \item There is only one equation that can fail, and all the patterns are
191 variables. Then that equation is used and the same equation is
192 non-exhaustive.
193
194 \item All the patterns are variables, and the match can fail, there are
195 more equations then the results is the result of the rest of equations
196 and this equation is used also.
197
198 \item In the general case, there can exist literals ,constructors or only
199 vars in the first column, we actuate in consequence.
200
201 \end{itemize}
202 -}
203
204 check' :: [(EqnNo, EquationInfo)]
205 -> ([ExhaustivePat], -- Pattern scheme that might not be matched at all
206 EqnSet) -- Eqns that are used (others are overlapped)
207
208 check' [] = ([],emptyUniqSet)
209 -- Was ([([],[])], emptyUniqSet)
210 -- But that (a) seems weird, and (b) triggered Trac #7669
211 -- So now I'm just doing the simple obvious thing
212
213 check' ((n, EqnInfo { eqn_pats = ps, eqn_rhs = MatchResult can_fail _ }) : rs)
214 | first_eqn_all_vars && case can_fail of { CantFail -> True; CanFail -> False }
215 = ([], unitUniqSet n) -- One eqn, which can't fail
216
217 | first_eqn_all_vars && null rs -- One eqn, but it can fail
218 = ([(takeList ps (repeat nlWildPatName),[])], unitUniqSet n)
219
220 | first_eqn_all_vars -- Several eqns, first can fail
221 = (pats, addOneToUniqSet indexs n)
222 where
223 first_eqn_all_vars = all_vars ps
224 (pats,indexs) = check' rs
225
226 check' qs
227 | some_literals = split_by_literals qs
228 | some_constructors = split_by_constructor qs
229 | only_vars = first_column_only_vars qs
230 | otherwise = pprPanic "Check.check': Not implemented :-(" (ppr first_pats)
231 -- Shouldn't happen
232 where
233 -- Note: RecPats will have been simplified to ConPats
234 -- at this stage.
235 first_pats = ASSERT2( okGroup qs, pprGroup qs ) map firstPatN qs
236 some_constructors = any is_con first_pats
237 some_literals = any is_lit first_pats
238 only_vars = all is_var first_pats
239
240 {-
241 Here begins the code to deal with literals, we need to split the matrix
242 in different matrix beginning by each literal and a last matrix with the
243 rest of values.
244 -}
245
246 split_by_literals :: [(EqnNo, EquationInfo)] -> ([ExhaustivePat], EqnSet)
247 split_by_literals qs = process_literals used_lits qs
248 where
249 used_lits = get_used_lits qs
250
251 {-
252 @process_explicit_literals@ is a function that process each literal that appears
253 in the column of the matrix.
254 -}
255
256 process_explicit_literals :: [HsLit] -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet)
257 process_explicit_literals lits qs = (concat pats, unionManyUniqSets indexs)
258 where
259 pats_indexs = map (\x -> construct_literal_matrix x qs) lits
260 (pats,indexs) = unzip pats_indexs
261
262 {-
263 @process_literals@ calls @process_explicit_literals@ to deal with the literals
264 that appears in the matrix and deal also with the rest of the cases. It
265 must be one Variable to be complete.
266 -}
267
268 process_literals :: [HsLit] -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet)
269 process_literals used_lits qs
270 | null default_eqns = ASSERT( not (null qs) ) ([make_row_vars used_lits (head qs)] ++ pats,indexs)
271 | otherwise = (pats_default,indexs_default)
272 where
273 (pats,indexs) = process_explicit_literals used_lits qs
274 default_eqns = ASSERT2( okGroup qs, pprGroup qs )
275 [remove_var q | q <- qs, is_var (firstPatN q)]
276 (pats',indexs') = check' default_eqns
277 pats_default = [(nlWildPatName:ps,constraints) |
278 (ps,constraints) <- (pats')] ++ pats
279 indexs_default = unionUniqSets indexs' indexs
280
281 {-
282 Here we have selected the literal and we will select all the equations that
283 begins for that literal and create a new matrix.
284 -}
285
286 construct_literal_matrix :: HsLit -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet)
287 construct_literal_matrix lit qs =
288 (map (\ (xs,ys) -> (new_lit:xs,ys)) pats,indexs)
289 where
290 (pats,indexs) = (check' (remove_first_column_lit lit qs))
291 new_lit = nlLitPat lit
292
293 remove_first_column_lit :: HsLit
294 -> [(EqnNo, EquationInfo)]
295 -> [(EqnNo, EquationInfo)]
296 remove_first_column_lit lit qs
297 = ASSERT2( okGroup qs, pprGroup qs )
298 [(n, shift_pat eqn) | q@(n,eqn) <- qs, is_var_lit lit (firstPatN q)]
299 where
300 shift_pat eqn@(EqnInfo { eqn_pats = _:ps}) = eqn { eqn_pats = ps }
301 shift_pat _ = panic "Check.shift_var: no patterns"
302
303 {-
304 This function splits the equations @qs@ in groups that deal with the
305 same constructor.
306 -}
307
308 split_by_constructor :: [(EqnNo, EquationInfo)] -> ([ExhaustivePat], EqnSet)
309 split_by_constructor qs
310 | null used_cons = ([], mkUniqSet $ map fst qs)
311 | notNull unused_cons = need_default_case used_cons unused_cons qs
312 | otherwise = no_need_default_case used_cons qs
313 where
314 used_cons = get_used_cons qs
315 unused_cons = get_unused_cons used_cons
316
317 {-
318 The first column of the patterns matrix only have vars, then there is
319 nothing to do.
320 -}
321
322 first_column_only_vars :: [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet)
323 first_column_only_vars qs
324 = (map (\ (xs,ys) -> (nlWildPatName:xs,ys)) pats,indexs)
325 where
326 (pats, indexs) = check' (map remove_var qs)
327
328 {-
329 This equation takes a matrix of patterns and split the equations by
330 constructor, using all the constructors that appears in the first column
331 of the pattern matching.
332
333 Whether we need a default clause or not depends if we used all the
334 constructors or not explicitly. The reasoning is similar to @process_literals@,
335 the difference is that here the default case is not always needed.
336 -}
337
338 no_need_default_case :: [Pat Id] -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet)
339 no_need_default_case cons qs = (concat pats, unionManyUniqSets indexs)
340 where
341 pats_indexs = map (\x -> construct_matrix x qs) cons
342 (pats,indexs) = unzip pats_indexs
343
344 need_default_case :: [Pat Id] -> [DataCon] -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet)
345 need_default_case used_cons unused_cons qs
346 | null default_eqns = (pats_default_no_eqns,indexs)
347 | otherwise = (pats_default,indexs_default)
348 where
349 (pats,indexs) = no_need_default_case used_cons qs
350 default_eqns = ASSERT2( okGroup qs, pprGroup qs )
351 [remove_var q | q <- qs, is_var (firstPatN q)]
352 (pats',indexs') = check' default_eqns
353 pats_default = [(make_whole_con c:ps,constraints) |
354 c <- unused_cons, (ps,constraints) <- pats'] ++ pats
355 new_wilds = ASSERT( not (null qs) ) make_row_vars_for_constructor (head qs)
356 pats_default_no_eqns = [(make_whole_con c:new_wilds,[]) | c <- unused_cons] ++ pats
357 indexs_default = unionUniqSets indexs' indexs
358
359 construct_matrix :: Pat Id -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet)
360 construct_matrix con qs =
361 (map (make_con con) pats,indexs)
362 where
363 (pats,indexs) = (check' (remove_first_column con qs))
364
365 {-
366 Here removing the first column is more difficult (than literals) due to the fact
367 that constructors can have arguments.
368
369 For instance, the matrix
370 \begin{verbatim}
371 (: x xs) y
372 z y
373 \end{verbatim}
374 is transformed in:
375 \begin{verbatim}
376 x xs y
377 _ _ y
378 \end{verbatim}
379 -}
380
381 remove_first_column :: Pat Id -- Constructor
382 -> [(EqnNo, EquationInfo)]
383 -> [(EqnNo, EquationInfo)]
384 remove_first_column (ConPatOut{ pat_con = L _ con, pat_args = PrefixCon con_pats }) qs
385 = ASSERT2( okGroup qs, pprGroup qs )
386 [(n, shift_var eqn) | q@(n, eqn) <- qs, is_var_con con (firstPatN q)]
387 where
388 new_wilds = [WildPat (hsLPatType arg_pat) | arg_pat <- con_pats]
389 shift_var eqn@(EqnInfo { eqn_pats = ConPatOut{ pat_args = PrefixCon ps' } : ps})
390 = eqn { eqn_pats = map unLoc ps' ++ ps }
391 shift_var eqn@(EqnInfo { eqn_pats = WildPat _ : ps })
392 = eqn { eqn_pats = new_wilds ++ ps }
393 shift_var _ = panic "Check.Shift_var:No done"
394 remove_first_column _ _ = panic "Check.remove_first_column: Not ConPatOut"
395
396 make_row_vars :: [HsLit] -> (EqnNo, EquationInfo) -> ExhaustivePat
397 make_row_vars used_lits (_, EqnInfo { eqn_pats = pats})
398 = (nlVarPat new_var:takeList (tail pats) (repeat nlWildPatName)
399 ,[(new_var,used_lits)])
400 where
401 new_var = hash_x
402
403 hash_x :: Name
404 hash_x = mkInternalName unboundKey {- doesn't matter much -}
405 (mkVarOccFS (fsLit "#x"))
406 noSrcSpan
407
408 make_row_vars_for_constructor :: (EqnNo, EquationInfo) -> [WarningPat]
409 make_row_vars_for_constructor (_, EqnInfo { eqn_pats = pats})
410 = takeList (tail pats) (repeat nlWildPatName)
411
412 compare_cons :: Pat Id -> Pat Id -> Bool
413 compare_cons (ConPatOut{ pat_con = L _ con1 }) (ConPatOut{ pat_con = L _ con2 })
414 = case (con1, con2) of
415 (RealDataCon id1, RealDataCon id2) -> id1 == id2
416 _ -> False
417 compare_cons _ _ = panic "Check.compare_cons: Not ConPatOut with RealDataCon"
418
419 remove_dups :: [Pat Id] -> [Pat Id]
420 remove_dups [] = []
421 remove_dups (x:xs) | any (\y -> compare_cons x y) xs = remove_dups xs
422 | otherwise = x : remove_dups xs
423
424 get_used_cons :: [(EqnNo, EquationInfo)] -> [Pat Id]
425 get_used_cons qs = remove_dups [pat | q <- qs, let pat = firstPatN q,
426 isConPatOut pat]
427
428 isConPatOut :: Pat Id -> Bool
429 isConPatOut ConPatOut{ pat_con = L _ RealDataCon{} } = True
430 isConPatOut _ = False
431
432 remove_dups' :: [HsLit] -> [HsLit]
433 remove_dups' [] = []
434 remove_dups' (x:xs) | x `elem` xs = remove_dups' xs
435 | otherwise = x : remove_dups' xs
436
437
438 get_used_lits :: [(EqnNo, EquationInfo)] -> [HsLit]
439 get_used_lits qs = remove_dups' all_literals
440 where
441 all_literals = get_used_lits' qs
442
443 get_used_lits' :: [(EqnNo, EquationInfo)] -> [HsLit]
444 get_used_lits' [] = []
445 get_used_lits' (q:qs)
446 | Just lit <- get_lit (firstPatN q) = lit : get_used_lits' qs
447 | otherwise = get_used_lits qs
448
449 get_lit :: Pat id -> Maybe HsLit
450 -- Get a representative HsLit to stand for the OverLit
451 -- It doesn't matter which one, because they will only be compared
452 -- with other HsLits gotten in the same way
453 get_lit (LitPat lit) = Just lit
454 get_lit (NPat (L _ (OverLit { ol_val = HsIntegral src i})) mb _)
455 = Just (HsIntPrim src (mb_neg negate mb i))
456 get_lit (NPat (L _ (OverLit { ol_val = HsFractional f })) mb _)
457 = Just (HsFloatPrim (mb_neg negateFractionalLit mb f))
458 get_lit (NPat (L _ (OverLit { ol_val = HsIsString src s })) _ _)
459 = Just (HsStringPrim src (fastStringToByteString s))
460 get_lit _ = Nothing
461
462 mb_neg :: (a -> a) -> Maybe b -> a -> a
463 mb_neg _ Nothing v = v
464 mb_neg negate (Just _) v = negate v
465
466 get_unused_cons :: [Pat Id] -> [DataCon]
467 get_unused_cons used_cons = ASSERT( not (null used_cons) ) unused_cons
468 where
469 used_set :: UniqSet DataCon
470 used_set = mkUniqSet [d | ConPatOut{ pat_con = L _ (RealDataCon d) } <- used_cons]
471 (ConPatOut { pat_con = L _ (RealDataCon con1), pat_arg_tys = inst_tys }) = head used_cons
472 ty_con = dataConTyCon con1
473 unused_cons = filterOut is_used (tyConDataCons ty_con)
474 is_used con = con `elementOfUniqSet` used_set
475 || dataConCannotMatch inst_tys con
476
477 all_vars :: [Pat Id] -> Bool
478 all_vars [] = True
479 all_vars (WildPat _:ps) = all_vars ps
480 all_vars _ = False
481
482 remove_var :: (EqnNo, EquationInfo) -> (EqnNo, EquationInfo)
483 remove_var (n, eqn@(EqnInfo { eqn_pats = WildPat _ : ps})) = (n, eqn { eqn_pats = ps })
484 remove_var _ = panic "Check.remove_var: equation does not begin with a variable"
485
486 -----------------------
487 eqnPats :: (EqnNo, EquationInfo) -> [Pat Id]
488 eqnPats (_, eqn) = eqn_pats eqn
489
490 okGroup :: [(EqnNo, EquationInfo)] -> Bool
491 -- True if all equations have at least one pattern, and
492 -- all have the same number of patterns
493 okGroup [] = True
494 okGroup (e:es) = n_pats > 0 && and [length (eqnPats e) == n_pats | e <- es]
495 where
496 n_pats = length (eqnPats e)
497
498 -- Half-baked print
499 pprGroup :: [(EqnNo, EquationInfo)] -> SDoc
500 pprEqnInfo :: (EqnNo, EquationInfo) -> SDoc
501 pprGroup es = vcat (map pprEqnInfo es)
502 pprEqnInfo e = ppr (eqnPats e)
503
504
505 firstPatN :: (EqnNo, EquationInfo) -> Pat Id
506 firstPatN (_, eqn) = firstPat eqn
507
508 is_con :: Pat Id -> Bool
509 is_con (ConPatOut {}) = True
510 is_con _ = False
511
512 is_lit :: Pat Id -> Bool
513 is_lit (LitPat _) = True
514 is_lit (NPat _ _ _) = True
515 is_lit _ = False
516
517 is_var :: Pat Id -> Bool
518 is_var (WildPat _) = True
519 is_var _ = False
520
521 is_var_con :: ConLike -> Pat Id -> Bool
522 is_var_con _ (WildPat _) = True
523 is_var_con con (ConPatOut{ pat_con = L _ id }) = id == con
524 is_var_con _ _ = False
525
526 is_var_lit :: HsLit -> Pat Id -> Bool
527 is_var_lit _ (WildPat _) = True
528 is_var_lit lit pat
529 | Just lit' <- get_lit pat = lit == lit'
530 | otherwise = False
531
532 {-
533 The difference beteewn @make_con@ and @make_whole_con@ is that
534 @make_whole_con@ creates a new constructor with all their arguments, and
535 @make_con@ takes a list of arguments, creates the constructor getting their
536 arguments from the list. See where \fbox{\ ???\ } are used for details.
537
538 We need to reconstruct the patterns (make the constructors infix and
539 similar) at the same time that we create the constructors.
540
541 You can tell tuple constructors using
542 \begin{verbatim}
543 Id.isTupleDataCon
544 \end{verbatim}
545 You can see if one constructor is infix with this clearer code :-))))))))))
546 \begin{verbatim}
547 Lex.isLexConSym (Name.occNameString (Name.getOccName con))
548 \end{verbatim}
549
550 Rather clumsy but it works. (Simon Peyton Jones)
551
552
553 We don't mind the @nilDataCon@ because it doesn't change the way to
554 print the message, we are searching only for things like: @[1,2,3]@,
555 not @x:xs@ ....
556
557 In @reconstruct_pat@ we want to ``undo'' the work
558 that we have done in @tidy_pat@.
559 In particular:
560 \begin{tabular}{lll}
561 @((,) x y)@ & returns to be & @(x, y)@
562 \\ @((:) x xs)@ & returns to be & @(x:xs)@
563 \\ @(x:(...:[])@ & returns to be & @[x,...]@
564 \end{tabular}
565
566 The difficult case is the third one because we need to follow all the
567 contructors until the @[]@ to know that we need to use the second case,
568 not the second. \fbox{\ ???\ }
569 -}
570
571 isInfixCon :: DataCon -> Bool
572 isInfixCon con = isDataSymOcc (getOccName con)
573
574 is_nil :: Pat Name -> Bool
575 is_nil (ConPatIn con (PrefixCon [])) = unLoc con == getName nilDataCon
576 is_nil _ = False
577
578 is_list :: Pat Name -> Bool
579 is_list (ListPat _ _ Nothing) = True
580 is_list _ = False
581
582 return_list :: DataCon -> Pat Name -> Bool
583 return_list id q = id == consDataCon && (is_nil q || is_list q)
584
585 make_list :: LPat Name -> Pat Name -> Pat Name
586 make_list p q | is_nil q = ListPat [p] placeHolderType Nothing
587 make_list p (ListPat ps ty Nothing) = ListPat (p:ps) ty Nothing
588 make_list _ _ = panic "Check.make_list: Invalid argument"
589
590 make_con :: Pat Id -> ExhaustivePat -> ExhaustivePat
591 make_con (ConPatOut{ pat_con = L _ (RealDataCon id) }) (lp:lq:ps, constraints)
592 | return_list id q = (noLoc (make_list lp q) : ps, constraints)
593 | isInfixCon id = (nlInfixConPat (getName id) lp lq : ps, constraints)
594 where q = unLoc lq
595
596 make_con (ConPatOut{ pat_con = L _ (RealDataCon id), pat_args = PrefixCon pats})
597 (ps, constraints)
598 | Just sort <- tyConTuple_maybe tc
599 = (noLoc (TuplePat pats_con (tupleSortBoxity sort) [])
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 for patterns that might fail
652 -- (that are 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 -- This is considered 'might fail', as pattern synonym
674 -- is not supported by checking algorithm
675
676 -- Finally the ones that are sure to succeed, or which are covered by the checking algorithm
677 might_fail_pat (LazyPat _) = False -- Always succeeds
678 might_fail_pat _ = False -- VarPat, WildPat, LitPat, NPat
679
680 --------------
681 might_fail_lpat :: LPat Id -> Bool
682 might_fail_lpat (L _ p) = might_fail_pat p
683
684 --------------
685 tidy_lpat :: LPat Id -> LPat Id
686 tidy_lpat p = fmap tidy_pat p
687
688 --------------
689 tidy_pat :: Pat Id -> Pat Id
690 tidy_pat pat@(WildPat _) = pat
691 tidy_pat (VarPat id) = WildPat (idType (unLoc id))
692 tidy_pat (ParPat p) = tidy_pat (unLoc p)
693 tidy_pat (LazyPat p) = WildPat (hsLPatType p) -- For overlap and exhaustiveness checking
694 -- purposes, a ~pat is like a wildcard
695 tidy_pat (BangPat p) = tidy_pat (unLoc p)
696 tidy_pat (AsPat _ p) = tidy_pat (unLoc p)
697 tidy_pat (SigPatOut p _) = tidy_pat (unLoc p)
698 tidy_pat (CoPat _ pat _) = tidy_pat pat
699
700 -- These are might_fail patterns, so we map them to
701 -- WildPats. The might_fail_pat stuff arranges that the
702 -- guard says "this equation might fall through".
703 tidy_pat (NPlusKPat id _ _ _) = WildPat (idType (unLoc id))
704 tidy_pat (ViewPat _ _ ty) = WildPat ty
705 tidy_pat (ListPat _ _ (Just (ty,_))) = WildPat ty
706 tidy_pat (ConPatOut { pat_con = L _ (PatSynCon syn), pat_arg_tys = tys })
707 = WildPat (patSynInstResTy syn tys)
708
709 tidy_pat pat@(ConPatOut { pat_con = L _ con, pat_args = ps })
710 = pat { pat_args = tidy_con con ps }
711
712 tidy_pat (ListPat ps ty Nothing)
713 = unLoc $ foldr (\ x y -> mkPrefixConPat consDataCon [x,y] [ty])
714 (mkNilPat ty)
715 (map tidy_lpat ps)
716
717 -- introduce fake parallel array constructors to be able to handle parallel
718 -- arrays with the existing machinery for constructor pattern
719 --
720 tidy_pat (PArrPat ps ty)
721 = unLoc $ mkPrefixConPat (parrFakeCon (length ps))
722 (map tidy_lpat ps)
723 [ty]
724
725 tidy_pat (TuplePat ps boxity tys)
726 = unLoc $ mkPrefixConPat (tupleDataCon boxity arity)
727 (map tidy_lpat ps) tys
728 where
729 arity = length ps
730
731 tidy_pat (NPat (L _ lit) mb_neg eq) = tidyNPat tidy_lit_pat lit mb_neg eq
732 tidy_pat (LitPat lit) = tidy_lit_pat lit
733
734 tidy_pat (ConPatIn {}) = panic "Check.tidy_pat: ConPatIn"
735 tidy_pat (SplicePat {}) = panic "Check.tidy_pat: SplicePat"
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 = conLikeArity con
759
760 -- pad out all the missing fields with WildPats.
761 field_pats = case con of
762 RealDataCon dc -> map (\ f -> (flSelector f, nlWildPatId)) (dataConFieldLabels dc)
763 PatSynCon{} -> panic "Check.tidy_con: pattern synonym with record syntax"
764 all_pats = foldr (\ (L _ x) acc -> insertNm (getName (unLoc (hsRecFieldId x))) (hsRecFieldArg x) acc)
765 field_pats fs
766
767 insertNm nm p [] = [(nm,p)]
768 insertNm nm p (x@(n,_):xs)
769 | nm == n = (nm,p):xs
770 | otherwise = x : insertNm nm p xs