-
Notifications
You must be signed in to change notification settings - Fork 148
Expand file tree
/
Copy pathBox.hs
More file actions
2429 lines (2050 loc) · 87.9 KB
/
Copy pathBox.hs
File metadata and controls
2429 lines (2050 loc) · 87.9 KB
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
{-# OPTIONS_GHC -Wall #-}
module ElmFormat.Render.Box where
import Elm.Utils ((|>))
import Box
import ElmVersion (ElmVersion(..))
import qualified AST.V0_16 as AST
import AST.V0_16 (UppercaseIdentifier(..), LowercaseIdentifier(..), SymbolIdentifier(..), WithEol)
import AST.Declaration (TopLevelStructure, Declaration)
import qualified AST.Declaration
import qualified AST.Expression
import qualified AST.Module
import qualified AST.Pattern
import qualified AST.Variable
import qualified Cheapskate.Types as Markdown
import qualified Control.Monad as Monad
import qualified Data.Char as Char
import qualified Data.Foldable as Foldable
import qualified Data.List as List
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe, maybeToList)
import qualified Data.Maybe as Maybe
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as Text
import qualified ElmFormat.Render.ElmStructure as ElmStructure
import qualified ElmFormat.Render.Markdown
import qualified ElmFormat.Upgrade_0_19 as Upgrade_0_19
import qualified ElmFormat.Version
import qualified ElmVersion
import qualified Parse.Parse as Parse
import qualified Reporting.Annotation as RA
import qualified Reporting.Region as Region
import qualified Reporting.Result as Result
import qualified ReversedList
import ReversedList (Reversed)
import Text.Printf (printf)
import Util.List
pleaseReport'' :: String -> String -> String
pleaseReport'' what details =
"<elm-format-" ++ ElmFormat.Version.asString ++ ": "++ what ++ ": " ++ details ++ " -- please report this at https://github.com/avh4/elm-format/issues >"
pleaseReport' :: String -> String -> Line
pleaseReport' what details =
keyword $ pleaseReport'' what details
pleaseReport :: String -> String -> Box
pleaseReport what details =
line $ pleaseReport' what details
surround :: Char -> Char -> Box -> Box
surround left right b =
let
left' = punc (left : [])
right' = punc (right : [])
in
case b of
SingleLine b' ->
line $ row [ left', b', right' ]
_ ->
stack1
[ b
|> prefix left'
, line $ right'
]
parens :: Box -> Box
parens = surround '(' ')'
formatBinary :: Bool -> Box -> [ ( Bool, AST.Comments, Box, Box ) ] -> Box
formatBinary multiline left ops =
case ops of
[] ->
left
( isLeftPipe, comments, op, next ) : rest ->
if isLeftPipe then
ElmStructure.forceableSpaceSepOrIndented multiline
(ElmStructure.spaceSepOrStack left $
concat
[ Maybe.maybeToList $ formatComments comments
, [op]
]
)
[formatBinary multiline next rest]
else
formatBinary
multiline
(ElmStructure.forceableSpaceSepOrIndented multiline left [formatCommented' comments id $ ElmStructure.spaceSepOrPrefix op next])
rest
splitWhere :: (a -> Bool) -> [a] -> [[a]]
splitWhere predicate list =
let
merge acc result =
ReversedList.push (ReversedList.toList acc) result
step (acc,result) next =
if predicate next then
(ReversedList.empty, merge (ReversedList.push next acc) result)
else
(ReversedList.push next acc, result)
in
list
|> foldl step (ReversedList.empty, ReversedList.empty)
|> uncurry merge
|> ReversedList.toList
|> dropWhile null
data DeclarationType
= DComment
| DStarter
| DCloser
| DDefinition (Maybe AST.Variable.Ref)
| DFixity
| DDocComment
deriving (Show)
declarationType :: (a -> BodyEntryType) -> TopLevelStructure a -> DeclarationType
declarationType entryType decl =
case decl of
AST.Declaration.Entry entry ->
case entryType $ RA.drop entry of
BodyNamed name -> DDefinition (Just name)
BodyUnnamed -> DDefinition Nothing
BodyFixity -> DFixity
AST.Declaration.DocComment _ ->
DDocComment
AST.Declaration.BodyComment AST.CommentTrickOpener ->
DStarter
AST.Declaration.BodyComment AST.CommentTrickCloser ->
DCloser
AST.Declaration.BodyComment _ ->
DComment
removeDuplicates :: Ord a => [[a]] -> [[a]]
removeDuplicates input =
foldl step (ReversedList.empty, Set.empty) input |> fst |> ReversedList.toList
where
step :: Ord a => (Reversed [a], Set a) -> [a] -> (Reversed [a], Set a)
step (acc, seen) next =
case foldl stepChildren (ReversedList.empty, seen) next |> (\(a,b) -> (ReversedList.toList a, b)) of
([], seen') -> (acc, seen')
(children', seen') -> (ReversedList.push children' acc, seen')
stepChildren :: Ord a => (Reversed a, Set a) -> a -> (Reversed a, Set a)
stepChildren (acc, seen) next =
if Set.member next seen
then (acc, seen)
else (ReversedList.push next acc, Set.insert next seen)
sortVars :: Bool -> Set (AST.Commented AST.Variable.Value) -> [[String]] -> ([[AST.Commented AST.Variable.Value]], AST.Comments)
sortVars forceMultiline fromExposing fromDocs =
let
varOrder :: AST.Commented AST.Variable.Value -> (Int, String)
varOrder (AST.Commented _ (AST.Variable.OpValue (SymbolIdentifier name)) _) = (1, name)
varOrder (AST.Commented _ (AST.Variable.Union (UppercaseIdentifier name, _) _) _) = (2, name)
varOrder (AST.Commented _ (AST.Variable.Value (LowercaseIdentifier name)) _) = (3, name)
listedInDocs =
fromDocs
|> fmap (Maybe.mapMaybe (\v -> Map.lookup v allowedInDocs))
|> filter (not . List.null)
|> fmap (fmap (\v -> AST.Commented [] v []))
|> removeDuplicates
listedInExposing =
fromExposing
|> Set.toList
|> List.sortOn varOrder
varName (AST.Commented _ (AST.Variable.Value (LowercaseIdentifier name)) _) = name
varName (AST.Commented _ (AST.Variable.OpValue (SymbolIdentifier name)) _) = name
varName (AST.Commented _ (AST.Variable.Union (UppercaseIdentifier name, _) _) _) = name
varSetToMap set =
Set.toList set
|> fmap (\(AST.Commented pre var post)-> (varName (AST.Commented pre var post), var))
|> Map.fromList
allowedInDocs =
varSetToMap fromExposing
allFromDocs =
Set.fromList $ fmap varName $ concat listedInDocs
inDocs x =
Set.member (varName x) allFromDocs
remainingFromExposing =
listedInExposing
|> filter (not . inDocs)
commentsFromReorderedVars =
listedInExposing
|> filter inDocs
|> fmap (\(AST.Commented pre _ post) -> pre ++ post)
|> concat
in
if List.null listedInDocs && forceMultiline
then ( fmap (\x -> [x]) remainingFromExposing, commentsFromReorderedVars )
else ( listedInDocs ++ if List.null remainingFromExposing then [] else [ remainingFromExposing ], commentsFromReorderedVars )
formatModuleHeader :: ElmVersion -> Bool -> AST.Module.Module -> [Box]
formatModuleHeader elmVersion addDefaultHeader modu =
let
maybeHeader =
if addDefaultHeader
then Just (AST.Module.header modu |> Maybe.fromMaybe AST.Module.defaultHeader)
else AST.Module.header modu
refName (AST.Variable.VarRef _ (LowercaseIdentifier name)) = name
refName (AST.Variable.TagRef _ (UppercaseIdentifier name)) = name
refName (AST.Variable.OpRef (SymbolIdentifier name)) = name
varName (AST.Commented _ (AST.Variable.Value (LowercaseIdentifier name)) _) = name
varName (AST.Commented _ (AST.Variable.OpValue (SymbolIdentifier name)) _) = name
varName (AST.Commented _ (AST.Variable.Union (UppercaseIdentifier name, _) _) _) = name
documentedVars :: [[String]]
documentedVars =
AST.Module.docs modu
|> RA.drop
|> fmap Foldable.toList
|> Maybe.fromMaybe []
|> concatMap extractDocs
documentedVarsSet :: Set String
documentedVarsSet = Set.fromList $ concat documentedVars
extractDocs block =
case block of
Markdown.ElmDocs vars ->
fmap (fmap (refName . textToRef)) vars
_ -> []
textToRef :: Text -> AST.Variable.Ref
textToRef text =
case Text.unpack text of
s@(c:_) | Char.isUpper c -> AST.Variable.TagRef [] (UppercaseIdentifier s)
s@(c:_) | Char.isLower c -> AST.Variable.VarRef [] (LowercaseIdentifier s)
'(':a:')':[] -> AST.Variable.OpRef (SymbolIdentifier $ a:[])
'(':a:b:')':[] -> AST.Variable.OpRef (SymbolIdentifier $ a:b:[])
s -> AST.Variable.VarRef [] (LowercaseIdentifier s)
definedVars :: Set (AST.Commented AST.Variable.Value)
definedVars =
AST.Module.body modu
|> concatMap extractVarName
|> fmap (\x -> AST.Commented [] x [])
|> Set.fromList
exportsList =
case
AST.Module.exports (maybeHeader |> Maybe.fromMaybe AST.Module.defaultHeader)
of
Just (AST.KeywordCommented _ _ e) -> e
Nothing -> AST.Variable.ClosedListing
detailedListingToSet :: AST.Variable.Listing AST.Module.DetailedListing -> Set (AST.Commented AST.Variable.Value)
detailedListingToSet (AST.Variable.OpenListing _) = Set.empty
detailedListingToSet AST.Variable.ClosedListing = Set.empty
detailedListingToSet (AST.Variable.ExplicitListing (AST.Module.DetailedListing values operators types) _) =
Set.unions
[ Map.assocs values |> fmap (\(name, AST.Commented pre () post) -> AST.Commented pre (AST.Variable.Value name) post) |> Set.fromList
, Map.assocs operators |> fmap (\(name, AST.Commented pre () post) -> AST.Commented pre (AST.Variable.OpValue name) post) |> Set.fromList
, Map.assocs types |> fmap (\(name, AST.Commented pre (preListing, listing) post) -> AST.Commented pre (AST.Variable.Union (name, preListing) listing) post) |> Set.fromList
]
detailedListingIsMultiline :: AST.Variable.Listing a -> Bool
detailedListingIsMultiline (AST.Variable.ExplicitListing _ isMultiline) = isMultiline
detailedListingIsMultiline _ = False
varsToExpose =
case AST.Module.exports =<< maybeHeader of
Nothing ->
if null $ concat documentedVars
then definedVars
else definedVars |> Set.filter (\v -> Set.member (varName v) documentedVarsSet)
Just (AST.KeywordCommented _ _ e) -> detailedListingToSet e
sortedExports =
sortVars
(detailedListingIsMultiline exportsList)
varsToExpose
documentedVars
extractVarName :: TopLevelStructure Declaration -> [AST.Variable.Value]
extractVarName decl =
case decl of
AST.Declaration.DocComment _ -> []
AST.Declaration.BodyComment _ -> []
AST.Declaration.Entry (RA.A _ (AST.Declaration.PortAnnotation (AST.Commented _ (LowercaseIdentifier name) _) _ _)) -> [ AST.Variable.Value (LowercaseIdentifier name) ]
AST.Declaration.Entry (RA.A _ (AST.Declaration.Definition (RA.A _ (AST.Pattern.VarPattern (LowercaseIdentifier name))) _ _ _)) -> [ AST.Variable.Value (LowercaseIdentifier name) ]
AST.Declaration.Entry (RA.A _ (AST.Declaration.Definition (RA.A _ (AST.Pattern.Record fields)) _ _ _)) -> fmap (\(AST.Commented _ f _) -> AST.Variable.Value f) fields
AST.Declaration.Entry (RA.A _ (AST.Declaration.Datatype (AST.Commented _ (UppercaseIdentifier name, _) _) _)) -> [ AST.Variable.Union (UppercaseIdentifier name, []) (AST.Variable.OpenListing (AST.Commented [] () []))]
AST.Declaration.Entry (RA.A _ (AST.Declaration.TypeAlias _ (AST.Commented _ (UppercaseIdentifier name, _) _) _)) -> [ AST.Variable.Union (UppercaseIdentifier name, []) AST.Variable.ClosedListing ]
AST.Declaration.Entry (RA.A _ _) -> []
formatModuleLine' header@(AST.Module.Header srcTag name moduleSettings exports) =
let
(preExposing, postExposing) =
case exports of
Nothing -> ([], [])
Just (AST.KeywordCommented pre post _) -> (pre, post)
in
case elmVersion of
Elm_0_16 ->
formatModuleLine_0_16 header
Elm_0_17 ->
formatModuleLine elmVersion sortedExports srcTag name moduleSettings preExposing postExposing
Elm_0_18 ->
formatModuleLine elmVersion sortedExports srcTag name moduleSettings preExposing postExposing
Elm_0_18_Upgrade ->
formatModuleLine elmVersion sortedExports srcTag name moduleSettings preExposing postExposing
Elm_0_19 ->
formatModuleLine elmVersion sortedExports srcTag name moduleSettings preExposing postExposing
Elm_0_19_Upgrade ->
formatModuleLine elmVersion sortedExports srcTag name moduleSettings preExposing postExposing
docs =
fmap (formatDocComment elmVersion (makeImportInfo modu)) $ RA.drop $ AST.Module.docs modu
imports =
formatImports elmVersion modu
in
List.intercalate [ blankLine ] $ concat
[ maybeToList $ fmap (return . formatModuleLine') maybeHeader
, maybeToList $ fmap return docs
, if null imports
then []
else [ imports ]
]
formatImports :: ElmVersion -> AST.Module.Module -> [Box]
formatImports elmVersion modu =
let
(comments, imports) =
AST.Module.imports modu
in
[ formatComments comments
|> maybeToList
, imports
|> Map.assocs
|> fmap (\(name, (pre, method)) -> formatImport elmVersion ((pre, name), method))
]
|> List.filter (not . List.null)
|> List.intersperse [blankLine]
|> concat
formatModuleLine_0_16 :: AST.Module.Header -> Box
formatModuleLine_0_16 header =
let
elmVersion = Elm_0_16
exports =
case AST.Module.exports header of
Just (AST.KeywordCommented _ _ value) -> value
Nothing -> AST.Variable.OpenListing (AST.Commented [] () [])
formatExports =
case formatListing (formatDetailedListing elmVersion) exports of
Just listing ->
listing
_ ->
pleaseReport "UNEXPECTED MODULE DECLARATION" "empty listing"
(preWhere, postWhere) =
case AST.Module.exports header of
Nothing -> ([], [])
Just (AST.KeywordCommented pre post _) -> (pre, post)
whereClause =
formatCommented (line . keyword) (AST.Commented preWhere "where" postWhere)
in
case
( formatCommented (line . formatQualifiedUppercaseIdentifier elmVersion) $ AST.Module.name header
, formatExports
, whereClause
)
of
(SingleLine name', SingleLine exports', SingleLine where') ->
line $ row
[ keyword "module"
, space
, name'
, row [ space, exports' ]
, space
, where'
]
(name', exports', _) ->
stack1
[ line $ keyword "module"
, indent $ name'
, indent $ exports'
, indent $ whereClause
]
formatModuleLine ::
ElmVersion
-> ([[AST.Commented AST.Variable.Value]], AST.Comments)
-> AST.Module.SourceTag
-> AST.Commented [UppercaseIdentifier]
-> Maybe (AST.KeywordCommented AST.Module.SourceSettings)
-> AST.Comments
-> AST.Comments
-> Box
formatModuleLine elmVersion (varsToExpose, extraComments) srcTag name moduleSettings preExposing postExposing =
let
tag =
case srcTag of
AST.Module.Normal ->
line $ keyword "module"
AST.Module.Port comments ->
ElmStructure.spaceSepOrIndented
(formatTailCommented (line . keyword) ("port", comments))
[ line $ keyword "module" ]
AST.Module.Effect comments ->
ElmStructure.spaceSepOrIndented
(formatTailCommented (line . keyword) ("effect", comments))
[ line $ keyword "module" ]
exports =
case varsToExpose of
[] -> line $ keyword "(..)"
[oneGroup] ->
oneGroup
|> fmap (formatCommented $ formatVarValue elmVersion)
|> ElmStructure.group' False "(" "," (maybeToList (formatComments extraComments)) ")" False
_ ->
varsToExpose
|> fmap (ElmStructure.group False "" "," "" False . fmap (formatCommented $ formatVarValue elmVersion))
|> ElmStructure.group' False "(" "," (maybeToList (formatComments extraComments)) ")" True
formatSetting (k, v) =
formatRecordPair elmVersion "=" (line . formatUppercaseIdentifier elmVersion) (k, v, False)
formatSettings settings =
map formatSetting settings
|> ElmStructure.group True "{" "," "}" False
whereClause =
moduleSettings
|> fmap (formatKeywordCommented "where" formatSettings)
|> fmap (\x -> [x])
|> Maybe.fromMaybe []
nameClause =
case
( tag
, formatCommented (line . formatQualifiedUppercaseIdentifier elmVersion) name
)
of
(SingleLine tag', SingleLine name') ->
line $ row
[ tag'
, space
, name'
]
(tag', name') ->
stack1
[ tag'
, indent $ name'
]
in
ElmStructure.spaceSepOrIndented
(ElmStructure.spaceSepOrIndented
nameClause
(whereClause ++ [formatCommented (line . keyword) (AST.Commented preExposing "exposing" postExposing)])
)
[ exports ]
formatModule :: ElmVersion -> Bool -> Int -> AST.Module.Module -> Box
formatModule elmVersion addDefaultHeader spacing modu =
let
initialComments' =
case AST.Module.initialComments modu of
[] ->
[]
comments ->
(map formatComment comments)
++ [ blankLine, blankLine ]
spaceBeforeBody =
case AST.Module.body modu of
[] -> 0
AST.Declaration.BodyComment _ : _ -> spacing + 1
_ -> spacing
in
stack1 $
concat
[ initialComments'
, formatModuleHeader elmVersion addDefaultHeader modu
, List.replicate spaceBeforeBody blankLine
, maybeToList $ formatModuleBody spacing elmVersion (makeImportInfo modu) (AST.Module.body modu)
]
data ImportInfo =
ImportInfo
{ _exposed :: Map.Map LowercaseIdentifier [UppercaseIdentifier]
, _aliases :: Map.Map [UppercaseIdentifier] UppercaseIdentifier
}
makeImportInfo :: AST.Module.Module -> ImportInfo
makeImportInfo modu =
let
-- these are things we know will get exposed for certain modules when we see "exposing (..)"
-- only things that are currently useful for Elm 0.19 upgrade are included
knownModuleContents :: Map.Map [UppercaseIdentifier] [LowercaseIdentifier]
knownModuleContents =
Map.fromList $
fmap (\(a,b) -> (fmap UppercaseIdentifier a, fmap LowercaseIdentifier b))
[ (["Html", "Attributes"], ["style"])
]
exposed =
-- currently this only checks for Html.Attributes (needed for Elm 0.19 upgrade)
let
importName = (fmap UppercaseIdentifier ["Html", "Attributes"])
in
case Map.lookup importName (snd $ AST.Module.imports modu) of
Nothing -> mempty
Just (_, importMethod) ->
case AST.Module.exposedVars importMethod of
(_, (_, AST.Variable.OpenListing _)) ->
-- import Html.Attributes [as ...] exposing (..)
Map.lookup importName knownModuleContents
|> Maybe.fromMaybe []
|> fmap (\n -> (n, importName))
|> Map.fromList
(_, (_, AST.Variable.ExplicitListing details _)) ->
-- import Html.Attributes [as ...] exposing (some, stuff)
AST.Module.values details
|> Map.keys
|> fmap (\n -> (n, importName))
|> Map.fromList
_ -> mempty
aliases =
-- currently this only checks for Html.Attributes (needed for Elm 0.19 upgrade)
let
importName = (fmap UppercaseIdentifier ["Html", "Attributes"])
in
case Map.lookup importName (snd $ AST.Module.imports modu) of
Nothing -> mempty
Just (_, importMethod) ->
case AST.Module.alias importMethod of
Just (_, (_, alias)) ->
Map.singleton importName alias
Nothing -> mempty
in
ImportInfo exposed aliases
formatModuleBody :: Int -> ElmVersion -> ImportInfo -> [TopLevelStructure Declaration] -> Maybe Box
formatModuleBody linesBetween elmVersion importInfo body =
let
entryType adecl =
case adecl of
AST.Declaration.Definition pat _ _ _ ->
case RA.drop pat of
AST.Pattern.VarPattern name ->
BodyNamed $ AST.Variable.VarRef [] name
AST.Pattern.OpPattern name ->
BodyNamed $ AST.Variable.OpRef name
_ ->
BodyUnnamed
AST.Declaration.Datatype (AST.Commented _ (name, _) _) _ ->
BodyNamed $ AST.Variable.TagRef [] name
AST.Declaration.TypeAlias _ (AST.Commented _ (name, _) _) _ ->
BodyNamed $ AST.Variable.TagRef [] name
AST.Declaration.PortDefinition (AST.Commented _ name _) _ _ ->
BodyNamed $ AST.Variable.VarRef [] name
AST.Declaration.TypeAnnotation (name, _) _ ->
BodyNamed name
AST.Declaration.PortAnnotation (AST.Commented _ name _) _ _ ->
BodyNamed $ AST.Variable.VarRef [] name
AST.Declaration.Fixity _ _ _ _ _ ->
BodyFixity
AST.Declaration.Fixity_0_19 _ _ _ _ ->
BodyFixity
in
formatTopLevelBody linesBetween elmVersion importInfo entryType (formatDeclaration elmVersion importInfo) body
data BodyEntryType
= BodyNamed AST.Variable.Ref
| BodyUnnamed
| BodyFixity
formatTopLevelBody ::
Int
-> ElmVersion
-> ImportInfo
-> (a -> BodyEntryType)
-> (a -> Box)
-> [TopLevelStructure a]
-> Maybe Box
formatTopLevelBody linesBetween elmVersion importInfo entryType formatEntry body =
let
extraLines n =
List.replicate n blankLine
spacer first second =
case (declarationType entryType first, declarationType entryType second) of
(DStarter, _) -> 0
(_, DCloser) -> 0
(DComment, DComment) -> 0
(_, DComment) -> if linesBetween == 1 then 1 else linesBetween + 1
(DComment, DDefinition _) -> if linesBetween == 1 then 0 else linesBetween
(DComment, _) -> linesBetween
(DDocComment, DDefinition _) -> 0
(DDefinition Nothing, DDefinition (Just _)) -> linesBetween
(DDefinition _, DStarter) -> linesBetween
(DDefinition Nothing, DDefinition Nothing) -> linesBetween
(DDefinition a, DDefinition b) ->
if a == b
then 0
else linesBetween
(DCloser, _) -> linesBetween
(_, DDocComment) -> linesBetween
(DDocComment, DStarter) -> 0
(DFixity, DFixity) -> 0
(DFixity, _) -> linesBetween
(_, DFixity) -> linesBetween
boxes =
intersperseMap (\a b -> extraLines $ spacer a b)
(formatTopLevelStructure elmVersion importInfo formatEntry)
body
in
case boxes of
[] -> Nothing
_ -> Just $ stack1 boxes
data ElmCodeBlock
= DeclarationsCode [TopLevelStructure Declaration]
| ExpressionsCode [TopLevelStructure (WithEol AST.Expression.Expr)]
| ModuleCode AST.Module.Module
deriving (Show)
-- TODO: there must be an existing haskell function that does this, right?
firstOf :: [a -> Maybe b] -> a -> Maybe b
firstOf options value =
case options of
[] -> Nothing
(next:rest) ->
case next value of
Just result -> Just result
Nothing -> firstOf rest value
formatDocComment :: ElmVersion -> ImportInfo -> Markdown.Blocks -> Box
formatDocComment elmVersion importInfo blocks =
let
parse :: String -> Maybe ElmCodeBlock
parse source =
source
|> firstOf
[ fmap DeclarationsCode . Result.toMaybe . Parse.parseDeclarations elmVersion
, fmap ExpressionsCode . Result.toMaybe . Parse.parseExpressions elmVersion
, fmap ModuleCode . Result.toMaybe . Parse.parseModule elmVersion
]
format :: ElmCodeBlock -> String
format result =
case result of
ModuleCode modu ->
formatModule elmVersion False 1 modu
|> (Text.unpack . Box.render)
DeclarationsCode declarations ->
formatModuleBody 1 elmVersion importInfo declarations
|> fmap (Text.unpack . Box.render)
|> fromMaybe ""
ExpressionsCode expressions ->
let
entryType _ = BodyUnnamed
in
expressions
|> formatTopLevelBody 1 elmVersion importInfo entryType (formatEolCommented $ formatExpression elmVersion importInfo SyntaxSeparated)
|> fmap (Text.unpack . Box.render)
|> fromMaybe ""
content :: String
content =
ElmFormat.Render.Markdown.formatMarkdown (fmap format . parse) $ fmap cleanBlock blocks
cleanBlock :: Markdown.Block -> Markdown.Block
cleanBlock block =
case block of
Markdown.ElmDocs docs ->
Markdown.ElmDocs $
(fmap . fmap)
(Text.replace (Text.pack "(..)") (Text.pack ""))
docs
_ ->
block
in
formatDocCommentString content
formatDocCommentString :: String -> Box
formatDocCommentString docs =
case lines docs of
[] ->
line $ row [ punc "{-|", space, punc "-}" ]
(first:[]) ->
stack1
[ line $ row [ punc "{-|", space, literal first ]
, line $ punc "-}"
]
(first:rest) ->
(line $ row [ punc "{-|", space, literal first ])
|> andThen (map (line . literal) rest)
|> andThen [ line $ punc "-}" ]
formatImport :: ElmVersion -> AST.Module.UserImport -> Box
formatImport elmVersion (name, method) =
let
as =
(AST.Module.alias method)
|> fmap (formatImportClause
(Just . line . formatUppercaseIdentifier elmVersion)
"as")
|> Monad.join
(exposingPreKeyword, exposingPostKeywordAndListing)
= AST.Module.exposedVars method
exposing =
formatImportClause
(formatListing (formatDetailedListing elmVersion))
"exposing"
(exposingPreKeyword, exposingPostKeywordAndListing)
formatImportClause :: (a -> Maybe Box) -> String -> (AST.Comments, (AST.Comments, a)) -> Maybe Box
formatImportClause format keyw input =
case
fmap (fmap format) $ input
of
([], ([], Nothing)) ->
Nothing
(preKeyword, (postKeyword, Just listing')) ->
case
( formatHeadCommented (line . keyword) (preKeyword, keyw)
, formatHeadCommented id (postKeyword, listing')
)
of
(SingleLine keyword', SingleLine listing'') ->
Just $ line $ row
[ keyword'
, space
, listing''
]
(keyword', listing'') ->
Just $ stack1
[ keyword'
, indent listing''
]
_ ->
Just $ pleaseReport "UNEXPECTED IMPORT" "import clause comments with no clause"
in
case
( formatHeadCommented (line . formatQualifiedUppercaseIdentifier elmVersion) name
, as
, exposing
)
of
( SingleLine name', Just (SingleLine as'), Just (SingleLine exposing') ) ->
line $ row
[ keyword "import"
, space
, name'
, space
, as'
, space
, exposing'
]
(SingleLine name', Just (SingleLine as'), Nothing) ->
line $ row
[ keyword "import"
, space
, name'
, space
, as'
]
(SingleLine name', Nothing, Just (SingleLine exposing')) ->
line $ row
[ keyword "import"
, space
, name'
, space
, exposing'
]
(SingleLine name', Nothing, Nothing) ->
line $ row
[ keyword "import"
, space
, name'
]
( SingleLine name', Just (SingleLine as'), Just exposing' ) ->
stack1
[ line $ row
[ keyword "import"
, space
, name'
, space
, as'
]
, indent exposing'
]
( SingleLine name', Just as', Just exposing' ) ->
stack1
[ line $ row
[ keyword "import"
, space
, name'
]
, indent as'
, indent exposing'
]
( SingleLine name', Nothing, Just exposing' ) ->
stack1
[ line $ row
[ keyword "import"
, space
, name'
]
, indent exposing'
]
( name', Just as', Just exposing' ) ->
stack1
[ line $ keyword "import"
, indent name'
, indent $ indent as'
, indent $ indent exposing'
]
( name', Nothing, Just exposing' ) ->
stack1
[ line $ keyword "import"
, indent name'
, indent $ indent exposing'
]
( name', Just as', Nothing ) ->
stack1
[ line $ keyword "import"
, indent name'
, indent $ indent as'
]
( name', Nothing, Nothing ) ->
stack1
[ line $ keyword "import"
, indent name'
]
formatListing :: (a -> [Box]) -> AST.Variable.Listing a -> Maybe Box
formatListing format listing =
case listing of
AST.Variable.ClosedListing ->
Nothing
AST.Variable.OpenListing comments ->
Just $ parens $ formatCommented (line . keyword) $ fmap (const "..") comments
AST.Variable.ExplicitListing vars multiline ->
Just $ ElmStructure.group False "(" "," ")" multiline $ format vars
formatDetailedListing :: ElmVersion -> AST.Module.DetailedListing -> [Box]
formatDetailedListing elmVersion listing =
concat
[ formatCommentedMap
(\name () -> AST.Variable.OpValue name)
(formatVarValue elmVersion)
(AST.Module.operators listing)
, formatCommentedMap
(\name (inner, listing_) -> AST.Variable.Union (name, inner) listing_)
(formatVarValue elmVersion)
(AST.Module.types listing)
, formatCommentedMap
(\name () -> AST.Variable.Value name)
(formatVarValue elmVersion)
(AST.Module.values listing)
]
formatCommentedMap :: (k -> v -> a) -> (a -> Box) -> AST.Variable.CommentedMap k v -> [Box]
formatCommentedMap construct format values =
let
format' (k, AST.Commented pre v post)
= formatCommented format $ AST.Commented pre (construct k v) post
in
values
|> Map.assocs
|> map format'
formatVarValue :: ElmVersion -> AST.Variable.Value -> Box
formatVarValue elmVersion aval =
case aval of
AST.Variable.Value val ->
line $ formatLowercaseIdentifier elmVersion [] val
AST.Variable.OpValue (SymbolIdentifier name) ->
line $ identifier $ "(" ++ name ++ ")"
AST.Variable.Union name listing ->
case
( formatListing
(formatCommentedMap
(\name_ () -> name_)
(line . formatUppercaseIdentifier elmVersion)
)
listing
, formatTailCommented (line . formatUppercaseIdentifier elmVersion) name
, snd name
, elmVersion
)
of
(Just _, _, _, Elm_0_19_Upgrade) ->
formatTailCommented
(\n -> line $ row [ formatUppercaseIdentifier elmVersion n, keyword "(..)" ])
name
(Just (SingleLine listing'), SingleLine name', [], _) ->
line $ row
[ name'
, listing'
]
(Just (SingleLine listing'), SingleLine name', _, _) ->
line $ row
[ name'
, space
, listing'