-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathInterpreter.hs
2473 lines (2142 loc) · 91.3 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 MultiParamTypeClasses #-}
#if !MIN_VERSION_base(4,8,0)
{-# LANGUAGE OverlappingInstances #-}
#endif
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE NondecreasingIndentation #-}
module SAWScript.Interpreter
( interpretStmt
, interpretFile
, processFile
, buildTopLevelEnv
, primDocEnv
)
where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
import Data.Traversable hiding ( mapM )
#endif
import qualified Control.Exception as X
import Control.Monad (unless, (>=>))
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 System.Directory (getCurrentDirectory, setCurrentDirectory, canonicalizePath)
import System.FilePath (takeDirectory)
import System.Process (readProcess)
import qualified SAWScript.AST as SS
import qualified SAWScript.Position as SS
import SAWScript.AST (Located(..),Import(..))
import SAWScript.Builtins
import SAWScript.Exceptions (failTypecheck)
import qualified SAWScript.Import
import SAWScript.JavaBuiltins
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.Prover.Rewrite(basic_ss)
import SAWScript.Prover.Exporter
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
import Verifier.SAW.TypedTerm
import qualified Verifier.SAW.CryptolEnv as CEnv
import qualified Verifier.Java.Codebase as JCB
import qualified Verifier.Java.SAWBackend as JavaSAW
import qualified Verifier.SAW.Cryptol.Prelude as CryptolSAW
-- Crucible
import qualified Lang.Crucible.JVM as CJ
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.LLVM.X86
import SAWScript.Crucible.LLVM.Boilerplate
import qualified SAWScript.Crucible.LLVM.MethodSpecIR as CIR
-- Cryptol
import Cryptol.ModuleSystem.Env (meSolverConfig)
import qualified Cryptol.Eval as V (PPOpts(..))
import qualified Cryptol.Eval.Monad as V (runEval)
import qualified Cryptol.Eval.Value as V (defaultPPOpts, ppValue)
import qualified Cryptol.Eval.Concrete.Value as V (Concrete(..))
import qualified Text.PrettyPrint.ANSI.Leijen as PP
import SAWScript.AutoMatch
import qualified Lang.Crucible.FunctionHandle as Crucible
-- Environment -----------------------------------------------------------------
data LocalBinding
= LocalLet SS.LName (Maybe SS.Schema) (Maybe String) Value
| LocalTypedef SS.Name SS.Type
type LocalEnv = [LocalBinding]
emptyLocal :: LocalEnv
emptyLocal = []
extendLocal :: SS.LName -> Maybe SS.Schema -> Maybe String -> Value -> LocalEnv -> LocalEnv
extendLocal x mt md v env = LocalLet x mt md v : env
addTypedef :: SS.Name -> SS.Type -> TopLevelRW -> TopLevelRW
addTypedef name ty rw = rw { rwTypedef = Map.insert name ty (rwTypedef rw) }
mergeLocalEnv :: LocalEnv -> TopLevelRW -> TopLevelRW
mergeLocalEnv env rw = foldr addBinding rw env
where addBinding (LocalLet x mt md v) = extendEnv x mt md v
addBinding (LocalTypedef n ty) = addTypedef n ty
getMergedEnv :: LocalEnv -> TopLevel TopLevelRW
getMergedEnv env = mergeLocalEnv env `fmap` getTopLevelRW
bindPatternGeneric :: (SS.LName -> Maybe SS.Schema -> Maybe String -> Value -> e -> e)
-> SS.Pattern -> Maybe SS.Schema -> Value -> e -> e
bindPatternGeneric ext pat ms v env =
case pat of
SS.PWild _ -> env
SS.PVar x _ -> ext x ms Nothing v env
SS.PTuple ps ->
case v of
VTuple vs -> foldr ($) env (zipWith3 (bindPatternGeneric ext) 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 ]
_ -> error "bindPattern: expected tuple value"
_ -> error "bindPattern: expected tuple value"
SS.LPattern _ pat' -> bindPatternGeneric ext pat' ms v env
bindPatternLocal :: SS.Pattern -> Maybe SS.Schema -> Value -> LocalEnv -> LocalEnv
bindPatternLocal = bindPatternGeneric extendLocal
bindPatternEnv :: SS.Pattern -> Maybe SS.Schema -> Value -> TopLevelRW -> TopLevelRW
bindPatternEnv = bindPatternGeneric extendEnv
-- Interpretation of SAWScript -------------------------------------------------
interpret :: LocalEnv -> SS.Expr -> TopLevel Value
interpret env expr =
let ?fileReader = BS.readFile in
case expr of
SS.Bool b -> return $ VBool b
SS.String s -> return $ VString s
SS.Int z -> return $ VInteger z
SS.Code str -> do sc <- getSharedContext
cenv <- fmap rwCryptol (getMergedEnv env)
--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 env)
s <- io $ CEnv.parseSchema cenv
$ locToInput str
return (toValue s)
SS.Array es -> VArray <$> traverse (interpret env) es
SS.Block stmts -> interpretStmts env stmts
SS.Tuple es -> VTuple <$> traverse (interpret env) es
SS.Record bs -> VRecord <$> traverse (interpret env) bs
SS.Index e1 e2 -> do a <- interpret env e1
i <- interpret env e2
return (indexValue a i)
SS.Lookup e n -> do a <- interpret env e
return (lookupValue a n)
SS.TLookup e i -> do a <- interpret env e
return (tupleLookupValue a i)
SS.Var x -> do rw <- getMergedEnv env
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 let f v = interpret (bindPatternLocal pat Nothing v env) e
return $ VLambda f
SS.Application e1 e2 -> do v1 <- interpret env e1
v2 <- interpret env e2
case v1 of
VLambda f -> f v2
_ -> fail $ "interpret Application: " ++ show v1
SS.Let dg e -> do env' <- interpretDeclGroup env dg
interpret env' e
SS.TSig e _ -> interpret env e
SS.IfThenElse e1 e2 e3 -> do v1 <- interpret env e1
case v1 of
VBool b -> interpret env (if b then e2 else e3)
_ -> fail $ "interpret IfThenElse: " ++ show v1
SS.LExpr _ e -> interpret env 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 env 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 = interpret (bindPatternLocal pat Nothing v env) e
SS.TSig e _ -> interpretFunction env e
_ -> error "interpretFunction: not a function"
interpretDeclGroup :: LocalEnv -> SS.DeclGroup -> TopLevel LocalEnv
interpretDeclGroup env (SS.NonRecursive d) = interpretDecl env d
interpretDeclGroup env (SS.Recursive ds) = return env'
where
env' = foldr addDecl env ds
addDecl (SS.Decl _ pat mty e) = bindPatternLocal pat mty (interpretFunction env' e)
interpretStmts :: LocalEnv -> [SS.Stmt] -> TopLevel Value
interpretStmts env stmts =
let ?fileReader = BS.readFile in
case stmts of
[] -> fail "empty block"
[SS.StmtBind _ (SS.PWild _) _ e] -> interpret env e
SS.StmtBind pos pat _ e : ss ->
do v1 <- interpret env e
let f v = interpretStmts (bindPatternLocal pat Nothing v env) ss
bindValue pos v1 (VLambda f)
SS.StmtLet _ bs : ss -> interpret env (SS.Let bs (SS.Block ss))
SS.StmtCode _ s : ss ->
do sc <- getSharedContext
rw <- getMergedEnv env
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 env ss
SS.StmtImport _ _ : _ ->
do fail "block import unimplemented"
SS.StmtTypedef _ name ty : ss ->
do let env' = LocalTypedef (getVal name) ty : env
interpretStmts env' ss
stmtInterpreter :: StmtInterpreter
stmtInterpreter ro rw stmts = fmap fst $ runTopLevel (interpretStmts emptyLocal stmts) ro rw
processStmtBind :: Bool -> SS.Pattern -> Maybe SS.Type -> SS.Expr -> TopLevel ()
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
let ctx = SS.tContext SS.TopLevel
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 <- getTopLevelRW
let opts = rwPPOpts rw
~(SS.Decl _ _ (Just schema) expr'') <-
either failTypecheck return $ checkDecl (rwTypes rw) (rwTypedef rw) decl
val <- interpret emptyLocal 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 <- SAWScript.Value.fromValue 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) ->
printOutLnTop Info (showsPrecValue opts 0 result "")
_ -> return ()
-- Print function type if result was a function
case ty of
SS.TyCon SS.FunCon _ -> printOutLnTop Info $ getVal lname ++ " : " ++ SS.pShow ty
_ -> return ()
rw' <- getTopLevelRW
putTopLevelRW $ bindPatternEnv pat (Just (SS.tMono ty)) result rw'
-- | Interpret a block-level statement in the TopLevel monad.
interpretStmt ::
Bool {-^ whether to print non-unit result values -} ->
SS.Stmt ->
TopLevel ()
interpretStmt printBinds stmt =
let ?fileReader = BS.readFile in
case stmt of
SS.StmtBind pos pat mc expr -> withPosition pos (processStmtBind printBinds pat mc expr)
SS.StmtLet _ dg -> do rw <- getTopLevelRW
dg' <- either failTypecheck return $
checkDeclGroup (rwTypes rw) (rwTypedef rw) dg
env <- interpretDeclGroup emptyLocal dg'
getMergedEnv env >>= putTopLevelRW
SS.StmtCode _ lstr -> 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 ->
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 spec
putTopLevelRW $ rw { rwCryptol = cenv' }
--showCryptolEnv
SS.StmtTypedef _ name ty -> do rw <- getTopLevelRW
putTopLevelRW $ addTypedef (getVal name) ty rw
interpretFile :: FilePath -> TopLevel ()
interpretFile file = do
opts <- getOptions
stmts <- io $ SAWScript.Import.loadFile opts file
mapM_ stmtWithPrint stmts
where
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
JavaSAW.scLoadJavaModule 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)
Crucible.withHandleAllocator $ \halloc -> do
let ro0 = TopLevelRO
{ roSharedContext = sc
, roJavaCodebase = jcb
, roOptions = opts
, roHandleAlloc = halloc
, roPosition = SS.Unknown
, roProxy = proxy
}
let bic = BuiltinContext {
biSharedContext = sc
, biJavaCodebase = jcb
, 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
, rwProofs = []
, rwPPOpts = SAWScript.Value.defaultPPOpts
, rwJVMTrans = jvmTrans
, rwPrimsAvail = primsAvail
, rwSMTArrayMemoryModel = False
, rwCrucibleAssertThenAssume = False
, rwProfilingFile = Nothing
, rwLaxArith = False
, rwWhat4HashConsing = False
}
return (bic, ro0, rw0)
processFile :: AIGProxy
-> Options
-> FilePath -> IO ()
processFile proxy opts file = do
(_, ro, rw) <- buildTopLevelEnv proxy opts
oldpath <- getCurrentDirectory
file' <- canonicalizePath file
setCurrentDirectory (takeDirectory file')
_ <- runTopLevel (interpretFile file' >> interpretMain) ro rw
`X.catch` (handleException opts)
setCurrentDirectory oldpath
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_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_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 }
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 }
include_value :: FilePath -> TopLevel ()
include_value file = do
oldpath <- io $ getCurrentDirectory
file' <- io $ canonicalizePath file
io $ setCurrentDirectory (takeDirectory file')
interpretFile file'
io $ setCurrentDirectory oldpath
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
putTopLevelRW rw { rwPPOpts = (rwPPOpts rw) { ppOptsColor = b } }
print_value :: Value -> TopLevel ()
print_value (VString s) = printOutLnTop Info s
print_value (VTerm t) = do
sc <- getSharedContext
cenv <- fmap rwCryptol getTopLevelRW
let cfg = 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 quietEvalOpts (V.ppValue V.Concrete opts' evaled_t)
sawOpts <- getOptions
io (rethrowEvalError $ printOutLn sawOpts Info $ show $ doc)
print_value v = do
opts <- fmap rwPPOpts getTopLevelRW
printOutLnTop Info (showsPrecValue opts 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
{ primName :: SS.LName
, primType :: SS.Schema
, primLife :: PrimitiveLifecycle
, primDoc :: [String]
, primFn :: 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 "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_crucible_assert_then_assume" "TopLevel ()"
(pureVal enable_crucible_assert_then_assume)
Current
[ "Assume predicate after asserting it during Crucible symbolic simulation." ]
, prim "disable_crucible_assert_then_assume" "TopLevel ()"
(pureVal disable_crucible_assert_then_assume)
Current
[ "Do not assume predicate after asserting it during Crucible symbolic simulation." ]
, prim "enable_lax_arithmetic" "TopLevel ()"
(pureVal enable_lax_arithmetic)
Current
[ "Enable lax rules for arithmetic overflow in Crucible." ]
, prim "enable_what4_hash_consing" "TopLevel ()"
(pureVal enable_what4_hash_consing)
Current
[ "Enable hash consing for What4 expressions." ]
, prim "disable_what4_hash_consing" "TopLevel ()"
(pureVal disable_what4_hash_consing)
Current
[ "Disable hash consing for What4 expressions." ]
, prim "env" "TopLevel ()"
(pureVal envCmd)
Current
[ "Print all sawscript values in scope." ]
, prim "set_ascii" "Bool -> TopLevel ()"
(pureVal set_ascii)
Current
[ "Select whether to pretty-print arrays of 8-bit numbers as ascii strings." ]
, prim "set_base" "Int -> TopLevel ()"
(pureVal set_base)
Current
[ "Set the number base for pretty-printing numeric literals."
, "Permissible values include 2, 8, 10, and 16." ]
, prim "set_color" "Bool -> TopLevel ()"
(pureVal set_color)
Current
[ "Select whether to pretty-print SAWCore terms using color." ]
, prim "set_timeout" "Int -> ProofScript ()"
(pureVal set_timeout)
Experimental
[ "Set the timeout, in milliseconds, for any automated prover at the"
, "end of this proof script. Not that this is simply ignored for provers"
, "that don't support timeouts, for now."
]
, prim "show" "{a} a -> String"
(funVal1 showPrim)
Current
[ "Convert the value of the given expression to a string." ]
, prim "print" "{a} a -> TopLevel ()"
(pureVal print_value)
Current
[ "Print the value of the given expression." ]
, prim "print_term" "Term -> TopLevel ()"
(pureVal print_term)
Current
[ "Pretty-print the given term in SAWCore syntax." ]
, prim "print_term_depth" "Int -> Term -> TopLevel ()"
(pureVal print_term_depth)
Current
[ "Pretty-print the given term in SAWCore syntax up to a given depth." ]
, prim "dump_file_AST" "String -> TopLevel ()"
(bicVal $ const $ \opts -> SAWScript.Import.loadFile opts >=> mapM_ print)
Current
[ "Dump a pretty representation of the SAWScript AST for a file." ]
, prim "parser_printer_roundtrip" "String -> TopLevel ()"
(bicVal $ const $
\opts -> SAWScript.Import.loadFile opts >=>
PP.putDoc . SS.prettyWholeModule)
Current
[ "Parses the file as SAWScript and renders the resultant AST back to SAWScript concrete syntax." ]
, prim "print_type" "Term -> TopLevel ()"
(pureVal print_type)
Current
[ "Print the type of the given term." ]
, prim "type" "Term -> Type"
(pureVal ttSchema)
Current
[ "Return the type of the given term." ]
, prim "show_term" "Term -> String"
(funVal1 show_term)
Current
[ "Pretty-print the given term in SAWCore syntax, yielding a String." ]
, prim "check_term" "Term -> TopLevel ()"
(pureVal check_term)
Current
[ "Type-check the given term, printing an error message if ill-typed." ]
, prim "check_goal" "ProofScript ()"
(pureVal check_goal)
Current
[ "Type-check the current proof goal, printing an error message if ill-typed." ]
, prim "term_size" "Term -> Int"
(pureVal scSharedSize)
Current
[ "Return the size of the given term in the number of DAG nodes." ]
, prim "term_tree_size" "Term -> Int"
(pureVal scTreeSize)
Current
[ "Return the size of the given term in the number of nodes it would"
, "have if treated as a tree instead of a DAG."
]
, prim "abstract_symbolic" "Term -> Term"
(funVal1 abstractSymbolicPrim)
Current
[ "Take a term containing symbolic variables of the form returned"
, "by 'fresh_symbolic' and return a new lambda term in which those"
, "variables have been replaced by parameter references."
]
, prim "fresh_symbolic" "String -> Type -> TopLevel Term"
(pureVal freshSymbolicPrim)
Current
[ "Create a fresh symbolic variable of the given type. The given name"
, "is used only for pretty-printing."
]
, prim "lambda" "Term -> Term -> Term"
(funVal2 lambda)
Current
[ "Take a 'fresh_symbolic' variable and another term containing that"
, "variable, and return a new lambda abstraction over that variable."
]
, prim "lambdas" "[Term] -> Term -> Term"
(funVal2 lambdas)
Current
[ "Take a list of 'fresh_symbolic' variable and another term containing"
, "those variables, and return a new lambda abstraction over the list of"
, "variables."
]
, prim "sbv_uninterpreted" "String -> Term -> TopLevel Uninterp"
(pureVal sbvUninterpreted)
Deprecated
[ "Indicate that the given term should be used as the definition of the"
, "named function when loading an SBV file. This command returns an"
, "object that can be passed to 'read_sbv'."
]
, prim "check_convertible" "Term -> Term -> TopLevel ()"
(pureVal checkConvertiblePrim)
Current
[ "Check if two terms are convertible." ]
, prim "replace" "Term -> Term -> Term -> TopLevel Term"
(pureVal replacePrim)
Current
[ "'replace x y z' rewrites occurences of term x into y inside the"
, "term z. x and y must be closed terms."
]
, prim "hoist_ifs" "Term -> TopLevel Term"
(pureVal hoistIfsPrim)
Current
[ "Hoist all if-then-else expressions as high as possible." ]
, prim "read_bytes" "String -> TopLevel Term"
(pureVal readBytes)
Current
[ "Read binary file as a value of type [n][8]." ]
, prim "read_sbv" "String -> [Uninterp] -> TopLevel Term"
(pureVal readSBV)
Deprecated
[ "Read an SBV file produced by Cryptol 1, using the given set of"
, "overrides for any uninterpreted functions that appear in the file."
]
, prim "load_aig" "String -> TopLevel AIG"
(pureVal loadAIGPrim)
Current
[ "Read an AIG file in binary AIGER format, yielding an AIG value." ]
, prim "save_aig" "String -> AIG -> TopLevel ()"
(pureVal saveAIGPrim)
Current
[ "Write an AIG to a file in binary AIGER format." ]
, prim "save_aig_as_cnf" "String -> AIG -> TopLevel ()"
(pureVal saveAIGasCNFPrim)
Current
[ "Write an AIG representing a boolean function to a file in DIMACS"
, "CNF format."
]
, prim "dsec_print" "Term -> Term -> TopLevel ()"
(scVal dsecPrint)
Current
[ "Use ABC's 'dsec' command to compare two terms as SAIGs."
, "The terms must have a type as described in ':help write_saig',"
, "i.e. of the form '(i, s) -> (o, s)'. Note that nothing is returned:"
, "you must read the output to see what happened."
, ""
, "You must have an 'abc' executable on your PATH to use this command."
]
, prim "cec" "AIG -> AIG -> TopLevel ProofResult"
(pureVal cecPrim)
Current
[ "Perform a Combinatorial Equivalence Check between two AIGs."
, "The AIGs must have the same number of inputs and outputs."
]
, prim "bitblast" "Term -> TopLevel AIG"
(pureVal bbPrim)
Current
[ "Translate a term into an AIG. The term must be representable as a"
, "function from a finite number of bits to a finite number of bits."
]
, prim "read_aig" "String -> TopLevel Term"
(pureVal readAIGPrim)
Current
[ "Read an AIG file in AIGER format and translate to a term." ]
, prim "read_core" "String -> TopLevel Term"
(pureVal readCore)
Current
[ "Read a term from a file in the SAWCore external format." ]
, prim "write_aig" "String -> Term -> TopLevel ()"
(pureVal writeAIGPrim)
Current
[ "Write out a representation of a term in binary AIGER format. The"
, "term must be representable as a function from a finite number of"
, "bits to a finite number of bits."
]
, prim "write_saig" "String -> Term -> TopLevel ()"
(pureVal writeSAIGPrim)
Current
[ "Write out a representation of a term in binary AIGER format. The"
, "term must be representable as a function from a finite number of"
, "bits to a finite number of bits. The type must be of the form"
, "'(i, s) -> (o, s)' and is interpreted as an '[|i| + |s|] -> [|o| + |s|]'"
, "AIG with '|s|' latches."
, ""
, "Arguments:"
, " file to translation to : String"
, " function to translate to sequential AIG : Term"
]
, prim "write_saig'" "String -> Term -> Int -> TopLevel ()"
(pureVal writeSAIGComputedPrim)
Current
[ "Write out a representation of a term in binary AIGER format. The"
, "term must be representable as a function from a finite number of"
, "bits to a finite number of bits, '[m] -> [n]'. The int argument,"
, "'k', must be at most 'min {m, n}', and specifies that the *last* 'k'"
, "input and output bits are joined as latches."
, ""
, "Arguments:"
, " file to translation to : String"
, " function to translate to sequential AIG : Term"
, " number of latches : Int"
]
, prim "write_cnf" "String -> Term -> TopLevel ()"
(scVal write_cnf)
Current
[ "Write the given term to the named file in CNF format." ]
, prim "write_smtlib2" "String -> Term -> TopLevel ()"
(scVal write_smtlib2)
Current
[ "Write the given term to the named file in SMT-Lib version 2 format." ]
, prim "write_core" "String -> Term -> TopLevel ()"
(pureVal writeCore)
Current
[ "Write out a representation of a term in SAWCore external format." ]
, prim "write_coq_term" "String -> [(String, String)] -> [String] -> String -> Term -> TopLevel ()"
(pureVal writeCoqTerm)
Experimental
[ "Write out a representation of a term in Gallina syntax for Coq."
, "The first argument is the name to use in a Definition."
, "The second argument is a list of pairs of notation substitutions:"
, "the operator on the left will be replaced with the identifier on"
, "the right, as we do not support notations on the Coq side."
, "The third argument is a list of identifiers to skip translating."
, "The fourth argument is the name of the file to output into,"
, "use an empty string to output to standard output."
, "The fifth argument is the term to export."
]
, prim "write_coq_cryptol_module" "String -> String -> [(String, String)] -> [String] -> TopLevel ()"
(pureVal writeCoqCryptolModule)
Experimental
[ "Write out a representation of a Cryptol module in Gallina syntax for"
, "Coq."
, "The first argument is the file containing the module to export."
, "The second argument is the name of the file to output into,"
, "use an empty string to output to standard output."
, "The third argument is a list of pairs of notation substitutions:"
, "the operator on the left will be replaced with the identifier on"
, "the right, as we do not support notations on the Coq side."
, "The fourth argument is a list of identifiers to skip translating."
]
, prim "write_coq_sawcore_prelude" "String -> [(String, String)] -> [String] -> TopLevel ()"
(pureVal writeCoqSAWCorePrelude)
Experimental
[ "Write out a representation of the SAW Core prelude in Gallina syntax for"
, "Coq."
, "The first argument is the name of the file to output into,"
, "use an empty string to output to standard output."
, "The second argument is a list of pairs of notation substitutions:"