forked from cvc5/ethos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstate.cpp
1414 lines (1334 loc) · 39.4 KB
/
state.cpp
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
/******************************************************************************
* This file is part of the ethos project.
*
* Copyright (c) 2023-2024 by the authors listed in the file AUTHORS
* in the top-level source directory and their institutional affiliations.
* All rights reserved. See the file COPYING in the top-level source
* directory for licensing information.
******************************************************************************/
#include "state.h"
#include <iostream>
#include "base/check.h"
#include "base/output.h"
#include "parser.h"
#include "util/filesystem.h"
namespace ethos {
Options::Options()
{
d_parseLet = true;
d_printLet = false;
d_stats = false;
d_statsCompact = false;
d_ruleSymTable = true;
d_normalizeDecimal = true;
d_normalizeHexadecimal = true;
d_normalizeNumeral = false;
d_binderFresh = false;
}
State::State(Options& opts, Stats& stats)
: d_hashCounter(0),
d_hasReference(false),
d_inGarbageCollection(false),
d_tc(*this, opts),
d_opts(opts),
d_stats(stats),
d_plugin(nullptr)
{
ExprValue::d_state = this;
d_absType = Expr(mkExprInternal(Kind::ABSTRACT_TYPE, {}));
// lambda is not builtin?
// forall, exists, choice?
//bindBuiltin("lambda", Kind::LAMBDA, true);
bindBuiltin("->", Kind::FUNCTION_TYPE);
bindBuiltin("_", Kind::APPLY);
bindBuiltin("eo::_", Kind::PARAMETERIZED);
bindBuiltinEval("is_eq", Kind::EVAL_IS_EQ);
bindBuiltinEval("ite", Kind::EVAL_IF_THEN_ELSE);
bindBuiltinEval("requires", Kind::EVAL_REQUIRES);
bindBuiltinEval("hash", Kind::EVAL_HASH);
bindBuiltinEval("nameof", Kind::EVAL_NAME_OF);
bindBuiltinEval("typeof", Kind::EVAL_TYPE_OF);
bindBuiltinEval("var", Kind::EVAL_VAR);
bindBuiltinEval("cmp", Kind::EVAL_COMPARE);
bindBuiltinEval("is_z", Kind::EVAL_IS_Z);
bindBuiltinEval("is_q", Kind::EVAL_IS_Q);
bindBuiltinEval("is_bin", Kind::EVAL_IS_BIN);
bindBuiltinEval("is_str", Kind::EVAL_IS_STR);
bindBuiltinEval("is_bool", Kind::EVAL_IS_BOOL);
bindBuiltinEval("is_var", Kind::EVAL_IS_VAR);
// lists
bindBuiltinEval("nil", Kind::EVAL_NIL);
bindBuiltinEval("cons", Kind::EVAL_CONS);
bindBuiltinEval("list_len", Kind::EVAL_LIST_LENGTH);
bindBuiltinEval("list_concat", Kind::EVAL_LIST_CONCAT);
bindBuiltinEval("list_nth", Kind::EVAL_LIST_NTH);
bindBuiltinEval("list_find", Kind::EVAL_LIST_FIND);
// boolean
bindBuiltinEval("not", Kind::EVAL_NOT);
bindBuiltinEval("and", Kind::EVAL_AND);
bindBuiltinEval("or", Kind::EVAL_OR);
bindBuiltinEval("xor", Kind::EVAL_XOR);
// arithmetic
bindBuiltinEval("add", Kind::EVAL_ADD);
bindBuiltinEval("neg", Kind::EVAL_NEG);
bindBuiltinEval("mul", Kind::EVAL_MUL);
bindBuiltinEval("zdiv", Kind::EVAL_INT_DIV);
bindBuiltinEval("zmod", Kind::EVAL_INT_MOD);
bindBuiltinEval("qdiv", Kind::EVAL_RAT_DIV);
bindBuiltinEval("is_neg", Kind::EVAL_IS_NEG);
bindBuiltinEval("to_z", Kind::EVAL_TO_INT);
bindBuiltinEval("to_q", Kind::EVAL_TO_RAT);
bindBuiltinEval("to_bin", Kind::EVAL_TO_BIN);
bindBuiltinEval("to_str", Kind::EVAL_TO_STRING);
bindBuiltinEval("gt", Kind::EVAL_GT);
// strings
bindBuiltinEval("len", Kind::EVAL_LENGTH);
bindBuiltinEval("concat", Kind::EVAL_CONCAT);
bindBuiltinEval("extract", Kind::EVAL_EXTRACT);
bindBuiltinEval("find", Kind::EVAL_FIND);
// as
bindBuiltinEval("as", Kind::AS);
// we do not export eo::null
// for now, eo::? is (undocumented) syntax for abstract type
bind("eo::?", mkAbstractType());
// self is a distinguished parameter
d_self = Expr(mkSymbolInternal(Kind::PARAM, "eo::self", mkAbstractType()));
bind("eo::self", d_self);
d_conclusion = Expr(mkSymbolInternal(Kind::PARAM, "eo::conclusion", mkBoolType()));
// eo::conclusion is not globally bound, since it can only appear
// in :requires.
// note we don't allow parsing (Proof ...), (Quote ...), or (quote ...).
// common constants
d_type = Expr(mkExprInternal(Kind::TYPE, {}));
d_boolType = Expr(mkExprInternal(Kind::BOOL_TYPE, {}));
d_true = Expr(new Literal(true));
bind("true", d_true);
d_false = Expr(new Literal(false));
bind("false", d_false);
}
State::~State() {}
void State::reset()
{
d_symTable.clear();
d_assumptions.clear();
d_assumptionsSizeCtx.clear();
d_decls.clear();
d_declsSizeCtx.clear();
if (d_plugin!=nullptr)
{
d_plugin->reset();
}
}
void State::pushScope()
{
d_declsSizeCtx.push_back(d_decls.size());
if (d_plugin!=nullptr)
{
d_plugin->pushScope();
}
}
void State::popScope()
{
if (d_plugin!=nullptr)
{
d_plugin->popScope();
}
if (d_declsSizeCtx.empty())
{
EO_FATAL() << "State::popScope: empty context";
}
size_t lastSize = d_declsSizeCtx.back();
d_declsSizeCtx.pop_back();
for (size_t i=lastSize, currSize = d_decls.size(); i<currSize; i++)
{
// Check if overloaded, which is the case if the last overloaded
// declaration had the same name.
if (!d_overloadedDecls.empty() && d_overloadedDecls.back()==d_decls[i])
{
d_overloadedDecls.pop_back();
// it should be overloaded
AppInfo* ai = getAppInfo(d_symTable[d_decls[i]].getValue());
Assert (ai!=nullptr);
Assert (!ai->d_overloads.empty());
ai->d_overloads.pop_back();
if (ai->d_overloads.size()==1)
{
Trace("overload") << "** no-overload: " << d_decls[i] << std::endl;
// no longer overloaded since the overload vector is now size one
ai->d_overloads.clear();
}
// was overloaded, so we don't unbind
continue;
}
d_symTable.erase(d_decls[i]);
}
d_decls.resize(lastSize);
}
void State::pushAssumptionScope()
{
// push scope
pushScope();
// remember assumption size
d_assumptionsSizeCtx.push_back(d_assumptions.size());
}
void State::popAssumptionScope()
{
// process assumptions
size_t lastSize = d_assumptionsSizeCtx.back();
d_assumptionsSizeCtx.pop_back();
d_assumptions.resize(lastSize);
// pop the parsing scope
popScope();
}
bool State::includeFile(const std::string& s, bool isSignature)
{
return includeFile(s, isSignature, false, d_null);
}
bool State::includeFile(const std::string& s, bool isSignature, bool isReference, const Expr& referenceNf)
{
Filepath inputPath;
Filepath file(s);
if (file.isAbsolute())
{
inputPath = file;
}
else
{
inputPath = d_inputFile.parentPath();
inputPath.append(file);
}
inputPath.makeCanonical();
if (!inputPath.exists())
{
return false;
}
if (!markIncluded(inputPath))
{
return true;
}
Assert (!isReference || !d_hasReference);
d_hasReference = isReference;
d_referenceNf = referenceNf;
Filepath currentPath = d_inputFile;
d_inputFile = inputPath;
if (d_plugin!=nullptr)
{
Assert (!isReference);
d_plugin->includeFile(inputPath, isReference, referenceNf);
}
Trace("state") << "Include " << inputPath << std::endl;
Assert (getAssumptionLevel()==0);
Parser p(*this, isSignature, isReference);
p.setFileInput(inputPath.getRawPath());
bool parsedCommand;
do
{
parsedCommand = p.parseNextCommand();
}
while (parsedCommand);
d_inputFile = currentPath;
Trace("state") << "...finished" << std::endl;
if (getAssumptionLevel()!=0)
{
EO_FATAL() << "Including file " << inputPath.getRawPath()
<< " did not preserve assumption scope";
}
return true;
}
bool State::markIncluded(const Filepath& s)
{
std::set<Filepath>::iterator it = d_includes.find(s);
if (it != d_includes.end())
{
return false;
}
d_includes.insert(s);
return true;
}
void State::markDeleted(ExprValue* e)
{
Assert(e != nullptr);
d_stats.d_deleteExprCount++;
if (d_inGarbageCollection)
{
d_toDelete.push_back(e);
return;
}
d_inGarbageCollection = true;
do
{
Kind k = e->getKind();
Trace("gc") << "Delete " << e << " " << k << std::endl;
switch(k)
{
case Kind::NUMERAL:
{
std::unordered_map<Integer, Expr, IntegerHashFunction>::iterator it = d_litIntMap.find(e->asLiteral()->d_int);
Assert (it!=d_litIntMap.end());
d_litIntMap.erase(it);
}
break;
case Kind::DECIMAL:
case Kind::RATIONAL:
{
size_t i = k==Kind::DECIMAL ? 0 : 1;
std::unordered_map<Rational, Expr, RationalHashFunction>& m = d_litRatMap[i];
std::unordered_map<Rational, Expr, RationalHashFunction>::iterator it = m.find(e->asLiteral()->d_rat);
Assert (it!=m.end());
m.erase(it);
}
break;
case Kind::HEXADECIMAL:
case Kind::BINARY:
{
size_t i = k==Kind::HEXADECIMAL ? 0 : 1;
std::unordered_map<BitVector, Expr, BitVectorHashFunction>& m = d_litBvMap[i];
std::unordered_map<BitVector, Expr, BitVectorHashFunction>::iterator it = m.find(e->asLiteral()->d_bv);
Assert (it!=m.end());
m.erase(it);
}
break;
case Kind::STRING:
{
std::unordered_map<String, Expr, StringHashFunction>::iterator it = d_litStrMap.find(e->asLiteral()->d_str);
Assert (it!=d_litStrMap.end());
d_litStrMap.erase(it);
}
break;
default:
{
if (isSymbol(k))
{
std::map<const ExprValue*, AppInfo>::const_iterator it = d_appData.find(e);
if (it != d_appData.end())
{
d_appData.erase(it);
}
}
}
break;
}
std::map<const ExprValue*, size_t>::const_iterator ith = d_hashMap.find(e);
if (ith != d_hashMap.end())
{
d_hashMap.erase(ith);
}
std::map<const ExprValue*, Expr>::const_iterator itt = d_typeCache.find(e);
if (itt != d_typeCache.end())
{
d_typeCache.erase(itt);
}
// remove from the expression trie
ExprTrie* et = &d_trie[e->getKind()];
Assert(et != nullptr);
const std::vector<ExprValue*>& children = e->d_children;
et->remove(children);
// now, free the expression
free(e);
if (!d_toDelete.empty())
{
e = d_toDelete.back();
d_toDelete.pop_back();
}
else
{
e = nullptr;
}
} while (e != nullptr);
d_inGarbageCollection = false;
}
bool State::addAssumption(const Expr& a)
{
d_assumptions.push_back(a);
if (d_hasReference)
{
// only care if at assumption level zero
if (d_assumptionsSizeCtx.empty())
{
Expr aa = a;
if (!d_referenceNf.isNull())
{
aa = mkExpr(Kind::APPLY, {d_referenceNf, a});
}
return d_referenceAsserts.find(aa.getValue()) != d_referenceAsserts.end();
}
}
return true;
}
void State::addReferenceAssert(const Expr& a)
{
Expr aa = a;
if (!d_referenceNf.isNull())
{
aa = mkExpr(Kind::APPLY, {d_referenceNf, a});
}
d_referenceAsserts.insert(aa.getValue());
// ensure ref count
d_referenceAssertList.push_back(aa);
}
void State::setLiteralTypeRule(Kind k, const Expr& t)
{
d_tc.setLiteralTypeRule(k, t);
if (d_plugin!=nullptr)
{
d_plugin->setLiteralTypeRule(k, t);
}
}
Expr State::mkType()
{
return d_type;
}
Expr State::mkTypeConstant(const std::string& name, size_t arity)
{
Expr t;
if (arity == 0)
{
t = d_type;
}
else
{
std::vector<Expr> args;
for (size_t i=0; i<arity; i++)
{
args.push_back(d_type);
}
t = mkFunctionType(args, d_type);
}
return mkSymbol(Kind::CONST, name, t);
}
Expr State::mkFunctionType(const std::vector<Expr>& args, const Expr& ret, bool flatten)
{
if (args.empty())
{
return ret;
}
// process restrictions
if (!flatten)
{
std::vector<ExprValue*> atypes;
for (size_t i = 0, nargs = args.size(); i < nargs; i++)
{
atypes.push_back(args[i].getValue());
}
atypes.push_back(ret.getValue());
return Expr(mkExprInternal(Kind::FUNCTION_TYPE, atypes));
}
Expr curr = ret;
for (size_t i=0, nargs = args.size(); i<nargs; i++)
{
Expr a = args[(nargs-1)-i];
// process arguments
if (a.getKind() == Kind::EVAL_REQUIRES)
{
curr = mkRequires(a[0], a[1], curr);
a = a[2];
}
// append the function
curr = Expr(
mkExprInternal(Kind::FUNCTION_TYPE, {a.getValue(), curr.getValue()}));
}
return curr;
}
Expr State::mkRequires(const std::vector<Expr>& args, const Expr& ret)
{
Expr curr = ret;
for (size_t i=0, nargs=args.size(); i<nargs; i++)
{
size_t ii = (nargs-1)-i;
Assert(args[ii].getKind() == Kind::TUPLE && args[ii].getNumChildren() == 2);
curr = mkRequires(args[ii][0], args[ii][1], curr);
}
return curr;
}
Expr State::mkRequires(const Expr& a1, const Expr& a2, const Expr& ret)
{
if (a1==a2)
{
// trivially equal to return
return ret;
}
return Expr(mkExprInternal(Kind::EVAL_REQUIRES,
{a1.getValue(), a2.getValue(), ret.getValue()}));
}
Expr State::mkAbstractType() { return d_absType; }
Expr State::mkBoolType()
{
return d_boolType;
}
Expr State::mkProofType(const Expr& proven)
{
return Expr(mkExprInternal(Kind::PROOF_TYPE, {proven.getValue()}));
}
Expr State::mkQuoteType(const Expr& t)
{
return Expr(mkExprInternal(Kind::QUOTE_TYPE, {t.getValue()}));
}
Expr State::mkBuiltinType(Kind k)
{
// for now, just use abstract type
return d_absType;
}
Expr State::mkSymbol(Kind k, const std::string& name, const Expr& type)
{
return Expr(mkSymbolInternal(k, name, type));
}
Expr State::mkSelf()
{
return d_self;
}
Expr State::mkConclusion()
{
return d_conclusion;
}
Expr State::mkPair(const Expr& t1, const Expr& t2)
{
return Expr(mkExprInternal(Kind::TUPLE, {t1.getValue(), t2.getValue()}));
}
ExprValue* State::mkSymbolInternal(Kind k,
const std::string& name,
const Expr& type)
{
d_stats.d_mkExprCount++;
// TODO: symbols can be shared if no attributes
/*
std::tuple<Kind, std::string, Expr> key(k, name, type);
std::map<std::tuple<Kind, std::string, Expr>, Expr>::iterator it = d_symcMap.find(key);
if (it!=d_symcMap.end())
{
return it->second;
}
*/
d_stats.d_symCount++;
d_stats.d_exprCount++;
std::vector<ExprValue*> emptyVec;
ExprValue* v = new Literal(k, name);
// immediately set its type
d_typeCache[v] = type;
Trace("type_checker") << "TYPE " << name << " : " << type << std::endl;
//d_symcMap[key] = v;
return v;
}
Expr State::mkExpr(Kind k, const std::vector<Expr>& children)
{
std::vector<ExprValue*> vchildren;
for (const Expr& c : children)
{
vchildren.push_back(c.getValue());
}
if (k==Kind::APPLY)
{
Assert(!children.empty());
// see if there is a special way of building terms for the head
ExprValue* hd = vchildren[0];
// immediately strip off PARAMETERIZED if it exists
hd = hd->getKind()==Kind::PARAMETERIZED ? (*hd)[1] : hd;
AppInfo* ai = getAppInfo(hd);
if (ai!=nullptr)
{
if (ai->d_kind!=Kind::NONE)
{
Trace("state-debug") << "Process builtin app " << ai->d_kind << std::endl;
if (ai->d_kind==Kind::FUNCTION_TYPE)
{
// functions (from parsing) are flattened here
std::vector<Expr> achildren(children.begin()+1, children.end()-1);
return mkFunctionType(achildren, children.back());
}
else if (ai->d_kind==Kind::PARAMETERIZED)
{
// make as tuple
std::vector<Expr> achildren(vchildren.begin()+2, vchildren.end());
return mkParameterized(vchildren[1], achildren);
}
// another builtin operator, possibly APPLY
std::vector<Expr> achildren(children.begin()+1, children.end());
// must call mkExpr again, since we may auto-evaluate
return mkExpr(ai->d_kind, achildren);
}
if (!ai->d_overloads.empty())
{
Trace("overload") << "Use overload when constructing " << k << " " << children << std::endl;
Expr ret = getOverloadInternal(ai->d_overloads, children);
if (!ret.isNull())
{
vchildren[0] = ret.getValue();
Trace("overload") << "...found overload " << ret << std::endl;
return vchildren.size()<=2 ? Expr(mkExprInternal(k, vchildren)) : Expr(mkApplyInternal(vchildren));
}
}
Trace("state-debug") << "Process category " << ai->d_attrCons << " for " << children[0] << std::endl;
size_t nchild = vchildren.size();
// Compute the "constructor term" for the operator, which may involve
// type inference. We store the constructor term in consTerm and operator
// in hdTerm, where notice hdTerm is of kind PARAMETERIZED if consTerm
// (prior to resolution) was PARAMETERIZED. So, for example, applying
// `bvor` to `a` of type `(BitVec 4)` results in
// hdTerm := (PARAMETERIZED (4) bvor),
// consTerm := #b0000.
Expr hdTerm;
Expr consTerm;
d_tc.computedParameterizedInternal(ai, children, hdTerm, consTerm);
Trace("state-debug") << "...updated " << hdTerm << " / " << consTerm << std::endl;
vchildren[0] = hd;
// if it has a constructor attribute
switch (ai->d_attrCons)
{
case Attr::LEFT_ASSOC:
case Attr::RIGHT_ASSOC:
case Attr::LEFT_ASSOC_NIL:
case Attr::RIGHT_ASSOC_NIL:
{
// This means that we don't construct bogus terms when e.g.
// right-assoc-nil operators are used in side condition bodies.
// note that nchild>=2 treats e.g. (or a) as (or a false).
// checking nchild>2 treats (or a) as a function Bool -> Bool.
if (nchild>=2)
{
bool isLeft = (ai->d_attrCons==Attr::LEFT_ASSOC ||
ai->d_attrCons==Attr::LEFT_ASSOC_NIL);
bool isNil = (ai->d_attrCons==Attr::RIGHT_ASSOC_NIL ||
ai->d_attrCons==Attr::LEFT_ASSOC_NIL);
size_t i = 1;
ExprValue* curr = vchildren[isLeft ? i : nchild - i];
std::vector<ExprValue*> cc{hd, nullptr, nullptr};
size_t nextIndex = isLeft ? 2 : 1;
size_t prevIndex = isLeft ? 1 : 2;
if (isNil)
{
if (getConstructorKind(curr) != Attr::LIST)
{
// if the last term is not marked as a list variable and
// we have a null terminator, then we insert the null terminator
Trace("state-debug") << "...insert nil terminator " << consTerm << std::endl;
if (consTerm.isNull())
{
// if we failed to infer a nil terminator (likely due to
// a non-ground parameter), then we insert a placeholder
// (eo::nil f t1 ... tn), which if t1...tn are non-ground
// will evaluate to the proper nil terminator when
// instantiated.
curr = mkExprInternal(Kind::EVAL_NIL, vchildren);
}
else
{
curr = consTerm.getValue();
}
i--;
}
}
// now, add the remaining children
i++;
while (i<nchild)
{
cc[prevIndex] = curr;
cc[nextIndex] = vchildren[isLeft ? i : nchild - i];
// if the "head" child is marked as list, we construct Kind::EVAL_LIST_CONCAT
if (isNil && getConstructorKind(cc[nextIndex]) == Attr::LIST)
{
curr = mkExprInternal(Kind::EVAL_LIST_CONCAT, cc);
}
else
{
curr = mkApplyInternal(cc);
}
i++;
}
Trace("type_checker") << "...return for " << children[0] << std::endl;// << ": " << Expr(curr) << std::endl;
return Expr(curr);
}
// otherwise partial??
}
break;
case Attr::CHAINABLE:
{
std::vector<Expr> cchildren;
Assert(!consTerm.isNull());
cchildren.push_back(consTerm);
std::vector<ExprValue*> cc{hd, nullptr, nullptr};
for (size_t i=1, nchild = vchildren.size()-1; i<nchild; i++)
{
cc[1] = vchildren[i];
cc[2] = vchildren[i + 1];
cchildren.emplace_back(mkApplyInternal(cc));
}
if (cchildren.size()==2)
{
// no need to chain
return cchildren[1];
}
// note this could loop
return mkExpr(Kind::APPLY, cchildren);
}
break;
case Attr::PAIRWISE:
{
std::vector<Expr> cchildren;
Assert(!consTerm.isNull());
cchildren.push_back(consTerm);
std::vector<ExprValue*> cc{hd, nullptr, nullptr};
for (size_t i=1, nchild = vchildren.size(); i<nchild-1; i++)
{
for (size_t j=i+1; j<nchild; j++)
{
cc[1] = vchildren[i];
cc[2] = vchildren[j];
cchildren.emplace_back(mkApplyInternal(cc));
}
}
if (cchildren.size()==2)
{
// no need to chain
return cchildren[1];
}
// note this could loop
return mkExpr(Kind::APPLY, cchildren);
}
break;
case Attr::OPAQUE:
{
// determine how many opaque children
Expr hdt = Expr(hd);
const Expr& t = d_tc.getType(hdt);
Assert (t.getKind()==Kind::FUNCTION_TYPE);
size_t nargs = t.getNumChildren()-1;
if (nargs>=children.size())
{
Warning() << "Too few arguments when applying opaque symbol " << hdt << std::endl;
}
else
{
std::vector<Expr> ochildren(children.begin(), children.begin()+1+nargs);
Expr op = mkExpr(Kind::APPLY_OPAQUE, ochildren);
Trace("opaque") << "Construct opaque operator " << op << std::endl;
if (nargs+1==children.size())
{
Trace("opaque") << "...return operator" << std::endl;
return op;
}
// higher order
std::vector<Expr> rchildren;
rchildren.push_back(op);
rchildren.insert(rchildren.end(), children.begin()+1+nargs, children.end());
Trace("opaque") << "...return operator applied to children" << std::endl;
return mkExpr(Kind::APPLY, rchildren);
}
}
default:
break;
}
}
Kind hk = hd->getKind();
if (hk==Kind::LAMBDA)
{
// beta-reduce eagerly, if the correct arity
const std::vector<ExprValue*>& vars = (*hd)[0]->getChildren();
size_t nvars = vars.size();
if (nvars==children.size()-1)
{
Ctx ctx;
for (size_t i=0; i<nvars; i++)
{
ctx[vars[i]] = vchildren[i + 1];
}
Expr ret = d_tc.evaluate((*hd)[1], ctx);
Trace("state") << "BETA_REDUCE " << Expr((*hd)[1]) << " " << ctx << " = " << ret << std::endl;
return ret;
}
else
{
Warning() << "Wrong number of arguments when applying " << Expr(hd) << std::endl;
}
}
else if (hk==Kind::PROGRAM_CONST || hk==Kind::ORACLE)
{
// have to check whether we have marked the constructor kind, which is
// not the case i.e. if we are constructing applications corresponding to
// the cases in the program definition itself.
if (getConstructorKind(hd)!=Attr::NONE)
{
Expr hdt = Expr(hd);
const Expr& t = d_tc.getType(hdt);
// only do this if the correct arity
if (t.getNumChildren() == children.size())
{
Ctx ctx;
Expr e = d_tc.evaluateProgramInternal(vchildren, ctx);
if (!e.isNull())
{
Expr ret = d_tc.evaluate(e.getValue(), ctx);
Trace("state") << "EAGER_EVALUATE " << ret << std::endl;
return ret;
}
}
else
{
Warning() << "Wrong number of arguments when applying program " << Expr(hd)
<< ", " << t.getNumChildren() << " arguments expected, got "
<< children.size() << std::endl;
}
}
}
// Most functions are unary and require currying if applied to more than one argument.
// The exceptions to this are operators whose types are not flattened (programs and proof rules).
if (children.size()>2)
{
if (hk!=Kind::PROGRAM_CONST && hk!=Kind::PROOF_RULE && hk!=Kind::ORACLE)
{
// return the curried version
return Expr(mkApplyInternal(vchildren));
}
}
}
else if (isLiteralOp(k))
{
// only if correct arity, else we will catch the type error
bool isArityOk = TypeChecker::checkArity(k, vchildren.size());
if (isArityOk)
{
// return the evaluation
return d_tc.evaluateLiteralOp(k, vchildren);
}
else
{
Warning() << "Wrong number of arguments when applying literal op " << k
<< ", " << children.size() << " arguments" << std::endl;
}
}
else if (k==Kind::AS)
{
// if it has 2 children, process it, otherwise we make the bogus term
// below
if (vchildren.size()==2)
{
Trace("overload") << "process eo::as " << children[0] << " " << children[1] << std::endl;
AppInfo* ai = getAppInfo(vchildren[0]);
Expr ret = children[0];
std::pair<std::vector<Expr>, Expr> ftype = children[1].getFunctionType();
Expr reto;
// look up the overload
std::vector<Expr> dummyChildren;
dummyChildren.push_back(children[1]);
for (const Expr& t : ftype.first)
{
dummyChildren.emplace_back(mkSymbol(Kind::CONST, "tmp", t));
}
if (ai!=nullptr && !ai->d_overloads.empty())
{
Trace("overload") << "...overloaded" << std::endl;
reto = getOverloadInternal(ai->d_overloads, dummyChildren, ftype.second.getValue());
}
else
{
Trace("overload") << "...not overloaded" << std::endl;
reto = getOverloadInternal({children[0]}, dummyChildren, ftype.second.getValue());
}
if (!reto.isNull())
{
Trace("overload") << "...found overload " << reto << " " << d_tc.getType(reto) << std::endl;
return reto;
}
}
}
return Expr(mkExprInternal(k, vchildren));
}
Expr State::mkTrue()
{
return d_true;
}
Expr State::mkFalse()
{
return d_false;
}
Expr State::mkLiteral(Kind k, const std::string& s)
{
// convert string to literal
Literal lit;
switch (k)
{
case Kind::BOOLEAN:
Assert (s=="true" || s=="false");
return s=="true" ? d_true : d_false;
break;
case Kind::NUMERAL: lit = Literal(Integer(s)); break;
case Kind::DECIMAL: lit = Literal(k, Rational::fromDecimal(s)); break;
case Kind::RATIONAL: lit = Literal(k, Rational(s)); break;
case Kind::HEXADECIMAL: lit = Literal(k, BitVector(s, 16)); break;
case Kind::BINARY: lit = Literal(k, BitVector(s, 2)); break;
case Kind::STRING: lit = Literal(String(s, true)); break;
default:
EO_FATAL() << "Unknown kind for mkLiteral " << k;
break;
}
return Expr(mkLiteralInternal(lit));
}
Expr State::mkParameterized(const ExprValue* hd, const std::vector<Expr>& params)
{
return mkExpr(Kind::PARAMETERIZED, {mkExpr(Kind::TUPLE, params), Expr(hd)});
}
ExprValue* State::mkLiteralInternal(Literal& l)
{
d_stats.d_mkExprCount++;
ExprValue * ev;
Kind k = l.getKind();
switch (k)
{
case Kind::BOOLEAN:
return l.d_bool ? d_true.getValue() : d_false.getValue();
case Kind::NUMERAL:
{
std::unordered_map<Integer, Expr, IntegerHashFunction>::iterator it = d_litIntMap.find(l.d_int);
if (it!=d_litIntMap.end())
{
return it->second.getValue();
}
ev = new Literal(l.d_int);
d_litIntMap[l.d_int] = Expr(ev);
}
break;
case Kind::DECIMAL:
case Kind::RATIONAL:
{
size_t i = k==Kind::DECIMAL ? 0 : 1;
std::unordered_map<Rational, Expr, RationalHashFunction>& m = d_litRatMap[i];
std::unordered_map<Rational, Expr, RationalHashFunction>::iterator it = m.find(l.d_rat);
if (it!=m.end())
{
return it->second.getValue();
}
ev = new Literal(k, l.d_rat);
m[l.d_rat] = Expr(ev);
}
break;
case Kind::HEXADECIMAL:
case Kind::BINARY:
{
size_t i = k==Kind::HEXADECIMAL ? 0 : 1;
std::unordered_map<BitVector, Expr, BitVectorHashFunction>& m = d_litBvMap[i];
std::unordered_map<BitVector, Expr, BitVectorHashFunction>::iterator it = m.find(l.d_bv);
if (it!=m.end())
{
return it->second.getValue();
}
ev = new Literal(k, l.d_bv);
m[l.d_bv] = Expr(ev);
}
break;
case Kind::STRING:
{
std::unordered_map<String, Expr, StringHashFunction>::iterator it = d_litStrMap.find(l.d_str);
if (it!=d_litStrMap.end())
{
return it->second.getValue();
}
ev = new Literal(l.d_str);
d_litStrMap[l.d_str] = Expr(ev);
}
break;
default:
EO_FATAL() << "Unknown kind for mkLiteralInternal " << l.getKind();
break;
}
d_stats.d_litCount++;
d_stats.d_exprCount++;
return ev;
}
ExprValue* State::mkApplyInternal(const std::vector<ExprValue*>& children)
{
Assert(children.size() > 2);
// requires currying
ExprValue* curr = children[0];
for (size_t i=1, nchildren = children.size(); i<nchildren; i++)
{
curr = mkExprInternal(Kind::APPLY, {curr, children[i]});
}
return curr;
}
ExprValue* State::mkExprInternal(Kind k,
const std::vector<ExprValue*>& children)
{
d_stats.d_mkExprCount++;
ExprTrie* et = &d_trie[k];
et = et->get(children);
if (et->d_data!=nullptr)
{
return et->d_data;
}