ParseUtils.hs 29.5 KB
Newer Older
1
2
3
4
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -cpp #-}
{-# OPTIONS_NHC98 -cpp #-}
{-# OPTIONS_JHC -fcpp #-}
simonmar's avatar
simonmar committed
5
6
7
8
9
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
42
43
44
45
46
47
48
49
50
-----------------------------------------------------------------------------
-- |
-- Module      :  Distribution.ParseUtils
-- Copyright   :  (c) The University of Glasgow 2004
-- 
-- Maintainer  :  libraries@haskell.org
-- Stability   :  alpha
-- Portability :  portable
--
-- Utilities for parsing PackageDescription and InstalledPackageInfo.


{- 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 the University 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. -}

-- This module is meant to be local-only to Distribution...

-- #hide
module Distribution.ParseUtils (
Simon Marlow's avatar
Simon Marlow committed
51
        LineNo, PError(..), PWarning, locatedErrorMsg, syntaxError, warning,
52
	runP, ParseResult(..), catchParseError, parseFail,
53
54
	Field(..), fName, lineNo, 
	FieldDescr(..), ppField, ppFields, readFields, 
ijones's avatar
ijones committed
55
	parseFilePathQ, parseTokenQ,
56
	parseModuleNameQ, parseDependency, parseBuildTool, parsePkgconfigDependency,
57
        parseOptVersion, parsePackageNameQ, parseVersionRangeQ,
Simon Marlow's avatar
Simon Marlow committed
58
59
	parseTestedWithQ, parseLicenseQ, parseExtensionQ, 
	parseSepList, parseCommaList, parseOptCommaList,
ijones's avatar
ijones committed
60
	showFilePath, showToken, showTestedWith, showDependency, showFreeText,
Simon Marlow's avatar
Simon Marlow committed
61
	field, simpleField, listField, commaListField, optsField, liftField,
62
63
64
	parseReadS, parseReadSQ, parseQuoted, parseBool,

        UnrecFieldParser, warnUnrec, ignoreUnrec,
simonmar's avatar
simonmar committed
65
66
  ) where

ijones's avatar
ijones committed
67
import Distribution.Compiler (CompilerFlavor)
simonmar's avatar
simonmar committed
68
69
70
71
import Distribution.License
import Distribution.Version
import Distribution.Package	( parsePackageName )
import Distribution.Compat.ReadP as ReadP hiding (get)
72
import Distribution.Simple.Utils (intercalate)
Simon Marlow's avatar
Simon Marlow committed
73
74
import Language.Haskell.Extension (Extension)

75
import Text.PrettyPrint.HughesPJ hiding (braces)
76
import Data.Char (isSpace, isUpper, toLower, isAlphaNum, isSymbol, isDigit)
Simon Marlow's avatar
Simon Marlow committed
77
import Data.Maybe	( fromMaybe)
78
79
80
81
82
83
84
85
import Data.List        (intersperse)

#ifdef DEBUG
import Test.HUnit (Test(..), assertBool, Assertion, runTestTT, Counts, assertEqual)
import IO
import System.Environment ( getArgs )
import Control.Monad ( zipWithM_ )
#endif
simonmar's avatar
simonmar committed
86
87
88
89
90
91
92

-- -----------------------------------------------------------------------------

type LineNo = Int

data PError = AmbigousParse String LineNo
            | NoParse String LineNo
93
            | TabsError LineNo
simonmar's avatar
simonmar committed
94
95
96
            | FromString String (Maybe LineNo)
        deriving Show

97
98
99
type PWarning = String

data ParseResult a = ParseFailed PError | ParseOk [PWarning] a
100
101
102
        deriving Show

instance Monad ParseResult where
103
	return x = ParseOk [] x
104
	ParseFailed err >>= _ = ParseFailed err
105
106
107
	ParseOk ws x >>= f = case f x of
	                       ParseFailed err -> ParseFailed err
			       ParseOk ws' x' -> ParseOk (ws'++ws) x'
108
	fail s = ParseFailed (FromString s Nothing)
simonmar's avatar
simonmar committed
109

110
111
112
113
114
115
116
117
catchParseError :: ParseResult a -> (PError -> ParseResult a)
                -> ParseResult a
p@(ParseOk _ _) `catchParseError` _ = p
ParseFailed e `catchParseError` k   = k e

parseFail :: PError -> ParseResult a
parseFail = ParseFailed

118
runP :: LineNo -> String -> ReadP a a -> String -> ParseResult a
nominolo@gmail.com's avatar
nominolo@gmail.com committed
119
runP line fieldname p s =
simonmar's avatar
simonmar committed
120
  case [ x | (x,"") <- results ] of
121
    [a] -> ParseOk [] a
simonmar's avatar
simonmar committed
122
    []  -> case [ x | (x,ys) <- results, all isSpace ys ] of
123
             [a] -> ParseOk [] a
nominolo@gmail.com's avatar
nominolo@gmail.com committed
124
125
126
             []  -> ParseFailed (NoParse fieldname line)
             _   -> ParseFailed (AmbigousParse fieldname line)
    _   -> ParseFailed (AmbigousParse fieldname line)
simonmar's avatar
simonmar committed
127
128
  where results = readP_to_S p s

ijones's avatar
ijones committed
129
locatedErrorMsg :: PError -> (Maybe LineNo, String)
nominolo@gmail.com's avatar
nominolo@gmail.com committed
130
locatedErrorMsg (AmbigousParse f n) = (Just n, "Ambiguous parse in field '"++f++"'")
131
locatedErrorMsg (NoParse f n)       = (Just n, "Parse of field '"++f++"' failed: ")
132
locatedErrorMsg (TabsError n)       = (Just n, "Tab used as indentation.")
ijones's avatar
ijones committed
133
134
135
136
locatedErrorMsg (FromString s n)    = (n, s)

syntaxError :: LineNo -> String -> ParseResult a
syntaxError n s = ParseFailed $ FromString s (Just n)
simonmar's avatar
simonmar committed
137

138
139
140
tabsError :: LineNo -> ParseResult a
tabsError ln = ParseFailed $ TabsError ln

141
142
143
warning :: String -> ParseResult ()
warning s = ParseOk [s] ()

nominolo@gmail.com's avatar
nominolo@gmail.com committed
144
145
-- | Field descriptor.  The parameter @a@ parameterizes over where the field's
--   value is stored in.
Simon Marlow's avatar
Simon Marlow committed
146
147
data FieldDescr a 
  = FieldDescr 
simonmar's avatar
simonmar committed
148
149
      { fieldName     :: String
      , fieldGet      :: a -> Doc
150
      , fieldSet      :: LineNo -> String -> a -> ParseResult a
nominolo@gmail.com's avatar
nominolo@gmail.com committed
151
152
153
        -- ^ @fieldSet n str x@ Parses the field value from the given input
        -- string @str@ and stores the result in @x@ if the parse was
        -- successful.  Otherwise, reports an error on line number @n@.
simonmar's avatar
simonmar committed
154
155
      }

Simon Marlow's avatar
Simon Marlow committed
156
157
field :: String -> (a -> Doc) -> (ReadP a a) -> FieldDescr a
field name showF readF = 
nominolo@gmail.com's avatar
nominolo@gmail.com committed
158
  FieldDescr name showF (\line val _st -> runP line name readF val)
Simon Marlow's avatar
Simon Marlow committed
159

nominolo@gmail.com's avatar
nominolo@gmail.com committed
160
161
-- Lift a field descriptor storing into an 'a' to a field descriptor storing
-- into a 'b'.
Simon Marlow's avatar
Simon Marlow committed
162
163
164
liftField :: (b -> a) -> (a -> b -> b) -> FieldDescr a -> FieldDescr b
liftField get set (FieldDescr name showF parseF)
 = FieldDescr name (\b -> showF (get b))
nominolo@gmail.com's avatar
nominolo@gmail.com committed
165
166
	(\line str b -> do
	    a <- parseF line str (get b)
Simon Marlow's avatar
Simon Marlow committed
167
168
	    return (set a b))

nominolo@gmail.com's avatar
nominolo@gmail.com committed
169
-- Parser combinator for simple fields.  Takes a field name, a pretty printer,
nominolo@gmail.com's avatar
nominolo@gmail.com committed
170
171
-- a parser function, an accessor, and a setter, returns a FieldDescr over the
-- compoid structure.
Simon Marlow's avatar
Simon Marlow committed
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
simpleField :: String -> (a -> Doc) -> (ReadP a a)
            -> (b -> a) -> (a -> b -> b) -> FieldDescr b
simpleField name showF readF get set
  = liftField get set $ field name showF readF

commaListField :: String -> (a -> Doc) -> (ReadP [a] a)
		 -> (b -> [a]) -> ([a] -> b -> b) -> FieldDescr b
commaListField name showF readF get set = 
  liftField get set $ 
    field name (fsep . punctuate comma . map showF) (parseCommaList readF)

listField :: String -> (a -> Doc) -> (ReadP [a] a)
		 -> (b -> [a]) -> ([a] -> b -> b) -> FieldDescr b
listField name showF readF get set = 
  liftField get set $ 
    field name (fsep . map showF) (parseOptCommaList readF)

optsField :: String -> CompilerFlavor -> (b -> [(CompilerFlavor,[String])]) -> ([(CompilerFlavor,[String])] -> b -> b) -> FieldDescr b
optsField name flavor get set = 
   liftField (fromMaybe [] . lookup flavor . get) 
	     (\opts b -> set (update flavor opts (get b)) b) $
	field name (hsep . map text)
		   (sepBy parseTokenQ' (munch1 isSpace))
  where
        update f opts [] = [(f,opts)]
	update f opts ((f',opts'):rest)
           | f == f'   = (f, opts ++ opts') : rest
           | otherwise = (f',opts') : update f opts rest
simonmar's avatar
simonmar committed
200

201
202
203
204
205
206
207
208
ppFields :: a -> [FieldDescr a] -> Doc
ppFields _ [] = empty
ppFields pkg' ((FieldDescr name getter _):flds) =
     ppField name (getter pkg') $$ ppFields pkg' flds

ppField :: String -> Doc -> Doc
ppField name fielddoc = text name <> colon <+> fielddoc

209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227

-- | The type of a function which, given a name-value pair of an
--   unrecognized field, and the current structure being built,
--   decides whether to incorporate the unrecognized field
--   (by returning  Just x, where x is a possibly modified version
--   of the structure being built), or not (by returning Nothing).
type UnrecFieldParser a = (String,String) -> a -> Maybe a

-- | A default unrecognized field parser which simply returns Nothing,
--   i.e. ignores all unrecognized fields, so warnings will be generated.
warnUnrec :: UnrecFieldParser a
warnUnrec _ _ = Nothing

-- | A default unrecognized field parser which silently (i.e. no
--   warnings will be generated) ignores unrecognized fields, by
--   returning the structure being built unmodified.
ignoreUnrec :: UnrecFieldParser a
ignoreUnrec _ x = Just x

228
229
------------------------------------------------------------------------------

nominolo@gmail.com's avatar
nominolo@gmail.com committed
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
-- The data type for our three syntactic categories 
data Field 
    = F LineNo String String
      -- ^ A regular @<property>: <value>@ field
    | Section LineNo String String [Field]
      -- ^ A section with a name and possible parameter.  The syntactic
      -- structure is:
      -- 
      -- @
      --   <sectionname> <arg> {
      --     <field>*
      --   }
      -- @
    | IfBlock LineNo String [Field] [Field]
      -- ^ A conditional block with an optional else branch:
      --
      -- @
      --  if <condition> {
      --    <field>*
      --  } else {
      --    <field>*
      --  }
Ian Lynagh's avatar
Ian Lynagh committed
252
      -- @
nominolo@gmail.com's avatar
nominolo@gmail.com committed
253
254
      deriving (Show
               ,Eq)   -- for testing
255
256
257
258
259
260

lineNo :: Field -> LineNo
lineNo (F n _ _) = n
lineNo (Section n _ _ _) = n
lineNo (IfBlock n _ _ _) = n

nominolo@gmail.com's avatar
nominolo@gmail.com committed
261
fName :: Field -> String
262
fName (F _ n _) = n
nominolo@gmail.com's avatar
nominolo@gmail.com committed
263
fName (Section _ n _ _) = n
264
fName _ = error "fname: not a field or section"
265

Simon Marlow's avatar
Simon Marlow committed
266
readFields :: String -> ParseResult [Field]
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
readFields input = 
      ifelse
  =<< mapM (mkField 0)
  =<< mkTree (tokenise input)

  where tokenise = concatMap tokeniseLine
                 . trimLines
                 . lines
                 . normaliseLineEndings
                 -- TODO: should decode UTF8

-- attach line number and determine indentation
trimLines :: [String] -> [(LineNo, Indent, HasTabs, String)]
trimLines ls = [ (lineno, indent, hastabs, (trimTrailing l'))
               | (lineno, l) <- zip [1..] ls
               , let (sps, l') = span isSpace l
                     indent    = length sps
                     hastabs   = '\t' `elem` sps
               , validLine l' ]
  where validLine ('-':'-':_) = False      -- Comment
        validLine []          = False      -- blank line
        validLine _           = True

-- | We parse generically based on indent level and braces '{' '}'. To do that
-- we split into lines and then '{' '}' tokens and other spans within a line.
data Token = 
       -- | The 'Line' token is for bits that /start/ a line, eg:
       --
       -- > "\n  blah blah { blah"
       --
       -- tokenises to:
       -- 
       -- > [Line n 2 False "blah blah", OpenBracket, Span n "blah"]
       --
       -- so lines are the only ones that can have nested layout, since they
       -- have a known indentation level.
       --
       -- eg: we can't have this:
Duncan Coutts's avatar
Duncan Coutts committed
305
       --
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
       -- > if ... {
       -- > } else
       -- >     other
       --
       -- because other cannot nest under else, since else doesn't start a line
       -- so cannot have nested layout. It'd have to be:
       --
       -- > if ... {
       -- > }
       -- >   else
       -- >     other
       --
       -- but that's not so common, people would normally use layout or
       -- brackets not both in a single @if else@ construct.
       -- 
       -- > if ... { foo : bar }
       -- > else
       -- >    other
       -- 
       -- this is ok
       Line LineNo Indent HasTabs String
     | Span LineNo                String  -- ^ span in a line, following brackets
     | OpenBracket LineNo | CloseBracket LineNo

type Indent = Int
type HasTabs = Bool

-- | Tokenise a single line, splitting on '{' '}' and the spans inbetween.
-- Also trims leading & trailing space on those spans within the line.
tokeniseLine :: (LineNo, Indent, HasTabs, String) -> [Token]
tokeniseLine (n0, i, t, l) = case split n0 l of
                            (Span _ l':ss) -> Line n0 i t l' :ss
                            cs              -> cs
  where split _ "" = []
        split n s  = case span (\c -> c /='}' && c /= '{') s of
          ("", '{' : s') ->             OpenBracket  n : split n s'
          (w , '{' : s') -> mkspan n w (OpenBracket  n : split n s')
          ("", '}' : s') ->             CloseBracket n : split n s'
          (w , '}' : s') -> mkspan n w (CloseBracket n : split n s') 
          (w ,        _) -> mkspan n w []

        mkspan n s ss | null s'   =             ss
                      | otherwise = Span n s' : ss
          where s' = trimTrailing (trimLeading s)

trimLeading, trimTrailing :: String -> String
trimLeading  = dropWhile isSpace
trimTrailing = reverse . dropWhile isSpace . reverse


-- | Fix different systems silly line ending conventions
normaliseLineEndings :: String -> String
normaliseLineEndings [] = []
normaliseLineEndings ('\r':'\n':s) = '\n' : normaliseLineEndings s -- windows
normaliseLineEndings ('\r':s)      = '\n' : normaliseLineEndings s -- old osx
normaliseLineEndings (  c :s)      =   c  : normaliseLineEndings s

type SyntaxTree = Tree (LineNo, HasTabs, String)

Duncan Coutts's avatar
Duncan Coutts committed
365
-- | Parse the stream of tokens into a tree of them, based on indent \/ layout
366
367
368
369
370
371
372
373
374
375
376
377
378
379
mkTree :: [Token] -> ParseResult [SyntaxTree]
mkTree toks =
  layout 0 [] toks >>= \(trees, trailing) -> case trailing of
    []               -> return trees
    OpenBracket  n:_ -> syntaxError n "mismatched backets, unexpected {"
    CloseBracket n:_ -> syntaxError n "mismatched backets, unexpected }"
    -- the following two should never happen:
    Span n     l  :_ -> syntaxError n $ "unexpected span: " ++ show l
    Line n _ _ l  :_ -> syntaxError n $ "unexpected line: " ++ show l


-- | Parse the stream of tokens into a tree of them, based on indent
-- This parse state expect to be in a layout context, though possibly
-- nested within a braces context so we may still encounter closing braces.
Duncan Coutts's avatar
Duncan Coutts committed
380
layout :: Indent       -- ^ indent level of the parent\/previous line
381
382
383
384
385
386
387
388
389
390
391
392
393
394
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
       -> [SyntaxTree] -- ^ accumulating param, trees in this level
       -> [Token]      -- ^ remaining tokens
       -> ParseResult ([SyntaxTree], [Token])
                       -- ^ collected trees on this level and trailing tokens
layout _ a []                               = return (reverse a, [])
layout i a (s@(Line _ i' _ _):ss) | i' < i  = return (reverse a, s:ss)
layout i a (Line n _ t l:OpenBracket n':ss) = do
    (sub, ss') <- braces n' [] ss
    layout i (Node (n,t,l) sub:a) ss'

layout i a (Span n     l:OpenBracket n':ss) = do
    (sub, ss') <- braces n' [] ss
    layout i (Node (n,False,l) sub:a) ss'

-- look ahead to see if following lines are more indented, giving a sub-tree
layout i a (Line n i' t l:ss) = do
    lookahead <- layout (i'+1) [] ss
    case lookahead of
        ([], _)   -> layout i (Node (n,t,l) [] :a) ss
        (ts, ss') -> layout i (Node (n,t,l) ts :a) ss'

layout _ _ (   OpenBracket  n :_)  = syntaxError n $ "unexpected '{'"
layout _ a (s@(CloseBracket _):ss) = return (reverse a, s:ss)
layout _ _ (   Span n l       : _) = syntaxError n $ "unexpected span: "
                                                  ++ show l

-- | Parse the stream of tokens into a tree of them, based on explicit braces
-- This parse state expects to find a closing bracket.
braces :: LineNo       -- ^ line of the '{', used for error messages
       -> [SyntaxTree] -- ^ accumulating param, trees in this level
       -> [Token]      -- ^ remaining tokens
       -> ParseResult ([SyntaxTree],[Token])
                       -- ^ collected trees on this level and trailing tokens
braces m a (Line n _ t l:OpenBracket n':ss) = do
    (sub, ss') <- braces n' [] ss
    braces m (Node (n,t,l) sub:a) ss'

braces m a (Span n     l:OpenBracket n':ss) = do 
    (sub, ss') <- braces n' [] ss
    braces m (Node (n,False,l) sub:a) ss'

braces m a (Line n i t l:ss) = do
    lookahead <- layout (i+1) [] ss
    case lookahead of
        ([], _)   -> braces m (Node (n,t,l) [] :a) ss
        (ts, ss') -> braces m (Node (n,t,l) ts :a) ss'

braces m a (Span n       l:ss) = braces m (Node (n,False,l) []:a) ss
braces _ a (CloseBracket _:ss) = return (reverse a, ss)
braces n _ []                  = syntaxError n $ "opening brace '{'"
                              ++ "has no matching closing brace '}'"
braces _ _ (OpenBracket  n:_)  = syntaxError n "unexpected '{'"

-- | Convert the parse tree into the Field AST
-- Also check for dodgy uses of tabs in indentation.
mkField :: Int -> SyntaxTree -> ParseResult Field
mkField d (Node (n,t,_) _) | d >= 1 && t = tabsError n
mkField d (Node (n,_,l) ts) = case span (\c -> isAlphaNum c || c == '-') l of
  ([], _)       -> syntaxError n $ "unrecognised field or section: " ++ show l
  (name, rest)  -> case trimLeading rest of
    (':':rest') -> do let followingLines = concatMap flatten ts
                          tabs = not (null [()| (_,True,_) <- followingLines ])
                      if tabs && d >= 1
                        then tabsError n
                        else return $ F n (map toLower name)
                                          (fieldValue rest' followingLines) 
    rest'       -> do ts' <- mapM (mkField (d+1)) ts
                      return (Section n (map toLower name) rest' ts')
    where fieldValue firstLine followingLines =
            let firstLine' = trimLeading firstLine
                followingLines' = map (\(_,_,s) -> stripDot s) followingLines
                allLines | null firstLine' =              followingLines'
                         | otherwise       = firstLine' : followingLines'
454
             in intercalate "\n" allLines
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
          stripDot "." = ""
          stripDot s   = s

-- | Convert if/then/else 'Section's to 'IfBlock's
ifelse :: [Field] -> ParseResult [Field]
ifelse [] = return []
ifelse (Section n "if"   cond thenpart
       :Section _ "else" as   elsepart:fs)
       | null cond     = syntaxError n "'if' with missing condition"
       | null thenpart = syntaxError n "'then' branch of 'if' is empty"
       | not (null as) = syntaxError n "'else' takes no arguments"
       | null elsepart = syntaxError n "'else' branch of 'if' is empty"
       | otherwise     = do tp  <- ifelse thenpart
                            ep  <- ifelse elsepart
                            fs' <- ifelse fs
                            return (IfBlock n cond tp ep:fs')
ifelse (Section n "if"   cond thenpart:fs)
       | null cond     = syntaxError n "'if' with missing condition"
       | null thenpart = syntaxError n "'then' branch of 'if' is empty"
       | otherwise     = do tp  <- ifelse thenpart
                            fs' <- ifelse fs
                            return (IfBlock n cond tp []:fs')
ifelse (Section n "else" _ _:_) = syntaxError n "stray 'else' with no preceding 'if'"
ifelse (Section n s a fs':fs) = do fs''  <- ifelse fs'
                                   fs''' <- ifelse fs
                                   return (Section n s a fs'' : fs''')
ifelse (f:fs) = do fs' <- ifelse fs 
                   return (f : fs')
483
484

------------------------------------------------------------------------------
simonmar's avatar
simonmar committed
485
486

-- |parse a module name
487
parseModuleNameQ :: ReadP r String
ijones's avatar
ijones committed
488
489
parseModuleNameQ = parseQuoted modu <++ modu
 where modu = do 
490
491
492
	  c <- satisfy isUpper
	  cs <- munch (\x -> isAlphaNum x || x `elem` "_'.")
	  return (c:cs)
simonmar's avatar
simonmar committed
493

494
parseFilePathQ :: ReadP r FilePath
495
496
497
parseFilePathQ = parseTokenQ 
  -- removed until normalise is no longer broken, was:
  --   liftM normalise parseTokenQ
simonmar's avatar
simonmar committed
498
499
500
501

parseReadS :: Read a => ReadP r a
parseReadS = readS_to_P reads

502
503
504
505
parseBool :: ReadP r Bool
parseBool = choice [ (string "true" <++ string "True") >> return True
                   , (string "false" <++ string "False") >> return False ]

506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
parseBuildTool :: ReadP r Dependency
parseBuildTool = do name <- parseBuildToolNameQ
                    skipSpaces
                    ver <- parseVersionRangeQ <++ return AnyVersion
                    skipSpaces
                    return $ Dependency name ver

parseBuildToolNameQ :: ReadP r String
parseBuildToolNameQ = parseQuoted parseBuildToolName <++ parseBuildToolName

-- like parsePackageName but accepts symbols in components
parseBuildToolName :: ReadP r String
parseBuildToolName = do ns <- sepBy1 component (ReadP.char '-')
                        return (concat (intersperse "-" ns))
  where component = do
          cs <- munch1 (\c -> isAlphaNum c || isSymbol c && c /= '-')
          if all isDigit cs then pfail else return cs

simonmar's avatar
simonmar committed
524
parseDependency :: ReadP r Dependency
525
parseDependency = do name <- parsePackageNameQ
simonmar's avatar
simonmar committed
526
                     skipSpaces
527
                     ver <- parseVersionRangeQ <++ return AnyVersion
simonmar's avatar
simonmar committed
528
529
530
                     skipSpaces
                     return $ Dependency name ver

531
532
533
534
535
536
537
538
539
540
-- pkg-config allows versions and other letters in package names, 
-- eg "gtk+-2.0" is a valid pkg-config package _name_.
-- It then has a package version number like 2.10.13
parsePkgconfigDependency :: ReadP r Dependency
parsePkgconfigDependency = do name <- munch1 (\c -> isAlphaNum c || c `elem` "+-._")
                              skipSpaces
                              ver <- parseVersionRangeQ <++ return AnyVersion
                              skipSpaces
                              return $ Dependency name ver

ijones's avatar
ijones committed
541
parsePackageNameQ :: ReadP r String
542
parsePackageNameQ = parseQuoted parsePackageName <++ parsePackageName 
ijones's avatar
ijones committed
543
544

parseVersionRangeQ :: ReadP r VersionRange
545
546
parseVersionRangeQ = parseQuoted parseVersionRange <++ parseVersionRange

simonmar's avatar
simonmar committed
547
parseOptVersion :: ReadP r Version
548
549
550
551
552
553
554
555
556
557
558
parseOptVersion = parseQuoted ver <++ ver
  where ver = parseVersion <++ return noVersion
	noVersion = Version{ versionBranch=[], versionTags=[] }

parseTestedWithQ :: ReadP r (CompilerFlavor,VersionRange)
parseTestedWithQ = parseQuoted tw <++ tw
  where tw = do compiler <- parseReadS
		skipSpaces
		version <- parseVersionRange <++ return AnyVersion
		skipSpaces
		return (compiler,version)
simonmar's avatar
simonmar committed
559

560
561
parseLicenseQ :: ReadP r License
parseLicenseQ = parseQuoted parseReadS <++ parseReadS
simonmar's avatar
simonmar committed
562

563
564
565
566
-- urgh, we can't define optQuotes :: ReadP r a -> ReadP r a
-- because the "compat" version of ReadP isn't quite powerful enough.  In
-- particular, the type of <++ is ReadP r r -> ReadP r a -> ReadP r a
-- Hence the trick above to make 'lic' polymorphic.
simonmar's avatar
simonmar committed
567

568
569
parseExtensionQ :: ReadP r Extension
parseExtensionQ = parseQuoted parseReadS <++ parseReadS
simonmar's avatar
simonmar committed
570

571
572
573
574
-- | Parse something optionally wrapped in quotes.
parseReadSQ :: Read a => ReadP r a
parseReadSQ = parseQuoted parseReadS <++ parseReadS

ijones's avatar
ijones committed
575
576
parseTokenQ :: ReadP r String
parseTokenQ = parseReadS <++ munch1 (\x -> not (isSpace x) && x /= ',')
simonmar's avatar
simonmar committed
577

Simon Marlow's avatar
Simon Marlow committed
578
579
580
581
582
583
584
585
586
parseTokenQ' :: ReadP r String
parseTokenQ' = parseReadS <++ munch1 (\x -> not (isSpace x))

parseSepList :: ReadP r b
	     -> ReadP r a -- ^The parser for the stuff between commas
             -> ReadP r [a]
parseSepList sepr p = sepBy p separator
    where separator = skipSpaces >> sepr >> skipSpaces

simonmar's avatar
simonmar committed
587
588
parseCommaList :: ReadP r a -- ^The parser for the stuff between commas
               -> ReadP r [a]
Simon Marlow's avatar
Simon Marlow committed
589
parseCommaList = parseSepList (ReadP.char ',')
simonmar's avatar
simonmar committed
590

ijones's avatar
ijones committed
591
parseOptCommaList :: ReadP r a -- ^The parser for the stuff between commas
Simon Marlow's avatar
Simon Marlow committed
592
593
                  -> ReadP r [a]
parseOptCommaList = parseSepList (optional (ReadP.char ','))
ijones's avatar
ijones committed
594

595
596
597
parseQuoted :: ReadP r a -> ReadP r a
parseQuoted p = between (ReadP.char '"') (ReadP.char '"') p

simonmar's avatar
simonmar committed
598
599
600
601
-- --------------------------------------------
-- ** Pretty printing

showFilePath :: FilePath -> Doc
ijones's avatar
ijones committed
602
603
604
605
showFilePath = showToken

showToken :: String -> Doc
showToken str
606
607
 | not (any dodgy str) &&
   not (null str)       = text str
ijones's avatar
ijones committed
608
609
 | otherwise            = text (show str)
  where dodgy c = isSpace c || c == ','
simonmar's avatar
simonmar committed
610
611
612
613
614
615

showTestedWith :: (CompilerFlavor,VersionRange) -> Doc
showTestedWith (compiler,version) = text (show compiler ++ " " ++ showVersionRange version)

showDependency :: Dependency -> Doc
showDependency (Dependency name ver) = text name <+> text (showVersionRange ver)
616
617
618
619
620

-- | Pretty-print free-format text, ensuring that it is vertically aligned,
-- and with blank lines replaced by dots for correct re-parsing.
showFreeText :: String -> Doc
showFreeText s = vcat [text (if null l then "." else l) | l <- lines s]
621

622
623
624
625
626
627
628
629
630
631
632
633
-- --------------------------------------------
-- ** Tree bits

-- Data.Tree was not present in ghc-6.2, and we only need these bits:

data Tree a = Node a (Forest a)
type Forest a = [Tree a]

flatten :: Tree a -> [a]
flatten t = squish t []
  where squish (Node x ts) xs = x:foldr squish xs ts

634
635
636
637
------------------------------------------------------------------------------
-- TESTING

#ifdef DEBUG
nominolo@gmail.com's avatar
nominolo@gmail.com committed
638
639
640
test_readFields = case 
                    readFields testFile 
                  of
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
                    ParseOk _ x -> x == expectedResult
                    _ -> False
  where 
    testFile = unlines $
          [ "Cabal-version: 3"
          , ""
          , "Description: This is a test file   "
          , "  with a description longer than two lines.  "
          , "if os(windows) {"
          , "  License:  You may not use this software"
          , "    ."
          , "    If you do use this software you will be seeked and destroyed."
          , "}"
          , "if os(linux) {"
          , "  Main-is:  foo1  "
          , "}"
          , ""
          , "if os(vista) {"
          , "  executable RootKit {"
          , "    Main-is: DRMManager.hs"
          , "  }"
          , "} else {"
          , "  executable VistaRemoteAccess {"
          , "    Main-is: VCtrl"
          , "}}"
          , ""
          , "executable Foo-bar {"
          , "  Main-is: Foo.hs"
          , "}"
          ]
    expectedResult = 
          [ F 1 "cabal-version" "3"
          , F 3 "description" 
                  "This is a test file\nwith a description longer than two lines."
675
          , IfBlock 5 "os(windows) " 
676
677
678
679
              [ F 6 "license" 
                      "You may not use this software\n\nIf you do use this software you will be seeked and destroyed."
              ]
              []
680
          , IfBlock 10 "os(linux) " 
681
682
              [ F 11 "main-is" "foo1" ] 
              [ ]
683
684
          , IfBlock 14 "os(vista) " 
              [ Section 15 "executable" "RootKit " 
685
686
                [ F 16 "main-is" "DRMManager.hs"]
              ] 
687
              [ Section 19 "executable" "VistaRemoteAccess "
688
689
                 [F 20 "main-is" "VCtrl"]
              ]
690
          , Section 23 "executable" "Foo-bar " 
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
              [F 24 "main-is" "Foo.hs"]
          ]

test_readFieldsCompat' = case test_readFieldsCompat of
                           ParseOk _ fs -> mapM_ (putStrLn . show) fs
                           x -> putStrLn $ "Failed: " ++ show x
test_readFieldsCompat = readFields testPkgDesc
  where 
    testPkgDesc = unlines [
        "-- Required",
        "Name: Cabal",
        "Version: 0.1.1.1.1-rain",
        "License: LGPL",
        "License-File: foo",
        "Copyright: Free Text String",
        "Cabal-version: >1.1.1",
        "-- Optional - may be in source?",
        "Author: Happy Haskell Hacker",
        "Homepage: http://www.haskell.org/foo",
        "Package-url: http://www.haskell.org/foo",
        "Synopsis: a nice package!",
        "Description: a really nice package!",
        "Category: tools",
        "buildable: True",
        "CC-OPTIONS: -g -o",
        "LD-OPTIONS: -BStatic -dn",
        "Frameworks: foo",
        "Tested-with: GHC",
        "Stability: Free Text String",
        "Build-Depends: haskell-src, HUnit>=1.0.0-rain",
        "Other-Modules: Distribution.Package, Distribution.Version,",
        "                Distribution.Simple.GHCPackageConfig",
        "Other-files: file1, file2",
        "Extra-Tmp-Files:    file1, file2",
        "C-Sources: not/even/rain.c, such/small/hands",
        "HS-Source-Dirs: src, src2",
        "Exposed-Modules: Distribution.Void, Foo.Bar",
        "Extensions: OverlappingInstances, TypeSynonymInstances",
        "Extra-Libraries: libfoo, bar, bang",
        "Extra-Lib-Dirs: \"/usr/local/libs\"",
        "Include-Dirs: your/slightest, look/will",
        "Includes: /easily/unclose, /me, \"funky, path\\\\name\"",
        "Install-Includes: /easily/unclose, /me, \"funky, path\\\\name\"",
        "GHC-Options: -fTH -fglasgow-exts",
        "Hugs-Options: +TH",
        "Nhc-Options: ",
        "Jhc-Options: ",
        "",
        "-- Next is an executable",
        "Executable: somescript",
        "Main-is: SomeFile.hs",
        "Other-Modules: Foo1, Util, Main",
        "HS-Source-Dir: scripts",
        "Extensions: OverlappingInstances",
        "GHC-Options: ",
        "Hugs-Options: ",
        "Nhc-Options: ",
        "Jhc-Options: "
        ]
{-
test' = do h <- openFile "../Cabal.cabal" ReadMode
           s <- hGetContents h
           let r = readFields s
           case r of
             ParseOk _ fs -> mapM_ (putStrLn . show) fs
             x -> putStrLn $ "Failed: " ++ show x
           putStrLn "==================="
           mapM_ (putStrLn . show) $
                 merge . zip [1..] . lines $ s
           hClose h
-}
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787

-- ghc -DDEBUG --make Distribution/ParseUtils.hs -o test

main :: IO ()
main = do
  inputFiles <- getArgs
  ok <- mapM checkResult inputFiles

  zipWithM_ summary inputFiles ok
  putStrLn $ show (length (filter not ok)) ++ " out of " ++ show (length ok) ++ " failed"

  where summary f True  = return ()
        summary f False = putStrLn $ f  ++ " failed :-("

checkResult :: FilePath -> IO Bool
checkResult inputFile = do
  file <- readFile inputFile
  case readFields file of
    ParseOk _ result -> do
       hPutStrLn stderr $ inputFile ++ " parses ok :-)"
       return True
    ParseFailed err -> do
       hPutStrLn stderr $ inputFile ++ " parse failed:"
       hPutStrLn stderr $ show err
       return False

nominolo@gmail.com's avatar
nominolo@gmail.com committed
788
789
-- 
#endif