tclbdd

Check-in [bd10382cec]
Login

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

Overview
Comment:Finished an initial whack at the compiler. It works well enough to do the 'reaching definitions' example.
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:bd10382cec6411856940a9cc05b0add2386db7fa
User & Date: kbk 2014-01-09 01:34:44
Context
2014-01-10
02:00
Clean up packaging a little bit, again. check-in: aa0c89ccc1 user: kbk tags: trunk
2014-01-09
01:34
Finished an initial whack at the compiler. It works well enough to do the 'reaching definitions' example. check-in: bd10382cec user: kbk tags: trunk
2014-01-08
04:57
more compiler development, most of the way through doing intermediate code for rules check-in: e19d9e2146 user: kbk tags: trunk
Changes
Hide Diffs Unified Diffs Show Whitespace Changes Patch

Changes to library/datalog.tcl.

18
19
20
21
22
23
24

25
26
27
28
29
30
31
32
...
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
...
535
536
537
538
539
540
541






542
543
544
545
546
547
548
...
579
580
581
582
583
584
585



586
587
588
589
590
591
592
...
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
...
666
667
668
669
670
671
672

















































673
674
675
676
677
678
679
...
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
...
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
...
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
...
891
892
893
894
895
896
897

898
899
900
901
902
903
904
...
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
...
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
....
1023
1024
1025
1026
1027
1028
1029

1030
1031
1032
1033
1034
1035
1036
1037
1038

1039
1040
1041
1042
1043
1044
1045
....
1051
1052
1053
1054
1055
1056
1057

1058
1059
1060
1061
1062
1063
1064
1065
1066

1067
1068
1069
1070

1071
1072
1073
1074
1075
1076
1077
1078
1079












































































































1080
1081
1082
1083
1084
1085
1086
....
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
....
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
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468

1469
1470
1471
1472
1473


1474
1475






1476
1477

1478
1479
1480















1481
1482
package require coroutine::iterator 1.0
package require grammar::aycock 1.0

namespace import coroutine::corovar::corovar

namespace eval bdd {
    namespace eval datalog {

	namespace export lex parse compile
    }
}

# bdd::datalog::lex --
#
#	Lexical analysis for the Datalog compiler.
#
................................................................................
    variable \
	rules \
	rulesForPredicate \
	factsForPredicate \
	outEdgesForPredicate \
	query \
	executionPlan \
	intcode \
	gensym

    # Constructor -
    #
    #	Creates an empty program.

    constructor {} {
	set rules {}
	set rulesForPredicate {}
	set factsForPredicate {}
	set outEdgesForPredicate {}
	set executionPlan {}
	set intcode {}
	set gensym 0
    }

    # gensym -
    #
    #	Generate a unique symbol
    #
    # Results:
    #	Returns a generated symbol

    method gensym {{prefix G}} {
	return ${prefix}[incr gensym]
    }

    # assertRule -
    #
    #	Semantic action called from the parser when a rule is being asserted
    #
    # Parameters:
................................................................................

	# Iterate through the components, in dependency order, and
	# plan their execution individually.
	
	foreach component [lreverse $components] {
	    my planExecutionForComponent $component
	}







	return $executionPlan

    }

    # Method: planExecutionForComponent
    #
................................................................................
		    }
		    1 {
			lappend loops $rule
		    }
		    0 {
			lappend executionPlan [list RULE $rule]
		    }



		}
	    }
	}
	if {[llength $loops] != 0} {
	    lappend executionPlan [my planIteration $component $loops]
	}
    }
................................................................................
    method planIteration {component loops} {
	# As a heuristic, iterate over the predicate whose in-degree
	# most exceeds its out-degree. This is the predicate whose deletion
	# will remove the most edges from the dependency graph

	# Score the predicates according to the degrees of the dependency
	# graph.
	foreach rule $loops {
	    set lhPredicate [lindex $rule 0 1]
	    foreach subgoal [lrange $rule 1 end] {
		switch -exact -- [lindex $subgoal 0] {
		    EQUALITY {	# does not introduce a dependency
			continue
		    }
		    NOT {
			set rhPredicate [lindex $subgoal 1 1]
		    }
		    LITERAL {
			set rhPredicate [lindex $subgoal 1]
		    }
		    default {
			error "in [info level 0]: can't happen."
		    }
		}
		if {[lsearch -exact $component $rhPredicate] >= 0} {
		    dict incr delta $lhPredicate 1; # edge into lhPredicate
		    dict incr delta $rhPredicate -1; # edge out of rhPredicate
		}
	    }
	}

	# Find the predicate with the high score
	set maxDelta -Inf
	dict for {pred d} $delta {
	    if {$d > $maxDelta} {
		set maxDelta $d
		set toRemove $pred
................................................................................
	} finally {
	    $loopBody destroy
	}

	return [list LOOP $toRemove $bodyCode]
		    
    }


















































    # Method: ruleDependsOn
    #
    #	Tests if a rule depends on one or more of a set of predicates.
    #
    # Parameters:
    #	rule - Parse tree of the rule
................................................................................
    #	Returns 2 if the rule depends on one of the predicates in negated
    #   form, 1, if the rule depends on one of the predicates only in
    #   non-negated form, 0 if the rule has no dependency on the predicates

    method subgoalDependsOn {subgoal predicates} {
	switch -exact -- [lindex $subgoal 0] {
	    EQUALITY {
		return false
	    }
	    NOT {
		if {[my subgoalDependsOn [lindex $subgoal 1] $predicates]} {
		    return 2
		} else {
		    return 0
		}
................................................................................
		} else {
		    return 0
		}
	    }
	}
    }
















    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] [lindex $step 2]
		}
		RULE {
		    my translateRule $db [lindex $step 1]
		}
		default {
		    error "in translateExecutionPlan: can't happen"
		}
	    }
	}
	return $intcode
    }



















    method translateFact {db fact {cols {}}} {
	lappend intcode "# [bdd::datalog::prettyprint-literal $fact]"

	set predicate [lindex $fact 1]




	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"
	    }
	}






	set probeColumns {}

	set dontCareColumns {}
	foreach term [lrange $fact 2 end] col $cols {
	    switch -exact [lindex $term 0] {
		CONSTANT {
		    lappend probeColumns $col
		    lappend probeValues $term
		}
		VARIABLE {
		    if {[lindex $term 1] ne {_}} {
			set ppfact [bdd::datalog::prettyprint-literal $fact]
			puts stderr "warning: unused variable [lindex $term 1]\
                                     in fact $ppfact."
		    }
		    lappend dontCareColumns $col
		}
	    }
	}



	if {$probeColumns eq {}} {
	    set ppfact [bdd::datalog::prettyprint-literal $fact]
	    puts stderr "warning: fact $ppfact. asserts the universal set"
	    lappend intcode \
		[list SET $predicate _]
	} else {






	    if {$dontCareColumns ne {}} {
		set probeRelation [my gensym #T]
		set dontCareRelation [my gensym #T]
		set joinedRelation [my gensym #T]
		lappend intcode \
		    [list RELATION $probeRelation $probeColumns]
		lappend intcode \
		    [list LOAD $probeRelation $probeValues]
		lappend intcode \
		    [list RELATION $dontCareRelation $dontCareColumns]
		lappend intcode \
		    [list SET $dontCareRelation _]
		lappend intcode \
		    [list RELATION $joinedRelation $cols]
		lappend intcode \

		    [list JOIN $joinedRelation $probeRelation $dontCareRelation]
		lappend intcode \
		    [list UNION $predicate $predicate $joinedRelation]
	    } else {




		lappend intcode \
		    [list LOAD $predicate $probeValues]
	    }
	}
    }



















    method translateLoop {db predicate body} {
	# TODO - Incrementalization?
	set comparison [my gensym #T]

	db relationMustExist $predicate
	set cols [$db columns $predicate]




	lappend intcode [list RELATION $comparison $cols]


	set where [llength $intcode]
	lappend intcode BEGINLOOP


	lappend intcode [list SET $comparison $predicate]


	my translateExecutionPlan $db $body


	lappend intcode [list ENDLOOP $comparison $predicate $where]
    }

    method translateQuery {db query} {
	# TODO: Destub


    }

    method translateRule {db rule} {
	lappend intcode "# [::bdd::datalog::prettyprint-rule $rule]"
	set tempRelation {}
	set tempColumns {}
	foreach subgoal [lrange $rule 1 end] {
	    lassign [my translateSubgoal \
			 $db $subgoal $tempRelation $tempColumns] \
		tempRelation tempColumns
	}
................................................................................
		    [my translateLiteral $db \
			 [lindex $subgoal 1] $dataSoFar $columnsSoFar] \
		    subgoalRelation subgoalColumns
		tailcall my translateSubgoalEnd $db ANTIJOIN \
		    $dataSoFar $columnsSoFar $subgoalRelation $subgoalColumns
	    }
	    EQUALITY {
		# TODO - what to do here?


	    }
	    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 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]
................................................................................
	set renamedFrom {}
	set renamedTo {}
	foreach term [lrange $literal 2 end] col $cols {
	    switch -exact -- [lindex $term 0] {
		CONSTANT {
		    lappend selectLiteral $term
		    set needSelect 1

		}
		VARIABLE {
		    set varName [lindex $term 1]
		    lappend selectLiteral {VARIABLE _}
		    if {$varName eq {_}} {
			set needProject 1
 		    } else {
................................................................................
			    lappend renamedFrom $col
			    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]
	    lappend intcode [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]
................................................................................
	    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]
	    lappend intcode [list $operation $resultRelation \
				 $dataSoFar $dataThisOp]
	}
	return [list $resultRelation $resultColumns]
    }

    method translateRuleHead {db literal sourceRelation sourceColumns} {
	set predicate [lindex $literal 1]
	db relationMustExist $predicate
................................................................................
	    if {[dict exists $destColumn $col]} {
		lappend projectColumns $col
	    } else {
		set needProject 1
	    }
	}
	if {$needProject} {

	    lappend intcode [list RELATION $projector $projectColumns]
	    lappend intcode [list PROJECT $projector $sourceRelation]
	    set renameSource $projector
	} else {
	    set renameSource $sourceRelation
	}

	# Rename columns from literal to destination.
	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 joinSource $renamed
................................................................................

	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]
	    lappend intcode [list JOIN $joined $joinSource $constant]
	    set joinSource $joined
	}

	# Join with any don't-cares

	if {[llength $dontCareColumns] > 0} {
	    set dontCareRelation [my gensym #T]

	    lappend intcode [list RELATION $dontCareRelation $dontCareColumns]
	    lappend intcode [list SET $dontCareRelation _]
	    lappend joinColumns {*}$dontCareColumns
	    set joined [my gensym #T]

	    lappend intcode [list RELATION $joined $joinColumns]
	    lappend intcode [list JOIN $joined $joinSource $dontCareRelation]
	    set joinSource $joined

	}

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












































































































    }

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

    method getRules {} {
................................................................................
	}
	yield $component

    }
    return
}

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

    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]
	
	# Extract the facts, rules, and edges joining the rules from the parse

	set facts [$program getFacts]
	set rules [$program getRules]
	set outedges [$program getEdges]

	
	set plan [$program planExecution]

	# TODO - need to clear executionPlan?
	set result [$program translateExecutionPlan $db $plan]


	# TODO - This sequence needs refactoring



    } finally {

	$program destroy

    }
    return $result
................................................................................
source [file join [file dirname [info script]] tclbdd.tcl]
load [file join $buildDir libtclbdd0.1.so]
source [file join [file dirname [info script]] tclfddd.tcl]
source [file join [file dirname [info script]] .. examples loadProgram.tcl]
source [file join [file dirname [info script]] .. examples program1.tcl]

set vars [analyzeProgram $program db]


db relation seq st st2
db relation writes st v
db relation flowspast v st st2
db relation reaches v st st2
db relation uninitRead st v
db relation deadWrite st v

set i 0
foreach step [bdd::datalog::compileProgram db {
 
    % A false entry node (node 0) sets every variable and flows
    % to node 1. If any of its variables are reachable, those are
    % variables possibly used uninitialized in the program.

    writes($startNode, _).
    writes(st,v) :- writes0(st,v).
    seq($startNode, 1).
    seq(st,st2) :- seq0(st,st2).

    % flowspast(v,st,st2) means that control passes from the exit of st
    % to the entry of st2 without altering the value of v

    flowspast(_, st, st2) :- seq(st, st2).
    flowspast(v, st, st2) :- flowspast(v, st, st3),
                             !writes(st3, v),
                             flowspast(v, st3, st2).

    % reaches(v,st,st2) means that st assigns a value to v, which
    % reaches st2, which reads the value of v : that is, st is a
    % reaching definition for the use of v at st2.

    reaches(v, st, st2) :- writes(st, v), flowspast(v, st, st2), reads(st2, v).

    % A variable read that is reachable from the entry is a read of a
    % possibly uninitialized variable

    uninitRead(st, v) :- reaches(v, $startNode, st).

    % The following statement is nonsense, but tests a constant in the head.

    uninitRead(st, $ENV) :- reads(st, $ENV).

    % A variable write that reaches nowhere else is dead code

    deadWrite(st, v) :- writes(st, v), !reaches(v, st, _).

    % Also do the bddbddb example. Only 1 stratum, but 2 loops in the larger SCC


    % vP(v, h) :- vP0(v,h).
    % vP(v1,h) :- assign(v1,v2), vP(v2,h).
    % hP(h1,f,h2) :- store(v1,f,v2), vP(v1,h1), vP(v2,h2).
    % vP(v2,h2) :- load(v1,f,v2), vP(v1,h1), hP(h1,f,h2).



    % Compile dead code query







    deadWrite(st, v)?


}] {
    puts "$i: $step"















    incr i
}







>
|







 







|
<












<










|







 







>
>
>
>
>
>







 







>
>
>







 







|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







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







 







|







 







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










|












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

<
>

>
>
>
>










>
>
>
>
>
>

>





|











>
>
>






>
>
>
>
>
>





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


>
>
>
>






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

<
<
>


>
>
>
>

>
>


>
>

>
>

>
>




|
>
>



<







 







|
>
>







 







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







 







>







 







>









>
|
|







 







|
|
|







 







>
|
|







>







 







>
|
|







>
|
|


>
|
|







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







 







|







 







>



>



<
|

>
|
>
>







 







>







|
|
|





|

|






|
|
|










|
<
<
<
<





<
>

|
|
|
|
>
>

<
>
>
>
>
>
>
|
<
>

<
<
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

|
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
...
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
...
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
...
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
...
615
616
617
618
619
620
621
622






















623
624
625
626
627
628
629
...
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
...
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
...
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
...
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
....
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
....
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
....
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
....
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
....
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
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
....
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
....
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
....
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
1728
1729
1730
1731
1732

1733
1734
1735
1736
1737
1738
1739

1740
1741


1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
package require coroutine::iterator 1.0
package require grammar::aycock 1.0

namespace import coroutine::corovar::corovar

namespace eval bdd {
    namespace eval datalog {
	variable gensym 0
	namespace export compileProgram
    }
}

# bdd::datalog::lex --
#
#	Lexical analysis for the Datalog compiler.
#
................................................................................
    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 {}

    }

    # gensym -
    #
    #	Generate a unique symbol
    #
    # Results:
    #	Returns a generated symbol

    method gensym {{prefix G}} {
	return ${prefix}[incr ::bdd::datalog::gensym]
    }

    # assertRule -
    #
    #	Semantic action called from the parser when a rule is being asserted
    #
    # Parameters:
................................................................................

	# Iterate through the components, in dependency order, and
	# plan their execution individually.
	
	foreach component [lreverse $components] {
	    my planExecutionForComponent $component
	}

	# Tack on the query at the end

	if {[info exists query]} {
	    lappend executionPlan [list QUERY $query]
	}

	return $executionPlan

    }

    # Method: planExecutionForComponent
    #
................................................................................
		    }
		    1 {
			lappend loops $rule
		    }
		    0 {
			lappend executionPlan [list RULE $rule]
		    }
		    default {
			error "in planExecutionForComponent: can't happen"
		    }
		}
	    }
	}
	if {[llength $loops] != 0} {
	    lappend executionPlan [my planIteration $component $loops]
	}
    }
................................................................................
    method planIteration {component loops} {
	# As a heuristic, iterate over the predicate whose in-degree
	# most exceeds its out-degree. This is the predicate whose deletion
	# will remove the most edges from the dependency graph

	# Score the predicates according to the degrees of the dependency
	# graph.
	set delta [my rankComponentMembers $component $loops]























	# Find the predicate with the high score
	set maxDelta -Inf
	dict for {pred d} $delta {
	    if {$d > $maxDelta} {
		set maxDelta $d
		set toRemove $pred
................................................................................
	} finally {
	    $loopBody destroy
	}

	return [list LOOP $toRemove $bodyCode]
		    
    }

    # Method: rankComponentMemebers
    #
    #	Ranks members of a connected component in the predicate dependency
    #   graph for selection of loop headers.
    #
    # Parameters:
    #	components - Set of predicates in the connected component
    #	loops - Set of rules in the connected component that must be iterated.
    #
    # Results:
    #	Returns a dictionary whose keys are predicates and whose values are
    #	scores. The high-scoring predicate is the one that will be removed.
    #
    # The heuristic in play is from TODO: [citation needed]. It is to
    # compare the in-degree and out-degree of the predicate in the
    # dependency graph. The one with the highest (in-out) is the one
    # that will remove the most edges from the component if the
    # loop is broken there, and hence is likely to simplify the graph.
    # (The paper quantifies how close the result is to optimum.)

    method rankComponentMembers {component loops} {
	set delta {}
	foreach rule $loops {
	    set lhPredicate [lindex $rule 0 1]
	    foreach subgoal [lrange $rule 1 end] {
		switch -exact -- [lindex $subgoal 0] {
		    EQUALITY {	# does not introduce a dependency
			continue
		    }
		    NOT {
			set rhPredicate [lindex $subgoal 1 1]
		    }
		    LITERAL {
			set rhPredicate [lindex $subgoal 1]
		    }
		    default {
			error "in [info level 0]: can't happen."
		    }
		}
		if {[lsearch -exact $component $rhPredicate] >= 0} {
		    dict incr delta $lhPredicate 1; # edge into lhPredicate
		    dict incr delta $rhPredicate -1; # edge out of rhPredicate
		}
	    }
	}
	return $delta
    }
    

    # Method: ruleDependsOn
    #
    #	Tests if a rule depends on one or more of a set of predicates.
    #
    # Parameters:
    #	rule - Parse tree of the rule
................................................................................
    #	Returns 2 if the rule depends on one of the predicates in negated
    #   form, 1, if the rule depends on one of the predicates only in
    #   non-negated form, 0 if the rule has no dependency on the predicates

    method subgoalDependsOn {subgoal predicates} {
	switch -exact -- [lindex $subgoal 0] {
	    EQUALITY {
		return 0
	    }
	    NOT {
		if {[my subgoalDependsOn [lindex $subgoal 1] $predicates]} {
		    return 2
		} else {
		    return 0
		}
................................................................................
		} else {
		    return 0
		}
	    }
	}
    }

    # 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"
	    }
	}

	# Examine the terms of the literal, and extract the list of
	# columns for which specific vales have been supplied, and the
	# list of columns that have 'don't care' values: unbound variables
	# or _.

	set probeColumns {}
	set probeValues {}
	set dontCareColumns {}
	foreach term [lrange $fact 2 end] col $cols {
	    switch -exact [lindex $term 0] {
		CONSTANT {
		    lappend probeColumns $col
		    lappend probeValues [lindex $term 1]
		}
		VARIABLE {
		    if {[lindex $term 1] ne {_}} {
			set ppfact [bdd::datalog::prettyprint-literal $fact]
			puts stderr "warning: unused variable [lindex $term 1]\
                                     in fact $ppfact."
		    }
		    lappend dontCareColumns $col
		}
	    }
	}

	# Complain if no variables in the literal are bound.

	if {$probeColumns eq {}} {
	    set ppfact [bdd::datalog::prettyprint-literal $fact]
	    puts stderr "warning: fact $ppfact. asserts the universal set"
	    lappend intcode \
		[list SET $predicate _]
	} else {

	    # If there are 'don't cares', then make a relation for the
	    # bound values, a universal relation for the 'don't cares',
	    # join the two, and then union the result into the relation
	    # under construction.

	    if {$dontCareColumns ne {}} {
		set probeRelation [my gensym #T]
		set dontCareRelation [my gensym #T]
		set joinedRelation [my gensym #T]
		lappend intcode \
		    [list RELATION $probeRelation $probeColumns] \

		    [list LOAD $probeRelation $probeValues] \

		    [list RELATION $dontCareRelation $dontCareColumns] \

		    [list SET $dontCareRelation _] \

		    [list RELATION $joinedRelation $cols] \

		    [list JOIN $joinedRelation \
			 $probeRelation $dontCareRelation] \

		    [list UNION $predicate $predicate $joinedRelation]
	    } else {

		# If there are no 'don't cares', then load the literal
		# directly into the relation under construction.

		lappend intcode \
		    [list LOAD $predicate $probeValues]
	    }
	}
    }

    # 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]

	# Mark the top of the loop
	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 translateLiteral $db \
			 [lindex $subgoal 1] $dataSoFar $columnsSoFar] \
		    subgoalRelation subgoalColumns
		tailcall my translateSubgoalEnd $db ANTIJOIN \
		    $dataSoFar $columnsSoFar $subgoalRelation $subgoalColumns
	    }
	    EQUALITY {
		tailcall my translateEquality $db \
		    [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 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 EQUALITY $equality $col1 $col2]
	if {$dataSoFar 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]
................................................................................
	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 renamedFrom $col
			    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]
................................................................................
	    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
................................................................................
	    if {[dict exists $destColumn $col]} {
		lappend projectColumns $col
	    } else {
		set needProject 1
	    }
	}
	if {$needProject} {
	    lappend intcode \
		[list RELATION $projector $projectColumns] \
		[list PROJECT $projector $sourceRelation]
	    set renameSource $projector
	} else {
	    set renameSource $sourceRelation
	}

	# Rename columns from literal to destination.
	if {[llength $renamedFrom] > 0} {
	    set renamed [my gensym \#T]
	    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 joinSource $renamed
................................................................................

	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
	}

	# Join with any don't-cares

	if {[llength $dontCareColumns] > 0} {
	    set dontCareRelation [my gensym #T]
	    lappend intcode \
		[list RELATION $dontCareRelation $dontCareColumns] \
		[list SET $dontCareRelation _]
	    lappend joinColumns {*}$dontCareColumns
	    set joined [my gensym #T]
	    lappend intcode \
		[list RELATION $joined $joinColumns] \
		[list JOIN $joined $joinSource $dontCareRelation]
	    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 {    }

	#append body $ind {puts {Start evaluation!}} \n
	foreach instr $icode {
	    # append body $ind [list puts $instr] \n
	    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
		}
		
		ANTIJOIN {
		    append body $ind \
			[$db antijoin {*}[lrange $instr 1 end]] \n
		}
		BEGINLOOP {
		    append body $ind "while 1 \{\n"
		    set ind "$ind    "
		}
		ENDLOOP {
		    set command [$db === [lindex $instr 1] [lindex $instr 2]]
		    append body \
			$ind if { } \{ \[ $command \] \} { } break \n
		    set ind [string replace $ind end-3 end]
		    append body $ind "\}" \n
		}
		EQUALITY {
		    append body $ind \
			[$db equate {*}[lrange $instr 1 end]] \n
		}
		JOIN {
		    append body $ind \
			[$db join {*}[lrange $instr 1 end]] \n
		}
		LOAD {
		    # append body $ind # $instr \n
		    set relation [lindex $instr 1]
		    if {![dict exists $loaders $relation]} {
			dict set loaders $relation [$db loader $relation]
		    }
		    append body $ind \
			[dict get $loaders $relation]
		    foreach val [lindex $instr 2] {
			switch -exact -- [lindex $val 0] {
			    INTEGER {
				append body { } [lindex $val 1]
			    }
			    TCLVAR {
				append body { } \$ [lindex $val 1]
			    }
			    default {
				error "in generateCode: can't happen"
			    }
			}
		    }
		    append body \n
		}
		NEGATE {
		    append body $ind \
			[$db negate {*}[lrange $instr 1 end]] \n
		}
		PROJECT {
		    append body $ind \
			[$db project {*}[lrange $instr 1 end]] \n
		}
		RENAME {
		    append body $ind \
			[$db replace {*}[lrange $instr 1 end]] \n
		}
		SET {
		    append body $ind \
			[$db set {*}[lrange $instr 1 end]] \n
		}
		UNION {
		    append body $ind \
			[$db union {*}[lrange $instr 1 end]] \n
		}

		RESULT {
		    if {[llength $args] != 2} {
			error "wrong # args"; # TODO - better reporting
		    }
		    append body \
			[list $db enumerate [lindex $args 0] \
			     [lindex $instr 1] \
			     [lindex $args 1]] \n
		}

		default {
		    error "in generateCode: can't happen"
		}
	    }

	}
	return $prologue$body$epilogue

    }

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

    method getRules {} {
................................................................................
	}
	yield $component

    }
    return
}

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

    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]
	
	# Extract the facts, rules, and edges joining the rules from the parse
	if 0 {
	    set facts [$program getFacts]
	    set rules [$program getRules]
	    set outedges [$program getEdges]
	}
	
	set plan [$program planExecution]


	set intcode [$program translateExecutionPlan $db $plan]

	# TODO: Here is where optimization should happen. And optimization
	#       can be helped with Datalog?

	set result [$program generateCode $db $intcode {*}$args]

    } finally {

	$program destroy

    }
    return $result
................................................................................
source [file join [file dirname [info script]] tclbdd.tcl]
load [file join $buildDir libtclbdd0.1.so]
source [file join [file dirname [info script]] tclfddd.tcl]
source [file join [file dirname [info script]] .. examples loadProgram.tcl]
source [file join [file dirname [info script]] .. examples program1.tcl]

set vars [analyzeProgram $program db]
set vnames [dict keys $vars]

db relation seq st st2
db relation writes st v
db relation flowspast v st st2
db relation reaches v st st2
db relation uninitRead st v
db relation deadWrite st v
# db relation induction v st

proc reaching_defs {} [bdd::datalog::compileProgram db {
 
    % A false entry node (node 0) sets every variable and flows
    % to node 1. If any of its variables are reachable, those are
    % variables possibly used uninitialized in the program.

    writes(0, _).
    writes(st,v) :- writes0(st,v).
    seq(0, 1).
    seq(st,st2) :- seq0(st,st2).

    % flowspast(v,st,st2) means that control passes from the exit of st
    % to the entry of st2 without altering the value of v

    flowspast(_, st, st2) :- seq(st, st2).
    flowspast(v, st3, st2) :- flowspast(v, st3, st),
                             !writes(st, v),
                             flowspast(v, st, st2).

    % reaches(v,st,st2) means that st assigns a value to v, which
    % reaches st2, which reads the value of v : that is, st is a
    % reaching definition for the use of v at st2.

    reaches(v, st, st2) :- writes(st, v), flowspast(v, st, st2), reads(st2, v).

    % A variable read that is reachable from the entry is a read of a
    % possibly uninitialized variable

    uninitRead(st, v) :- reaches(v, 0, st).





    % A variable write that reaches nowhere else is dead code

    deadWrite(st, v) :- writes(st, v), !reaches(v, st, _).


}]

# Report which variable definitions reach statement $i
proc query1 {i} [bdd::datalog::compileProgram db {
    reaches(v, st, $i)?
} d {
    lappend ::flowsto [lindex $::vnames [dict get $d v]] [dict get $d st]
}]


# Report which variable uses flow from statement $i
proc query2 {i} [bdd::datalog::compileProgram db {
    reaches(v, $i, st)?
} d {
    lappend ::flowsfrom [lindex $::vnames [dict get $d v]] [dict get $d st]
}]
    

puts [info body reaching_defs]



reaching_defs
puts [format {%-16s %2s  %-32s %-16s} PRODUCERS {} INSTRUCTIONS CONSUMERS]
set i 0
foreach stmt $program {
    set flowsto {}
    query1 $i
    set flowsfrom {}
    query2 $i
    puts [format "%-16s %2d: %-32s %-16s" \
	      [lsort -stride 2 -index 0 -ascii \
		   [lsort -stride 2 -index 1 -integer $flowsto]] \
	      $i \
	      $stmt \
	      [lsort -stride 2 -index 0 -ascii \
		   [lsort -stride 2 -index 1 -integer $flowsfrom]]]
    incr i
}

Changes to library/tclfddd.tcl.

726
727
728
729
730
731
732
































733
734
735
736
737
738
739
		lappend result $p [dict get $cmdpos $column] $bit
	    }
	    incr p
	}
	set cmd [list [namespace which sys] load $relation $result]
	return $cmd
    }

































    # Method: profile
    #
    #	Determines the number of BDD beads in use for each variable.
    #
    # Parameters:
    #	relation - Relation to profile







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







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
		lappend result $p [dict get $cmdpos $column] $bit
	    }
	    incr p
	}
	set cmd [list [namespace which sys] load $relation $result]
	return $cmd
    }

    # Method: negate
    #
    #	Generates code to compute the complement of a relation. All
    #	tuples over the relation's domain will be in the output relation
    #	if they are not in the input
    #
    # Usage:
    #	$db union $dest $source
    #
    # Parameters:
    #	dest    - Name of the relation that will receive the complement
    #   source1 - Name of the input relation
    #
    # Results:
    #	Returns a burst of code that computes the complement of the
    #   relation
    #
    # Both relations must contain the same set of columns.
    #
    # This method does not compute the complement; it returns a fragment
    # of code that computes it.
    #
    # The time taken to compute the complement is linear in the 
    # size of the BDD.

    method negate {dest source} {
	my relationMustExist $dest
	my relationMustExist $source
	my ColumnsMustBeSame $dest $source
	return [list [namespace which sys] ~ $dest $source]
    }

    # Method: profile
    #
    #	Determines the number of BDD beads in use for each variable.
    #
    # Parameters:
    #	relation - Relation to profile