-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathImport.hs
More file actions
1360 lines (1099 loc) · 47.5 KB
/
Import.hs
File metadata and controls
1360 lines (1099 loc) · 47.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -Wall #-}
{-| Dhall lets you import external expressions located either in local files or
hosted on network endpoints.
To import a local file as an expression, just insert the path to the file,
prepending a @./@ if the path is relative to the current directory. For
example, if you create a file named @id@ with the following contents:
> $ cat id
> λ(a : Type) → λ(x : a) → x
Then you can use the file directly within a @dhall@ program just by
referencing the file's path:
> $ dhall
> ./id Bool True
> <Ctrl-D>
> Bool
>
> True
Imported expressions may contain imports of their own, too, which will
continue to be resolved. However, Dhall will prevent cyclic imports. For
example, if you had these two files:
> $ cat foo
> ./bar
> $ cat bar
> ./foo
... Dhall would throw the following exception if you tried to import @foo@:
> $ dhall
> ./foo
> ^D
> ↳ ./foo
> ↳ ./bar
>
> Cyclic import: ./foo
You can also import expressions hosted on network endpoints. Just use the
URL
> http://host[:port]/path
The compiler expects the downloaded expressions to be in the same format
as local files, specifically UTF8-encoded source code text.
For example, if our @id@ expression were hosted at @http://example.com/id@,
then we would embed the expression within our code using:
> http://example.com/id
You can also import expressions stored within environment variables using
@env:NAME@, where @NAME@ is the name of the environment variable. For
example:
> $ export FOO=1
> $ export BAR='"Hi"'
> $ export BAZ='λ(x : Bool) → x == False'
> $ dhall <<< "{ foo = env:FOO , bar = env:BAR , baz = env:BAZ }"
> { bar : Text, baz : ∀(x : Bool) → Bool, foo : Integer }
>
> { bar = "Hi", baz = λ(x : Bool) → x == False, foo = 1 }
If you wish to import the raw contents of an impoert as @Text@ then add
@as Text@ to the end of the import:
> $ dhall <<< "http://example.com as Text"
> Text
>
> "<!doctype html>\n<html>\n<head>\n <title>Example Domain</title>\n\n <meta
> charset=\"utf-8\" />\n <meta http-equiv=\"Content-type\" content=\"text/html
> ; charset=utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width,
> initial-scale=1\" />\n <style type=\"text/css\">\n body {\n backgro
> und-color: #f0f0f2;\n margin: 0;\n padding: 0;\n font-famil
> y: \"Open Sans\", \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n \n
> }\n div {\n width: 600px;\n margin: 5em auto;\n paddi
> ng: 50px;\n background-color: #fff;\n border-radius: 1em;\n }\n
> a:link, a:visited {\n color: #38488f;\n text-decoration: none;
> \n }\n @media (max-width: 700px) {\n body {\n background
> -color: #fff;\n }\n div {\n width: auto;\n m
> argin: 0 auto;\n border-radius: 0;\n padding: 1em;\n
> }\n }\n </style> \n</head>\n\n<body>\n<div>\n <h1>Example Domain</
> h1>\n <p>This domain is established to be used for illustrative examples in d
> ocuments. You may use this\n domain in examples without prior coordination or
> asking for permission.</p>\n <p><a href=\"http://www.iana.org/domains/exampl
> e\">More information...</a></p>\n</div>\n</body>\n</html>\n"
-}
module Dhall.Import (
-- * Import
load
, loadWithManager
, loadRelativeTo
, loadWithStatus
, loadWith
, localToPath
, hashExpression
, hashExpressionToCode
, writeExpressionToSemanticCache
, assertNoImports
, Manager
, defaultNewManager
, CacheWarning(..)
, Status(..)
, SemanticCacheMode(..)
, Chained
, chainedImport
, chainedFromLocalHere
, chainedChangeMode
, emptyStatus
, emptyStatusWithManager
, envOriginHeaders
, makeEmptyStatus
, remoteStatus
, remoteStatusWithManager
, fetchRemote
, stack
, cache
, Depends(..)
, graph
, remote
, toHeaders
, substitutions
, normalizer
, startingContext
, chainImport
, dependencyToFile
, ImportSemantics
, HTTPHeader
, Cycle(..)
, ReferentiallyOpaque(..)
, Imported(..)
, ImportResolutionDisabled(..)
, PrettyHttpException(..)
, MissingFile(..)
, MissingEnvironmentVariable(..)
, MissingImports(..)
, HashMismatch(..)
) where
import Control.Applicative (Alternative (..))
import Control.Exception
( Exception
, IOException
, SomeException
, toException
)
import Control.Monad.Catch (MonadCatch (catch), handle, throwM)
import Control.Monad.IO.Class (MonadIO (..))
import Control.Monad.Morph (hoist)
import Control.Monad.State.Strict (MonadState, StateT)
import Data.ByteString (ByteString)
import Data.List.NonEmpty (NonEmpty (..))
import Data.Text (Text)
import Data.Typeable (Typeable)
import Data.Void (Void, absurd)
import Dhall.TypeCheck (TypeError)
import Dhall.Syntax
( Chunks (..)
, Directory (..)
, Expr (..)
, File (..)
, FilePrefix (..)
, Import (..)
, ImportHashed (..)
, ImportMode (..)
, ImportType (..)
, URL (..)
, bindingExprs
, functionBindingExprs
, recordFieldExprs
)
import System.FilePath ((</>))
import Text.Megaparsec (SourcePos (SourcePos), mkPos)
#ifdef WITH_HTTP
import Dhall.Import.HTTP
#endif
import Dhall.Import.Headers
( normalizeHeaders
, originHeadersTypeExpr
, toHeaders
, toOriginHeaders
)
import Dhall.Import.Types
import Dhall.Parser
( ParseError (..)
, Parser (..)
, SourcedException (..)
, Src (..)
)
import Lens.Family.State.Strict (zoom)
import qualified Codec.CBOR.Write as Write
import qualified Codec.Serialise
import qualified Control.Exception as Exception
import qualified Control.Monad.State.Strict as State
import qualified Control.Monad.Trans.Maybe as Maybe
import qualified Data.ByteString
import qualified Data.ByteString.Lazy
import qualified Data.List.NonEmpty as NonEmpty
import qualified Data.Maybe as Maybe
import qualified Data.Text as Text
import qualified Data.Text.IO
import qualified Dhall.Binary
import qualified Dhall.Core as Core
import qualified Dhall.Crypto
import qualified Dhall.Map
import qualified Dhall.Parser
import qualified Dhall.Pretty.Internal
import qualified Dhall.Substitution
import qualified Dhall.Syntax as Syntax
import qualified Dhall.TypeCheck
import qualified System.AtomicWrite.Writer.ByteString.Binary as AtomicWrite.Binary
import qualified System.Directory as Directory
import qualified System.Environment
import qualified System.FilePath as FilePath
import qualified System.IO
import qualified System.Info
import qualified Text.Megaparsec
import qualified Text.Parser.Combinators
import qualified Text.Parser.Token
{- $setup
>>> import Dhall.Syntax
-}
-- | An import failed because of a cycle in the import graph
newtype Cycle = Cycle
{ cyclicImport :: Import -- ^ The offending cyclic import
}
deriving (Typeable)
instance Exception Cycle
instance Show Cycle where
show (Cycle import_) =
"\nCyclic import: " ++ Dhall.Pretty.Internal.prettyToString import_
{-| Dhall tries to ensure that all expressions hosted on network endpoints are
weakly referentially transparent, meaning roughly that any two clients will
compile the exact same result given the same URL.
To be precise, a strong interpretaton of referential transparency means that
if you compiled a URL you could replace the expression hosted at that URL
with the compiled result. Let's call this \"static linking\". Dhall (very
intentionally) does not satisfy this stronger interpretation of referential
transparency since \"statically linking\" an expression (i.e. permanently
resolving all imports) means that the expression will no longer update if
its dependencies change.
In general, either interpretation of referential transparency is not
enforceable in a networked context since one can easily violate referential
transparency with a custom DNS, but Dhall can still try to guard against
common unintentional violations. To do this, Dhall enforces that a
non-local import may not reference a local import.
Local imports are defined as:
* A file
* A URL with a host of @localhost@ or @127.0.0.1@
All other imports are defined to be non-local
-}
newtype ReferentiallyOpaque = ReferentiallyOpaque
{ opaqueImport :: Import -- ^ The offending opaque import
} deriving (Typeable)
instance Exception ReferentiallyOpaque
instance Show ReferentiallyOpaque where
show (ReferentiallyOpaque import_) =
"\nReferentially opaque import: " ++ Dhall.Pretty.Internal.prettyToString import_
-- | Extend another exception with the current import stack
data Imported e = Imported
{ importStack :: NonEmpty Chained -- ^ Imports resolved so far, in reverse order
, nested :: e -- ^ The nested exception
} deriving (Typeable)
instance Exception e => Exception (Imported e)
instance Show e => Show (Imported e) where
show (Imported canonicalizedImports e) =
concat (zipWith indent [0..] toDisplay)
++ "\n"
++ show e
where
indent n import_ =
"\n" ++ replicate (2 * n) ' ' ++ "↳ " ++ Dhall.Pretty.Internal.prettyToString import_
canonical = NonEmpty.toList canonicalizedImports
-- Tthe final (outermost) import is fake to establish the base
-- directory. Also, we need outermost-first.
toDisplay = drop 1 (reverse canonical)
-- | Exception thrown when an imported file is missing
newtype MissingFile = MissingFile FilePath
deriving (Typeable)
instance Exception MissingFile
instance Show MissingFile where
show (MissingFile path) =
"\n"
<> "\ESC[1;31mError\ESC[0m: Missing file "
<> path
-- | Exception thrown when an environment variable is missing
newtype MissingEnvironmentVariable = MissingEnvironmentVariable { name :: Text }
deriving (Typeable)
instance Exception MissingEnvironmentVariable
instance Show MissingEnvironmentVariable where
show MissingEnvironmentVariable{..} =
"\n"
<> "\ESC[1;31mError\ESC[0m: Missing environment variable\n"
<> "\n"
<> "↳ " <> Text.unpack name
-- | List of Exceptions we encounter while resolving Import Alternatives
newtype MissingImports = MissingImports [SomeException]
instance Exception MissingImports
instance Show MissingImports where
show (MissingImports []) =
"\n"
<> "\ESC[1;31mError\ESC[0m: No valid imports"
show (MissingImports [e]) = show e
show (MissingImports es) =
"\n"
<> "\ESC[1;31mError\ESC[0m: Failed to resolve imports. Error list:"
<> "\n"
<> concatMap (\e -> "\n" <> show e <> "\n") es
throwMissingImport :: (MonadCatch m, Exception e) => e -> m a
throwMissingImport e = throwM (MissingImports [toException e])
-- | Exception thrown when a HTTP url is imported but dhall was built without
-- the @with-http@ Cabal flag.
data CannotImportHTTPURL =
CannotImportHTTPURL
String
(Maybe [HTTPHeader])
deriving (Typeable)
instance Exception CannotImportHTTPURL
instance Show CannotImportHTTPURL where
show (CannotImportHTTPURL url _mheaders) =
"\n"
<> "\ESC[1;31mError\ESC[0m: Cannot import HTTP URL.\n"
<> "\n"
<> "Dhall was compiled without the 'with-http' flag.\n"
<> "\n"
<> "The requested URL was: "
<> url
<> "\n"
{-|
> canonicalize . canonicalize = canonicalize
> canonicalize (a <> b) = canonicalize (canonicalize a <> canonicalize b)
-}
class Semigroup path => Canonicalize path where
canonicalize :: path -> path
-- |
-- >>> canonicalize (Directory {components = ["..",".."]})
-- Directory {components = ["..",".."]}
instance Canonicalize Directory where
canonicalize (Directory []) = Directory []
canonicalize (Directory ("." : components₀)) =
canonicalize (Directory components₀)
canonicalize (Directory (".." : components₀)) =
case canonicalize (Directory components₀) of
Directory [] ->
Directory [ ".." ]
Directory (".." : components₁) ->
Directory (".." : ".." : components₁)
Directory (_ : components₁) ->
Directory components₁
canonicalize (Directory (component : components₀)) =
Directory (component : components₁)
where
Directory components₁ = canonicalize (Directory components₀)
instance Canonicalize File where
canonicalize (File { directory, .. }) =
File { directory = canonicalize directory, .. }
instance Canonicalize ImportType where
canonicalize (Local prefix file) =
Local prefix (canonicalize file)
canonicalize (Remote (URL {..})) =
Remote (URL { path = canonicalize path, headers = fmap (fmap canonicalize) headers, ..})
canonicalize (Env name) =
Env name
canonicalize Missing =
Missing
instance Canonicalize ImportHashed where
canonicalize (ImportHashed hash importType) =
ImportHashed hash (canonicalize importType)
instance Canonicalize Import where
canonicalize (Import importHashed importMode) =
Import (canonicalize importHashed) importMode
-- | Exception thrown when an integrity check fails
data HashMismatch = HashMismatch
{ expectedHash :: Dhall.Crypto.SHA256Digest
, actualHash :: Dhall.Crypto.SHA256Digest
} deriving (Typeable)
instance Exception HashMismatch
instance Show HashMismatch where
show HashMismatch{..} =
"\n"
<> "\ESC[1;31mError\ESC[0m: " <> makeHashMismatchMessage expectedHash actualHash
makeHashMismatchMessage :: Dhall.Crypto.SHA256Digest -> Dhall.Crypto.SHA256Digest -> String
makeHashMismatchMessage expectedHash actualHash =
"Import integrity check failed\n"
<> "\n"
<> "Expected hash:\n"
<> "\n"
<> "↳ " <> show expectedHash <> "\n"
<> "\n"
<> "Actual hash:\n"
<> "\n"
<> "↳ " <> show actualHash <> "\n"
-- | Construct the file path corresponding to a local import. If the import is
-- _relative_ then the resulting path is also relative.
localToPath :: MonadIO io => FilePrefix -> File -> io FilePath
localToPath prefix file_ = liftIO $ do
let File {..} = file_
let Directory {..} = directory
prefixPath <- case prefix of
Home ->
Directory.getHomeDirectory
Absolute ->
return "/"
Parent ->
return ".."
Here ->
return "."
let cs = map Text.unpack (file : components)
let cons component dir = dir </> component
return (foldr cons prefixPath cs)
-- | Given a `Local` import construct the corresponding unhashed `Chained`
-- import (interpreting relative path as relative to the current directory).
chainedFromLocalHere :: FilePrefix -> File -> ImportMode -> Chained
chainedFromLocalHere prefix file mode = Chained $
Import (ImportHashed Nothing (Local prefix (canonicalize file))) mode
-- | Adjust the import mode of a chained import
chainedChangeMode :: ImportMode -> Chained -> Chained
chainedChangeMode mode (Chained (Import importHashed _)) =
Chained (Import importHashed mode)
-- | Chain imports, also typecheck and normalize headers if applicable.
chainImport :: Chained -> Import -> StateT Status IO Chained
chainImport (Chained parent) child@(Import importHashed@(ImportHashed _ (Remote url)) _) = do
url' <- normalizeHeadersIn url
let child' = child { importHashed = importHashed { importType = Remote url' } }
return (Chained (canonicalize (parent <> child')))
chainImport (Chained parent) child =
return (Chained (canonicalize (parent <> child)))
-- | Load an import, resulting in a fully resolved, type-checked and normalised
-- expression. @loadImport@ handles the \"hot\" cache in @Status@ and defers
-- to @loadImportWithSemanticCache@ for imports that aren't in the @Status@
-- cache already.
loadImport :: Chained -> StateT Status IO ImportSemantics
loadImport import_ = do
Status {..} <- State.get
case Dhall.Map.lookup import_ _cache of
Just importSemantics -> return importSemantics
Nothing -> do
importSemantics <- loadImportWithSemanticCache import_
zoom cache (State.modify (Dhall.Map.insert import_ importSemantics))
return importSemantics
-- | Load an import from the 'semantic cache'. Defers to
-- @loadImportWithSemisemanticCache@ for imports that aren't frozen (and
-- therefore not cached semantically), as well as those that aren't cached yet.
loadImportWithSemanticCache :: Chained -> StateT Status IO ImportSemantics
loadImportWithSemanticCache
import_@(Chained (Import (ImportHashed Nothing _) _)) =
loadImportWithSemisemanticCache import_
loadImportWithSemanticCache
import_@(Chained (Import _ Location)) =
loadImportWithSemisemanticCache import_
loadImportWithSemanticCache
import_@(Chained (Import (ImportHashed (Just semanticHash) _) _)) = do
Status { .. } <- State.get
mCached <-
case _semanticCacheMode of
UseSemanticCache ->
zoom cacheWarning (fetchFromSemanticCache semanticHash)
IgnoreSemanticCache ->
pure Nothing
case mCached of
Just bytesStrict -> do
let actualHash = Dhall.Crypto.sha256Hash bytesStrict
if semanticHash == actualHash
then do
let bytesLazy = Data.ByteString.Lazy.fromStrict bytesStrict
importSemantics <- case Dhall.Binary.decodeExpression bytesLazy of
Left err -> throwMissingImport (Imported _stack err)
Right e -> return e
return (ImportSemantics {..})
else do
printWarning $
makeHashMismatchMessage semanticHash actualHash
<> "\n"
<> "The interpreter will attempt to fix the cached import\n"
fetch
Nothing -> fetch
where
fetch = do
ImportSemantics{ importSemantics } <- loadImportWithSemisemanticCache import_
let bytes = encodeExpression (Core.alphaNormalize importSemantics)
let actualHash = Dhall.Crypto.sha256Hash bytes
let expectedHash = semanticHash
if actualHash == expectedHash
then do
zoom cacheWarning (writeToSemanticCache semanticHash bytes)
else do
Status{ _stack } <- State.get
throwMissingImport (Imported _stack HashMismatch{..})
return ImportSemantics{..}
-- Fetch encoded normal form from "semantic cache"
fetchFromSemanticCache
:: (MonadState CacheWarning m, MonadCatch m, MonadIO m)
=> Dhall.Crypto.SHA256Digest
-> m (Maybe Data.ByteString.ByteString)
fetchFromSemanticCache expectedHash = Maybe.runMaybeT $ do
cacheFile <- getCacheFile "dhall" expectedHash
True <- liftIO (Directory.doesFileExist cacheFile)
liftIO (Data.ByteString.readFile cacheFile)
-- | Ensure that the given expression is present in the semantic cache. The
-- given expression should be alpha-beta-normal.
writeExpressionToSemanticCache :: Expr Void Void -> IO ()
writeExpressionToSemanticCache expression =
-- Defaulting to not displaying the warning is for backwards compatibility
-- with the old behavior
State.evalStateT (writeToSemanticCache hash bytes) CacheWarned
where
bytes = encodeExpression expression
hash = Dhall.Crypto.sha256Hash bytes
writeToSemanticCache
:: (MonadState CacheWarning m, MonadCatch m, MonadIO m)
=> Dhall.Crypto.SHA256Digest
-> Data.ByteString.ByteString
-> m ()
writeToSemanticCache hash bytes = do
_ <- Maybe.runMaybeT $ do
cacheFile <- getCacheFile "dhall" hash
liftIO (AtomicWrite.Binary.atomicWriteFile cacheFile bytes)
return ()
-- Check the "semi-semantic" disk cache, otherwise typecheck and normalise from
-- scratch.
loadImportWithSemisemanticCache
:: Chained -> StateT Status IO ImportSemantics
loadImportWithSemisemanticCache (Chained (Import (ImportHashed _ importType) Code)) = do
text <- fetchFresh importType
Status {..} <- State.get
path <- case importType of
Local prefix file -> liftIO $ do
path <- localToPath prefix file
absolutePath <- Directory.makeAbsolute path
return absolutePath
Remote url -> do
let urlText = Core.pretty (url { headers = Nothing })
return (Text.unpack urlText)
Env env -> return $ Text.unpack env
Missing -> throwM (MissingImports [])
let parser = unParser $ do
Text.Parser.Token.whiteSpace
r <- Dhall.Parser.expr
Text.Parser.Combinators.eof
return r
parsedImport <- case Text.Megaparsec.parse parser path text of
Left errInfo ->
throwMissingImport (Imported _stack (ParseError errInfo text))
Right expr -> return expr
resolvedExpr <- loadWith parsedImport -- we load imports recursively here
-- Check the semi-semantic cache. See
-- https://github.com/dhall-lang/dhall-haskell/issues/1098 for the reasoning
-- behind semi-semantic caching.
let semisemanticHash = computeSemisemanticHash (Core.denote resolvedExpr)
mCached <- zoom cacheWarning (fetchFromSemisemanticCache semisemanticHash)
importSemantics <- case mCached of
Just bytesStrict -> do
let bytesLazy = Data.ByteString.Lazy.fromStrict bytesStrict
importSemantics <- case Dhall.Binary.decodeExpression bytesLazy of
Left err -> throwMissingImport (Imported _stack err)
Right sem -> return sem
return importSemantics
Nothing -> do
let substitutedExpr =
Dhall.Substitution.substitute resolvedExpr _substitutions
case Core.shallowDenote parsedImport of
-- If this import trivially wraps another import, we can skip
-- the type-checking and normalization step as the transitive
-- import was already type-checked and normalized
Embed _ ->
return (Core.denote substitutedExpr)
_ -> do
case Dhall.TypeCheck.typeWith _startingContext substitutedExpr of
Left err -> throwMissingImport (Imported _stack err)
Right _ -> return ()
let betaNormal =
Core.normalizeWith _normalizer substitutedExpr
let bytes = encodeExpression betaNormal
zoom cacheWarning (writeToSemisemanticCache semisemanticHash bytes)
return betaNormal
return (ImportSemantics {..})
-- `as Text` imports aren't cached since they are well-typed and normal by
-- construction
loadImportWithSemisemanticCache (Chained (Import (ImportHashed _ importType) RawText)) = do
text <- fetchFresh importType
-- importSemantics is alpha-beta-normal by construction!
let importSemantics = TextLit (Chunks [] text)
return (ImportSemantics {..})
-- `as Location` imports aren't cached since they are well-typed and normal by
-- construction
loadImportWithSemisemanticCache (Chained (Import (ImportHashed _ importType) Location)) = do
let locationType = Union $ Dhall.Map.fromList
[ ("Environment", Just Text)
, ("Remote", Just Text)
, ("Local", Just Text)
, ("Missing", Nothing)
]
-- importSemantics is alpha-beta-normal by construction!
let importSemantics = case importType of
Missing -> Field locationType $ Core.makeFieldSelection "Missing"
local@(Local _ _) ->
App (Field locationType $ Core.makeFieldSelection "Local")
(TextLit (Chunks [] (Core.pretty local)))
remote_@(Remote _) ->
App (Field locationType $ Core.makeFieldSelection "Remote")
(TextLit (Chunks [] (Core.pretty remote_)))
Env env ->
App (Field locationType $ Core.makeFieldSelection "Environment")
(TextLit (Chunks [] (Core.pretty env)))
return (ImportSemantics {..})
-- The semi-semantic hash of an expression is computed from the fully resolved
-- AST (without normalising or type-checking it first). See
-- https://github.com/dhall-lang/dhall-haskell/issues/1098 for further
-- discussion.
computeSemisemanticHash :: Expr Void Void -> Dhall.Crypto.SHA256Digest
computeSemisemanticHash resolvedExpr = hashExpression resolvedExpr
-- Fetch encoded normal form from "semi-semantic cache"
fetchFromSemisemanticCache
:: (MonadState CacheWarning m, MonadCatch m, MonadIO m)
=> Dhall.Crypto.SHA256Digest
-> m (Maybe Data.ByteString.ByteString)
fetchFromSemisemanticCache semisemanticHash = Maybe.runMaybeT $ do
cacheFile <- getCacheFile "dhall-haskell" semisemanticHash
True <- liftIO (Directory.doesFileExist cacheFile)
liftIO (Data.ByteString.readFile cacheFile)
writeToSemisemanticCache
:: (MonadState CacheWarning m, MonadCatch m, MonadIO m)
=> Dhall.Crypto.SHA256Digest
-> Data.ByteString.ByteString
-> m ()
writeToSemisemanticCache semisemanticHash bytes = do
_ <- Maybe.runMaybeT $ do
cacheFile <- getCacheFile "dhall-haskell" semisemanticHash
liftIO (AtomicWrite.Binary.atomicWriteFile cacheFile bytes)
return ()
-- Fetch source code directly from disk/network
fetchFresh :: ImportType -> StateT Status IO Text
fetchFresh (Local prefix file) = do
Status { _stack } <- State.get
path <- liftIO $ localToPath prefix file
exists <- liftIO $ Directory.doesFileExist path
if exists
then liftIO $ Data.Text.IO.readFile path
else throwMissingImport (Imported _stack (MissingFile path))
fetchFresh (Remote url) = do
Status { _remote } <- State.get
_remote url
fetchFresh (Env env) = do
Status { _stack } <- State.get
x <- liftIO $ System.Environment.lookupEnv (Text.unpack env)
case x of
Just string ->
return (Text.pack string)
Nothing ->
throwMissingImport (Imported _stack (MissingEnvironmentVariable env))
fetchFresh Missing = throwM (MissingImports [])
fetchRemote :: URL -> StateT Status IO Data.Text.Text
#ifndef WITH_HTTP
fetchRemote (url@URL { headers = maybeHeadersExpression }) = do
let maybeHeaders = fmap toHeaders maybeHeadersExpression
let urlString = Text.unpack (Core.pretty url)
Status { _stack } <- State.get
throwMissingImport (Imported _stack (CannotImportHTTPURL urlString maybeHeaders))
#else
fetchRemote url = do
zoom remote (State.put fetchFromHTTP)
fetchFromHTTP url
where
fetchFromHTTP :: URL -> StateT Status IO Data.Text.Text
fetchFromHTTP (url'@URL { headers = maybeHeadersExpression }) = do
let maybeHeaders = fmap toHeaders maybeHeadersExpression
fetchFromHttpUrl url' maybeHeaders
#endif
getCacheFile
:: (MonadCatch m, Alternative m, MonadState CacheWarning m, MonadIO m)
=> FilePath -> Dhall.Crypto.SHA256Digest -> m FilePath
getCacheFile cacheName hash = do
cacheDirectory <- getOrCreateCacheDirectory cacheName
let cacheFile = cacheDirectory </> ("1220" <> show hash)
return cacheFile
getOrCreateCacheDirectory
:: (MonadCatch m, Alternative m, MonadState CacheWarning m, MonadIO m)
=> FilePath -> m FilePath
getOrCreateCacheDirectory cacheName = do
let warn message = do
cacheWarningStatus <- State.get
case cacheWarningStatus of
CacheWarned -> printWarning message
CacheNotWarned -> return ()
State.put CacheWarned
empty
let handler action dir (ioex :: IOException) = do
let ioExMsg =
"When trying to " <> action <> ":\n"
<> "\n"
<> "↳ " <> dir <> "\n"
<> "\n"
<> "... the following exception was thrown:\n"
<> "\n"
<> "↳ " <> show ioex <> "\n"
warn ioExMsg
let setPermissions dir = do
let private = transform Directory.emptyPermissions
where
transform =
Directory.setOwnerReadable True
. Directory.setOwnerWritable True
. Directory.setOwnerSearchable True
catch
(liftIO (Directory.setPermissions dir private))
(handler "correct the permissions for" dir)
let assertPermissions dir = do
let accessible path =
Directory.readable path
&& Directory.writable path
&& Directory.searchable path
permissions <-
catch (liftIO (Directory.getPermissions dir))
(handler "get permissions of" dir)
if accessible permissions
then
return ()
else do
let render f = if f permissions then "✓" else "✗"
let message =
"The directory:\n"
<> "\n"
<> "↳ " <> dir <> "\n"
<> "\n"
<> "... does not give you permission to read, write, or search files.\n\n"
<> "\n"
<> "The directory's current permissions are:\n"
<> "\n"
<> "• " <> render Directory.readable <> " readable\n"
<> "• " <> render Directory.writable <> " writable\n"
<> "• " <> render Directory.searchable <> " searchable\n"
warn message
let existsDirectory dir =
catch (liftIO (Directory.doesDirectoryExist dir))
(handler "check the existence of" dir)
let existsFile path =
catch (liftIO (Directory.doesFileExist path))
(handler "check the existence of" path)
let createDirectory dir =
catch (liftIO (Directory.createDirectory dir))
(handler "create" dir)
let assertDirectory dir = do
existsDir <- existsDirectory dir
if existsDir
then
assertPermissions dir
else do
existsFile' <- existsFile dir
if existsFile'
then do
let message =
"The given path:\n"
<> "\n"
<> "↳ " <> dir <> "\n"
<> "\n"
<> "... already exists but is not a directory.\n"
warn message
else do
assertDirectory (FilePath.takeDirectory dir)
createDirectory dir
setPermissions dir
cacheBaseDirectory <- getCacheBaseDirectory
let directory = cacheBaseDirectory </> cacheName
let message =
"Could not get or create the default cache directory:\n"
<> "\n"
<> "↳ " <> directory <> "\n"
<> "\n"
<> "You can enable caching by creating it if needed and setting read,\n"
<> "write and search permissions on it or providing another cache base\n"
<> "directory by setting the $XDG_CACHE_HOME environment variable.\n"
<> "\n"
assertDirectory directory <|> warn message
return directory
getCacheBaseDirectory
:: (MonadState CacheWarning m, Alternative m, MonadIO m) => m FilePath
getCacheBaseDirectory = alternative₀ <|> alternative₁ <|> alternative₂
where
alternative₀ = do
maybeXDGCacheHome <-
liftIO (System.Environment.lookupEnv "XDG_CACHE_HOME")
case maybeXDGCacheHome of
Just xdgCacheHome -> return xdgCacheHome
Nothing -> empty
alternative₁
| isWindows = do
maybeLocalAppDirectory <-
liftIO (System.Environment.lookupEnv "LOCALAPPDATA")
case maybeLocalAppDirectory of
Just localAppDirectory -> return localAppDirectory
Nothing -> empty
| otherwise = do
maybeHomeDirectory <-
liftIO (System.Environment.lookupEnv "HOME")
case maybeHomeDirectory of
Just homeDirectory -> return (homeDirectory </> ".cache")
Nothing -> empty
where isWindows = System.Info.os == "mingw32"
alternative₂ = do
cacheWarningStatus <- State.get
let message =
"\n"
<> "\ESC[1;33mWarning\ESC[0m: "
<> "Could not locate a cache base directory from the environment.\n"
<> "\n"
<> "You can provide a cache base directory by pointing the $XDG_CACHE_HOME\n"
<> "environment variable to a directory with read and write permissions.\n"
case cacheWarningStatus of
CacheNotWarned ->
liftIO (System.IO.hPutStrLn System.IO.stderr message)
CacheWarned ->
return ()
State.put CacheWarned
empty