File: Pretty.hs

package info (click to toggle)
ctklight 0.22.2-1
  • links: PTS
  • area: main
  • in suites: sarge, woody
  • size: 208 kB
  • ctags: 8
  • sloc: haskell: 1,208; makefile: 51
file content (456 lines) | stat: -rw-r--r-- 12,836 bytes parent folder | download | duplicates (4)
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
47
48
49
50
51
52
53
54
55
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
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
164
165
166
167
168
169
170
171
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
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
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
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
454
455
456
--  Compiler Toolkit: pretty-printer combinators
--
--  Author : Manuel M. T. Chakravarty
--  Created: 16 February 95
--
--  Copyright (c) [1995..2000] Manuel M. T. Chakravarty
--
--  This file is free software; you can redistribute it and/or modify
--  it under the terms of the GNU General Public License as published by
--  the Free Software Foundation; either version 2 of the License, or
--  (at your option) any later version.
--
--  This file is distributed in the hope that it will be useful,
--  but WITHOUT ANY WARRANTY; without even the implied warranty of
--  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
--  GNU General Public License for more details.
--
--- DESCRIPTION ---------------------------------------------------------------
--
--  This module provides combinators for pretty-printing, following the ideas
--  in ``Pretty-printing: An Exercise in Functional Programming (DRAFT)'' by
--  John Hughes.  Subsequently, partially brought in line with Simon Peyton
--  Jones' version of John Hughes' combinators.
--
--- DOCU ----------------------------------------------------------------------
--
--  language: Haskell 98
--
--  * In a revision of the module, the names of the exported functions where
--    brought in line with SimonPJs variant.  The old names are still exported
--    as to maintain compatibility to older code.  They will disappear
--    somewhere down the road.
--
--  * The type of `fullRender' is different from the one in SimonPJ's variant.
--
--  * `toDoc' is not supported by SimonPJ's variant.
--
--  * The combinators `($+$)', `fcat', and `fsep' are not supported.
--
--- TODO ----------------------------------------------------------------------
--
--  * currently `$|$' imposes a n^2 cost when building a text from top to
--    bottom
--
 
module Pretty (
  Doc, -- instance Show
  empty, isEmpty, char, text, nest, ($$), (<>), cat, sep, fullRender,
  --
  -- derived combinators
  --
  semi, comma, colon, dot, space, equals, lparen, rparen, lbrack, rbrack,
  lbrace, rbrace, toDoc, int, integer, float, double, rational, parens,
  brackets, braces, quotes, doubleQuotes, (<+>), hcat, hsep, vcat, hang,
  punctuate, render,
  --
  -- pretty-printing type class & precedences
  --
  Pretty(pretty, prettyPrec), usedWhen, Assoc(..), infixOp,
  --
  -- the following routines are part of the legacy interface that should not
  -- be used anymore - it will disappear in due course
  --
  textDoc, nestDoc, ($|$), (<^>), sepDocs, bestDoc,
  --
  -- *** for debugging ONLY ***
  --
  dumpDoc
) where


infixl 6 <>, <+>	-- vertical composition
infixl 5 $$		-- horizontal composition


-- default parameters
-- ------------------

dftWidth :: Int
dftWidth  = 79

dftRibbonRatio :: Float
dftRibbonRatio  = 1.5


-- representation of documents
-- ---------------------------

-- a document is a compact representation (tree shaped) of a set of layouts 
-- for a given text (EXPORTED ABSTRACTLY)
--
data Doc    = Nest      Int [DocAlt]  -- set of layouts, indented as given
data DocAlt = Text      String	      -- one row
	    | TextAbove String Doc    -- row of text above the remaining doc

-- render with defaults
--
instance Show Doc where
  showsPrec _ = showString . render

-- empty document (EXPORTED)
--
empty :: Doc
empty  = Nest 0 []

-- test for emptiness (EXPORTED)
--
isEmpty             :: Doc -> Bool
isEmpty (Nest _ [])  = True
isEmpty _	     = False

-- single character (EXPORTED)
--
char   :: Char -> Doc
char c  = text [c]

-- single line of text (EXPORTED)
--
text   :: String -> Doc
text s  = Nest 0 [Text s]

-- increase nesting of given document (EXPORTED)
--
nest                 :: Int -> Doc -> Doc
nest k (Nest m alts)  = Nest (k + m) alts

-- vertical composition of documents (EXPORTED)
--
($$)                :: Doc -> Doc -> Doc
(Nest _ []  ) $$ doc = doc
(Nest m alts) $$ doc = Nest m [below a | a <- alts]
		       where
			 below                   :: DocAlt -> DocAlt
			 below (Text s)           = let
						      doc' = nestDoc (-m) doc
						    in
						    TextAbove s doc'
			 below (TextAbove s rest) = let
						      doc' = rest 
							     $$ 
							     nestDoc (-m) doc
						    in
						    TextAbove s doc'

-- horizontal composition of documents (EXPORTED)
--
(<>)                           :: Doc -> Doc -> Doc
(Nest _ []  ) <> doc            = doc
doc           <> (Nest _ []  )  = doc
(Nest m alts) <> doc            = Nest m (concat [nextTo a | a <- alts])
  where
    nextTo                    :: DocAlt -> [DocAlt]
    nextTo (Text s)            = let
				   Nest _ bs = doc
				 in
				 [s `inFrontOf` b | b <- bs]
    nextTo (TextAbove s rest)  = [TextAbove s (rest <> doc)]

    inFrontOf                       :: String -> DocAlt -> DocAlt
    s `inFrontOf` (Text t)	       = Text (s ++ t)
    s `inFrontOf` (TextAbove t doc') = let 
					 l = length s
				       in
				       TextAbove (s ++ t) 
						 (nestDoc l doc')

-- given a list of sub-documents, generate a composite document where the 
-- sub-documents are placed next to each other (EXPORTED)
--
-- * when generating a layout a horizontal layout is only chosen
--   when the given collection of sub-documents fits on a single line
--
cat      :: [Doc] -> Doc
cat docs  = catsep (<>) docs

-- given a list of sub-documents, generate a composite document where the 
-- sub-documents are placed next to each other with some seperation between
-- each of them (EXPORTED)
--
-- * when generating a layout a horizontal layout is only chosen
--   when the given collection of sub-documents fits on a single line
--
sep      :: [Doc] -> Doc
sep docs  = catsep (<+>) docs

-- generalise `cat' and `sep'
--
catsep            :: (Doc -> Doc -> Doc) -> [Doc] -> Doc
catsep _     []    = textDoc ""
catsep hcomb docs  = fitunion (foldr hcomb empty docs) 
			      (foldr ($$)  empty docs)
  where
    --
    -- given two documents, where the first one is a horizontal
    -- composition, we only choose a single line alternative (if at
    -- all present) from the first document
    --
    fitunion                                     :: Doc -> Doc -> Doc
    fitunion (Nest m (Text s : _)) (Nest _ alts)  = Nest m (Text s : alts)
    fitunion _                     doc            = doc

-- select the best layout from a document and return it in string form
-- (EXPORTED)
--
-- * given are the overall width and the ribbon ration, ie, the number of
--   times the ribbon fits into a line (the ribbon is the number of
--   characters on a line excluding leading and trailing white spaces)
--
fullRender                   :: Int -> Float -> Doc -> String
fullRender width ribbonRatio  = 
  let
    ribbon = round (fromIntegral width / ribbonRatio)
  in
  dropWhile (== '\n') . nestbest 0 width ribbon
  where
    --
    -- like `best', but with explicit nesting
    --
    nestbest                   :: Int -> Int -> Int -> Doc -> String
    nestbest k w r (Nest _ []  )  = ""
    nestbest k w r (Nest m alts)  = 
	     case foldr1 (choose (w - m) r) alts 
	     of
	       Text s         -> indent (k + m) s
	       TextAbove s bs -> indent (k + m) s 
				 ++ nestbest (k + m) (w - m) r bs
    --
    -- indent the given string by the given amount
    --
    indent     :: Int -> String -> String
    indent k s  = "\n" ++ copy k ' ' ++ s
		  where
		    copy   :: Int -> a -> [a]
		    copy n  = take n . repeat	     

    -- given the remaining width and ribbon together with two possible
    -- documents, choose the first one if its first line is nice; otherwise,
    -- take the second
    --
    choose                 :: Int -> Int -> DocAlt -> DocAlt -> DocAlt
    choose w r alts1 alts2  = if (nice w r (firstline alts1))
			      then alts1
			      else alts2
			      where
			        firstline (Text s)        = s
			        firstline (TextAbove s _) = s

    -- given remaining width and ribbon width decide whether a line
    -- is nice or not
    --
    nice       :: Int -> Int -> String -> Bool
    nice w r s  = (l <= w) && (l <= r)
		  where
		    l = length s


-- derived combinators
-- -------------------

-- punctuation characters (EXPORTED)
--
semi, comma, colon, dot :: Doc
semi  = char ';'
comma = char ','
colon = char ':'
dot   = char '.'

-- separators (EXPORTED)
--
space, equals :: Doc
space  = char ' '
equals = char '='

-- round parenthesis (EXPORTED)
--
lparen, rparen :: Doc
lparen = char '('
rparen = char ')'

-- square brackets (EXPORTED)
--
lbrack, rbrack :: Doc
lbrack = char '['
rbrack = char ']'

-- curly braces (EXPORTED)
--
lbrace, rbrace :: Doc
lbrace = char '{'
rbrace = char '}'

-- any value that has a textual representation (EXPORTED)
--
toDoc :: Show a => a -> Doc
toDoc  = text . show

-- ints (EXPORTED)
--
-- * these are only for compatibility with SimonPJ's `Pretty' module as `toDoc'
--   is more general
--
int      :: Int      -> Doc
int       = toDoc
integer  :: Integer  -> Doc
integer   = toDoc
float    :: Float    -> Doc
float     = toDoc
double   :: Double   -> Doc
double    = toDoc
rational :: Rational -> Doc
rational  = toDoc

-- wrap a document into various forms of brackets
--
parens, brackets, braces :: Doc -> Doc 
parens   doc = lparen <> doc <> rparen
brackets doc = lbrack <> doc <> rbrack
braces   doc = lbrace <> doc <> rbrace

-- wrap a document into quotes
--
quotes, doubleQuotes :: Doc -> Doc
quotes       doc = char '`' <> doc <> char '\''
doubleQuotes doc = char '"' <> doc <> char '"'

-- horizontal composition including a space if none of the documents is empty
-- (EXPORTED)
--
(<+>)                  :: Doc -> Doc -> Doc
d1 <+> d2 | isEmpty d1  = d2
	  | isEmpty d2  = d1
	  | otherwise   = d1 <> space <> d2

-- list version of horizontal composition (EXPORTED)
--
hcat :: [Doc] -> Doc
hcat  = foldr (<>) empty

-- list version of horizontal composition including a space (EXPORTED)
--
hsep :: [Doc] -> Doc
hsep  = foldr (<+>) empty

-- list version of vertical composition (EXPORTED)
--
vcat :: [Doc] -> Doc
vcat = foldr ($$) empty

-- hang the second document of the first, where the second one is indented
-- (EXPORTED)
--
hang             :: Doc -> Int -> Doc -> Doc
hang doc1 n doc2  = sep [doc1, nest n doc2]

-- add a punctuation document to every document in a list, but the last
-- (EXPORTED)
--
punctuate      :: Doc -> [Doc] -> [Doc]
punctuate _ []  = []
punctuate p ds  = map (<> p) (init ds) ++ [last ds]

-- render a document using the default settings
--
render :: Doc -> String
render  = fullRender dftWidth dftRibbonRatio


-- type class and precedence
-- -------------------------

-- overloaded pretty-printing function (EXPORTED)
--
class Pretty a where
  pretty     :: a -> Doc
  prettyPrec :: Int -> a -> Doc

  pretty       = prettyPrec 0
  prettyPrec _ = pretty

-- useful to keep the interface simple and general
--
instance Pretty Doc where
  pretty = id

-- conditionally apply a document transformer (EXPORTED)
--
-- * typically a function like `parens' is applied when the precedences require
--   this
--
usedWhen                        :: (Doc -> Doc) -> Bool -> Doc -> Doc
usedWhen wrap c doc | c          = wrap doc
		    | otherwise  = doc

-- associativity of an infix operator (EXPORTED)
--
data Assoc = LeftAssoc | RightAssoc | NoAssoc
	   deriving (Eq)

-- pretty print an infix operator given its precedence, lexeme, and its two
-- arguments (EXPORTED)
--
infixOp                              :: (Pretty a, Pretty b) 
				     => Assoc	  -- associativity of operator
				     -> Int	  -- precedence of operator
				     -> String    -- lexeme of operator
				     -> a	  -- left argument
				     -> b	  -- right argument
				     -> Int	  -- precedence of context
	                             -> Doc
infixOp assoc opp lexeme arg1 arg2 p  = parens `usedWhen` (p > opp) $ 
					  hsep [
					    prettyPrec leftOpp  arg1,
					    text lexeme,
					    prettyPrec rightOpp arg2
					  ]
  where
    leftOpp  = if (assoc == RightAssoc) then opp + 1 else opp
    rightOpp = if (assoc == LeftAssoc ) then opp + 1 else opp


-- the legacy interface (this is only kept for compatibility)
-- --------------------

infixr 1 $|$	-- vertical composition
infixr 1 <^>	-- horizontal composition


textDoc :: String -> Doc
textDoc  = text

nestDoc :: Int -> Doc -> Doc
nestDoc  = nest

($|$) :: Doc -> Doc -> Doc
($|$)  = ($$)

(<^>) :: Doc -> Doc -> Doc
(<^>)  = (<>)

sepDocs :: [Doc] -> Doc
sepDocs  = sep

bestDoc              :: Int -> Int -> Doc -> String
bestDoc width ribbon  = fullRender width 
				   (fromIntegral width / fromIntegral ribbon)


-- debugging support
-- -----------------

dumpDoc               :: Doc -> String
dumpDoc (Nest _ []  )  = "<empty>"
dumpDoc (Nest m alts)  = unlines . map (++ "\n--") . map outline $ alts
			 where
			   outline (Text      str  ) = str
			   outline (TextAbove str _) = str ++ "\n..."