]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.scl.runtime/src/org/simantics/scl/runtime/chr/CHRPriority.java
(refs #7250) Refactoring CHR implementation
[simantics/platform.git] / bundles / org.simantics.scl.runtime / src / org / simantics / scl / runtime / chr / CHRPriority.java
1 package org.simantics.scl.runtime.chr;
2
3 /**
4  * This class implements a pairing heap of CHR priorities.
5  */
6 public abstract class CHRPriority implements Comparable<CHRPriority> {
7     
8     public final int priority;
9     
10     // Pairing heap
11     private CHRPriority sibling;
12     private CHRPriority child;
13     
14     boolean inContext;
15     
16     public CHRPriority(int priority) {
17         this.priority = priority;
18     }
19     
20     /**
21      * This method assume that a and b are roots and their sibling field
22      * can be overridden. 
23      */
24     public static CHRPriority merge(CHRPriority a, CHRPriority b) {
25         if(a.priority <= b.priority) {
26             a.sibling = null;
27             b.sibling = a.child;
28             a.child = b;
29             return a;
30         }
31         else {
32             a.sibling = b.child;
33             b.sibling = null;
34             b.child = a;
35             return b;
36         }
37     }
38     
39     protected void ensureInContext(CHRContext context) {
40         if(!inContext) {
41             CHRPriority topPriority = context.topPriority;
42             if(topPriority == null)
43                 context.topPriority = this;
44             else
45                 context.topPriority = merge(topPriority, this);
46             inContext = true;
47         }
48     }
49     
50     private CHRPriority mergeSiblings() {
51         if(sibling == null)
52             return this;
53         CHRPriority nextSibling = sibling.sibling;
54         CHRPriority merged = merge(this, sibling);
55         if(nextSibling == null)
56             return merged;
57         else
58             return merge(merged, nextSibling.mergeSiblings());
59     }
60     
61     public CHRPriority nextPriority() {
62         if(child == null)
63             return null;
64         else {
65             CHRPriority result = child.mergeSiblings();
66             child = null;
67             return result;
68         }
69     }
70     
71     @Override
72     public int compareTo(CHRPriority o) {
73         return Double.compare(priority, o.priority);
74     }
75     
76     public abstract void activate(CHRContext context);
77     //public abstract CHRRuntimeRuleset getParent();
78 }