-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathexpr_parser.cpp
More file actions
1534 lines (1490 loc) · 45.6 KB
/
expr_parser.cpp
File metadata and controls
1534 lines (1490 loc) · 45.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
* 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 "expr_parser.h"
#include <string.h>
#include <iostream>
#include "base/check.h"
#include "base/output.h"
#include "type_checker.h"
namespace ethos {
/**
* Definition of state identifiers when parsing terms
*
* This is required for non-recursive parsing of terms. Note that in SMT-LIB,
* terms generally are of the form (...anything not involving terms... <term>*)
* However, let-terms, match-terms, and terms appearing within attributes
* for term annotations are exceptions to this.
* Thus, in the main parsing loop in parseExpr below, we require tracking
* the context we are in, which dictates how to setup parsing the term after
* the current one.
*
* In each state, the stack frame contains a list of arguments `d_args`, which
* give a recipe for the term we are parsing. The interpretation of args depends
* on the context we are in, as documented below.
*/
enum class ParseCtx
{
NONE,
/**
* NEXT_ARG: in context (<op> <term>* <term>
* `args` contain the accumulated list of arguments.
*/
NEXT_ARG,
/**
* Let bindings
*
* LET_NEXT_BIND: in context (let (<binding>* (<symbol> <term>
*
* LET_BODY: in context (let (<binding>*) <term>
*/
LET_NEXT_BIND,
LET_BODY,
/**
* Match terms
*
* MATCH_HEAD: in context (match <term>
*
* MATCH_NEXT_CASE: in context (match <term> (<case>* (<pattern> <term>
* or in context (match <term> (<case>* (<pattern>.
* `args` contains the head, plus a list of arguments of the form
* (TUPLE t1 t2), denoting the cases we have parsed. Optionally, the
* last element of args is a (non-TUPLE) term denoting the pattern.
*/
MATCH_HEAD,
MATCH_NEXT_CASE,
/**
* Term annotations
*
* TERM_ANNOTATE_BODY: in context (! <term> <attribute>* <attribute>
* `args` contains the term we parsed, which is modified based on the
* attributes read.
*/
TERM_ANNOTATE_BODY
};
ExprParser::ExprParser(Lexer& lex, State& state, bool isSignature)
: d_lex(lex), d_state(state), d_isSignature(isSignature)
{
d_strToAttr[":var"] = Attr::VAR;
d_strToAttr[":implicit"] = Attr::IMPLICIT;
d_strToAttr[":type"] = Attr::TYPE;
d_strToAttr[":list"] = Attr::LIST;
d_strToAttr[":requires"] = Attr::REQUIRES;
d_strToAttr[":left-assoc"] = Attr::LEFT_ASSOC;
d_strToAttr[":right-assoc"] = Attr::RIGHT_ASSOC;
d_strToAttr[":left-assoc-nil"] = Attr::LEFT_ASSOC_NIL;
d_strToAttr[":right-assoc-nil"] = Attr::RIGHT_ASSOC_NIL;
d_strToAttr[":chainable"] = Attr::CHAINABLE;
d_strToAttr[":pairwise"] = Attr::PAIRWISE;
d_strToAttr[":binder"] = Attr::BINDER;
d_strToAttr[":let-binder"] = Attr::LET_BINDER;
d_strToAttr[":opaque"] = Attr::OPAQUE;
d_strToAttr[":syntax"] = Attr::SYNTAX;
d_strToAttr[":restrict"] = Attr::RESTRICT;
d_strToAttr[":sorry"] = Attr::SORRY;
d_strToLiteralKind["<boolean>"] = Kind::BOOLEAN;
d_strToLiteralKind["<numeral>"] = Kind::NUMERAL;
d_strToLiteralKind["<decimal>"] = Kind::DECIMAL;
d_strToLiteralKind["<rational>"] = Kind::RATIONAL;
d_strToLiteralKind["<hexadecimal>"] = Kind::HEXADECIMAL;
d_strToLiteralKind["<binary>"] = Kind::BINARY;
d_strToLiteralKind["<string>"] = Kind::STRING;
}
class StackFrame
{
public:
StackFrame(ParseCtx ctx, size_t nscopes = 0) :
d_ctx(ctx), d_nscopes(nscopes) {}
StackFrame(ParseCtx ctx, size_t nscopes, const std::vector<Expr>& args) :
d_ctx(ctx), d_nscopes(nscopes), d_args(args) {}
ParseCtx d_ctx;
size_t d_nscopes;
std::vector<Expr> d_args;
void pop(State& s)
{
// process the scope change
for (size_t i=0; i<d_nscopes; i++)
{
s.popScope();
}
}
};
Expr ExprParser::parseExpr()
{
// the last parsed term
Expr ret;
// a request was made to update the current parse context
bool needsUpdateCtx = false;
// the last token we read
Token tok;
// The stack(s) containing the parse context, the number of scopes, and the
// arguments for the current expression we are building.
std::vector<StackFrame> pstack;
// Let bindings, dynamically allocated for each let in scope.
std::vector<std::vector<std::pair<std::string, Expr>>> letBinders;
do
{
// At this point, we are ready to parse the next term
tok = d_lex.nextToken();
Expr currExpr;
switch (tok)
{
// ------------------- open paren
case Token::LPAREN:
{
tok = d_lex.nextToken();
switch (tok)
{
case Token::LET:
case Token::EVAL_DEFINE:
{
pstack.emplace_back(ParseCtx::LET_NEXT_BIND);
needsUpdateCtx = true;
letBinders.emplace_back();
}
break;
case Token::EVAL_MATCH:
{
// parse the variable list
d_state.pushScope();
std::vector<Expr> vs = parseAndBindSortedVarList(Kind::PROGRAM);
std::vector<Expr> args;
args.emplace_back(d_state.mkExpr(Kind::TUPLE, vs));
pstack.emplace_back(ParseCtx::MATCH_HEAD, 1, args);
}
break;
case Token::ATTRIBUTE:
pstack.emplace_back(ParseCtx::TERM_ANNOTATE_BODY);
break;
case Token::LPAREN:
{
// we allow the syntax ((_ to begin a term
pstack.emplace_back(ParseCtx::NEXT_ARG);
tok = d_lex.nextToken();
if (tokenStrToSymbol(tok)!="_")
{
d_lex.parseError("Expected indexed symbol as head of apply");
}
}
case Token::SYMBOL:
case Token::QUOTED_SYMBOL:
{
// function identifier
std::string name = tokenStrToSymbol(tok);
std::vector<Expr> args;
Expr v = getVar(name);
args.push_back(v);
size_t nscopes = 0;
// if a binder, read a variable list and push a scope
Attr ck = d_state.getConstructorKind(v.getValue());
if (ck==Attr::BINDER || ck==Attr::LET_BINDER)
{
// If it is a binder, immediately read the bound variable list.
// We make calls to State::getBoundVar meaning the bound variables
// are unique for each (name, type) pair.
// We only do this if there are two left parentheses. Otherwise we
// will parse a tuple term that stands for a symbolic bound
// variable list. We do this because there are no terms that
// begin ((... currently allowed in this parser.
// Note we use nextToken here since we cannot peek more than once.
tok = d_lex.nextToken();
if (tok==Token::LPAREN)
{
tok = d_lex.peekToken();
d_lex.reinsertToken(Token::LPAREN);
if (tok==Token::LPAREN)
{
if (ck==Attr::BINDER)
{
nscopes = 1;
d_state.pushScope();
std::vector<Expr> vs =
parseAndBindSortedVarList(Kind::NONE);
if (vs.empty())
{
d_lex.parseError("Expected non-empty sorted variable list");
}
Expr vl = d_state.mkBinderList(v.getValue(), vs);
args.push_back(vl);
}
else
{
Assert (ck==Attr::LET_BINDER);
nscopes = 1;
d_state.pushScope();
std::vector<std::pair<Expr, Expr>> lls = parseAndBindLetList();
if (lls.empty())
{
d_lex.parseError("Expected non-empty let list");
}
Expr vl = d_state.mkLetBinderList(v.getValue(), lls);
args.push_back(vl);
}
}
}
else
{
d_lex.reinsertToken(tok);
}
}
pstack.emplace_back(ParseCtx::NEXT_ARG, nscopes, args);
}
break;
case Token::UNTERMINATED_QUOTED_SYMBOL:
d_lex.parseError("Expected SMT-LIBv2 operator", true);
break;
default:
d_lex.unexpectedTokenError(tok, "Expected SMT-LIBv2 operator");
break;
}
}
break;
// ------------------- close paren
case Token::RPAREN:
{
StackFrame& sf = pstack.back();
// should only be here if we are expecting arguments
if (pstack.empty() || sf.d_ctx != ParseCtx::NEXT_ARG)
{
d_lex.unexpectedTokenError(
tok, "Mismatched parentheses in SMT-LIBv2 term");
}
// Construct the application term specified by tstack.back()
ret = d_state.mkExpr(Kind::APPLY, sf.d_args);
//typeCheck(ret);
// pop the stack
sf.pop(d_state);
pstack.pop_back();
}
break;
// ------------------- base cases
case Token::SYMBOL:
case Token::QUOTED_SYMBOL:
{
std::string name = tokenStrToSymbol(tok);
ret = getVar(name);
if (ret.getKind()==Kind::BUILTIN_CONST)
{
std::stringstream ss;
ss << "Cannot use \"" << name << "\" as a first-class term.";
d_lex.parseError(ss.str());
}
}
break;
case Token::INTEGER_LITERAL:
{
// normalize to rational if not signature and option is set
if (!d_isSignature && d_state.getOptions().d_normalizeNumeral)
{
Rational r(d_lex.tokenStr());
ret = d_state.mkLiteral(Kind::RATIONAL, r.toString());
}
else
{
ret = d_state.mkLiteral(Kind::NUMERAL, d_lex.tokenStr());
}
}
break;
case Token::DECIMAL_LITERAL:
{
// normalize to rational if not signature and option is set
if (!d_isSignature && d_state.getOptions().d_normalizeDecimal)
{
// normalize from decimal
Rational r = Rational::fromDecimal(d_lex.tokenStr());
ret = d_state.mkLiteral(Kind::RATIONAL, r.toString());
}
else
{
ret = d_state.mkLiteral(Kind::DECIMAL, d_lex.tokenStr());
}
}
break;
case Token::RATIONAL_LITERAL:
{
std::string s = d_lex.tokenStr();
size_t spos = s.find('/');
if (spos != std::string::npos)
{
// Ensure the denominator contains a non-zero digit. We catch this here to
// avoid a floating point exception in GMP. This exception will be caught
// and given the standard error message below.
if (s.find_first_not_of('0', spos + 1) == std::string::npos)
{
d_lex.parseError("Expected non-zero denominator", true);
}
}
ret = d_state.mkLiteral(Kind::RATIONAL, s);
}
break;
case Token::HEX_LITERAL:
{
std::string hexStr = d_lex.tokenStr();
hexStr = hexStr.substr(2);
// normalize to binary if not signature and option is set
if (!d_isSignature && d_state.getOptions().d_normalizeHexadecimal)
{
// normalize from hexadecimal
BitVector bv(hexStr, 16);
ret = d_state.mkLiteral(Kind::BINARY, bv.toString());
}
else
{
ret = d_state.mkLiteral(Kind::HEXADECIMAL, hexStr);
}
}
break;
case Token::BINARY_LITERAL:
{
std::string binStr = d_lex.tokenStr();
binStr = binStr.substr(2);
ret = d_state.mkLiteral(Kind::BINARY, binStr);
}
break;
case Token::STRING_LITERAL:
{
std::string s = d_lex.tokenStr();
unescapeString(s);
// now, must run through String utility so that its unicode
// handling is unique
String str(s, true);
ret = d_state.mkLiteral(Kind::STRING, str.toString());
}
break;
case Token::ABSTRACT_TYPE:
ret = d_state.mkAbstractType();
break;
case Token::TYPE:
ret = d_state.mkType();
break;
case Token::BOOL_TYPE:
ret = d_state.mkBoolType();
break;
case Token::UNTERMINATED_QUOTED_SYMBOL:
d_lex.parseError("Expected SMT-LIBv2 term", true);
break;
default:
d_lex.unexpectedTokenError(tok, "Expected SMT-LIBv2 term");
break;
}
// Based on the current context, setup next parsed term.
// We do this only if a context is allocated (!tstack.empty()) and we
// either just finished parsing a term (!ret.isNull()), or otherwise have
// indicated that we need to update the context (needsUpdateCtx).
while (!pstack.empty() && (!ret.isNull() || needsUpdateCtx))
{
needsUpdateCtx = false;
StackFrame& sf = pstack.back();
switch (sf.d_ctx)
{
// ------------------------- argument lists
case ParseCtx::NEXT_ARG:
{
Assert(!ret.isNull());
// add it to the list of arguments and clear
sf.d_args.push_back(ret);
ret = d_null;
}
break;
// ------------------------- let terms
case ParseCtx::LET_NEXT_BIND:
{
// if we parsed a term, process it as a binding
if (!ret.isNull())
{
Assert(!letBinders.empty());
std::vector<std::pair<std::string, Expr>>& bs = letBinders.back();
// add binding from the symbol to ret
Assert(!bs.empty());
bs.back().second = ret;
ret = d_null;
// close the current binding
d_lex.eatToken(Token::RPAREN);
}
else
{
// eat the opening left parenthesis of the binding list
d_lex.eatToken(Token::LPAREN);
}
// see if there is another binding
if (d_lex.eatTokenChoice(Token::LPAREN, Token::RPAREN))
{
// (, another binding: setup parsing the next term
// get the symbol and store in the ParseOp
std::string name = parseSymbol();
std::vector<std::pair<std::string, Expr>>& bs = letBinders.back();
bs.emplace_back(name, Expr());
}
else
{
// ), we are now looking for the body of the let
sf.d_ctx = ParseCtx::LET_BODY;
sf.d_nscopes++;
// push scope
d_state.pushScope();
// implement the bindings
Assert(!letBinders.empty());
std::vector<std::pair<std::string, Expr>>& bs =
letBinders.back();
for (std::pair<std::string, Expr>& b : bs)
{
bind(b.first, b.second);
}
// done with the binders
letBinders.pop_back();
}
}
break;
case ParseCtx::LET_BODY:
{
// the let body is the returned term
d_lex.eatToken(Token::RPAREN);
sf.pop(d_state);
pstack.pop_back();
}
break;
// ------------------------- annotated terms
case ParseCtx::TERM_ANNOTATE_BODY:
{
// now parse attribute list
AttrMap attrs;
bool pushedScope = false;
// NOTE parsing attributes may trigger recursive calls to this
// method.
parseAttributeList(Kind::NONE, ret, attrs, pushedScope);
// the scope of the variable is one level up
if (pushedScope && pstack.size()>1)
{
pstack[pstack.size()-2].d_nscopes++;
}
// process the attributes
for (std::pair<const Attr, std::vector<Expr>>& a : attrs)
{
switch(a.first)
{
case Attr::VAR:
Assert (a.second.size()==1);
// it is now (Quote v) for that variable
ret = d_state.mkQuoteType(a.second[0]);
break;
case Attr::IMPLICIT:
// the term will not be added as an argument to the parent
// note this always comes after VAR due to enum order
ret = d_state.mkNullType();
break;
case Attr::REQUIRES:
if (ret.isNull())
{
d_lex.parseError("Cannot mark requires on implicit argument");
}
ret = d_state.mkRequires(a.second, ret);
break;
case Attr::OPAQUE:
if (ret.isNull())
{
d_lex.parseError("Cannot mark opaque on implicit argument");
}
if (ret.getKind()==Kind::EVAL_REQUIRES)
{
d_lex.parseError("Cannot combine opaque and requires");
}
ret = d_state.mkExpr(Kind::OPAQUE_TYPE, {ret});
break;
default:
// ignored
std::stringstream ss;
ss << "Unprocessed attribute " << a.first;
d_lex.warning(ss.str());
break;
}
}
d_lex.eatToken(Token::RPAREN);
// finished parsing attributes, ret is either nullptr if implicit,
// or the term we parsed as the body of the annotation.
sf.pop(d_state);
pstack.pop_back();
}
break;
// ------------------------- match terms
case ParseCtx::MATCH_HEAD:
{
Assert(!ret.isNull());
// add the head
sf.d_args.push_back(ret);
ret = d_null;
d_lex.eatToken(Token::LPAREN);
// we now parse a pattern
sf.d_ctx = ParseCtx::MATCH_NEXT_CASE;
needsUpdateCtx = true;
}
break;
case ParseCtx::MATCH_NEXT_CASE:
{
std::vector<Expr>& args = sf.d_args;
bool checkNextPat = true;
if (!ret.isNull())
{
// if we just got done parsing a term (either a pattern or a return)
Expr last = args.back();
if (args.size() > 2 && last.getKind() != Kind::TUPLE)
{
// case where we just read a return value
// replace the back of this with a pair
args.back() = d_state.mkPair(last, ret);
d_lex.eatToken(Token::RPAREN);
}
else
{
// case where we just read a pattern
args.push_back(ret);
checkNextPat = false;
}
ret = d_null;
}
// if no more cases, we are done
if (checkNextPat)
{
if (d_lex.eatTokenChoice(Token::RPAREN, Token::LPAREN))
{
d_lex.eatToken(Token::RPAREN);
Trace("parser") << "Parsed match " << args << std::endl;
// make a program
if (args.size()<=2)
{
d_lex.parseError("Expected non-empty list of cases");
}
Expr atype = d_state.mkAbstractType();
// environment is the variable list
std::vector<Expr> vl;
for (size_t i = 0, nchildren = args[0].getNumChildren();
i < nchildren;
i++)
{
vl.push_back(args[0][i]);
}
Expr hd = args[1];
std::vector<Expr> caseArgs(args.begin()+2, args.end());
std::vector<Expr> allVars = Expr::getVariables(caseArgs);
std::vector<Expr> env;
std::vector<Expr> fargTypes;
fargTypes.push_back(atype);
for (const Expr& v : allVars)
{
if (std::find(vl.begin(), vl.end(), v)==vl.end())
{
// A variable not appearing in the local binding of the match,
// add it to the environment.
env.push_back(v);
// It will be an argument to the internal program
fargTypes.push_back(atype);
}
}
Trace("parser") << "Binder is " << vl << std::endl;
Trace("parser") << "Env is " << env << std::endl;
// make the program variable, whose type is abstract
Expr ftype = d_state.mkFunctionType(fargTypes, atype, false);
std::stringstream pvname;
pvname << "eo::match_" << hd;
Expr pv = d_state.mkSymbol(Kind::PROGRAM_CONST, pvname.str(), ftype);
// process the cases
std::vector<Expr> cases;
for (size_t i=0, nargs = caseArgs.size(); i<nargs; i++)
{
const Expr& cs = caseArgs[i];
Assert(cs.getKind() == Kind::TUPLE);
const Expr& lhs = cs[0];
// check that variables in the pattern are only from the binder
ensureBound(lhs, vl);
const Expr& rhs = cs[1];
std::vector<Expr> appArgs{pv, lhs};
appArgs.insert(appArgs.end(), env.begin(), env.end());
Expr lhsa = d_state.mkExpr(Kind::APPLY, appArgs);
cases.push_back(d_state.mkPair(lhsa, rhs));
// check free variable requirement
std::vector<Expr> bvsl = Expr::getVariables(lhs);
std::vector<Expr> bvsr = Expr::getVariables(rhs);
for (const Expr& v : bvsr)
{
// if not in the locally bound variable list, skip
if (std::find(vl.begin(), vl.end(), v)==vl.end())
{
continue;
}
// otherwise, must be in the left hand side
if (std::find(bvsl.begin(), bvsl.end(), v)==bvsl.end())
{
std::stringstream msg;
msg << "Unexpected free parameter in match case:" << std::endl;
msg << " Expression: " << rhs << std::endl;
msg << " Free parameter: " << v << std::endl;
msg << "Does not occur in: " << lhs << std::endl;
d_lex.parseError(msg.str());
}
}
}
Expr prog = d_state.mkExpr(Kind::PROGRAM, cases);
d_state.defineProgram(pv, prog);
std::vector<Expr> appArgs{pv, hd};
appArgs.insert(appArgs.end(), env.begin(), env.end());
ret = d_state.mkExpr(Kind::APPLY, appArgs);
// pop the stack
sf.pop(d_state);
pstack.pop_back();
}
}
// otherwise, ready to parse the next expression
}
break;
default: break;
}
}
// otherwise ret will be returned
} while (!pstack.empty());
return ret;
}
Expr ExprParser::parseType()
{
Expr e = parseExpr();
// ensure it is a type
typeCheck(e, d_state.mkType());
// should not contain stuck term
if (e.isGround() && e.isEvaluatable())
{
std::stringstream msg;
msg << "Parsed type has an unevalated term:" << std::endl;
msg << "Type: " << e << std::endl;
d_lex.parseError(msg.str());
}
return e;
}
Expr ExprParser::parseFormula()
{
Expr e = parseExpr();
// ensure it has type Bool
typeCheck(e, d_state.mkBoolType());
return e;
}
std::vector<Expr> ExprParser::parseExprList()
{
d_lex.eatToken(Token::LPAREN);
std::vector<Expr> terms;
Token tok = d_lex.nextToken();
while (tok != Token::RPAREN)
{
d_lex.reinsertToken(tok);
Expr t = parseExpr();
terms.push_back(t);
tok = d_lex.nextToken();
}
return terms;
}
std::vector<Expr> ExprParser::parseTypeList()
{
d_lex.eatToken(Token::LPAREN);
std::vector<Expr> terms;
Token tok = d_lex.nextToken();
while (tok != Token::RPAREN)
{
d_lex.reinsertToken(tok);
Expr t = parseType();
terms.push_back(t);
tok = d_lex.nextToken();
}
return terms;
}
Expr ExprParser::parseExprPair()
{
d_lex.eatToken(Token::LPAREN);
Expr t1 = parseExpr();
Expr t2 = parseExpr();
d_lex.eatToken(Token::RPAREN);
return d_state.mkPair(t1, t2);
}
std::string ExprParser::parseSymbolicExpr()
{
std::stringstream ss;
size_t nparen = 0;
Token tok;
do
{
tok = d_lex.nextToken();
switch (tok)
{
case Token::LPAREN: nparen++; break;
case Token::RPAREN: nparen--; break;
case Token::EOF_TOK:
{
d_lex.parseError("Expected s-expression");
}
break;
default: break;
}
ss << d_lex.tokenStr() << " ";
}while (nparen!=0);
return ss.str();
}
std::vector<Expr> ExprParser::parseExprPairList()
{
d_lex.eatToken(Token::LPAREN);
std::vector<Expr> terms;
while (d_lex.eatTokenChoice(Token::LPAREN, Token::RPAREN))
{
Expr t1 = parseExpr();
Expr t2 = parseExpr();
Expr t = d_state.mkPair(t1, t2);
terms.push_back(t);
d_lex.eatToken(Token::RPAREN);
}
return terms;
}
std::vector<Expr> ExprParser::parseAndBindSortedVarList(Kind k)
{
std::map<ExprValue*, AttrMap> amap;
std::vector<Expr> vars = parseAndBindSortedVarList(k, amap);
processAttributeMaps(amap);
return vars;
}
std::vector<Expr> ExprParser::parseAndBindSortedVarList(
Kind k, std::map<ExprValue*, AttrMap>& amap)
{
std::vector<Expr> varList;
d_lex.eatToken(Token::LPAREN);
std::string name;
Expr t;
// while the next token is LPAREN, exit if RPAREN
while (d_lex.eatTokenChoice(Token::LPAREN, Token::RPAREN))
{
name = parseSymbol();
t = parseType();
Expr v;
bool isImplicit = false;
if (k == Kind::NONE)
{
// lookup and type check
v = d_state.getBoundVar(name, t);
// bind it for now
bind(name, v);
}
else
{
v = d_state.mkSymbol(Kind::PARAM, name, t);
bind(name, v);
// parse attribute list
AttrMap& attrs = amap[v.getValue()];
// all other parameter lists make fresh parameters, pass along the
// parameter list kind k
parseAttributeList(Kind::PARAM, v, attrs, k);
if (attrs.find(Attr::IMPLICIT)!=attrs.end())
{
attrs.erase(Attr::IMPLICIT);
isImplicit = true;
}
}
d_lex.eatToken(Token::RPAREN);
if (!isImplicit)
{
varList.push_back(v);
}
}
return varList;
}
std::vector<std::pair<Expr, Expr>> ExprParser::parseAndBindLetList()
{
std::vector<std::pair<Expr, Expr>> letList;
d_lex.eatToken(Token::LPAREN);
std::string name;
Expr v, t, tt;
// while the next token is LPAREN, exit if RPAREN
while (d_lex.eatTokenChoice(Token::LPAREN, Token::RPAREN))
{
name = parseSymbol();
t = parseExpr();
d_lex.eatToken(Token::RPAREN);
tt = typeCheck(t);
v = d_state.mkSymbol(Kind::VARIABLE, name, tt);
letList.emplace_back(v, t);
}
// now perform the bindings, which bind to the variable, not its definition
for (std::pair<Expr, Expr>& ll : letList)
{
bind(ll.first.getSymbol(), ll.first);
}
return letList;
}
std::string ExprParser::parseSymbol()
{
Token tok = d_lex.nextToken();
return tokenStrToSymbol(tok);
}
std::vector<std::string> ExprParser::parseSymbolList()
{
d_lex.eatToken(Token::LPAREN);
std::vector<std::string> symbols;
Token tok = d_lex.nextToken();
while (tok != Token::RPAREN)
{
d_lex.reinsertToken(tok);
std::string sym = parseSymbol();
symbols.push_back(sym);
tok = d_lex.nextToken();
}
return symbols;
}
bool ExprParser::parseDatatypesDef(
const std::vector<std::string>& dnames,
const std::vector<size_t>& arities,
std::map<const ExprValue*, std::vector<Expr>>& dts,
std::map<const ExprValue*, std::vector<Expr>>& dtcons,
std::unordered_set<const ExprValue*>& ambCons)
{
Assert(dnames.size() == arities.size()
|| (dnames.size() == 1 && arities.empty()));
// Declare the datatypes that are currently being defined as unresolved
// types. If we do not know the arity of the datatype yet, we wait to
// define it until parsing the preamble of its body, which may optionally
// involve `par`. This is limited to the case of single datatypes defined
// via declare-datatype, and hence no datatype body is parsed without
// having all types declared. This ensures we can parse datatypes with
// nested recursion, e.g. datatypes D having a subfield type
// (Array Int D).
std::vector<Expr> dtlist;
for (unsigned i = 0, dsize = dnames.size(); i < dsize; i++)
{
if (i >= arities.size())
{
// do not know the arity yet
continue;
}
// make the datatype, which has the given arity
Expr t = d_state.mkTypeConstant(dnames[i], arities[i]);
// bind
if (!d_state.bind(dnames[i], t))
{
return false;
}
dtlist.push_back(t);
}
// while we get another datatype declaration, or close the list
Token tok = d_lex.nextToken();
size_t i = 0;
while (tok == Token::LPAREN)
{
std::vector<Expr> params;
if (i >= dnames.size())
{
d_lex.parseError("Too many datatypes defined in this block.");
}
tok = d_lex.nextToken();
bool pushedScope = false;
if (tok == Token::PAR)
{
pushedScope = true;
d_state.pushScope();
std::vector<std::string> symList = parseSymbolList();
if (symList.empty())
{
d_lex.parseError("Expected non-empty parameter list");
}
// parameters are type variables
for (const std::string& sym : symList)
{
Expr t = d_state.mkSymbol(Kind::PARAM, sym, d_state.mkType());
if (!d_state.bind(sym, t))
{
return false;
}
params.push_back(t);
}
}
else
{
d_lex.reinsertToken(tok);
// we will parse the parentheses-enclosed construct list below
d_lex.reinsertToken(Token::LPAREN);
}
if (i >= arities.size())
{
// if the arity is not yet fixed, bind it now
Expr t = d_state.mkTypeConstant(dnames[i], params.size());
// bind
if (!d_state.bind(dnames[i], t))
{
return false;
}
dtlist.push_back(t);
}
else if (arities[i] >= 0 && params.size() != arities[i])
{
// if the arity was fixed by prelude and is not equal to the number of
// parameters
d_lex.parseError("Wrong number of parameters for datatype.");
}
// read constructor definition list, populate into the current datatype
Expr& dt = dtlist[i];
Expr dti = dt;
if (!params.empty())
{
std::vector<Expr> dapp;
dapp.push_back(dt);
dapp.insert(dapp.end(), params.begin(), params.end());
dti = d_state.mkExpr(Kind::APPLY, dapp);
}
std::vector<std::pair<std::string, Expr>> toBind;
std::vector<Expr>& clist = dts[dt.getValue()];
parseConstructorDefinitionList(dti, clist, dtcons, toBind, ambCons, params);
if (pushedScope)
{
d_lex.eatToken(Token::RPAREN);
d_state.popScope();
}
for (std::pair<std::string, Expr>& b : toBind)
{
if (!d_state.bind(b.first, b.second))
{
return false;
}
}
tok = d_lex.nextToken();
i++;
}
if (dtlist.size() != dnames.size())
{
d_lex.unexpectedTokenError(tok, "Wrong number of datatypes provided.");
}
d_lex.reinsertToken(tok);
return true;
}
void ExprParser::parseConstructorDefinitionList(
Expr& dt,
std::vector<Expr>& conslist,
std::map<const ExprValue*, std::vector<Expr>>& dtcons,
std::vector<std::pair<std::string, Expr>>& toBind,
std::unordered_set<const ExprValue*>& ambCons,
const std::vector<Expr>& params)
{
d_lex.eatToken(Token::LPAREN);
Expr boolType = d_state.mkBoolType();
// parse another constructor or close the list
while (d_lex.eatTokenChoice(Token::LPAREN, Token::RPAREN))
{
std::string name = parseSymbol();