-
Notifications
You must be signed in to change notification settings - Fork 243
/
verifier.cc
1744 lines (1656 loc) · 60.9 KB
/
verifier.cc
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
/*
* Copyright 2014 The Kythe Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "verifier.h"
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <memory>
#include "absl/strings/strip.h"
#include "assertions.h"
#include "glog/logging.h"
#include "google/protobuf/text_format.h"
#include "google/protobuf/util/json_util.h"
#include "kythe/cxx/common/kythe_uri.h"
#include "kythe/cxx/common/scope_guard.h"
#include "kythe/cxx/verifier/souffle_interpreter.h"
#include "kythe/proto/common.pb.h"
#include "kythe/proto/storage.pb.h"
namespace kythe {
namespace verifier {
namespace {
/// \brief The return code from a verifier thunk.
using ThunkRet = size_t;
/// \brief The operation failed normally.
static ThunkRet kNoException = {0};
/// \brief There is no more work to do, so unwind.
static ThunkRet kSolved = {1};
/// \brief The program is invalid, so unwind.
static ThunkRet kInvalidProgram = {2};
/// \brief The goal group is known to be impossible to solve.
static ThunkRet kImpossible = {3};
/// \brief ThunkRets >= kFirstCut should unwind to the frame
/// establishing that cut without changing assignments.
static ThunkRet kFirstCut = {4};
typedef const std::function<ThunkRet()>& Thunk;
static std::string* kDefaultDatabase = new std::string("builtin");
static std::string* kStandardIn = new std::string("-");
static bool EncodedIdentEqualTo(AstNode* a, AstNode* b) {
Identifier* ia = a->AsIdentifier();
Identifier* ib = b->AsIdentifier();
return ia->symbol() == ib->symbol();
}
static bool EncodedIdentLessThan(AstNode* a, AstNode* b) {
Identifier* ia = a->AsIdentifier();
Identifier* ib = b->AsIdentifier();
return ia->symbol() < ib->symbol();
}
static bool EncodedVNameEqualTo(App* a, App* b) {
Tuple* ta = a->rhs()->AsTuple();
Tuple* tb = b->rhs()->AsTuple();
for (int i = 0; i < 5; ++i) {
if (!EncodedIdentEqualTo(ta->element(i), tb->element(i))) {
return false;
}
}
return true;
}
static bool EncodedVNameLessThan(App* a, App* b) {
Tuple* ta = a->rhs()->AsTuple();
Tuple* tb = b->rhs()->AsTuple();
for (int i = 0; i < 4; ++i) {
if (EncodedIdentLessThan(ta->element(i), tb->element(i))) {
return true;
}
if (!EncodedIdentEqualTo(ta->element(i), tb->element(i))) {
return false;
}
}
return EncodedIdentLessThan(ta->element(4), tb->element(4));
}
static bool EncodedVNameOrIdentLessThan(AstNode* a, AstNode* b) {
App* aa = a->AsApp(); // nullptr if a is not a vname
App* ab = b->AsApp(); // nullptr if b is not a vname
if (aa && ab) {
return EncodedVNameLessThan(aa, ab);
} else if (!aa && ab) {
// Arbitrarily, vname < ident.
return true;
} else if (aa && !ab) {
return false;
} else {
return EncodedIdentLessThan(a, b);
}
}
static bool EncodedVNameOrIdentEqualTo(AstNode* a, AstNode* b) {
App* aa = a->AsApp(); // nullptr if a is not a vname
App* ab = b->AsApp(); // nullptr if b is not a vname
if (aa && ab) {
return EncodedVNameEqualTo(aa, ab);
} else if (!aa && ab) {
return false;
} else if (aa && !ab) {
return false;
} else {
return EncodedIdentEqualTo(a, b);
}
}
/// \brief Sort entries such that those that set fact values are adjacent.
static bool EncodedFactLessThan(AstNode* a, AstNode* b) {
Tuple* ta = a->AsApp()->rhs()->AsTuple();
Tuple* tb = b->AsApp()->rhs()->AsTuple();
if (EncodedVNameOrIdentLessThan(ta->element(0), tb->element(0))) {
return true;
}
if (!EncodedVNameOrIdentEqualTo(ta->element(0), tb->element(0))) {
return false;
}
if (EncodedIdentLessThan(ta->element(1), tb->element(1))) {
return true;
}
if (!EncodedIdentEqualTo(ta->element(1), tb->element(1))) {
return false;
}
if (EncodedVNameOrIdentLessThan(ta->element(2), tb->element(2))) {
return true;
}
if (!EncodedVNameOrIdentEqualTo(ta->element(2), tb->element(2))) {
return false;
}
if (EncodedIdentLessThan(ta->element(3), tb->element(3))) {
return true;
}
if (!EncodedIdentEqualTo(ta->element(3), tb->element(3))) {
return false;
}
if (EncodedIdentLessThan(ta->element(4), tb->element(4))) {
return true;
}
return false;
}
static AstNode* DerefEVar(AstNode* node) {
while (node) {
if (auto* evar = node->AsEVar()) {
node = evar->current();
} else {
break;
}
}
return node;
}
static Identifier* SafeAsIdentifier(AstNode* node) {
return node == nullptr ? nullptr : node->AsIdentifier();
}
struct AtomFactKey {
Identifier* edge_kind;
Identifier* fact_name;
Identifier* fact_value;
Identifier* source_vname[5] = {nullptr, nullptr, nullptr, nullptr, nullptr};
Identifier* target_vname[5] = {nullptr, nullptr, nullptr, nullptr, nullptr};
// fact_tuple is expected to be a full tuple from a Fact head
AtomFactKey(AstNode* vname_head, Tuple* fact_tuple)
: edge_kind(SafeAsIdentifier(DerefEVar(fact_tuple->element(1)))),
fact_name(SafeAsIdentifier(DerefEVar(fact_tuple->element(3)))),
fact_value(SafeAsIdentifier(DerefEVar(fact_tuple->element(4)))) {
InitVNameFields(vname_head, fact_tuple->element(0), &source_vname[0]);
InitVNameFields(vname_head, fact_tuple->element(2), &target_vname[0]);
}
void InitVNameFields(AstNode* vname_head, AstNode* maybe_vname,
Identifier** out) {
maybe_vname = DerefEVar(maybe_vname);
if (maybe_vname == nullptr) {
return;
}
if (auto* app = maybe_vname->AsApp()) {
if (DerefEVar(app->lhs()) != vname_head) {
return;
}
AstNode* maybe_tuple = DerefEVar(app->rhs());
if (maybe_tuple == nullptr) {
return;
}
if (auto* tuple = maybe_tuple->AsTuple()) {
if (tuple->size() != 5) {
return;
}
for (size_t i = 0; i < 5; ++i) {
out[i] = SafeAsIdentifier(DerefEVar(tuple->element(i)));
}
}
}
}
};
enum class Order { LT, EQ, GT };
// How we order incomplete keys depends on whether we're looking for
// an upper or lower bound. See below for details. The node passed in
// must be an application of Fact to a full fact tuple.
static Order CompareFactWithKey(Order incomplete, AstNode* a, AtomFactKey* k) {
Tuple* ta = a->AsApp()->rhs()->AsTuple();
if (k->edge_kind == nullptr) {
return incomplete;
} else if (EncodedIdentLessThan(ta->element(1), k->edge_kind)) {
return Order::LT;
} else if (!EncodedIdentEqualTo(ta->element(1), k->edge_kind)) {
return Order::GT;
}
if (k->fact_name == nullptr) {
return incomplete;
} else if (EncodedIdentLessThan(ta->element(3), k->fact_name)) {
return Order::LT;
} else if (!EncodedIdentEqualTo(ta->element(3), k->fact_name)) {
return Order::GT;
}
if (k->fact_value == nullptr) {
return incomplete;
} else if (EncodedIdentLessThan(ta->element(4), k->fact_value)) {
return Order::LT;
} else if (!EncodedIdentEqualTo(ta->element(4), k->fact_value)) {
return Order::GT;
}
auto vname_compare = [incomplete](Tuple* va, Identifier* tuple[5]) {
for (size_t i = 0; i < 5; ++i) {
if (tuple[i] == nullptr) {
return incomplete;
}
if (EncodedIdentLessThan(va->element(i), tuple[i])) {
return Order::LT;
}
if (!EncodedIdentEqualTo(va->element(i), tuple[i])) {
return Order::GT;
}
}
return Order::EQ;
};
if (Tuple* vs = ta->element(0)->AsApp()->rhs()->AsTuple()) {
auto ord = vname_compare(vs, k->source_vname);
if (ord != Order::EQ) {
return ord;
}
}
if (auto* app = ta->element(2)->AsApp()) {
if (Tuple* vt = app->rhs()->AsTuple()) {
auto ord = vname_compare(vt, k->target_vname);
if (ord != Order::EQ) {
return ord;
}
}
}
return Order::EQ;
}
// We want to be able to find the following bounds:
// (0,0,2,3) (0,1,2,3) (0,1,2,4) (1,1,2,4)
// ^--- (0,1,_,_) ---^
static bool FastLookupKeyLessThanFact(AtomFactKey* k, AstNode* a) {
// This is used to find upper bounds, so keys with incomplete suffixes should
// be ordered after all facts that share their complete prefixes.
return CompareFactWithKey(Order::LT, a, k) == Order::GT;
}
static bool FastLookupFactLessThanKey(AstNode* a, AtomFactKey* k) {
// This is used to find lower bounds, so keys with incomplete suffixes should
// be ordered after facts with lower prefixes but before facts with complete
// suffixes.
return CompareFactWithKey(Order::GT, a, k) == Order::LT;
}
// Sort entries in lexicographic order, collating as:
// `(edge_kind, fact_name, fact_value, source_node, target_node)`.
// In practice most unification was happening between tuples
// with the first three fields present; then source_node
// missing some of the time; then target_node missing most of
// the time.
static bool FastLookupFactLessThan(AstNode* a, AstNode* b) {
Tuple* ta = a->AsApp()->rhs()->AsTuple();
Tuple* tb = b->AsApp()->rhs()->AsTuple();
if (EncodedIdentLessThan(ta->element(1), tb->element(1))) {
return true;
}
if (!EncodedIdentEqualTo(ta->element(1), tb->element(1))) {
return false;
}
if (EncodedIdentLessThan(ta->element(3), tb->element(3))) {
return true;
}
if (!EncodedIdentEqualTo(ta->element(3), tb->element(3))) {
return false;
}
if (EncodedIdentLessThan(ta->element(4), tb->element(4))) {
return true;
}
if (!EncodedIdentEqualTo(ta->element(4), tb->element(4))) {
return false;
}
if (EncodedVNameOrIdentLessThan(ta->element(0), tb->element(0))) {
return true;
}
if (!EncodedVNameOrIdentEqualTo(ta->element(0), tb->element(0))) {
return false;
}
if (EncodedVNameOrIdentLessThan(ta->element(2), tb->element(2))) {
return true;
}
return false;
}
// The Solver acts in a closed world: any universal quantification can be
// exhaustively tested against database facts.
// Based on _A Semi-Functional Implementation of a Higher-Order Logic
// Programming Language_ by Conal Elliott and Frank Pfenning (draft of
// February 1990).
// It is not our intention to build a particularly performant or complete
// inference engine. If the solver starts to get too hairy we might want to
// look at deferring to a pre-existing system.
class Solver {
public:
Solver(Verifier* context, Database& database, AnchorMap& anchors,
std::function<bool(Verifier*, const Inspection&)>& inspect)
: context_(*context),
database_(database),
anchors_(anchors),
inspect_(inspect) {}
ThunkRet UnifyTuple(Tuple* st, Tuple* tt, size_t ofs, size_t max,
ThunkRet cut, Thunk f) {
if (ofs == max) return f();
return Unify(st->element(ofs), tt->element(ofs), cut,
[this, st, tt, ofs, max, cut, &f]() {
return UnifyTuple(st, tt, ofs + 1, max, cut, f);
});
}
ThunkRet Unify(AstNode* s, AstNode* t, ThunkRet cut, Thunk f) {
if (EVar* e = s->AsEVar()) {
return UnifyEVar(e, t, cut, f);
} else if (EVar* e = t->AsEVar()) {
return UnifyEVar(e, s, cut, f);
} else if (Identifier* si = s->AsIdentifier()) {
if (Identifier* ti = t->AsIdentifier()) {
if (si->symbol() == ti->symbol()) {
return f();
}
}
} else if (App* sa = s->AsApp()) {
if (App* ta = t->AsApp()) {
return Unify(sa->lhs(), ta->lhs(), cut, [this, sa, ta, cut, &f]() {
return Unify(sa->rhs(), ta->rhs(), cut, f);
});
}
} else if (Tuple* st = s->AsTuple()) {
if (Tuple* tt = t->AsTuple()) {
if (st->size() != tt->size()) {
return kNoException;
}
return UnifyTuple(st, tt, 0, st->size(), cut, f);
}
} else if (Range* sr = s->AsRange()) {
if (Range* tr = t->AsRange()) {
if (*sr == *tr) {
return f();
}
}
}
return kNoException;
}
bool Occurs(EVar* e, AstNode* t) {
if (App* a = t->AsApp()) {
return Occurs(e, a->lhs()) || Occurs(e, a->rhs());
} else if (EVar* ev = t->AsEVar()) {
return ev->current() ? Occurs(e, ev->current()) : e == ev;
} else if (Tuple* tu = t->AsTuple()) {
for (size_t i = 0, c = tu->size(); i != c; ++i) {
if (Occurs(e, tu->element(i))) {
return true;
}
}
return false;
} else if (Range* r = t->AsRange()) {
return false;
} else {
CHECK(t->AsIdentifier() && "Inexhaustive match.");
return false;
}
return true;
}
ThunkRet UnifyEVar(EVar* e, AstNode* t, ThunkRet cut, Thunk f) {
if (AstNode* ec = e->current()) {
return Unify(ec, t, cut, f);
}
if (t->AsEVar() == e) {
return f();
}
if (Occurs(e, t)) {
FileHandlePrettyPrinter printer(stderr);
printer.Print("Detected a cycle involving ");
e->Dump(*context_.symbol_table(), &printer);
printer.Print(" while unifying it with ");
t->Dump(*context_.symbol_table(), &printer);
printer.Print(".\n");
return kInvalidProgram;
}
e->set_current(t);
ThunkRet f_ret = f();
if (f_ret != cut) {
e->set_current(nullptr);
}
return f_ret;
}
ThunkRet MatchAtomVersusDatabase(AstNode* atom, ThunkRet cut, Thunk f) {
if (auto* app = atom->AsApp()) {
if (app->lhs() == context_.fact_id()) {
if (auto* tuple = app->rhs()->AsTuple()) {
if (tuple->size() == 5) {
AtomFactKey key(context_.vname_id(), tuple);
// Make use of the fast lookup sort order.
auto begin = std::lower_bound(database_.begin(), database_.end(),
&key, FastLookupFactLessThanKey);
auto end = std::upper_bound(database_.begin(), database_.end(),
&key, FastLookupKeyLessThanFact);
for (auto i = begin; i != end; ++i) {
ThunkRet exc = Unify(atom, *i, cut, f);
if (exc != kNoException) {
return exc;
}
}
return kNoException;
}
}
}
}
// Not enough information to filter by.
for (size_t fact = 0; fact < database_.size(); ++fact) {
ThunkRet exc = Unify(atom, database_[fact], cut, f);
if (exc != kNoException) {
return exc;
}
}
return kNoException;
}
/// \brief If `atom` has the syntactic form =(a, b), returns the tuple (a, b).
/// Otherwise returns `null`.
Tuple* MatchEqualsArgs(AstNode* atom) {
if (App* a = atom->AsApp()) {
if (Identifier* id = a->lhs()->AsIdentifier()) {
if (id->symbol() == context_.eq_id()->symbol()) {
if (Tuple* tu = a->rhs()->AsTuple()) {
if (tu->size() == 2) {
return tu;
}
}
}
}
}
return nullptr;
}
ThunkRet MatchAtom(AstNode* atom, AstNode* program, ThunkRet cut, Thunk f) {
// We only have the database and eq-constraints right now.
assert(program == nullptr);
if (auto* tu = MatchEqualsArgs(atom)) {
if (Range* r = tu->element(0)->AsRange()) {
auto anchors =
anchors_.equal_range(std::make_pair(r->begin(), r->end()));
if (anchors.first == anchors.second) {
// There's no anchor with this range in the database.
// This goal can therefore never succeed.
return kImpossible;
}
for (auto anchor = anchors.first; anchor != anchors.second; ++anchor) {
ThunkRet unify_ret = Unify(anchor->second, tu->element(1), cut, f);
if (unify_ret != kNoException) {
return unify_ret;
}
}
return kNoException;
}
// =(a, b) succeeds if unify(a, b) succeeds.
return Unify(tu->element(0), tu->element(1), cut, f);
}
return MatchAtomVersusDatabase(atom, cut, f);
}
ThunkRet SolveGoal(AstNode* goal, ThunkRet cut, Thunk f) {
// We only have atomic goals right now.
if (App* a = goal->AsApp()) {
return MatchAtom(goal, nullptr, cut, f);
} else {
// TODO(zarko): Replace with a configurable PrettyPrinter.
LOG(ERROR) << "Invalid AstNode in goal-expression.";
return kInvalidProgram;
}
}
ThunkRet SolveGoalArray(GoalGroup* group, size_t cur, ThunkRet cut, Thunk f) {
if (cur > highest_goal_reached_) {
highest_goal_reached_ = cur;
}
if (cur == group->goals.size()) {
return f();
}
return SolveGoal(group->goals[cur], cut, [this, group, cur, cut, &f]() {
return SolveGoalArray(group, cur + 1, cut, f);
});
}
bool PerformInspection() {
for (const auto& inspection : context_.parser()->inspections()) {
if (!inspect_(&context_, inspection)) {
return false;
}
}
return true;
}
ThunkRet SolveGoalGroups(AssertionParser* context, Thunk f) {
for (size_t cur = 0, cut = kFirstCut; cur < context->groups().size();
++cur, ++cut) {
auto* group = &context->groups()[cur];
if (cur > highest_group_reached_) {
highest_goal_reached_ = 0;
highest_group_reached_ = cur;
}
ThunkRet result = SolveGoalArray(group, 0, cut, [cut]() { return cut; });
// Lots of unwinding later...
if (result == cut) {
// That last goal group succeeded.
if (group->accept_if != GoalGroup::kNoneMayFail) {
return PerformInspection() ? kNoException : kInvalidProgram;
}
} else if (result == kNoException || result == kImpossible) {
// That last goal group failed.
if (group->accept_if != GoalGroup::kSomeMustFail) {
return PerformInspection() ? kNoException : kInvalidProgram;
}
} else {
return result;
}
}
return PerformInspection() ? f() : kInvalidProgram;
}
bool Solve() {
ThunkRet exn = SolveGoalGroups(context_.parser(), []() { return kSolved; });
return exn == kSolved;
}
size_t highest_group_reached() const { return highest_group_reached_; }
size_t highest_goal_reached() const { return highest_goal_reached_; }
private:
Verifier& context_;
Database& database_;
AnchorMap& anchors_;
std::function<bool(Verifier*, const Inspection&)>& inspect_;
size_t highest_group_reached_ = 0;
size_t highest_goal_reached_ = 0;
};
enum class NodeKind { kFile, kAnchor, kOther };
struct NodeFacts {
NodeKind kind = NodeKind::kOther;
absl::Span<AstNode* const> facts;
};
NodeFacts ReadNodeFacts(absl::Span<AstNode* const> entries, Verifier& ctx) {
NodeFacts result = {
.kind = NodeKind::kOther,
.facts = entries,
};
if (entries.empty()) {
return result;
}
Tuple* head = entries.front()->AsApp()->rhs()->AsTuple();
for (size_t i = 0; i < entries.size(); ++i) {
Tuple* current = entries[i]->AsApp()->rhs()->AsTuple();
if (!EncodedVNameOrIdentEqualTo(current->element(0), head->element(0)) ||
current->element(1) != ctx.empty_string_id()) {
// Moved past the fact block or moved to a different source node;
// we're done.
result.facts = entries.subspan(0, i);
break;
}
if (EncodedIdentEqualTo(current->element(3), ctx.kind_id())) {
if (EncodedIdentEqualTo(current->element(4), ctx.anchor_id())) {
result.kind = NodeKind::kAnchor;
} else if (EncodedIdentEqualTo(current->element(4), ctx.file_id())) {
result.kind = NodeKind::kFile;
}
}
}
return result;
}
} // namespace
Verifier::Verifier(bool trace_lex, bool trace_parse)
: parser_(this, trace_lex, trace_parse),
builtin_location_name_("builtins") {
builtin_location_.initialize(&builtin_location_name_);
builtin_location_.begin.column = 1;
builtin_location_.end.column = 1;
empty_string_id_ = IdentifierFor(builtin_location_, "");
fact_id_ = IdentifierFor(builtin_location_, "fact");
vname_id_ = IdentifierFor(builtin_location_, "vname");
kind_id_ = IdentifierFor(builtin_location_, "/kythe/node/kind");
anchor_id_ = IdentifierFor(builtin_location_, "anchor");
start_id_ = IdentifierFor(builtin_location_, "/kythe/loc/start");
end_id_ = IdentifierFor(builtin_location_, "/kythe/loc/end");
root_id_ = IdentifierFor(builtin_location_, "/");
eq_id_ = IdentifierFor(builtin_location_, "=");
ordinal_id_ = IdentifierFor(builtin_location_, "/kythe/ordinal");
file_id_ = IdentifierFor(builtin_location_, "file");
text_id_ = IdentifierFor(builtin_location_, "/kythe/text");
code_id_ = IdentifierFor(builtin_location_, "/kythe/code");
code_json_id_ = IdentifierFor(builtin_location_, "/kythe/code/json");
marked_source_child_id_ =
IdentifierFor(builtin_location_, "/kythe/edge/child");
marked_source_box_id_ = IdentifierFor(builtin_location_, "BOX");
marked_source_type_id_ = IdentifierFor(builtin_location_, "TYPE");
marked_source_parameter_id_ = IdentifierFor(builtin_location_, "PARAMETER");
marked_source_identifier_id_ = IdentifierFor(builtin_location_, "IDENTIFIER");
marked_source_context_id_ = IdentifierFor(builtin_location_, "CONTEXT");
marked_source_initializer_id_ =
IdentifierFor(builtin_location_, "INITIALIZER");
marked_source_parameter_lookup_by_param_id_ =
IdentifierFor(builtin_location_, "PARAMETER_LOOKUP_BY_PARAM");
marked_source_lookup_by_param_id_ =
IdentifierFor(builtin_location_, "LOOKUP_BY_PARAM");
marked_source_parameter_lookup_by_tparam_id_ =
IdentifierFor(builtin_location_, "PARAMETER_LOOKUP_BY_TPARAM");
marked_source_lookup_by_tparam_id_ =
IdentifierFor(builtin_location_, "LOOKUP_BY_TPARAM");
marked_source_parameter_lookup_by_param_with_defaults_id_ = IdentifierFor(
builtin_location_, "PARAMETER_LOOKUP_BY_PARAM_WITH_DEFAULTS");
marked_source_lookup_by_typed_id_ =
IdentifierFor(builtin_location_, "LOOKUP_BY_TYPED");
marked_source_kind_id_ = IdentifierFor(builtin_location_, "/kythe/kind");
marked_source_pre_text_id_ =
IdentifierFor(builtin_location_, "/kythe/pre_text");
marked_source_post_child_text_id_ =
IdentifierFor(builtin_location_, "/kythe/post_child_text");
marked_source_post_text_id_ =
IdentifierFor(builtin_location_, "/kythe/post_text");
marked_source_lookup_index_id_ =
IdentifierFor(builtin_location_, "/kythe/lookup_index");
marked_source_default_children_count_id_ =
IdentifierFor(builtin_location_, "/kythe/default_children_count");
marked_source_add_final_list_token_id_ =
IdentifierFor(builtin_location_, "/kythe/add_final_list_token");
marked_source_link_id_ = IdentifierFor(builtin_location_, "/kythe/edge/link");
marked_source_true_id_ = IdentifierFor(builtin_location_, "true");
marked_source_code_edge_id_ =
IdentifierFor(builtin_location_, "/kythe/edge/code");
marked_source_false_id_ = IdentifierFor(builtin_location_, "false");
known_file_sym_ = symbol_table_.unique();
known_not_file_sym_ = symbol_table_.unique();
SetGoalCommentPrefix("//-");
}
void Verifier::SetGoalCommentPrefix(const std::string& it) {
std::string error;
auto escaped = RE2::QuoteMeta(it);
CHECK(SetGoalCommentRegex("\\s*" + escaped + "(.*)", &error)) << error;
}
bool Verifier::SetGoalCommentRegex(const std::string& regex,
std::string* error) {
auto re2 = std::make_unique<RE2>(regex);
if (re2->error_code() != RE2::NoError) {
if (error) {
*error = re2->error();
return false;
}
}
if (re2->NumberOfCapturingGroups() != 1) {
if (error) {
*error = "Wrong number of capture groups in goal comment regex ";
// This is useful to show, since the shell might unexpectedly shred
// regexes.
error->append(regex);
error->append("(want 1).");
return false;
}
}
goal_comment_regex_ = std::move(re2);
return true;
}
bool Verifier::LoadInlineProtoFile(const std::string& file_data) {
kythe::proto::Entries entries;
bool ok = google::protobuf::TextFormat::ParseFromString(file_data, &entries);
if (!ok) {
// TODO(zarko): Replace with a configurable PrettyPrinter.
LOG(ERROR) << "Unable to parse text protobuf.";
return false;
}
for (int i = 0; i < entries.entries_size(); ++i) {
if (!AssertSingleFact(kDefaultDatabase, i, entries.entries(i))) {
return false;
}
}
Symbol empty = symbol_table_.intern("");
return parser_.ParseInlineRuleString(file_data, *kStandardIn, empty, empty,
empty, "\\s*\\#\\-(.*)");
}
bool Verifier::LoadInlineRuleFile(const std::string& filename) {
int fd = ::open(filename.c_str(), 0);
if (fd < 0) {
LOG(ERROR) << "Can't open " << filename;
return false;
}
auto guard = MakeScopeGuard([&] { ::close(fd); });
struct stat fd_stat;
if (::fstat(fd, &fd_stat) < 0) {
LOG(ERROR) << "Can't stat " << filename;
return false;
}
std::string content;
content.resize(fd_stat.st_size);
if (::read(fd, const_cast<char*>(content.data()), fd_stat.st_size) !=
fd_stat.st_size) {
LOG(ERROR) << "Can't read " << filename;
return false;
}
Symbol content_sym = symbol_table_.intern(content);
if (file_vnames_) {
auto vname = content_to_vname_.find(content_sym);
if (vname == content_to_vname_.end()) {
LOG(ERROR) << "Could not find a file node for " << filename;
return false;
}
return LoadInMemoryRuleFile(filename, vname->second, content_sym);
} else {
kythe::proto::VName empty;
auto* vname = ConvertVName(yy::location{}, empty);
return LoadInMemoryRuleFile(filename, vname, content_sym);
}
}
bool Verifier::LoadInMemoryRuleFile(const std::string& filename, AstNode* vname,
Symbol text) {
Tuple* checked_tuple = nullptr;
if (auto* app = vname->AsApp()) {
if (auto* tuple = app->rhs()->AsTuple()) {
if (tuple->size() == 5 && tuple->element(1)->AsIdentifier() &&
tuple->element(2)->AsIdentifier() &&
tuple->element(3)->AsIdentifier()) {
checked_tuple = tuple;
}
}
}
if (checked_tuple == nullptr) {
return false;
}
StringPrettyPrinter printer;
vname->Dump(symbol_table_, &printer);
fake_files_[printer.str()] = text;
return parser_.ParseInlineRuleString(
symbol_table_.text(text), filename.empty() ? printer.str() : filename,
checked_tuple->element(3)->AsIdentifier()->symbol(),
checked_tuple->element(2)->AsIdentifier()->symbol(),
checked_tuple->element(1)->AsIdentifier()->symbol(),
*goal_comment_regex_);
}
void Verifier::IgnoreDuplicateFacts() { ignore_dups_ = true; }
void Verifier::IgnoreCodeConflicts() { ignore_code_conflicts_ = true; }
void Verifier::SaveEVarAssignments() {
saving_assignments_ = true;
parser_.InspectAllEVars();
}
void Verifier::ShowGoals() {
FileHandlePrettyPrinter printer(stdout);
for (auto& group : parser_.groups()) {
if (group.accept_if == GoalGroup::kNoneMayFail) {
printer.Print("group:\n");
} else {
printer.Print("negated group:\n");
}
for (auto* goal : group.goals) {
printer.Print(" goal: ");
goal->Dump(symbol_table_, &printer);
printer.Print("\n");
}
}
}
static bool PrintInMemoryFileSection(const std::string& file_text,
size_t start_line, size_t start_ix,
size_t end_line, size_t end_ix,
PrettyPrinter* printer) {
size_t current_line = 0;
size_t pos = 0;
auto walk_lines = [&](size_t until_line) {
if (until_line == current_line) {
return pos;
}
do {
auto endline = file_text.find('\n', pos);
if (endline == std::string::npos) {
return std::string::npos;
}
pos = endline + 1;
} while (++current_line < start_line);
return pos;
};
auto begin = walk_lines(start_line);
auto end = begin == std::string::npos ? begin : walk_lines(end_line);
auto begin_ofs = begin + start_ix;
auto end_ofs = end + end_ix;
if (begin == std::string::npos || end == std::string::npos ||
begin_ofs > file_text.size() || end_ofs > file_text.size()) {
printer->Print("(error line out of bounds)");
return false;
}
printer->Print(file_text.substr(begin_ofs, end_ofs - begin_ofs));
return true;
}
static bool PrintFileSection(FILE* file, size_t start_line, size_t start_ix,
size_t end_line, size_t end_ix,
PrettyPrinter* printer) {
if (!file) {
printer->Print("(null file)\n");
return false;
}
char* lineptr = nullptr;
size_t buf_length = 0;
ssize_t line_length = 0;
size_t line_number = 0;
while ((line_length = getline(&lineptr, &buf_length, file)) != -1) {
if (line_number >= start_line && line_number <= end_line) {
std::string text(lineptr);
size_t line_begin = 0, line_end = text.size();
if (line_number == start_line) {
line_begin = start_ix;
}
if (line_number == end_line) {
line_end = end_ix;
}
if (line_end - line_begin > text.size()) {
printer->Print("(error line too big for actual line)\n");
} else {
text = text.substr(line_begin, line_end - line_begin);
printer->Print(text);
}
}
if (line_number == end_line) {
free(lineptr);
return true;
}
++line_number;
}
printer->Print("(error line out of bounds)\n");
free(lineptr);
return false;
}
void Verifier::DumpErrorGoal(size_t group, size_t index) {
FileHandlePrettyPrinter printer(stderr);
if (group >= parser_.groups().size()) {
printer.Print("(invalid group index ");
printer.Print(std::to_string(group));
printer.Print(")\n");
}
if (index >= parser_.groups()[group].goals.size()) {
if (index > parser_.groups()[group].goals.size() ||
parser_.groups()[group].goals.empty()) {
printer.Print("(invalid index ");
printer.Print(std::to_string(group));
printer.Print(":");
printer.Print(std::to_string(index));
printer.Print(")\n");
return;
}
printer.Print("(past the end of a ");
if (parser_.groups()[group].accept_if == GoalGroup::kSomeMustFail) {
printer.Print("negated ");
}
printer.Print("group, whose last goal was)\n ");
--index;
}
auto* goal = parser_.groups()[group].goals[index];
yy::location goal_location = goal->location();
yy::position goal_begin = goal_location.begin;
yy::position goal_end = goal_location.end;
if (goal_end.filename) {
printer.Print(*goal_end.filename);
} else {
printer.Print("-");
}
printer.Print(":");
if (goal_begin.filename) {
printer.Print(std::to_string(goal_begin.line) + ":" +
std::to_string(goal_begin.column));
}
printer.Print("-");
if (goal_end.filename) {
printer.Print(std::to_string(goal_end.line) + ":" +
std::to_string(goal_end.column));
}
bool printed_goal = false;
printer.Print(" ");
if (goal_end.filename) {
auto has_symbol = fake_files_.find(*goal_end.filename);
if (has_symbol != fake_files_.end()) {
printed_goal = PrintInMemoryFileSection(
symbol_table_.text(has_symbol->second), goal_begin.line - 1,
goal_begin.column - 1, goal_end.line - 1, goal_end.column - 1,
&printer);
} else if (*goal_end.filename != *kStandardIn &&
*goal_begin.filename == *goal_end.filename) {
FILE* f = fopen(goal_end.filename->c_str(), "r");
if (f != nullptr) {
printed_goal =
PrintFileSection(f, goal_begin.line - 1, goal_begin.column - 1,
goal_end.line - 1, goal_end.column - 1, &printer);
fclose(f);
}
}
}
printer.Print("\n Goal: ");
goal->Dump(symbol_table_, &printer);
printer.Print("\n");
}
bool Verifier::VerifyAllGoals(
std::function<bool(Verifier*, const Inspection&)> inspect) {
if (use_fast_solver_) {
auto result = RunSouffle(symbol_table_, parser_.groups(), facts_, anchors_,
parser_.inspections(), [&](const Inspection& i) {
return inspect(this, i);
});
highest_goal_reached_ = result.highest_goal_reached;
highest_group_reached_ = result.highest_group_reached;
return result.success;
} else {
if (!PrepareDatabase()) {
return false;
}
Solver solver(this, facts_, anchors_, inspect);
bool result = solver.Solve();
highest_goal_reached_ = solver.highest_goal_reached();
highest_group_reached_ = solver.highest_group_reached();
return result;
}
}
bool Verifier::VerifyAllGoals() {
return VerifyAllGoals([this](Verifier* context,
const Inspection& inspection) {
if (inspection.kind == Inspection::Kind::EXPLICIT) {
FileHandlePrettyPrinter printer(saving_assignments_ ? stderr : stdout);
printer.Print(inspection.label);
printer.Print(": ");
inspection.evar->Dump(symbol_table_, &printer);
printer.Print("\n");
}
if (inspection.evar->current()) {
saved_assignments_[inspection.label] = inspection.evar->current();
}
return true;
});
}
Identifier* Verifier::IdentifierFor(const yy::location& location,