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
|
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE NoImplicitPrelude #-}
-- | Physical source names and mount policy.
--
-- A 'SafeRelativePath' is interpreted from a source mount, never from the
-- importing file. A 'CanonicalPath' is an absolute host path used only to
-- identify the physical file selected during this invocation.
module Felix.Source
( SourceMountId
, sourceMountId
, sourceMountIdText
, CanonicalPath
, canonicalPathFilePath
, SafeRelativePath
, safeRelativePath
, safeRelativePathFilePath
, SourceMount
, sourceMountIdentifier
, sourceMountRoot
, SourceMounts
, prepareSourceMounts
, sourceMountList
, RootRequest
, searchedRoot
, existingRoot
, canonicalizeExistingSourcePath
, rootRequestSpelling
, ResolvedSource
, resolvedSourceCanonicalPath
, resolvedSourceMount
, resolvedSourceMountRoot
, resolvedSourceRelativePath
, resolvedSourceLocationPath
, ResolvedSourceAddress
, resolvedSourceAddress
, sourceAddressMount
, sourceAddressRoot
, sourceAddressRelativePath
, LoadedSource
, loadedSource
, loadedBytes
, loadedText
, loadedByteCount
, ImportRef
, importRef
, importPath
, importLocation
, SourceCandidate
, sourceCandidateMount
, sourceCandidatePath
, sourceCandidates
, attributeCanonicalSource
, resolveRoot
, resolveImport
, SourceSelectionMeasurements(..)
, resolveRootMeasured
, resolveImportMeasured
, loadResolvedSource
, resolveAndLoadRoot
, resolveAndLoadImport
, SourceLookup(..)
, SourceCycleStep
, sourceCycleStep
, cycleImporter
, cycleImport
, cycleImported
, RelativePathError(..)
, SourceError(..)
, renderSourceError
) where
import Base
import Control.DeepSeq (NFData)
import Control.Exception (Exception, IOException, displayException, try)
import Data.Bifunctor (first)
import Data.ByteString qualified as ByteString
import Data.Char (ord)
import Data.List qualified as List
import Data.Map.Strict qualified as Map
import Data.Set qualified as Set
import Data.Text qualified as Text
import Data.Text.Encoding qualified as Encoding
import Report.Location
( Location
, LocationRegistrationError(..)
, locationToText
)
import System.Directory qualified as Directory
import System.FilePath.Posix qualified as Posix
import System.Posix.Files qualified as PosixFiles
-- | Invocation-local name of a configured source mount.
newtype SourceMountId = SourceMountId Text
deriving stock (Show, Eq, Ord, Generic)
deriving newtype (NFData)
sourceMountId :: Text -> SourceMountId
sourceMountId = SourceMountId
sourceMountIdText :: SourceMountId -> Text
sourceMountIdText (SourceMountId ident) = ident
-- | Absolute canonical host path.
newtype CanonicalPath = CanonicalPath FilePath
deriving stock (Show, Eq, Ord, Generic)
deriving newtype (NFData)
canonicalPathFilePath :: CanonicalPath -> FilePath
canonicalPathFilePath (CanonicalPath path) = path
-- | Nonempty mount-root-relative POSIX path without @.@, @..@, or empty
-- components. A backslash is an ordinary filename character.
newtype SafeRelativePath = SafeRelativePath FilePath
deriving stock (Show, Eq, Ord, Generic)
deriving newtype (NFData)
safeRelativePathFilePath :: SafeRelativePath -> FilePath
safeRelativePathFilePath (SafeRelativePath path) = path
data RelativePathError
= EmptyRelativePath
| AbsoluteRelativePath
| EmptyPathComponent
| CurrentDirectoryComponent
| ParentDirectoryComponent
| NullPathCharacter
| NonUnicodeScalarPathCharacter
deriving stock (Show, Eq)
safeRelativePath :: FilePath -> Either RelativePathError SafeRelativePath
safeRelativePath path
| null path =
Left EmptyRelativePath
| Posix.isAbsolute path =
Left AbsoluteRelativePath
| '\0' `elem` path =
Left NullPathCharacter
| any (not . isUnicodeScalar) path =
Left NonUnicodeScalarPathCharacter
| any null components =
Left EmptyPathComponent
| "." `elem` components =
Left CurrentDirectoryComponent
| ".." `elem` components =
Left ParentDirectoryComponent
| otherwise =
Right (SafeRelativePath path)
where
components = splitPathComponents path
splitPathComponents :: FilePath -> [FilePath]
splitPathComponents path =
case break (== '/') path of
(component, []) ->
[component]
(component, _slash : rest) ->
component : splitPathComponents rest
data SourceMount = SourceMount
!SourceMountId
!CanonicalPath
deriving stock (Show, Eq)
sourceMountIdentifier :: SourceMount -> SourceMountId
sourceMountIdentifier (SourceMount ident _root) = ident
sourceMountRoot :: SourceMount -> CanonicalPath
sourceMountRoot (SourceMount _ident root) = root
-- | Validated ordered source mounts. Order controls candidate search only;
-- canonical ownership is determined independently.
newtype SourceMounts = SourceMounts (NonEmpty SourceMount)
deriving stock (Show, Eq)
sourceMountList :: SourceMounts -> [SourceMount]
sourceMountList (SourceMounts mounts) = toList mounts
data RootRequest
= SearchedRoot !SafeRelativePath
| ExistingRoot !CanonicalPath !FilePath
deriving stock (Show)
-- The exact-root spelling is diagnostic trivia and does not participate in
-- request equality.
instance Eq RootRequest where
SearchedRoot left == SearchedRoot right =
left == right
ExistingRoot left _leftSpelling == ExistingRoot right _rightSpelling =
left == right
_ == _ =
False
searchedRoot :: FilePath -> Either SourceError RootRequest
searchedRoot path =
SearchedRoot <$> first (InvalidSearchedRoot path) (safeRelativePath path)
-- | Validate and canonicalize an absolute spelling of an existing source.
existingRoot :: FilePath -> IO (Either SourceError RootRequest)
existingRoot path
| not (Posix.isAbsolute path) =
pure (Left (ExistingRootNotAbsolute path))
| otherwise = do
statusResult <- try (PosixFiles.getFileStatus path)
:: IO (Either IOException PosixFiles.FileStatus)
case statusResult of
Left err
| isDoesNotExistError err ->
pure (Left (ExistingRootUnavailable path))
| otherwise ->
pure
(Left
(ExistingRootInspectionFailed
path
(Text.pack (displayException err))))
Right status
| not (PosixFiles.isRegularFile status) -> do
canonicalized <-
canonicalize ExistingRootCanonicalizationFailed path
pure
(canonicalized >>= \canonical ->
Left (ExistingRootNotRegular path canonical))
| otherwise ->
fmap (\canonical -> ExistingRoot canonical path) <$>
canonicalize ExistingRootCanonicalizationFailed path
-- | Validate and canonicalize an existing source path without assigning it
-- to a source mount.
canonicalizeExistingSourcePath
:: FilePath
-> IO (Either SourceError CanonicalPath)
canonicalizeExistingSourcePath path =
fmap extract <$> existingRoot path
where
extract = \case
ExistingRoot canonical _spelling ->
canonical
SearchedRoot{} ->
impossible
"canonicalizeExistingSourcePath produced a searched root"
-- | The user-facing spelling retained only for diagnostics.
rootRequestSpelling :: RootRequest -> FilePath
rootRequestSpelling = \case
SearchedRoot path ->
safeRelativePathFilePath path
ExistingRoot _canonical spelling ->
spelling
data ResolvedSource = ResolvedSource
!CanonicalPath
!SourceMountId
!CanonicalPath
!SafeRelativePath
deriving stock (Show, Eq, Ord, Generic)
deriving anyclass (NFData)
resolvedSourceCanonicalPath :: ResolvedSource -> CanonicalPath
resolvedSourceCanonicalPath
(ResolvedSource path _mount _mountRoot _relative) =
path
resolvedSourceMount :: ResolvedSource -> SourceMountId
resolvedSourceMount
(ResolvedSource _path mount _mountRoot _relative) =
mount
-- | Canonical root selected for the source's durable namespace.
resolvedSourceMountRoot :: ResolvedSource -> CanonicalPath
resolvedSourceMountRoot
(ResolvedSource _path _mount mountRoot _relative) =
mountRoot
resolvedSourceRelativePath :: ResolvedSource -> SafeRelativePath
resolvedSourceRelativePath
(ResolvedSource _path _mount _mountRoot relative) =
relative
-- | Stable mount-relative spelling for locations in one resolved workspace.
-- This is derived from the selected source rather than its request or import
-- spelling.
resolvedSourceLocationPath :: ResolvedSource -> FilePath
resolvedSourceLocationPath =
safeRelativePathFilePath . resolvedSourceRelativePath
-- | The selected mount-relative address retained by the logical source graph.
--
-- This is an invocation-local physical address, not a module or theorem
-- identity.
data ResolvedSourceAddress = ResolvedSourceAddress
!SourceMountId
!CanonicalPath
!SafeRelativePath
deriving stock (Show, Eq, Ord, Generic)
deriving anyclass (NFData)
resolvedSourceAddress :: ResolvedSource -> ResolvedSourceAddress
resolvedSourceAddress source =
ResolvedSourceAddress
(resolvedSourceMount source)
(resolvedSourceMountRoot source)
(resolvedSourceRelativePath source)
sourceAddressMount :: ResolvedSourceAddress -> SourceMountId
sourceAddressMount
(ResolvedSourceAddress mount _mountRoot _relative) =
mount
-- | Canonical root carried from source selection.
sourceAddressRoot :: ResolvedSourceAddress -> CanonicalPath
sourceAddressRoot
(ResolvedSourceAddress _mount mountRoot _relative) =
mountRoot
sourceAddressRelativePath :: ResolvedSourceAddress -> SafeRelativePath
sourceAddressRelativePath
(ResolvedSourceAddress _mount _mountRoot relative) =
relative
data LoadedSource = LoadedSource
!ResolvedSource
!ByteString.ByteString
!Text
deriving stock (Show, Eq, Generic)
deriving anyclass (NFData)
loadedSource :: LoadedSource -> ResolvedSource
loadedSource (LoadedSource source _bytes _text) = source
loadedBytes :: LoadedSource -> ByteString.ByteString
loadedBytes (LoadedSource _source bytes _text) = bytes
loadedText :: LoadedSource -> Text
loadedText (LoadedSource _source _bytes text) = text
loadedByteCount :: LoadedSource -> Word64
loadedByteCount =
fromIntegral . ByteString.length . loadedBytes
data ImportRef = ImportRef
!SafeRelativePath
!Location
deriving stock (Show, Eq, Ord, Generic)
deriving anyclass (NFData)
importRef :: Location -> FilePath -> Either RelativePathError ImportRef
importRef location path =
flip ImportRef location <$> safeRelativePath path
importPath :: ImportRef -> SafeRelativePath
importPath (ImportRef path _location) = path
importLocation :: ImportRef -> Location
importLocation (ImportRef _path location) = location
data SourceCandidate = SourceCandidate
!SourceMountId
!FilePath
deriving stock (Show, Eq)
sourceCandidateMount :: SourceCandidate -> SourceMountId
sourceCandidateMount (SourceCandidate ident _path) = ident
sourceCandidatePath :: SourceCandidate -> FilePath
sourceCandidatePath (SourceCandidate _ident path) = path
-- | Candidate paths in configured precedence order.
sourceCandidates :: SourceMounts -> SafeRelativePath -> [SourceCandidate]
sourceCandidates mounts relative =
[ SourceCandidate
(sourceMountIdentifier mount)
(canonicalPathFilePath (sourceMountRoot mount)
Posix.</> safeRelativePathFilePath relative)
| mount <- sourceMountList mounts
]
data SourceLookup
= SearchedRootLookup !SafeRelativePath
| ImportedSourceLookup !ResolvedSource !ImportRef
deriving stock (Show, Eq)
data SourceCycleStep = SourceCycleStep
!ResolvedSource
!ImportRef
!ResolvedSource
deriving stock (Show, Eq)
sourceCycleStep
:: ResolvedSource
-> ImportRef
-> ResolvedSource
-> SourceCycleStep
sourceCycleStep = SourceCycleStep
cycleImporter :: SourceCycleStep -> ResolvedSource
cycleImporter (SourceCycleStep importer _reference _imported) = importer
cycleImport :: SourceCycleStep -> ImportRef
cycleImport (SourceCycleStep _importer reference _imported) = reference
cycleImported :: SourceCycleStep -> ResolvedSource
cycleImported (SourceCycleStep _importer _reference imported) = imported
data SourceError
= EmptySourceMountTable
| DuplicateSourceMountId !SourceMountId
| SourceMountCanonicalizationFailed !SourceMountId !FilePath !Text
| SourceMountInspectionFailed !SourceMountId !FilePath !Text
| CanonicalPathContainsNonUnicodeScalar !FilePath
| SourceMountNotDirectory
!SourceMountId
!FilePath
!CanonicalPath
| DuplicateCanonicalMountRoot
!CanonicalPath
!SourceMountId
!SourceMountId
| InvalidSearchedRoot !FilePath !RelativePathError
| ExistingRootNotAbsolute !FilePath
| ExistingRootUnavailable !FilePath
| ExistingRootCanonicalizationFailed !FilePath !Text
| ExistingRootInspectionFailed !FilePath !Text
| ExistingRootNotRegular !FilePath !CanonicalPath
| RootOutsideConfiguredMount !FilePath !CanonicalPath
| InvalidAttributedRelativePath
!CanonicalPath
!CanonicalPath
!RelativePathError
| SourceNotFound !SourceLookup ![SourceCandidate]
| SelectedSourceCanonicalizationFailed
!SourceLookup
!FilePath
!Text
| SelectedSourceInspectionFailed
!SourceLookup
!FilePath
!Text
| SelectedSourceNotRegular
!SourceLookup
!FilePath
!CanonicalPath
| InvalidImportPath
!ResolvedSource
!Location
!FilePath
!RelativePathError
| SourceReadFailed !ResolvedSource !Text
| SourceReadTargetNotRegular !ResolvedSource
| SourceDecodeError !ResolvedSource !Int
| SourceImportDiscoveryFailed !ResolvedSource !Text
| SourceLocationRegistrationFailed
!ResolvedSource
!LocationRegistrationError
| SourceImportCycle !(NonEmpty SourceCycleStep)
| PackagedPreludeSelectedAsOrdinarySource !ResolvedSource
| SourceGraphInvariantViolation !Text
deriving stock (Show, Eq)
instance Exception SourceError
renderSourceError :: SourceError -> Text
renderSourceError = \case
EmptySourceMountTable ->
"no source mounts are configured"
DuplicateSourceMountId mount ->
"source mount " <> quoteText (sourceMountIdText mount)
<> " is configured more than once"
SourceMountCanonicalizationFailed mount path reason ->
"could not resolve source mount "
<> quoteText (sourceMountIdText mount)
<> " at " <> quotePath path <> ": " <> reason
SourceMountInspectionFailed mount path reason ->
"could not inspect source mount "
<> quoteText (sourceMountIdText mount)
<> " at " <> quotePath path <> ": " <> reason
CanonicalPathContainsNonUnicodeScalar path ->
"canonical source path contains a non-Unicode scalar: "
<> quotePath path
SourceMountNotDirectory mount spelling canonical ->
"source mount " <> quoteText (sourceMountIdText mount)
<> " is not a directory: " <> quotePath spelling
<> " (resolved to "
<> quotePath (canonicalPathFilePath canonical) <> ")"
DuplicateCanonicalMountRoot canonical firstMount secondMount ->
"source mounts " <> quoteText (sourceMountIdText firstMount)
<> " and " <> quoteText (sourceMountIdText secondMount)
<> " resolve to the same directory "
<> quotePath (canonicalPathFilePath canonical)
InvalidSearchedRoot path problem ->
"invalid searched source " <> quotePath path <> ": "
<> renderRelativePathError problem
ExistingRootNotAbsolute path ->
"exact source path must be absolute: " <> quotePath path
ExistingRootUnavailable path ->
"exact source does not exist: " <> quotePath path
ExistingRootCanonicalizationFailed path reason ->
"could not resolve exact source " <> quotePath path
<> ": " <> reason
ExistingRootInspectionFailed path reason ->
"could not inspect exact source " <> quotePath path
<> ": " <> reason
ExistingRootNotRegular spelling canonical ->
"exact source is not a regular file: " <> quotePath spelling
<> " (resolved to "
<> quotePath (canonicalPathFilePath canonical) <> ")"
RootOutsideConfiguredMount spelling canonical ->
"exact source " <> quotePath spelling
<> " resolves outside every configured mount: "
<> quotePath (canonicalPathFilePath canonical)
InvalidAttributedRelativePath canonical root problem ->
"source " <> quotePath (canonicalPathFilePath canonical)
<> " cannot be represented relative to mount "
<> quotePath (canonicalPathFilePath root) <> ": "
<> renderRelativePathError problem
SourceNotFound lookup candidates ->
"source not found for " <> renderSourceLookup lookup
<> renderCandidates candidates
SelectedSourceCanonicalizationFailed lookup path reason ->
"could not resolve selected source " <> quotePath path
<> " for " <> renderSourceLookup lookup <> ": " <> reason
SelectedSourceInspectionFailed lookup path reason ->
"could not inspect selected source " <> quotePath path
<> " for " <> renderSourceLookup lookup <> ": " <> reason
SelectedSourceNotRegular lookup path canonical ->
"selected source for " <> renderSourceLookup lookup
<> " is not a regular file: " <> quotePath path
<> " (resolved to "
<> quotePath (canonicalPathFilePath canonical) <> ")"
InvalidImportPath importer location path problem ->
sourceLabel importer <> " at " <> locationToText location
<> " imports invalid path " <> quotePath path <> ": "
<> renderRelativePathError problem
SourceReadFailed source reason ->
"could not read " <> sourceLabel source <> ": " <> reason
SourceReadTargetNotRegular source ->
sourceLabel source <> " is no longer a regular file"
SourceDecodeError source offset ->
sourceLabel source <> " contains malformed UTF-8 at byte offset "
<> Text.pack (show offset)
SourceImportDiscoveryFailed source reason ->
"could not discover imports in " <> sourceLabel source
<> ": " <> reason
SourceLocationRegistrationFailed source FileIdSpaceExhausted ->
"could not register locations for " <> sourceLabel source
<> ": the file identifier space is exhausted"
SourceImportCycle steps ->
"source import cycle: "
<> Text.intercalate " -> "
[ sourceLabel (cycleImporter step)
<> " at "
<> locationToText
(importLocation (cycleImport step))
<> " imports "
<> sourceLabel (cycleImported step)
| step <- toList steps
]
PackagedPreludeSelectedAsOrdinarySource source ->
"the packaged final prelude cannot be used as ordinary source "
<> quotePath (resolvedSourceLocationPath source)
SourceGraphInvariantViolation reason ->
"source graph invariant failed: " <> reason
renderSourceLookup :: SourceLookup -> Text
renderSourceLookup = \case
SearchedRootLookup relative ->
"root " <> quotePath (safeRelativePathFilePath relative)
ImportedSourceLookup importer reference ->
"import " <> quotePath
(safeRelativePathFilePath (importPath reference))
<> " from " <> sourceLabel importer
<> " at " <> locationToText (importLocation reference)
renderCandidates :: [SourceCandidate] -> Text
renderCandidates = \case
[] ->
" (no candidate paths)"
candidates ->
"; searched "
<> Text.intercalate ", "
[ quoteText (sourceMountIdText (sourceCandidateMount candidate))
<> ":" <> quotePath (sourceCandidatePath candidate)
| candidate <- candidates
]
renderRelativePathError :: RelativePathError -> Text
renderRelativePathError = \case
EmptyRelativePath -> "the path is empty"
AbsoluteRelativePath -> "the path is absolute"
EmptyPathComponent -> "the path contains an empty component"
CurrentDirectoryComponent -> "the path contains a current-directory component"
ParentDirectoryComponent -> "the path contains a parent-directory component"
NullPathCharacter -> "the path contains a null character"
NonUnicodeScalarPathCharacter ->
"the path contains a non-Unicode scalar"
sourceLabel :: ResolvedSource -> Text
sourceLabel source =
sourceMountIdText (resolvedSourceMount source)
<> ":"
<> Text.pack
(safeRelativePathFilePath
(resolvedSourceRelativePath source))
quotePath :: FilePath -> Text
quotePath = Text.pack . show
quoteText :: Text -> Text
quoteText = Text.pack . show
-- | Canonicalize and validate the complete mount table before source
-- resolution. Missing mount directories are permitted: they simply cannot
-- supply a candidate in this invocation.
prepareSourceMounts
:: [(SourceMountId, FilePath)]
-> IO (Either SourceError SourceMounts)
prepareSourceMounts specifications =
case specifications of
[] ->
pure (Left EmptySourceMountTable)
_ ->
case firstDuplicate (fst <$> specifications) of
Just duplicateId ->
pure (Left (DuplicateSourceMountId duplicateId))
Nothing -> do
canonicalized <- traverse canonicalizeMount specifications
pure do
mounts <- sequence canonicalized
rejectDuplicateRoots mounts
case mounts of
[] ->
Left EmptySourceMountTable
firstMount : rest ->
Right (SourceMounts (firstMount :| rest))
canonicalizeMount
:: (SourceMountId, FilePath)
-> IO (Either SourceError SourceMount)
canonicalizeMount (ident, path) = do
canonicalized <- canonicalize
(\raw message -> SourceMountCanonicalizationFailed ident raw message)
path
case canonicalized of
Left err ->
pure (Left err)
Right root ->
inspectMount ident path root
inspectMount
:: SourceMountId
-> FilePath
-> CanonicalPath
-> IO (Either SourceError SourceMount)
inspectMount ident spelling root = do
result <- try (PosixFiles.getFileStatus (canonicalPathFilePath root))
:: IO (Either IOException PosixFiles.FileStatus)
pure case result of
Left err
| isDoesNotExistError err ->
Right (SourceMount ident root)
| otherwise ->
Left
(SourceMountInspectionFailed
ident
spelling
(Text.pack (displayException err)))
Right status
| PosixFiles.isDirectory status ->
Right (SourceMount ident root)
| otherwise ->
Left (SourceMountNotDirectory ident spelling root)
canonicalize
:: (FilePath -> Text -> SourceError)
-> FilePath
-> IO (Either SourceError CanonicalPath)
canonicalize makeError path = do
result <- try (Directory.canonicalizePath path)
:: IO (Either IOException FilePath)
pure case result of
Left err ->
Left (makeError path (Text.pack (displayException err)))
Right canonical ->
if all isUnicodeScalar canonical
then Right (CanonicalPath canonical)
else Left
(CanonicalPathContainsNonUnicodeScalar canonical)
isUnicodeScalar :: Char -> Bool
isUnicodeScalar character =
let codePoint = ord character
in codePoint < 0xd800
|| codePoint > 0xdfff
firstDuplicate :: Ord a => [a] -> Maybe a
firstDuplicate = go mempty
where
go _seen [] =
Nothing
go seen (value : values)
| value `Set.member` seen =
Just value
| otherwise =
go (Set.insert value seen) values
rejectDuplicateRoots :: [SourceMount] -> Either SourceError ()
rejectDuplicateRoots = go Map.empty
where
go _seen [] =
Right ()
go seen (mount : mounts) =
case Map.lookup root seen of
Just earlierId ->
Left (DuplicateCanonicalMountRoot root earlierId ident)
Nothing ->
go (Map.insert root ident seen) mounts
where
root = sourceMountRoot mount
ident = sourceMountIdentifier mount
-- This policy is kept here, beside the types that establish its invariants.
-- Loading uses it after canonicalizing an actual selected source.
attributeCanonicalSource
:: SourceMounts
-> CanonicalPath
-> Either SourceError ResolvedSource
attributeCanonicalSource mounts sourcePath =
case containingMounts of
[] ->
Left
(RootOutsideConfiguredMount
(canonicalPathFilePath sourcePath)
sourcePath)
firstMount : otherMounts -> do
let owner = foldl' chooseMoreSpecific firstMount otherMounts
ownerRoot = sourceMountRoot owner
ownerId = sourceMountIdentifier owner
relative <- first
(InvalidAttributedRelativePath ownerRoot sourcePath)
(safeRelativePath
(Posix.makeRelative
(canonicalPathFilePath ownerRoot)
(canonicalPathFilePath sourcePath)))
Right
(ResolvedSource
sourcePath
ownerId
ownerRoot
relative)
where
containingMounts =
List.filter
(\mount ->
pathComponents (sourceMountRoot mount)
`List.isPrefixOf` pathComponents sourcePath)
(sourceMountList mounts)
chooseMoreSpecific left right
| pathDepth (sourceMountRoot right) > pathDepth (sourceMountRoot left) =
right
| otherwise =
left
pathComponents :: CanonicalPath -> [FilePath]
pathComponents =
Posix.splitDirectories
. Posix.dropTrailingPathSeparator
. canonicalPathFilePath
pathDepth :: CanonicalPath -> Int
pathDepth = length . pathComponents
resolveAndLoadRoot
:: SourceMounts
-> RootRequest
-> IO (Either SourceError LoadedSource)
resolveAndLoadRoot mounts request =
resolveAndLoad (resolveRoot mounts request)
resolveAndLoadImport
:: SourceMounts
-> ResolvedSource
-> ImportRef
-> IO (Either SourceError LoadedSource)
resolveAndLoadImport mounts importer reference =
resolveAndLoad (resolveImport mounts importer reference)
resolveAndLoad
:: IO (Either SourceError ResolvedSource)
-> IO (Either SourceError LoadedSource)
resolveAndLoad resolve = do
resolved <- resolve
case resolved of
Left err ->
pure (Left err)
Right source ->
loadResolvedSource source
resolveRoot
:: SourceMounts
-> RootRequest
-> IO (Either SourceError ResolvedSource)
resolveRoot mounts request =
fmap fst <$> resolveRootMeasured mounts request
-- | High-level operations used to select successful searched sources.
-- These are resolver operations, not operating-system syscall counts.
data SourceSelectionMeasurements =
SourceSelectionMeasurements
{ sourceSelectionCandidateProbeCount :: !Int
, sourceSelectionCanonicalizationCount :: !Int
, sourceSelectionTargetInspectionCount :: !Int
}
deriving stock (Show, Eq)
instance Semigroup SourceSelectionMeasurements where
left <> right =
SourceSelectionMeasurements
{ sourceSelectionCandidateProbeCount =
sourceSelectionCandidateProbeCount left
+ sourceSelectionCandidateProbeCount right
, sourceSelectionCanonicalizationCount =
sourceSelectionCanonicalizationCount left
+ sourceSelectionCanonicalizationCount right
, sourceSelectionTargetInspectionCount =
sourceSelectionTargetInspectionCount left
+ sourceSelectionTargetInspectionCount right
}
instance Monoid SourceSelectionMeasurements where
mempty =
SourceSelectionMeasurements
{ sourceSelectionCandidateProbeCount = 0
, sourceSelectionCanonicalizationCount = 0
, sourceSelectionTargetInspectionCount = 0
}
resolveRootMeasured
:: SourceMounts
-> RootRequest
-> IO
(Either
SourceError
(ResolvedSource, SourceSelectionMeasurements))
resolveRootMeasured mounts = \case
SearchedRoot path ->
resolveSearchedMeasured mounts (SearchedRootLookup path) path
ExistingRoot canonical spelling ->
pure
((\source -> (source, mempty))
<$> attributeSelectedSource spelling mounts canonical)
resolveImport
:: SourceMounts
-> ResolvedSource
-> ImportRef
-> IO (Either SourceError ResolvedSource)
resolveImport mounts importer reference =
fmap fst
<$> resolveImportMeasured mounts importer reference
resolveImportMeasured
:: SourceMounts
-> ResolvedSource
-> ImportRef
-> IO
(Either
SourceError
(ResolvedSource, SourceSelectionMeasurements))
resolveImportMeasured mounts importer reference =
resolveSearchedMeasured
mounts
(ImportedSourceLookup importer reference)
(importPath reference)
resolveSearchedMeasured
:: SourceMounts
-> SourceLookup
-> SafeRelativePath
-> IO
(Either
SourceError
(ResolvedSource, SourceSelectionMeasurements))
resolveSearchedMeasured mounts lookupKind relative =
choose 0 (sourceCandidates mounts relative)
where
candidates = sourceCandidates mounts relative
choose _probeCount [] =
pure (Left (SourceNotFound lookupKind candidates))
choose previousProbeCount (candidate : rest) = do
let path = sourceCandidatePath candidate
probeCount = previousProbeCount + 1
statusResult <- try (PosixFiles.getSymbolicLinkStatus path)
:: IO (Either IOException PosixFiles.FileStatus)
case statusResult of
Left err
| isDoesNotExistError err ->
choose probeCount rest
| otherwise ->
pure
(Left
(SelectedSourceInspectionFailed
lookupKind
path
(Text.pack (displayException err))))
Right _status ->
fmap
(\source ->
( source
, SourceSelectionMeasurements
{ sourceSelectionCandidateProbeCount =
probeCount
, sourceSelectionCanonicalizationCount =
1
, sourceSelectionTargetInspectionCount =
1
}
))
<$> resolveCandidate mounts lookupKind candidate
resolveCandidate
:: SourceMounts
-> SourceLookup
-> SourceCandidate
-> IO (Either SourceError ResolvedSource)
resolveCandidate mounts lookupKind candidate = do
canonicalized <- canonicalize
(\path message ->
SelectedSourceCanonicalizationFailed lookupKind path message)
(sourceCandidatePath candidate)
case canonicalized of
Left err ->
pure (Left err)
Right canonical -> do
statusResult <- try
(PosixFiles.getFileStatus
(canonicalPathFilePath canonical))
:: IO (Either IOException PosixFiles.FileStatus)
pure case statusResult of
Left err ->
Left
(SelectedSourceInspectionFailed
lookupKind
(sourceCandidatePath candidate)
(Text.pack (displayException err)))
Right status
| not (PosixFiles.isRegularFile status) ->
Left
(SelectedSourceNotRegular
lookupKind
(sourceCandidatePath candidate)
canonical)
| otherwise ->
attributeSelectedSource
(sourceCandidatePath candidate)
mounts
canonical
attributeSelectedSource
:: FilePath
-> SourceMounts
-> CanonicalPath
-> Either SourceError ResolvedSource
attributeSelectedSource spelling mounts canonical =
first retainSpelling (attributeCanonicalSource mounts canonical)
where
retainSpelling = \case
RootOutsideConfiguredMount _defaultSpelling outside ->
RootOutsideConfiguredMount spelling outside
err ->
err
loadResolvedSource :: ResolvedSource -> IO (Either SourceError LoadedSource)
loadResolvedSource source = do
let path =
canonicalPathFilePath (resolvedSourceCanonicalPath source)
statusResult <- try (PosixFiles.getFileStatus path)
:: IO (Either IOException PosixFiles.FileStatus)
case statusResult of
Left err ->
pure
(Left
(SourceReadFailed
source
(Text.pack (displayException err))))
Right status
| not (PosixFiles.isRegularFile status) ->
pure (Left (SourceReadTargetNotRegular source))
| otherwise -> do
bytesResult <- try (ByteString.readFile path)
:: IO (Either IOException ByteString.ByteString)
pure case bytesResult of
Left err ->
Left
(SourceReadFailed
source
(Text.pack (displayException err)))
Right bytes ->
case Encoding.decodeUtf8' bytes of
Left _ ->
let (validPrefixLength, _state) =
Encoding.validateUtf8Chunk bytes
in
Left
(SourceDecodeError
source
validPrefixLength)
Right text ->
Right
(LoadedSource
source
bytes
text)
|