d715439015cfe34002c9a0c32ca70fd46fe29cf2
[ghc.git] / compiler / deSugar / MatchLit.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5
6 Pattern-matching literal patterns
7 -}
8
9 {-# LANGUAGE CPP, ScopedTypeVariables #-}
10
11 module MatchLit ( dsLit, dsOverLit, dsOverLit', hsLitKey
12 , tidyLitPat, tidyNPat
13 , matchLiterals, matchNPlusKPats, matchNPats
14 , warnAboutIdentities, warnAboutOverflowedLiterals
15 , warnAboutEmptyEnumerations
16 ) where
17
18 #include "HsVersions.h"
19
20 import GhcPrelude
21
22 import {-# SOURCE #-} Match ( match )
23 import {-# SOURCE #-} DsExpr ( dsExpr, dsSyntaxExpr )
24
25 import DsMonad
26 import DsUtils
27
28 import HsSyn
29
30 import Id
31 import CoreSyn
32 import MkCore
33 import TyCon
34 import DataCon
35 import TcHsSyn ( shortCutLit )
36 import TcType
37 import Name
38 import Type
39 import PrelNames
40 import TysWiredIn
41 import Literal
42 import SrcLoc
43 import Data.Ratio
44 import Outputable
45 import BasicTypes
46 import DynFlags
47 import Util
48 import FastString
49 import qualified GHC.LanguageExtensions as LangExt
50
51 import Control.Monad
52 import Data.Int
53 import Data.Word
54 import Data.Proxy
55
56 {-
57 ************************************************************************
58 * *
59 Desugaring literals
60 [used to be in DsExpr, but DsMeta needs it,
61 and it's nice to avoid a loop]
62 * *
63 ************************************************************************
64
65 We give int/float literals type @Integer@ and @Rational@, respectively.
66 The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
67 around them.
68
69 ToDo: put in range checks for when converting ``@i@''
70 (or should that be in the typechecker?)
71
72 For numeric literals, we try to detect there use at a standard type
73 (@Int@, @Float@, etc.) are directly put in the right constructor.
74 [NB: down with the @App@ conversion.]
75
76 See also below where we look for @DictApps@ for \tr{plusInt}, etc.
77 -}
78
79 dsLit :: HsLit GhcRn -> DsM CoreExpr
80 dsLit (HsStringPrim _ s) = return (Lit (MachStr s))
81 dsLit (HsCharPrim _ c) = return (Lit (MachChar c))
82 dsLit (HsIntPrim _ i) = return (Lit (MachInt i))
83 dsLit (HsWordPrim _ w) = return (Lit (MachWord w))
84 dsLit (HsInt64Prim _ i) = return (Lit (MachInt64 i))
85 dsLit (HsWord64Prim _ w) = return (Lit (MachWord64 w))
86 dsLit (HsFloatPrim _ f) = return (Lit (MachFloat (fl_value f)))
87 dsLit (HsDoublePrim _ d) = return (Lit (MachDouble (fl_value d)))
88 dsLit (HsChar _ c) = return (mkCharExpr c)
89 dsLit (HsString _ str) = mkStringExprFS str
90 dsLit (HsInteger _ i _) = mkIntegerExpr i
91 dsLit (HsInt _ i) = do dflags <- getDynFlags
92 return (mkIntExpr dflags (il_value i))
93
94 dsLit (HsRat _ (FL _ _ val) ty) = do
95 num <- mkIntegerExpr (numerator val)
96 denom <- mkIntegerExpr (denominator val)
97 return (mkCoreConApps ratio_data_con [Type integer_ty, num, denom])
98 where
99 (ratio_data_con, integer_ty)
100 = case tcSplitTyConApp ty of
101 (tycon, [i_ty]) -> ASSERT(isIntegerTy i_ty && tycon `hasKey` ratioTyConKey)
102 (head (tyConDataCons tycon), i_ty)
103 x -> pprPanic "dsLit" (ppr x)
104
105 dsLit (XLit x) = pprPanic "dsLit" (ppr x)
106
107 dsOverLit :: HsOverLit GhcTc -> DsM CoreExpr
108 dsOverLit lit = do { dflags <- getDynFlags
109 ; warnAboutOverflowedLiterals dflags lit
110 ; dsOverLit' dflags lit }
111
112 dsOverLit' :: DynFlags -> HsOverLit GhcTc -> DsM CoreExpr
113 -- Post-typechecker, the HsExpr field of an OverLit contains
114 -- (an expression for) the literal value itself
115 dsOverLit' dflags (OverLit { ol_val = val, ol_ext = OverLitTc rebindable ty
116 , ol_witness = witness })
117 | not rebindable
118 , Just expr <- shortCutLit dflags val ty = dsExpr expr -- Note [Literal short cut]
119 | otherwise = dsExpr witness
120 dsOverLit' _ XOverLit{} = panic "dsOverLit'"
121 {-
122 Note [Literal short cut]
123 ~~~~~~~~~~~~~~~~~~~~~~~~
124 The type checker tries to do this short-cutting as early as possible, but
125 because of unification etc, more information is available to the desugarer.
126 And where it's possible to generate the correct literal right away, it's
127 much better to do so.
128
129
130 ************************************************************************
131 * *
132 Warnings about overflowed literals
133 * *
134 ************************************************************************
135
136 Warn about functions like toInteger, fromIntegral, that convert
137 between one type and another when the to- and from- types are the
138 same. Then it's probably (albeit not definitely) the identity
139 -}
140
141 warnAboutIdentities :: DynFlags -> CoreExpr -> Type -> DsM ()
142 warnAboutIdentities dflags (Var conv_fn) type_of_conv
143 | wopt Opt_WarnIdentities dflags
144 , idName conv_fn `elem` conversionNames
145 , Just (arg_ty, res_ty) <- splitFunTy_maybe type_of_conv
146 , arg_ty `eqType` res_ty -- So we are converting ty -> ty
147 = warnDs (Reason Opt_WarnIdentities)
148 (vcat [ text "Call of" <+> ppr conv_fn <+> dcolon <+> ppr type_of_conv
149 , nest 2 $ text "can probably be omitted"
150 ])
151 warnAboutIdentities _ _ _ = return ()
152
153 conversionNames :: [Name]
154 conversionNames
155 = [ toIntegerName, toRationalName
156 , fromIntegralName, realToFracName ]
157 -- We can't easily add fromIntegerName, fromRationalName,
158 -- because they are generated by literals
159
160 warnAboutOverflowedLiterals :: DynFlags -> HsOverLit GhcTc -> DsM ()
161 warnAboutOverflowedLiterals dflags lit
162 | wopt Opt_WarnOverflowedLiterals dflags
163 , Just (i, tc) <- getIntegralLit lit
164 = if tc == intTyConName then check i tc (Proxy :: Proxy Int)
165 else if tc == int8TyConName then check i tc (Proxy :: Proxy Int8)
166 else if tc == int16TyConName then check i tc (Proxy :: Proxy Int16)
167 else if tc == int32TyConName then check i tc (Proxy :: Proxy Int32)
168 else if tc == int64TyConName then check i tc (Proxy :: Proxy Int64)
169 else if tc == wordTyConName then check i tc (Proxy :: Proxy Word)
170 else if tc == word8TyConName then check i tc (Proxy :: Proxy Word8)
171 else if tc == word16TyConName then check i tc (Proxy :: Proxy Word16)
172 else if tc == word32TyConName then check i tc (Proxy :: Proxy Word32)
173 else if tc == word64TyConName then check i tc (Proxy :: Proxy Word64)
174 else return ()
175
176 | otherwise = return ()
177 where
178 check :: forall a. (Bounded a, Integral a) => Integer -> Name -> Proxy a -> DsM ()
179 check i tc _proxy
180 = when (i < minB || i > maxB) $ do
181 warnDs (Reason Opt_WarnOverflowedLiterals)
182 (vcat [ text "Literal" <+> integer i
183 <+> text "is out of the" <+> ppr tc <+> ptext (sLit "range")
184 <+> integer minB <> text ".." <> integer maxB
185 , sug ])
186 where
187 minB = toInteger (minBound :: a)
188 maxB = toInteger (maxBound :: a)
189 sug | minB == -i -- Note [Suggest NegativeLiterals]
190 , i > 0
191 , not (xopt LangExt.NegativeLiterals dflags)
192 = text "If you are trying to write a large negative literal, use NegativeLiterals"
193 | otherwise = Outputable.empty
194
195 {-
196 Note [Suggest NegativeLiterals]
197 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
198 If you write
199 x :: Int8
200 x = -128
201 it'll parse as (negate 128), and overflow. In this case, suggest NegativeLiterals.
202 We get an erroneous suggestion for
203 x = 128
204 but perhaps that does not matter too much.
205 -}
206
207 warnAboutEmptyEnumerations :: DynFlags -> LHsExpr GhcTc -> Maybe (LHsExpr GhcTc)
208 -> LHsExpr GhcTc -> DsM ()
209 -- Warns about [2,3 .. 1] which returns the empty list
210 -- Only works for integral types, not floating point
211 warnAboutEmptyEnumerations dflags fromExpr mThnExpr toExpr
212 | wopt Opt_WarnEmptyEnumerations dflags
213 , Just (from,tc) <- getLHsIntegralLit fromExpr
214 , Just mThn <- traverse getLHsIntegralLit mThnExpr
215 , Just (to,_) <- getLHsIntegralLit toExpr
216 , let check :: forall a. (Enum a, Num a) => Proxy a -> DsM ()
217 check _proxy
218 = when (null enumeration) $
219 warnDs (Reason Opt_WarnEmptyEnumerations) (text "Enumeration is empty")
220 where
221 enumeration :: [a]
222 enumeration = case mThn of
223 Nothing -> [fromInteger from .. fromInteger to]
224 Just (thn,_) -> [fromInteger from, fromInteger thn .. fromInteger to]
225
226 = if tc == intTyConName then check (Proxy :: Proxy Int)
227 else if tc == int8TyConName then check (Proxy :: Proxy Int8)
228 else if tc == int16TyConName then check (Proxy :: Proxy Int16)
229 else if tc == int32TyConName then check (Proxy :: Proxy Int32)
230 else if tc == int64TyConName then check (Proxy :: Proxy Int64)
231 else if tc == wordTyConName then check (Proxy :: Proxy Word)
232 else if tc == word8TyConName then check (Proxy :: Proxy Word8)
233 else if tc == word16TyConName then check (Proxy :: Proxy Word16)
234 else if tc == word32TyConName then check (Proxy :: Proxy Word32)
235 else if tc == word64TyConName then check (Proxy :: Proxy Word64)
236 else if tc == integerTyConName then check (Proxy :: Proxy Integer)
237 else return ()
238
239 | otherwise = return ()
240
241 getLHsIntegralLit :: LHsExpr GhcTc -> Maybe (Integer, Name)
242 -- See if the expression is an Integral literal
243 -- Remember to look through automatically-added tick-boxes! (Trac #8384)
244 getLHsIntegralLit (L _ (HsPar _ e)) = getLHsIntegralLit e
245 getLHsIntegralLit (L _ (HsTick _ _ e)) = getLHsIntegralLit e
246 getLHsIntegralLit (L _ (HsBinTick _ _ _ e)) = getLHsIntegralLit e
247 getLHsIntegralLit (L _ (HsOverLit _ over_lit)) = getIntegralLit over_lit
248 getLHsIntegralLit _ = Nothing
249
250 getIntegralLit :: HsOverLit GhcTc -> Maybe (Integer, Name)
251 getIntegralLit (OverLit { ol_val = HsIntegral i, ol_ext = OverLitTc _ ty })
252 | Just tc <- tyConAppTyCon_maybe ty
253 = Just (il_value i, tyConName tc)
254 getIntegralLit _ = Nothing
255
256 {-
257 ************************************************************************
258 * *
259 Tidying lit pats
260 * *
261 ************************************************************************
262 -}
263
264 tidyLitPat :: HsLit GhcTc -> Pat GhcTc
265 -- Result has only the following HsLits:
266 -- HsIntPrim, HsWordPrim, HsCharPrim, HsFloatPrim
267 -- HsDoublePrim, HsStringPrim, HsString
268 -- * HsInteger, HsRat, HsInt can't show up in LitPats
269 -- * We get rid of HsChar right here
270 tidyLitPat (HsChar src c) = unLoc (mkCharLitPat src c)
271 tidyLitPat (HsString src s)
272 | lengthFS s <= 1 -- Short string literals only
273 = unLoc $ foldr (\c pat -> mkPrefixConPat consDataCon
274 [mkCharLitPat src c, pat] [charTy])
275 (mkNilPat charTy) (unpackFS s)
276 -- The stringTy is the type of the whole pattern, not
277 -- the type to instantiate (:) or [] with!
278 tidyLitPat lit = LitPat noExt lit
279
280 ----------------
281 tidyNPat :: HsOverLit GhcTc -> Maybe (SyntaxExpr GhcTc) -> SyntaxExpr GhcTc
282 -> Type
283 -> Pat GhcTc
284 tidyNPat (OverLit (OverLitTc False ty) val _) mb_neg _eq outer_ty
285 -- False: Take short cuts only if the literal is not using rebindable syntax
286 --
287 -- Once that is settled, look for cases where the type of the
288 -- entire overloaded literal matches the type of the underlying literal,
289 -- and in that case take the short cut
290 -- NB: Watch out for weird cases like Trac #3382
291 -- f :: Int -> Int
292 -- f "blah" = 4
293 -- which might be ok if we have 'instance IsString Int'
294 --
295 | not type_change, isIntTy ty, Just int_lit <- mb_int_lit
296 = mk_con_pat intDataCon (HsIntPrim NoSourceText int_lit)
297 | not type_change, isWordTy ty, Just int_lit <- mb_int_lit
298 = mk_con_pat wordDataCon (HsWordPrim NoSourceText int_lit)
299 | not type_change, isStringTy ty, Just str_lit <- mb_str_lit
300 = tidyLitPat (HsString NoSourceText str_lit)
301 -- NB: do /not/ convert Float or Double literals to F# 3.8 or D# 5.3
302 -- If we do convert to the constructor form, we'll generate a case
303 -- expression on a Float# or Double# and that's not allowed in Core; see
304 -- Trac #9238 and Note [Rules for floating-point comparisons] in PrelRules
305 where
306 -- Sometimes (like in test case
307 -- overloadedlists/should_run/overloadedlistsrun04), the SyntaxExprs include
308 -- type-changing wrappers (for example, from Id Int to Int, for the identity
309 -- type family Id). In these cases, we can't do the short-cut.
310 type_change = not (outer_ty `eqType` ty)
311
312 mk_con_pat :: DataCon -> HsLit GhcTc -> Pat GhcTc
313 mk_con_pat con lit
314 = unLoc (mkPrefixConPat con [noLoc $ LitPat noExt lit] [])
315
316 mb_int_lit :: Maybe Integer
317 mb_int_lit = case (mb_neg, val) of
318 (Nothing, HsIntegral i) -> Just (il_value i)
319 (Just _, HsIntegral i) -> Just (-(il_value i))
320 _ -> Nothing
321
322 mb_str_lit :: Maybe FastString
323 mb_str_lit = case (mb_neg, val) of
324 (Nothing, HsIsString _ s) -> Just s
325 _ -> Nothing
326
327 tidyNPat over_lit mb_neg eq outer_ty
328 = NPat outer_ty (noLoc over_lit) mb_neg eq
329
330 {-
331 ************************************************************************
332 * *
333 Pattern matching on LitPat
334 * *
335 ************************************************************************
336 -}
337
338 matchLiterals :: [Id]
339 -> Type -- Type of the whole case expression
340 -> [[EquationInfo]] -- All PgLits
341 -> DsM MatchResult
342
343 matchLiterals (var:vars) ty sub_groups
344 = ASSERT( notNull sub_groups && all notNull sub_groups )
345 do { -- Deal with each group
346 ; alts <- mapM match_group sub_groups
347
348 -- Combine results. For everything except String
349 -- we can use a case expression; for String we need
350 -- a chain of if-then-else
351 ; if isStringTy (idType var) then
352 do { eq_str <- dsLookupGlobalId eqStringName
353 ; mrs <- mapM (wrap_str_guard eq_str) alts
354 ; return (foldr1 combineMatchResults mrs) }
355 else
356 return (mkCoPrimCaseMatchResult var ty alts)
357 }
358 where
359 match_group :: [EquationInfo] -> DsM (Literal, MatchResult)
360 match_group eqns
361 = do dflags <- getDynFlags
362 let LitPat _ hs_lit = firstPat (head eqns)
363 match_result <- match vars ty (shiftEqns eqns)
364 return (hsLitKey dflags hs_lit, match_result)
365
366 wrap_str_guard :: Id -> (Literal,MatchResult) -> DsM MatchResult
367 -- Equality check for string literals
368 wrap_str_guard eq_str (MachStr s, mr)
369 = do { -- We now have to convert back to FastString. Perhaps there
370 -- should be separate MachBytes and MachStr constructors?
371 let s' = mkFastStringByteString s
372 ; lit <- mkStringExprFS s'
373 ; let pred = mkApps (Var eq_str) [Var var, lit]
374 ; return (mkGuardedMatchResult pred mr) }
375 wrap_str_guard _ (l, _) = pprPanic "matchLiterals/wrap_str_guard" (ppr l)
376
377 matchLiterals [] _ _ = panic "matchLiterals []"
378
379 ---------------------------
380 hsLitKey :: DynFlags -> HsLit GhcTc -> Literal
381 -- Get the Core literal corresponding to a HsLit.
382 -- It only works for primitive types and strings;
383 -- others have been removed by tidy
384 -- For HsString, it produces a MachStr, which really represents an _unboxed_
385 -- string literal; and we deal with it in matchLiterals above. Otherwise, it
386 -- produces a primitive Literal of type matching the original HsLit.
387 -- In the case of the fixed-width numeric types, we need to wrap here
388 -- because Literal has an invariant that the literal is in range, while
389 -- HsLit does not.
390 hsLitKey dflags (HsIntPrim _ i) = mkMachIntWrap dflags i
391 hsLitKey dflags (HsWordPrim _ w) = mkMachWordWrap dflags w
392 hsLitKey _ (HsInt64Prim _ i) = mkMachInt64Wrap i
393 hsLitKey _ (HsWord64Prim _ w) = mkMachWord64Wrap w
394 hsLitKey _ (HsCharPrim _ c) = mkMachChar c
395 hsLitKey _ (HsFloatPrim _ f) = mkMachFloat (fl_value f)
396 hsLitKey _ (HsDoublePrim _ d) = mkMachDouble (fl_value d)
397 hsLitKey _ (HsString _ s) = MachStr (fastStringToByteString s)
398 hsLitKey _ l = pprPanic "hsLitKey" (ppr l)
399
400 {-
401 ************************************************************************
402 * *
403 Pattern matching on NPat
404 * *
405 ************************************************************************
406 -}
407
408 matchNPats :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult
409 matchNPats (var:vars) ty (eqn1:eqns) -- All for the same literal
410 = do { let NPat _ (L _ lit) mb_neg eq_chk = firstPat eqn1
411 ; lit_expr <- dsOverLit lit
412 ; neg_lit <- case mb_neg of
413 Nothing -> return lit_expr
414 Just neg -> dsSyntaxExpr neg [lit_expr]
415 ; pred_expr <- dsSyntaxExpr eq_chk [Var var, neg_lit]
416 ; match_result <- match vars ty (shiftEqns (eqn1:eqns))
417 ; return (mkGuardedMatchResult pred_expr match_result) }
418 matchNPats vars _ eqns = pprPanic "matchOneNPat" (ppr (vars, eqns))
419
420 {-
421 ************************************************************************
422 * *
423 Pattern matching on n+k patterns
424 * *
425 ************************************************************************
426
427 For an n+k pattern, we use the various magic expressions we've been given.
428 We generate:
429 \begin{verbatim}
430 if ge var lit then
431 let n = sub var lit
432 in <expr-for-a-successful-match>
433 else
434 <try-next-pattern-or-whatever>
435 \end{verbatim}
436 -}
437
438 matchNPlusKPats :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult
439 -- All NPlusKPats, for the *same* literal k
440 matchNPlusKPats (var:vars) ty (eqn1:eqns)
441 = do { let NPlusKPat _ (L _ n1) (L _ lit1) lit2 ge minus = firstPat eqn1
442 ; lit1_expr <- dsOverLit lit1
443 ; lit2_expr <- dsOverLit lit2
444 ; pred_expr <- dsSyntaxExpr ge [Var var, lit1_expr]
445 ; minusk_expr <- dsSyntaxExpr minus [Var var, lit2_expr]
446 ; let (wraps, eqns') = mapAndUnzip (shift n1) (eqn1:eqns)
447 ; match_result <- match vars ty eqns'
448 ; return (mkGuardedMatchResult pred_expr $
449 mkCoLetMatchResult (NonRec n1 minusk_expr) $
450 adjustMatchResult (foldr1 (.) wraps) $
451 match_result) }
452 where
453 shift n1 eqn@(EqnInfo { eqn_pats = NPlusKPat _ (L _ n) _ _ _ _ : pats })
454 = (wrapBind n n1, eqn { eqn_pats = pats })
455 -- The wrapBind is a no-op for the first equation
456 shift _ e = pprPanic "matchNPlusKPats/shift" (ppr e)
457
458 matchNPlusKPats vars _ eqns = pprPanic "matchNPlusKPats" (ppr (vars, eqns))