tclbdd

Check-in [53105db3b1]
Login

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

Overview
Comment:Fix several packaging errors. Refactor some of the FDDD type checking. Continue Datalog development; including replacing 'condition' with 'subgoal' in commentary.
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:53105db3b1dc318101bfc69ab8f6ded6d2028647
User & Date: kbk 2014-01-03 22:09:58
Context
2014-01-06
12:17
More compiler development - part of the procedures to translate Datalog to relational algebra. check-in: 7636e8a432 user: kbk tags: trunk
2014-01-03
22:09
Fix several packaging errors. Refactor some of the FDDD type checking. Continue Datalog development; including replacing 'condition' with 'subgoal' in commentary. check-in: 53105db3b1 user: kbk tags: trunk
2014-01-01
05:59
Major refactor - stratification simplified by the fact that scc generates components in postorder. Finished execution planning. check-in: e6862c5093 user: kbk tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to examples/reach.tcl.

31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# reach(v,st,st2) means: "The use of variable v at instruction st2
# might see the assignment to variable v at instruction st1"

# Reachability: relation definitions that might be generated by a Datalog
# compiler.

db relation t10 v;		# The universal set of variables
db relation t11 v st3;	# writes(v, st3)
db relation t12 v st st3;	# flowspast(v, st, st3)
db relation t13 v st st3;	# flowspast(v, st, st3),!writes(st3,v)
db relation t14 v st2 st3;	# flowspast(v, st3, st2)
db relation t15 v st st2 st3;	# flowspast(v, st, st3),
				# !writes(st3,v),
				# flowspast(v, st3, st2)
db relation t16 v st st2;	# project{v,st,st2}(t15)







|







31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# reach(v,st,st2) means: "The use of variable v at instruction st2
# might see the assignment to variable v at instruction st1"

# Reachability: relation definitions that might be generated by a Datalog
# compiler.

db relation t10 v;		# The universal set of variables
db relation t11 v st3;		# writes(v, st3)
db relation t12 v st st3;	# flowspast(v, st, st3)
db relation t13 v st st3;	# flowspast(v, st, st3),!writes(st3,v)
db relation t14 v st2 st3;	# flowspast(v, st3, st2)
db relation t15 v st st2 st3;	# flowspast(v, st, st3),
				# !writes(st3,v),
				# flowspast(v, st3, st2)
db relation t16 v st st2;	# project{v,st,st2}(t15)

Changes to library/datalog.tcl.

8
9
10
11
12
13
14
15

16
17
18
19
20


21
22
23
24
25
26
27
...
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
...
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
...
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
...
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
...
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
...
493
494
495
496
497
498
499


500
501
502
503
504
505
506
...
509
510
511
512
513
514
515


516
517
518
519
520
521
522
523
524
525
526
527




528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
...
568
569
570
571
572
573
574
575
576
577
578
579
580
581


582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604


605
606
607
608
609
610
611
612

613
614


615
616
617
618
619
620
621



622
623
624
625

626
627
628
629
630
631
632
633



634
635
636
637
638
639
640
...
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
...
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
...
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
....
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
#------------------------------------------------------------------------------

source [file dirname [info script]]/coroutine_iterator.tcl; # TEMP
source [file dirname [info script]]/coroutine_corovar.tcl; # TEMP



package require Tcl 8.6
package require coroutine::corovar 1.0
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
    }
................................................................................
	linsert [lindex $_ 2] 0 [lindex $_ 0]
    }

    # The head is a single, non-negated literal

    head	::=	pliteral		{}

    # The body is a set of comma-separated, possibly negated conditions

    body	::=	condition
    {
	set _
    }
    body	::=	body , condition
    {
	linsert [lindex $_ 0] end [lindex $_ 2]
    }

    # A condition is either a literal, or else an equality constraint

    condition	::=	literal			{}
    condition	::=	equality		{}

    # A literal is a predicate symbol optionally followed by a list of terms

    literal	::=	pliteral		{}
    literal	::=	! pliteral
    {
	list NOT [lindex $_ 1]
................................................................................
#
# Parameters:
#	rule - Rule in the parse tree

proc bdd::datalog::prettyprint-rule {rule} {
    set s [prettyprint-literal [lindex $rule 0]]
    set sep :-
    foreach condition [lrange $rule 1 end] {
	append s $sep [prettyprint-condition $condition]
	set sep ,
    }
    return $s
}
proc bdd::datalog::prettyprint-condition {condition} {
    switch -exact [lindex $condition 0] {
	EQUALITY {
	    set s [prettyprint-variable [lindex $condition 1]]
	    append s = [prettyprint-variable [lindex $condition 2]]
	}
	NOT {
	    set s !
	    append s [prettyprint-literal [lindex $condition 1]]
	}
	LITERAL {
	    set s [prettyprint-literal $condition]
	}
	default {
	    error "Expected condition and got $condition"
	}
    }
    return $s
}
proc bdd::datalog::prettyprint-literal {literal} {
    # FIXME: May need to quote s (and backslashify its content)
    set s [lindex $literal 1]
................................................................................
    #         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
    #                 conditions on the right hand side of the dependent rule.
    # 'query' is a literal giving the query at the end of the program
    #         (if any)







    variable \
	rules \
	rulesForPredicate \
	factsForPredicate \
	outEdgesForPredicate \
	query


    # Constructor -
    #
    #	Creates an empty program.

    constructor {} {
	set rules {}
	set rulesForPredicate {}
	set factsForPredicate {}
	set outEdgesForPredicate {}

    }

    # assertRule -
    #
    #	Semantic action called from the parser when a rule is being asserted
    #
    # Parameters:
................................................................................
	# the predicate on the left-hand side

	set ruleIndex [llength $rules]
	set lhPredicate [lindex $rule 0 1]
	lappend rules $rule
	dict lappend rulesForPredicate $lhPredicate $ruleIndex

	# Examine the conditions on the right hand side

	set i 0
	foreach condition [lrange $rule 1 end] {
	    incr i
	    switch -exact -- [lindex $condition 0] {
		EQUALITY { 	# does not create a dependency
		    continue
		}
		LITERAL {
		    set dependency [lindex $condition 1]
		    set not 0
		}
		NOT {
		    set dependency [lindex $condition 1 1]
		    set not 1
		}
		default {
		    error "[info level 0] - can't happen"
		}
	    }

................................................................................
    #
    #	Develops an execution plan for the program
    #
    # Parameters:
    #	None.
    #
    # Results:
    #	TBD
    #
    # Errors:
    #	Throws an error if the program is not stratifiable.
    #
    # Notes:
    #	The general approach is that the predicate dependency graph is
    #   broken up into strongly connected components. For each component,
................................................................................
    #	it contains at least one loop. A loop header is identified
    #	heuristically, and an iteration is constructed to compute the
    #	predicate that corresponds to it. That predicate is removed from
    #	the component, and whatever remains of the component is extracted
    #	as a new program and compiled to become the loop body.

    method planExecution {} {



	# Partition the program into strongly connected components.

	set components {}
	set i 0
	bdd::datalog::scc c $outEdgesForPredicate {
	    lappend components $c
................................................................................
	# Iterate through the components, in dependency order, and
	# plan their execution individually.
	
	foreach component [lreverse $components] {
	    my planExecutionForComponent $component
	}



    }

    # Method: planExecutionForComponent
    #
    #	Plans the execution for one strongly-connected component of a
    #	program.
    #
    # Parameters:
    #	component - List of predicates belonging to the component
    #
    # Results:
    #	TBD




    #
    # Errors:
    #	Throws an error if the program is not stratifiable.
    
    method planExecutionForComponent {component} {

	set loops {}
	foreach predicate $component {
	    foreach fact [my getFactsForPredicate $predicate] {
		# TODO - Implement this
		puts "Compile fact: [::bdd::datalog::prettyprint-literal $fact]"
	    }
	    foreach ruleNo [my getRulesForPredicate $predicate] {
		set rule [my getRule $ruleNo]
		switch -exact -- [my ruleDependsOn $rule $component] {
		    2 {
			error "The program is not stratifiable.\
                               Check the rule\n\
                               [::bdd::datalog::prettyprint-rule $rule]"
		    }
		    1 {
			lappend loops $rule
		    }
		    0 {
			# TODO - Implement this
			puts "Compile rule:\
                              [::bdd::datalog::prettyprint-rule $rule]"
		    }
		}
	    }
	}
	if {[llength $loops] != 0} {
	    my planIteration $component $loops
	}
    }

    # Method: planIteration
    #
    #	Plans an iteration pattern once a recursive component has been
    #   identified.
................................................................................
    #
    # Parameters:
    #   component - Set of predicates that need to be resolved.
    #	loops - Set of rules that require iteration. All irrelevant rules
    #           have been removed.
    #
    # Results:
    #	TBD

    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



	foreach rule $loops {
	    set lhPredicate [lindex $rule 0 1]
	    foreach condition [lrange $rule 1 end] {
		switch -exact -- [lindex $condition 0] {
		    EQUALITY {	# does not introduce a dependency
			continue
		    }
		    NOT {
			set rhPredicate [lindex $condition 1 1]
		    }
		    LITERAL {
			set rhPredicate [lindex $condition 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
		}
	    }
	}


	set maxDelta -Inf
	dict for {pred d} $delta {
	    if {$d > $maxDelta} {
		set maxDelta $d
		set toRemove $pred
	    }
	}
	# TODO - Implement this

	puts "Generate a loop header for testing convergence of $toRemove"
	try {


	    set loopBody [::bdd::datalog::program new]
	    foreach rule $loops {
		if {[lindex $rule 0 1] ne $toRemove} {
		    $loopBody assertRule $rule
		}
	    }
	    $loopBody planExecution



	    foreach rule $loops {
		if {[lindex $rule 0 1] eq $toRemove} {
		    puts "Compile rule:\
                              [::bdd::datalog::prettyprint-rule $rule]"

		}
	    }
	    # TODO - Implement this
	    puts "Close the loop on $toRemove"
		    
	} finally {
	    $loopBody destroy
	}



    }

    # Method: ruleDependsOn
    #
    #	Tests if a rule depends on one or more of a set of predicates.
    #
    # Parameters:
................................................................................
    # Results:
    #	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 ruleDependsOn {rule predicates} {
	set result 0
	foreach condition [lrange $rule 1 end] {
	    if {[set r [my conditionDependsOn $condition $predicates]]
		> $result} {
		set result $r
	    }
	}
	return $result
    }

    # Method: conditionDependsOn
    #
    #	Tests if a condition depends on one or more of a set of predicates.
    #
    # Parameters:
    #	rule - Parse tree of the condition
    #	predicates - List of predicate names
    #
    # Results:
    #	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 conditionDependsOn {condition predicates} {
	switch -exact -- [lindex $condition 0] {
	    EQUALITY {
		return false
	    }
	    NOT {
		if {[my conditionDependsOn [lindex $condition 1] $predicates]} {
		    return 2
		} else {
		    return 0
		}
	    }
	    LITERAL {
		if {[lsearch -exact $predicates [lindex $condition 1]] >= 0} {
		    return 1
		} else {
		    return 0
		}
	    }
	}
    }
................................................................................
	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]
	
	$program planExecution

    } finally {

	$program destroy

    }
    return

}

package provide tclbdd::datalog 0.1

##############################################################################

................................................................................
# PROGRAM statements
# statement:
#   ASSERTION clause
#   RETRACTION clause
#   QUERY literal
# clause:
#   FACT literal
#   RULE Name conditions
# condition:
#   literal
#   EQUALITY variable variable
# literal:
#   NOT literal
#   LITERAL Name terms
# term:
#   CONSTANT const
#   variable
# variable:
#   VARIABLE name

}























# Try compiling a program

bdd::datalog::compileProgram {
 
    % 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(v, st, st2) :- seq(st, st2).
    flowspast(v, st, st2) :- flowspast(v, st, st3),
................................................................................
    % 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, _).

    % 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).

}







|
>





>
>







 







|

|



|




|

|
|







 







|
|




|
|

|
|



|


|


|







 







|


>
>
>
>
>
>






|
>










>







 







|


|

|




|



|







 







|







 







>
>







 







>
>











|
>
>
>
>









|
<













|
<
<





|







 







|






>
>


|
|




|


|











>
>







<
>
|

>
>






|
>
>
>


<
<
>


<
<
<



>
>
>







 







|
|







|

|


|







|
|




|






|







 







|






|







 







|
|













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


|





|

|







 







|












|
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
...
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
...
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
...
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
...
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
...
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
...
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
...
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556

557
558
559
560
561
562
563
564
565
566
567
568
569
570


571
572
573
574
575
576
577
578
579
580
581
582
583
...
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631

632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648


649
650
651



652
653
654
655
656
657
658
659
660
661
662
663
664
...
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
...
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
...
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
....
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
#------------------------------------------------------------------------------

source [file dirname [info script]]/coroutine_iterator.tcl; # TEMP
source [file dirname [info script]]/coroutine_corovar.tcl; # TEMP
source [file dirname [info script]]/tclbdd.tcl;		   # TEMP
source [file dirname [info script]]/tclfddd.tcl;	   # TEMP

package require Tcl 8.6
package require coroutine::corovar 1.0
package require coroutine::iterator 1.0
package require grammar::aycock 1.0
package require tclbdd 0.1
package require tclbdd::fddd 0.1

namespace import coroutine::corovar::corovar

namespace eval bdd {
    namespace eval datalog {
	namespace export lex parse compile
    }
................................................................................
	linsert [lindex $_ 2] 0 [lindex $_ 0]
    }

    # The head is a single, non-negated literal

    head	::=	pliteral		{}

    # The body is a set of comma-separated, possibly negated subgoals

    body	::=	subgoal
    {
	set _
    }
    body	::=	body , subgoal
    {
	linsert [lindex $_ 0] end [lindex $_ 2]
    }

    # A subgoal is either a literal, or else an equality constraint

    subgoal	::=	literal			{}
    subgoal	::=	equality		{}

    # A literal is a predicate symbol optionally followed by a list of terms

    literal	::=	pliteral		{}
    literal	::=	! pliteral
    {
	list NOT [lindex $_ 1]
................................................................................
#
# 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]]
	}
	NOT {
	    set s !
	    append s [prettyprint-literal [lindex $subgoal 1]]
	}
	LITERAL {
	    set s [prettyprint-literal $subgoal]
	}
	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]
................................................................................
    #         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.

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

    # Constructor -
    #
    #	Creates an empty program.

    constructor {} {
	set rules {}
	set rulesForPredicate {}
	set factsForPredicate {}
	set outEdgesForPredicate {}
	set executionPlan {}
    }

    # assertRule -
    #
    #	Semantic action called from the parser when a rule is being asserted
    #
    # Parameters:
................................................................................
	# the predicate on the left-hand side

	set ruleIndex [llength $rules]
	set lhPredicate [lindex $rule 0 1]
	lappend rules $rule
	dict lappend rulesForPredicate $lhPredicate $ruleIndex

	# Examine the subgoals on the right hand side

	set i 0
	foreach subgoal [lrange $rule 1 end] {
	    incr i
	    switch -exact -- [lindex $subgoal 0] {
		EQUALITY { 	# does not create a dependency
		    continue
		}
		LITERAL {
		    set dependency [lindex $subgoal 1]
		    set not 0
		}
		NOT {
		    set dependency [lindex $subgoal 1 1]
		    set not 1
		}
		default {
		    error "[info level 0] - can't happen"
		}
	    }

................................................................................
    #
    #	Develops an execution plan for the program
    #
    # Parameters:
    #	None.
    #
    # Results:
    #	Returns the execution plan
    #
    # Errors:
    #	Throws an error if the program is not stratifiable.
    #
    # Notes:
    #	The general approach is that the predicate dependency graph is
    #   broken up into strongly connected components. For each component,
................................................................................
    #	it contains at least one loop. A loop header is identified
    #	heuristically, and an iteration is constructed to compute the
    #	predicate that corresponds to it. That predicate is removed from
    #	the component, and whatever remains of the component is extracted
    #	as a new program and compiled to become the loop body.

    method planExecution {} {

	set executionPlan {}

	# Partition the program into strongly connected components.

	set components {}
	set i 0
	bdd::datalog::scc c $outEdgesForPredicate {
	    lappend components $c
................................................................................
	# Iterate through the components, in dependency order, and
	# plan their execution individually.
	
	foreach component [lreverse $components] {
	    my planExecutionForComponent $component
	}

	return $executionPlan

    }

    # Method: planExecutionForComponent
    #
    #	Plans the execution for one strongly-connected component of a
    #	program.
    #
    # Parameters:
    #	component - List of predicates belonging to the component
    #
    # Results:
    #	None.
    #
    # Side effects:
    #	Appends the execution plan for the component to the plan
    #	under construction for the program.
    #
    # Errors:
    #	Throws an error if the program is not stratifiable.
    
    method planExecutionForComponent {component} {

	set loops {}
	foreach predicate $component {
	    foreach fact [my getFactsForPredicate $predicate] {
		lappend executionPlan [list FACT $fact]

	    }
	    foreach ruleNo [my getRulesForPredicate $predicate] {
		set rule [my getRule $ruleNo]
		switch -exact -- [my ruleDependsOn $rule $component] {
		    2 {
			error "The program is not stratifiable.\
                               Check the rule\n\
                               [::bdd::datalog::prettyprint-rule $rule]"
		    }
		    1 {
			lappend loops $rule
		    }
		    0 {
			lappend executionPlan [list RULE $rule]


		    }
		}
	    }
	}
	if {[llength $loops] != 0} {
	    lappend executionPlan [my planIteration $component $loops]
	}
    }

    # Method: planIteration
    #
    #	Plans an iteration pattern once a recursive component has been
    #   identified.
................................................................................
    #
    # Parameters:
    #   component - Set of predicates that need to be resolved.
    #	loops - Set of rules that require iteration. All irrelevant rules
    #           have been removed.
    #
    # Results:
    #	Returns the execution plan for the iteration

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


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

	    # Append the rules for deriving the current member at
	    # the bottom of the loop.
	    foreach rule $loops {
		if {[lindex $rule 0 1] eq $toRemove} {


		    lappend bodyCode [list RULE $rule]
		}
	    }



	} 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:
................................................................................
    # Results:
    #	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 ruleDependsOn {rule predicates} {
	set result 0
	foreach subgoal [lrange $rule 1 end] {
	    if {[set r [my subgoalDependsOn $subgoal $predicates]]
		> $result} {
		set result $r
	    }
	}
	return $result
    }

    # Method: subgoalDependsOn
    #
    #	Tests if a subgoal depends on one or more of a set of predicates.
    #
    # Parameters:
    #	rule - Parse tree of the subgoal
    #	predicates - List of predicate names
    #
    # Results:
    #	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
		}
	    }
	    LITERAL {
		if {[lsearch -exact $predicates [lindex $subgoal 1]] >= 0} {
		    return 1
		} else {
		    return 0
		}
	    }
	}
    }
................................................................................
	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 result [$program planExecution]

    } finally {

	$program destroy

    }
    return $result

}

package provide tclbdd::datalog 0.1

##############################################################################

................................................................................
# PROGRAM statements
# statement:
#   ASSERTION clause
#   RETRACTION clause
#   QUERY literal
# clause:
#   FACT literal
#   RULE Name subgoals
# subgoal:
#   literal
#   EQUALITY variable variable
# literal:
#   NOT literal
#   LITERAL Name terms
# term:
#   CONSTANT const
#   variable
# variable:
#   VARIABLE name

}

# TEMP printing stuff - needs to go somewhere...

proc bdd::datalog::prettyprint-plan {plan {indent 0}} {
    foreach step $plan {
	switch -exact [lindex $step 0] {
	    FACT {
		puts [format {%*sFACT %s.} $indent {} \
			  [prettyprint-literal [lindex $step 1]]]
	    }
	    LOOP {
		puts [format "%*sLOOP %s \{" $indent {} [lindex $step 1]]
		prettyprint-plan [lindex $step 2] [expr {$indent + 4}]
		puts [format "%*s\}" $indent {}]
	    }
	    RULE {
		puts [format {%*sRULE %s.} $indent {} \
			  [prettyprint-rule [lindex $step 1]]]
	    }
	}
    }
}

# Try compiling a program

bdd::datalog::prettyprint-plan [bdd::datalog::compileProgram {
 
    % 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(v, st, st2) :- seq(st, st2).
    flowspast(v, st, st2) :- flowspast(v, st, st3),
................................................................................
    % 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).

    % 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).

}]

Changes to library/tclbdd.tcl.

410
411
412
413
414
415
416


    addexp ::= primary {}

    primary ::= ( expression ) { lindex $_ 1 }
    primary ::= variable { list variable [lindex $_ 0] }
    primary ::= CONSTANT { list constant [lindex $_ 0] }

}]









>
>
410
411
412
413
414
415
416
417
418
    addexp ::= primary {}

    primary ::= ( expression ) { lindex $_ 1 }
    primary ::= variable { list variable [lindex $_ 0] }
    primary ::= CONSTANT { list constant [lindex $_ 0] }

}]

package provide tclbdd 0.1

Changes to library/tclfddd.tcl.

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
...
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
...
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
...
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
...
547
548
549
550
551
552
553
554


555
556
557
558
559


560
561
562
563
564


565
566
567
568
569
570
571
...
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
...
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
...
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
...
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
...
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
...
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
...
911
912
913
914
915
916
917

918
919
920
921
922
923
924
925
...
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
...
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
	    return -level 2 -code error \
		-errorcode [list FDDD DifferentColumns $rel1 $rel2] \
		"relations \"$rel1\" and \"$rel2\" have different columns"
	}
	return
    }

    # Private method: RelationMustExist
    #
    #	Makes sure that a given relation exists in the database
    #
    # Usage:
    #	my RelationMustExist $name
    #
    # Parameters:
    #	name - Name of a relation
    #
    # Results:
    #	Returns an empty result if the relation exists. Causes the caller
    #	to return an error if the relation is not found.

    method RelationMustExist {name} {
	if {![dict exists $m_relcolumns $name]} {
	    return -level 2 -code error \
		-errorcode [list FDDD RelationNotDefined $name] \
		"relation \"$name\" is not defined in this database"
	}
	return
    }

    # Private method: Varlist
    #	
    #	Enumerates the BDD variables that make up a relation.
    #
    # Usage:
    #	$db Varlist $relation
    #
................................................................................
    #
    # This method does not perform the test directly: it generates
    # code to perform the test.
    #
    # The test executes in constant time.

    method === {rel1 rel2} {
	my RelationMustExist $rel1
	my RelationMustExist $rel2
	my ColumnsMustBeSame $rel1 $rel2
	return [list [namespace which sys] === $rel1 $rel2]
    }
    export ===

    # Method: antijoin
    #
................................................................................
    # This method does not perform the copy directly: it generates
    # code to perform the copy.
    #
    # The antijoin executes in time proportional to the size of the
    # source1 BDD.

    method antijoin {dest source1 source2} {
	my RelationMustExist $dest
	my RelationMustExist $source1
	my RelationMustExist $source2

	# Determine the columns in the joined relations
	set destcolumns [dict get $m_relcolumns $source1]
	lappend destcolumns {*}[dict get $m_relcolumns $source2]
	set destcolumns [lsort -dictionary -unique $destcolumns]
	my ColumnsMustBe $dest $destcolumns

	# Make code to do the antijoin
	return [list [namespace which sys] > $dest $source1 $source2]
    }
























    # Method: columns
    #
    #	Enumerates all columns in the database

    #
    # Usage:
    #	$db columns
    #



    # Results:



    #	Returns a list of the column names that are known to the databsae.
    #
    # This method executes directly, rather than returning a code fragment

    method columns {} {

	return [dict keys $m_columns]




    }

    # Method: enumerate
    #
    #	Iterates over all the tuples in a relation
    #
    # Usage:
................................................................................
    # Any other nonstandard status code terminates the iteration.
    #
    # This method executes directly, rather than returning a code fragment

    method enumerate {dictvar relation script} {
	upvar 1 $dictvar valdict

	my RelationMustExist $relation

	# Iterate over the relation, getting SAT terms. Iterate over
	# the variable assignments that satisfy the terms.
	sys foreach_sat satterm $relation {
	    bdd::foreach_fullsat vars [my Varlist $relation] $satterm {

		# Iterate over the columns and populate the dictionary
................................................................................
    # The time taken to create the equality is highly variable. In the case
    # where the two columns' variables are interleaved, the time is linear
    # in the number of bits of the domains. In the case where they are
    # concatenated, both time and space are exponential in the number of
    # variables. Other orderings will give results between these two extremes.

    method equate {dest col1 col2} {
	my RelationMustExist $dest


	set destcolumns [dict get $m_relcolumns $dest]
	if {![dict exists $m_columns $col1] 
	    | [lsearch -exact $destcolumns $col1] == -1} {
	    return -code error -errorcode [list FDDD NoSuchColumn $col1] \
		"no such column: \"$col1\""


	}
	if {![dict exists $m_columns $col2]
	    | [lsearch -exact $destcolumns $col2] == -1} {
	    return -code error -errorcode [list FDDD NoSuchColumn $col2] \
		"no such column: \"$col2\""


	}
	set vars1 [dict get $m_columns $col1]
	set vars2 [dict get $m_columns $col2]
	if {[llength $vars1] != [llength $vars2]} {
	    return -code error \
		-errorcode [list FDDD EquateWrongDomains $col1 $col2] \
		"cannot equate domains \"$col1\" and \"$col2\":\
................................................................................
    # This method does not perform the copy directly: it generates
    # code to perform the copy.
    #
    # The join executes in time proportional to the size of the
    # source1 BDD.

    method join {dest source1 source2} {
	my RelationMustExist $dest
	my RelationMustExist $source1
	my RelationMustExist $source2

	# Determine the columns in the joined relations
	set destcolumns [dict get $m_relcolumns $source1]
	lappend destcolumns {*}[dict get $m_relcolumns $source2]
	set destcolumns [lsort -dictionary -unique $destcolumns]
	my ColumnsMustBe $dest $destcolumns

................................................................................
    #	Returns a command prefix for a command that will add a tuple
    #	to the given relation.
    #
    # To the prefix should be appended the values of the columns,
    # in dictonary order by the column names.

    method loader {relation} {
	my RelationMustExist $relation
	set i 0
	foreach column [dict get $m_relcolumns $relation] {
	    dict set cmdpos $column $i
	    incr i
	}
	set result {}
	set p 0
................................................................................
    # Results:
    #	Returns a list ordered by variable level giving the number of
    #	beads at each level
    #
    # This method executes directly, rather than returning a codeburst.

    method profile {relation} {
	my RelationMustExist $relation
	sys profile $relation
    }

    # Method: project
    #
    #	Uses existential quantification to project a relation onto
    #	a smaller domain.
................................................................................
    # code to perform the projection.
    #
    # The projection executes in time proportional to the size of the
    # source BDD.

    method project {dest source} {
	# columns to project away are determined by dest and source
	my RelationMustExist $dest
	my RelationMustExist $source
	set discards {}
	foreach col [dict get $m_relcolumns $dest] {
	    dict set want $col {}
	}
	foreach col [dict get $m_relcolumns $source] {
	    if {![dict exists $want $col]} {
		lappend discards {*}[dict get $m_columns $col]
................................................................................
    #	column... - Set of columns that the relation constrains
    #
    # Results:
    #	None.
    #
    # Side effects:
    #	The given relation is defined. Its content in the database
    #	is left undefined. It must either be loaded or populated by
    #	a rule such as 'join' or 'union' prior to being used.




    method relation {name args} {
	if {[dict exists $m_relcolumns $name]} {
	    return -code error \
		-errorcode [list FDDD RelationAlreadyDefined $name] \
		"relation \"$name\" is already defined in this database"
	}
	set havecol {}
	foreach col $args {

	    if {[dict exists $havecol $col]} {
		return -code error -errorcode [list FDDD DuplicateColumn $col] \
		    "column $col is duplicated in the column list"
	    }
	    if {![dict exists $m_columns $col]} {
		return -code error -errorcode [list FDDD NoSuchColumn $col] \
		    "no such column: \"$col\""
	    }
	    dict set $havecol $col {}
	}
	dict set m_relcolumns $name [lsort -dictionary $args]

	return $name
    }
























    # Method: replace
    #
    #	Generates code to reassign physical domains in a relation
    #
    # Usage:
    #	$db replace dest source ?outcol incol?...
................................................................................
    # the same order as those of the input columns (RECOMMENDED), it
    # is linear in the size of the input BDD. In the worst case of variable
    # reordering, it may be exponential in the size of the input BDD.
    # This will happen, for instance, if an equality over an interleaved
    # pair of columns is replaced with an equality over a concatenated pair.

    method replace {dest source args} {
	my RelationMustExist $dest
	my RelationMustExist $source
	set sourcecols {}
	foreach col [dict get $m_relcolumns $source] {
	    dict set sourcecols $col {}
	}
	set destcols {}
	foreach col [dict get $m_relcolumns $dest] {
	    dict set destcols $col {}
	}
	set colsAdded {}
	foreach {to from} $args {


	    if {[dict exists $colsAdded $to]} {
		return -code error \
		    -errorcode [list FDDD DuplicateReplaceOutput $to] \
		    "attempt to rename two input columns to \"$to\""
	    }
	    if {![dict exists $sourcecols $from]} {
		return -code error \
................................................................................
		    "replacement column \"$to\" is to narrow to hold values\
                     from column \"$from\""
	    }
	    lappend fromvars {*}$fv
	    lappend tovars {*}[lrange $tv 0 [expr {[llength $fv] - 1}]]
	}


	return [list [namespace which sys] replace $dest $fromvars $tovars $source]
    }

    # Method: set
    #
    #	Generates code to copy one relation to another
    #
    # Usage:
................................................................................
    #
    # This method does not perform the copy directly: it generates
    # code to perform the copy.
    #
    # The copy executes in constant time.

    method set {dest source} {
	my RelationMustExist $dest
	if {$source eq {}} {
	    set source 0
	} elseif {$source eq {_}} {
	    set source 1
	} else {
	    my RelationMustExist $source
	    my ColumnsMustBeSame $dest $source
	}
	return [list [namespace which sys] := $dest $source]
    }

    # Method: union
    #
................................................................................
    # This method does not compute the union; it returns a fragment
    # of code that computes it.
    #
    # The time taken to compute the union is linear in the sum of the
    # sizes of the two BDD's.

    method union {dest source1 source2} {
	my RelationMustExist $dest
	my RelationMustExist $source1
	my RelationMustExist $source2
	my ColumnsMustBeSame $dest $source1
	my ColumnsMustBeSame $dest $source2
	return [list [namespace which sys] | $dest $source1 $source2]
    }

if 0 {
    # deprecate this for now.
    method load {name list} {
	my RelationMustExist $name
	set nColumns [llength [dict get $m_relcolumns $name]]
	if {[llength $list] % $nColumns != 0} {
	    return -code error \
		-errorcode [list FDDD WrongListLength $nColumns] \
		"list must have a multiple of $nColumns values"
	}
	set reader [my loader $name]







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







|
|







 







|
|
|











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


|
>


|

>
>
>

>
>
>
|



|
>
|
>
>
>
>







 







|







 







|
>
>

<
|
|
<
>
>

<
|
|
<
>
>







 







|
|
|







 







|







 







|







 







|
|







 







|
<
>
>
>









>




<
<
<
<



>


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







 







|
|










>
>







 







>
|







 







|





|







 







|
|
|








|







311
312
313
314
315
316
317























318
319
320
321
322
323
324
...
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
...
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
...
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
...
559
560
561
562
563
564
565
566
567
568
569

570
571

572
573
574

575
576

577
578
579
580
581
582
583
584
585
...
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
...
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
...
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
...
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
...
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
...
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
...
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
...
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
....
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
	    return -level 2 -code error \
		-errorcode [list FDDD DifferentColumns $rel1 $rel2] \
		"relations \"$rel1\" and \"$rel2\" have different columns"
	}
	return
    }
























    # Private method: Varlist
    #	
    #	Enumerates the BDD variables that make up a relation.
    #
    # Usage:
    #	$db Varlist $relation
    #
................................................................................
    #
    # This method does not perform the test directly: it generates
    # code to perform the test.
    #
    # The test executes in constant time.

    method === {rel1 rel2} {
	my relationMustExist $rel1
	my relationMustExist $rel2
	my ColumnsMustBeSame $rel1 $rel2
	return [list [namespace which sys] === $rel1 $rel2]
    }
    export ===

    # Method: antijoin
    #
................................................................................
    # This method does not perform the copy directly: it generates
    # code to perform the copy.
    #
    # The antijoin executes in time proportional to the size of the
    # source1 BDD.

    method antijoin {dest source1 source2} {
	my relationMustExist $dest
	my relationMustExist $source1
	my relationMustExist $source2

	# Determine the columns in the joined relations
	set destcolumns [dict get $m_relcolumns $source1]
	lappend destcolumns {*}[dict get $m_relcolumns $source2]
	set destcolumns [lsort -dictionary -unique $destcolumns]
	my ColumnsMustBe $dest $destcolumns

	# Make code to do the antijoin
	return [list [namespace which sys] > $dest $source1 $source2]
    }

    # Method: columnMustExist
    #
    #	Makes sure that a given column exists in the database
    #
    # Usage:
    #	my columnMustExist $name
    #
    # Parameters:
    #	name - Name of a column
    #
    # Results:
    #	Returns an empty result if the column exists. Causes the caller
    #	to return an error if the column is not found.

    method columnMustExist {name} {
	if {![dict exists $m_columns $name]} {
	    return -level 2 -code error \
		-errorcode [list FDDD ColumnNotDefined $name] \
		"column \"$name\" is not defined in this database"
	}
	return
    }

    # Method: columns
    #
    #	Enumerates all columns in the database, or the columns of a
    #	specific relation.
    #
    # Usage:
    #	$db columns ?relation?
    #
    # Parameters:
    #	relation - If supplied, indicates the relation being queried.
    #
    # Results:
    #
    #	Returns the list of columns that participate in the given
    #	relation.  If no relation is supplied, returns a list of all
    #	the column names that are known to the database
    #
    # This method executes directly, rather than returning a code fragment

    method columns {{relation {}}} {
	if {$relation eq {}} {
	    return [dict keys $m_columns]
	} else {
	    my relationMustExist $relation
	    return [dict get $m_relcolumns $relation]
	}
    }

    # Method: enumerate
    #
    #	Iterates over all the tuples in a relation
    #
    # Usage:
................................................................................
    # Any other nonstandard status code terminates the iteration.
    #
    # This method executes directly, rather than returning a code fragment

    method enumerate {dictvar relation script} {
	upvar 1 $dictvar valdict

	my relationMustExist $relation

	# Iterate over the relation, getting SAT terms. Iterate over
	# the variable assignments that satisfy the terms.
	sys foreach_sat satterm $relation {
	    bdd::foreach_fullsat vars [my Varlist $relation] $satterm {

		# Iterate over the columns and populate the dictionary
................................................................................
    # The time taken to create the equality is highly variable. In the case
    # where the two columns' variables are interleaved, the time is linear
    # in the number of bits of the domains. In the case where they are
    # concatenated, both time and space are exponential in the number of
    # variables. Other orderings will give results between these two extremes.

    method equate {dest col1 col2} {
	my relationMustExist $dest
	my columnMustExist $col1
	my columnMustExist $col2
	set destcolumns [dict get $m_relcolumns $dest]

	if {[lsearch -exact $destcolumns $col1] == -1} {
	    return -code error -errorcode \

		[list FDDD RelationDoesNotContainColumn $dest $col1] \
		"relation \"$dest\" does not contain column \"$col1\""
	}

	if {[lsearch -exact $destcolumns $col2] == -1} {
	    return -code error -errorcode \

		[list FDDD RelationDoesNotContainColumn $dest $col1] \
		"relation \"$dest\" does not contain column \"$col1\""
	}
	set vars1 [dict get $m_columns $col1]
	set vars2 [dict get $m_columns $col2]
	if {[llength $vars1] != [llength $vars2]} {
	    return -code error \
		-errorcode [list FDDD EquateWrongDomains $col1 $col2] \
		"cannot equate domains \"$col1\" and \"$col2\":\
................................................................................
    # This method does not perform the copy directly: it generates
    # code to perform the copy.
    #
    # The join executes in time proportional to the size of the
    # source1 BDD.

    method join {dest source1 source2} {
	my relationMustExist $dest
	my relationMustExist $source1
	my relationMustExist $source2

	# Determine the columns in the joined relations
	set destcolumns [dict get $m_relcolumns $source1]
	lappend destcolumns {*}[dict get $m_relcolumns $source2]
	set destcolumns [lsort -dictionary -unique $destcolumns]
	my ColumnsMustBe $dest $destcolumns

................................................................................
    #	Returns a command prefix for a command that will add a tuple
    #	to the given relation.
    #
    # To the prefix should be appended the values of the columns,
    # in dictonary order by the column names.

    method loader {relation} {
	my relationMustExist $relation
	set i 0
	foreach column [dict get $m_relcolumns $relation] {
	    dict set cmdpos $column $i
	    incr i
	}
	set result {}
	set p 0
................................................................................
    # Results:
    #	Returns a list ordered by variable level giving the number of
    #	beads at each level
    #
    # This method executes directly, rather than returning a codeburst.

    method profile {relation} {
	my relationMustExist $relation
	sys profile $relation
    }

    # Method: project
    #
    #	Uses existential quantification to project a relation onto
    #	a smaller domain.
................................................................................
    # code to perform the projection.
    #
    # The projection executes in time proportional to the size of the
    # source BDD.

    method project {dest source} {
	# columns to project away are determined by dest and source
	my relationMustExist $dest
	my relationMustExist $source
	set discards {}
	foreach col [dict get $m_relcolumns $dest] {
	    dict set want $col {}
	}
	foreach col [dict get $m_relcolumns $source] {
	    if {![dict exists $want $col]} {
		lappend discards {*}[dict get $m_columns $col]
................................................................................
    #	column... - Set of columns that the relation constrains
    #
    # Results:
    #	None.
    #
    # Side effects:
    #	The given relation is defined. Its content in the database
    #	is initially empty.

    #
    # This command takes effect immediately, rather than returning
    # code to perform an operation at run time.

    method relation {name args} {
	if {[dict exists $m_relcolumns $name]} {
	    return -code error \
		-errorcode [list FDDD RelationAlreadyDefined $name] \
		"relation \"$name\" is already defined in this database"
	}
	set havecol {}
	foreach col $args {
	    my columnMustExist $col
	    if {[dict exists $havecol $col]} {
		return -code error -errorcode [list FDDD DuplicateColumn $col] \
		    "column $col is duplicated in the column list"
	    }




	    dict set $havecol $col {}
	}
	dict set m_relcolumns $name [lsort -dictionary $args]
	$db set $name {}
	return $name
    }

    # Method: relationMustExist
    #
    #	Makes sure that a given relation exists in the database
    #
    # Usage:
    #	my relationMustExist $name
    #
    # Parameters:
    #	name - Name of a relation
    #
    # Results:
    #	Returns an empty result if the relation exists. Causes the caller
    #	to return an error if the relation is not found.

    method relationMustExist {name} {
	if {![dict exists $m_relcolumns $name]} {
	    return -level 2 -code error \
		-errorcode [list FDDD RelationNotDefined $name] \
		"relation \"$name\" is not defined in this database"
	}
	return
    }

    # Method: replace
    #
    #	Generates code to reassign physical domains in a relation
    #
    # Usage:
    #	$db replace dest source ?outcol incol?...
................................................................................
    # the same order as those of the input columns (RECOMMENDED), it
    # is linear in the size of the input BDD. In the worst case of variable
    # reordering, it may be exponential in the size of the input BDD.
    # This will happen, for instance, if an equality over an interleaved
    # pair of columns is replaced with an equality over a concatenated pair.

    method replace {dest source args} {
	my relationMustExist $dest
	my relationMustExist $source
	set sourcecols {}
	foreach col [dict get $m_relcolumns $source] {
	    dict set sourcecols $col {}
	}
	set destcols {}
	foreach col [dict get $m_relcolumns $dest] {
	    dict set destcols $col {}
	}
	set colsAdded {}
	foreach {to from} $args {
	    my columnMustExist $to
	    my columnMustExist $from
	    if {[dict exists $colsAdded $to]} {
		return -code error \
		    -errorcode [list FDDD DuplicateReplaceOutput $to] \
		    "attempt to rename two input columns to \"$to\""
	    }
	    if {![dict exists $sourcecols $from]} {
		return -code error \
................................................................................
		    "replacement column \"$to\" is to narrow to hold values\
                     from column \"$from\""
	    }
	    lappend fromvars {*}$fv
	    lappend tovars {*}[lrange $tv 0 [expr {[llength $fv] - 1}]]
	}

	return \
	    [list [namespace which sys] replace $dest $fromvars $tovars $source]
    }

    # Method: set
    #
    #	Generates code to copy one relation to another
    #
    # Usage:
................................................................................
    #
    # This method does not perform the copy directly: it generates
    # code to perform the copy.
    #
    # The copy executes in constant time.

    method set {dest source} {
	my relationMustExist $dest
	if {$source eq {}} {
	    set source 0
	} elseif {$source eq {_}} {
	    set source 1
	} else {
	    my relationMustExist $source
	    my ColumnsMustBeSame $dest $source
	}
	return [list [namespace which sys] := $dest $source]
    }

    # Method: union
    #
................................................................................
    # This method does not compute the union; it returns a fragment
    # of code that computes it.
    #
    # The time taken to compute the union is linear in the sum of the
    # sizes of the two BDD's.

    method union {dest source1 source2} {
	my relationMustExist $dest
	my relationMustExist $source1
	my relationMustExist $source2
	my ColumnsMustBeSame $dest $source1
	my ColumnsMustBeSame $dest $source2
	return [list [namespace which sys] | $dest $source1 $source2]
    }

if 0 {
    # deprecate this for now.
    method load {name list} {
	my relationMustExist $name
	set nColumns [llength [dict get $m_relcolumns $name]]
	if {[llength $list] % $nColumns != 0} {
	    return -code error \
		-errorcode [list FDDD WrongListLength $nColumns] \
		"list must have a multiple of $nColumns values"
	}
	set reader [my loader $name]