ParseUtils.hs 10.9 KB
Newer Older
simonmar's avatar
simonmar committed
1
2
3
4
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
-----------------------------------------------------------------------------
-- |
-- 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
47
        LineNo, PError(..), PWarning, locatedErrorMsg, syntaxError, warning,
48
	runP, ParseResult(..),
Simon Marlow's avatar
Simon Marlow committed
49
50
	Field,
	FieldDescr(..), readFields,
ijones's avatar
ijones committed
51
	parseFilePathQ, parseTokenQ,
52
53
	parseModuleNameQ, parseDependency, parseOptVersion,
	parsePackageNameQ, parseVersionRangeQ,
Simon Marlow's avatar
Simon Marlow committed
54
55
	parseTestedWithQ, parseLicenseQ, parseExtensionQ, 
	parseSepList, parseCommaList, parseOptCommaList,
ijones's avatar
ijones committed
56
	showFilePath, showToken, showTestedWith, showDependency, showFreeText,
Simon Marlow's avatar
Simon Marlow committed
57
	field, simpleField, listField, commaListField, optsField, liftField,
58
	parseReadS, parseReadSQ, parseQuoted,
simonmar's avatar
simonmar committed
59
60
  ) where

ijones's avatar
ijones committed
61
import Distribution.Compiler (CompilerFlavor)
simonmar's avatar
simonmar committed
62
63
64
65
import Distribution.License
import Distribution.Version
import Distribution.Package	( parsePackageName )
import Distribution.Compat.ReadP as ReadP hiding (get)
66
import System.FilePath (normalise)
Simon Marlow's avatar
Simon Marlow committed
67
68
69
import Language.Haskell.Extension (Extension)

import Text.PrettyPrint.HughesPJ
ijones's avatar
ijones committed
70
import Control.Monad (liftM)
simonmar's avatar
simonmar committed
71
import Data.Char
Simon Marlow's avatar
Simon Marlow committed
72
import Data.Maybe	( fromMaybe)
simonmar's avatar
simonmar committed
73
74
75
76
77
78
79
80
81
82

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

type LineNo = Int

data PError = AmbigousParse String LineNo
            | NoParse String LineNo
            | FromString String (Maybe LineNo)
        deriving Show

83
84
85
type PWarning = String

data ParseResult a = ParseFailed PError | ParseOk [PWarning] a
86
87
88
        deriving Show

instance Monad ParseResult where
89
	return x = ParseOk [] x
90
	ParseFailed err >>= _ = ParseFailed err
91
92
93
	ParseOk ws x >>= f = case f x of
	                       ParseFailed err -> ParseFailed err
			       ParseOk ws' x' -> ParseOk (ws'++ws) x'
94
	fail s = ParseFailed (FromString s Nothing)
simonmar's avatar
simonmar committed
95

96
runP :: LineNo -> String -> ReadP a a -> String -> ParseResult a
Simon Marlow's avatar
Simon Marlow committed
97
runP lineNo fieldname p s =
simonmar's avatar
simonmar committed
98
  case [ x | (x,"") <- results ] of
99
    [a] -> ParseOk [] a
simonmar's avatar
simonmar committed
100
    []  -> case [ x | (x,ys) <- results, all isSpace ys ] of
101
             [a] -> ParseOk [] a
Simon Marlow's avatar
Simon Marlow committed
102
103
104
             []  -> ParseFailed (NoParse fieldname lineNo)
             _   -> ParseFailed (AmbigousParse fieldname lineNo)
    _   -> ParseFailed (AmbigousParse fieldname lineNo)
simonmar's avatar
simonmar committed
105
106
  where results = readP_to_S p s

ijones's avatar
ijones committed
107
108
locatedErrorMsg :: PError -> (Maybe LineNo, String)
locatedErrorMsg (AmbigousParse f n) = (Just n, "Ambigous parse in field '"++f++"'")
109
locatedErrorMsg (NoParse f n)       = (Just n, "Parse of field '"++f++"' failed: ")
ijones's avatar
ijones committed
110
111
112
113
locatedErrorMsg (FromString s n)    = (n, s)

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

115
116
117
warning :: String -> ParseResult ()
warning s = ParseOk [s] ()

Simon Marlow's avatar
Simon Marlow committed
118
119
data FieldDescr a 
  = FieldDescr 
simonmar's avatar
simonmar committed
120
121
      { fieldName     :: String
      , fieldGet      :: a -> Doc
122
      , fieldSet      :: LineNo -> String -> a -> ParseResult a
simonmar's avatar
simonmar committed
123
124
      }

Simon Marlow's avatar
Simon Marlow committed
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
field :: String -> (a -> Doc) -> (ReadP a a) -> FieldDescr a
field name showF readF = 
  FieldDescr name showF (\lineNo val _st -> runP lineNo name readF val)

liftField :: (b -> a) -> (a -> b -> b) -> FieldDescr a -> FieldDescr b
liftField get set (FieldDescr name showF parseF)
 = FieldDescr name (\b -> showF (get b))
	(\lineNo str b -> do
	    a <- parseF lineNo str (get b)
	    return (set a b))

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
164

165
166
trimTrailingSpaces :: String -> String
trimTrailingSpaces = reverse . dropWhile isSpace . reverse
simonmar's avatar
simonmar committed
167

Simon Marlow's avatar
Simon Marlow committed
168
169
170
171
172
type Field  = (LineNo,String,String)

-- |Split a file into "Field: value" groups
readFields :: String -> ParseResult [Field]
readFields = mkStanza . merge . filter validLine . zip [1..] . map trimTrailingSpaces . lines
ijones's avatar
ijones committed
173
174
175
176
  where validLine (_,s) = case dropWhile isSpace s of
                            '-':'-':_ -> False      -- Comment
                            []        -> False      -- blank line
                            _         -> True
simonmar's avatar
simonmar committed
177

ijones's avatar
ijones committed
178
merge :: [(a, [Char])] -> [(a, [Char])]
179
180
181
182
183
184
185
merge ((n,x):ys) = (n, x++concat (map (get_continuation . snd) rest)):merge ys'
  where (rest, ys') = span (is_continuation . snd) ys
        is_continuation (c:_) = isSpace c
        is_continuation []    = False
        get_continuation s = '\n':strip_dot (dropWhile isSpace s)
        strip_dot "." = ""
        strip_dot s   = s
simonmar's avatar
simonmar committed
186
187
merge []         = []

Simon Marlow's avatar
Simon Marlow committed
188
mkStanza :: [(Int,String)] -> ParseResult [Field]
ijones's avatar
ijones committed
189
mkStanza []          = return []
Simon Marlow's avatar
Simon Marlow committed
190
191
192
193
mkStanza ((n,'#':xs):ys) | not (isSpace (head xs)) = do
  ss <- mkStanza ys
  return ((n, '#':dir, dropWhile isSpace val) : ss)
  where (dir,val) = break isSpace xs
ijones's avatar
ijones committed
194
195
mkStanza ((n,xs):ys) =
  case break (==':') xs of
Simon Marlow's avatar
Simon Marlow committed
196
197
    (fld0, ':':val) -> do
       let fld = map toLower fld0
ijones's avatar
ijones committed
198
199
       ss <- mkStanza ys
       return ((n, fld, dropWhile isSpace val):ss)
ijones's avatar
ijones committed
200
    (_, _)       -> syntaxError n "Invalid syntax (no colon after field name)"
simonmar's avatar
simonmar committed
201
202

-- |parse a module name
203
parseModuleNameQ :: ReadP r String
ijones's avatar
ijones committed
204
205
parseModuleNameQ = parseQuoted modu <++ modu
 where modu = do 
206
207
208
	  c <- satisfy isUpper
	  cs <- munch (\x -> isAlphaNum x || x `elem` "_'.")
	  return (c:cs)
simonmar's avatar
simonmar committed
209

210
parseFilePathQ :: ReadP r FilePath
211
parseFilePathQ = liftM normalise parseTokenQ
simonmar's avatar
simonmar committed
212
213
214
215
216

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

parseDependency :: ReadP r Dependency
217
parseDependency = do name <- parsePackageNameQ
simonmar's avatar
simonmar committed
218
                     skipSpaces
219
                     ver <- parseVersionRangeQ <++ return AnyVersion
simonmar's avatar
simonmar committed
220
221
222
                     skipSpaces
                     return $ Dependency name ver

ijones's avatar
ijones committed
223
parsePackageNameQ :: ReadP r String
224
parsePackageNameQ = parseQuoted parsePackageName <++ parsePackageName 
ijones's avatar
ijones committed
225
226

parseVersionRangeQ :: ReadP r VersionRange
227
228
parseVersionRangeQ = parseQuoted parseVersionRange <++ parseVersionRange

simonmar's avatar
simonmar committed
229
parseOptVersion :: ReadP r Version
230
231
232
233
234
235
236
237
238
239
240
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
241

242
243
parseLicenseQ :: ReadP r License
parseLicenseQ = parseQuoted parseReadS <++ parseReadS
simonmar's avatar
simonmar committed
244

245
246
247
248
-- 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
249

250
251
parseExtensionQ :: ReadP r Extension
parseExtensionQ = parseQuoted parseReadS <++ parseReadS
simonmar's avatar
simonmar committed
252

253
254
255
256
-- | Parse something optionally wrapped in quotes.
parseReadSQ :: Read a => ReadP r a
parseReadSQ = parseQuoted parseReadS <++ parseReadS

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

Simon Marlow's avatar
Simon Marlow committed
260
261
262
263
264
265
266
267
268
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
269
270
parseCommaList :: ReadP r a -- ^The parser for the stuff between commas
               -> ReadP r [a]
Simon Marlow's avatar
Simon Marlow committed
271
parseCommaList = parseSepList (ReadP.char ',')
simonmar's avatar
simonmar committed
272

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

277
278
279
parseQuoted :: ReadP r a -> ReadP r a
parseQuoted p = between (ReadP.char '"') (ReadP.char '"') p

simonmar's avatar
simonmar committed
280
281
282
283
-- --------------------------------------------
-- ** Pretty printing

showFilePath :: FilePath -> Doc
ijones's avatar
ijones committed
284
285
286
287
showFilePath = showToken

showToken :: String -> Doc
showToken str
288
289
 | not (any dodgy str) &&
   not (null str)       = text str
ijones's avatar
ijones committed
290
291
 | otherwise            = text (show str)
  where dodgy c = isSpace c || c == ','
simonmar's avatar
simonmar committed
292
293
294
295
296
297

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

showDependency :: Dependency -> Doc
showDependency (Dependency name ver) = text name <+> text (showVersionRange ver)
298
299
300
301
302

-- | 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]