5.2. Warnings and sanity-checking¶
GHC has a number of options that select which types of non-fatal error
messages, otherwise known as warnings, can be generated during compilation.
Some options control individual warnings and others control collections
of warnings.
Use -W⟨wflag⟩
to turn on an individual warning or a collection, or use
-Wno-⟨wflag⟩
to turn it off.
Use -Werror
to make all warnings into fatal errors, or -Werror=⟨wflag⟩
to
make a specific warning into an error. Reverse this with -Wwarn
to make all
warnings non-fatal, or -Wwarn=⟨wflag⟩
to make a specific warning non-fatal.
Note
In GHC < 8 the syntax for -W⟨wflag⟩
was -fwarn-⟨wflag⟩
(e.g. -fwarn-incomplete-patterns
).
This spelling is deprecated, but still accepted for backwards compatibility.
Likewise, -Wno-⟨wflag⟩
used to be fno-warn-⟨wflag⟩
(e.g. -fno-warn-incomplete-patterns
).
5.2.1. Warning groups¶
The following flags are simple ways to select standard “packages” of
warnings. They can be reversed using -Wno-⟨group⟩
, which has the same effect
as -Wno-...
for every individual warning in the group.
-
-Wdefault
¶ Since: 8.0 By default, you get a standard set of warnings which are generally likely to indicate bugs in your program. These are:
-
-W
¶ Provides the standard warnings plus
-
-Wall
¶ Turns on all warning options that indicate potentially suspicious code. They include all warnings in
-Wextra
, plus:
-
-Weverything
¶ Since: 8.0 Turns on every single warning supported by the compiler.
-
-Wcompat
¶ Since: 8.0 Turns on warnings that will be enabled by default in the future, but remain off in normal compilations for the time being. This allows library authors eager to make their code future compatible to adapt to new features before they even generate warnings.
This currently enables
When a warning is emitted, the specific warning flag which controls it is shown, but the group can optionally be shown as well:
-
-fshow-warning-groups
¶ Default: off When showing which flag controls a warning, also show the respective warning group flag(s) that warning is contained in.
5.2.2. Treating warnings as fatal errors¶
These options control which warnings are considered fatal and cause compilation to abort.
-
-Werror
¶ Since: 6.8 ( -Wwarn
)Makes any warning into a fatal error. Useful so that you don’t miss warnings when doing batch compilation. To reverse
-Werror
and stop treating any warnings as errors use-Wwarn
, or use-Wwarn=⟨wflag⟩
to stop treating specific warnings as errors.
-
-Werror
=⟨wflag⟩
Implies: -W⟨wflag⟩
Makes a specific warning into a fatal error. The warning will be enabled if it hasn’t been enabled yet. Can be reversed with
-Wwarn=⟨wflag⟩
.-Werror=⟨group⟩
has the same effect as-Werror=...
for each warning flag in the group (for example,-Werror=compat
will turn every warning in the-Wcompat
group into a fatal error).
-
-Wwarn
¶ Warnings are treated only as warnings, not as errors. This is the default, but can be useful to negate a
-Werror
flag.
-
-Wwarn
=⟨wflag⟩
Causes a specific warning to be treated as normal warning, not fatal error.
Note that it doesn’t fully negate the effects of
-Werror=⟨wflag⟩
- the warning will still be enabled.-Wwarn=⟨group⟩
has the same effect as-Wwarn=...
for each warning flag in the group (for example,-Wwarn=compat
will mark every warning in the-Wcompat
group as non-fatal).
-
-Wno-error
=⟨wflag⟩
Alternative spelling for
-Wwarn=⟨wflag⟩
.
5.2.3. Individual warning options¶
The full set of warning options is described below. To turn off any
warning, simply give the corresponding -Wno-...
option on the
command line. For backwards compatibility with GHC versions prior to 8.0,
all these warnings can still be controlled with -f(no-)warn-*
instead
of -W(no-)*
.
-
-Wunrecognised-warning-flags
¶ Since: 8.0 Default: on Enables warnings when the compiler encounters a
-W...
flag that is not recognised.
-
-Wcompat-unqualified-imports
¶ Since: 8.10 Warns on unqualified imports of core library modules which are subject to change in future GHC releases. Currently the following modules are covered by this warning:
Data.List
due to the future addition ofData.List.singleton
and specialisation of exports to the[]
type. See the mailing list for details.
This warning can be addressed by either adding an explicit import list or using a
qualified
import.
-
-Wprepositive-qualified-module
¶ Since: 8.10 Normally, imports are qualified prepositively:
import qualified M
. By usingImportQualifiedPost
, the qualified keyword can be used after the module name. Like so:import M qualified
. This will warn when the first, prepositive syntax is used.
-
-Wtyped-holes
¶ Since: 7.8 Default: on Determines whether the compiler reports typed holes warnings. Has no effect unless typed holes errors are deferred until runtime. See Typed Holes and Deferring type errors to runtime.
-
-Wdeferred-type-errors
¶ Since: 8.0 Default: on Causes a warning to be reported when a type error is deferred until runtime. See Deferring type errors to runtime.
-
-Wdeferred-out-of-scope-variables
¶ Since: 8.0 Warn when a deferred out-of-scope variable is encountered. See Deferring type errors to runtime.
-
-Wpartial-type-signatures
¶ Since: 7.10 Default: on Determines whether the compiler reports holes in partial type signatures as warnings. Has no effect unless
PartialTypeSignatures
is enabled, which controls whether errors should be generated for holes in types or not. See Partial Type Signatures.
-
-fhelpful-errors
¶ Since: 7.4 Default: on When a name or package is not found in scope, make suggestions for the name or package you might have meant instead.
-
-Wunrecognised-pragmas
¶ Since: 6.10 Default: on Causes a warning to be emitted when a pragma that GHC doesn’t recognise is used. As well as pragmas that GHC itself uses, GHC also recognises pragmas known to be used by other tools, e.g.
OPTIONS_HUGS
andDERIVE
.
-
-Wmisplaced-pragmas
¶ Since: 9.4 Default: on Warn when a pragma that should only appear in the header of a module, such as a LANGUAGE or OPTIONS_GHC pragma, appears in the body of the module instead.
-
-Wmissed-specialisations
¶ Since: 8.0 Default: off Emits a warning if GHC cannot specialise an overloaded function, usually because the function needs an
INLINABLE
pragma. Reports when the situation arises during specialisation of an imported function.This form is intended to catch cases where an imported function that is marked as
INLINABLE
(presumably to enable specialisation) cannot be specialised as it calls other functions that are themselves not specialised.Note that this warning will not throw errors if used with
-Werror
.
-
-Wmissed-specializations
¶ Alias for
-Wmissed-specialisations
-
-Wall-missed-specialisations
¶ Since: 8.0 Default: off Emits a warning if GHC cannot specialise an overloaded function, usually because the function needs an
INLINABLE
pragma. Reports all such situations.Note that this warning will not throw errors if used with
-Werror
.
-
-Wall-missed-specializations
¶ Alias for
-Wall-missed-specialisations
-
-Wextended-warnings
¶ Since: 9.8.1 Default: on Causes a warning to be emitted when a module, function or type with a
WARNING
orDEPRECATED
pragma is used, regardless of the category which may be associated with the pragma. See WARNING and DEPRECATED pragmas for more details on the pragmas. This implies-Wdeprecations
and all-Wx-⟨category⟩
flags.
-
-Wx-⟨category⟩
¶ Since: 9.8.1 Default: on Causes a warning to be emitted when a module, function or type with a
WARNING in "x-⟨category⟩"
pragma is used. See WARNING and DEPRECATED pragmas for more details on the pragmas.
-
-Wdeprecations
¶ Default: on Causes a warning to be emitted when a module, function or type with
DEPRECATED pragma
, or aWARNING
pragma with thedeprecated
category, is used. See WARNING and DEPRECATED pragmas for more details on the pragmas.
-
-Wwarnings-deprecations
¶ Since: 6.10 Default: on Causes a warning to be emitted when a module, function or type with
DEPRECATED pragma
, or aWARNING
pragma with thedeprecated
category, is used. See WARNING and DEPRECATED pragmas for more details on the pragmas. An alias for-Wdeprecations
.
-
-Wnoncanonical-monad-instances
¶ Since: 8.0 Default: on Warn if noncanonical
Applicative
orMonad
instances declarations are detected.When this warning is enabled, the following conditions are verified:
In
Monad
instances declarations warn if any of the following conditions does not hold:- If
return
is defined it must be canonical (i.e.return = pure
). - If
(>>)
is defined it must be canonical (i.e.(>>) = (*>)
).
Moreover, in
Applicative
instance declarations:- Warn if
pure
is defined backwards (i.e.pure = return
). - Warn if
(*>)
is defined backwards (i.e.(*>) = (>>)
).
- If
-
-Wnoncanonical-monadfail-instances
¶ Since: 8.0 This warning is deprecated. It no longer has any effect since GHC 8.8. It was used during the transition period of the MonadFail proposal, to detect when an instance of the
Monad
class was not defined viaMonadFail
, or when aMonadFail
instance was defined backwards, using the method inMonad
.
-
-Wnoncanonical-monoid-instances
¶ Since: 8.0 Default: on Warn if noncanonical
Semigroup
orMonoid
instances declarations are detected.When this warning is enabled, the following conditions are verified:
In
Monoid
instances declarations warn if any of the following conditions does not hold:- If
mappend
is defined it must be canonical (i.e.mappend = (Data.Semigroup.<>)
).
Moreover, in
Semigroup
instance declarations:- Warn if
(<>)
is defined backwards (i.e.(<>) = mappend
).
- If
-
-Wmissing-monadfail-instances
¶ Since: 8.0 This warning is deprecated. It no longer has any effect since GHC 8.8. It was used during the transition period of the MonadFail proposal, to warn when a failable pattern is used in a do-block that does not have a
MonadFail
instance.
-
-Wsemigroup
¶ Since: 8.0 This warning is deprecated. It no longer has any effect since GHC 9.8. It was used during the transition period of the semigroup proposal, to warn when an instance of
Monoid
was not an instance ofSemigroup
, or when a custom local operator(<>)
could clash with (<>), now exported fromPrelude
.
-
-Wdeprecated-flags
¶ Since: 6.10 Default: on Causes a warning to be emitted when a deprecated command-line flag is used.
-
-Wunsupported-calling-conventions
¶ Since: 7.6 Causes a warning to be emitted for foreign declarations that use unsupported calling conventions. In particular, if the
stdcall
calling convention is used on an architecture other than i386 then it will be treated asccall
.
-
-Wdodgy-foreign-imports
¶ Since: 6.10 Causes a warning to be emitted for foreign imports of the following form:
foreign import "f" f :: FunPtr t
on the grounds that it probably should be
foreign import "&f" f :: FunPtr t
The first form declares that
f
is a (pure) C function that takes no arguments and returns a pointer to a C function with typet
, whereas the second form declares thatf
itself is a C function with typet
. The first declaration is usually a mistake, and one that is hard to debug because it results in a crash, hence this warning.
-
-Wdodgy-exports
¶ Since: 6.12 Causes a warning to be emitted when a datatype
T
is exported with all constructors, i.e.T(..)
, but is it just a type synonym.Also causes a warning to be emitted when a module is re-exported, but that module exports nothing.
-
-Wdodgy-imports
¶ Since: 6.8 Causes a warning to be emitted in the following cases:
- When a datatype
T
is imported with all constructors, i.e.T(..)
, but has been exported abstractly, i.e.T
. - When an
import
statement hides an entity that is not exported.
- When a datatype
-
-Woverflowed-literals
¶ Since: 7.8 Causes a warning to be emitted if a literal will overflow, e.g.
300 :: Word8
.
-
-Wempty-enumerations
¶ Since: 7.8 Causes a warning to be emitted if an enumeration is empty, e.g.
[5 .. 3]
.
-
-Wderiving-defaults
¶ Since: 8.10 Causes a warning when both
DeriveAnyClass
andGeneralizedNewtypeDeriving
are enabled and no explicit deriving strategy is in use. For example, this would result a warning:class C a newtype T a = MkT a deriving C
-
-Wduplicate-constraints
¶ Since: 7.8 Have the compiler warn about duplicate constraints in a type signature. For example
f :: (Eq a, Show a, Eq a) => a -> a
The warning will indicate the duplicated
Eq a
constraint.This option is now deprecated in favour of
-Wredundant-constraints
.
-
-Wredundant-constraints
¶ Since: 8.0 Have the compiler warn about redundant constraints in a type signature. In particular:
A redundant constraint within the type signature itself:
f :: (Eq a, Ord a) => a -> a
The warning will indicate the redundant
Eq a
constraint: it is subsumed by theOrd a
constraint.A constraint in the type signature is not used in the code it covers:
f :: Eq a => a -> a -> Bool f x y = True
The warning will indicate the redundant
Eq a
constraint: : it is not used by the definition off
.)
Similar warnings are given for a redundant constraint in an instance declaration.
When turning on, you can suppress it on a per-module basis with
-Wno-redundant-constraints
. Occasionally you may specifically want a function to have a more constrained signature than necessary, perhaps to leave yourself wiggle-room for changing the implementation without changing the API. In that case, you can suppress the warning on a per-function basis, using a call in a dead binding. For example:f :: Eq a => a -> a -> Bool f x y = True where _ = x == x -- Suppress the redundant-constraint warning for (Eq a)
Here the call to
(==)
makes GHC think that the(Eq a)
constraint is needed, so no warning is issued.
-
-Wduplicate-exports
¶ Since: at least 5.04 Default: on Have the compiler warn about duplicate entries in export lists. This is useful information if you maintain large export lists, and want to avoid the continued export of a definition after you’ve deleted (one) mention of it in the export list.
-
-Whi-shadowing
¶ Since: at least 5.04, deprecated Causes the compiler to emit a warning when a module or interface file in the current directory is shadowing one with the same module name in a library or other directory.
This flag was not implemented correctly and is now deprecated. It will be removed in a later version of GHC.
-
-Widentities
¶ Since: 7.2 Causes the compiler to emit a warning when a Prelude numeric conversion converts a type
T
to the same typeT
; such calls are probably no-ops and can be omitted. The functions checked for are:toInteger
,toRational
,fromIntegral
, andrealToFrac
.
-
-Wimplicit-kind-vars
¶ Since: 8.6 This warning is deprecated. It no longer has any effect since GHC 8.10. It was used to detect if a kind variable is not explicitly quantified over. For instance, the following would produce a warning:
f :: forall (a :: k). Proxy a
This is now an error and can be fixed by explicitly quantifying over
k
:f :: forall k (a :: k). Proxy a
or
f :: forall {k} (a :: k). Proxy a
-
-Wimplicit-lift
¶ Since: 9.2 Template Haskell quotes referring to local variables bound outside of the quote are implicitly converted to use
lift
. For example,f x = [| reverse x |]
becomesf x = [| reverse $(lift x) |])
. This flag issues a warning for every such implicit addition oflift
. This can be useful when debugging more complex staged programs, where an implicitlift
can accidentally conceal a variable used at a wrong stage.
-
-Wimplicit-prelude
¶ Since: 6.8 Default: off Have the compiler warn if the Prelude is implicitly imported. This happens unless either the Prelude module is explicitly imported with an
import ... Prelude ...
line, or this implicit import is disabled (either byNoImplicitPrelude
or aLANGUAGE NoImplicitPrelude
pragma).Note that no warning is given for syntax that implicitly refers to the Prelude, even if
NoImplicitPrelude
would change whether it refers to the Prelude. For example, no warning is given when368
meansPrelude.fromInteger (368::Prelude.Integer)
(wherePrelude
refers to the actual Prelude module, regardless of the imports of the module being compiled).
-
-Wincomplete-patterns
¶ Since: 5.04 The option
-Wincomplete-patterns
warns about places where a pattern-match might fail at runtime. The functiong
below will fail when applied to non-empty lists, so the compiler will emit a warning about this when-Wincomplete-patterns
is enabled.g [] = 2
This option isn’t enabled by default because it can be a bit noisy, and it doesn’t always indicate a bug in the program. However, it’s generally considered good practice to cover all the cases in your functions, and it is switched on by
-W
.
-
-Wincomplete-uni-patterns
¶ Since: 7.2 The flag
-Wincomplete-uni-patterns
is similar to-Wincomplete-patterns
, except that it applies only to lambda-expressions and pattern bindings, constructs that only allow a single pattern:h = \[] -> 2 Just k = f y
Furthermore, this flag also applies to lazy patterns, since they are syntactic sugar for pattern bindings. For example,
f ~(Just x) = (x,x)
is equivalent tof y = let Just x = y in (x,x)
.
-
-fmax-pmcheck-models
=⟨n⟩
¶ Since: 8.10 Default: 30 The pattern match checker works by assigning symbolic values to each pattern. We call each such assignment a ‘model’. Now, each pattern match clause leads to potentially multiple splits of that model, encoding different ways for the pattern match to fail. For example, when matching
x
againstJust 4
, we split each incoming matching model into two uncovered sub-models: One wherex
isNothing
and one wherex
isJust y
buty
is not4
.This can be exponential in the arity of the pattern and in the number of guards in some cases. The
-fmax-pmcheck-models=⟨n⟩
limit makes sure we scale polynomially in the number of patterns, by forgetting refined information gained from a partially successful match. For the above example, if we had a limit of 1, we would continue checking the next clause with the original, unrefined model.
-
-Wincomplete-record-updates
¶ Since: 6.4 The function
f
below will fail when applied toBar
, so the compiler will emit a warning about this when-Wincomplete-record-updates
is enabled.data Foo = Foo { x :: Int } | Bar f :: Foo -> Foo f foo = foo { x = 6 }
This option isn’t enabled by default because it can be very noisy, and it often doesn’t indicate a bug in the program.
-
-Wincomplete-record-selectors
¶ Since: 9.10 When a record selector is applied to a constructor that does not contain that field, it will produce an error. For example
data T = T1 | T2 { x :: Int } f :: T -> Int f a = x a -- `f T1` will fail g1 :: HasField "x" t Int => t -> Int g1 a = 1 + getField @"x" a g2 :: T -> Int g2 a = g1 a + 2 -- `g2 T1` will fail as well
The warning warns about cases like that. It also takes into account previously pattern-matched cases, for example
d :: T -> Int d T1 = 0 d a = x a -- would not warn
-
-Wmissing-deriving-strategies
¶ Since: 8.8.1 Default: off The datatype below derives the
Eq
typeclass, but doesn’t specify a strategy. When-Wmissing-deriving-strategies
is enabled, the compiler will emit a warning about this.data Foo a = Foo a deriving (Eq)
The compiler will warn here that the deriving clause doesn’t specify a strategy. If the warning is enabled, but
DerivingStrategies
is not enabled, the compiler will suggest turning on theDerivingStrategies
extension.
-
-Wmissing-fields
¶ Since: at least 5.04 This option is on by default, and warns you whenever the construction of a labelled field constructor isn’t complete, missing initialisers for one or more fields. While not an error (the missing fields are initialised with bottoms), it is often an indication of a programmer error.
-
-Wmissing-export-lists
¶ Since: 8.4 This flag warns if you declare a module without declaring an explicit export list. For example
module M where p x = x
The
-Wmissing-export-lists
flag will warn thatM
does not declare an export list. Declaring an explicit export list forM
enables GHC dead code analysis, prevents accidental export of names and can ease optimizations like inlining.
-
-Wmissing-import-lists
¶ Since: 7.0 This flag warns if you use an unqualified
import
declaration that does not explicitly list the entities brought into scope. For examplemodule M where import X( f ) import Y import qualified Z p x = f x x
The
-Wmissing-import-lists
flag will warn about the import ofY
but notX
If moduleY
is later changed to export (say)f
, then the reference tof
inM
will become ambiguous. No warning is produced for the import ofZ
because extendingZ
’s exports would be unlikely to produce ambiguity inM
.
-
-Wmissing-methods
¶ Since: at least 5.04 Default: on This option warns you whenever an instance declaration is missing one or more methods, and the corresponding class declaration has no default declaration for them.
The
MINIMAL
pragma can be used to change which combination of methods will be required for instances of a particular class. See MINIMAL pragma.
-
-Wmissing-signatures
¶ Since: at least 5.04 Default: off If you would like GHC to check that every top-level function/value has a type signature, use the
-Wmissing-signatures
option. As part of the warning GHC also reports the inferred type.
-
-Wmissing-exported-sigs
¶ Since: 7.10 This option is now deprecated in favour of
-Wmissing-exported-signatures
.
-
-Wmissing-exported-signatures
¶ Since: 8.0 Default: off If you would like GHC to check that every exported top-level function/value has a type signature, but not check unexported values, use the
-Wmissing-exported-signatures
option. If this option is used in conjunction with-Wmissing-signatures
then every top-level function/value must have a type signature. As part of the warning GHC also reports the inferred type.
-
-Wmissing-local-sigs
¶ Since: 7.0 This option is now deprecated in favour of
-Wmissing-local-signatures
.
-
-Wmissing-local-signatures
¶ Since: 8.0 If you use the
-Wmissing-local-signatures
flag GHC will warn you about any polymorphic local bindings. As part of the warning GHC also reports the inferred type. The option is off by default.
-
-Wmissing-pattern-synonym-signatures
¶ Since: 8.0 Default: off If you would like GHC to check that every pattern synonym has a type signature, use the
-Wmissing-pattern-synonym-signatures
option. If this option is used in conjunction with-Wmissing-exported-signatures
then only exported pattern synonyms must have a type signature. GHC also reports the inferred type.
-
-Wmissing-kind-signatures
¶ Since: 9.2 Default: off If you would like GHC to check that every data, type family, type-class definition has a standalone kind signature or a CUSK, use the
-Wmissing-kind-signatures
option. You can specify the kind viaStandaloneKindSignatures
orCUSKs
.Note that
-Wmissing-kind-signatures
does not warn about associated type families, as GHC considers an associated type family declaration to have a CUSK if its enclosing class has a CUSK. (See Complete user-supplied kind signatures and polymorphic recursion for more on this point.) Therefore, giving the parent class a standalone kind signature or CUSK is sufficient to fix the warning for the class’s associated type families as well.
-
-Wmissing-poly-kind-signatures
¶ Since: 9.8 Default: off This is a restricted version of
-Wmissing-kind-signatures
.It warns when a declaration defines a type constructor that lacks a standalone kind signature and whose inferred kind is polymorphic (which happens with -PolyKinds. For example
data T a = MkT (a -> Int) -- T :: Type -> Type -- Not polymorphic, hence no warning data W f a = MkW (f a) -- W :: forall k. (k->Type) -> k -> Type -- Polymorphic, hence warning!
It is useful to catch accidentally polykinded types, or to make that polymorphism explicit, without requiring a kind signature for every type.
-
-Wmissing-exported-pattern-synonym-signatures
¶ Default: off If you would like GHC to check that every exported pattern synonym has a type signature, but not check unexported pattern synonyms, use the
-Wmissing-exported-pattern-synonym-signatures
option. If this option is used in conjunction with-Wmissing-pattern-synonym-signatures
then every pattern synonym must have a type signature. As part of the warning GHC also reports the inferred type.
-
-Wname-shadowing
¶ Since: at least 5.04 This option causes a warning to be emitted whenever an inner-scope value has the same name as an outer-scope value, i.e. the inner value shadows the outer one. This can catch typographical errors that turn into hard-to-find bugs, e.g., in the inadvertent capture of what would be a recursive call in
f = ... let f = id in ... f ...
.The warning is suppressed for names beginning with an underscore. For example
f x = do { _ignore <- this; _ignore <- that; return (the other) }
-
-Worphans
¶ Since: 6.4 These flags cause a warning to be emitted whenever the module contains an “orphan” instance declaration or rewrite rule. An instance declaration is an orphan if it appears in a module in which neither the class nor the type being instanced are declared in the same module. A rule is an orphan if it is a rule for a function declared in another module. A module containing any orphans is called an orphan module.
The trouble with orphans is that GHC must pro-actively read the interface files for all orphan modules, just in case their instances or rules play a role, whether or not the module’s interface would otherwise be of any use. See Orphan modules and instance declarations for details.
The flag
-Worphans
warns about user-written orphan rules or instances.
-
-Woverlapping-patterns
¶ Since: at least 5.04 By default, the compiler will warn you if a set of patterns are overlapping, e.g.,
f :: String -> Int f [] = 0 f (_:xs) = 1 f "2" = 2
where the last pattern match in
f
won’t ever be reached, as the second pattern overlaps it. More often than not, redundant patterns is a programmer mistake/error, so this option is enabled by default.If the programmer is dead set on keeping a redundant clause, for example to prevent bitrot, they can make use of a guard scrutinising
GHC.Exts.considerAccessible
to prevent the checker from flagging the parent clause as redundant:g :: String -> Int g [] = 0 g (_:xs) = 1 g "2" | considerAccessible = 2 -- No warning!
Note that
considerAccessible
should come as the last statement of the guard in order not to impact the results of the checker. E.g., if you writeh :: Bool -> Int h x = case (x, x) of (True, True) -> 1 (False, False) -> 2 (True, False) | considerAccessible, False <- x -> 3
The pattern-match checker takes you by your word, will conclude that
False <- x
might fail and warn that the pattern-match is inexhaustive. PutconsiderAccessible
last to avoid such confusions.Note that due to technical limitations,
considerAccessible
will not suppress-Winaccessible-code
warnings.
-
-Winaccessible-code
¶ Since: 8.6 By default, the compiler will warn you if types make a branch inaccessible. This generally requires GADTs or similar extensions.
Take, for example, the following program
{-# LANGUAGE GADTs #-} data Foo a where Foo1 :: Foo Char Foo2 :: Foo Int data TyEquality a b where Refl :: TyEquality a a checkTEQ :: Foo t -> Foo u -> Maybe (TyEquality t u) checkTEQ x y = error "unimportant" step2 :: Bool step2 = case checkTEQ Foo1 Foo2 of Just Refl -> True -- Inaccessible code Nothing -> False
The
Just Refl
case instep2
is inaccessible, because in order forcheckTEQ
to be able to produce aJust
,t ~ u
must hold, but since we’re passingFoo1
andFoo2
here, it follows thatt ~ Char
, andu ~ Int
, and thust ~ u
cannot hold.
-
-Wstar-is-type
¶ Since: 8.6 The use of
*
to denote the kind of inhabited types relies on theStarIsType
extension, which in a future release will be turned off by default and then possibly removed. The reasons for this and the deprecation schedule are described in GHC proposal #143.This warning allows to detect such uses of
*
before the actual breaking change takes place. The recommended fix is to replace*
withType
imported fromData.Kind
.
-
-Wstar-binder
¶ Since: 8.6 Under
StarIsType
, a*
in types is not an operator nor even a name, it is special syntax that stands forData.Kind.Type
. This means that an expression likeEither * Char
is parsed asEither (*) Char
and not(*) Either Char
.In binding positions, we have similar parsing rules. Consider the following example
{-# LANGUAGE TypeOperators, TypeFamilies, StarIsType #-} type family a + b type family a * b
While
a + b
is parsed as(+) a b
and becomes a binding position for the(+)
type operator,a * b
is parsed asa (*) b
and is rejected.As a workaround, we allow to bind
(*)
in prefix form:type family (*) a b
This is a rather fragile arrangement, as generally a programmer expects
(*) a b
to be equivalent toa * b
. With-Wstar-binder
we warn when this special treatment of(*)
takes place.
-
-Wsimplifiable-class-constraints
¶ Since: 8.2 Default: on Warn about class constraints in a type signature that can be simplified using a top-level instance declaration. For example:
f :: Eq [a] => a -> a
Here the
Eq [a]
in the signature overlaps with the top-level instance forEq [a]
. GHC goes to some efforts to use the former, but if it should use the latter, it would then have an insolubleEq a
constraint. Best avoided by instead writing:f :: Eq a => a -> a
-
-Wtabs
¶ Since: 6.8 Have the compiler warn if there are tabs in your source file.
-
-Wtype-defaults
¶ Since: at least 5.04 Default: off Have the compiler warn/inform you where in your source the Haskell defaulting mechanism for numeric types kicks in. This is useful information when converting code from a context that assumed one default into one with another, e.g., the ‘default default’ for Haskell 1.4 caused the otherwise unconstrained value
1
to be given the typeInt
, whereas Haskell 98 and later defaults it toInteger
. This may lead to differences in performance and behaviour, hence the usefulness of being non-silent about this.
-
-Wmonomorphism-restriction
¶ Since: 6.8 Default: off Have the compiler warn/inform you where in your source the Haskell Monomorphism Restriction is applied. If applied silently the MR can give rise to unexpected behaviour, so it can be helpful to have an explicit warning that it is being applied.
Since: 8.8 Warn when GHCi can’t load a shared lib it deduced it should load when loading a package and analyzing the extra-libraries stanza of the target package description.
-
-Wunticked-promoted-constructors
¶ Since: 7.10 Warn if a promoted data constructor is used without a tick preceding its name.
For example:
data Nat = Succ Nat | Zero data Vec n s where Nil :: Vec Zero a Cons :: a -> Vec n a -> Vec (Succ n) a
Will raise two warnings because
Zero
andSucc
are not written as'Zero
and'Succ
.This also applies to list literals since 9.4. For example:
type L = [Int, Char, Bool]
will raise a warning, because
[Int, Char, Bool]
is a promoted list which lacks a tick.
-
-Wunused-binds
¶ Since: at least 5.04 Report any function definitions (and local bindings) which are unused. An alias for
-
-Wunused-top-binds
¶ Since: 8.0 Report any function definitions which are unused.
More precisely, warn if a binding brings into scope a variable that is not used, except if the variable’s name starts with an underscore. The “starts-with-underscore” condition provides a way to selectively disable the warning.
A variable is regarded as “used” if
- It is exported, or
- It appears in the right hand side of a binding that binds at least one used variable that is used
For example:
module A (f) where f = let (p,q) = rhs1 in t p -- No warning: q is unused, but is locally bound t = rhs3 -- No warning: f is used, and hence so is t g = h x -- Warning: g unused h = rhs2 -- Warning: h is only used in the -- right-hand side of another unused binding _w = True -- No warning: _w starts with an underscore
-
-Wunused-local-binds
¶ Since: 8.0 Report any local definitions which are unused. For example:
module A (f) where f = let (p,q) = rhs1 in t p -- Warning: q is unused g = h x -- No warning: g is unused, but is a top-level binding
-
-Wunused-pattern-binds
¶ Since: 8.0 Warn if a pattern binding binds no variables at all, unless it is a lone wild-card pattern, or a banged pattern. For example:
Just _ = rhs3 -- Warning: unused pattern binding (_, _) = rhs4 -- Warning: unused pattern binding _ = rhs3 -- No warning: lone wild-card pattern !() = rhs4 -- No warning: banged pattern; behaves like seq
In general a lazy pattern binding p = e is a no-op if p does not bind any variables. The motivation for allowing lone wild-card patterns is they are not very different from
_v = rhs3
, which elicits no warning; and they can be useful to add a type constraint, e.g._ = x::Int
. A banged pattern (see Bang patterns and Strict Haskell) is not a no-op, because it forces evaluation, and is useful as an alternative toseq
.
-
-Wunused-imports
¶ Since: at least 5.04 Report any modules that are explicitly imported but never used. However, the form
import M()
is never reported as an unused import, because it is a useful idiom for importing instance declarations, which are anonymous in Haskell.
-
-Wunused-matches
¶ Since: at least 5.04 Report all unused variables which arise from term-level pattern matches, including patterns consisting of a single variable. For instance
f x y = []
would reportx
andy
as unused. The warning is suppressed if the variable name begins with an underscore, thus:f _x = True
Note that
-Wunused-matches
does not warn about variables which arise from type-level patterns, as found in type family and data family instances. This must be enabled separately through the-Wunused-type-patterns
flag.
-
-Wunused-do-bind
¶ Since: 6.12 Report expressions occurring in
do
andmdo
blocks that appear to silently throw information away. For instancedo { mapM popInt xs ; return 10 }
would report the first statement in thedo
block as suspicious, as it has the typeStackM [Int]
and notStackM ()
, but that[Int]
value is not bound to anything. The warning is suppressed by explicitly mentioning in the source code that your program is throwing something away:do { _ <- mapM popInt xs ; return 10 }
Of course, in this particular situation you can do even better:
do { mapM_ popInt xs ; return 10 }
-
-Wunused-type-patterns
¶ Since: 8.0 Report all unused implicitly bound type variables which arise from patterns in type family and data family instances. For instance:
type instance F x y = []
would report
x
andy
as unused on the right hand side. The warning is suppressed if the type variable name begins with an underscore, like so:type instance F _x _y = []
When
ExplicitForAll
is enabled, explicitly quantified type variables may also be identified as unused. For instance:type instance forall x y. F x y = []
would still report
x
andy
as unused on the right hand sideUnlike
-Wunused-matches
,-Wunused-type-patterns
is not implied by-Wall
. The rationale for this decision is that unlike term-level pattern names, type names are often chosen expressly for documentation purposes, so using underscores in type names can make the documentation harder to read.
-
-Wunused-foralls
¶ Since: 8.0 Report all unused type variables which arise from explicit, user-written
forall
statements. For instance:g :: forall a b c. (b -> b)
would report
a
andc
as unused.
-
-Wunused-record-wildcards
¶ Since: 8.10 Report all record wildcards where none of the variables bound implicitly are used. For instance:
data P = P { x :: Int, y :: Int } f1 :: P -> Int f1 P{..} = 1 + 3
would report that the
P{..}
match is unused.
-
-Wredundant-bang-patterns
¶ Since: 9.2 Report dead bang patterns, where dead bangs are bang patterns that under no circumstances can force a thunk that wasn’t already forced. Dead bangs are a form of redundant bangs. The new check is performed in pattern-match coverage checker along with other checks (namely, redundant and inaccessible RHSs). Given
f :: Bool -> Int f True = 1 f !x = 2
The bang pattern on
!x
is dead. By the time thex
in the second equation is reached,x
will already have been forced due to the first equation (f True = 1
). Moreover, there is no way to reach the second equation without going through the first one.Note that
-Wredundant-bang-patterns
will not warn about dead bangs that appear on a redundant clause. That is because in that case, it is recommended to delete the clause wholly, including its leading pattern match.Dead bang patterns are redundant. But there are bang patterns which are redundant that aren’t dead, for example:
f !() = 0
the bang still forces the argument, before we attempt to match on
()
. But it is redundant with the forcing done by the()
match. Currently such redundant bangs are not considered dead, and-Wredundant-bang-patterns
will not warn about them.
-
-Wredundant-record-wildcards
¶ Since: 8.10 Report all record wildcards where the wild card match binds no patterns. For instance:
data P = P { x :: Int, y :: Int } f1 :: P -> Int f1 P{x,y,..} = x + y
would report that the
P{x, y, ..}
match has a redundant use of..
.
-
-Wredundant-strictness-flags
¶ Since: 9.4 Report strictness flags applied to unlifted types. An unlifted type is always strict, and applying a strictness flag has no effect.
For example:
data T = T !Int#
-
-Wwrong-do-bind
¶ Since: 6.12 Report expressions occurring in
do
andmdo
blocks that appear to lack a binding. For instancedo { return (popInt 10) ; return 10 }
would report the first statement in thedo
block as suspicious, as it has the typeStackM (StackM Int)
(which consists of two nested applications of the same monad constructor), but which is not then “unpacked” by binding the result. The warning is suppressed by explicitly mentioning in the source code that your program is throwing something away:do { _ <- return (popInt 10) ; return 10 }
For almost all sensible programs this will indicate a bug, and you probably intended to write:
do { popInt 10 ; return 10 }
-
-Winline-rule-shadowing
¶ Since: 7.8 Warn if a rewrite RULE might fail to fire because the function might be inlined before the rule has a chance to fire. See How rules interact with INLINE/NOINLINE pragmas.
-
-Wcpp-undef
¶ Since: 8.2 This flag passes
-Wundef
to the C pre-processor (if its being used) which causes the pre-processor to warn on uses of the #if directive on undefined identifiers.
-
-Wunbanged-strict-patterns
¶ Since: 8.2 This flag warns whenever you write a pattern that binds a variable whose type is unlifted, and yet the pattern is not a bang pattern nor a bare variable. See Unboxed types for information about unlifted types.
-
-Wmissing-home-modules
¶ Since: 8.2 When a module provided by the package currently being compiled (i.e. the “home” package) is imported, but not explicitly listed in command line as a target. Useful for Cabal to ensure GHC won’t pick up modules, not listed neither in
exposed-modules
, nor inother-modules
.
-
-Wpartial-fields
¶ Since: 8.4 The option
-Wpartial-fields
warns about a record fieldf
that is defined in some, but not all, of the constructors of a data type, as such selector functions are partial. For example, when-Wpartial-fields
is enabled the compiler will emit a warning at the definition ofFoo
below:data Foo = Foo { f :: Int } | Bar
The warning is suppressed if the field name begins with an underscore.
data Foo = Foo { _f :: Int } | Bar
Another related warning is
-Wincomplete-record-selectors
, which warns at use sites rather than definition sites.
-
-Wunused-packages
¶ Since: 8.10 The option
-Wunused-packages
warns about packages, specified on command line via-package ⟨pkg⟩
or-package-id ⟨unit-id⟩
, but were not needed during compilation. If the warning fires it means the specified package wasn’t needed for compilation.This warning interacts poorly with GHCi because most invocations will pass a large number of
-package
arguments on the initial load. Therefore if you modify the targets using:load
or:cd
then the warning will be silently disabled if it’s enabled (see #21110).
-
-Winvalid-haddock
¶ Since: 9.0 When the
-haddock
option is enabled, GHC collects documentation comments and associates them with declarations, function arguments, data constructors, and other syntactic elements. Documentation comments in invalid positions are discarded:myValue = -- | Invalid (discarded) comment in an expression 2 + 2
This warning informs you about discarded documentation comments. It has no effect when
-haddock
is disabled.
-
-Woperator-whitespace-ext-conflict
¶ Since: 9.2 When
TemplateHaskell
is enabled,f $x
is parsed asf
applied to an untyped splice. But when the extension is disabled, the expression is parsed as a use of the$
infix operator.To make it easy to read
f $x
without checking the enabled extensions, one could rewrite it asf $ x
, which is what this warning suggests.Currently, it detects the following cases:
$x
could mean an untyped splice underTemplateHaskell
$$x
could mean a typed splice underTemplateHaskell
%m
could mean a multiplicity annotation underLinearTypes
It only covers extensions that currently exist. If you want to enforce a stricter policy and always require whitespace around all infix operators, use
-Woperator-whitespace
.
-
-Woperator-whitespace
¶ Since: 9.2 There are four types of infix operator occurrences, as defined by GHC Proposal #229:
a ! b -- a loose infix occurrence a!b -- a tight infix occurrence a !b -- a prefix occurrence a! b -- a suffix occurrence
A loose infix occurrence of any operator is always parsed as an infix operator, but other occurrence types may be assigned a special meaning. For example, a prefix
!
denotes a bang pattern, and a prefix$
denotes aTemplateHaskell
splice.This warning encourages the use of loose infix occurrences of all infix operators, to prevent possible conflicts with future language extensions.
-
-Wauto-orphans
¶ Since: 7.4 Does nothing.
-
-Wmissing-space-after-bang
¶ Since: 8.8 Does nothing.
-
-Wderiving-typeable
¶ Since: 7.10 This flag warns when
Typeable
is listed in a deriving clause or derived withStandaloneDeriving
.Since GHC 7.10,
Typeable
is automatically derived for all types. Thus, derivingTypeable
yourself is redundant.
-
-Wambiguous-fields
¶ Since: 9.2 When
DuplicateRecordFields
is enabled, the option-Wambiguous-fields
warns about occurrences of fields in selectors or updates that depend on the deprecated mechanism for type-directed disambiguation. This mechanism will be removed in a future GHC release, at which point these occurrences will be rejected as ambiguous. See the proposal DuplicateRecordFields without ambiguous field access and the documentation onDuplicateRecordFields
for further details.This warning has no effect when
DuplicateRecordFields
is disabled.
-
-Wforall-identifier
¶ Since: 9.4 This warning is deprecated. It no longer has any effect since GHC 9.10.
In the past, GHC used to accept
forall
as a term-level identifier:-- from constraints-0.13 forall :: forall p. (forall a. Dict (p a)) -> Dict (Forall p) forall d = ...
In accordance with GHC Proposal #281, this is no longer possible, as
forall
has become a proper keyword.-Wforall-identifier
was used in the migration period before the breaking change took place.
-
-Wunicode-bidirectional-format-characters
¶ Since: 9.0.2 Explicit unicode bidirectional formatting characters can cause source code to be rendered misleadingly in many viewers. We warn if any such character is present in the source.
Specifically, the characters disallowed by this warning are those which are a part of the ‘Explicit Formatting` category of the Unicode Bidirectional Character Type Listing
-
-Wgadt-mono-local-binds
¶ Since: 9.4.1 This warning is triggered on pattern matching involving GADTs, if
MonoLocalBinds
is disabled. Type inference can be fragile in this case.See the OutsideIn(X) paper (section 4.2) and Let-generalisation for more details.
To resolve this warning, you can enable
MonoLocalBinds
or an extension implying it (GADTs
orTypeFamilies
).The warning is also triggered when matching on GADT-like pattern synonyms (i.e. pattern synonyms containing equalities in provided constraints).
In previous versions of GHC (9.2 and below), it was an error to pattern match on a GADT if neither
GADTs
norTypeFamilies
were enabled.
-
-Wtype-equality-out-of-scope
¶ Since: 9.4.1 Default: on In accordance with GHC Proposal #371, the type equality syntax
a ~ b
is no longer built-in. Instead,~
is a regular type operator that can be imported fromData.Type.Equality
orPrelude
.To minimize breakage, a compatibility fallback is provided: whenever
~
is used but is not in scope, the compiler assumes that it stands for a type equality constraint. The warning is triggered by any code that relies on this fallback. It can be addressed by bringing~
into scope explicitly.The likely culprit is that you use
NoImplicitPrelude
and a custom Prelude. In this case, consider updating your custom Prelude to re-export~
fromData.Type.Equality
.
-
-Wtype-equality-requires-operators
¶ Since: 9.4.1 In accordance with GHC Proposal #371, the type equality syntax
a ~ b
is no longer built-in. Instead,~
is a regular type operator that requires theTypeOperators
extension.To minimize breakage,
~
specifically (unlike other type operators) can be used even whenTypeOperators
is disabled. The warning is triggered whenever this happens, and can be addressed by enabling the extension.
-
-Wloopy-superclass-solve
¶ Since: 9.6.1 This warning is deprecated. It no longer has any effect since GHC 9.10. In the past,
UndecidableInstances
allowed potentially non-terminating evidence for certain superclass constraints. This is no longer allowed, as explained in Undecidable instances and loopy superclasses. This warning was used during the transition period.
-
-Wterm-variable-capture
¶ Since: 9.8.1 Under
RequiredTypeArguments
, implicit quantification of type variables does not take place if there is a term variable of the same name in scope.For example:
a = 15 f :: a -> a -- NoRequiredTypeArguments: The ‘a’ is implicitly quantified -- RequiredTypeArguments: The ‘a’ refers to the term-level binding
When
-Wterm-variable-capture
is enabled, GHC warns against implicit quantification that would stop working underRequiredTypeArguments
.
-
-Wmissing-role-annotations
¶ Since: 9.8.1 Default: off If you would like GHC to check that every data type definition has a role annotation, use the
-Wmissing-role-annotations
option. You can specify the role viaRoleAnnotations
.GHC will not warn about type class definitions with missing role annotations, as their default roles are the strictest: all nominal. In other words the type-class role cannot be accidentally left representational or phantom, which could affected the code correctness.
-
-Wimplicit-rhs-quantification
¶ Since: 9.8.1 Default: off In accordance with GHC Proposal #425, GHC will stop implicitly quantifying over type variables that occur free on the right-hand side of a type synonym but are not mentioned on the left-hand side. Type synonym declarations that rely on this form of quantification should be rewritten with invisible binders.
For example:
type T1 :: forall a . Maybe a type T1 = 'Nothing :: Maybe a -- old type T1 @a = 'Nothing :: Maybe a -- new
This warning detects code that will be affected by this breaking change.
-
-Wdeprecated-type-abstractions
¶ Since: 9.10.1 Default: off Type abstractions in constructor patterns allow binding existential type variables:
import Type.Reflection (Typeable, typeRep) data Ex = forall e. (Typeable e, Show e) => MkEx e showEx (MkEx @e a) = show a ++ " :: " ++ show (typeRep @e)
Note the pattern
MkEx @e a
, and specifically the@e
binder.Support for this feature was added to GHC in version 9.2, but instead of getting its own language extension the feature was enabled by a combination of
TypeApplications
andScopedTypeVariables
. As per GHC Proposal #448 and its amendment #604 we are now transitioning towards guarding this feature behindTypeAbstractions
instead.As a compatibility measure, GHC continues to support old programs that use type abstractions in constructor patterns without enabling the appropriate extension
TypeAbstractions
, but it will stop doing so in a future release.This warning detects code that will be affected by this breaking change.
-
-Wincomplete-export-warnings
¶ Since: 9.8.1 Ino accordance with GHC Proposal #134, it is now possible to deprecate certain exports of a name without deprecating the name itself.
As explained in WARNING and DEPRECATED pragmas, when a name is exported in several ways in the same module, but only some of those ways have a warning, it will not end up deprecated when imported in another module.
For example:
module A (x) where x :: Int x = 2 module M ( {-# WARNING x "deprecated" #-} x module A ) import A When :ghc-flag:`-Wincomplete-export-warnings` is enabled, GHC warns about exports that are not deprecating a name that is deprecated with another export in that module.
-
-Wbadly-staged-types
¶ Since: 9.10.1 Consider an example:
tardy :: forall a. Proxy a -> IO Type tardy _ = [t| a |]
The type binding
a
is bound at stage 1 but used on stage 2.This is badly staged program, and the
tardy (Proxy @Int)
won’t produce a type representation ofInt
, but rather a local namea
.
-
-Winconsistent-flags
¶ Since: 9.8.1 Default: on Warn when command line options are inconsistent in some way.
For example, when using GHCi, optimisation flags are ignored and a warning is issued. Another example is
-dynamic
is ignored when-dynamic-too
is passed.
-
-Wdata-kinds-tc
¶ Since: 9.10.1 Introduced in GHC 9.10.1, this warns when an illegal use of a type or kind (without having enabled the
DataKinds
extension) is caught in the typechecker (hence the-tc
suffix). These warnings complement the existingDataKinds
checks (that have existed sinceDataKinds
was first introduced), which result in errors instead of warnings.This warning is scheduled to be changed to an error in a future GHC version, at which point the
-Wdata-kinds-tc
flag will be removed. Users can enable theDataKinds
extension to avoid issues (thus silencing the warning).
-
-Wdefaulted-exception-context
¶ Since: 9.10.1 Introduced in GHC 9.10.1 with the introduction of an implicit Control.Exception.Context.ExceptionContext` context to Control.Exception.SomeException. To preserve compatibility with earlier compilers, this constraints is implicitly defaulted to Control.Exception.Context.emptyExceptionContext when no other evidence is available. As this behavior may result in dropped exception context this warning is provided to give notice when defaulting occurs.
If you’re feeling really paranoid, the -dcore-lint
option is a good choice.
It turns on heavyweight intra-pass sanity-checking within GHC. (It checks GHC’s
sanity, not yours.)