Extension.hs 17.8 KB
Newer Older
1
2
3
4
-----------------------------------------------------------------------------
-- |
-- Module      :  Language.Haskell.Extension
-- Copyright   :  Isaac Jones 2003-2004
5
--
Duncan Coutts's avatar
Duncan Coutts committed
6
-- Maintainer  :  libraries@haskell.org
7
8
-- Portability :  portable
--
9
-- Haskell language dialects and extensions
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

{- All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above
      copyright notice, this list of conditions and the following
      disclaimer in the documentation and/or other materials provided
      with the distribution.

    * Neither the name of Isaac Jones nor the names of other
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -}

module Language.Haskell.Extension (
42
43
44
        Language(..),
        knownLanguages,

45
        Extension(..),
46
        KnownExtension(..),
47
        knownExtensions,
48
        deprecatedExtensions
49
50
  ) where

51
52
53
54
import Distribution.Text (Text(..))
import qualified Distribution.Compat.ReadP as Parse
import qualified Text.PrettyPrint as Disp
import qualified Data.Char as Char (isAlphaNum)
55
import Data.Array (Array, accumArray, bounds, Ix(inRange), (!))
56

57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
-- ------------------------------------------------------------
-- * Language
-- ------------------------------------------------------------

-- | This represents a Haskell language dialect.
--
-- Language 'Extension's are interpreted relative to one of these base
-- languages.
--
data Language =

  -- | The Haskell 98 language as defined by the Haskell 98 report.
  -- <http://haskell.org/onlinereport/>
     Haskell98

  -- | The Haskell 2010 language as defined by the Haskell 2010 report.
  -- <http://www.haskell.org/onlinereport/haskell2010>
  | Haskell2010

  -- | An unknown language, identified by its name.
  | UnknownLanguage String
  deriving (Show, Read, Eq)

knownLanguages :: [Language]
knownLanguages = [Haskell98, Haskell2010]

instance Text Language where
  disp (UnknownLanguage other) = Disp.text other
  disp other                   = Disp.text (show other)

  parse = do
    lang <- Parse.munch1 Char.isAlphaNum
    return (classifyLanguage lang)

classifyLanguage :: String -> Language
classifyLanguage = \str -> case lookup str langTable of
    Just lang -> lang
    Nothing   -> UnknownLanguage str
  where
    langTable = [ (show lang, lang)
                | lang <- knownLanguages ]

99
100
101
102
-- ------------------------------------------------------------
-- * Extension
-- ------------------------------------------------------------

103
-- Note: if you add a new 'KnownExtension':
104
105
106
107
--
-- * also add it to the Distribution.Simple.X.languageExtensions lists
--   (where X is each compiler: GHC, JHC, Hugs, NHC)
--
108
109
110
-- | This represents language extensions beyond a base 'Language' definition
-- (such as 'Haskell98') that are supported by some implementations, usually
-- in some special mode.
111
112
113
114
115
116
--
-- Where applicable, references are given to an implementation's
-- official documentation, e.g. \"GHC &#xa7; 7.2.1\" for an extension
-- documented in section 7.2.1 of the GHC User's Guide.

data Extension =
117
  -- | Enable a known extension
118
119
    EnableExtension KnownExtension

120
121
122
  -- | Disable a known extension
  | DisableExtension KnownExtension

123
124
125
126
127
128
129
130
  -- | An unknown extension, identified by the name of its @LANGUAGE@
  -- pragma.
  | UnknownExtension String

  deriving (Show, Read, Eq)

data KnownExtension =

131
132
133
  -- | [GHC &#xa7; 7.6.3.4] Allow overlapping class instances,
  -- provided there is a unique most specific instance for each use.
    OverlappingInstances
134

135
136
137
138
  -- | [GHC &#xa7; 7.6.3.3] Ignore structural rules guaranteeing the
  -- termination of class instance resolution.  Termination is
  -- guaranteed by a fixed-depth recursion stack, and compilation
  -- may fail if this depth is exceeded.
ijones's avatar
ijones committed
139
  | UndecidableInstances
140
141
142
143
144

  -- | [GHC &#xa7; 7.6.3.4] Implies 'OverlappingInstances'.  Allow the
  -- implementation to choose an instance even when it is possible
  -- that further instantiation of types will lead to a more specific
  -- instance being applicable.
ijones's avatar
ijones committed
145
  | IncoherentInstances
146

147
148
149
150
  -- | [GHC &#xa7; 7.3.8] Allows recursive bindings in @do@ blocks,
  -- using the @rec@ keyword.
  | DoRec

151
152
153
  -- | [GHC &#xa7; 7.3.8.2] Deprecated in GHC.  Allows recursive bindings
  -- using @mdo@, a variant of @do@.  @DoRec@ provides a different,
  -- preferred syntax.
154
  | RecursiveDo
155
156
157
158

  -- | [GHC &#xa7; 7.3.9] Provide syntax for writing list
  -- comprehensions which iterate over several lists together, like
  -- the 'zipWith' family of functions.
159
  | ParallelListComp
160
161

  -- | [GHC &#xa7; 7.6.1.1] Allow multiple parameters in a type class.
162
  | MultiParamTypeClasses
163

164
165
  -- | [GHC &#xa7; 7.17] Enable the dreaded monomorphism restriction.
  | MonomorphismRestriction
166
167
168
169
170
171

  -- | [GHC &#xa7; 7.6.2] Allow a specification attached to a
  -- multi-parameter type class which indicates that some parameters
  -- are entirely determined by others. The implementation will check
  -- that this property holds for the declared instances, and will use
  -- this property to reduce ambiguity in instance resolution.
172
  | FunctionalDependencies
173
174
175
176

  -- | [GHC &#xa7; 7.8.5] Like 'RankNTypes' but does not allow a
  -- higher-rank type to itself appear on the left of a function
  -- arrow.
ijones's avatar
ijones committed
177
  | Rank2Types
178
179
180

  -- | [GHC &#xa7; 7.8.5] Allow a universally-quantified type to occur on
  -- the left of a function arrow.
181
  | RankNTypes
182
183
184
185

  -- | [GHC &#xa7; 7.8.5] Allow data constructors to have polymorphic
  -- arguments.  Unlike 'RankNTypes', does not allow this for ordinary
  -- functions.
186
  | PolymorphicComponents
187
188

  -- | [GHC &#xa7; 7.4.4] Allow existentially-quantified data constructors.
189
  | ExistentialQuantification
190
191
192
193

  -- | [GHC &#xa7; 7.8.7] Cause a type variable in a signature, which has an
  -- explicit @forall@ quantifier, to scope over the definition of the
  -- accompanying value declaration.
194
  | ScopedTypeVariables
195
196

  -- | Deprecated, use 'ScopedTypeVariables' instead.
197
  | PatternSignatures
198
199
200

  -- | [GHC &#xa7; 7.8.3] Enable implicit function parameters with dynamic
  -- scope.
201
  | ImplicitParams
202
203
204

  -- | [GHC &#xa7; 7.8.2] Relax some restrictions on the form of the context
  -- of a type signature.
205
  | FlexibleContexts
206
207
208

  -- | [GHC &#xa7; 7.6.3.2] Relax some restrictions on the form of the
  -- context of an instance declaration.
209
  | FlexibleInstances
210
211

  -- | [GHC &#xa7; 7.4.1] Allow data type declarations with no constructors.
212
  | EmptyDataDecls
213
214

  -- | [GHC &#xa7; 4.10.3] Run the C preprocessor on Haskell source code.
215
216
  | CPP

217
218
  -- | [GHC &#xa7; 7.8.4] Allow an explicit kind signature giving the kind of
  -- types over which a type variable ranges.
Ian Lynagh's avatar
Ian Lynagh committed
219
  | KindSignatures
220
221
222
223

  -- | [GHC &#xa7; 7.11] Enable a form of pattern which forces evaluation
  -- before an attempted match, and a form of strict @let@/@where@
  -- binding.
simonpj's avatar
simonpj committed
224
  | BangPatterns
225
226

  -- | [GHC &#xa7; 7.6.3.1] Allow type synonyms in instance heads.
227
  | TypeSynonymInstances
228
229
230

  -- | [GHC &#xa7; 7.9] Enable Template Haskell, a system for compile-time
  -- metaprogramming.
231
  | TemplateHaskell
232
233
234
235

  -- | [GHC &#xa7; 8] Enable the Foreign Function Interface.  In GHC,
  -- implements the standard Haskell 98 Foreign Function Interface
  -- Addendum, plus some GHC-specific extensions.
236
  | ForeignFunctionInterface
237
238

  -- | [GHC &#xa7; 7.10] Enable arrow notation.
239
  | Arrows
240
241
242

  -- | [GHC &#xa7; 7.16] Enable generic type classes, with default instances
  -- defined in terms of the algebraic structure of a type.
243
  | Generics
244

245
246
247
248
249
  -- | [GHC &#xa7; 7.3.11] Enable the implicit importing of the module
  -- @Prelude@.  When disabled, when desugaring certain built-in syntax
  -- into ordinary identifiers, use whatever is in scope rather than the
  -- @Prelude@ -- version.
  | ImplicitPrelude
250
251
252
253

  -- | [GHC &#xa7; 7.3.15] Enable syntax for implicitly binding local names
  -- corresponding to the field names of a record.  Puns bind specific
  -- names, unlike 'RecordWildCards'.
254
  | NamedFieldPuns
255
256
257

  -- | [GHC &#xa7; 7.3.5] Enable a form of guard which matches a pattern and
  -- binds variables.
258
  | PatternGuards
259
260
261

  -- | [GHC &#xa7; 7.5.4] Allow a type declared with @newtype@ to use
  -- @deriving@ for any class with an instance for the underlying type.
262
  | GeneralizedNewtypeDeriving
263

264
  -- | [Hugs &#xa7; 7.1] Enable the \"Trex\" extensible records system.
265
  | ExtensibleRecords
266
267
268
269

  -- | [Hugs &#xa7; 7.2] Enable type synonyms which are transparent in
  -- some definitions and opaque elsewhere, as a way of implementing 
  -- abstract datatypes.
270
  | RestrictedTypeSynonyms
271
272
273

  -- | [Hugs &#xa7; 7.3] Enable an alternate syntax for string literals,
  -- with string templating.
274
  | HereDocuments
275
276
277

  -- | [GHC &#xa7; 7.3.2] Allow the character @#@ as a postfix modifier on
  -- identifiers.  Also enables literal syntax for unboxed values.
Ian Lynagh's avatar
Ian Lynagh committed
278
  | MagicHash
279
280
281

  -- | [GHC &#xa7; 7.7] Allow data types and type synonyms which are
  -- indexed by types, i.e. ad-hoc polymorphism for types.
Ian Lynagh's avatar
Ian Lynagh committed
282
  | TypeFamilies
283
284
285

  -- | [GHC &#xa7; 7.5.2] Allow a standalone declaration which invokes the
  -- type class @deriving@ mechanism.
Ian Lynagh's avatar
Ian Lynagh committed
286
  | StandaloneDeriving
287

288
289
  -- | [GHC &#xa7; 7.3.1] Allow certain Unicode characters to stand for
  -- certain ASCII character sequences, e.g. keywords and punctuation.
290
  | UnicodeSyntax
291
292
293

  -- | [GHC &#xa7; 8.1.1] Allow the use of unboxed types as foreign types,
  -- e.g. in @foreign import@ and @foreign export@.
294
  | UnliftedFFITypes
295
296
297
298

  -- | [GHC &#xa7; 7.4.3] Defer validity checking of types until after
  -- expanding type synonyms, relaxing the constraints on how synonyms
  -- may be used.
299
  | LiberalTypeSynonyms
300
301
302

  -- | [GHC &#xa7; 7.4.2] Allow the name of a type constructor, type class,
  -- or type variable to be an infix operator.
303
  | TypeOperators
304

305
--PArr -- not ready yet, and will probably be renamed to ParallelArrays
306
307
308
309

  -- | [GHC &#xa7; 7.3.16] Enable syntax for implicitly binding local names
  -- corresponding to the field names of a record.  A wildcard binds
  -- all unmentioned names, unlike 'NamedFieldPuns'.
310
  | RecordWildCards
311
312

  -- | Deprecated, use 'NamedFieldPuns' instead.
313
  | RecordPuns
314
315
316

  -- | [GHC &#xa7; 7.3.14] Allow a record field name to be disambiguated
  -- by the type of the record it's in.
317
  | DisambiguateRecordFields
318
319
320

  -- | [GHC &#xa7; 7.6.4] Enable overloading of string literals using a
  -- type class, much like integer literals.
321
  | OverloadedStrings
322
323
324

  -- | [GHC &#xa7; 7.4.6] Enable generalized algebraic data types, in
  -- which type variables may be instantiated on a per-constructor
Ian Lynagh's avatar
Ian Lynagh committed
325
  -- basis. Implies GADTSyntax.
326
  | GADTs
327

Ian Lynagh's avatar
Ian Lynagh committed
328
329
330
  -- | Enable GADT syntax for declaring ordinary algebraic datatypes.
  | GADTSyntax

331
332
  -- | [GHC &#xa7; 7.17.2] Make pattern bindings monomorphic.
  | MonoPatBinds
333
334
335

  -- | [GHC &#xa7; 7.8.8] Relax the requirements on mutually-recursive
  -- polymorphic functions.
336
  | RelaxedPolyRec
337
338
339

  -- | [GHC &#xa7; 2.4.5] Allow default instantiation of polymorphic
  -- types in more situations.
340
  | ExtendedDefaultRules
341
342

  -- | [GHC &#xa7; 7.2.2] Enable unboxed tuples.
343
  | UnboxedTuples
344
345
346

  -- | [GHC &#xa7; 7.5.3] Enable @deriving@ for classes
  -- @Data.Typeable.Typeable@ and @Data.Generics.Data@.
347
  | DeriveDataTypeable
348
349
350

  -- | [GHC &#xa7; 7.6.1.3] Allow a class method's type to place
  -- additional constraints on a class type variable.
351
  | ConstrainedClassMethods
352

353
354
  -- | [GHC &#xa7; 7.3.18] Allow imports to be qualified by the package
  -- name the module is intended to be imported from, e.g.
355
356
357
358
  --
  -- > import "network" Network.Socket
  | PackageImports

359
  -- | [GHC &#xa7; 7.8.6] Deprecated in GHC 6.12 and will be removed in
360
  -- GHC 7.  Allow a type variable to be instantiated at a
361
  -- polymorphic type.
362
  | ImpredicativeTypes
363
364
365

  -- | [GHC &#xa7; 7.3.3] Change the syntax for qualified infix
  -- operators.
366
  | NewQualifiedOperators
367
368
369

  -- | [GHC &#xa7; 7.3.12] Relax the interpretation of left operator
  -- sections to allow unary postfix operators.
370
  | PostfixOperators
371
372
373

  -- | [GHC &#xa7; 7.9.5] Enable quasi-quotation, a mechanism for defining
  -- new concrete syntax for expressions and patterns.
374
  | QuasiQuotes
375
376
377

  -- | [GHC &#xa7; 7.3.10] Enable generalized list comprehensions,
  -- supporting operations such as sorting and grouping.
378
  | TransformListComp
379
380
381

  -- | [GHC &#xa7; 7.3.6] Enable view patterns, which match a value by
  -- applying a function and matching on the result.
382
383
  | ViewPatterns

384
  -- | Allow concrete XML syntax to be used in expressions and patterns,
Ian Lynagh's avatar
Ian Lynagh committed
385
386
  -- as per the Haskell Server Pages extension language:
  -- <http://www.haskell.org/haskellwiki/HSP>. The ideas behind it are
387
  -- discussed in the paper \"Haskell Server Pages through Dynamic Loading\"
388
389
390
391
  -- by Niklas Broberg, from Haskell Workshop '05.
  | XmlSyntax

  -- | Allow regular pattern matching over lists, as discussed in the
392
  -- paper \"Regular Expression Patterns\" by Niklas Broberg, Andreas Farre
393
394
  -- and Josef Svenningsson, from ICFP '04.
  | RegularPatterns
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435

  -- | Enables the use of tuple sections, e.g. @(, True)@ desugars into
  -- @\x -> (x, True)@.
  | TupleSections

  -- | Allows GHC primops, written in C--, to be imported into a Haskell
  -- file.
  | GHCForeignImportPrim

  -- | Support for patterns of the form @n + k@, where @k@ is an
  -- integer literal.
  | NPlusKPatterns

  -- | Improve the layout rule when @if@ expressions are used in a @do@
  -- block.
  | DoAndIfThenElse

  -- | Makes much of the Haskell sugar be desugared into calls to the
  -- function with a particular name that is in scope.
  | RebindableSyntax

  -- | Make @forall@ a keyword in types, which can be used to give the
  -- generalisation explicitly.
  | ExplicitForAll

  -- | Allow contexts to be put on datatypes, e.g. the @Eq a@ in
  -- @data Eq a => Set a = NilSet | ConsSet a (Set a)@.
  | DatatypeContexts

  -- | Local (@let@ and @where@) bindings are monomorphic.
  | MonoLocalBinds

  -- | Enable @deriving@ for the @Data.Functor.Functor@ class.
  | DeriveFunctor

  -- | Enable @deriving@ for the @Data.Traversable.Traversable@ class.
  | DeriveTraversable

  -- | Enable @deriving@ for the @Data.Foldable.Foldable@ class.
  | DeriveFoldable

436
437
438
  -- | Enable non-decreasing indentation for 'do' blocks.
  | NondecreasingIndentation

439
440
441
442
443
444
  deriving (Show, Read, Eq, Enum, Bounded)

{-# DEPRECATED knownExtensions
   "KnownExtension is an instance of Enum and Bounded, use those instead." #-}
knownExtensions :: [KnownExtension]
knownExtensions = [minBound..maxBound]
445

446
447
448
-- | Extensions that have been deprecated, possibly paired with another
-- extension that replaces it.
--
Ian Lynagh's avatar
Ian Lynagh committed
449
deprecatedExtensions :: [(Extension, Maybe Extension)]
450
deprecatedExtensions =
Ian Lynagh's avatar
Ian Lynagh committed
451
452
  [ (EnableExtension RecordPuns, Just (EnableExtension NamedFieldPuns))
  , (EnableExtension PatternSignatures, Just (EnableExtension ScopedTypeVariables))
453
  ]
454
455
456
457
458
459
-- NOTE: when adding deprecated extensions that have new alternatives
-- we must be careful to make sure that the deprecation messages are
-- valid. We must not recomend aliases that cannot be used with older
-- compilers, perhaps by adding support in Cabal to translate the new
-- name to the old one for older compilers. Otherwise we are in danger
-- of the scenario in ticket #689.
460

461
462
instance Text Extension where
  disp (UnknownExtension other) = Disp.text other
463
  disp (EnableExtension ke)     = Disp.text (show ke)
464
  disp (DisableExtension ke)    = Disp.text ("No" ++ show ke)
465
466
467
468
469

  parse = do
    extension <- Parse.munch1 Char.isAlphaNum
    return (classifyExtension extension)

470
471
472
473
474
instance Text KnownExtension where
  disp ke = Disp.text (show ke)

  parse = do
    extension <- Parse.munch1 Char.isAlphaNum
475
476
    case classifyKnownExtension extension of
        Just ke ->
477
            return ke
478
        Nothing ->
479
480
            fail ("Can't parse " ++ show extension ++ " as KnownExtension")

481
482
483
484
485
486
487
488
489
490
491
492
classifyExtension :: String -> Extension
classifyExtension string
  = case classifyKnownExtension string of
    Just ext -> EnableExtension ext
    Nothing ->
        case string of
        'N':'o':string' ->
            case classifyKnownExtension string' of
            Just ext -> DisableExtension ext
            Nothing -> UnknownExtension string
        _ -> UnknownExtension string

493
494
-- | 'read' for 'KnownExtension's is really really slow so for the Text
-- instance
495
-- what we do is make a simple table indexed off the first letter in the
496
-- extension name. The extension names actually cover the range @'A'-'Z'@
497
498
499
500
501
502
-- pretty densely and the biggest bucket is 7 so it's not too bad. We just do
-- a linear search within each bucket.
--
-- This gives an order of magnitude improvement in parsing speed, and it'll
-- also allow us to do case insensitive matches in future if we prefer.
--
503
504
505
classifyKnownExtension :: String -> Maybe KnownExtension
classifyKnownExtension "" = Nothing
classifyKnownExtension string@(c : _)
506
  | inRange (bounds knownExtensionTable) c
507
508
  = lookup string (knownExtensionTable ! c)
  | otherwise = Nothing
509

510
511
knownExtensionTable :: Array Char [(String, KnownExtension)]
knownExtensionTable =
512
  accumArray (flip (:)) [] ('A', 'Z')
513
    [ (head str, (str, extension))
514
    | extension <- [toEnum 0 ..]
515
    , let str = show extension ]
516