1 // Copyright 2008 the V8 project authors. All rights reserved.
2 // Copyright 1996 John Maloney and Mario Wolczko.
4 // This program is free software; you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation; either version 2 of the License, or
7 // (at your option) any later version.
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with this program; if not, write to the Free Software
16 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 // This implementation of the DeltaBlue benchmark is derived
20 // from the Smalltalk implementation by John Maloney and Mario
21 // Wolczko. Some parts have been translated directly, whereas
22 // others have been modified more aggresively to make it feel
23 // more like a JavaScript program.
26 * A JavaScript implementation of the DeltaBlue constrain-solving
27 * algorithm, as described in:
29 * "The DeltaBlue Algorithm: An Incremental Constraint Hierarchy Solver"
30 * Bjorn N. Freeman-Benson and John Maloney
31 * January 1990 Communications of the ACM,
32 * also available as University of Washington TR 89-08-06.
34 * Beware: this benchmark is written in a grotesque style where
35 * the constraint model is built by side-effects from constructors.
36 * I've kept it this way to avoid deviating too much from the original
41 /* --- O b j e c t M o d e l --- */
43 Object.prototype.inherits = function (shuper) {
44 function Inheriter() { }
45 Inheriter.prototype = shuper.prototype;
46 this.prototype = new Inheriter();
47 this.superConstructor = shuper;
50 function OrderedCollection() {
51 this.elms = new Array();
54 OrderedCollection.prototype.add = function (elm) {
58 OrderedCollection.prototype.at = function (index) {
59 return this.elms[index];
62 OrderedCollection.prototype.size = function () {
63 return this.elms.length;
66 OrderedCollection.prototype.removeFirst = function () {
67 return this.elms.pop();
70 OrderedCollection.prototype.remove = function (elm) {
71 var index = 0, skipped = 0;
72 for (var i = 0; i < this.elms.length; i++) {
73 var value = this.elms[i];
75 this.elms[index] = value;
81 for (var i = 0; i < skipped; i++)
90 * Strengths are used to measure the relative importance of constraints.
91 * New strengths may be inserted in the strength hierarchy without
92 * disrupting current constraints. Strengths cannot be created outside
93 * this class, so pointer comparison can be used for value comparison.
95 function Strength(strengthValue, name) {
96 this.strengthValue = strengthValue;
100 Strength.stronger = function (s1, s2) {
101 return s1.strengthValue < s2.strengthValue;
104 Strength.weaker = function (s1, s2) {
105 return s1.strengthValue > s2.strengthValue;
108 Strength.weakestOf = function (s1, s2) {
109 return this.weaker(s1, s2) ? s1 : s2;
112 Strength.strongest = function (s1, s2) {
113 return this.stronger(s1, s2) ? s1 : s2;
116 Strength.prototype.nextWeaker = function () {
117 switch (this.strengthValue) {
118 case 0: return Strength.WEAKEST;
119 case 1: return Strength.WEAK_DEFAULT;
120 case 2: return Strength.NORMAL;
121 case 3: return Strength.STRONG_DEFAULT;
122 case 4: return Strength.PREFERRED;
123 case 5: return Strength.REQUIRED;
127 // Strength constants.
128 Strength.REQUIRED = new Strength(0, "required");
129 Strength.STONG_PREFERRED = new Strength(1, "strongPreferred");
130 Strength.PREFERRED = new Strength(2, "preferred");
131 Strength.STRONG_DEFAULT = new Strength(3, "strongDefault");
132 Strength.NORMAL = new Strength(4, "normal");
133 Strength.WEAK_DEFAULT = new Strength(5, "weakDefault");
134 Strength.WEAKEST = new Strength(6, "weakest");
137 * C o n s t r a i n t
141 * An abstract class representing a system-maintainable relationship
142 * (or "constraint") between a set of variables. A constraint supplies
143 * a strength instance variable; concrete subclasses provide a means
144 * of storing the constrained variables and other information required
145 * to represent a constraint.
147 function Constraint(strength) {
148 this.strength = strength;
152 * Activate this constraint and attempt to satisfy it.
154 Constraint.prototype.addConstraint = function () {
156 planner.incrementalAdd(this);
160 * Attempt to find a way to enforce this constraint. If successful,
161 * record the solution, perhaps modifying the current dataflow
162 * graph. Answer the constraint that this constraint overrides, if
163 * there is one, or nil, if there isn't.
164 * Assume: I am not already satisfied.
166 Constraint.prototype.satisfy = function (mark) {
167 this.chooseMethod(mark);
168 if (!this.isSatisfied()) {
169 if (this.strength == Strength.REQUIRED)
170 alert("Could not satisfy a required constraint!");
173 this.markInputs(mark);
174 var out = this.output();
175 var overridden = out.determinedBy;
176 if (overridden != null) overridden.markUnsatisfied();
177 out.determinedBy = this;
178 if (!planner.addPropagate(this, mark))
179 alert("Cycle encountered");
184 Constraint.prototype.destroyConstraint = function () {
185 if (this.isSatisfied()) planner.incrementalRemove(this);
186 else this.removeFromGraph();
190 * Normal constraints are not input constraints. An input constraint
191 * is one that depends on external state, such as the mouse, the
192 * keybord, a clock, or some arbitraty piece of imperative code.
194 Constraint.prototype.isInput = function () {
199 * U n a r y C o n s t r a i n t
203 * Abstract superclass for constraints having a single possible output
206 function UnaryConstraint(v, strength) {
207 UnaryConstraint.superConstructor.call(this, strength);
209 this.satisfied = false;
210 this.addConstraint();
213 UnaryConstraint.inherits(Constraint);
216 * Adds this constraint to the constraint graph
218 UnaryConstraint.prototype.addToGraph = function () {
219 this.myOutput.addConstraint(this);
220 this.satisfied = false;
224 * Decides if this constraint can be satisfied and records that
227 UnaryConstraint.prototype.chooseMethod = function (mark) {
228 this.satisfied = (this.myOutput.mark != mark)
229 && Strength.stronger(this.strength, this.myOutput.walkStrength);
233 * Returns true if this constraint is satisfied in the current solution.
235 UnaryConstraint.prototype.isSatisfied = function () {
236 return this.satisfied;
239 UnaryConstraint.prototype.markInputs = function (mark) {
244 * Returns the current output variable.
246 UnaryConstraint.prototype.output = function () {
247 return this.myOutput;
251 * Calculate the walkabout strength, the stay flag, and, if it is
252 * 'stay', the value for the current output of this constraint. Assume
253 * this constraint is satisfied.
255 UnaryConstraint.prototype.recalculate = function () {
256 this.myOutput.walkStrength = this.strength;
257 this.myOutput.stay = !this.isInput();
258 if (this.myOutput.stay) this.execute(); // Stay optimization
262 * Records that this constraint is unsatisfied
264 UnaryConstraint.prototype.markUnsatisfied = function () {
265 this.satisfied = false;
268 UnaryConstraint.prototype.inputsKnown = function () {
272 UnaryConstraint.prototype.removeFromGraph = function () {
273 if (this.myOutput != null) this.myOutput.removeConstraint(this);
274 this.satisfied = false;
278 * S t a y C o n s t r a i n t
282 * Variables that should, with some level of preference, stay the same.
283 * Planners may exploit the fact that instances, if satisfied, will not
284 * change their output during plan execution. This is called "stay
287 function StayConstraint(v, str) {
288 StayConstraint.superConstructor.call(this, v, str);
291 StayConstraint.inherits(UnaryConstraint);
293 StayConstraint.prototype.execute = function () {
294 // Stay constraints do nothing
298 * E d i t C o n s t r a i n t
302 * A unary input constraint used to mark a variable that the client
305 function EditConstraint(v, str) {
306 EditConstraint.superConstructor.call(this, v, str);
309 EditConstraint.inherits(UnaryConstraint);
312 * Edits indicate that a variable is to be changed by imperative code.
314 EditConstraint.prototype.isInput = function () {
318 EditConstraint.prototype.execute = function () {
319 // Edit constraints do nothing
323 * B i n a r y C o n s t r a i n t
326 var Direction = new Object();
328 Direction.FORWARD = 1;
329 Direction.BACKWARD = -1;
332 * Abstract superclass for constraints having two possible output
335 function BinaryConstraint(var1, var2, strength) {
336 BinaryConstraint.superConstructor.call(this, strength);
339 this.direction = Direction.NONE;
340 this.addConstraint();
343 BinaryConstraint.inherits(Constraint);
346 * Decides if this constratint can be satisfied and which way it
347 * should flow based on the relative strength of the variables related,
348 * and record that decision.
350 BinaryConstraint.prototype.chooseMethod = function (mark) {
351 if (this.v1.mark == mark) {
352 this.direction = (this.v1.mark != mark && Strength.stronger(this.strength, this.v2.walkStrength))
356 if (this.v2.mark == mark) {
357 this.direction = (this.v1.mark != mark && Strength.stronger(this.strength, this.v1.walkStrength))
361 if (Strength.weaker(this.v1.walkStrength, this.v2.walkStrength)) {
362 this.direction = Strength.stronger(this.strength, this.v1.walkStrength)
366 this.direction = Strength.stronger(this.strength, this.v2.walkStrength)
373 * Add this constraint to the constraint graph
375 BinaryConstraint.prototype.addToGraph = function () {
376 this.v1.addConstraint(this);
377 this.v2.addConstraint(this);
378 this.direction = Direction.NONE;
382 * Answer true if this constraint is satisfied in the current solution.
384 BinaryConstraint.prototype.isSatisfied = function () {
385 return this.direction != Direction.NONE;
389 * Mark the input variable with the given mark.
391 BinaryConstraint.prototype.markInputs = function (mark) {
392 this.input().mark = mark;
396 * Returns the current input variable
398 BinaryConstraint.prototype.input = function () {
399 return (this.direction == Direction.FORWARD) ? this.v1 : this.v2;
403 * Returns the current output variable
405 BinaryConstraint.prototype.output = function () {
406 return (this.direction == Direction.FORWARD) ? this.v2 : this.v1;
410 * Calculate the walkabout strength, the stay flag, and, if it is
411 * 'stay', the value for the current output of this
412 * constraint. Assume this constraint is satisfied.
414 BinaryConstraint.prototype.recalculate = function () {
415 var ihn = this.input(), out = this.output();
416 out.walkStrength = Strength.weakestOf(this.strength, ihn.walkStrength);
418 if (out.stay) this.execute();
422 * Record the fact that this constraint is unsatisfied.
424 BinaryConstraint.prototype.markUnsatisfied = function () {
425 this.direction = Direction.NONE;
428 BinaryConstraint.prototype.inputsKnown = function (mark) {
429 var i = this.input();
430 return i.mark == mark || i.stay || i.determinedBy == null;
433 BinaryConstraint.prototype.removeFromGraph = function () {
434 if (this.v1 != null) this.v1.removeConstraint(this);
435 if (this.v2 != null) this.v2.removeConstraint(this);
436 this.direction = Direction.NONE;
440 * S c a l e C o n s t r a i n t
444 * Relates two variables by the linear scaling relationship: "v2 =
445 * (v1 * scale) + offset". Either v1 or v2 may be changed to maintain
446 * this relationship but the scale factor and offset are considered
449 function ScaleConstraint(src, scale, offset, dest, strength) {
450 this.direction = Direction.NONE;
452 this.offset = offset;
453 ScaleConstraint.superConstructor.call(this, src, dest, strength);
456 ScaleConstraint.inherits(BinaryConstraint);
459 * Adds this constraint to the constraint graph.
461 ScaleConstraint.prototype.addToGraph = function () {
462 ScaleConstraint.superConstructor.prototype.addToGraph.call(this);
463 this.scale.addConstraint(this);
464 this.offset.addConstraint(this);
467 ScaleConstraint.prototype.removeFromGraph = function () {
468 ScaleConstraint.superConstructor.prototype.removeFromGraph.call(this);
469 if (this.scale != null) this.scale.removeConstraint(this);
470 if (this.offset != null) this.offset.removeConstraint(this);
473 ScaleConstraint.prototype.markInputs = function (mark) {
474 ScaleConstraint.superConstructor.prototype.markInputs.call(this, mark);
475 this.scale.mark = this.offset.mark = mark;
479 * Enforce this constraint. Assume that it is satisfied.
481 ScaleConstraint.prototype.execute = function () {
482 if (this.direction == Direction.FORWARD) {
483 this.v2.value = this.v1.value * this.scale.value + this.offset.value;
485 this.v1.value = (this.v2.value - this.offset.value) / this.scale.value;
490 * Calculate the walkabout strength, the stay flag, and, if it is
491 * 'stay', the value for the current output of this constraint. Assume
492 * this constraint is satisfied.
494 ScaleConstraint.prototype.recalculate = function () {
495 var ihn = this.input(), out = this.output();
496 out.walkStrength = Strength.weakestOf(this.strength, ihn.walkStrength);
497 out.stay = ihn.stay && this.scale.stay && this.offset.stay;
498 if (out.stay) this.execute();
502 * E q u a l i t y C o n s t r a i n t
506 * Constrains two variables to have the same value.
508 function EqualityConstraint(var1, var2, strength) {
509 EqualityConstraint.superConstructor.call(this, var1, var2, strength);
512 EqualityConstraint.inherits(BinaryConstraint);
515 * Enforce this constraint. Assume that it is satisfied.
517 EqualityConstraint.prototype.execute = function () {
518 this.output().value = this.input().value;
526 * A constrained variable. In addition to its value, it maintain the
527 * structure of the constraint graph, the current dataflow graph, and
528 * various parameters of interest to the DeltaBlue incremental
531 function Variable(name, initialValue) {
532 this.value = initialValue || 0;
533 this.constraints = new OrderedCollection();
534 this.determinedBy = null;
536 this.walkStrength = Strength.WEAKEST;
542 * Add the given constraint to the set of all constraints that refer
545 Variable.prototype.addConstraint = function (c) {
546 this.constraints.add(c);
550 * Removes all traces of c from this variable.
552 Variable.prototype.removeConstraint = function (c) {
553 this.constraints.remove(c);
554 if (this.determinedBy == c) this.determinedBy = null;
562 * The DeltaBlue planner
565 this.currentMark = 0;
569 * Attempt to satisfy the given constraint and, if successful,
570 * incrementally update the dataflow graph. Details: If satifying
571 * the constraint is successful, it may override a weaker constraint
572 * on its output. The algorithm attempts to resatisfy that
573 * constraint using some other method. This process is repeated
574 * until either a) it reaches a variable that was not previously
575 * determined by any constraint or b) it reaches a constraint that
576 * is too weak to be satisfied using any of its methods. The
577 * variables of constraints that have been processed are marked with
578 * a unique mark value so that we know where we've been. This allows
579 * the algorithm to avoid getting into an infinite loop even if the
580 * constraint graph has an inadvertent cycle.
582 Planner.prototype.incrementalAdd = function (c) {
583 var mark = this.newMark();
584 var overridden = c.satisfy(mark);
585 while (overridden != null)
586 overridden = overridden.satisfy(mark);
590 * Entry point for retracting a constraint. Remove the given
591 * constraint and incrementally update the dataflow graph.
592 * Details: Retracting the given constraint may allow some currently
593 * unsatisfiable downstream constraint to be satisfied. We therefore collect
594 * a list of unsatisfied downstream constraints and attempt to
595 * satisfy each one in turn. This list is traversed by constraint
596 * strength, strongest first, as a heuristic for avoiding
597 * unnecessarily adding and then overriding weak constraints.
598 * Assume: c is satisfied.
600 Planner.prototype.incrementalRemove = function (c) {
601 var out = c.output();
604 var unsatisfied = this.removePropagateFrom(out);
605 var strength = Strength.REQUIRED;
607 for (var i = 0; i < unsatisfied.size(); i++) {
608 var u = unsatisfied.at(i);
609 if (u.strength == strength)
610 this.incrementalAdd(u);
612 strength = strength.nextWeaker();
613 } while (strength != Strength.WEAKEST);
617 * Select a previously unused mark value.
619 Planner.prototype.newMark = function () {
620 return ++this.currentMark;
624 * Extract a plan for resatisfaction starting from the given source
625 * constraints, usually a set of input constraints. This method
626 * assumes that stay optimization is desired; the plan will contain
627 * only constraints whose output variables are not stay. Constraints
628 * that do no computation, such as stay and edit constraints, are
629 * not included in the plan.
630 * Details: The outputs of a constraint are marked when it is added
631 * to the plan under construction. A constraint may be appended to
632 * the plan when all its input variables are known. A variable is
633 * known if either a) the variable is marked (indicating that has
634 * been computed by a constraint appearing earlier in the plan), b)
635 * the variable is 'stay' (i.e. it is a constant at plan execution
636 * time), or c) the variable is not determined by any
637 * constraint. The last provision is for past states of history
638 * variables, which are not stay but which are also not computed by
640 * Assume: sources are all satisfied.
642 Planner.prototype.makePlan = function (sources) {
643 var mark = this.newMark();
644 var plan = new Plan();
646 while (todo.size() > 0) {
647 var c = todo.removeFirst();
648 if (c.output().mark != mark && c.inputsKnown(mark)) {
649 plan.addConstraint(c);
650 c.output().mark = mark;
651 this.addConstraintsConsumingTo(c.output(), todo);
658 * Extract a plan for resatisfying starting from the output of the
659 * given constraints, usually a set of input constraints.
661 Planner.prototype.extractPlanFromConstraints = function (constraints) {
662 var sources = new OrderedCollection();
663 for (var i = 0; i < constraints.size(); i++) {
664 var c = constraints.at(i);
665 if (c.isInput() && c.isSatisfied())
666 // not in plan already and eligible for inclusion
669 return this.makePlan(sources);
673 * Recompute the walkabout strengths and stay flags of all variables
674 * downstream of the given constraint and recompute the actual
675 * values of all variables whose stay flag is true. If a cycle is
676 * detected, remove the given constraint and answer
677 * false. Otherwise, answer true.
678 * Details: Cycles are detected when a marked variable is
679 * encountered downstream of the given constraint. The sender is
680 * assumed to have marked the inputs of the given constraint with
681 * the given mark. Thus, encountering a marked node downstream of
682 * the output constraint means that there is a path from the
683 * constraint's output to one of its inputs.
685 Planner.prototype.addPropagate = function (c, mark) {
686 var todo = new OrderedCollection();
688 while (todo.size() > 0) {
689 var d = todo.removeFirst();
690 if (d.output().mark == mark) {
691 this.incrementalRemove(c);
695 this.addConstraintsConsumingTo(d.output(), todo);
702 * Update the walkabout strengths and stay flags of all variables
703 * downstream of the given constraint. Answer a collection of
704 * unsatisfied constraints sorted in order of decreasing strength.
706 Planner.prototype.removePropagateFrom = function (out) {
707 out.determinedBy = null;
708 out.walkStrength = Strength.WEAKEST;
710 var unsatisfied = new OrderedCollection();
711 var todo = new OrderedCollection();
713 while (todo.size() > 0) {
714 var v = todo.removeFirst();
715 for (var i = 0; i < v.constraints.size(); i++) {
716 var c = v.constraints.at(i);
717 if (!c.isSatisfied())
720 var determining = v.determinedBy;
721 for (var i = 0; i < v.constraints.size(); i++) {
722 var next = v.constraints.at(i);
723 if (next != determining && next.isSatisfied()) {
725 todo.add(next.output());
732 Planner.prototype.addConstraintsConsumingTo = function (v, coll) {
733 var determining = v.determinedBy;
734 var cc = v.constraints;
735 for (var i = 0; i < cc.size(); i++) {
737 if (c != determining && c.isSatisfied())
747 * A Plan is an ordered list of constraints to be executed in sequence
748 * to resatisfy all currently satisfiable constraints in the face of
749 * one or more changing inputs.
752 this.v = new OrderedCollection();
755 Plan.prototype.addConstraint = function (c) {
759 Plan.prototype.size = function () {
760 return this.v.size();
763 Plan.prototype.constraintAt = function (index) {
764 return this.v.at(index);
767 Plan.prototype.execute = function () {
768 for (var i = 0; i < this.size(); i++) {
769 var c = this.constraintAt(i);
779 * This is the standard DeltaBlue benchmark. A long chain of equality
780 * constraints is constructed with a stay constraint on one end. An
781 * edit constraint is then added to the opposite end and the time is
782 * measured for adding and removing this constraint, and extracting
783 * and executing a constraint satisfaction plan. There are two cases.
784 * In case 1, the added constraint is stronger than the stay
785 * constraint and values must propagate down the entire length of the
786 * chain. In case 2, the added constraint is weaker than the stay
787 * constraint so it cannot be accomodated. The cost in this case is,
788 * of course, very low. Typical situations lie somewhere between these
791 function chainTest(n) {
792 planner = new Planner();
793 var prev = null, first = null, last = null;
795 // Build chain of n equality constraints
796 for (var i = 0; i <= n; i++) {
798 var v = new Variable(name);
800 new EqualityConstraint(prev, v, Strength.REQUIRED);
801 if (i == 0) first = v;
802 if (i == n) last = v;
806 new StayConstraint(last, Strength.STRONG_DEFAULT);
807 var edit = new EditConstraint(first, Strength.PREFERRED);
808 var edits = new OrderedCollection();
810 var plan = planner.extractPlanFromConstraints(edits);
811 for (var i = 0; i < 100; i++) {
815 alert("Chain test failed.");
820 * This test constructs a two sets of variables related to each
821 * other by a simple linear transformation (scale and offset). The
822 * time is measured to change a variable on either side of the
823 * mapping and to change the scale and offset factors.
825 function projectionTest(n) {
826 planner = new Planner();
827 var scale = new Variable("scale", 10);
828 var offset = new Variable("offset", 1000);
829 var src = null, dst = null;
831 var dests = new OrderedCollection();
832 for (var i = 0; i < n; i++) {
833 src = new Variable("src" + i, i);
834 dst = new Variable("dst" + i, i);
836 new StayConstraint(src, Strength.NORMAL);
837 new ScaleConstraint(src, scale, offset, dst, Strength.REQUIRED);
841 if (dst.value != 1170) alert("Projection 1 failed");
843 if (src.value != 5) alert("Projection 2 failed");
845 for (var i = 0; i < n - 1; i++) {
846 if (dests.at(i).value != i * 5 + 1000)
847 alert("Projection 3 failed");
849 change(offset, 2000);
850 for (var i = 0; i < n - 1; i++) {
851 if (dests.at(i).value != i * 5 + 2000)
852 alert("Projection 4 failed");
856 function change(v, newValue) {
857 var edit = new EditConstraint(v, Strength.PREFERRED);
858 var edits = new OrderedCollection();
860 var plan = planner.extractPlanFromConstraints(edits);
861 for (var i = 0; i < 10; i++) {
865 edit.destroyConstraint();
868 // Global variable holding the current planner.
871 function deltaBlue() {
876 for (var i = 0; i < 155; ++i)