Check-in [c9faa932a7]

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Substantial code and commentary cleanup in datalog.tcl
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:c9faa932a714252c5c6b1794a5b9e70f0f71c956
User & Date: kbk 2014-08-03 23:19:11
Context
2014-08-06
13:08
better error checking for compileProgram check-in: 776298dbea user: kbk tags: trunk
2014-08-03
23:19
Substantial code and commentary cleanup in datalog.tcl check-in: c9faa932a7 user: kbk tags: trunk
01:58
Add more FDDD tests, clean up whitespace in tests, and fix bugs exposed in testing. check-in: d1e531296b user: kbk tags: trunk
Changes

Changes to library/datalog.tcl.

233
234
235
236
237
238
239



240
241
242
243
244
245
246
247
248
249















250
251
252
253
254
255
256
...
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
...
637
638
639
640
641
642
643

644
645
646
647
648
649
650
651
652
653
654
...
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
...
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
...
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
1001
1002
1003
1004
1005





















1006
1007
1008
1009
1010
1011
1012


1013
1014
1015


1016
1017
1018
1019
1020
1021
1022
1023
1024
1025



















1026


1027
1028
1029
1030
1031
1032
1033
1034
1035






1036
1037
1038
1039
1040
1041
1042
1043
1044


1045
1046
1047





1048
1049
1050
1051
1052





1053
1054
1055
1056
1057
1058
1059
....
1064
1065
1066
1067
1068
1069
1070

1071
1072
1073
1074
1075
1076
1077
1078


1079
1080
1081
1082
1083
1084
1085
1086


1087
1088
1089
1090
1091
1092
1093
....
1094
1095
1096
1097
1098
1099
1100























1101
1102
1103
1104



1105
1106
1107
1108
1109
1110



1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121

















1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
....
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
....
1235
1236
1237
1238
1239
1240
1241





1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
....
1345
1346
1347
1348
1349
1350
1351










1352
1353
1354
1355







1356
1357
1358
1359
1360
1361
1362









1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378



1379
1380
1381
1382
1383
1384
1385
....
1531
1532
1533
1534
1535
1536
1537
































































































1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
#	Formats a rule for printing.
#
# Usage:
#	bdd::datalog::prettyprint-rule $rule
#
# Parameters:
#	rule - Rule in the parse tree




proc bdd::datalog::prettyprint-rule {rule} {
    set s [prettyprint-literal [lindex $rule 0]]
    set sep :-
    foreach subgoal [lrange $rule 1 end] {
	append s $sep [prettyprint-subgoal $subgoal]
	set sep ,
    }
    return $s
}















proc bdd::datalog::prettyprint-subgoal {subgoal} {
    switch -exact [lindex $subgoal 0] {
	EQUALITY {
	    set s [prettyprint-variable [lindex $subgoal 1]]
	    append s = [prettyprint-variable [lindex $subgoal 2]]
	}
	INEQUALITY {
................................................................................
	}
	default {
	    error "Expected subgoal and got $subgoal"
	}
    }
    return $s
}















proc bdd::datalog::prettyprint-literal {literal} {
    # FIXME: May need to quote s (and backslashify its content)
    set s [lindex $literal 1]
    if {[llength $literal] > 2} {
	set sep \(
	foreach t [lrange $literal 2 end] {
	    append s $sep [prettyprint-term $t]
	    set sep ,
	}
	append s \)
    }
    return $s
}














proc bdd::datalog::prettyprint-term {term} {
    switch -exact [lindex $term 0] {
	VARIABLE {
	    return [prettyprint-variable $term]
	}
	CONSTANT {
................................................................................
	    return [prettyprint-constant $term]
	}
	default {
	    error "expected term and got $term"
	}
    }
}















proc bdd::datalog::prettyprint-constant {constant} {
    switch -exact [lindex $constant 1 0] {
	INTEGER {
	    return [lindex $constant 1 1]
	}
	TCLVAR {
	    return \$[list [lindex $constant 1 1]]
	}
    }
}














proc bdd::datalog::prettyprint-variable {variable} {
    # FIXME: May need to quote and backslashify
    return [lindex $variable 1]
}

# bdd::datalog::program --
#
#	Class that exists to hold a program description under construction
#	from the parser.

oo::class create bdd::datalog::program {



    # 'rules' is a list of all the rules in the program, expressed as
    #         parse trees.

    # 'rulesForPredicate' is a dictionary whose keys are predicate names
    #         and whose values are lists of rules that assign a value to the
    #	      given predicate. The lists consist of integer indices into
    #         the 'rules' list.



    # 'factsForPredicate' is a dictionary whose keys are predicate names
    #         and whose values are lists of facts that assign a value to the
    #         given predicate

    # 'outEdgesForPredicate' is a dictionary whose keys are predicate names
    #         and whose values are edges that describe the rules that depend
    #         on the given predicate. Each edge is a tuple:
    #             [0] The name of the predicate being tracked
    #             [1] The name of the predicate on the left hand side of
    #                 the dependent rule
    #		  [2] 1 if the predicate is negated in the rule, 0 otherwise
    #             [3] The dependent rule, as a parse tree
    #             [4] The index of the predicate being tracked within the
    #                 subgoals on the right hand side of the dependent rule.

    # 'query' is a literal giving the query at the end of the program
    #         (if any)

    # 'executionPlan' gives the eventual order of execution of the facts
    #                 and rules. It is a list of tuples:
    #                     RULE literal subgoal subgoal ...
    #		          FACT literal
    #		          LOOP predicate executionPlan
    #                 possibly having 'QUERY literal' at the end.

    # 'intcode' is the execution plan translated to an intermediate code
    #           that expresses the work to be done in terms of relational
    #	        algebra.








































































    variable \

	rules \
	rulesForPredicate \
	factsForPredicate \
	outEdgesForPredicate \
	query \
	executionPlan \
	intcode

    # Constructor -
    #
    #	Creates an empty program.




    constructor {} {

	set rules {}
	set rulesForPredicate {}
	set factsForPredicate {}
	set outEdgesForPredicate {}
	set executionPlan {}
	set intcode {}
    }
................................................................................
	    if {$d > $maxDelta} {
		set maxDelta $d
		set toRemove $pred
	    }
	}

	# Make a loop to iterate over that predicate

	try {
	    # Take all the other component members and compile
	    # their rules recursively.
	    set loopBody [::bdd::datalog::program new]
	    foreach rule $loops {
		if {[lindex $rule 0 1] ne $toRemove} {
		    $loopBody assertRule $rule
		}
	    }
	    set bodyCode [$loopBody planExecution]

................................................................................

    # Method: translateExecutionPlan
    #
    #	Once an execution plan has been constructed, translates it to
    #	three-address code.
    #
    # Parameters:
    #	db - Database on which the plan will be executed. The input and
    #	     output relations, and all columns appearing in the code,
    #	     must be defined.
    #	plan - Execution plan, a list of FACT, RULE, LOOP, and QUERY
    #	       subplans, as returned from 'planExecution'
    #
    # Results:
    #	Returns a list of three-address instructions.

    method translateExecutionPlan {db plan} {
	foreach step $plan {
	    switch -exact -- [lindex $step 0] {
		FACT {
		    my translateFact $db [lindex $step 1]
		}
		LOOP {
		    my translateLoop $db [lindex $step 1] [lindex $step 2]
		} 
		QUERY {
		    my translateQuery $db [lindex $step 1]
		}
		RULE {
		    my translateRule $db [lindex $step 1]
		}
		default {
		    error "in translateExecutionPlan: can't happen"
		}
	    }
	}
	return $intcode
................................................................................
    }

    # Method: translateFact
    #
    #	Translates a fact in the execution plan to three-address code
    #
    # Parameters:
    #	db - Database on which the plan will be executed. The input and
    #	     output relations, and all columns appearing in the code,
    #	     must be defined.
    #	fact - Literal representing the fact to be translated.
    #	cols - If supplied, list of names of the columns of the
    #	       relation representing $fact's predicate.
    #
    # Results:
    #	None.
    #
    # Side effects:
    #	Appends three-addres instructions to 'intcode'

    method translateFact {db fact {cols {}}} {

	set predicate [lindex $fact 1]

	# Retrieve the set of columns in the output relation if not supplied
	# by the caller.

	if {$cols eq {}} {
	    db relationMustExist $predicate
	    set cols [$db columns $predicate]
	    if {[llength $cols] != [llength $fact]-2} {
		set ppfact [bdd::datalog::prettyprint-literal $fact]
		return -code error \
		    -errorCode [list DATALOG wrongColumns $predicate $ppfact] \
		    "$predicate has a different number of columns from $ppfact"
	    }
................................................................................

    # Method: translateLoop
    #
    #	Generates three-address code for rules with a cyclic dependency,
    #	iterating to a fixed point.
    #
    # Parameters:
    #	db - Database on which the plan will be executed. The input and
    #	     output relations, and all columns appearing in the code,
    #	     must be defined.
    #   predicate - Predicate to test for a fixed point.
    #	body - Execution plan for the loop body.
    #
    # Results:
    #	None.
    #
    # Side effects:
    #	Appends three-address instructions to 'intcode'

    method translateLoop {db predicate body} {

	db relationMustExist $predicate
	set cols [$db columns $predicate]
	set comparison [my gensym #T]

	# Create a temporary relation to record the old value of
	# predicate for convergence testing.
	lappend intcode [list RELATION $comparison $cols]

................................................................................
	set where [llength $intcode]
	lappend intcode BEGINLOOP

	# Save the value of the relation being iterated
	lappend intcode [list SET $comparison $predicate]

	# Translate the loop body
	my translateExecutionPlan $db $body

	# Translate the loop footer.
	lappend intcode [list ENDLOOP $comparison $predicate $where]
    }














    method translateQuery {db query} {
	lassign [my translateSubgoal $db $query {} {}] tempRelation tempColumns
	lappend intcode [list RESULT $tempRelation $tempColumns]
	
    }














    method translateRule {db rule} {
	set tempRelation {}
	set tempColumns {}
	foreach subgoal [lrange $rule 1 end] {
	    lassign [my translateSubgoal \
			 $db $subgoal $tempRelation $tempColumns] \
		tempRelation tempColumns
	}
	my translateRuleHead $db [lindex $rule 0] $tempRelation $tempColumns
    }




















    method translateSubgoal {db subgoal dataSoFar columnsSoFar} {


	switch -exact [lindex $subgoal 0] {
	    NOT {
		lassign \
		    [my translateLiteral $db \
			 [lindex $subgoal 1] $dataSoFar $columnsSoFar] \
		    subgoalRelation subgoalColumns
		tailcall my translateSubgoalEnd $db ANTIJOIN \
		    $dataSoFar $columnsSoFar $subgoalRelation $subgoalColumns
	    }
	    EQUALITY -
	    INEQUALITY {
		tailcall my translateEquality $db [lindex $subgoal 0] \
		    [lindex $subgoal 1] [lindex $subgoal 2] \
		    $dataSoFar $columnsSoFar
	    }
	    LITERAL {
		lassign \
		    [my translateLiteral \
			 $db $subgoal $dataSoFar $columnsSoFar] \
		    subgoalRelation subgoalColumns
		tailcall my translateSubgoalEnd $db JOIN \
		    $dataSoFar $columnsSoFar $subgoalRelation $subgoalColumns
	    }
	    default {
		error "in translateSubgoal: can't happen"
	    }
	}
    }






















    method translateEquality {db operation var1 var2 dataSoFar columnsSoFar} {
	set col1 [lindex $var1 1]
	set col2 [lindex $var2 1]
	set equality [my gensym #T]
	lappend intcode \
	    [list RELATION $equality [list $col1 $col2]] \
	    [list $operation $equality $col1 $col2]


	if {$columnsSoFar eq {}} {
	    return [list $equality [list $col1 $col2]]
	} else {


	    set joined [my gensym #T]
	    lappend columnsSoFar $col1 $col2
	    set columnsSoFar [lsort -dictionary -unique $columnsSoFar]
	    lappend intcode \
		[list RELATION $joined $columnsSoFar] \
		[list JOIN $joined $dataSoFar $equality]
	    return [list $joined $columnsSoFar]
	}
    }




















    method translateLiteral {db literal dataSoFar columnsSoFar} {


	set predicate [lindex $literal 1]
	db relationMustExist $predicate
	set cols [db columns $predicate]
	if {[llength $cols] != [llength $literal]-2} {
	    set pplit [bdd::datalog::prettyprint-literal $literal]
	    return -code error \
		-errorCode [list DATALOG wrongColumns $predicate $pplit] \
		"$predicate has a different number of columns from $pplit"
	}






	set selector [my gensym #T]
	set selectLiteral [list LITERAL $selector]
	set needSelect 0
	set needProject 0
	set projector [my gensym #T]
	set projectColumns {}
	set renamed [my gensym #T]
	set renamedFrom {}
	set renamedTo {}


	foreach term [lrange $literal 2 end] col $cols {
	    switch -exact -- [lindex $term 0] {
		CONSTANT {





		    lappend selectLiteral $term
		    set needSelect 1
		    set needProject 1
		}
		VARIABLE {





		    set varName [lindex $term 1]
		    lappend selectLiteral {VARIABLE _}
		    if {$varName eq {_}} {
			set needProject 1
 		    } else {
			lappend projectColumns $col
			lappend renamedColumns $varName
................................................................................
			    lappend renamedTo $varName
			}
		    }
		}
	    }
	}


	if {$needSelect} {
	    lappend intcode [list RELATION $selector $cols]
	    my translateFact $db $selectLiteral $cols
	    lappend intcode [list JOIN $selector $selector $predicate]
	    set projectSource $selector
	} else {
	    set projectSource $predicate
	}


	if {$needProject} {
	    lappend intcode \
		[list RELATION $projector $projectColumns] \
		[list PROJECT $projector $projectSource]
	    set renameSource $projector
	} else {
	    set renameSource $projectSource
	}


	if {[llength $renamedFrom] > 0} {
	    lappend intcode [list RELATION $renamed $renamedColumns]
	    set renameCommand [list RENAME $renamed $renameSource]
	    foreach to $renamedTo from $renamedFrom {
		lappend renameCommand $to $from
	    }
	    lappend intcode $renameCommand
................................................................................
	    set result $renamed
	} else {
	    set result $renameSource
	}
	return [list $result $renamedColumns]
    }
























    method translateSubgoalEnd {db operation 
				dataSoFar columnsSoFar
				dataThisOp columnsThisOp} {
	if {$dataSoFar eq {}} {



	    if {$operation eq {ANTIJOIN}} {
		lappend intcode [list NEGATE $dataThisOp $dataThisOp]
	    }
	    set resultRelation $dataThisOp
	    set resultColumns $columnsThisOp
	} else {



	    set resultColumns $columnsSoFar
	    lappend resultColumns {*}$columnsThisOp
	    set resultColumns [lsort -unique -dictionary $resultColumns]
	    set resultRelation [my gensym #T]
	    lappend intcode \
		[list RELATION $resultRelation $resultColumns] \
		[list $operation $resultRelation $dataSoFar $dataThisOp]
	}
	return [list $resultRelation $resultColumns]
    }


















    method translateRuleHead {db literal sourceRelation sourceColumns} {
	set predicate [lindex $literal 1]
	db relationMustExist $predicate
	set cols [db columns $predicate]
	if {[llength $cols] != [llength $literal]-2} {
	    set pplit [bdd::datalog::prettyprint-literal $literal]
	    return -code error \
		-errorCode [list DATALOG wrongColumns $predicate $pplit] \
		"$predicate has a different number of columns from $pplit"
	}

................................................................................
	}

	# Join with any constants

	set joinColumns $renamedColumns
	if {[llength $constantColumns] > 0} {
	    lappend intcode [list RELATION $constant $constantColumns]
	    my translateFact $db $constantLiteral $constantColumns
	    lappend joinColumns {*}$constantColumns
	    set joined [my gensym #T]
	    lappend intcode \
		[list RELATION $joined $joinColumns] \
		[list JOIN $joined $joinSource $constant]
	    set joinSource $joined
	}
................................................................................
	}

	# Union the result into the destination
	lappend intcode [list UNION $predicate $predicate $joinSource]
	
    }






    method generateCode {db icode args} {

	set loaders {}

	set prologue \n
	set body \n
	set epilogue \n

	set ind0 {    }
	set ind {    }

	foreach instr $icode {
	    switch -exact -- [lindex $instr 0] {
		RELATION {
		    $db relation [lindex $instr 1] {*}[lindex $instr 2]
		    append prologue $ind0 [$db set [lindex $instr 1] {}] \n
		    append epilogue $ind0 [$db set [lindex $instr 1] {}] \n
		}
		
................................................................................
	    }

	}
	return $prologue$body$epilogue

    }











    method getRule {ruleNo} {
	return [lindex $rules $ruleNo]
    }








    method getRules {} {
	return $rules
    }

    method getRulesFor {} {
	return $rulesForPredicate
    }










    method getRulesForPredicate {predicate} {
	if {[dict exists $rulesForPredicate $predicate]} {
	    return [dict get $rulesForPredicate $predicate]
	} else {
	    return {}
	}
    }

    method getEdges {} {
	return $outEdgesForPredicate
    }

    method getFacts {} {
	return $factsForPredicate
    }




    method getFactsForPredicate {predicate} {
	if {[dict exists $factsForPredicate $predicate]} {
	    return [dict get $factsForPredicate $predicate]
	} else {
	    return {}
	}
................................................................................
	}
	yield $component

    }
    return
}

































































































proc bdd::datalog::compileProgram {db prelude programText args} {

    set postlude [lindex $args end]

    variable parser

    try {

	set program [bdd::datalog::program new]

	# Do lexical analysis of the program
	lassign [lex $programText] tokens values
	
	# Parse the program
	set parseTree [$parser parse $tokens $values $program]

	# Plan the execution
	set plan [$program planExecution]

	# Translate the execution plan to relational algebra
	set intcode [$program translateExecutionPlan $db $plan]

	# Generate code
	append result \
	    $prelude \n \
	    [$program generateCode $db $intcode {*}[lrange $args 0 end-1]] \n \
	    $postlude

    } finally {

	$program destroy

    }
    return $result

}

package provide tclbdd::datalog 0.1







>
>
>










>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>













>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>










>
>
>
>
>
>
>
>
>
>
>
>
>
>












>
>


>

|
<
<
>
>
>
|


>










>


>






>



|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

>











|
>
>
>
|
>







 







>



<







 







<
<
<






|



|


|


|


|







 







<
<
<










|







|







 







<
<
<









|

|







 







|





>
>
>
>
>
>
>
>
>
>
>
>
>
|
|




>
>
>
>
>
>
>
>
>
>
>
>
>
|



<
|


|


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>



|


|




|





<
|

|








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|






>
>



>
>










>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>

|
|






>
>
>
>
>
>









>
>



>
>
>
>
>





>
>
>
>
>







 







>


|





>
>








>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|



>
>
>






>
>
>











>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|

|
|







 







|







 







>
>
>
>
>
|










|







 







>
>
>
>
>
>
>
>
>
>




>
>
>
>
>
>
>




<
|
<
>
>
>
>
>
>
>
>
>









|
|
|
|
|
|
|
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>








|




|
|





|




|












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
...
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
...
796
797
798
799
800
801
802
803
804
805
806

807
808
809
810
811
812
813
...
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
1001
1002
1003
1004
....
1069
1070
1071
1072
1073
1074
1075



1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
....
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144

1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189

1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
....
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
....
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
....
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
....
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
....
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691

1692

1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
....
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
#	Formats a rule for printing.
#
# Usage:
#	bdd::datalog::prettyprint-rule $rule
#
# Parameters:
#	rule - Rule in the parse tree
#
# Results:
#	Returns the formatted string.

proc bdd::datalog::prettyprint-rule {rule} {
    set s [prettyprint-literal [lindex $rule 0]]
    set sep :-
    foreach subgoal [lrange $rule 1 end] {
	append s $sep [prettyprint-subgoal $subgoal]
	set sep ,
    }
    return $s
}

# bdd::datalog::prettyprint-subgoal --
#
#	Formats a subgoal for printing.
#
# Usage:
#	bdd::datalog::prettyprint-subgoal $subgoal
#
# Parameters:
#	subgoal - Subgoal (EQUALITY, INEQUALITY, NOT or LITERAL) to be
#		  printed, expressed as a parse tree.
#
# Results:
#	Returns the formatted string.

proc bdd::datalog::prettyprint-subgoal {subgoal} {
    switch -exact [lindex $subgoal 0] {
	EQUALITY {
	    set s [prettyprint-variable [lindex $subgoal 1]]
	    append s = [prettyprint-variable [lindex $subgoal 2]]
	}
	INEQUALITY {
................................................................................
	}
	default {
	    error "Expected subgoal and got $subgoal"
	}
    }
    return $s
}

# bdd::datalog::prettyprint-literal --
#
#	Formats a literal for printing.
#
# Usage:
#	bdd::datalog::prettyprint-literal $literal
#
# Parameters:
#	literal - Literal (LITERAL relation ?term...?) to be printed,
#                 expressed as a parse tree.
#
# Results:
#	Returns the formatted string.

proc bdd::datalog::prettyprint-literal {literal} {
    # FIXME: May need to quote s (and backslashify its content)
    set s [lindex $literal 1]
    if {[llength $literal] > 2} {
	set sep \(
	foreach t [lrange $literal 2 end] {
	    append s $sep [prettyprint-term $t]
	    set sep ,
	}
	append s \)
    }
    return $s
}

# bdd::datalog::prettyprint-term --
#
#	Formats a term for printing.
#
# Usage:
#	bdd::datalog::prettyprint-term $term
#
# Parameters:
#	term - Term (VARIABLE or CONSTANT) expressed as a parse tree.
#
# Results:
#	Returns the formatted string.

proc bdd::datalog::prettyprint-term {term} {
    switch -exact [lindex $term 0] {
	VARIABLE {
	    return [prettyprint-variable $term]
	}
	CONSTANT {
................................................................................
	    return [prettyprint-constant $term]
	}
	default {
	    error "expected term and got $term"
	}
    }
}

# bdd::datalog::prettyprint-constant --
#
#	Formats a constant for printing.
#
# Usage:
#	bdd::datalog::prettyprint-constant $term
#
# Parameters:
#	term - Term (CONSTANT {INTEGER value} or CONSTANT {TCLVAR name})
#              to be formatted.
#
# Results:
#	Returns the formatted string.

proc bdd::datalog::prettyprint-constant {constant} {
    switch -exact [lindex $constant 1 0] {
	INTEGER {
	    return [lindex $constant 1 1]
	}
	TCLVAR {
	    return \$[list [lindex $constant 1 1]]
	}
    }
}

# bdd::datalog::prettyprint-variable --
#
#	Formats a variable for printing.
#
# Usage:
#	bdd::datalog::prettyprint-variable $term
#
# Parameters:
#	term - Term (VARIABLE name) to be formatted.
#
# Results:
#	Returns the formatted string.

proc bdd::datalog::prettyprint-variable {variable} {
    # FIXME: May need to quote and backslashify
    return [lindex $variable 1]
}

# bdd::datalog::program --
#
#	Class that exists to hold a program description under construction
#	from the parser.

oo::class create bdd::datalog::program {

    # 'db' is the name of the database we're compiling against
    #
    # 'rules' is a list of all the rules in the program, expressed as
    #         parse trees.
    #
    # 'rulesForPredicate' is a dictionary whose keys are predicate names
    #         and whose values are lists of rule numbers of


    #	      rules that have the given predicate on the
    #	      left hand side.
    #
    # factsForPredicate' is a dictionary whose keys are predicate names
    #         and whose values are lists of facts that assign a value to the
    #         given predicate
    #
    # 'outEdgesForPredicate' is a dictionary whose keys are predicate names
    #         and whose values are edges that describe the rules that depend
    #         on the given predicate. Each edge is a tuple:
    #             [0] The name of the predicate being tracked
    #             [1] The name of the predicate on the left hand side of
    #                 the dependent rule
    #		  [2] 1 if the predicate is negated in the rule, 0 otherwise
    #             [3] The dependent rule, as a parse tree
    #             [4] The index of the predicate being tracked within the
    #                 subgoals on the right hand side of the dependent rule.
    #
    # 'query' is a literal giving the query at the end of the program
    #         (if any)
    #
    # 'executionPlan' gives the eventual order of execution of the facts
    #                 and rules. It is a list of tuples:
    #                     RULE literal subgoal subgoal ...
    #		          FACT literal
    #		          LOOP predicate executionPlan
    #                 possibly having 'QUERY literal' at the end.
    #
    # 'intcode' is the execution plan translated to an intermediate code
    #           that expresses the work to be done in terms of relational
    #	        algebra.
    #
    # The language of the intermediate code is that it is a list of 
    # instructions, each of which is itself a list comprising an operation
    # and arguments.  Instructions that are currently recognized include:
    #
    # RELATION name ?column...?
    #	This is a declaration, rather than an instruction. It describes
    #   that a relation has a given set of columns. As a side effect, the
    #   relation is cleared (set to the empty set of tuples) before and
    #   after the program executes.
    #
    # ANTIJOIN outputRelation inputRelation1 inputRelation2
    #	When executed, this instruction sets the output relation to the
    #   antijoin of the two input relations.
    #
    # BEGINLOOP
    #   Begins a loop. All loops in the generated code are of the "iterate
    #   until convergence" type: they test at the bottom of the loop and
    #   run as long as something changes
    #
    # ENDLOOP relation1 relation2
    #   Closes a loop begun with BEGINLOOP. The loop runs until the contents
    #   of relation1 and relation2 are identical (===).
    #
    # EQUALITY relation column1 column2
    #   Sets the given relation to the set of tuples in which column1 and
    #   column2 have equal values.
    #
    # INEQUALITY relation column1 column2
    #   Sets the given relation to the set of tuples in which column1 and
    #   column2 have distinct values.
    #
    # JOIN outputRelation inputRelation1 inputRelation2
    #   Sets the given output relation to the relational join of the two
    #   input relations.
    #
    # LOAD outputRelation ?value...?
    #   Adds a single tuple to the given output relation. The 'value' arguments
    #   give the column values in order. Each argument is a two-element list:
    #	    INTEGER intval
    #		intval must be an integer at most the same width as the
    #		corresponding column. Its value will be used as the value
    #		in the tuple
    #	    TCLVAR varname
    #		The Tcl variable named 'varname' will be used for the value
    #		in the tuple. It must contain an integer at most the same width
    #		as the corresponding column.
    #
    # NEGATE outputRelation inputRelation
    #	Sets the output relation to the set of all tuples NOT present in the
    #   input relation.
    #
    # PROJECT outputRelation inputRelation
    #	Initializes the output relation, whose columns must be a subset
    #	of the columns of the input relation, by projecting away any unused
    #   columns of the input relation.
    #
    # RENAME outputRelation inputRelation ?outputVar inputVar?...
    #	Sets the output relation's tuples to the tuples of the input relation,
    #	with each variable named by an 'inputVar' replaced with the
    #   variable named by the corresponding 'outputVar'.
    #
    # SET outputRelation inputRelation
    #	Copies the given input relation to the given output relation.
    #
    # UNION outputRelation inputRelation1 inputRelation2
    #	Sets the ouput relation to the union of the two given input relations.
    #
    # RESULT relation
    #	Must be the last instruction in the list. Sets up to enumerate the
    #   tuples in the given relation as the result of a Datalog program.

    variable \
	db \
	rules \
	rulesForPredicate \
	factsForPredicate \
	outEdgesForPredicate \
	query \
	executionPlan \
	intcode

    # Constructor -
    #
    #	Creates an empty program.
    #
    # Arguments:
    #	db_ - Name of the database being compiled agains

    constructor {db_} {
	set db $db_
	set rules {}
	set rulesForPredicate {}
	set factsForPredicate {}
	set outEdgesForPredicate {}
	set executionPlan {}
	set intcode {}
    }
................................................................................
	    if {$d > $maxDelta} {
		set maxDelta $d
		set toRemove $pred
	    }
	}

	# Make a loop to iterate over that predicate
	set loopBody [::bdd::datalog::program new $db]
	try {
	    # Take all the other component members and compile
	    # their rules recursively.

	    foreach rule $loops {
		if {[lindex $rule 0 1] ne $toRemove} {
		    $loopBody assertRule $rule
		}
	    }
	    set bodyCode [$loopBody planExecution]

................................................................................

    # Method: translateExecutionPlan
    #
    #	Once an execution plan has been constructed, translates it to
    #	three-address code.
    #
    # Parameters:



    #	plan - Execution plan, a list of FACT, RULE, LOOP, and QUERY
    #	       subplans, as returned from 'planExecution'
    #
    # Results:
    #	Returns a list of three-address instructions.

    method translateExecutionPlan {plan} {
	foreach step $plan {
	    switch -exact -- [lindex $step 0] {
		FACT {
		    my translateFact [lindex $step 1]
		}
		LOOP {
		    my translateLoop [lindex $step 1] [lindex $step 2]
		} 
		QUERY {
		    my translateQuery [lindex $step 1]
		}
		RULE {
		    my translateRule [lindex $step 1]
		}
		default {
		    error "in translateExecutionPlan: can't happen"
		}
	    }
	}
	return $intcode
................................................................................
    }

    # Method: translateFact
    #
    #	Translates a fact in the execution plan to three-address code
    #
    # Parameters:



    #	fact - Literal representing the fact to be translated.
    #	cols - If supplied, list of names of the columns of the
    #	       relation representing $fact's predicate.
    #
    # Results:
    #	None.
    #
    # Side effects:
    #	Appends three-addres instructions to 'intcode'

    method translateFact {fact {cols {}}} {

	set predicate [lindex $fact 1]

	# Retrieve the set of columns in the output relation if not supplied
	# by the caller.

	if {$cols eq {}} {
	    $db relationMustExist $predicate
	    set cols [$db columns $predicate]
	    if {[llength $cols] != [llength $fact]-2} {
		set ppfact [bdd::datalog::prettyprint-literal $fact]
		return -code error \
		    -errorCode [list DATALOG wrongColumns $predicate $ppfact] \
		    "$predicate has a different number of columns from $ppfact"
	    }
................................................................................

    # Method: translateLoop
    #
    #	Generates three-address code for rules with a cyclic dependency,
    #	iterating to a fixed point.
    #
    # Parameters:



    #   predicate - Predicate to test for a fixed point.
    #	body - Execution plan for the loop body.
    #
    # Results:
    #	None.
    #
    # Side effects:
    #	Appends three-address instructions to 'intcode'

    method translateLoop {predicate body} {

	$db relationMustExist $predicate
	set cols [$db columns $predicate]
	set comparison [my gensym #T]

	# Create a temporary relation to record the old value of
	# predicate for convergence testing.
	lappend intcode [list RELATION $comparison $cols]

................................................................................
	set where [llength $intcode]
	lappend intcode BEGINLOOP

	# Save the value of the relation being iterated
	lappend intcode [list SET $comparison $predicate]

	# Translate the loop body
	my translateExecutionPlan $body

	# Translate the loop footer.
	lappend intcode [list ENDLOOP $comparison $predicate $where]
    }

    # Method: translateQuery
    #
    #	Generates three-address code to return the result of a Datalog query
    #
    # Parameters:
    #	query - Parse tree of the query
    #
    # Results:
    #	None.
    #
    # Side effects:
    #	Appends three-address instructions to 'intcode'

    method translateQuery {query} {
	lassign [my translateSubgoal $query {} {}] tempRelation tempColumns
	lappend intcode [list RESULT $tempRelation $tempColumns]
	
    }

    # Method: translateRule
    #
    #	Generates three-address code to evaluate a Datalog rule
    #
    # Parameters:
    #	rule - Parse tree of the rule
    #
    # Results:
    #	None.
    #
    # Side effects:
    #	Appends three-address instructions to 'intcode'

    method translateRule {rule} {
	set tempRelation {}
	set tempColumns {}
	foreach subgoal [lrange $rule 1 end] {

	    lassign [my translateSubgoal $subgoal $tempRelation $tempColumns] \
		tempRelation tempColumns
	}
	my translateRuleHead [lindex $rule 0] $tempRelation $tempColumns
    }

    # Method: translateSubgoal
    #
    #	Generates three-address code to evaluate a subgoal within a 
    #   Datalog rule
    #
    # Parameters:
    #	subgoal - Parse tree of the subgoal
    #	dataSoFar - Name of a relation that holds the result of evaluating
    #               the subgoals to the left of this subgoal
    #   columnsSoFar - List of column names present in 'dataSoFar'
    #
    # Results:
    #   Returns a two element list consisting of the name of the relation
    #   representing the partly-translated rule, and the names of the
    #   columns in that relation
    #
    # Side effects:
    #	Appends three-address instructions to 'intcode'

    method translateSubgoal {subgoal dataSoFar columnsSoFar} {

	# Dispatch according to the type of the subgoal
	switch -exact [lindex $subgoal 0] {
	    NOT {
		lassign \
		    [my translateLiteral \
			 [lindex $subgoal 1] $dataSoFar $columnsSoFar] \
		    subgoalRelation subgoalColumns
		tailcall my translateSubgoalEnd ANTIJOIN \
		    $dataSoFar $columnsSoFar $subgoalRelation $subgoalColumns
	    }
	    EQUALITY -
	    INEQUALITY {
		tailcall my translateEquality [lindex $subgoal 0] \
		    [lindex $subgoal 1] [lindex $subgoal 2] \
		    $dataSoFar $columnsSoFar
	    }
	    LITERAL {
		lassign \

		    [my translateLiteral $subgoal $dataSoFar $columnsSoFar] \
		    subgoalRelation subgoalColumns
		tailcall my translateSubgoalEnd JOIN \
		    $dataSoFar $columnsSoFar $subgoalRelation $subgoalColumns
	    }
	    default {
		error "in translateSubgoal: can't happen"
	    }
	}
    }

    # Method: translateEquality
    #
    #	Generates three-address code to evaluate a subgoal of the
    #   form 'a==b' or 'a!=b' within a Datalog rule
    #
    # Parameters:
    #	operation - EQUALITY or INEQUALITY depending on the operator encountered
    #   var1 - {VARIABLE name}, where 'name' is the left hand variable name
    #   var2 - {VARIABLE name}, where 'name' is the right hand variable name
    #	dataSoFar - Name of a relation that holds the result of evaluating
    #               the subgoals to the left of this subgoal
    #   columnsSoFar - List of column names present in 'dataSoFar'
    #
    # Results:
    #   Returns a two element list consisting of the name of the relation
    #   representing the partly-translated rule, and the names of the
    #   columns in that relation
    #
    # Side effects:
    #	Appends three-address instructions to 'intcode'

    method translateEquality {operation var1 var2 dataSoFar columnsSoFar} {
	set col1 [lindex $var1 1]
	set col2 [lindex $var2 1]
	set equality [my gensym #T]
	lappend intcode \
	    [list RELATION $equality [list $col1 $col2]] \
	    [list $operation $equality $col1 $col2]
	
	# If there are no earlier subgoals, just create and return the equality
	if {$columnsSoFar eq {}} {
	    return [list $equality [list $col1 $col2]]
	} else {

	    # There are earlier subgoals. Join the equality relation with them.
	    set joined [my gensym #T]
	    lappend columnsSoFar $col1 $col2
	    set columnsSoFar [lsort -dictionary -unique $columnsSoFar]
	    lappend intcode \
		[list RELATION $joined $columnsSoFar] \
		[list JOIN $joined $dataSoFar $equality]
	    return [list $joined $columnsSoFar]
	}
    }

    # Method: translateLiteral
    #
    #	Generates three-address code to evaluate a literal subgoal of a
    #   Datalog rule
    #
    # Parameters:
    #   literal - Parse tree of the literal
    #	dataSoFar - Name of a relation that holds the result of evaluating
    #               the subgoals to the left of this subgoal
    #   columnsSoFar - List of column names present in 'dataSoFar'
    #
    # Results:
    #   Returns a two element list consisting of the name of the relation
    #   representing the partly-translated rule, and the names of the
    #   columns in that relation
    #
    # Side effects:
    #	Appends three-address instructions to 'intcode'

    method translateLiteral {literal dataSoFar columnsSoFar} {

	# What relation/predicate does the literal refer to?
	set predicate [lindex $literal 1]
	$db relationMustExist $predicate
	set cols [$db columns $predicate]
	if {[llength $cols] != [llength $literal]-2} {
	    set pplit [bdd::datalog::prettyprint-literal $literal]
	    return -code error \
		-errorCode [list DATALOG wrongColumns $predicate $pplit] \
		"$predicate has a different number of columns from $pplit"
	}

	# Make a relation to hold the result of selecting for the tuples
	# that match the literal. The result of the selection may need
	# projection (to eliminate 'don't-care' columns) or renaming
	# (if the domains in the literal don't match the columns in the 
	# relation).
	set selector [my gensym #T]
	set selectLiteral [list LITERAL $selector]
	set needSelect 0
	set needProject 0
	set projector [my gensym #T]
	set projectColumns {}
	set renamed [my gensym #T]
	set renamedFrom {}
	set renamedTo {}

	# Process the terms
	foreach term [lrange $literal 2 end] col $cols {
	    switch -exact -- [lindex $term 0] {
		CONSTANT {

		    # Constant term - make it a selection condition.
		    # The result will require at least a SELECT operation
		    # to choose the tuples, and a projection to get rid
		    # of the constant value.
		    lappend selectLiteral $term
		    set needSelect 1
		    set needProject 1
		}
		VARIABLE {

		    # Variable term. If the variable is '_' (don't care),
		    # then it will need to be projected away. If the variable
		    # is other than the domain of the column, it will need
		    # renaming.
		    set varName [lindex $term 1]
		    lappend selectLiteral {VARIABLE _}
		    if {$varName eq {_}} {
			set needProject 1
 		    } else {
			lappend projectColumns $col
			lappend renamedColumns $varName
................................................................................
			    lappend renamedTo $varName
			}
		    }
		}
	    }
	}

	# Generate the selection to bring in any required tuples
	if {$needSelect} {
	    lappend intcode [list RELATION $selector $cols]
	    my translateFact $selectLiteral $cols
	    lappend intcode [list JOIN $selector $selector $predicate]
	    set projectSource $selector
	} else {
	    set projectSource $predicate
	}

	# Project away any constants and don't-cares
	if {$needProject} {
	    lappend intcode \
		[list RELATION $projector $projectColumns] \
		[list PROJECT $projector $projectSource]
	    set renameSource $projector
	} else {
	    set renameSource $projectSource
	}

	# Rename any columns that need it.
	if {[llength $renamedFrom] > 0} {
	    lappend intcode [list RELATION $renamed $renamedColumns]
	    set renameCommand [list RENAME $renamed $renameSource]
	    foreach to $renamedTo from $renamedFrom {
		lappend renameCommand $to $from
	    }
	    lappend intcode $renameCommand
................................................................................
	    set result $renamed
	} else {
	    set result $renameSource
	}
	return [list $result $renamedColumns]
    }

    # Method: translateSubgoalEnd
    #
    #	Generates three-address code to finish the evaluation of a literal
    #   subgoal of a Datalog rule, after code has been generated for all terms.
    #
    # Parameters:
    #   operation - JOIN or ANTIJOIN according to whether the literal is
    #               negated.
    #	dataSoFar - Name of a relation that holds the result of evaluating
    #               the subgoals to the left of this subgoal
    #   columnsSoFar - List of column names present in 'dataSoFar'
    #   dataThisOp - Name of a relation that holds the result of evaluating
    #                the literal
    #   columnsThisOp - Lisst of column names present in 'dataThisOp'
    #
    # Results:
    #   Returns a two element list consisting of the name of the relation
    #   representing the partly-translated rule, and the names of the
    #   columns in that relation
    #
    # Side effects:
    #	Appends three-address instructions to 'intcode'

    method translateSubgoalEnd {operation 
				dataSoFar columnsSoFar
				dataThisOp columnsThisOp} {
	if {$dataSoFar eq {}} {

	    # This is the first literal in the rule. Negate it if necessary,
	    # and let it be the result
	    if {$operation eq {ANTIJOIN}} {
		lappend intcode [list NEGATE $dataThisOp $dataThisOp]
	    }
	    set resultRelation $dataThisOp
	    set resultColumns $columnsThisOp
	} else {

	    # Join or antijoin the result of the literal to the result of
	    # the subgoals to its left
	    set resultColumns $columnsSoFar
	    lappend resultColumns {*}$columnsThisOp
	    set resultColumns [lsort -unique -dictionary $resultColumns]
	    set resultRelation [my gensym #T]
	    lappend intcode \
		[list RELATION $resultRelation $resultColumns] \
		[list $operation $resultRelation $dataSoFar $dataThisOp]
	}
	return [list $resultRelation $resultColumns]
    }

    # Method: translateRuleHead
    #
    #	Generates three-address code to finish the evaluation of a rule
    #   in a Datalog program, after code has been generated for its right
    #   hand side..
    #
    # Parameters:
    #   literal - Literal on the left hand side of the rule
    #	sourceRelation - Relation computed by the right-hand side
    #   sourceColumns - List of column names in 'sourceRelation'
    #
    # Results:
    #	None.
    #
    # Side effects:
    #	Appends three-address instructions to 'intcode'

    method translateRuleHead {literal sourceRelation sourceColumns} {
	set predicate [lindex $literal 1]
	$db relationMustExist $predicate
	set cols [$db columns $predicate]
	if {[llength $cols] != [llength $literal]-2} {
	    set pplit [bdd::datalog::prettyprint-literal $literal]
	    return -code error \
		-errorCode [list DATALOG wrongColumns $predicate $pplit] \
		"$predicate has a different number of columns from $pplit"
	}

................................................................................
	}

	# Join with any constants

	set joinColumns $renamedColumns
	if {[llength $constantColumns] > 0} {
	    lappend intcode [list RELATION $constant $constantColumns]
	    my translateFact $constantLiteral $constantColumns
	    lappend joinColumns {*}$constantColumns
	    set joined [my gensym #T]
	    lappend intcode \
		[list RELATION $joined $joinColumns] \
		[list JOIN $joined $joinSource $constant]
	    set joinSource $joined
	}
................................................................................
	}

	# Union the result into the destination
	lappend intcode [list UNION $predicate $predicate $joinSource]
	
    }

    # Method: generateCode
    #
    #	Generates Tcl code for a Datalog program from the intermediate code 
    #	lists

    method generateCode {args} {

	set loaders {}

	set prologue \n
	set body \n
	set epilogue \n

	set ind0 {    }
	set ind {    }

	foreach instr $intcode {
	    switch -exact -- [lindex $instr 0] {
		RELATION {
		    $db relation [lindex $instr 1] {*}[lindex $instr 2]
		    append prologue $ind0 [$db set [lindex $instr 1] {}] \n
		    append epilogue $ind0 [$db set [lindex $instr 1] {}] \n
		}
		
................................................................................
	    }

	}
	return $prologue$body$epilogue

    }

    # Method: getRule
    #
    #	Looks up a rule
    #
    # Parameters:
    #	ruleNo - Number of the rule in the order of definition
    #
    # Results:
    #	Returns the parse tree of the rule

    method getRule {ruleNo} {
	return [lindex $rules $ruleNo]
    }

    # Method: getRules
    #
    #	Returns a list of all defined rules
    #
    # Results:
    #	Returns a list of parse trees of all the rules, in order of definition

    method getRules {} {
	return $rules
    }


    # Method: getRulesForPredicate

    #
    #	Returns a list of the rules for a given predicate
    #
    # Parameters;
    #	predicate - Predicate (or name of the relation) being sought
    #
    # Results:
    #	Returns a list of rule nhmbers for the rules having the given
    #	predicate on the left hand side.

    method getRulesForPredicate {predicate} {
	if {[dict exists $rulesForPredicate $predicate]} {
	    return [dict get $rulesForPredicate $predicate]
	} else {
	    return {}
	}
    }

    # Method: getFactsForPredicate
    #
    #	Returns a list of the facts for a given predicate
    #
    # Parameters:
    #	predicate - Name of a predicate (relation)
    #
    # Results:
    #	Returns a list of the facts that assert values for the given predicate.
    #	Each fact is expressed as the parse tree of a literal.

    method getFactsForPredicate {predicate} {
	if {[dict exists $factsForPredicate $predicate]} {
	    return [dict get $factsForPredicate $predicate]
	} else {
	    return {}
	}
................................................................................
	}
	yield $component

    }
    return
}

# bdd::datalog::compileProgram --
#
#	Compiles a Datalog program into Tcl code
#
# Usage:
#	bdd::datalog::compileProgram $db {
#	    prelude
#	} {
#	    programText
#	} {
#	    postlude
#	}
#
#	-or-
#
#	bdd::datalog::compileProgram $db {
#	    prelude
#	} {
#	    programText
#	} dictVar {
#	    actions
#	} {
#	    postlude
#	}
#
# Parameters:
#	db - Name of the BDD database against which the Datalog program
#	     should operate
#	prelude - A block of Tcl code that should be evaluate before execution
#		  of the Datalog program begins.
#	programText - Text of the program to compile. In the first form,
#		      the text should comprise only assertions of facts
#		      and rules. In the second form, the text may contain
#		      assertions of facts and rules, and must end with
#		      a single query.
#	dictVar - The name of a Tcl variable that will receive, for each
#		  query result, a dictionary whose keys are the names of
#		  terms in the query and whose values are the values of
#		  the terms.
#	actions - A block of Tcl code that will be executed for each query
#		  result, after filling in 'dictVar' with the values
#		  produced by the query.
#	postlude - A block of Tcl code that should execute after the
#		   Datalog program, including all actions, ends.
#
# Results:
#	Returns a block of Tcl code that when evaluated, executes the Datalog
#	program.
#
# Ordinarily, this procedure is used with 'proc' or 'method' to define
# a procedure, with a full example looking like the following:
#
# # create the database, defining 8-bit domains a, b and c
# bdd::fddd::database create db \
#     [bdd::fddd::interleave \
#         [bdd::fddd::domain a 8] \
#         [bdd::fddd::domain b 8] \
#         [bdd::fddd::domain c 8]]]
#
# # create the 'parent' relation and load data into it
# db relation parent a b
# db relation grandparent a b
#
# interp alias {} loadParents {} {*}[db loader parent]
# loadParent 1 0
# loadParent 2 0
# loadParent 3 1
# loadParent 4 1
# loadParent 5 2
# loadParent 6 2
#
# # procedure to create the derived relations from 'parent'
# proc listGrandparents {} [bdd::datalog::compileProgram $db {
#     # no initialization needed
# } {
#     grandparent(a,b) :- parent(a,c), parent(c,b).
# } {
#     return
# }]
#
# # Query the database for the grandparents of an item
# proc grandparent {grandchild} [bdd::datalog::compileProgram $db {
#     set grandparents {}
# } {
#     grandparent(a,$grandchild)?
# } d {
#     lappend grandparents [dict get $d a]
# } {
#     return $grandparents
# }
#
# # Populate the 'grandparent' relation
# listGrandparents
# # What items are the grandparents of item 0?
# puts [grandparents 0]; # prints a list containing 3, 4, 5, and 6

proc bdd::datalog::compileProgram {db prelude programText args} {

    set postlude [lindex $args end]

    variable parser

    try {

	set program [bdd::datalog::program new $db]

	# Do lexical analysis of the program
	lassign [lex $programText] tokens values
	
	# Parse the program and feed the parse into $program
	$parser parse $tokens $values $program

	# Plan the execution
	set plan [$program planExecution]

	# Translate the execution plan to relational algebra
	$program translateExecutionPlan $plan

	# Generate code
	append result \
	    $prelude \n \
	    [$program generateCode {*}[lrange $args 0 end-1]] \n \
	    $postlude

    } finally {

	$program destroy

    }
    return $result

}

package provide tclbdd::datalog 0.1