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.
25 let __exceptionCounter = 0;
26 function exception() {
27 if (__exceptionCounter++ % 35 === 0)
28 throw __exceptionCounter;
33 * A JavaScript implementation of the DeltaBlue constraint-solving
34 * algorithm, as described in:
36 * "The DeltaBlue Algorithm: An Incremental Constraint Hierarchy Solver"
37 * Bjorn N. Freeman-Benson and John Maloney
38 * January 1990 Communications of the ACM,
39 * also available as University of Washington TR 89-08-06.
41 * Beware: this benchmark is written in a grotesque style where
42 * the constraint model is built by side-effects from constructors.
43 * I've kept it this way to avoid deviating too much from the original
48 /* --- O b j e c t M o d e l --- */
50 Object.defineProperty(Object.prototype, "inheritsFrom", {
52 value: function (shuper) {
53 function Inheriter() { }
54 Inheriter.prototype = shuper.prototype;
55 this.prototype = new Inheriter();
56 this.superConstructor = shuper;
60 function OrderedCollection() {
61 this.elms = new Array();
64 OrderedCollection.prototype.add = function (elm) {
68 OrderedCollection.prototype.at = function (index) {
69 return this.elms[index];
72 OrderedCollection.prototype.size = function () {
73 return this.elms.length;
76 OrderedCollection.prototype.removeFirst = function () {
77 return this.elms.pop();
80 OrderedCollection.prototype.remove = function (elm) {
81 var index = 0, skipped = 0;
82 for (var i = 0; i < this.elms.length; i++) {
83 var value = this.elms[i];
85 this.elms[index] = value;
90 try { exception(); } catch(e) { }
92 for (var i = 0; i < skipped; i++) {
94 try { exception(); } catch(e) { }
103 * Strengths are used to measure the relative importance of constraints.
104 * New strengths may be inserted in the strength hierarchy without
105 * disrupting current constraints. Strengths cannot be created outside
106 * this class, so pointer comparison can be used for value comparison.
108 function Strength(strengthValue, name) {
109 this.strengthValue = strengthValue;
113 Strength.stronger = function (s1, s2) {
114 return s1.strengthValue < s2.strengthValue;
117 Strength.weaker = function (s1, s2) {
118 return s1.strengthValue > s2.strengthValue;
121 Strength.weakestOf = function (s1, s2) {
122 return this.weaker(s1, s2) ? s1 : s2;
125 Strength.strongest = function (s1, s2) {
126 return this.stronger(s1, s2) ? s1 : s2;
129 Strength.prototype.nextWeaker = function () {
130 switch (this.strengthValue) {
131 case 0: return Strength.WEAKEST;
132 case 1: return Strength.WEAK_DEFAULT;
133 case 2: return Strength.NORMAL;
134 case 3: return Strength.STRONG_DEFAULT;
135 case 4: return Strength.PREFERRED;
136 case 5: return Strength.REQUIRED;
140 // Strength constants.
141 Strength.REQUIRED = new Strength(0, "required");
142 Strength.STONG_PREFERRED = new Strength(1, "strongPreferred");
143 Strength.PREFERRED = new Strength(2, "preferred");
144 Strength.STRONG_DEFAULT = new Strength(3, "strongDefault");
145 Strength.NORMAL = new Strength(4, "normal");
146 Strength.WEAK_DEFAULT = new Strength(5, "weakDefault");
147 Strength.WEAKEST = new Strength(6, "weakest");
150 * C o n s t r a i n t
154 * An abstract class representing a system-maintainable relationship
155 * (or "constraint") between a set of variables. A constraint supplies
156 * a strength instance variable; concrete subclasses provide a means
157 * of storing the constrained variables and other information required
158 * to represent a constraint.
160 function Constraint(strength) {
161 this.strength = strength;
165 * Activate this constraint and attempt to satisfy it.
167 Constraint.prototype.addConstraint = function () {
169 planner.incrementalAdd(this);
173 * Attempt to find a way to enforce this constraint. If successful,
174 * record the solution, perhaps modifying the current dataflow
175 * graph. Answer the constraint that this constraint overrides, if
176 * there is one, or nil, if there isn't.
177 * Assume: I am not already satisfied.
179 Constraint.prototype.satisfy = function (mark) {
180 this.chooseMethod(mark);
181 if (!this.isSatisfied()) {
182 if (this.strength == Strength.REQUIRED)
183 alert("Could not satisfy a required constraint!");
186 this.markInputs(mark);
187 var out = this.output();
188 var overridden = out.determinedBy;
189 if (overridden != null) overridden.markUnsatisfied();
190 out.determinedBy = this;
191 if (!planner.addPropagate(this, mark))
192 alert("Cycle encountered");
197 Constraint.prototype.destroyConstraint = function () {
198 if (this.isSatisfied()) planner.incrementalRemove(this);
199 else this.removeFromGraph();
203 * Normal constraints are not input constraints. An input constraint
204 * is one that depends on external state, such as the mouse, the
205 * keybord, a clock, or some arbitraty piece of imperative code.
207 Constraint.prototype.isInput = function () {
212 * U n a r y C o n s t r a i n t
216 * Abstract superclass for constraints having a single possible output
219 function UnaryConstraint(v, strength) {
220 UnaryConstraint.superConstructor.call(this, strength);
222 this.satisfied = false;
223 this.addConstraint();
226 UnaryConstraint.inheritsFrom(Constraint);
229 * Adds this constraint to the constraint graph
231 UnaryConstraint.prototype.addToGraph = function () {
232 this.myOutput.addConstraint(this);
233 this.satisfied = false;
237 * Decides if this constraint can be satisfied and records that
240 UnaryConstraint.prototype.chooseMethod = function (mark) {
241 this.satisfied = (this.myOutput.mark != mark)
242 && Strength.stronger(this.strength, this.myOutput.walkStrength);
246 * Returns true if this constraint is satisfied in the current solution.
248 UnaryConstraint.prototype.isSatisfied = function () {
249 return this.satisfied;
252 UnaryConstraint.prototype.markInputs = function (mark) {
257 * Returns the current output variable.
259 UnaryConstraint.prototype.output = function () {
260 return this.myOutput;
264 * Calculate the walkabout strength, the stay flag, and, if it is
265 * 'stay', the value for the current output of this constraint. Assume
266 * this constraint is satisfied.
268 UnaryConstraint.prototype.recalculate = function () {
269 this.myOutput.walkStrength = this.strength;
270 this.myOutput.stay = !this.isInput();
271 if (this.myOutput.stay) this.execute(); // Stay optimization
275 * Records that this constraint is unsatisfied
277 UnaryConstraint.prototype.markUnsatisfied = function () {
278 this.satisfied = false;
281 UnaryConstraint.prototype.inputsKnown = function () {
285 UnaryConstraint.prototype.removeFromGraph = function () {
286 if (this.myOutput != null) this.myOutput.removeConstraint(this);
287 this.satisfied = false;
291 * S t a y C o n s t r a i n t
295 * Variables that should, with some level of preference, stay the same.
296 * Planners may exploit the fact that instances, if satisfied, will not
297 * change their output during plan execution. This is called "stay
300 function StayConstraint(v, str) {
301 StayConstraint.superConstructor.call(this, v, str);
304 StayConstraint.inheritsFrom(UnaryConstraint);
306 StayConstraint.prototype.execute = function () {
307 // Stay constraints do nothing
311 * E d i t C o n s t r a i n t
315 * A unary input constraint used to mark a variable that the client
318 function EditConstraint(v, str) {
319 EditConstraint.superConstructor.call(this, v, str);
322 EditConstraint.inheritsFrom(UnaryConstraint);
325 * Edits indicate that a variable is to be changed by imperative code.
327 EditConstraint.prototype.isInput = function () {
331 EditConstraint.prototype.execute = function () {
332 // Edit constraints do nothing
336 * B i n a r y C o n s t r a i n t
339 var Direction = new Object();
341 Direction.FORWARD = 1;
342 Direction.BACKWARD = -1;
345 * Abstract superclass for constraints having two possible output
348 function BinaryConstraint(var1, var2, strength) {
349 BinaryConstraint.superConstructor.call(this, strength);
352 this.direction = Direction.NONE;
353 this.addConstraint();
356 BinaryConstraint.inheritsFrom(Constraint);
359 * Decides if this constraint can be satisfied and which way it
360 * should flow based on the relative strength of the variables related,
361 * and record that decision.
363 BinaryConstraint.prototype.chooseMethod = function (mark) {
364 if (this.v1.mark == mark) {
365 this.direction = (this.v2.mark != mark && Strength.stronger(this.strength, this.v2.walkStrength))
369 if (this.v2.mark == mark) {
370 this.direction = (this.v1.mark != mark && Strength.stronger(this.strength, this.v1.walkStrength))
374 if (Strength.weaker(this.v1.walkStrength, this.v2.walkStrength)) {
375 this.direction = Strength.stronger(this.strength, this.v1.walkStrength)
379 this.direction = Strength.stronger(this.strength, this.v2.walkStrength)
386 * Add this constraint to the constraint graph
388 BinaryConstraint.prototype.addToGraph = function () {
389 this.v1.addConstraint(this);
390 this.v2.addConstraint(this);
391 this.direction = Direction.NONE;
395 * Answer true if this constraint is satisfied in the current solution.
397 BinaryConstraint.prototype.isSatisfied = function () {
398 return this.direction != Direction.NONE;
402 * Mark the input variable with the given mark.
404 BinaryConstraint.prototype.markInputs = function (mark) {
405 this.input().mark = mark;
409 * Returns the current input variable
411 BinaryConstraint.prototype.input = function () {
412 return (this.direction == Direction.FORWARD) ? this.v1 : this.v2;
416 * Returns the current output variable
418 BinaryConstraint.prototype.output = function () {
419 return (this.direction == Direction.FORWARD) ? this.v2 : this.v1;
423 * Calculate the walkabout strength, the stay flag, and, if it is
424 * 'stay', the value for the current output of this
425 * constraint. Assume this constraint is satisfied.
427 BinaryConstraint.prototype.recalculate = function () {
428 var ihn = this.input(), out = this.output();
429 out.walkStrength = Strength.weakestOf(this.strength, ihn.walkStrength);
431 if (out.stay) this.execute();
435 * Record the fact that this constraint is unsatisfied.
437 BinaryConstraint.prototype.markUnsatisfied = function () {
438 this.direction = Direction.NONE;
441 BinaryConstraint.prototype.inputsKnown = function (mark) {
442 var i = this.input();
443 return i.mark == mark || i.stay || i.determinedBy == null;
446 BinaryConstraint.prototype.removeFromGraph = function () {
447 if (this.v1 != null) this.v1.removeConstraint(this);
448 if (this.v2 != null) this.v2.removeConstraint(this);
449 this.direction = Direction.NONE;
453 * S c a l e C o n s t r a i n t
457 * Relates two variables by the linear scaling relationship: "v2 =
458 * (v1 * scale) + offset". Either v1 or v2 may be changed to maintain
459 * this relationship but the scale factor and offset are considered
462 function ScaleConstraint(src, scale, offset, dest, strength) {
463 this.direction = Direction.NONE;
465 this.offset = offset;
466 ScaleConstraint.superConstructor.call(this, src, dest, strength);
469 ScaleConstraint.inheritsFrom(BinaryConstraint);
472 * Adds this constraint to the constraint graph.
474 ScaleConstraint.prototype.addToGraph = function () {
475 ScaleConstraint.superConstructor.prototype.addToGraph.call(this);
476 this.scale.addConstraint(this);
477 this.offset.addConstraint(this);
480 ScaleConstraint.prototype.removeFromGraph = function () {
481 ScaleConstraint.superConstructor.prototype.removeFromGraph.call(this);
482 if (this.scale != null) this.scale.removeConstraint(this);
483 if (this.offset != null) this.offset.removeConstraint(this);
486 ScaleConstraint.prototype.markInputs = function (mark) {
487 ScaleConstraint.superConstructor.prototype.markInputs.call(this, mark);
488 this.scale.mark = this.offset.mark = mark;
492 * Enforce this constraint. Assume that it is satisfied.
494 ScaleConstraint.prototype.execute = function () {
495 if (this.direction == Direction.FORWARD) {
496 this.v2.value = this.v1.value * this.scale.value + this.offset.value;
498 this.v1.value = (this.v2.value - this.offset.value) / this.scale.value;
503 * Calculate the walkabout strength, the stay flag, and, if it is
504 * 'stay', the value for the current output of this constraint. Assume
505 * this constraint is satisfied.
507 ScaleConstraint.prototype.recalculate = function () {
508 var ihn = this.input(), out = this.output();
509 out.walkStrength = Strength.weakestOf(this.strength, ihn.walkStrength);
510 out.stay = ihn.stay && this.scale.stay && this.offset.stay;
511 if (out.stay) this.execute();
515 * E q u a l i t y C o n s t r a i n t
519 * Constrains two variables to have the same value.
521 function EqualityConstraint(var1, var2, strength) {
522 EqualityConstraint.superConstructor.call(this, var1, var2, strength);
525 EqualityConstraint.inheritsFrom(BinaryConstraint);
528 * Enforce this constraint. Assume that it is satisfied.
530 EqualityConstraint.prototype.execute = function () {
531 this.output().value = this.input().value;
539 * A constrained variable. In addition to its value, it maintain the
540 * structure of the constraint graph, the current dataflow graph, and
541 * various parameters of interest to the DeltaBlue incremental
544 function Variable(name, initialValue) {
545 this.value = initialValue || 0;
546 this.constraints = new OrderedCollection();
547 this.determinedBy = null;
549 this.walkStrength = Strength.WEAKEST;
555 * Add the given constraint to the set of all constraints that refer
558 Variable.prototype.addConstraint = function (c) {
559 this.constraints.add(c);
563 * Removes all traces of c from this variable.
565 Variable.prototype.removeConstraint = function (c) {
566 this.constraints.remove(c);
567 if (this.determinedBy == c) this.determinedBy = null;
575 * The DeltaBlue planner
578 this.currentMark = 0;
582 * Attempt to satisfy the given constraint and, if successful,
583 * incrementally update the dataflow graph. Details: If satifying
584 * the constraint is successful, it may override a weaker constraint
585 * on its output. The algorithm attempts to resatisfy that
586 * constraint using some other method. This process is repeated
587 * until either a) it reaches a variable that was not previously
588 * determined by any constraint or b) it reaches a constraint that
589 * is too weak to be satisfied using any of its methods. The
590 * variables of constraints that have been processed are marked with
591 * a unique mark value so that we know where we've been. This allows
592 * the algorithm to avoid getting into an infinite loop even if the
593 * constraint graph has an inadvertent cycle.
595 Planner.prototype.incrementalAdd = function (c) {
596 var mark = this.newMark();
597 var overridden = c.satisfy(mark);
598 while (overridden != null)
599 overridden = overridden.satisfy(mark);
603 * Entry point for retracting a constraint. Remove the given
604 * constraint and incrementally update the dataflow graph.
605 * Details: Retracting the given constraint may allow some currently
606 * unsatisfiable downstream constraint to be satisfied. We therefore collect
607 * a list of unsatisfied downstream constraints and attempt to
608 * satisfy each one in turn. This list is traversed by constraint
609 * strength, strongest first, as a heuristic for avoiding
610 * unnecessarily adding and then overriding weak constraints.
611 * Assume: c is satisfied.
613 Planner.prototype.incrementalRemove = function (c) {
614 var out = c.output();
617 var unsatisfied = this.removePropagateFrom(out);
618 var strength = Strength.REQUIRED;
620 for (var i = 0; i < unsatisfied.size(); i++) {
621 var u = unsatisfied.at(i);
622 if (u.strength == strength)
623 this.incrementalAdd(u);
625 strength = strength.nextWeaker();
626 } while (strength != Strength.WEAKEST);
630 * Select a previously unused mark value.
632 Planner.prototype.newMark = function () {
633 return ++this.currentMark;
637 * Extract a plan for resatisfaction starting from the given source
638 * constraints, usually a set of input constraints. This method
639 * assumes that stay optimization is desired; the plan will contain
640 * only constraints whose output variables are not stay. Constraints
641 * that do no computation, such as stay and edit constraints, are
642 * not included in the plan.
643 * Details: The outputs of a constraint are marked when it is added
644 * to the plan under construction. A constraint may be appended to
645 * the plan when all its input variables are known. A variable is
646 * known if either a) the variable is marked (indicating that has
647 * been computed by a constraint appearing earlier in the plan), b)
648 * the variable is 'stay' (i.e. it is a constant at plan execution
649 * time), or c) the variable is not determined by any
650 * constraint. The last provision is for past states of history
651 * variables, which are not stay but which are also not computed by
653 * Assume: sources are all satisfied.
655 Planner.prototype.makePlan = function (sources) {
656 var mark = this.newMark();
657 var plan = new Plan();
659 while (todo.size() > 0) {
660 var c = todo.removeFirst();
661 if (c.output().mark != mark && c.inputsKnown(mark)) {
662 plan.addConstraint(c);
663 c.output().mark = mark;
664 this.addConstraintsConsumingTo(c.output(), todo);
671 * Extract a plan for resatisfying starting from the output of the
672 * given constraints, usually a set of input constraints.
674 Planner.prototype.extractPlanFromConstraints = function (constraints) {
675 var sources = new OrderedCollection();
676 for (var i = 0; i < constraints.size(); i++) {
677 try { exception(); } catch(e) { }
678 var c = constraints.at(i);
679 try { exception(); } catch(e) { }
680 if (c.isInput() && c.isSatisfied())
681 // not in plan already and eligible for inclusion
684 return this.makePlan(sources);
688 * Recompute the walkabout strengths and stay flags of all variables
689 * downstream of the given constraint and recompute the actual
690 * values of all variables whose stay flag is true. If a cycle is
691 * detected, remove the given constraint and answer
692 * false. Otherwise, answer true.
693 * Details: Cycles are detected when a marked variable is
694 * encountered downstream of the given constraint. The sender is
695 * assumed to have marked the inputs of the given constraint with
696 * the given mark. Thus, encountering a marked node downstream of
697 * the output constraint means that there is a path from the
698 * constraint's output to one of its inputs.
700 Planner.prototype.addPropagate = function (c, mark) {
701 var todo = new OrderedCollection();
703 while (todo.size() > 0) {
704 var d = todo.removeFirst();
705 if (d.output().mark == mark) {
706 this.incrementalRemove(c);
710 this.addConstraintsConsumingTo(d.output(), todo);
717 * Update the walkabout strengths and stay flags of all variables
718 * downstream of the given constraint. Answer a collection of
719 * unsatisfied constraints sorted in order of decreasing strength.
721 Planner.prototype.removePropagateFrom = function (out) {
722 out.determinedBy = null;
723 out.walkStrength = Strength.WEAKEST;
725 var unsatisfied = new OrderedCollection();
726 var todo = new OrderedCollection();
728 while (todo.size() > 0) {
729 var v = todo.removeFirst();
730 for (var i = 0; i < v.constraints.size(); i++) {
731 var c = v.constraints.at(i);
732 try { exception(); } catch(e) { }
733 if (!c.isSatisfied())
736 var determining = v.determinedBy;
737 for (var i = 0; i < v.constraints.size(); i++) {
738 var next = v.constraints.at(i);
739 if (next != determining && next.isSatisfied()) {
741 todo.add(next.output());
743 try { exception(); } catch(e) { }
749 Planner.prototype.addConstraintsConsumingTo = function (v, coll) {
750 var determining = v.determinedBy;
751 var cc = v.constraints;
752 for (var i = 0; i < cc.size(); i++) {
754 try { exception(); } catch(e) { }
755 if (c != determining && c.isSatisfied())
765 * A Plan is an ordered list of constraints to be executed in sequence
766 * to resatisfy all currently satisfiable constraints in the face of
767 * one or more changing inputs.
770 this.v = new OrderedCollection();
773 Plan.prototype.addConstraint = function (c) {
777 Plan.prototype.size = function () {
778 return this.v.size();
781 Plan.prototype.constraintAt = function (index) {
782 return this.v.at(index);
785 Plan.prototype.execute = function () {
786 for (var i = 0; i < this.size(); i++) {
787 var c = this.constraintAt(i);
788 try { exception(); } catch(e) { }
798 * This is the standard DeltaBlue benchmark. A long chain of equality
799 * constraints is constructed with a stay constraint on one end. An
800 * edit constraint is then added to the opposite end and the time is
801 * measured for adding and removing this constraint, and extracting
802 * and executing a constraint satisfaction plan. There are two cases.
803 * In case 1, the added constraint is stronger than the stay
804 * constraint and values must propagate down the entire length of the
805 * chain. In case 2, the added constraint is weaker than the stay
806 * constraint so it cannot be accomodated. The cost in this case is,
807 * of course, very low. Typical situations lie somewhere between these
810 function chainTest(n) {
811 planner = new Planner();
812 var prev = null, first = null, last = null;
814 // Build chain of n equality constraints
815 for (var i = 0; i <= n; i++) {
817 var v = new Variable(name);
819 new EqualityConstraint(prev, v, Strength.REQUIRED);
820 if (i == 0) first = v;
821 if (i == n) last = v;
822 try { exception(); } catch(e) { }
826 new StayConstraint(last, Strength.STRONG_DEFAULT);
827 var edit = new EditConstraint(first, Strength.PREFERRED);
828 var edits = new OrderedCollection();
830 var plan = planner.extractPlanFromConstraints(edits);
831 for (var i = 0; i < 100; i++) {
835 alert("Chain test failed.");
836 try { exception(); } catch(e) { }
841 * This test constructs a two sets of variables related to each
842 * other by a simple linear transformation (scale and offset). The
843 * time is measured to change a variable on either side of the
844 * mapping and to change the scale and offset factors.
846 function projectionTest(n) {
847 planner = new Planner();
848 var scale = new Variable("scale", 10);
849 var offset = new Variable("offset", 1000);
850 var src = null, dst = null;
852 var dests = new OrderedCollection();
853 for (var i = 0; i < n; i++) {
854 src = new Variable("src" + i, i);
855 dst = new Variable("dst" + i, i);
857 try { exception(); } catch(e) { }
858 new StayConstraint(src, Strength.NORMAL);
859 new ScaleConstraint(src, scale, offset, dst, Strength.REQUIRED);
863 if (dst.value != 1170) alert("Projection 1 failed");
865 if (src.value != 5) alert("Projection 2 failed");
867 for (var i = 0; i < n - 1; i++) {
868 if (dests.at(i).value != i * 5 + 1000)
869 alert("Projection 3 failed");
870 try { exception(); } catch(e) { }
872 change(offset, 2000);
873 for (var i = 0; i < n - 1; i++) {
874 if (dests.at(i).value != i * 5 + 2000)
875 alert("Projection 4 failed");
876 try { exception(); } catch(e) { }
880 function change(v, newValue) {
881 var edit = new EditConstraint(v, Strength.PREFERRED);
882 var edits = new OrderedCollection();
884 var plan = planner.extractPlanFromConstraints(edits);
885 for (var i = 0; i < 10; i++) {
889 edit.destroyConstraint();
892 // Global variable holding the current planner.
895 function deltaBlue() {
901 let start = Date.now();
902 for (let i = 0; i < 50; ++i)