aboutsummaryrefslogtreecommitdiff
path: root/app/Server.hs
blob: 62e556f4221bf6b5b0ac60dc1bca36bae3c96320 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
{-# LANGUAGE CPP #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}

module Main where

import Control.DeepSeq (NFData, force)
import Control.Exception
  ( SomeAsyncException
  , SomeException
  , fromException
  , handle
  , throwIO
  , throwIO
  , try
  )
import Control.Monad (foldM, unless)
import Control.Monad.Except (ExceptT(..))
import Control.Monad.State.Strict (StateT(..))
import Control.Monad.Reader (MonadIO, MonadReader, ReaderT(..), asks, liftIO)
import qualified Data.Aeson as A
import qualified Data.ByteString as BS
import qualified Data.ByteString.Short as BSS
import qualified Data.ByteString.Char8 as BSC
import qualified Data.ByteString.Lazy as BSL
import Data.Default (def)
import Data.Either (lefts, rights)
import qualified Data.HashMap.Strict as HM
import Data.Hashable (Hashable)
import qualified Data.IntervalMap.Strict as IVM
import Data.IntervalMap.Interval (Interval(..), subsumes)
import qualified Data.List as L
import qualified Data.Map.Strict as M
import Data.Maybe (fromMaybe, mapMaybe)
import qualified Data.Vector as V
#if MIN_VERSION_GLASGOW_HASKELL(8,4,3,0)
import qualified GHC.Compact as C
#else
import Data.Functor.Identity(Identity(..))
#endif
import Data.Pagination
  ( Paginated
  , hasNextPage
  , hasPrevPage
  , mkPagination
  , paginate
  , paginatedItems
  , paginatedPagesTotal
  )
import Data.Proxy (Proxy(..))
import Data.Semigroup ((<>))
import qualified Data.Serialize as Serialize
import qualified Data.Set as S
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Data.Text.Lazy (toStrict)
import Data.Text.Read(decimal)
import Data.Version (Version(..))
import GHC.Exts (Down(..), groupWith)
import GHC.Generics (Generic)
import qualified HaskellCodeExplorer.Types as HCE
import Network.HTTP.Types (hContentEncoding, hContentType, status200, status404)
import Network.Mime (defaultMimeLookup)
import Network.Wai
  ( Application
  , Middleware
  , Response
  , pathInfo
  , requestHeaders
  , responseFile
  , responseLBS
  )
import Network.Wai.Handler.Warp (run)
import Network.Wai.Middleware.RequestLogger
  ( Destination(..)
  , OutputFormat(..)
  , RequestLoggerSettings(..)
  , mkRequestLogger
  )
import Numeric.Natural(Natural)
import Options.Applicative
  ( Parser
  , (<**>)
  , (<|>)
  , auto
  , execParser
  , fullDesc
  , help
  , helper
  , info
  , long
  , metavar
  , option
  , optional
  , progDesc
  , short
  , some
  , strOption
  , switch
  )
import Servant
  ( (:<|>)(..)
  , (:>)
  , Capture
  , FromHttpApiData(..)
  , Get
  , Header
  , Headers
  , QueryParam
  , ServantErr
  , ServerT
  , ToHttpApiData(..)
  , addHeader
  , err404
  , err500
  , errBody
  , serve
  )
import Servant.API.ContentTypes (AllCTRender(..), JSON)
import Servant.Server (Handler(..), hoistServer)
import Servant.Utils.Links (safeLink)
import System.Directory (doesFileExist)
import System.Exit (exitFailure, exitSuccess)
import System.FilePath.Find
  ( FileType(..)
  , (&&?)
  , (/=?)
  , (==?)
  , (==?)
  , depth
  , filePath
  , fileType
  , find
  )
import System.FilePath.Posix ((</>), takeFileName)
import System.Log.FastLogger
  ( LoggerSet
  , defaultBufSize
  , newFileLoggerSet
  , newStdoutLoggerSet
  )
import Text.Blaze.Html.Renderer.Text (renderHtml)
import qualified Text.Blaze.Html5 as Html hiding (html, source)
import Data.FileEmbed (embedDir, embedFile)
import Data.Bifunctor (second)
import qualified Store

--------------------------------------------------------------------------------
-- Server config
--------------------------------------------------------------------------------

data ServerConfig = ServerConfig
  { configPackagesPath :: !PackagesPath
  , configPort :: !Int
  , configServeStaticFiles :: !Bool
  , configEnableExpressionInfo :: !Bool
  , configIndexDirectoryName :: !(Maybe FilePath)
  , configLog :: !HCE.Log
  , configStaticFilesUrlPrefix :: !String
  , configJsDistDirectory :: !(Maybe String)
  , configMaxPerPage :: !Int
  , configStore :: !(Maybe Store)
  } deriving (Show, Eq)

data PackagesPath
  = DirectoryWithPackages FilePath
  | Directories [FilePath]
  deriving (Show, Eq)

data Store
  = CreateStore FilePath
  | UseStore FilePath
  | UseStoreMmap FilePath
  deriving (Show, Eq)

configParser :: Parser ServerConfig
configParser =
  ServerConfig <$>
  ((DirectoryWithPackages <$>
    strOption
      (long "packages" <> metavar "PATH" <>
       help "Path to a directory with Cabal packages")) <|>
   Directories <$>
   some
     (strOption
        (long "package" <> short 'p' <> metavar "PATH" <>
         help "Path to a Cabal package"))) <*>
  (pure 8080 <|>
   option
     auto
     (long "port" <> help "Port to use (default is 8080)" <> metavar "PORT")) <*>
  (not <$> switch (long "no-static" <> help "Do not serve static files")) <*>
  (not <$>
   switch
     (long "no-expressions" <>
      help "Disable queries that return expressions inside selected span")) <*>
  optional
    (strOption
       (long "index-directory" <>
        help
          "Name of a directory with index (default is '.haskell-code-explorer')" <>
        metavar "DIRECTORY_NAME")) <*>
  (pure HCE.StdOut <|>
   (HCE.ToFile <$>
    strOption
      (long "logfile" <>
       help "Path to a log file (by default log is written to stdout)" <>
       metavar "PATH"))) <*>
  (pure "files" <|>
   strOption
     (long "static-url-prefix" <> metavar "STRING" <>
      help "URL prefix for static files (default is 'files')")) <*>
  optional
    (strOption
       (long "js-path" <> help "Path to a directory with javascript files" <>
        metavar "PATH")) <*>
  (pure 50 <|>
   option
     auto
     (long "max-per-page" <> metavar "INTEGER" <>
      help "Maximum number of items per page (default is 50)")) <*>
  optional
    (CreateStore <$>
     strOption
       (long "create-store" <>
        help "Create a key-value store from PackageInfo of each indexed package" <>
        metavar "PATH_TO_DATA_DIRECTORY") <|>
     (UseStore <$>
      strOption
        (long "use-store" <>
         help "Use existing key-value store. Read 'values' file into memory." <>
         metavar "PATH_TO_DATA_DIRECTORY")) <|>
     (UseStoreMmap <$>
      strOption
        (long "use-store-mmap" <>
         help "Use existing key-value store. mmap 'values' file." <>
         metavar "PATH_TO_DATA_DIRECTORY")))

--------------------------------------------------------------------------------
-- Loading packages
--------------------------------------------------------------------------------

data PackageVersions = PackageVersions
  { name :: T.Text
  , versions :: [Version]
  } deriving (Show, Ord, Eq, Generic)

instance Serialize.Serialize PackageVersions

data PackageMap
  = PackageMap (HM.HashMap PackageName (M.Map Version (HCE.PackageInfo HCE.CompactModuleInfo)))
  | PackageMapStore { store :: Store.Store
                    , packageMap :: HM.HashMap PackageName (M.Map Version HCE.PackageId) }

type PackagePathMap = HM.HashMap PackageId FilePath

newtype AllPackages = AllPackages BSL.ByteString

newtype PackageId = PackageId
  { getPackageId :: T.Text
  } deriving (Show, Eq, Hashable, Generic, NFData)

instance Serialize.Serialize PackageId

newtype PackageName = PackageName
  { getPackageName :: T.Text
  } deriving (Show, Eq, Hashable, Generic, NFData)

instance Serialize.Serialize PackageName
instance A.ToJSON PackageVersions

type GlobalReferenceMap = HM.HashMap HCE.ExternalId (S.Set GlobalReferences)
type GlobalIdentifierMap = HCE.Trie Char HCE.ExternalIdentifierInfo

data GlobalReferences = GlobalReferences
  { count :: Int
  , packageId :: T.Text
  } deriving (Show, Eq, Ord, Generic)

instance NFData GlobalReferences

instance Serialize.Serialize GlobalReferences

instance A.ToJSON GlobalReferences

instance Store.StoreItem (HCE.Trie Char HCE.ExternalIdentifierInfo) where
  toByteString = Serialize.encode
  fromByteString = Serialize.decode
  type KeyArgs (HCE.Trie Char HCE.ExternalIdentifierInfo) =
    ( HCE.PackageId
    , String
    , Proxy (HCE.Trie Char HCE.ExternalIdentifierInfo))
  itemKey (packageId, prefix, _) =
    BSS.toShort $ BS.concat
      [ "externalIdInfoMap"
      , "|"
      , TE.encodeUtf8 $ HCE.packageIdToText packageId
      , "|"
      , BSC.pack prefix
      ]

instance Store.StoreItem [HCE.ExternalIdentifierInfo] where
  toByteString = Serialize.encode
  fromByteString = Serialize.decode
  type KeyArgs [HCE.ExternalIdentifierInfo] = ( HCE.PackageId
                                              , String
                                              , Proxy [HCE.ExternalIdentifierInfo])
  itemKey (packageId, prefix, _) =
    BSS.toShort $ BS.concat
      [ "externalIdInfo"
      , "|"
      , TE.encodeUtf8 $ HCE.packageIdToText packageId
      , "|"
      , BSC.pack prefix
      ] 

instance Store.StoreItem (S.Set HCE.IdentifierSrcSpan) where
  toByteString = Serialize.encode
  fromByteString = Serialize.decode
  type KeyArgs (S.Set HCE.IdentifierSrcSpan) = ( HCE.PackageId
                                               , HCE.ExternalId
                                               , Proxy (S.Set HCE.IdentifierSrcSpan))
  itemKey (packageId, HCE.ExternalId extId, _) =
    BSS.toShort $ BS.concat
      [ "externalIdOcc"
      , "|"
      , TE.encodeUtf8 $ HCE.packageIdToText packageId
      , "|"
      , TE.encodeUtf8 extId
      ]

instance Store.StoreItem (HM.HashMap HCE.HaskellModuleName (HM.HashMap HCE.ComponentId HCE.HaskellModulePath)) where
  toByteString = Serialize.encode
  fromByteString = Serialize.decode
  type KeyArgs (HM.HashMap HCE.HaskellModuleName (HM.HashMap HCE.ComponentId HCE.HaskellModulePath)) =
    ( HCE.PackageId
    , Proxy (HM.HashMap HCE.HaskellModuleName (HM.HashMap HCE.ComponentId HCE.HaskellModulePath)))
  itemKey (packageId,_) =
    BSS.toShort $ BS.append "moduleNameMap|" $ TE.encodeUtf8 $ HCE.packageIdToText packageId

instance (Serialize.Serialize modInfo) =>
         Store.StoreItem (HM.HashMap HCE.HaskellModulePath modInfo) where
  toByteString = Serialize.encode
  fromByteString = Serialize.decode
  type KeyArgs (HM.HashMap HCE.HaskellModulePath modInfo) =
    (HCE.PackageId,Proxy (HM.HashMap HCE.HaskellModulePath modInfo))    
  itemKey (packageId, _) =
    BSS.toShort $ BS.append "moduleMap|" $ TE.encodeUtf8 $ HCE.packageIdToText packageId

instance Store.StoreItem HCE.ExpressionInfoMap where
  toByteString = Serialize.encode
  fromByteString = Serialize.decode
  type KeyArgs HCE.ExpressionInfoMap = ( HCE.PackageId
                                       , HCE.HaskellModulePath
                                       , BS.ByteString  
                                       , Proxy HCE.ExpressionInfoMap)
  itemKey (packageId, HCE.HaskellModulePath modulePath, topLevelExprKey, _) =
    BSS.toShort $ BS.concat
      [ "exprInfoMap"
      , "|"
      , TE.encodeUtf8 $ HCE.packageIdToText packageId
      , "|"
      , TE.encodeUtf8 modulePath
      , "|"
      , topLevelExprKey  
      ]

instance Store.StoreItem (IVM.IntervalMap (Int, Int) BS.ByteString) where
  toByteString = Serialize.encode
  fromByteString = Serialize.decode
  type KeyArgs (IVM.IntervalMap (Int, Int) BS.ByteString) =
    ( HCE.PackageId
    , HCE.HaskellModulePath
    , Proxy (IVM.IntervalMap (Int, Int) BS.ByteString))
  itemKey (packageId, HCE.HaskellModulePath modulePath, _) =
    BSS.toShort $ BS.concat
      [ "topLevelExpr"
      , "|"
      , TE.encodeUtf8 $ HCE.packageIdToText packageId
      , "|"
      , TE.encodeUtf8 modulePath
      ]
    
instance Store.StoreItem HCE.DefinitionSiteMap where
  toByteString = Serialize.encode
  fromByteString = Serialize.decode
  type KeyArgs HCE.DefinitionSiteMap = ( HCE.PackageId
                                       , HCE.HaskellModulePath
                                       , Proxy HCE.DefinitionSiteMap)
  itemKey (packageId, HCE.HaskellModulePath modulePath, _) =
    BSS.toShort $ BS.concat
      [ "definitionSiteMap"
      , "|"
      , TE.encodeUtf8 $ HCE.packageIdToText packageId
      , "|"
      , TE.encodeUtf8 modulePath
      ]
      
instance Store.StoreItem (V.Vector T.Text) where
  toByteString = Serialize.encode
  fromByteString = Serialize.decode
  type KeyArgs (V.Vector T.Text) = ( HCE.PackageId
                                   , HCE.HaskellModulePath
                                   , Proxy (V.Vector T.Text))
  itemKey (packageId, HCE.HaskellModulePath modulePath, _) =
    BSS.toShort $ BS.concat
      [ "source"
      , "|"
      , TE.encodeUtf8 $ HCE.packageIdToText packageId
      , "|"
      , TE.encodeUtf8 modulePath
      ]

instance Store.StoreItem (HM.HashMap PackageName (M.Map Version HCE.PackageId)) where
  toByteString = Serialize.encode
  fromByteString = Serialize.decode
  type KeyArgs (HM.HashMap PackageName (M.Map Version HCE.PackageId)) =
    Proxy (HM.HashMap PackageName (M.Map Version HCE.PackageId))
  itemKey _ = "packageMap"

instance Store.StoreItem PackagePathMap where
  toByteString = Serialize.encode
  fromByteString = Serialize.decode
  type KeyArgs PackagePathMap = Proxy PackagePathMap
  itemKey _ = "packagePathMap"

instance Store.StoreItem GlobalReferenceMap where
  toByteString = Serialize.encode
  fromByteString = Serialize.decode
  type KeyArgs GlobalReferenceMap = Proxy GlobalReferenceMap
  itemKey _ = "globalReferenceMap"

newtype GlobalIdentifierMapWrapper = GlobalIdentifierMapWrapper
  { getGlobalIdentifierMap :: GlobalIdentifierMap
  }

instance Store.StoreItem GlobalIdentifierMapWrapper where
  toByteString (GlobalIdentifierMapWrapper idMap) = Serialize.encode idMap
  fromByteString bs = GlobalIdentifierMapWrapper <$> Serialize.decode bs
  type KeyArgs GlobalIdentifierMapWrapper = Proxy GlobalIdentifierMapWrapper
  itemKey _ = "globalIdentifierMap"  

instance Store.StoreItem [PackageVersions] where
  toByteString = Serialize.encode
  fromByteString = Serialize.decode
  type KeyArgs [PackageVersions] = Proxy [PackageVersions]
  itemKey _ = "packageVersions"

findTopLevelExpressions :: (Ord k) => IVM.IntervalMap k v -> [(Interval k, v)]
findTopLevelExpressions =
  L.foldl'
    (\topLevel interval ->
       case topLevel of
         [] -> [interval]
         topLevelIntervals@(currentTopLevelInterval:rest)
           | subsumes (fst currentTopLevelInterval) (fst interval) -> topLevelIntervals
           | subsumes (fst interval) (fst currentTopLevelInterval) ->
             interval : rest
           | otherwise -> interval : topLevelIntervals)         
    [] .
  IVM.assocs

splitIntervalMap ::
     (Show k, Ord k)
  => IVM.IntervalMap k v
  -> (IVM.IntervalMap k BS.ByteString, [(BS.ByteString, IVM.IntervalMap k v)])
splitIntervalMap ivmap =
  let topLevelExprs = findTopLevelExpressions ivmap
   in L.foldl'
        (\(index, ivMaps) (interval, _) ->
           let topLevelExpressionKey = BSC.pack $ show interval
            in ( IVM.insert interval topLevelExpressionKey index
               , (topLevelExpressionKey, IVM.within ivmap interval) : ivMaps))
        (IVM.empty, [])
        topLevelExprs

createStore :: FilePath -> ServerConfig -> IO ()
createStore storePath config = do
  packageDirectories <- findDirectories (configPackagesPath config)
  Store.createStore storePath $ \fileHandle -> do
    (errors, packageMap', packagePathMap', packageVersions', globalReferenceMap', globalIdentifiers', index'') <-
      foldM
        (\(errors, packageMap, packagePathMap, packageVersions, globalReferenceMap, globalIdentifiers, index) path -> do
           eitherPackageInfo <- loadPackageInfo config path
           case eitherPackageInfo of
             Right (packageInfo, packagePath) -> do
               let packageId =
                     HCE.id
                       (packageInfo :: HCE.PackageInfo HCE.CompactModuleInfo)
                   addPackageInfo :: StateT Store.State IO ()
                   addPackageInfo = do
                     Store.add
                       (HCE.moduleNameMap packageInfo)
                       ( packageId
                       , Proxy :: Proxy (HM.HashMap HCE.HaskellModuleName (HM.HashMap HCE.ComponentId HCE.HaskellModulePath)))
                     addExternalIdInfo packageId packageInfo
                     mapM_
                       (\(extId, occs) ->
                          Store.add
                            occs
                            ( packageId
                            , extId
                            , Proxy :: Proxy (S.Set HCE.IdentifierSrcSpan)))
                       (HM.toList $ HCE.externalIdOccMap packageInfo)
                     mapM_
                       (\(modulePath, moduleInfo) -> do
                          addExpressionInfo
                            packageId
                            modulePath
                            (HCE.exprInfoMap
                               (moduleInfo :: HCE.CompactModuleInfo))
                          Store.add
                            (HCE.definitionSiteMap
                               (moduleInfo :: HCE.CompactModuleInfo))
                            ( packageId
                            , modulePath
                            , Proxy :: Proxy HCE.DefinitionSiteMap)
                          Store.add
                            (HCE.source (moduleInfo :: HCE.CompactModuleInfo))
                            ( packageId
                            , modulePath
                            , Proxy :: Proxy (V.Vector T.Text))) .
                       HM.toList $
                       HCE.moduleMap packageInfo
               index' <- Store.writeValues fileHandle index addPackageInfo
               print $ T.unpack (HCE.packageIdToText packageId)
               return $
                 force
                   ( errors
                   , let packageVersion = HCE.version packageId
                         val = M.singleton packageVersion packageId
                      in HM.insertWith
                           M.union
                           (PackageName $ HCE.packageName packageInfo)
                           val
                           packageMap
                   , let key = PackageId $ HCE.packageIdToText packageId
                      in HM.insert key packagePath packagePathMap
                   , (\(HCE.PackageId name version) -> (name, [version]))
                       packageId :
                     packageVersions
                   , let references =
                           HM.map
                             (\spans ->
                                S.singleton
                                  (GlobalReferences
                                     (S.size spans)
                                     (HCE.packageIdToText packageId))) .
                           HCE.externalIdOccMap $
                           packageInfo
                      in HM.unionWith S.union references globalReferenceMap
                   , globalIdentifiers ++
                     filter
                       isExportedId
                       (trieValues $ HCE.externalIdInfoMap packageInfo)
                   , index')
             Left (errorMessage, path') ->
               return $
               force
                 ( (errorMessage, path') : errors
                 , packageMap
                 , packagePathMap
                 , packageVersions
                 , globalReferenceMap
                 , globalIdentifiers
                 , index))
        ([], HM.empty, HM.empty, [], HM.empty, [], M.empty)
        packageDirectories
    let versions =
          L.sortOn (T.toLower . (name :: PackageVersions -> T.Text)) .
          map (\(name, vers) -> PackageVersions name (L.sortOn Down vers)) .
          HM.toList . HM.fromListWith (++) $
          packageVersions'
    indexFinal <-
      Store.writeValues fileHandle index'' $ do
        Store.add packagePathMap' (Proxy :: Proxy PackagePathMap)
        Store.add versions (Proxy :: Proxy [PackageVersions])
        Store.add globalReferenceMap' (Proxy :: Proxy GlobalReferenceMap)
        let globalIdentifierMap =
              L.foldl'
                (\trie exportedId@(HCE.ExternalIdentifierInfo HCE.IdentifierInfo {HCE.demangledOccName = name}) ->
                   HCE.insertToTrie S.insert (T.unpack name) exportedId trie)
                HCE.emptyTrie
                globalIdentifiers'
        Store.add
          (GlobalIdentifierMapWrapper globalIdentifierMap)
          (Proxy :: Proxy GlobalIdentifierMapWrapper)
        Store.add
          packageMap'
          (Proxy :: Proxy (HM.HashMap PackageName (M.Map Version HCE.PackageId)))
    unless (null errors) $ do
      putStrLn "Package loading errors : "
      mapM_ (\(err, path) -> putStrLn $ path ++ " : " ++ err) errors
    return indexFinal

addExpressionInfo ::
     ( Show k
     , Ord k
     , Store.StoreItem (IVM.IntervalMap k v)
     , Store.StoreItem (IVM.IntervalMap k BSC.ByteString)
     , Store.KeyArgs (IVM.IntervalMap k BSC.ByteString) ~ ( a
                                                          , b
                                                          , Proxy (IVM.IntervalMap ( Int
                                                                                   , Int) BSC.ByteString))
     , Store.KeyArgs (IVM.IntervalMap k v) ~ ( a
                                             , b
                                             , BSC.ByteString
                                             , Proxy HCE.ExpressionInfoMap)
     )
  => a
  -> b
  -> IVM.IntervalMap k v
  -> StateT Store.State IO ()
addExpressionInfo packageId modulePath ivMap = do
  let (index, ivMaps) = splitIntervalMap ivMap
  Store.add
    index
    ( packageId
    , modulePath
    , Proxy :: Proxy (IVM.IntervalMap (Int, Int) BS.ByteString))
  mapM_
    (\(topLevelExprKey, ivMap') ->
       Store.add
         ivMap'
         ( packageId
         , modulePath
         , topLevelExprKey
         , Proxy :: Proxy HCE.ExpressionInfoMap))
    ivMaps

addExternalIdInfo ::
     HCE.PackageId
  -> HCE.PackageInfo HCE.CompactModuleInfo
  -> StateT Store.State IO ()
addExternalIdInfo packageId packageInfo = do
  let addTrieValues ::
           HCE.Trie Char HCE.ExternalIdentifierInfo
        -> String
        -> StateT Store.State IO ()
      addTrieValues trie name =
        let len = L.length name
         in Store.add
              (let ids =
                     S.toAscList $
                     HCE.match
                       name
                       (trie :: HCE.Trie Char HCE.ExternalIdentifierInfo)
                   (exactMatches, rest) =
                     L.span
                       (\(HCE.ExternalIdentifierInfo HCE.IdentifierInfo {..}) ->
                          T.length demangledOccName == len)
                       ids
                   maxIds = 10
                   exactMatchesCount = L.length exactMatches
                in if exactMatchesCount >= maxIds
                     then exactMatches
                     else exactMatches ++
                          L.take (maxIds - exactMatchesCount) rest)
              (packageId, name, Proxy :: Proxy [HCE.ExternalIdentifierInfo])
  let fullTrie = HCE.externalIdInfoMap packageInfo
  mapM_
    (\(firstLetter, trie) -> do
       mapM_
         (\(secondLetter, trie') -> do
            mapM_
              (\(thirdLetter, trie'') -> do
                 mapM_
                   (\(fourthLetter, trie''') ->
                      Store.add
                        trie'''
                        ( packageId
                        , [firstLetter, secondLetter, thirdLetter, fourthLetter]
                        , Proxy :: Proxy (HCE.Trie Char HCE.ExternalIdentifierInfo)))
                   (HM.toList . HCE.children $ trie'')
                 addTrieValues fullTrie [firstLetter, secondLetter, thirdLetter])
              (HM.toList . HCE.children $ trie')
            addTrieValues fullTrie [firstLetter, secondLetter])
         (HM.toList . HCE.children $ trie)
       addTrieValues fullTrie [firstLetter])
    (HM.toList . HCE.children $ fullTrie)

findDirectories :: PackagesPath -> IO [FilePath]
findDirectories p =
  case p of
    DirectoryWithPackages dir ->
      find (depth ==? 0) (fileType ==? Directory &&? filePath /=? dir) dir
    Directories dirs -> return dirs

loadPackages ::
     ServerConfig
  -> Maybe Store.Store
  -> IO (Maybe ( PackageMap
               , PackagePathMap
               , [PackageVersions]
               , GlobalReferenceMap
               , GlobalIdentifierMap))
loadPackages _config mbStore
  | (Just store) <- mbStore = do
    let eitherPackagePathMap =
          Store.lookup (Proxy :: Proxy PackagePathMap) store
        eitherGlobalReferenceMap =
          Store.lookup (Proxy :: Proxy GlobalReferenceMap) store
        eitherGlobalIdentifierMap =
          getGlobalIdentifierMap <$>
          Store.lookup (Proxy :: Proxy GlobalIdentifierMapWrapper) store
        eitherPackageVersions =
          Store.lookup (Proxy :: Proxy [PackageVersions]) store
        eitherPackageMap =
          Store.lookup
            (Proxy :: Proxy (HM.HashMap PackageName (M.Map Version HCE.PackageId)))
            store
    case (,,,,) <$> (PackageMapStore store <$> eitherPackageMap) <*>
         eitherPackagePathMap <*>
         eitherPackageVersions <*>
         eitherGlobalReferenceMap <*>
         eitherGlobalIdentifierMap of
      Right res -> return $ Just res
      Left _ -> do        
        putStrLn "Store lookup errors : "
        let ignoreRight :: Either a b -> Either a ()
            ignoreRight = second (const ())
        print $
          lefts
            [ ignoreRight eitherGlobalReferenceMap
            , ignoreRight eitherPackageMap
            , ignoreRight eitherPackageVersions
            , ignoreRight eitherGlobalIdentifierMap
            ]
        return Nothing 
loadPackages config _ = do
  packageDirectories <- findDirectories (configPackagesPath config)
  result <- mapM (loadPackageInfo config) packageDirectories
  let loadedPackages = rights result
      packageLoadErrors = lefts result
      packageInfos = map fst loadedPackages
      packageIds =
        map (HCE.id :: HCE.PackageInfo modInfo -> HCE.PackageId) packageInfos
  unless (null packageInfos) $ do
    putStrLn "Loaded packages : "
    mapM_ (print . HCE.packageIdToText) packageIds
  unless (null packageLoadErrors) $ do
    putStrLn "Package loading errors : "
    mapM_ (\(err, path) -> putStrLn $ path ++ " : " ++ err) packageLoadErrors
  if not . null $ loadedPackages
    then do
      let packageVersions =
            L.sortOn (T.toLower . (name :: PackageVersions -> T.Text)) .
            map
              (\(name, versions) ->
                 PackageVersions name (L.sortOn Down versions)) .
            HM.toList .
            HM.fromListWith (++) .
            map (\HCE.PackageId {..} -> (name, [version])) $
            packageIds
          packageMap =
            PackageMap $
            L.foldl'
              (\hMap packageInfo ->
                 let val = M.singleton (packageVersion packageInfo) packageInfo
                  in HM.insertWith M.union (packageName packageInfo) val hMap)
              HM.empty
              packageInfos
          packagePathMap =
            L.foldl'
              (\hMap (packageInfo, path) ->
                 let key =
                       PackageId $
                       HCE.packageIdToText
                         (HCE.id
                            (packageInfo :: HCE.PackageInfo HCE.CompactModuleInfo))
                  in HM.insert key path hMap)
              HM.empty
              loadedPackages
          globalReferenceMap =
            L.foldl'
              (\hMap (packageInfo, _path) ->
                 let references =
                       HM.map
                         (\spans ->
                            S.singleton
                              (GlobalReferences
                                 (S.size spans)
                                 (HCE.packageIdToText packageId))) .
                       HCE.externalIdOccMap $
                       packageInfo
                     packageId =
                       HCE.id
                         (packageInfo :: HCE.PackageInfo HCE.CompactModuleInfo)
                  in HM.unionWith S.union references hMap)
              HM.empty
              loadedPackages
          globalIdentifierMap =
            L.foldl'
              (\trie (packageInfo, _path) ->
                 let exportedIds :: [HCE.ExternalIdentifierInfo]
                     exportedIds =
                       filter isExportedId $
                       trieValues $ HCE.externalIdInfoMap packageInfo
                  in L.foldl
                       (\trie' exportedId@(HCE.ExternalIdentifierInfo (HCE.IdentifierInfo {HCE.demangledOccName = name})) ->
                          HCE.insertToTrie
                            S.insert
                            (T.unpack name)
                            exportedId
                            trie')
                       trie
                       exportedIds)
              HCE.emptyTrie
              loadedPackages
      packageMapCompacted <- ghcCompact packageMap
      packagePathMapCompacted <- ghcCompact packagePathMap
      packageVersionsCompacted <- ghcCompact packageVersions
      globalReferenceMapCompacted <- ghcCompact globalReferenceMap
      globalIdentifierMapCompacted <- ghcCompact globalIdentifierMap
      return . Just $
        ( packageMapCompacted
        , packagePathMapCompacted
        , packageVersionsCompacted
        , globalReferenceMapCompacted
        , globalIdentifierMapCompacted  
        )
    else return Nothing
  where
    packageName :: HCE.PackageInfo HCE.CompactModuleInfo -> PackageName
    packageName =
      PackageName .
      (HCE.name :: HCE.PackageId -> T.Text) .
      (HCE.id :: HCE.PackageInfo modInfo -> HCE.PackageId)
    packageVersion :: HCE.PackageInfo HCE.CompactModuleInfo -> Version
    packageVersion =
      HCE.version . (HCE.id :: HCE.PackageInfo modInfo -> HCE.PackageId)

trieValues :: HCE.Trie k v -> [v]
trieValues (HCE.Trie values children) =
  S.toList values ++ concatMap trieValues (HM.elems children)

isExportedId :: HCE.ExternalIdentifierInfo -> Bool
isExportedId (HCE.ExternalIdentifierInfo HCE.IdentifierInfo {isExported}) =
  isExported

ghcCompact :: forall a. a -> IO a
ghcCompact =
#if MIN_VERSION_GLASGOW_HASKELL(8,4,3,0)
  (fmap C.getCompact . C.compact)
#else
  return
#endif

loadPackageInfo ::
     ServerConfig
  -> String
  -> IO (Either (String, FilePath) ( HCE.PackageInfo HCE.CompactModuleInfo
                                   , FilePath))
loadPackageInfo config path =
  handleSync (\e -> return $ Left (show e, path)) $ do
    let indexDirectory =
          fromMaybe
            HCE.defaultOutputDirectoryName
            (configIndexDirectoryName config)
    binaryContent <-
      BS.readFile (path </> indexDirectory </> HCE.packageInfoBinaryFileName)
    let eitherPackageInfo = Serialize.decode binaryContent
        enableExpressionInfo = configEnableExpressionInfo config
    case eitherPackageInfo of
      Right packageInfo ->
        return . Right $
        ( updateEachModuleInfo
            packageInfo
            (\modInfo ->
               if not enableExpressionInfo
                 then modInfo {HCE.exprInfoMap = IVM.empty}
                 else modInfo)
        , path)
      Left e -> return . Left $ (e, path)

updateEachModuleInfo ::
     HCE.PackageInfo HCE.CompactModuleInfo
  -> (HCE.CompactModuleInfo -> HCE.CompactModuleInfo)
  -> HCE.PackageInfo HCE.CompactModuleInfo
updateEachModuleInfo packageInfo update =
  packageInfo {HCE.moduleMap = HM.map update $ HCE.moduleMap packageInfo}

handleSync :: (SomeException -> IO a) -> IO a -> IO a
handleSync onError =
  handle
    (\ex ->
       case fromException ex of
         Just (asyncEx :: SomeAsyncException) -> throwIO asyncEx
         _ -> onError ex)

--------------------------------------------------------------------------------
-- Servant API
--------------------------------------------------------------------------------

type API = GetAllPackages
  :<|> GetDefinitionSite
  :<|> GetExpressions
  :<|> GetReferences
  :<|> GetIdentifiers
  :<|> GetGlobalReferences
  :<|> GetGlobalIdentifiers

type GetAllPackages = "api" :> "packages" :> Get '[JSON] AllPackages

type GetDefinitionSite = "api" :> "definitionSite"
  :> Capture "packageId" PackageId
  :> Capture "componentId" HCE.ComponentId
  :> Capture "moduleName" HCE.HaskellModuleName
  :> Capture "entity" HCE.LocatableEntity
  :> Capture "name" T.Text
  :> Get '[JSON] HCE.DefinitionSite

type GetExpressions = "api" :> "expressions"
  :> Capture "packageId" PackageId
  :> Capture "modulePath" HCE.HaskellModulePath
  :> Capture "lineStart" Int
  :> Capture "columnStart" Int
  :> Capture "lineEnd" Int
  :> Capture "columnEnd" Int
  :> Get '[JSON] [Expression]

type GetReferences = "api" :> "references"
  :> Capture "packageId" PackageId
  :> Capture "externalId" HCE.ExternalId
  :> QueryParam "page" Int
  :> QueryParam "per_page" Int
  :> Get '[JSON] (Headers '[Header "Link" T.Text,Header "X-Total-Count" Int]
                 [SourceFile])

type GetIdentifiers = "api" :> "identifiers"
  :> Capture "packageId" PackageId
  :> Capture "query" T.Text
  :> QueryParam "page" Int
  :> QueryParam "per_page" Int
  :> Get '[JSON] (Headers '[Header "Link" T.Text,Header "X-Total-Count" Int]
                 [HCE.ExternalIdentifierInfo])

type GetGlobalReferences = "api" :> "globalReferences"
  :> Capture "externalId" HCE.ExternalId  
  :> Get '[JSON] [GlobalReferences]

type GetGlobalIdentifiers = "api" :> "globalIdentifiers"
  :> Capture "query" T.Text
  :> QueryParam "page" Int
  :> QueryParam "per_page" Int
  :> Get '[JSON] (Headers '[Header "Link" T.Text,Header "X-Total-Count" Int]
                 [HCE.ExternalIdentifierInfo])  

instance AllCTRender '[ JSON] AllPackages where
  handleAcceptH _ _ (AllPackages bytestring) =
    Just ("application/json", bytestring)

instance FromHttpApiData HCE.LocatableEntity where
  parseQueryParam "Val" = Right HCE.Val
  parseQueryParam "Typ" = Right HCE.Typ
  parseQueryParam "Inst" = Right HCE.Inst
  parseQueryParam "Mod" = Right HCE.Mod
  parseQueryParam val = Left $ T.append "Incorrect LocatableEntity : " val

instance ToHttpApiData HCE.LocatableEntity where
  toUrlPiece HCE.Val = "ValueEntity"
  toUrlPiece HCE.Typ = "TypeEntity"
  toUrlPiece HCE.Inst = "InstanceEntity"
  toUrlPiece HCE.Mod = "ModuleEntity"

instance ToHttpApiData HCE.ExternalId where
  toUrlPiece (HCE.ExternalId i) = i
  
instance ToHttpApiData PackageId where
  toUrlPiece (PackageId p) = p
  
instance FromHttpApiData HCE.HaskellModulePath where
  parseQueryParam = Right . HCE.HaskellModulePath

instance FromHttpApiData HCE.ComponentId where
  parseQueryParam = Right . HCE.ComponentId

instance FromHttpApiData HCE.HaskellModuleName where
  parseQueryParam = Right . HCE.HaskellModuleName

instance FromHttpApiData HCE.ExternalId where
  parseQueryParam = Right . HCE.ExternalId
  
instance FromHttpApiData PackageId where
  parseQueryParam = Right . PackageId
  
--------------------------------------------------------------------------------
-- Request handlers
--------------------------------------------------------------------------------

data Environment = Environment
  { envLogger :: !LoggerSet
  , envPackageMap :: !PackageMap
  , envPackageVersions :: !AllPackages
  , envGlobalReferenceMap :: !GlobalReferenceMap
  , envGlobalIdentifierMap :: !GlobalIdentifierMap
  , envConfig :: !ServerConfig
  }

data Expression = Expression
  { srcSpan :: !(IVM.Interval (Int, Int))
  , info :: !HCE.ExpressionInfo
  } deriving (Show, Eq, Generic)

instance A.ToJSON Expression

data ReferenceWithSource = ReferenceWithSource
  { sourceCodeHtml :: !T.Text
  , idSrcSpan :: !HCE.IdentifierSrcSpan
  } deriving (Show, Eq, Generic)

data SourceFile = SourceFile
  { name :: !T.Text
  , references :: ![ReferenceWithSource]
  } deriving (Show, Eq, Generic)

instance A.ToJSON ReferenceWithSource
instance A.ToJSON SourceFile

getAllPackages :: ReaderT Environment IO AllPackages
getAllPackages = asks envPackageVersions
    
getExpressions ::
     PackageId
  -> HCE.HaskellModulePath
  -> Int -- ^ Start line
  -> Int -- ^ Start column
  -> Int -- ^ End line
  -> Int -- ^ End column
  -> ReaderT Environment IO [Expression]
getExpressions packageId modulePath startLine startColumn endLine endColumn = do
  enableExpressionInfo <- asks (configEnableExpressionInfo . envConfig)
  if not enableExpressionInfo
    then error404 "Expression queries are disabled"
    else withPackageInfo packageId $ \packageInfo' -> do
           maxPerPage <- asks (configMaxPerPage . envConfig)
           let requestedInterval =
                 IVM.ClosedInterval
                   (startLine, startColumn)
                   (endLine, endColumn)
               findInterval ::
                    HCE.ExpressionInfoMap -> ReaderT Environment IO [Expression]
               findInterval exprInfoMap =
                 return .
                 map (uncurry Expression) .
                 L.take maxPerPage . IVM.toList . IVM.within exprInfoMap $
                 requestedInterval
            in case packageInfo' of
                 PackageInfo packageInfo ->
                   withModuleInfo packageInfo modulePath $ \modInfo -> do
                     let exprInfoMap =
                           HCE.exprInfoMap (modInfo :: HCE.CompactModuleInfo)
                     findInterval exprInfoMap
                 PackageInfoStore pId store -> do
                   let topLevelExprKey =
                         ( pId
                         , modulePath
                         , Proxy :: Proxy (IVM.IntervalMap (Int, Int) BS.ByteString))
                       eitherTopLevelExprMap =
                         Store.lookup topLevelExprKey store
                   case eitherTopLevelExprMap of
                     Right topLevelExprMap ->
                       case map snd . IVM.toList $
                            IVM.intersecting topLevelExprMap requestedInterval of
                         exprKey:_ -> do
                           let key =
                                 ( pId
                                 , modulePath
                                 , exprKey
                                 , Proxy :: Proxy HCE.ExpressionInfoMap)
                               eitherExprMap = Store.lookup key store
                           case eitherExprMap of
                             Right exprMap -> findInterval exprMap
                             Left e -> error500 $ BSL.fromStrict $ BSC.pack e
                         _ -> return []
                     Left e -> error500 $ BSL.fromStrict $ BSC.pack e

getDefinitionSite ::
     PackageId
  -> HCE.ComponentId
  -> HCE.HaskellModuleName
  -> HCE.LocatableEntity
  -> T.Text
  -> ReaderT Environment IO HCE.DefinitionSite
getDefinitionSite packageId componentId modName entity name' =
  withPackageInfo packageId $ \packageInfo' ->
    withModulePath packageInfo' componentId modName $ \modPath ->
      let findDefSite ::
               HCE.PackageId
            -> HCE.DefinitionSiteMap
            -> ReaderT Environment IO HCE.DefinitionSite
          findDefSite pId defSiteMap =
            case entity of
              HCE.Mod ->
                return $
                HCE.DefinitionSite
                  (HCE.ExactLocation pId modPath modName 1 1 1 1)
                  Nothing
              _ -> do
                let mbDefinitionSite =
                      let name = fixDots name'
                      in case entity of
                        HCE.Typ ->
                          HM.lookup (HCE.OccName name) $
                          HCE.types (defSiteMap :: HCE.DefinitionSiteMap)
                        HCE.Val ->
                          HM.lookup (HCE.OccName name) $
                          HCE.values (defSiteMap :: HCE.DefinitionSiteMap)
                        HCE.Inst ->
                          HM.lookup name $
                          HCE.instances (defSiteMap :: HCE.DefinitionSiteMap)
                        _ -> Nothing
                case mbDefinitionSite of
                  Just definitionSite -> return definitionSite
                  Nothing ->
                    error404 $
                    BSL.concat
                      [ toLazyBS . T.pack $ show entity
                      , " "
                      , toLazyBS name'
                      , " "
                      , " not found in module "
                      , toLazyBS $ HCE.getHaskellModulePath modPath
                      ]
       in case packageInfo' of
            PackageInfo packageInfo ->
              let pId =
                    HCE.id
                      (packageInfo :: HCE.PackageInfo HCE.CompactModuleInfo)
               in case HM.lookup
                         modPath
                         (HCE.moduleMap
                            (packageInfo :: HCE.PackageInfo HCE.CompactModuleInfo)) of
                    Just HCE.CompactModuleInfo {definitionSiteMap = defSiteMap} ->
                      findDefSite pId defSiteMap
                    Nothing ->
                      error404 $
                      BSL.concat
                        [ "Module "
                        , toLazyBS $ HCE.getHaskellModulePath modPath
                        , " is not found in package "
                        , toLazyBS $ HCE.packageIdToText pId
                        ]
            PackageInfoStore pId store -> do
              let eitherDefinitionSiteMap =
                    Store.lookup
                      (pId, modPath, Proxy :: Proxy HCE.DefinitionSiteMap)
                      store
              case eitherDefinitionSiteMap of
                Right definitionSiteMap -> findDefSite pId definitionSiteMap
                Left e -> error500 (BSL.fromStrict $ BSC.pack e)

-- | "." and ".." is a special case because of the Path Segment Normalization:
-- https://tools.ietf.org/html/rfc3986#section-6.2.2.3
-- The segments “..” and “.” can be removed from a URL by a browser.
-- https://stackoverflow.com/questions/3856693/a-url-resource-that-is-a-dot-2e
fixDots :: T.Text -> T.Text
fixDots " ." = "."
fixDots " .." = ".."
fixDots t = t

buildLinkHeader :: T.Text -> Paginated a -> Natural -> Natural -> T.Text
buildLinkHeader url paginated currentPage perPage =
  T.intercalate
    ","
    (let addFirst
           | currentPage /= 1 =
             (:) (link (T.append url $ params 1 perPage) "first")
           | otherwise = id
         addLast
           | currentPage /= paginatedPagesTotal paginated =
             (:)
               (link
                  (T.append url $ params (paginatedPagesTotal paginated) perPage)
                  "last")
           | otherwise = id
         addNext
           | hasNextPage paginated =
             (:) (link (T.append url $ params (currentPage + 1) perPage) "next")
           | otherwise = id
         addPrev
           | hasPrevPage paginated =
             (:) (link (T.append url $ params (currentPage - 1) perPage) "prev")
           | otherwise = id
      in addFirst . addLast . addNext . addPrev $ [])
  where
    link :: T.Text -> T.Text -> T.Text
    link u rel = T.concat ["<", u, ">; rel=\"", rel, "\""]
    params :: Natural -> Natural -> T.Text
    params p pp =
      T.concat ["?page=", T.pack . show $ p, "&per_page=", T.pack . show $ pp]

initializePagination ::
     (MonadReader Environment m)
  => Maybe Int
  -> Maybe Int
  -> m (Natural, Natural)
initializePagination mbPage mbPerPage = do
  maxPerPage <- asks (configMaxPerPage . envConfig)
  let page =
        case mbPage of
          Just p ->
            if p > 0
              then p
              else 1
          Nothing -> 1
      perPage =
        case mbPerPage of
          Just pp ->
            if pp <= maxPerPage && pp > 0
              then pp
              else maxPerPage
          Nothing -> maxPerPage
  return (fromIntegral page, fromIntegral perPage)

getGlobalReferences ::
     HCE.ExternalId -> ReaderT Environment IO [GlobalReferences]
getGlobalReferences externalId = do
  refMap <- asks envGlobalReferenceMap
  return $ maybe [] S.toDescList (HM.lookup externalId refMap)  

getReferences ::
     PackageId
  -> HCE.ExternalId
  -> Maybe Int -- ^ Page number
  -> Maybe Int -- ^ Items per page
  -> ReaderT Environment IO (Headers '[ Header "Link" T.Text, Header "X-Total-Count" Int] [SourceFile])
getReferences packageId externalId mbPage mbPerPage =
  withPackageInfo packageId $ \packageInfo' ->
    let mkRefsWithSource ::
             Maybe [HCE.IdentifierSrcSpan]
          -> ReaderT Environment IO (Headers '[ Header "Link" T.Text, Header "X-Total-Count" Int] [SourceFile])
        mkRefsWithSource mbReferences =
          case mbReferences of
            Just references -> do
              (paginatedReferences, page, perPage, totalCount) <-
                paginateItems mbPage mbPerPage references
              let url =
                    T.append "/" $
                    toUrlPiece $
                    safeLink
                      (Proxy :: Proxy API)
                      (Proxy :: Proxy GetReferences)
                      packageId
                      externalId
                      Nothing
                      Nothing
                  linkHeader =
                    buildLinkHeader url paginatedReferences page perPage
                  addHeaders ::
                       forall a.
                       a
                    -> Headers '[ Header "Link" T.Text, Header "X-Total-Count" Int] a
                  addHeaders = addHeader linkHeader . addHeader totalCount
                  refModulePath :: ReferenceWithSource -> HCE.HaskellModulePath
                  refModulePath =
                    (HCE.modulePath :: HCE.IdentifierSrcSpan -> HCE.HaskellModulePath) .
                    idSrcSpan
              return $
                addHeaders $
                concatMap
                  (\refs ->
                     case refs of
                       ref:_ ->
                         let path =
                               HCE.getHaskellModulePath .
                               (HCE.modulePath :: HCE.IdentifierSrcSpan -> HCE.HaskellModulePath) .
                               idSrcSpan $
                               ref
                          in [SourceFile path refs]
                       _ -> []) $
                groupWith refModulePath $
                mapMaybe
                  (mkReferenceWithSource packageInfo')
                  (L.groupBy (\span1 span2 -> HCE.line span1 == HCE.line span2) $
                   paginatedItems paginatedReferences)
            Nothing ->
              error404 $
              BSL.concat
                [ "Cannot find references to "
                , toLazyBS $ HCE.getExternalId externalId
                ]
     in case packageInfo' of
          PackageInfo packageInfo ->
            mkRefsWithSource $ S.toList <$> HM.lookup externalId (HCE.externalIdOccMap packageInfo)            
          PackageInfoStore pId store -> do
            let eitherOccurrences =
                  Store.lookup
                    ( pId
                    , externalId
                    , Proxy :: Proxy (S.Set HCE.IdentifierSrcSpan))
                    store
            case eitherOccurrences of
              Right occurrences ->
                mkRefsWithSource (Just $ S.toList occurrences)
              Left e -> error500 $ BSL.fromStrict $ BSC.pack e

mkReferenceWithSource ::
     PackageInfo -> [HCE.IdentifierSrcSpan] -> Maybe ReferenceWithSource
mkReferenceWithSource packageInfo' spans@(srcSpan:_) =
  let mkRef :: Maybe (V.Vector T.Text) -> Maybe ReferenceWithSource
      mkRef mbSource =
        case mbSource of
          Just source ->
            let sourceCodeHtml =
                  buildHtmlCodeSnippet
                    source
                    (HCE.line (srcSpan :: HCE.IdentifierSrcSpan))
                    (map
                       (\HCE.IdentifierSrcSpan {..} -> (startColumn, endColumn))
                       spans)
             in Just $ ReferenceWithSource sourceCodeHtml srcSpan
          _ -> Just $ ReferenceWithSource "" srcSpan
   in case packageInfo' of
        PackageInfo packageInfo -> do
          let mbSource =
                (HCE.source :: HCE.CompactModuleInfo -> V.Vector T.Text) <$>
                HM.lookup
                  (HCE.modulePath (srcSpan :: HCE.IdentifierSrcSpan))
                  (HCE.moduleMap
                     (packageInfo :: HCE.PackageInfo HCE.CompactModuleInfo))
          mkRef mbSource
        PackageInfoStore packageId store -> do
          let eitherSourceCode =
                Store.lookup
                  ( packageId
                  , HCE.modulePath (srcSpan :: HCE.IdentifierSrcSpan)
                  , Proxy :: Proxy (V.Vector T.Text))
                  store
          case eitherSourceCode of
            Right source -> mkRef (Just source)
            Left _ -> mkRef Nothing
mkReferenceWithSource _ _ = Nothing

buildHtmlCodeSnippet :: V.Vector T.Text -> Int -> [(Int, Int)] -> T.Text
buildHtmlCodeSnippet sourceLines lineNumber positions =
  toStrict $
  renderHtml $ do
    mkLineNumber (lineNumber - 1) >>
      Html.toHtml
        (T.append (fromMaybe "" $ (V.!?) sourceLines (lineNumber - 2)) "\n")
    mkLineNumber lineNumber >>
      highlightIdentifiers
        (T.append (fromMaybe "" $ (V.!?) sourceLines (lineNumber - 1)) "\n")
    mkLineNumber (lineNumber + 1) >>
      Html.toHtml (T.append (fromMaybe "" $ (V.!?) sourceLines lineNumber) "\n")
  where
    mkLineNumber :: Int -> Html.Html
    mkLineNumber i = Html.toHtml (show i ++ "  ")
    highlightIdentifiers :: T.Text -> Html.Html
    highlightIdentifiers line =
      mapM_
        (\(text, _, mbId) ->
           case mbId of
             Just _ -> Html.b (Html.toHtml text)
             Nothing -> Html.toHtml text) $
      HCE.tokenize line (map (, ()) positions)

findIdentifiers ::
     PackageId
  -> T.Text
  -> Maybe Int
  -> Maybe Int
  -> ReaderT Environment IO (Headers '[ Header "Link" T.Text, Header "X-Total-Count" Int] [HCE.ExternalIdentifierInfo])
findIdentifiers packageId query' mbPage mbPerPage =  
  withPackageInfo packageId $ \packageInfo' ->
    let query = fixDots query'
        respond identifiers = do
          (paginatedIdentifiers, page, perPage, totalCount) <-
            paginateItems mbPage mbPerPage identifiers
          let url =
                T.append "/" $
                toUrlPiece $
                safeLink
                  (Proxy :: Proxy API)
                  (Proxy :: Proxy GetIdentifiers)
                  packageId
                  query'
                  Nothing
                  Nothing
              linkHeader = buildLinkHeader url paginatedIdentifiers page perPage
              addHeaders ::
                   forall a.
                   a
                -> Headers '[ Header "Link" T.Text, Header "X-Total-Count" Int] a
              addHeaders = addHeader linkHeader . addHeader totalCount
          return . addHeaders . paginatedItems $ paginatedIdentifiers
     in case packageInfo' of
          PackageInfo packageInfo -> do
            let identifiers
                  | not $ T.null query =
                    S.toList $
                    HCE.match
                      (T.unpack query)
                      (HCE.externalIdInfoMap packageInfo)
                  | otherwise = []
            respond identifiers
          PackageInfoStore pId store ->
            let findIds :: T.Text -> [HCE.ExternalIdentifierInfo]
                findIds q =
                  let eitherIdInfo =
                        Store.lookup
                          ( pId
                          , T.unpack q
                          , Proxy :: Proxy [HCE.ExternalIdentifierInfo])
                          store
                   in case eitherIdInfo of
                        Right ids -> ids
                        Left _ -> []
             in case T.length query of
                  0 -> respond []
                  1 -> respond $ findIds query
                  2 -> respond $ findIds query
                  3 -> respond $ findIds query
                  _ ->
                    let eitherIdInfoMap =
                          Store.lookup
                            ( pId
                            , T.unpack $ T.take 4 query
                            , Proxy :: Proxy (HCE.Trie Char HCE.ExternalIdentifierInfo))
                            store
                     in case eitherIdInfoMap of
                          Right trie ->
                            respond $
                            S.toList $
                            HCE.match (T.unpack $ T.drop 4 query) trie
                          Left _ -> respond []                          

findGlobalIdentifiers ::
     T.Text
  -> Maybe Int
  -> Maybe Int
  -> ReaderT Environment IO (Headers '[ Header "Link" T.Text, Header "X-Total-Count" Int] [HCE.ExternalIdentifierInfo])
findGlobalIdentifiers query' mbPage mbPerPage = do
  let query = fixDots query'
  globalIdentifierMap <- asks envGlobalIdentifierMap
  let maxItems = 500
  let identifiers
        | T.length query > 0 =
          L.take maxItems $
          S.toList $ HCE.match (T.unpack query) globalIdentifierMap
        | otherwise = []
  (paginatedIdentifiers, page, perPage, totalCount) <-
    paginateItems mbPage mbPerPage identifiers
  let url =
        T.append "/" $
        toUrlPiece $
        safeLink
          (Proxy :: Proxy API)
          (Proxy :: Proxy GetGlobalIdentifiers)
          query'
          Nothing
          Nothing
      linkHeader = buildLinkHeader url paginatedIdentifiers page perPage
      addHeaders ::
           forall a.
           a
        -> Headers '[ Header "Link" T.Text, Header "X-Total-Count" Int] a
      addHeaders = addHeader linkHeader . addHeader totalCount
  return . addHeaders . paginatedItems $ paginatedIdentifiers

paginateItems ::
     Maybe Int
  -> Maybe Int
  -> [a]
  -> ReaderT Environment IO (Paginated a, Natural, Natural, Int)
paginateItems mbPage mbPerPage items = do
  (page, perPage) <- initializePagination mbPage mbPerPage
  let totalCount = L.length items
  pagination <- mkPagination perPage page
  paginated <-
    paginate
      pagination
      (fromIntegral totalCount)
      (\offset limit -> return . L.take limit . L.drop offset $ items)
  return (paginated, page, perPage, totalCount)
    
error404 :: BSL.ByteString -> ReaderT Environment IO a
error404 body = throwServantError $ err404 {errBody = body}

error500 :: BSL.ByteString -> ReaderT Environment IO a
error500 body = throwServantError $ err500 {errBody = body}

toLazyBS :: T.Text -> BSL.ByteString
toLazyBS = BSL.fromStrict . TE.encodeUtf8

data PackageInfo
  = PackageInfo (HCE.PackageInfo HCE.CompactModuleInfo)
  | PackageInfoStore HCE.PackageId
                     Store.Store
  
withPackageInfo ::
     PackageId
  -> (PackageInfo -> ReaderT Environment IO a)
  -> ReaderT Environment IO a
withPackageInfo packageId action
  | Just (packageName, mbVersion) <- parsePackageId packageId = do
    packageMap <- asks envPackageMap
    let findPackage ::
             (Hashable k, Eq k, Ord k1)
          => k
          -> Maybe k1
          -> HM.HashMap k (M.Map k1 v)
          -> Maybe v
        findPackage name mbVer pMap =
          HM.lookup name pMap >>=
          (\packages ->
             let findLastVersion :: M.Map k v -> Maybe v
                 findLastVersion = fmap (snd . fst) . L.uncons . M.toDescList
              in case mbVer of
                   Just version ->
                     M.lookup version packages <|> findLastVersion packages
                   Nothing -> findLastVersion packages)
        mbPackageInfo =
          case packageMap of
            PackageMap pMap ->
              PackageInfo <$> findPackage packageName mbVersion pMap
            PackageMapStore store pMap ->
              case findPackage packageName mbVersion pMap of
                Just pId -> Just $ PackageInfoStore pId store
                Nothing -> Nothing
    case mbPackageInfo of
      Just p -> action p
      Nothing -> packageNotFound packageId
withPackageInfo packageId _ = packageNotFound packageId

packageNotFound :: PackageId -> ReaderT Environment IO a
packageNotFound packageId =
  error404 $
  BSL.concat ["Package ", toLazyBS $ getPackageId packageId, " is not found."]

withModuleInfo ::
     HCE.PackageInfo HCE.CompactModuleInfo
  -> HCE.HaskellModulePath
  -> (HCE.CompactModuleInfo -> ReaderT Environment IO a)
  -> ReaderT Environment IO a
withModuleInfo packageInfo path action =
  case HM.lookup
         path
         (HCE.moduleMap (packageInfo :: HCE.PackageInfo HCE.CompactModuleInfo)) of
    Just modInfo -> action modInfo
    Nothing ->
      error404 $
      BSL.concat
        [ "Module "
        , toLazyBS $ HCE.getHaskellModulePath path
        , " is not found in package "
        , toLazyBS $
          HCE.packageIdToText $
          HCE.id (packageInfo :: HCE.PackageInfo HCE.CompactModuleInfo)
        ]

withModulePath ::
     PackageInfo
  -> HCE.ComponentId
  -> HCE.HaskellModuleName
  -> (HCE.HaskellModulePath -> ReaderT Environment IO a)
  -> ReaderT Environment IO a
withModulePath packageInfo' componentId moduleName action =
  case packageInfo' of
    PackageInfo packageInfo ->
      case HM.lookup
             (ghcPrimHack packageInfo' moduleName)
             (HCE.moduleNameMap packageInfo) of
        Just modulePathMap ->
          case HM.lookup componentId modulePathMap of
            Just modulePath -> action modulePath
            Nothing ->
              case HM.lookup (HCE.ComponentId "lib") modulePathMap of
                Just path -> action path
                Nothing -> notFoundInComponent
        Nothing -> notFoundInPackage (HCE.id (packageInfo :: HCE.PackageInfo HCE.CompactModuleInfo))
    PackageInfoStore packageId store -> do
      let eitherModNameMap =
              Store.lookup
                ( packageId
                , Proxy :: Proxy (HM.HashMap HCE.HaskellModuleName (HM.HashMap HCE.ComponentId HCE.HaskellModulePath)))
                store
      case eitherModNameMap of
          Right modNameMap ->
            case HM.lookup (ghcPrimHack packageInfo' moduleName) modNameMap of 
              Just componentMap -> case HM.lookup componentId componentMap of
                Just modulePath -> action modulePath
                Nothing -> case HM.lookup (HCE.ComponentId "lib") componentMap of
                  Just modulePath -> action modulePath
                  Nothing -> notFoundInComponent
              Nothing -> notFoundInPackage packageId
          Left e -> error500 (BSL.fromStrict $ BSC.pack e)
  where
    notFoundInComponent =
      error404 $
      BSL.concat
        [ "Module "
        , toLazyBS $ HCE.getHaskellModuleName moduleName
        , " is not found in component "
        , toLazyBS $ HCE.getComponentId componentId
        ]
    notFoundInPackage packageId =
      error404 $
      BSL.concat
        [ "Module "
        , toLazyBS $ HCE.getHaskellModuleName moduleName
        , " is not found in package "
        , toLazyBS $ HCE.packageIdToText packageId
        ]

-- | Workaround for :
-- https://github.com/ghc/ghc/blob/ghc-8.2.2-release/compiler/main/Finder.hs#L310-L315
ghcPrimHack :: PackageInfo -> HCE.HaskellModuleName -> HCE.HaskellModuleName
ghcPrimHack packageInfo' modName@(HCE.HaskellModuleName name) =
  case packageInfo' of
    PackageInfo packageInfo
      | HCE.packageName packageInfo == "ghc-prim" && name == "GHC.Prim" ->
        HCE.HaskellModuleName "GHC.Prim_"
      | otherwise -> modName
    PackageInfoStore (HCE.PackageId packageName _) _
      | packageName == "ghc-prim" && name == "GHC.Prim" ->
        HCE.HaskellModuleName "GHC.Prim_"
      | otherwise -> modName
  
parsePackageId :: PackageId -> Maybe (PackageName, Maybe Version)
parsePackageId (PackageId text) =
  case T.splitOn "-" text of
    [name] -> Just (PackageName name, Nothing)
    chunks@(_x:_xs) ->
      case mapM decimal . T.splitOn "." . last $ chunks of
        Right numbers ->
          Just
            ( PackageName $ T.intercalate "-" . init $ chunks
            , Just $ Version (map fst numbers) [])
        Left _ -> Just (PackageName text, Nothing)
    _ -> Nothing

staticMiddleware :: String -> PackagePathMap -> Maybe FilePath -> Middleware
staticMiddleware staticFilesPrefix packagePathMap _ app req callback
  | ("api":_) <- pathInfo req = app req callback
  | (prefix:packageId:rest) <- pathInfo req
  , prefix == T.pack staticFilesPrefix =
    case HM.lookup (PackageId packageId) packagePathMap of
      Just basePath
        | ".." `notElem` rest -> do
          let clientAcceptsEncoding =
                maybe
                  []
                  (map T.strip . T.splitOn "," . TE.decodeUtf8)
                  (lookup "Accept-Encoding" (requestHeaders req))
              clientAcceptsGzip = "gzip" `elem` clientAcceptsEncoding
              path = basePath </> T.unpack (T.intercalate "/" rest)
              gzPath = path ++ ".gz"
          sendGzipFile <-
            if clientAcceptsGzip
              then doesFileExist gzPath
              else return False
          if sendGzipFile
            then callback $
                 responseFile
                   status200
                   [ (hContentEncoding, "gzip")
                   , ( hContentType
                     , defaultMimeLookup . T.pack . takeFileName $ path)
                   ]
                   gzPath
                   Nothing
            else do
              exists <- doesFileExist path
              if exists
                then callback $ sendFile path
                else callback fileNotFound
      _ -> callback fileNotFound     
staticMiddleware _ _ mbJsDistPath _app req callback =
  case mbJsDistPath of
    Just jsDistPath -> do
      let path = jsDistPath </> T.unpack (T.intercalate "/" $ pathInfo req)
      exists <- doesFileExist path
      if exists
         then callback $ sendFile path
         else callback $ sendFile (jsDistPath </> "index.html")
    Nothing -> do
      let path = T.unpack $ T.intercalate "/" $ pathInfo req
      if path == ""
        then callback $ sendEmbeddedFile "index.html" indexHtml
        else case HM.lookup path staticAssets of
          Just bs -> callback $ sendEmbeddedFile path bs
          Nothing -> callback $ sendEmbeddedFile "index.html" indexHtml

staticAssets :: HM.HashMap FilePath BS.ByteString
staticAssets = HM.fromList $(embedDir "javascript/release")

indexHtml :: BS.ByteString
indexHtml = $(embedFile "javascript/release/index.html")

sendFile :: FilePath -> Response
sendFile path =
  responseFile
    status200
    [(hContentType, defaultMimeLookup $ T.pack $ takeFileName path)]
    path
    Nothing

sendEmbeddedFile :: FilePath -> BS.ByteString -> Response
sendEmbeddedFile path bs =
  responseLBS
    status200
    [(hContentType, defaultMimeLookup $ T.pack $ takeFileName path)]
    (BSL.fromStrict bs)    

fileNotFound :: Response
fileNotFound =
  responseLBS status404 [("Content-Type", "text/plain")] "Not found"

throwServantError :: (MonadIO m) => ServantErr -> m a
throwServantError = liftIO . throwIO 

server :: Environment -> ServerT API Handler
server env =
  hoistServer
    (Proxy :: Proxy API)
    toServantHandler
    (getAllPackages :<|>
     getDefinitionSite :<|>     
     getExpressions :<|>
     getReferences :<|>
     findIdentifiers :<|>
     getGlobalReferences :<|>
     findGlobalIdentifiers)
  where
    toServantHandler :: ReaderT Environment IO a -> Handler a
    toServantHandler ma = Handler . ExceptT . try . runReaderT ma $ env

application :: Environment -> Application
application env = serve (Proxy :: Proxy API) (server env)

main :: IO ()
main = do
  config <-
    execParser
      (Options.Applicative.info
         (configParser <**> helper)
         (fullDesc <>
          progDesc
            "haskell-code-server provides an HTTP API for Haskell Code Explorer"))
  print config
  mbStore <-
    let loadStore :: FilePath -> Store.ReadMode -> IO (Maybe Store.Store)
        loadStore path readOrMmap = do
          eitherStore <- Store.load path readOrMmap
          case eitherStore of
            Right store -> return $ Just store
            Left e -> putStrLn e >> exitFailure
     in case configStore config of
          Just (UseStore path) -> loadStore path Store.ReadEntireFile
          Just (UseStoreMmap path) -> loadStore path Store.MemoryMapFile
          Just (CreateStore path) -> do
            createStore path config
            exitSuccess
          Nothing -> return Nothing
  packages <- loadPackages config mbStore
  case packages of
    Just (packageMap, packagePathMap, packageVersions, globalReferenceMap, globalIdentifierMap) -> do
      loggerSet <-
        case configLog config of
          HCE.ToFile logfile -> newFileLoggerSet defaultBufSize logfile
          HCE.StdOut -> newStdoutLoggerSet defaultBufSize
      loggerMiddleware <-
        liftIO $
        mkRequestLogger
          def {outputFormat = Detailed True, destination = Logger loggerSet}      
      let staticFilePrefix = configStaticFilesUrlPrefix config
          mbJsDistPath = configJsDistDirectory config
          environment =
            Environment
              loggerSet
              packageMap
              (AllPackages . A.encode $ packageVersions)
              globalReferenceMap
              globalIdentifierMap
              config
          static =
            if configServeStaticFiles config
              then staticMiddleware staticFilePrefix packagePathMap mbJsDistPath
              else id
      run
        (configPort config)
        (loggerMiddleware . static $ application environment)
    Nothing -> putStrLn "No packages found."