-
Notifications
You must be signed in to change notification settings - Fork 62
/
Interpreter.hs
4765 lines (4175 loc) · 182 KB
/
Interpreter.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{- |
Module : SAWScript.Interpreter
Description : Interpreter for SAW-Script files and statements.
License : BSD3
Maintainer : huffman
Stability : provisional
-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
#if !MIN_VERSION_base(4,8,0)
{-# LANGUAGE OverlappingInstances #-}
#endif
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE NondecreasingIndentation #-}
-- See Note [-Wincomplete-uni-patterns and irrefutable patterns] in SAWScript.MGU
{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
module SAWScript.Interpreter
( interpretStmt
, interpretFile
, processFile
, buildTopLevelEnv
, primDocEnv
, InteractiveMonad(..)
)
where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
import Data.Traversable hiding ( mapM )
#endif
import Control.Applicative ( (<|>) )
import qualified Control.Exception as X
import Control.Monad (unless, (>=>), when)
import Control.Monad.IO.Class (liftIO)
import qualified Data.ByteString as BS
import qualified Data.Map as Map
import Data.Map ( Map )
import qualified Data.Set as Set
import Data.Set ( Set )
import qualified Data.Text as Text
import System.Directory (getCurrentDirectory, setCurrentDirectory, canonicalizePath)
import System.FilePath (takeDirectory)
import System.Environment (lookupEnv)
import System.Process (readProcess)
import qualified SAWScript.AST as SS
import qualified SAWScript.Position as SS
import SAWScript.AST (Located(..),Import(..))
import SAWScript.Bisimulation
import SAWScript.Builtins
import SAWScript.Exceptions (failTypecheck)
import qualified SAWScript.Import
import SAWScript.HeapsterBuiltins
import SAWScript.JavaExpr
import SAWScript.LLVMBuiltins
import SAWScript.Options
import SAWScript.Lexer (lexSAW)
import SAWScript.MGU (checkDecl, checkDeclGroup)
import SAWScript.Parser (parseSchema)
import SAWScript.TopLevel
import SAWScript.Utils
import SAWScript.Value
import SAWScript.SolverCache
import SAWScript.SolverVersions
import SAWScript.Proof (emptyTheoremDB)
import SAWScript.Prover.Rewrite(basic_ss)
import SAWScript.Prover.Exporter
import SAWScript.Prover.MRSolver (emptyMREnv, emptyRefnset)
import SAWScript.Yosys
import Verifier.SAW.Conversion
--import Verifier.SAW.PrettySExp
import Verifier.SAW.Prim (rethrowEvalError)
import Verifier.SAW.Rewriter (emptySimpset, rewritingSharedContext, scSimpset)
import Verifier.SAW.SharedTerm
import Verifier.SAW.TypedAST hiding (FlatTermF(..))
import Verifier.SAW.TypedTerm
import qualified Verifier.SAW.CryptolEnv as CEnv
import qualified Verifier.SAW.Cryptol.Monadify as Monadify
import qualified Lang.JVM.Codebase as JCB
import qualified Verifier.SAW.Cryptol.Prelude as CryptolSAW
-- Crucible
import qualified Lang.Crucible.JVM as CJ
import Mir.Intrinsics (MIR)
import qualified Mir.Mir as Mir
import qualified SAWScript.Crucible.Common as CC
import qualified SAWScript.Crucible.Common.MethodSpec as CMS
import qualified SAWScript.Crucible.JVM.BuiltinsJVM as CJ
import SAWScript.Crucible.LLVM.Builtins
import SAWScript.Crucible.JVM.Builtins
import SAWScript.Crucible.MIR.Builtins
import SAWScript.Crucible.LLVM.X86
import SAWScript.Crucible.LLVM.Boilerplate
import SAWScript.Crucible.LLVM.Skeleton.Builtins
import SAWScript.Crucible.LLVM.FFI
import qualified SAWScript.Crucible.LLVM.MethodSpecIR as CIR
-- Cryptol
import qualified Cryptol.Eval as V (PPOpts(..))
import qualified Cryptol.Backend.Monad as V (runEval)
import qualified Cryptol.Eval.Value as V (defaultPPOpts, ppValue)
import qualified Cryptol.Eval.Concrete as V (Concrete(..))
import qualified Prettyprinter.Render.Text as PP (putDoc)
import SAWScript.AutoMatch
import qualified Lang.Crucible.FunctionHandle as Crucible
-- Environment -----------------------------------------------------------------
bindPatternLocal :: SS.Pattern -> Maybe SS.Schema -> Value -> LocalEnv -> LocalEnv
bindPatternLocal pat ms v env =
case pat of
SS.PWild _ -> env
SS.PVar x mt -> extendLocal x (ms <|> (SS.tMono <$> mt)) Nothing v env
SS.PTuple ps ->
case v of
VTuple vs -> foldr ($) env (zipWith3 bindPatternLocal ps mss vs)
where mss = case ms of
Nothing -> repeat Nothing
Just (SS.Forall ks (SS.TyCon (SS.TupleCon _) ts))
-> [ Just (SS.Forall ks t) | t <- ts ]
Just t -> error ("bindPatternLocal: expected tuple type " ++ show t)
_ -> error "bindPatternLocal: expected tuple value"
SS.LPattern _ pat' -> bindPatternLocal pat' ms v env
bindPatternEnv :: SS.Pattern -> Maybe SS.Schema -> Value -> TopLevelRW -> TopLevel TopLevelRW
bindPatternEnv pat ms v env =
case pat of
SS.PWild _ -> pure env
SS.PVar x mt ->
do sc <- getSharedContext
liftIO $ extendEnv sc x (ms <|> (SS.tMono <$> mt)) Nothing v env
SS.PTuple ps ->
case v of
VTuple vs -> foldr (=<<) (pure env) (zipWith3 bindPatternEnv ps mss vs)
where mss = case ms of
Nothing -> repeat Nothing
Just (SS.Forall ks (SS.TyCon (SS.TupleCon _) ts))
-> [ Just (SS.Forall ks t) | t <- ts ]
Just t -> error ("bindPatternEnv: expected tuple type " ++ show t)
_ -> error "bindPatternEnv: expected tuple value"
SS.LPattern _ pat' -> bindPatternEnv pat' ms v env
-- Interpretation of SAWScript -------------------------------------------------
interpret :: SS.Expr -> TopLevel Value
interpret expr =
let ?fileReader = BS.readFile in
case expr of
SS.Bool b -> return $ VBool b
SS.String s -> return $ VString (Text.pack s)
SS.Int z -> return $ VInteger z
SS.Code str -> do sc <- getSharedContext
cenv <- fmap rwCryptol getMergedEnv
--io $ putStrLn $ "Parsing code: " ++ show str
--showCryptolEnv' cenv
t <- io $ CEnv.parseTypedTerm sc cenv
$ locToInput str
return (toValue t)
SS.CType str -> do cenv <- fmap rwCryptol getMergedEnv
s <- io $ CEnv.parseSchema cenv
$ locToInput str
return (toValue s)
SS.Array es -> VArray <$> traverse interpret es
SS.Block stmts -> interpretStmts stmts
SS.Tuple es -> VTuple <$> traverse interpret es
SS.Record bs -> VRecord <$> traverse interpret bs
SS.Index e1 e2 -> do a <- interpret e1
i <- interpret e2
return (indexValue a i)
SS.Lookup e n -> do a <- interpret e
return (lookupValue a n)
SS.TLookup e i -> do a <- interpret e
return (tupleLookupValue a i)
SS.Var x -> do rw <- getMergedEnv
case Map.lookup x (rwValues rw) of
Nothing -> fail $ "unknown variable: " ++ SS.getVal x
Just v -> return (addTrace (show x) v)
SS.Function pat e -> do env <- getLocalEnv
let f v = withLocalEnv (bindPatternLocal pat Nothing v env) (interpret e)
return $ VLambda f
SS.Application e1 e2 -> do v1 <- interpret e1
v2 <- interpret e2
case v1 of
VLambda f -> f v2
_ -> fail $ "interpret Application: " ++ show v1
SS.Let dg e -> do env' <- interpretDeclGroup dg
withLocalEnv env' (interpret e)
SS.TSig e _ -> interpret e
SS.IfThenElse e1 e2 e3 -> do v1 <- interpret e1
case v1 of
VBool b -> interpret (if b then e2 else e3)
_ -> fail $ "interpret IfThenElse: " ++ show v1
SS.LExpr _ e -> interpret e
locToInput :: Located String -> CEnv.InputText
locToInput l = CEnv.InputText { CEnv.inpText = getVal l
, CEnv.inpFile = file
, CEnv.inpLine = ln
, CEnv.inpCol = col + 2 -- for dropped }}
}
where
(file,ln,col) =
case locatedPos l of
SS.Range f sl sc _ _ -> (f,sl, sc)
SS.PosInternal s -> (s,1,1)
SS.PosREPL -> ("<interactive>", 1, 1)
SS.Unknown -> ("Unknown", 1, 1)
interpretDecl :: LocalEnv -> SS.Decl -> TopLevel LocalEnv
interpretDecl env (SS.Decl _ pat mt expr) = do
v <- interpret expr
return (bindPatternLocal pat mt v env)
interpretFunction :: LocalEnv -> SS.Expr -> Value
interpretFunction env expr =
case expr of
SS.Function pat e -> VLambda f
where f v = withLocalEnv (bindPatternLocal pat Nothing v env) (interpret e)
SS.TSig e _ -> interpretFunction env e
_ -> error "interpretFunction: not a function"
interpretDeclGroup :: SS.DeclGroup -> TopLevel LocalEnv
interpretDeclGroup (SS.NonRecursive d) =
do env <- getLocalEnv
interpretDecl env d
interpretDeclGroup (SS.Recursive ds) =
do env <- getLocalEnv
let addDecl (SS.Decl _ pat mty e) = bindPatternLocal pat mty (interpretFunction env' e)
env' = foldr addDecl env ds
return env'
interpretStmts :: [SS.Stmt] -> TopLevel Value
interpretStmts stmts =
let ?fileReader = BS.readFile in
case stmts of
[] -> fail "empty block"
[SS.StmtBind pos (SS.PWild _) _ e] -> withPosition pos (interpret e)
SS.StmtBind pos pat _mcxt e : ss ->
do env <- getLocalEnv
v1 <- withPosition pos (interpret e)
let f v = withLocalEnv (bindPatternLocal pat Nothing v env) (interpretStmts ss)
bindValue pos v1 (VLambda f)
SS.StmtLet _ bs : ss -> interpret (SS.Let bs (SS.Block ss))
SS.StmtCode _ s : ss ->
do sc <- getSharedContext
rw <- getMergedEnv
ce' <- io $ CEnv.parseDecls sc (rwCryptol rw) $ locToInput s
-- FIXME: Local bindings get saved into the global cryptol environment here.
-- We should change parseDecls to return only the new bindings instead.
putTopLevelRW $ rw{rwCryptol = ce'}
interpretStmts ss
SS.StmtImport _ _ : _ ->
do fail "block import unimplemented"
SS.StmtTypedef _ name ty : ss ->
do env <- getLocalEnv
let env' = LocalTypedef (getVal name) ty : env
withLocalEnv env' (interpretStmts ss)
stmtInterpreter :: StmtInterpreter
stmtInterpreter ro rw stmts =
fst <$> runTopLevel (withLocalEnv emptyLocal (interpretStmts stmts)) ro rw
processStmtBind ::
InteractiveMonad m =>
Bool ->
SS.Pattern ->
Maybe SS.Type ->
SS.Expr ->
m ()
processStmtBind printBinds pat _mc expr = do -- mx mt
let (mx, mt) = case pat of
SS.PWild t -> (Nothing, t)
SS.PVar x t -> (Just x, t)
_ -> (Nothing, Nothing)
let it = SS.Located "it" "it" SS.PosREPL
let lname = maybe it id mx
ctx <- SS.tContext <$> getMonadContext
let expr' = case mt of
Nothing -> expr
Just t -> SS.TSig expr (SS.tBlock ctx t)
let decl = SS.Decl (SS.getPos expr) pat Nothing expr'
rw <- liftTopLevel getMergedEnv
let opts = rwPPOpts rw
~(SS.Decl _ _ (Just schema) expr'') <- liftTopLevel $
either failTypecheck return $ checkDecl (rwTypes rw) (rwTypedef rw) decl
val <- liftTopLevel $ interpret expr''
-- Run the resulting TopLevel action.
(result, ty) <-
case schema of
SS.Forall [] t ->
case t of
SS.TyCon SS.BlockCon [c, t'] | c == ctx -> do
result <- actionFromValue val
return (result, t')
_ -> return (val, t)
_ -> fail $ "Not a monomorphic type: " ++ SS.pShow schema
--io $ putStrLn $ "Top-level bind: " ++ show mx
--showCryptolEnv
-- Print non-unit result if it was not bound to a variable
case pat of
SS.PWild _ | printBinds && not (isVUnit result) ->
liftTopLevel $
do nenv <- io . scGetNamingEnv =<< getSharedContext
printOutLnTop Info (showsPrecValue opts nenv 0 result "")
_ -> return ()
-- Print function type if result was a function
case ty of
SS.TyCon SS.FunCon _ ->
liftTopLevel $ printOutLnTop Info $ getVal lname ++ " : " ++ SS.pShow ty
_ -> return ()
liftTopLevel $
do rw' <- getTopLevelRW
putTopLevelRW =<< bindPatternEnv pat (Just (SS.tMono ty)) result rw'
class (Monad m, MonadFail m) => InteractiveMonad m where
liftTopLevel :: TopLevel a -> m a
withTopLevel :: (forall b. TopLevel b -> TopLevel b) -> m a -> m a
actionFromValue :: FromValue a => Value -> m a
getMonadContext :: m SS.Context
instance InteractiveMonad TopLevel where
liftTopLevel m = m
withTopLevel f m = f m
actionFromValue = fromValue
getMonadContext = return SS.TopLevel
instance InteractiveMonad ProofScript where
liftTopLevel m = scriptTopLevel m
withTopLevel f (ProofScript m) = ProofScript (underExceptT (underStateT f) m)
actionFromValue = fromValue
getMonadContext = return SS.ProofScript
-- | Interpret a block-level statement in the TopLevel monad.
interpretStmt :: InteractiveMonad m =>
Bool {-^ whether to print non-unit result values -} ->
SS.Stmt ->
m ()
interpretStmt printBinds stmt =
let ?fileReader = BS.readFile in
case stmt of
SS.StmtBind pos pat mc expr ->
withTopLevel (withPosition pos) (processStmtBind printBinds pat mc expr)
SS.StmtLet _ dg ->
liftTopLevel $
do rw <- getTopLevelRW
dg' <- either failTypecheck return $
checkDeclGroup (rwTypes rw) (rwTypedef rw) dg
env <- interpretDeclGroup dg'
withLocalEnv env getMergedEnv >>= putTopLevelRW
SS.StmtCode _ lstr ->
liftTopLevel $
do rw <- getTopLevelRW
sc <- getSharedContext
--io $ putStrLn $ "Processing toplevel code: " ++ show lstr
--showCryptolEnv
cenv' <- io $ CEnv.parseDecls sc (rwCryptol rw) $ locToInput lstr
putTopLevelRW $ rw { rwCryptol = cenv' }
--showCryptolEnv
SS.StmtImport _ imp ->
liftTopLevel $
do rw <- getTopLevelRW
sc <- getSharedContext
--showCryptolEnv
let mLoc = iModule imp
qual = iAs imp
spec = iSpec imp
cenv' <- io $ CEnv.importModule sc (rwCryptol rw) mLoc qual CEnv.PublicAndPrivate spec
putTopLevelRW $ rw { rwCryptol = cenv' }
--showCryptolEnv
SS.StmtTypedef _ name ty ->
liftTopLevel $
do rw <- getTopLevelRW
putTopLevelRW $ addTypedef (getVal name) ty rw
interpretFile :: FilePath -> Bool {- ^ run main? -} -> TopLevel ()
interpretFile file runMain =
bracketTopLevel (io getCurrentDirectory) (io . setCurrentDirectory) (const interp)
where
interp =
do opts <- getOptions
io $ setCurrentDirectory (takeDirectory file)
stmts <- io $ SAWScript.Import.loadFile opts file
mapM_ stmtWithPrint stmts
when runMain interpretMain
writeVerificationSummary
stmtWithPrint s = do let withPos str = unlines $
("[output] at " ++ show (SS.getPos s) ++ ": ") :
map (\l -> "\t" ++ l) (lines str)
showLoc <- printShowPos <$> getOptions
if showLoc
then localOptions (\o -> o { printOutFn = \lvl str ->
printOutFn o lvl (withPos str) })
(interpretStmt False s)
else interpretStmt False s
-- | Evaluate the value called 'main' from the current environment.
interpretMain :: TopLevel ()
interpretMain = do
rw <- getTopLevelRW
let mainName = Located "main" "main" (SS.PosInternal "entry")
case Map.lookup mainName (rwValues rw) of
Nothing -> return () -- fail "No 'main' defined"
Just v -> fromValue v
buildTopLevelEnv :: AIGProxy
-> Options
-> IO (BuiltinContext, TopLevelRO, TopLevelRW)
buildTopLevelEnv proxy opts =
do let mn = mkModuleName ["SAWScript"]
sc0 <- mkSharedContext
let ?fileReader = BS.readFile
CryptolSAW.scLoadPreludeModule sc0
CryptolSAW.scLoadCryptolModule sc0
scLoadModule sc0 (emptyModule mn)
cryptol_mod <- scFindModule sc0 $ mkModuleName ["Cryptol"]
let convs = natConversions
++ bvConversions
++ vecConversions
++ [ tupleConversion
, recordConversion
, remove_ident_coerce
, remove_ident_unsafeCoerce
]
cryptolDefs = filter defPred $ moduleDefs cryptol_mod
defPred d = defIdent d `Set.member` includedDefs
includedDefs = Set.fromList
[ "Cryptol.ecDemote"
, "Cryptol.seq"
]
simps <- scSimpset sc0 cryptolDefs [] convs
let sc = rewritingSharedContext sc0 simps
ss <- basic_ss sc
jcb <- JCB.loadCodebase (jarList opts) (classPath opts) (javaBinDirs opts)
currDir <- getCurrentDirectory
mb_cache <- lookupEnv "SAW_SOLVER_CACHE_PATH" >>= \case
Just path | not (null path) -> Just <$> lazyOpenSolverCache path
_ -> return Nothing
Crucible.withHandleAllocator $ \halloc -> do
let ro0 = TopLevelRO
{ roJavaCodebase = jcb
, roOptions = opts
, roHandleAlloc = halloc
, roPosition = SS.Unknown
, roProxy = proxy
, roInitWorkDir = currDir
, roBasicSS = ss
, roStackTrace = []
, roSubshell = fail "Subshells not supported"
, roProofSubshell = fail "Proof subshells not supported"
, roLocalEnv = []
}
let bic = BuiltinContext {
biSharedContext = sc
, biBasicSS = ss
}
primsAvail = Set.fromList [Current]
ce0 <- CEnv.initCryptolEnv sc
jvmTrans <- CJ.mkInitialJVMContext halloc
let rw0 = TopLevelRW
{ rwValues = valueEnv primsAvail opts bic
, rwTypes = primTypeEnv primsAvail
, rwTypedef = Map.empty
, rwDocs = primDocEnv primsAvail
, rwCryptol = ce0
, rwMonadify = Monadify.defaultMonEnv
, rwMRSolverEnv = emptyMREnv
, rwProofs = []
, rwPPOpts = SAWScript.Value.defaultPPOpts
, rwSharedContext = sc
, rwSolverCache = mb_cache
, rwTheoremDB = emptyTheoremDB
, rwJVMTrans = jvmTrans
, rwPrimsAvail = primsAvail
, rwSMTArrayMemoryModel = False
, rwCrucibleAssertThenAssume = False
, rwProfilingFile = Nothing
, rwLaxArith = False
, rwLaxPointerOrdering = False
, rwLaxLoadsAndStores = False
, rwDebugIntrinsics = True
, rwWhat4HashConsing = False
, rwWhat4HashConsingX86 = False
, rwWhat4Eval = False
, rwPreservedRegs = []
, rwStackBaseAlign = defaultStackBaseAlign
, rwAllocSymInitCheck = True
, rwCrucibleTimeout = CC.defaultSAWCoreBackendTimeout
, rwPathSatSolver = CC.PathSat_Z3
, rwSkipSafetyProofs = False
, rwSingleOverrideSpecialCase = False
, rwSequentGoals = False
}
return (bic, ro0, rw0)
processFile ::
AIGProxy ->
Options ->
FilePath ->
Maybe (TopLevel ()) ->
Maybe (ProofScript ()) ->
IO ()
processFile proxy opts file mbSubshell mbProofSubshell = do
(_, ro, rw) <- buildTopLevelEnv proxy opts
let ro' = case mbSubshell of
Nothing -> ro
Just m -> ro{ roSubshell = m }
let ro'' = case mbProofSubshell of
Nothing -> ro'
Just m -> ro'{ roProofSubshell = m }
file' <- canonicalizePath file
_ <- runTopLevel (interpretFile file' True) ro'' rw
`X.catch` (handleException opts)
return ()
-- Primitives ------------------------------------------------------------------
add_primitives :: PrimitiveLifecycle -> BuiltinContext -> Options -> TopLevel ()
add_primitives lc bic opts = do
rw <- getTopLevelRW
let lcs = Set.singleton lc
putTopLevelRW rw {
rwValues = rwValues rw `Map.union` valueEnv lcs opts bic
, rwTypes = rwTypes rw `Map.union` primTypeEnv lcs
, rwDocs = rwDocs rw `Map.union` primDocEnv lcs
, rwPrimsAvail = Set.insert lc (rwPrimsAvail rw)
}
enable_safety_proofs :: TopLevel ()
enable_safety_proofs = do
rw <- getTopLevelRW
putTopLevelRW rw{ rwSkipSafetyProofs = False }
disable_safety_proofs :: TopLevel ()
disable_safety_proofs = do
opts <- getOptions
io $ printOutLn opts Warn "Safety proofs disabled! This is unsound!"
rw <- getTopLevelRW
putTopLevelRW rw{ rwSkipSafetyProofs = True }
enable_sequent_goals :: TopLevel ()
enable_sequent_goals = do
rw <- getTopLevelRW
putTopLevelRW rw{ rwSequentGoals = True }
disable_sequent_goals :: TopLevel ()
disable_sequent_goals = do
rw <- getTopLevelRW
putTopLevelRW rw{ rwSequentGoals = False }
enable_smt_array_memory_model :: TopLevel ()
enable_smt_array_memory_model = do
rw <- getTopLevelRW
putTopLevelRW rw { rwSMTArrayMemoryModel = True }
disable_smt_array_memory_model :: TopLevel ()
disable_smt_array_memory_model = do
rw <- getTopLevelRW
putTopLevelRW rw { rwSMTArrayMemoryModel = False }
enable_crucible_assert_then_assume :: TopLevel ()
enable_crucible_assert_then_assume = do
rw <- getTopLevelRW
putTopLevelRW rw { rwCrucibleAssertThenAssume = True }
disable_crucible_assert_then_assume :: TopLevel ()
disable_crucible_assert_then_assume = do
rw <- getTopLevelRW
putTopLevelRW rw { rwCrucibleAssertThenAssume = False }
enable_single_override_special_case :: TopLevel ()
enable_single_override_special_case = do
rw <- getTopLevelRW
putTopLevelRW rw { rwSingleOverrideSpecialCase = True }
disable_single_override_special_case :: TopLevel ()
disable_single_override_special_case = do
rw <- getTopLevelRW
putTopLevelRW rw { rwSingleOverrideSpecialCase = False }
enable_crucible_profiling :: FilePath -> TopLevel ()
enable_crucible_profiling f = do
rw <- getTopLevelRW
putTopLevelRW rw { rwProfilingFile = Just f }
disable_crucible_profiling :: TopLevel ()
disable_crucible_profiling = do
rw <- getTopLevelRW
putTopLevelRW rw { rwProfilingFile = Nothing }
enable_lax_arithmetic :: TopLevel ()
enable_lax_arithmetic = do
rw <- getTopLevelRW
putTopLevelRW rw { rwLaxArith = True }
disable_lax_arithmetic :: TopLevel ()
disable_lax_arithmetic = do
rw <- getTopLevelRW
putTopLevelRW rw { rwLaxArith = False }
enable_lax_pointer_ordering :: TopLevel ()
enable_lax_pointer_ordering = do
rw <- getTopLevelRW
putTopLevelRW rw { rwLaxPointerOrdering = True }
disable_lax_pointer_ordering :: TopLevel ()
disable_lax_pointer_ordering = do
rw <- getTopLevelRW
putTopLevelRW rw { rwLaxPointerOrdering = False }
enable_lax_loads_and_stores :: TopLevel ()
enable_lax_loads_and_stores = do
rw <- getTopLevelRW
putTopLevelRW rw { rwLaxLoadsAndStores = True }
disable_lax_loads_and_stores :: TopLevel ()
disable_lax_loads_and_stores = do
rw <- getTopLevelRW
putTopLevelRW rw { rwLaxLoadsAndStores = False }
set_solver_cache_path :: FilePath -> TopLevel ()
set_solver_cache_path path = do
rw <- getTopLevelRW
case rwSolverCache rw of
Just _ -> onSolverCache (setSolverCachePath path)
Nothing -> do cache <- io $ openSolverCache path
putTopLevelRW rw { rwSolverCache = Just cache }
clean_mismatched_versions_solver_cache :: TopLevel ()
clean_mismatched_versions_solver_cache = do
vs <- io $ getSolverBackendVersions allBackends
onSolverCache (cleanMismatchedVersionsSolverCache vs)
test_solver_cache_stats :: Integer -> Integer -> Integer -> Integer ->
Integer -> TopLevel ()
test_solver_cache_stats sz ls ls_f is is_f =
onSolverCache (testSolverCacheStats sz ls ls_f is is_f)
enable_debug_intrinsics :: TopLevel ()
enable_debug_intrinsics = do
rw <- getTopLevelRW
putTopLevelRW rw { rwDebugIntrinsics = True }
disable_debug_intrinsics :: TopLevel ()
disable_debug_intrinsics = do
rw <- getTopLevelRW
putTopLevelRW rw { rwDebugIntrinsics = False }
enable_what4_hash_consing :: TopLevel ()
enable_what4_hash_consing = do
rw <- getTopLevelRW
putTopLevelRW rw { rwWhat4HashConsing = True }
disable_what4_hash_consing :: TopLevel ()
disable_what4_hash_consing = do
rw <- getTopLevelRW
putTopLevelRW rw { rwWhat4HashConsing = False }
enable_x86_what4_hash_consing :: TopLevel ()
enable_x86_what4_hash_consing = do
rw <- getTopLevelRW
putTopLevelRW rw { rwWhat4HashConsingX86 = True }
disable_x86_what4_hash_consing :: TopLevel ()
disable_x86_what4_hash_consing = do
rw <- getTopLevelRW
putTopLevelRW rw { rwWhat4HashConsingX86 = False }
enable_what4_eval :: TopLevel ()
enable_what4_eval = do
rw <- getTopLevelRW
putTopLevelRW rw { rwWhat4Eval = True }
disable_what4_eval :: TopLevel ()
disable_what4_eval = do
rw <- getTopLevelRW
putTopLevelRW rw { rwWhat4Eval = False }
add_x86_preserved_reg :: String -> TopLevel ()
add_x86_preserved_reg r = do
rw <- getTopLevelRW
putTopLevelRW rw { rwPreservedRegs = r:rwPreservedRegs rw }
default_x86_preserved_reg :: TopLevel ()
default_x86_preserved_reg = do
rw <- getTopLevelRW
putTopLevelRW rw { rwPreservedRegs = [] }
set_x86_stack_base_align :: Integer -> TopLevel ()
set_x86_stack_base_align a = do
rw <- getTopLevelRW
putTopLevelRW rw { rwStackBaseAlign = a }
default_x86_stack_base_align :: TopLevel ()
default_x86_stack_base_align = do
rw <- getTopLevelRW
putTopLevelRW rw { rwStackBaseAlign = defaultStackBaseAlign }
enable_alloc_sym_init_check :: TopLevel ()
enable_alloc_sym_init_check = do
rw <- getTopLevelRW
putTopLevelRW rw { rwAllocSymInitCheck = True }
disable_alloc_sym_init_check :: TopLevel ()
disable_alloc_sym_init_check = do
rw <- getTopLevelRW
putTopLevelRW rw { rwAllocSymInitCheck = False }
set_crucible_timeout :: Integer -> TopLevel ()
set_crucible_timeout t = do
rw <- getTopLevelRW
putTopLevelRW rw { rwCrucibleTimeout = t }
include_value :: FilePath -> TopLevel ()
include_value file = do
file' <- io $ canonicalizePath file
interpretFile file' False
set_ascii :: Bool -> TopLevel ()
set_ascii b = do
rw <- getTopLevelRW
putTopLevelRW rw { rwPPOpts = (rwPPOpts rw) { ppOptsAscii = b } }
set_base :: Int -> TopLevel ()
set_base b = do
rw <- getTopLevelRW
putTopLevelRW rw { rwPPOpts = (rwPPOpts rw) { ppOptsBase = b } }
set_color :: Bool -> TopLevel ()
set_color b = do
rw <- getTopLevelRW
opts <- getOptions
-- Keep color disabled if `--no-color` command-line option is present
let b' = b && useColor opts
putTopLevelRW rw { rwPPOpts = (rwPPOpts rw) { ppOptsColor = b' } }
set_min_sharing :: Int -> TopLevel ()
set_min_sharing b = do
rw <- getTopLevelRW
putTopLevelRW rw { rwPPOpts = (rwPPOpts rw) { ppOptsMinSharing = b } }
print_value :: Value -> TopLevel ()
print_value (VString s) = printOutLnTop Info (Text.unpack s)
print_value (VTerm t) = do
sc <- getSharedContext
cenv <- fmap rwCryptol getTopLevelRW
let cfg = CEnv.meSolverConfig (CEnv.eModuleEnv cenv)
unless (null (getAllExts (ttTerm t))) $
fail "term contains symbolic variables"
sawopts <- getOptions
t' <- io $ defaultTypedTerm sawopts sc cfg t
opts <- fmap rwPPOpts getTopLevelRW
let opts' = V.defaultPPOpts { V.useAscii = ppOptsAscii opts
, V.useBase = ppOptsBase opts
}
evaled_t <- io $ evaluateTypedTerm sc t'
doc <- io $ V.runEval mempty (V.ppValue V.Concrete opts' evaled_t)
sawOpts <- getOptions
io (rethrowEvalError $ printOutLn sawOpts Info $ show $ doc)
print_value v = do
opts <- fmap rwPPOpts getTopLevelRW
nenv <- io . scGetNamingEnv =<< getSharedContext
printOutLnTop Info (showsPrecValue opts nenv 0 v "")
readSchema :: String -> SS.Schema
readSchema str =
case parseSchema (lexSAW "internal" str) of
Left err -> error (show err)
Right schema -> schema
data Primitive
= Primitive
{ primitiveName :: SS.LName
, primitiveType :: SS.Schema
, primitiveLife :: PrimitiveLifecycle
, primitiveDoc :: [String]
, primitiveFn :: Options -> BuiltinContext -> Value
}
primitives :: Map SS.LName Primitive
primitives = Map.fromList
[ prim "return" "{m, a} a -> m a"
(pureVal VReturn)
Current
[ "Yield a value in a command context. The command"
, " x <- return e"
,"will result in the same value being bound to 'x' as the command"
, " let x = e"
]
, prim "true" "Bool"
(pureVal True)
Current
[ "A boolean value." ]
, prim "false" "Bool"
(pureVal False)
Current
[ "A boolean value." ]
, prim "for" "{m, a, b} [a] -> (a -> m b) -> m [b]"
(pureVal (VLambda . forValue))
Current
[ "Apply the given command in sequence to the given list. Return"
, "the list containing the result returned by the command at each"
, "iteration."
]
, prim "run" "{a} TopLevel a -> a"
(funVal1 (id :: TopLevel Value -> TopLevel Value))
Current
[ "Evaluate a monadic TopLevel computation to produce a value." ]
, prim "null" "{a} [a] -> Bool"
(pureVal (null :: [Value] -> Bool))
Current
[ "Test whether a list value is empty." ]
, prim "nth" "{a} [a] -> Int -> a"
(funVal2 (nthPrim :: [Value] -> Int -> TopLevel Value))
Current
[ "Look up the value at the given list position." ]
, prim "head" "{a} [a] -> a"
(funVal1 (headPrim :: [Value] -> TopLevel Value))
Current
[ "Get the first element from the list." ]
, prim "tail" "{a} [a] -> [a]"
(funVal1 (tailPrim :: [Value] -> TopLevel [Value]))
Current
[ "Drop the first element from a list." ]
, prim "concat" "{a} [a] -> [a] -> [a]"
(pureVal ((++) :: [Value] -> [Value] -> [Value]))
Current
[ "Concatenate two lists to yield a third." ]
, prim "length" "{a} [a] -> Int"
(pureVal (length :: [Value] -> Int))
Current
[ "Compute the length of a list." ]
, prim "str_concat" "String -> String -> String"
(pureVal ((++) :: String -> String -> String))
Current
[ "Concatenate two strings to yield a third." ]
, prim "str_concats" "[String] -> String"
(pureVal (concat :: [String] -> String))
Current
[ "Concatenate a list of strings together to yield a string." ]
, prim "callcc" "{a} ((a -> TopLevel ()) -> TopLevel a) -> TopLevel a"
(\_ _ -> toplevelCallCC)
Experimental
[ "Call-with-current-continuation."
, ""
, "This is a highly experimental control operator that can be used"
, "to capture the surrounding top-level computation as a continuation."
, "The consequences of delaying and reentering the current continuation"
, "may be somewhat unpredictable, so use this operator with great caution."
]
, prim "checkpoint" "TopLevel (() -> TopLevel ())"
(pureVal checkpoint)
Experimental
[ "Capture the current state of the SAW interpreter, and return"
, "A TopLevel monadic action that, if invoked, will reset the"
, "state of the interpreter back to to what it was at the"
, "moment checkpoint was invoked."
, ""
, "NOTE that this facility is highly experimental and may not"
, "be entirely reliable. It is intended only for proof development"
, "where it can speed up the process of experimenting with"
, "mid-proof changes. Finalized proofs should not use this facility."
]
, prim "subshell" "() -> TopLevel ()"
(\_ _ -> toplevelSubshell)
Experimental
[ "Open an interactive subshell instance in the context where"
, "'subshell' was called. This works either from within execution"
, "of a outer shell instance, or from interpreting a file in batch"
, "mode. Enter the end-of-file character in your terminal (Ctrl^D, usually)"
, "to exit the subshell and resume execution."
, ""
, "This command is especially useful in conjunction with the 'checkpoint'"
, "and 'callcc' commands, which allow state reset capabilities and the capturing"
, "of the calling context."
, ""
, "Note that, due to the way the SAW script interpreter works, changes made"
, "to a script file in which the 'subshell' command directly appears will"
, "NOT affect subsequent execution following a 'checkpoint' or 'callcc' use."
, "However, changes made in a file that executed via 'include' WILL affect"
, "restarted executions, as the 'include' command will read and parse the"
, "file from scratch."
]
, prim "proof_subshell" "() -> ProofScript ()"
(\ _ _ -> proofScriptSubshell)
Experimental
[ "Open an interactive subshell instance in the context of the current proof."
, "This allows the user to interactively execute 'ProofScript' tactic commands"
, "directly on the command line an examine their effects using, e.g., 'print_goal'."
, "In proof mode, the command prompt will change to 'proof (n)', where the 'n'"
, "indicates the number of subgoals remaining to proof for the current overall goal."
, "In this mode, tactic commands applied will only affect the current subgoal."
, "When a particular subgoal is completed, the next subgoal will automatically become"
, "the active subgoal. An overall goal is completed when all subgoals are proved"
, "and the current number of subgoals is 0."
, ""
, "Enter the end-of-file character in your terminal (Ctrl^D, usually) to exit the proof"
, "subshell and resume execution."
]
, prim "proof_checkpoint" "ProofScript (() -> ProofScript ())"
(pureVal proof_checkpoint)
Experimental
[ "Capture the current state of the proof and return a"
, "ProofScript monadic action that, if invoked, will reset the"
, "state of the proof back to to what it was at the"
, "moment checkpoint was invoked."
, ""
, "NOTE that this facility is highly experimental and may not"
, "be entirely reliable. It is intended only for proof development"
, "where it can speed up the process of experimenting with"
, "mid-proof changes. Finalized proofs should not use this facility."
]
, prim "define" "String -> Term -> TopLevel Term"
(pureVal definePrim)
Current
[ "Wrap a term with a name that allows its body to be hidden or"
, "revealed. This can allow any sub-term to be treated as an"
, "uninterpreted function during proofs."
]
, prim "include" "String -> TopLevel ()"
(pureVal include_value)
Current
[ "Execute the given SAWScript file." ]
, prim "enable_deprecated" "TopLevel ()"
(bicVal (add_primitives Deprecated))
Current
[ "Enable the use of deprecated commands." ]
, prim "enable_experimental" "TopLevel ()"
(bicVal (add_primitives Experimental))
Current
[ "Enable the use of experimental commands." ]
, prim "enable_smt_array_memory_model" "TopLevel ()"
(pureVal enable_smt_array_memory_model)
Current
[ "Enable the SMT array memory model." ]
, prim "disable_smt_array_memory_model" "TopLevel ()"
(pureVal disable_smt_array_memory_model)
Current
[ "Disable the SMT array memory model." ]
, prim "enable_sequent_goals" "TopLevel ()"
(pureVal enable_sequent_goals)
Experimental
[ "When verifying proof obligations arising from `llvm_verify` and similar commands,"
, "generate sequents for the proof obligations instead of a single boolean goal."