-
Notifications
You must be signed in to change notification settings - Fork 215
/
Internal.hs
1985 lines (1762 loc) · 66.9 KB
/
Internal.hs
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
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
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
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
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveLift #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -Wall #-}
{-| This module provides internal pretty-printing utilities which are used by
other modules but are not part of the public facing API
-}
module Dhall.Pretty.Internal (
Ann(..)
, annToAnsiStyle
, prettyExpr
, prettySrcExpr
, CharacterSet(..)
, detectCharacterSet
, prettyCharacterSet
, prettyImportExpression
, prettyVar
, pretty_
, escapeText_
, escapeEnvironmentVariable
, prettyEnvironmentVariable
, prettyConst
, UnescapedLabel(..)
, escapeLabel
, prettyLabel
, prettyAnyLabel
, prettyLabels
, prettyNatural
, prettyNumber
, prettyInt
, prettyDouble
, prettyToStrictText
, prettyToString
, prettyBase16
, layout
, layoutOpts
, docToStrictText
, builtin
, keyword
, literal
, operator
, colon
, comma
, dot
, equals
, forall_
, label
, lambda
, langle
, lbrace
, lbracket
, lparen
, pipe
, rangle
, rarrow
, rbrace
, rbracket
, rparen
, temporalToText
) where
import Control.DeepSeq (NFData)
import Data.Aeson
( FromJSON (..)
, Value (String)
)
import Data.Aeson.Types (typeMismatch, unexpected)
import Data.ByteString (ByteString)
import Data.Data (Data)
import Data.Foldable
import Data.List.NonEmpty (NonEmpty (..))
import Data.Text (Text)
import Dhall.Map (Map)
import Dhall.Optics (cosmosOf, foldOf, to)
import Dhall.Src (Src (..))
import Dhall.Syntax
import {-# SOURCE #-} Dhall.Syntax.Instances.Pretty ()
import GHC.Generics (Generic)
import Language.Haskell.TH.Syntax (Lift)
import Numeric.Natural (Natural)
import Prettyprinter (Doc, Pretty, space)
import qualified Control.Exception as Exception
import qualified Data.ByteString.Base16 as Base16
import qualified Data.Char
import qualified Data.HashSet
import qualified Data.List as List
import qualified Data.List.NonEmpty as NonEmpty
import qualified Data.Maybe
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Encoding
import qualified Data.Time as Time
import qualified Dhall.Map as Map
import qualified Dhall.Syntax.Operations as Operations
import qualified Prettyprinter as Pretty
import qualified Prettyprinter.Render.String as Pretty
import qualified Prettyprinter.Render.Terminal as Terminal
import qualified Prettyprinter.Render.Text as Pretty
import qualified Text.Printf as Printf
{-| Annotation type used to tag elements in a pretty-printed document for
syntax highlighting purposes
-}
data Ann
= Keyword -- ^ Used for syntactic keywords
| Syntax -- ^ Syntax punctuation such as commas, parenthesis, and braces
| Label -- ^ Record labels
| Literal -- ^ Literals such as integers and strings
| Builtin -- ^ Builtin types and values
| Operator -- ^ Operators
deriving Show
{-| Convert annotations to their corresponding color for syntax highlighting
purposes
-}
annToAnsiStyle :: Ann -> Terminal.AnsiStyle
annToAnsiStyle Keyword = Terminal.bold <> Terminal.colorDull Terminal.Green
annToAnsiStyle Syntax = Terminal.bold <> Terminal.colorDull Terminal.Green
annToAnsiStyle Label = mempty
annToAnsiStyle Literal = Terminal.colorDull Terminal.Magenta
annToAnsiStyle Builtin = Terminal.underlined
annToAnsiStyle Operator = Terminal.bold <> Terminal.colorDull Terminal.Green
-- | This type determines whether to render code as `ASCII` or `Unicode`
data CharacterSet = ASCII | Unicode
deriving (Eq, Ord, Show, Data, Generic, Lift, NFData)
-- | Since ASCII is a subset of Unicode, if either argument is Unicode, the
-- result is Unicode
instance Semigroup CharacterSet where
Unicode <> _ = Unicode
_ <> other = other
instance Monoid CharacterSet where
mempty = ASCII
instance FromJSON CharacterSet where
parseJSON (String "unicode") = pure Unicode
parseJSON (String "ascii") = pure ASCII
parseJSON v@(String _) = unexpected v
parseJSON v = typeMismatch "String" v
-- | Detect which character set is used for the syntax of an expression
-- If any parts of the expression uses the Unicode syntax, the whole expression
-- is deemed to be using the Unicode syntax.
detectCharacterSet :: Expr Src a -> CharacterSet
detectCharacterSet = foldOf (cosmosOf subExpressions . to exprToCharacterSet)
where
exprToCharacterSet = \case
Embed _ -> mempty -- Don't go down the embed route, otherwise: <<loop>>
Lam (Just Unicode) _ _ -> Unicode
Pi (Just Unicode) _ _ _ -> Unicode
Combine (Just Unicode) _ _ _ -> Unicode
CombineTypes (Just Unicode) _ _ -> Unicode
Prefer (Just Unicode) _ _ _ -> Unicode
Equivalent (Just Unicode) _ _ -> Unicode
_ -> mempty
-- | Pretty print an expression
prettyExpr :: Pretty a => Expr s a -> Doc Ann
prettyExpr = prettySrcExpr . denote
prettySrcExpr :: Pretty a => Expr Src a -> Doc Ann
prettySrcExpr = prettyCharacterSet Unicode
{-| Internal utility for pretty-printing, used when generating element lists
to supply to `enclose` or `enclose'`. This utility indicates that the
compact represent is the same as the multi-line representation for each
element
-}
duplicate :: a -> (a, a)
duplicate x = (x, x)
isWhitespace :: Char -> Bool
isWhitespace c =
case c of
' ' -> True
'\n' -> True
'\t' -> True
'\r' -> True
_ -> False
{-| Used to render inline `Src` spans preserved by the syntax tree
>>> let unusedSourcePos = Text.Megaparsec.SourcePos "" (Text.Megaparsec.mkPos 1) (Text.Megaparsec.mkPos 1)
>>> let nonEmptySrc = Src unusedSourcePos unusedSourcePos "-- Documentation for x\n"
>>> "let" <> " " <> renderSrc id (Just nonEmptySrc) <> "x = 1 in x"
let -- Documentation for x
x = 1 in x
>>> let emptySrc = Src unusedSourcePos unusedSourcePos " "
>>> "let" <> " " <> renderSrc id (Just emptySrc) <> "x = 1 in x"
let x = 1 in x
>>> "let" <> " " <> renderSrc id Nothing <> "x = 1 in x"
let x = 1 in x
-}
renderSrc
:: (Text -> Text)
-- ^ Used to preprocess the comment string (e.g. to strip whitespace)
-> Maybe Src
-- ^ Source span to render (if present)
-> Doc Ann
renderSrc strip (Just (Src {..}))
| not (Text.all isWhitespace srcText) =
renderComment (strip srcText)
renderSrc _ _ =
mempty
{-| Render a comment.
Any preprocessing, such as whitespace stripping, needs to be handled by the
caller, see e.g. 'renderSrc'.
See the documentation for 'renderSrc' for examples.
-}
renderComment :: Text -> Doc Ann
renderComment text =
Pretty.align (Pretty.concatWith f newLines <> suffix)
where
horizontalSpace c = c == ' ' || c == '\t'
suffix =
if Text.null text || Text.last text == '\n'
then mempty
else " "
oldLines = Text.splitOn "\n" text
spacePrefix = Text.takeWhile horizontalSpace
commonPrefix a b = case Text.commonPrefixes a b of
Nothing -> ""
Just (c, _, _) -> c
sharedSpacePrefix [] = ""
sharedSpacePrefix (l : ls) = foldl' commonPrefix (spacePrefix l) ls
blank = Text.all horizontalSpace
newLines =
case oldLines of
[] ->
[]
l0 : ls ->
let sharedPrefix =
sharedSpacePrefix (filter (not . blank) ls)
perLine l =
case Text.stripPrefix sharedPrefix l of
Nothing -> Pretty.pretty l
Just l' -> Pretty.pretty l'
in Pretty.pretty l0 : map perLine ls
f x y = x <> Pretty.hardline <> y
{-| This is a variant of 'renderSrc' with the following differences:
* The 'srcText' is stripped of all whitespace at the start and the end.
* When the stripped 'srcText' is empty, the result is 'Nothing'.
-}
renderSrcMaybe :: Maybe Src -> Maybe (Doc Ann)
renderSrcMaybe (Just Src{..}) =
case Text.dropAround isWhitespace srcText of
"" -> Nothing
t -> Just (renderComment t)
renderSrcMaybe _ = Nothing
{-| @
'containsComment' mSrc ≡ 'Data.Maybe.isJust' ('renderSrcMaybe' mSrc)
@
-}
containsComment :: Maybe Src -> Bool
containsComment Nothing = False
containsComment (Just Src{..}) = not (Text.all isWhitespace srcText)
-- Annotation helpers
keyword, syntax, label, literal, builtin, operator :: Doc Ann -> Doc Ann
keyword = Pretty.annotate Keyword
syntax = Pretty.annotate Syntax
label = Pretty.annotate Label
literal = Pretty.annotate Literal
builtin = Pretty.annotate Builtin
operator = Pretty.annotate Operator
comma, lbracket, rbracket, langle, rangle, lbrace, rbrace, lparen, rparen, pipe, dollar, colon, equals, dot :: Doc Ann
comma = syntax Pretty.comma
lbracket = syntax Pretty.lbracket
rbracket = syntax Pretty.rbracket
langle = syntax Pretty.langle
rangle = syntax Pretty.rangle
lbrace = syntax Pretty.lbrace
rbrace = syntax Pretty.rbrace
lparen = syntax Pretty.lparen
rparen = syntax Pretty.rparen
pipe = syntax Pretty.pipe
dollar = syntax "$"
colon = syntax ":"
equals = syntax "="
dot = syntax "."
lambda :: CharacterSet -> Doc Ann
lambda Unicode = syntax "λ"
lambda ASCII = syntax "\\"
forall_ :: CharacterSet -> Doc Ann
forall_ Unicode = syntax "∀"
forall_ ASCII = syntax "forall "
rarrow :: CharacterSet -> Doc Ann
rarrow Unicode = syntax "→"
rarrow ASCII = syntax "->"
doubleColon :: Doc Ann
doubleColon = syntax "::"
-- | Pretty-print a list
list :: [Doc Ann] -> Doc Ann
list [] = lbracket <> rbracket
list docs =
enclose
(lbracket <> space)
(lbracket <> space)
(comma <> space)
(comma <> space)
(space <> rbracket)
rbracket
(fmap duplicate docs)
-- | Pretty-print union types and literals
angles :: [(Doc Ann, Doc Ann)] -> Doc Ann
angles [] = langle <> rangle
angles docs =
enclose
(langle <> space)
(langle <> space)
(space <> pipe <> space)
(pipe <> space)
(space <> rangle)
rangle
docs
-- | Pretty-print record types and literals
braces :: [(Doc Ann, Doc Ann)] -> Doc Ann
braces [] = lbrace <> rbrace
braces docs =
enclose
(lbrace <> space)
(lbrace <> space)
(comma <> space)
(comma <> space)
(space <> rbrace)
rbrace
docs
hangingBraces :: Int -> [(Doc Ann, Doc Ann)] -> Doc Ann
hangingBraces _ [] =
lbrace <> rbrace
hangingBraces n docs =
Pretty.group
(Pretty.flatAlt
( lbrace
<> Pretty.hardline
<> Pretty.indent n
( mconcat (map (combineLong separator) docsLong)
<> rbrace
)
)
(mconcat (zipWith (<>) (beginShort : repeat separator) docsShort) <> space <> rbrace)
)
where
separator = comma <> space
docsShort = fmap fst docs
docsLong = fmap snd docs
beginShort = lbrace <> space
combineLong x y = x <> y <> Pretty.hardline
unsnoc :: [a] -> Maybe ([a], a)
unsnoc [] = Nothing
unsnoc (x0 : xs0) = Just (go id x0 xs0)
where
go diffXs x [] = (diffXs [], x)
go diffXs x (y : ys) = go (diffXs . (x:)) y ys
-- | Pretty-print anonymous functions and function types
arrows :: CharacterSet -> [ Doc Ann ] -> Doc Ann
arrows characterSet docs = Pretty.group (Pretty.flatAlt long short)
where
long = Pretty.align (mconcat (List.intersperse Pretty.hardline docs'))
where
docs' = case unsnoc docs of
Nothing -> docs
Just (init_, last_) -> init' ++ [ last' ]
where
appendArrow doc = doc <> space <> rarrow characterSet
init' = map appendArrow init_
last' = space <> space <> last_
short = mconcat (List.intersperse separator docs)
where
separator = space <> rarrow characterSet <> space
combine :: CharacterSet -> Text
combine ASCII = "/\\"
combine Unicode = "∧"
combineTypes :: CharacterSet -> Text
combineTypes ASCII = "//\\\\"
combineTypes Unicode = "⩓"
prefer :: CharacterSet -> Text
prefer ASCII = "//"
prefer Unicode = "⫽"
equivalent :: CharacterSet -> Text
equivalent ASCII = "==="
equivalent Unicode = "≡"
{-| Format an expression that holds a variable number of elements, such as a
list, record, or union
-}
enclose
:: Doc ann
-- ^ Beginning document for compact representation
-> Doc ann
-- ^ Beginning document for multi-line representation
-> Doc ann
-- ^ Separator for compact representation
-> Doc ann
-- ^ Separator for multi-line representation
-> Doc ann
-- ^ Ending document for compact representation
-> Doc ann
-- ^ Ending document for multi-line representation
-> [(Doc ann, Doc ann)]
-- ^ Elements to format, each of which is a pair: @(compact, multi-line)@
-> Doc ann
enclose beginShort _ _ _ endShort _ [] =
beginShort <> endShort
enclose beginShort beginLong sepShort sepLong endShort endLong docs =
Pretty.group
(Pretty.flatAlt
(Pretty.align
(mconcat (zipWith combineLong (beginLong : repeat sepLong) docsLong) <> endLong)
)
(mconcat (zipWith combineShort (beginShort : repeat sepShort) docsShort) <> endShort)
)
where
docsShort = fmap fst docs
docsLong = fmap snd docs
combineLong x y = x <> y <> Pretty.hardline
combineShort x y = x <> y
{-| Format an expression that holds a variable number of elements without a
trailing document such as nested @let@, nested lambdas, or nested @forall@s
-}
enclose'
:: Doc ann
-- ^ Beginning document for compact representation
-> Doc ann
-- ^ Beginning document for multi-line representation
-> Doc ann
-- ^ Separator for compact representation
-> Doc ann
-- ^ Separator for multi-line representation
-> [(Doc ann, Doc ann)]
-- ^ Elements to format, each of which is a pair: @(compact, multi-line)@
-> Doc ann
enclose' beginShort beginLong sepShort sepLong docs =
Pretty.group (Pretty.flatAlt long short)
where
longLines = zipWith (<>) (beginLong : repeat sepLong) docsLong
long =
Pretty.align (mconcat (List.intersperse Pretty.hardline longLines))
short = mconcat (zipWith (<>) (beginShort : repeat sepShort) docsShort)
docsShort = fmap fst docs
docsLong = fmap snd docs
alpha :: Char -> Bool
alpha c = ('\x41' <= c && c <= '\x5A') || ('\x61' <= c && c <= '\x7A')
digit :: Char -> Bool
digit c = '\x30' <= c && c <= '\x39'
alphaNum :: Char -> Bool
alphaNum c = alpha c || digit c
headCharacter :: Char -> Bool
headCharacter c = alpha c || c == '_'
tailCharacter :: Char -> Bool
tailCharacter c = alphaNum c || c == '_' || c == '-' || c == '/'
-- | The set of labels which do not need to be escaped
data UnescapedLabel
= NonReservedLabel
-- ^ This corresponds to the `nonreserved-label` rule in the grammar
| AnyLabel
-- ^ This corresponds to the `any-label` rule in the grammar
| AnyLabelOrSome
-- ^ This corresponds to the `any-label-or-some` rule in the grammar
-- | Escape a label if it is not valid when unquoted
escapeLabel :: UnescapedLabel -> Text -> Text
escapeLabel allowedLabel l =
case Text.uncons l of
Just (h, t)
| headCharacter h && Text.all tailCharacter t && allowed && l /= "?"
-> l
_ -> "`" <> l <> "`"
where
allowed = case allowedLabel of
NonReservedLabel -> notReservedIdentifier
AnyLabel -> notReservedKeyword
AnyLabelOrSome -> notReservedKeyword || l == "Some"
notReservedIdentifier = not (Data.HashSet.member l reservedIdentifiers)
notReservedKeyword = not (Data.HashSet.member l reservedKeywords)
prettyLabelShared :: UnescapedLabel -> Text -> Doc Ann
prettyLabelShared b l = label (Pretty.pretty (escapeLabel b l))
prettyLabel :: Text -> Doc Ann
prettyLabel = prettyLabelShared NonReservedLabel
prettyAnyLabel :: Text -> Doc Ann
prettyAnyLabel = prettyLabelShared AnyLabel
prettyAnyLabelOrSome :: Text -> Doc Ann
prettyAnyLabelOrSome = prettyLabelShared AnyLabelOrSome
prettyKeys
:: Foldable list
=> (key -> Doc Ann)
-> list (Maybe Src, key, Maybe Src)
-> Doc Ann
prettyKeys prettyK keys = Pretty.group (Pretty.flatAlt long short)
where
short = (mconcat . Pretty.punctuate dot . map prettyKey . toList) keys
long =
case map prettyKey (toList keys) of
[] -> mempty
[doc] -> doc
doc:docs ->
Pretty.align
. mconcat
. Pretty.punctuate (Pretty.hardline <> ". ")
$ Pretty.indent 2 doc : docs
prettyKey (mSrc0, key, mSrc1) =
Pretty.align
. mconcat
. Pretty.punctuate Pretty.hardline
. Data.Maybe.catMaybes
$ [ renderSrcMaybe mSrc0
, Just (prettyK key)
, renderSrcMaybe mSrc1
]
prettyLabels :: [Text] -> Doc Ann
prettyLabels a
| null a = lbrace <> rbrace
| otherwise = braces (map (duplicate . prettyAnyLabelOrSome) a)
prettyNumber :: Integer -> Doc Ann
prettyNumber = literal . Pretty.pretty
prettyInt :: Int -> Doc Ann
prettyInt = literal . Pretty.pretty
prettyNatural :: Natural -> Doc Ann
prettyNatural = literal . Pretty.pretty
prettyDouble :: Double -> Doc Ann
prettyDouble = literal . Pretty.pretty
prettyConst :: Const -> Doc Ann
prettyConst Type = builtin "Type"
prettyConst Kind = builtin "Kind"
prettyConst Sort = builtin "Sort"
prettyVar :: Var -> Doc Ann
prettyVar (V x 0) = label (Pretty.unAnnotate (prettyLabel x))
prettyVar (V x n) = label (Pretty.unAnnotate (prettyLabel x <> "@" <> prettyInt n))
prettyEnvironmentVariable :: Text -> Doc ann
prettyEnvironmentVariable t = Pretty.pretty (escapeEnvironmentVariable t)
preserveSource :: Expr Src a -> Maybe (Doc Ann)
preserveSource (Note Src{..} (DoubleLit {})) = Just (Pretty.pretty srcText)
preserveSource (Note Src{..} (IntegerLit {})) = Just (Pretty.pretty srcText)
preserveSource (Note Src{..} (NaturalLit {})) = Just (Pretty.pretty srcText)
preserveSource _ = Nothing
-- | Escape an environment variable if not a valid Bash environment variable
escapeEnvironmentVariable :: Text -> Text
escapeEnvironmentVariable t
| validBashEnvVar t = t
| otherwise = "\"" <> escapeText_ t <> "\""
where
validBashEnvVar v = case Text.uncons v of
Nothing -> False
Just (c, v') ->
(alpha c || c == '_')
&& Text.all (\c' -> alphaNum c' || c' == '_') v'
{- There is a close correspondence between the pretty-printers in 'prettyCharacterSet'
and the sub-parsers in 'Dhall.Parser.Expression.parsers'. Most pretty-printers are
named after the corresponding parser and the relationship between pretty-printers
exactly matches the relationship between parsers. This leads to the nice emergent
property of automatically getting all the parentheses and precedences right.
This approach has one major disadvantage: you can get an infinite loop if
you add a new constructor to the syntax tree without adding a matching
case the corresponding builder.
-}
{-| Pretty-print an 'Expr' using the given 'CharacterSet'.
'prettyCharacterSet' largely ignores 'Note's. 'Note's do however matter for
the layout of let-blocks:
>>> let inner = Let (Binding Nothing "x" Nothing Nothing Nothing (NaturalLit 1)) (Var (V "x" 0)) :: Expr Src ()
>>> prettyCharacterSet ASCII (Let (Binding Nothing "y" Nothing Nothing Nothing (NaturalLit 2)) inner)
let y = 2 let x = 1 in x
>>> prettyCharacterSet ASCII (Let (Binding Nothing "y" Nothing Nothing Nothing (NaturalLit 2)) (Note (Src unusedSourcePos unusedSourcePos "") inner))
let y = 2 in let x = 1 in x
This means the structure of parsed let-blocks is preserved.
-}
prettyCharacterSet :: Pretty a => CharacterSet -> Expr Src a -> Doc Ann
prettyCharacterSet characterSet = prettyCompleteExpression
where
PrettyPrinters{..} = prettyPrinters characterSet
-- Mainly used by the `Pretty` instance for `Import`
prettyImportExpression :: Pretty a => Expr Src a -> Doc Ann
prettyImportExpression = prettyImportExpression_
where
PrettyPrinters{..} = prettyPrinters Unicode
data PrettyPrinters a = PrettyPrinters
{ prettyCompleteExpression :: Expr Src a -> Doc Ann
, prettyImportExpression_ :: Expr Src a -> Doc Ann
}
prettyPrinters :: Pretty a => CharacterSet -> PrettyPrinters a
prettyPrinters characterSet =
PrettyPrinters{..}
where
prettyCompleteExpression expression =
Pretty.group (prettyExpression expression)
prettyExpression a0@(Lam _ _ _) =
arrows characterSet (docs a0)
where
docs (Lam _ (FunctionBinding { functionBindingVariable = a, functionBindingAnnotation = b }) c) =
Pretty.group (Pretty.flatAlt long short) : docs c
where
long = (lambda characterSet <> space)
<> Pretty.align
( (lparen <> space)
<> prettyLabel a
<> Pretty.hardline
<> (colon <> space)
<> prettyExpression b
<> Pretty.hardline
<> rparen
)
short = (lambda characterSet <> lparen)
<> prettyLabel a
<> (space <> colon <> space)
<> prettyExpression b
<> rparen
docs c
| Just doc <- preserveSource c =
[ doc ]
| Note _ d <- c =
docs d
| otherwise =
[ prettyExpression c ]
prettyExpression a0@(BoolIf _ _ _) =
Pretty.group (Pretty.flatAlt long short)
where
prefixesLong =
""
: cycle
[ keyword "then" <> " "
, keyword "else" <> " "
]
prefixesShort =
""
: cycle
[ space <> keyword "then" <> space
, space <> keyword "else" <> space
]
longLines = zipWith (<>) prefixesLong (docsLong True a0)
long =
Pretty.align (mconcat (List.intersperse Pretty.hardline longLines))
short = mconcat (zipWith (<>) prefixesShort (docsShort a0))
docsLong initial (BoolIf a b c) =
docLong ++ docsLong False c
where
padding
| initial = " "
| otherwise = mempty
docLong =
[ keyword "if" <> padding <> " " <> prettyExpression a
, prettyExpression b
]
docsLong initial c
| Just doc <- preserveSource c =
[ doc ]
| Note _ d <- c =
docsLong initial d
| otherwise =
[ prettyExpression c ]
docsShort (BoolIf a b c) =
docShort ++ docsShort c
where
docShort =
[ keyword "if" <> " " <> prettyExpression a
, prettyExpression b
]
docsShort c
| Just doc <- preserveSource c =
[ doc ]
| Note _ d <- c =
docsShort d
| otherwise =
[ prettyExpression c ]
prettyExpression (Let a0 b0) =
enclose' "" "" space Pretty.hardline
(fmap (duplicate . docA) (toList as) ++ [ docB ])
where
MultiLet as b = multiLet a0 b0
isSpace c = c == ' ' || c == '\t'
stripSpaces =
Text.dropAround isSpace
. Text.intercalate "\n"
. map (Text.dropWhileEnd isSpace)
. Text.splitOn "\n"
-- Strip a single newline character. Needed to ensure idempotency in
-- cases where we add hard line breaks.
stripNewline t =
case Text.uncons t' of
Just ('\n', t'') -> stripSpaces t''
_ -> t'
where t' = stripSpaces t
docA (Binding src0 c src1 Nothing src2 e) =
Pretty.group (Pretty.flatAlt long short)
where
long = keyword "let" <> space
<> Pretty.align
( renderSrc stripSpaces src0
<> prettyLabel c <> space <> renderSrc stripSpaces src1
<> equals <> Pretty.hardline <> renderSrc stripNewline src2
<> " " <> prettyExpression e
)
short = keyword "let" <> space <> renderSrc stripSpaces src0
<> prettyLabel c <> space <> renderSrc stripSpaces src1
<> equals <> space <> renderSrc stripSpaces src2
<> prettyExpression e
docA (Binding src0 c src1 (Just (src3, d)) src2 e) =
keyword "let" <> space
<> Pretty.align
( renderSrc stripSpaces src0
<> prettyLabel c <> Pretty.hardline <> renderSrc stripNewline src1
<> colon <> space <> renderSrc stripSpaces src3 <> prettyExpression d <> Pretty.hardline
<> equals <> space <> renderSrc stripSpaces src2
<> prettyExpression e
)
docB =
( keyword "in" <> " " <> prettyExpression b
, keyword "in" <> " " <> prettyExpression b
)
prettyExpression a0@(Pi _ _ _ _) =
arrows characterSet (docs a0)
where
docs (Pi _ "_" b c) = prettyOperatorExpression b : docs c
docs (Pi _ a b c) = Pretty.group (Pretty.flatAlt long short) : docs c
where
long = forall_ characterSet <> space
<> Pretty.align
( lparen <> space
<> prettyLabel a
<> Pretty.hardline
<> colon <> space
<> prettyExpression b
<> Pretty.hardline
<> rparen
)
short = forall_ characterSet <> lparen
<> prettyLabel a
<> space <> colon <> space
<> prettyExpression b
<> rparen
docs c
| Just doc <- preserveSource c =
[ doc ]
| Note _ d <- c =
docs d
| otherwise =
[ prettyExpression c ]
prettyExpression (With (Dhall.Syntax.shallowDenote -> a) b c) =
case a of
With{} ->
-- Don't parenthesize an inner with-expression
prettyExpression a
_ ->
prettyImportExpression_ a
<> Pretty.flatAlt long short
where
short = " " <> keyword "with" <> " " <> update
long = Pretty.hardline
<> " "
<> Pretty.align (keyword "with" <> " " <> update)
(update, _) =
prettyKeyValue prettyKey prettyOperatorExpression equals
(makeKeyValue b c)
prettyKey (WithLabel text) = prettyAnyLabelOrSome text
prettyKey WithQuestion = syntax "?"
prettyExpression (Assert a) =
Pretty.group (Pretty.flatAlt long short)
where
short = keyword "assert" <> " " <> colon <> " " <> prettyExpression a
long =
Pretty.align
( " " <> keyword "assert"
<> Pretty.hardline <> colon <> " " <> prettyExpression a
)
prettyExpression a
| Just doc <- preserveSource a =
doc
| Note _ b <- a =
prettyExpression b
| otherwise =
prettyAnnotatedExpression a
prettyAnnotatedExpression :: Pretty a => Expr Src a -> Doc Ann
prettyAnnotatedExpression (Merge a b (Just c)) =
Pretty.group (Pretty.flatAlt long short)
where
long =
Pretty.align
( keyword "merge"
<> Pretty.hardline
<> Pretty.indent 2 (prettyImportExpression_ a)
<> Pretty.hardline
<> Pretty.indent 2 (prettyImportExpression_ b)
<> Pretty.hardline
<> colon <> space
<> prettyExpression c
)
short = keyword "merge" <> space
<> prettyImportExpression_ a
<> " "
<> prettyImportExpression_ b
<> space <> colon <> space
<> prettyExpression c
prettyAnnotatedExpression (ToMap a (Just b)) =
Pretty.group (Pretty.flatAlt long short)
where
long =
Pretty.align
( keyword "toMap"
<> Pretty.hardline
<> Pretty.indent 2 (prettyImportExpression_ a)
<> Pretty.hardline
<> colon <> space
<> prettyExpression b
)
short = keyword "toMap" <> space
<> prettyImportExpression_ a
<> space <> colon <> space
<> prettyExpression b
prettyAnnotatedExpression a0@(Annot _ _) =
enclose'
""
" "
(" " <> colon <> " ")
(colon <> space)
(fmap duplicate (docs a0))
where
docs (Annot a b) = prettyOperatorExpression a : docs b
docs a
| Just doc <- preserveSource a =
[ doc ]
| Note _ b <- a =
docs b
| otherwise =
[ prettyExpression a ]
prettyAnnotatedExpression (ListLit (Just a) b) =
list (map prettyExpression (Data.Foldable.toList b))
<> " : "
<> prettyExpression a
prettyAnnotatedExpression a
| Just doc <- preserveSource a =
doc
| Note _ b <- a =
prettyAnnotatedExpression b
| otherwise =
prettyOperatorExpression a
prettyOperatorExpression :: Pretty a => Expr Src a -> Doc Ann
prettyOperatorExpression = prettyEquivalentExpression
prettyOperator :: Text -> [Doc Ann] -> Doc Ann
prettyOperator op docs =
enclose'
""
prefix
(" " <> operator (Pretty.pretty op) <> " ")
(operator (Pretty.pretty op) <> spacer)
(reverse (fmap duplicate docs))
where
prefix = if Text.length op == 1 then " " else " "
spacer = if Text.length op == 1 then " " else " "
prettyEquivalentExpression :: Pretty a => Expr Src a -> Doc Ann
prettyEquivalentExpression a0@(Equivalent _ _ _) =
prettyOperator (equivalent characterSet) (docs a0)
where
docs (Equivalent _ a b) = prettyImportAltExpression b : docs a
docs a
| Just doc <- preserveSource a =
[ doc ]
| Note _ b <- a =
docs b
| otherwise =
[ prettyImportAltExpression a ]
prettyEquivalentExpression a
| Just doc <- preserveSource a =
doc
| Note _ b <- a =
prettyEquivalentExpression b
| otherwise =
prettyImportAltExpression a
prettyImportAltExpression :: Pretty a => Expr Src a -> Doc Ann
prettyImportAltExpression a0@(ImportAlt _ _) =
prettyOperator "?" (docs a0)
where
docs (ImportAlt a b) = prettyOrExpression b : docs a
docs a
| Just doc <- preserveSource a =
[ doc ]
| Note _ b <- a =
docs b