Repository navigation
Expand file tree
/
Copy pathawklog.awk
More file actions
2085 lines (1947 loc) · 64.9 KB
/
Copy pathawklog.awk
File metadata and controls
2085 lines (1947 loc) · 64.9 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
# awklog -- a tiny stratified Datalog interpreter in portable AWK.
#
# The main rule only collects source lines; everything else runs in END, as a
# pipeline: parse, load facts, check safety, stratify, evaluate, run queries.
# README.md describes the language and the design.
#
# POSIX awk only. No gensub, asort/asorti, PROCINFO, arrays of arrays,
# switch, typeof, indirect calls, length(array), delete of a whole array, or
# regex shorthands such as \s. Two-dimensional access is always a[x, y] with
# an explicit SUBSEP.
#
# Settings arrive in the environment as AWKLOG_* (set by the awklog wrapper);
# an explicit -v awklog_* assignment wins, so direct
#
# awk -v awklog_query='edge(X, Y)?' -f awklog.awk graph.dl
#
# stays ergonomic.
BEGIN {
init()
}
FNR == 1 {
stat_files++
}
{
source_add_line(FILENAME, FNR, $0)
}
END {
if (dying)
exit exit_code
parse_all()
load_facts()
check_program()
stratify()
if (!opt_check) {
evaluate()
if (run_constraints() > 0)
exit_code = 1
else
run_queries()
if (opt_dump)
dump_relations()
}
if (opt_verbose)
print_stats()
exit exit_code
}
# ---------------------------------------------------------------- options ---
function init() {
# Belt and braces only: POSIX converts an integral value with %d and
# consults CONVFMT just for the rest, and the language has no
# non-integral values to reach it. Numbers that go into tuple keys are
# spelled explicitly by number_text() in any case.
CONVFMT = "%.17g"
OFMT = "%.17g"
SUBSEP = sprintf("%c", 28)
# The lexer classifies bytes with index() into these sets rather than
# scanning tokens with match(), which takes no start offset and so would
# copy the rest of the line for every token -- quadratic on a long line.
UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
LOWER = "abcdefghijklmnopqrstuvwxyz"
DIGITS = "0123456789"
WORDCH = UPPER LOWER DIGITS "_"
STDERR = opt_str(awklog_stderr, "AWKLOG_STDERR", "/dev/stderr")
opt_query = opt_str(awklog_query, "AWKLOG_QUERY", "")
opt_format = opt_str(awklog_format, "AWKLOG_FORMAT", "text")
opt_mode = opt_str(awklog_mode, "AWKLOG_MODE", "semi")
opt_check = opt_flag(awklog_check, "check")
opt_quiet = opt_flag(awklog_quiet, "quiet")
opt_sort = opt_flag(awklog_sort, "sort")
opt_werror = opt_flag(awklog_werror, "werror")
opt_verbose = opt_num(awklog_verbose, "AWKLOG_VERBOSE", 0)
# Undocumented, and deliberately absent from the wrapper: the test
# harness sets it to have every relation printed after evaluation, so
# that the two engines are compared over the whole model and not only
# over what the queries happen to ask.
# It also suppresses the queries' own rows -- see query_print() -- so
# that what reaches stdout is the model and nothing else.
opt_dump = opt_flag(awklog_dump, "dump")
if (opt_format != "text" && opt_format != "csv" && opt_format != "tsv")
usage_error("unknown output format: " opt_format)
if (opt_mode != "semi" && opt_mode != "naive")
usage_error("unknown evaluation mode: " opt_mode)
# The column separator of each format; how a column itself is spelled
# is format_field()'s business.
if (opt_format == "csv")
FIELDSEP = ","
else if (opt_format == "tsv")
FIELDSEP = "\t"
else
FIELDSEP = " "
# The relation dump sorts its rows through sort(1).
SORTCMD = "sort"
src_n = 0
stat_lines = 0
pred_n = 0
tuple_n = 0
rule_n = 0
query_n = 0
constraint_n = 0
stat_files = 0
stat_input_facts = 0
stat_dup_facts = 0
stat_rules = 0
stat_undefined = 0
stat_unused = 0
stat_derived_facts = 0
stat_rule_runs = 0
stat_tuple_scans = 0
stat_iterations = 0
max_stratum = 0
join_stop = 0
delta_active = 0
delta_lit = 0
delta_pending = 0
exit_code = 0
dying = 0
}
# An unset awk variable is "", so a -v assignment takes precedence over the
# environment only when it actually carries a value.
function opt_str(v, name, dflt) {
if (v != "")
return v
if (name in ENVIRON && ENVIRON[name] != "")
return ENVIRON[name]
return dflt
}
function opt_num(v, name, dflt) {
return opt_str(v, name, dflt) + 0
}
# An on/off switch, awklog_NAME or AWKLOG_NAME, is 0 or 1 and nothing else.
# Read as a number, any other value would be 0, and a mistyped "yes" would
# quietly turn a switch off -- -W above all, whose job is to make a run fail.
# The result is a number, so "if (opt_x)" means what it says: the string "0"
# would test true.
function opt_flag(v, name, s) {
s = opt_str(v, "AWKLOG_" toupper(name), "0")
if (s != "0" && s != "1")
usage_error("awklog_" name " / AWKLOG_" toupper(name) \
" must be 0 or 1, not '" s "'")
return s == "1"
}
# ------------------------------------------------------------ diagnostics ---
# Messages carry their own classification ("syntax error: ...", "error:
# unsafe rule: ...") so that a located diagnostic reads
#
# project.dl:14:3: syntax error: expected ')', found 'c'
#
# All stages run in END, so exit here terminates immediately; the dying flag
# covers the one caller in BEGIN, where exit would otherwise fall into END.
function die(where, msg) {
if (where != "")
print where ": " msg > STDERR
else
print "awklog: " msg > STDERR
close(STDERR)
exit_code = 1
dying = 1
exit 1
}
function usage_error(msg) {
print "awklog: " msg > STDERR
close(STDERR)
exit_code = 2
dying = 1
exit 2
}
# Every warning comes through here, so -W is one test: the warning becomes
# an error, and like any error it ends the run at once. The message keeps
# its text and changes only its classification.
function warn(where, msg) {
if (opt_werror)
die(where, "error: " msg)
if (where != "")
print where ": warning: " msg > STDERR
else
print "awklog: warning: " msg > STDERR
}
function note(msg) {
print "awklog: " msg > STDERR
}
# How a token is named in a diagnostic.
# Punctuation carries no text and is named by its kind, which is its spelling.
function token_desc(kind, text) {
if (kind == "EOF")
return "end of input"
if (kind == "STR")
return "a string literal"
return "'" (text != "" ? text : kind) "'"
}
# Whole-array delete is not POSIX, so every array is emptied through here.
function array_clear(a, k) {
for (k in a)
delete a[k]
}
# --------------------------------------------------------------- sources ---
# Input lines are kept with their origin so that the lexer's (line, column)
# cursor yields file:line:col diagnostics with no offset mapping table.
function source_add_line(file, fnr, text) {
# Standard input reaches awk under three spellings: BWK awk leaves
# FILENAME empty, mawk and gawk set it to "-", and an explicit
# /dev/stdin operand names the same stream a third way. All three get
# one label, so a diagnostic reads the same whichever awk is running.
if (file == "" || file == "-" || file == "/dev/stdin")
file = "<stdin>"
src_n++
src_file[src_n] = file
src_fnr[src_n] = fnr
src_text[src_n] = text
}
function source_where(i, col) {
if (i < 1 || i > src_n)
return "awklog"
if (col > 0)
return src_file[i] ":" src_fnr[i] ":" col
return src_file[i] ":" src_fnr[i]
}
# Query text from -q becomes ordinary source lines, so it lexes with the same
# cursor and reports the same file:line:col diagnostics. Several -q queries
# arrive joined by newlines and so become several lines of "<query>".
function source_add_query(text, parts, i, n, start) {
start = src_n + 1
n = split(text, parts, "\n")
for (i = 1; i <= n; i++)
source_add_line("<query>", i, parts[i])
return start
}
# ----------------------------------------------------------------- lexer ---
#
# The cursor is (lex_i, lex_col): an index into src_text[] and a 1-based
# column. Keeping the lines separate instead of concatenating them into one
# buffer gives every token a file:line:col for free; statements still span
# lines because the scanner walks through line ends transparently.
#
# Token kinds are IDENT, VAR, ANON, INT, STR, not, EOF and the punctuation
# spelled as itself ("(", ")", ",", ".", "?", ":-", "=", "!=", "<", "<=", ">",
# ">="), so a diagnostic can name a token without a translation table.
function lex_start(i) {
lex_i = i
lex_col = 1
lex_end_ln = 0
lex_end_col = 0
have_peek = 0
tok_kind = ""
tok_text = ""
tok_ln = i
tok_col = 1
}
# The scanner always fills the lookahead slot pk_*, and lex_next() moves that
# slot into tok_*; one token of pushback is enough for the whole grammar, and
# keeping the two slots apart saves saving and restoring the current token
# around every peek.
function lex_next() {
if (!have_peek)
lex_scan()
have_peek = 0
tok_kind = pk_kind
tok_text = pk_text
tok_ln = pk_ln
tok_col = pk_col
return tok_kind
}
function lex_peek() {
if (!have_peek) {
lex_scan()
have_peek = 1
}
return pk_kind
}
# Whitespace and %-comments are skipped between tokens, so a % inside a string
# literal is safe by construction.
function lex_skip_space( c) {
while (lex_i <= src_n) {
# substr() past the end of a line returns "", which is how the
# scanner detects end of line.
c = substr(src_text[lex_i], lex_col, 1)
if (c == "" || c == "%") {
# Remember where the source ran out, so that the EOF token
# still carries a location for "unexpected end of input".
# A comment runs to the end of the line, so step over it
# first: pointing the caret inside it would be misleading.
if (c == "%")
lex_col = length(src_text[lex_i]) + 1
lex_end_ln = lex_i
lex_end_col = lex_col
lex_i++
lex_col = 1
} else if (c == " " || c == "\t" || c == "\r") {
lex_col++
} else {
return
}
}
}
function lex_scan( line, c, n, span, two) {
lex_skip_space()
pk_ln = lex_i
pk_col = lex_col
pk_text = ""
if (lex_i > src_n) {
pk_ln = lex_end_ln
pk_col = lex_end_col
return pk_kind = "EOF"
}
line = src_text[lex_i]
c = substr(line, lex_col, 1)
if (c == "\"")
return lex_string(line)
if (index(WORDCH, c) > 0 && index(DIGITS, c) == 0) {
span = lex_span(line, lex_col, WORDCH)
pk_text = substr(line, lex_col, span)
lex_col += span
return pk_kind = lex_word_kind(pk_text)
}
# "-" is a sign on a numeric literal, never an operator: there is no
# arithmetic.
if (c == "-" || index(DIGITS, c) > 0) {
n = (c == "-") ? 1 : 0
span = lex_span(line, lex_col + n, DIGITS)
if (span == 0)
lex_error(lex_i, lex_col, "expected a digit after '-'")
pk_text = substr(line, lex_col, n + span)
lex_col += n + span
return pk_kind = "INT"
}
# Two-byte operators first, so that "<=" is not read as "<" then "=".
two = substr(line, lex_col, 2)
if (two == ":-" || two == "!=" || two == "<=" || two == ">=") {
lex_col += 2
return pk_kind = two
}
if (index("(),.?=<>", c) > 0) {
lex_col++
return pk_kind = c
}
if (c == ":" || c == "!")
lex_error(lex_i, lex_col, "expected '" c (c == ":" ? "-" : "=") "'")
lex_error(lex_i, lex_col, "unexpected character '" c "'")
}
# Number of consecutive bytes of set starting at col.
function lex_span(line, col, set, n, c) {
n = 0
for (;;) {
c = substr(line, col + n, 1)
if (c == "" || index(set, c) == 0)
break
n++
}
return n
}
function lex_word_kind(w, c) {
if (w == "not")
return "not"
if (w == "_")
return "ANON"
c = substr(w, 1, 1)
if (index(UPPER, c) > 0)
return "VAR"
if (index(LOWER, c) > 0)
return "IDENT"
lex_error(pk_ln, pk_col, "'" w "' is not a valid name: predicates and " \
"symbols begin with a lowercase letter, variables with an uppercase one")
}
# String literals do not span lines; the escapes are \\ \" \n \t \r and no
# others.
function lex_string(line, col, start, c, esc, out) {
start = lex_col
col = lex_col + 1
out = ""
for (;;) {
c = substr(line, col, 1)
if (c == "")
lex_error(lex_i, start, "unterminated string literal")
if (c == "\"") {
col++
break
}
if (c == "\\") {
col++
c = substr(line, col, 1)
if (c == "")
lex_error(lex_i, start, "unterminated string literal")
# The two tables are parallel: \\ \" n t r -> \ " NL TAB CR.
esc = index("\\\"ntr", c)
if (esc == 0)
# col is on the escaped character; point at the backslash.
lex_error(lex_i, col - 1, "unknown escape '\\" c "' in string literal")
out = out substr("\\\"\n\t\r", esc, 1)
col++
continue
}
out = out c
col++
}
lex_col = col
pk_text = out
return pk_kind = "STR"
}
function lex_error(ln, col, msg) {
die(source_where(ln, col), "syntax error: " msg)
}
# -------------------------------------------------------- symbols, values ---
function predicate_get(name, arity, key) {
key = name SUBSEP arity
if (key in pred_id)
return pred_id[key]
pred_n++
pred_id[key] = pred_n
pred_name[pred_n] = name
pred_arity[pred_n] = arity
# Seeded because every relation scan reads it and reading an absent
# element would create it anyway. pred_has_fact and pred_has_rule are
# deliberately left absent instead: seeding them would make
# (p in pred_has_rule) true for every predicate, and that test is how
# the checker and the delta loop ask whether a predicate is defined.
pred_tuple_count[pred_n] = 0
return pred_n
}
function predicate_label(p) {
return pred_name[p] "/" pred_arity[p]
}
# Constants carry a type tag -- s: symbol, q: string, n: number -- so that
# foo, "foo" and 42 are three distinct values under equality and inside tuple
# keys. The engine only ever compares and stores encoded values; decoding
# happens on output.
function value_encode(kind, text) {
if (kind == "n")
return "n:" number_text(text + 0)
return kind ":" value_escape(text)
}
# Tuple keys join encoded values with SUBSEP, so a SUBSEP (or the escape
# character itself) inside a string constant could otherwise forge another
# tuple's key; escaping here makes key construction injective.
function value_escape(s, out, c, i) {
if (index(s, "\\") == 0 && index(s, SUBSEP) == 0)
return s
out = ""
for (i = 1; ; i++) {
c = substr(s, i, 1)
if (c == "")
break
if (c == "\\")
out = out "\\\\"
else if (c == SUBSEP)
out = out "\\S"
else
out = out c
}
return out
}
# The encoded spelling of a number is built explicitly rather than left to the
# host's number->string rule: below 2^53 %d is exact, and above it a host's %d
# may convert through an integer type too narrow to hold the value, so those go
# through %.17g, which round-trips a double.
function number_text(v) {
if (v == int(v) && v < 9007199254740992 && v > -9007199254740992)
return sprintf("%d", v)
return sprintf("%.17g", v)
}
# ----------------------------------------------------------- tuple store ---
#
# A tuple is one ground row of a relation, with an integer id. Rows are
# interned under
#
# predicate-id SUBSEP encoded-arg-1 SUBSEP ... SUBSEP encoded-arg-n
#
# so re-deriving a row is one hash lookup and set semantics fall out of the
# array. That key is injective only because value_encode() escapes
# SUBSEP and the backslash inside constants: otherwise the two rows
#
# p("x" SUBSEP "q:y", "z") p("x", "y" SUBSEP "q:z")
#
# would spell the same key and the second would vanish as a duplicate.
#
# Arguments arrive in an array rather than one packed string because a caller
# usually has them in separate places already (head terms here, bindings in the
# evaluator), and packing them twice would cost a scan per candidate row.
function tuple_key(p, n, argv, key, k) {
key = p
for (k = 1; k <= n; k++)
key = key SUBSEP argv[k]
return key
}
# Interns argv[1..n] as a row of predicate p and returns its tuple id. Whether
# the row was new is reported through the global tuple_added, since an awk
# function returns one scalar.
function tuple_add(p, n, argv, key, t, k) {
key = tuple_key(p, n, argv)
if (key in tuple_exists) {
tuple_added = 0
return tuple_exists[key]
}
tuple_n++
t = tuple_n
tuple_exists[key] = t
tuple_pred[t] = p
for (k = 1; k <= n; k++)
tuple_arg[t, k] = argv[k]
pred_tuple_count[p]++
pred_tuple[p, pred_tuple_count[p]] = t
tuple_added = 1
return t
}
# ---------------------------------------------------------------- parser ---
#
# Recursive descent with one token of lookahead. Facts, rules, queries and
# constraints all become rules: a fact is a rule with an empty body, a query
# is a rule whose synthetic head carries its named variables in order of
# first appearance, and a constraint is a query whose rows are violations.
# Parsed objects are integer ids into flat arrays -- rule_*[r],
# rule_lit_*[r, i], term_*[r, i, k] -- rather than ASTs encoded as strings.
#
# The head of a fact or rule is parsed as body literal 1 and moved by
# rule_promote_head(), because no amount of lookahead at the first literal
# tells "head :- body" from "literal, literal?".
function parse_all( start) {
# Query text is appended to the same array below, so the input-file
# line count has to be taken before that.
stat_lines = src_n
lex_start(1)
parse_program(0)
if (opt_query != "") {
start = source_add_query(opt_query)
lex_start(start)
parse_program(1)
}
}
function parse_program(query_only) {
while (lex_peek() != "EOF")
parse_statement(query_only)
}
function parse_statement(query_only, r, k, n) {
if (lex_peek() == ":-") {
parse_constraint(query_only)
return
}
r = rule_new(pk_ln, pk_col)
parse_literal(r, 1)
k = lex_peek()
if (k == ":-") {
lex_next()
if (rule_lit_kind[r, 1] != 1)
die(source_where(rule_line[r], rule_col[r]),
"syntax error: a rule head must be a positive atom")
rule_promote_head(r)
rule_body_n[r] = parse_body(r)
expect(".", "'.'")
} else if (k == ".") {
lex_next()
if (rule_lit_kind[r, 1] != 1)
die(source_where(rule_line[r], rule_col[r]),
"syntax error: a fact must be a positive atom")
rule_promote_head(r)
rule_body_n[r] = 0
rule_is_fact[r] = 1
} else if (k == "," || k == "?") {
n = 1
while (lex_peek() == ",") {
lex_next()
n++
parse_literal(r, n)
}
rule_body_n[r] = n
expect("?", "'?'")
rule_is_query[r] = 1
rule_query_head(r)
query_n++
query_rule[query_n] = r
} else {
die(source_where(pk_ln, pk_col), "syntax error: expected ':-', '.' " \
"or '?', found " token_desc(pk_kind, pk_text))
}
if (query_only && !rule_is_query[r])
die(source_where(rule_line[r], rule_col[r]),
"error: only queries may be given with -q")
# What the statement defines is recorded once it is known to be one
# this caller accepts: -q rejects a fact or a rule only after parsing
# the whole thing, and marking its predicate as defined on the way
# through would silence an undefined warning that belongs elsewhere.
if (rule_is_query[r])
return
if (rule_is_fact[r])
pred_has_fact[rule_head_pred[r]] = 1
else {
pred_has_rule[rule_head_pred[r]] = 1
stat_rules++
}
}
# constraint := ":-" body "."
#
# A rule with no head is an integrity constraint: its body must never hold,
# and each row that satisfies it is a violation. It is parsed as a query --
# rule_is_query is set, and the synthetic head carries its named variables --
# because that is what it is: a body run against the finished relations,
# whose rows are reported instead of printed. Everything that takes a query
# to define nothing (the dependency graph, the strata, the unused-predicate
# check) takes a constraint the same way without knowing about it, and its
# body literals count as uses, as a query's do.
function parse_constraint(query_only, r) {
r = rule_new(pk_ln, pk_col)
lex_next()
rule_body_n[r] = parse_body(r)
expect(".", "'.'")
if (query_only)
die(source_where(rule_line[r], rule_col[r]),
"error: only queries may be given with -q")
rule_is_query[r] = 1
rule_is_constraint[r] = 1
rule_query_head(r)
constraint_n++
constraint_rule[constraint_n] = r
}
# body := literal ("," literal)* -- into positions 1.. of rule r; returns
# the number of literals.
function parse_body(r, n) {
n = 0
for (;;) {
n++
parse_literal(r, n)
if (lex_peek() != ",")
break
lex_next()
}
return n
}
function rule_new(ln, col, r) {
rule_n++
r = rule_n
rule_line[r] = ln
rule_col[r] = col
rule_head_pred[r] = 0
rule_head_arity[r] = 0
rule_body_n[r] = 0
rule_var_n[r] = 0
rule_is_fact[r] = 0
rule_is_query[r] = 0
rule_is_constraint[r] = 0
return r
}
function rule_promote_head(r, k, n) {
rule_head_pred[r] = rule_lit_pred[r, 1]
n = rule_lit_arity[r, 1]
rule_head_arity[r] = n
for (k = 1; k <= n; k++) {
rule_head_kind[r, k] = term_kind[r, 1, k]
rule_head_val[r, k] = term_val[r, 1, k]
}
}
# A query's columns are its named variables in order of first appearance;
# anonymous variables are never projected. The head
# predicate stays 0: a query emits rows, it does not populate a relation.
function rule_query_head(r, s, n) {
n = 0
for (s = 1; s <= rule_var_n[r]; s++) {
if (rule_var_name[r, s] == "")
continue
n++
rule_head_kind[r, n] = 1
rule_head_val[r, n] = s
}
rule_head_arity[r] = n
}
# literal := atom | "not" atom | comparison
#
# An IDENT in literal position starts an atom unless a comparison operator
# follows it, in which case it is a bare symbol operand ("foo = X").
function parse_literal(r, i, k, name, ln, col) {
k = lex_peek()
if (k == "not") {
lex_next()
expect("IDENT", "a predicate name")
rule_lit_kind[r, i] = 2
parse_atom(r, i, tok_text, tok_ln, tok_col)
return
}
if (k == "IDENT") {
lex_next()
name = tok_text
ln = tok_ln
col = tok_col
if (!comparator_p(lex_peek())) {
rule_lit_kind[r, i] = 1
parse_atom(r, i, name, ln, col)
return
}
pt_kind = 2
pt_val = value_encode("s", name)
parse_comparison(r, i, ln, col)
return
}
if (k == "VAR" || k == "ANON" || k == "INT" || k == "STR") {
ln = pk_ln
col = pk_col
parse_term(r)
parse_comparison(r, i, ln, col)
return
}
die(source_where(pk_ln, pk_col),
"syntax error: expected a literal, found " token_desc(pk_kind, pk_text))
}
# atom := IDENT [ "(" [term ("," term)*] ")" ] -- the name is already read.
function parse_atom(r, i, name, ln, col, argc) {
argc = 0
if (lex_peek() == "(") {
lex_next()
if (lex_peek() == ")") {
lex_next()
} else {
for (;;) {
argc++
parse_term(r)
term_kind[r, i, argc] = pt_kind
term_val[r, i, argc] = pt_val
if (lex_peek() != ",")
break
lex_next()
}
expect(")", "')'")
}
}
rule_lit_pred[r, i] = predicate_get(name, argc)
rule_lit_arity[r, i] = argc
rule_lit_line[r, i] = ln
rule_lit_col[r, i] = col
}
# comparison := term comparator term -- the left operand is in pt_kind/pt_val.
function parse_comparison(r, i, ln, col, op) {
term_kind[r, i, 1] = pt_kind
term_val[r, i, 1] = pt_val
op = lex_next()
if (!comparator_p(op))
die(source_where(tok_ln, tok_col), "syntax error: expected a " \
"comparison operator, found " token_desc(tok_kind, tok_text))
parse_term(r)
term_kind[r, i, 2] = pt_kind
term_val[r, i, 2] = pt_val
rule_lit_kind[r, i] = 3
rule_lit_pred[r, i] = 0
rule_lit_op[r, i] = op
rule_lit_arity[r, i] = 2
rule_lit_line[r, i] = ln
rule_lit_col[r, i] = col
# Where the right operand starts, so that a type error on it points at
# the operand and not at the head of the whole comparison. parse_term()
# consumed exactly one token, so tok_* still names it.
rule_lit_rhs_ln[r, i] = tok_ln
rule_lit_rhs_col[r, i] = tok_col
}
# Terms return through pt_kind/pt_val: 1 variable slot, 2 symbol, 3 string,
# 4 number, with constants already encoded.
function parse_term(r, k) {
k = lex_next()
if (k == "VAR") {
pt_kind = 1
pt_val = var_slot(r, tok_text)
} else if (k == "ANON") {
pt_kind = 1
pt_val = var_slot(r, "")
} else if (k == "IDENT") {
pt_kind = 2
pt_val = value_encode("s", tok_text)
} else if (k == "STR") {
pt_kind = 3
pt_val = value_encode("q", tok_text)
} else if (k == "INT") {
# A literal past the largest double becomes infinity, which each
# awk spells its own way ("inf", "+inf") and mawk reads back as
# 0, so it would be neither one value nor one spelling.
if (tok_text + 0 > 1.7976931348623157e308 ||
tok_text + 0 < -1.7976931348623157e308)
die(source_where(tok_ln, tok_col), "error: integer literal " \
"out of range: beyond the largest double, about 1.8e308")
pt_kind = 4
pt_val = value_encode("n", tok_text)
} else {
die(source_where(tok_ln, tok_col),
"syntax error: expected a term, found " token_desc(tok_kind, tok_text))
}
}
# Each variable becomes a small integer slot, numbered in order of first
# appearance, so evaluation never looks a name up. Every occurrence of _ gets
# a fresh nameless slot, so pair(_, _) does not force the two arguments to be
# equal.
function var_slot(r, name, s) {
if (name != "" && (r, name) in rule_var_slot)
return rule_var_slot[r, name]
rule_var_n[r]++
s = rule_var_n[r]
rule_var_name[r, s] = name
if (name != "")
rule_var_slot[r, name] = s
return s
}
function comparator_p(k) {
return k == "=" || k == "!=" || k == "<" || k == "<=" || k == ">" || k == ">="
}
function expect(kind, what) {
if (lex_next() != kind)
die(source_where(tok_ln, tok_col), "syntax error: expected " what \
", found " token_desc(tok_kind, tok_text))
}
# ---------------------------------------------------------- fact loading ---
# A fact is a rule with an empty body and must be ground, so it is
# stored directly instead of being evaluated. Loading runs before the semantic
# checks so that -c reports the relation sizes it would really evaluate over,
# and so that a missing-variable diagnostic names the fact that carries it.
function load_facts( r, p, n, k, name, argv) {
for (r = 1; r <= rule_n; r++) {
if (!rule_is_fact[r])
continue
p = rule_head_pred[r]
n = rule_head_arity[r]
for (k = 1; k <= n; k++) {
if (rule_head_kind[r, k] == 1) {
name = rule_var_name[r, rule_head_val[r, k]]
if (name == "")
name = "_"
die(source_where(rule_line[r], rule_col[r]),
"error: a fact must be ground: " \
predicate_label(p) " contains variable '" name "'")
}
argv[k] = rule_head_val[r, k]
}
# Stale argv entries past n are never read: the key stops at n.
tuple_add(p, n, argv)
if (tuple_added)
stat_input_facts++
else
stat_dup_facts++
}
}
# ---------------------------------------------------------------- checks ---
#
# Safety is decided statically and independently of the order the body is
# written in, because the evaluator reorders literals: the set of slots a
# positive body literal can bind is collected over the whole body first, and
# the head, every negation and every comparison are then measured against it.
function check_program( r) {
for (r = 1; r <= rule_n; r++)
if (!rule_is_fact[r])
check_rule_safety(r)
check_undefined()
check_unused()
}
function check_rule_safety(r, bound, i, k, kind) {
# Every slot bound by a positive body literal.
for (i = 1; i <= rule_body_n[r]; i++) {
if (rule_lit_kind[r, i] != 1)
continue
for (k = 1; k <= rule_lit_arity[r, i]; k++)
if (term_kind[r, i, k] == 1)
bound[term_val[r, i, k]] = 1
}
for (i = 1; i <= rule_body_n[r]; i++) {
kind = rule_lit_kind[r, i]
# Negation is membership on a ground tuple, so every argument
# must already be bound; = is a filter and not a binder, so it
# needs no special case.
if (kind == 2)
check_bound_terms(r, i, bound,
"'not " predicate_label(rule_lit_pred[r, i]) "'")
else if (kind == 3) {
check_bound_terms(r, i, bound,
"comparison '" rule_lit_op[r, i] "'")
check_compare_types(r, i)
}
}
check_head_safety(r, bound)
}
function check_bound_terms(r, i, bound, what, k, s) {
for (k = 1; k <= rule_lit_arity[r, i]; k++) {
if (term_kind[r, i, k] != 1)
continue
s = term_val[r, i, k]
if (s in bound)
continue
die(source_where(rule_lit_line[r, i], rule_lit_col[r, i]),
"error: unsafe " rule_noun(r) ": variable '" var_display(r, s) \
"' in " what " is not bound by a positive body literal")
}
}
# Range restriction: every head variable is bound by the body. A query's
# synthetic head carries its named variables, so queries get the same check.
function check_head_safety(r, bound, k, s, where) {
where = source_where(rule_line[r], rule_col[r])
for (k = 1; k <= rule_head_arity[r]; k++) {
if (rule_head_kind[r, k] != 1)
continue
s = rule_head_val[r, k]
if (s in bound)
continue
if (rule_is_query[r])
die(where, "error: unsafe " rule_noun(r) ": variable '" \
var_display(r, s) \
"' is not bound by a positive body literal")
die(where, "error: unsafe rule: variable '" var_display(r, s) \
"' in the head of " predicate_label(rule_head_pred[r]) \
" is not bound by a positive body literal")
}
}
# An ordering comparison is legal only where both operands resolve to
# numbers. A symbol or string constant never will, so it is rejected here
# rather than at run time, where the same operand would abort a query midway.
function check_compare_types(r, i, op, k, kind) {
op = rule_lit_op[r, i]
if (op == "=" || op == "!=")
return
for (k = 1; k <= 2; k++) {
kind = term_kind[r, i, k]
if (kind != 2 && kind != 3)
continue
die(operand_where(r, i, k),
"error: ordering comparison '" op "' requires " \
"numeric operands, found " \
(kind == 2 ? "a symbol" : "a string literal"))
}
}
# A predicate with neither facts nor rules is an empty relation rather than an
# error, so that a program whose fact file is absent still runs; the warning
# goes to stderr, leaving stdout clean for pipelines.
# The memo is per predicate, so a name stays reported once however many
# literals mention it.
function check_undefined( r, i, p) {
for (r = 1; r <= rule_n; r++)
for (i = 1; i <= rule_body_n[r]; i++) {
if (rule_lit_kind[r, i] == 3)