1 // Copyright 2006 all rights reserved; see LICENSE file for BSD-style license
3 package edu.berkeley.sbp;
4 import edu.berkeley.sbp.*;
5 import edu.berkeley.sbp.util.*;
6 import edu.berkeley.sbp.Parser.Table.*;
7 import edu.berkeley.sbp.Sequence.Position;
10 import java.lang.reflect.*;
12 final class Reduction implements Comparable<Reduction> {
14 public Position position;
15 public GSS.Phase phase;
20 public Reduction(Node node, Position position, Forest result, GSS.Phase target) {
21 this.position = position;
25 target.reductionQueue.add(this);
28 public void perform() {
31 node.finish(position, result, phase);
34 public int compareTo(Reduction r) {
35 int ret = compareTo0(r);
37 Walk.Cache cache = node.state().cache();
38 if (canKill(cache, position, r.position) && canKill(cache, r.position, position)) throw new Error();
39 if (canKill(cache, position, r.position)) ret = 1;
40 else if (canKill(cache, r.position, position)) ret = -1;
41 if (canNeed(cache, position, r.position)) ret = 1;
42 else if (canNeed(cache, r.position, position)) ret = -1;
47 private static boolean isRightNullable(Walk.Cache c, Position p) {
48 if (p.isLast()) return true;
49 if (!c.possiblyEpsilon(p.element())) return false;
50 return isRightNullable(c, p.next());
53 public static boolean canKill(Walk.Cache cache, Position mep, Position himp) {
54 if (!isRightNullable(cache, mep)) return false;
55 if (!isRightNullable(cache, himp)) return false;
56 Sequence me = mep.owner();
57 Sequence him = himp.owner();
58 for(Sequence killer : him.hates()) {
59 HashSet<Sequence> eq2 = new Walk.EquivalentTo(killer, cache).walk();
60 if (eq2.contains(me)) return true;
65 public static final int LESS_THAN = -1;
66 public static final int EQUAL_TO = 0;
67 public static final int GREATER_THAN = 1;
69 public int compareTo0(Reduction n) {
70 if (targetPhase()==null && n.targetPhase()==null) return EQUAL_TO;
71 if (targetPhase()==null) return LESS_THAN;
72 if (n.targetPhase()==null) return GREATER_THAN;
73 if (targetPhase().pos < n.targetPhase().pos) return LESS_THAN;
74 if (targetPhase().pos > n.targetPhase().pos) return GREATER_THAN;
77 public int pos() { return targetPhase()==null ? 0 : targetPhase().pos; }
78 public GSS.Phase targetPhase() { return node.phase(); }
80 public static boolean canNeed(Walk.Cache cache, Position mep, Position himp) {
81 if (!isRightNullable(cache, mep)) return false;
82 if (!isRightNullable(cache, himp)) return false;
83 Sequence me = mep.owner();
84 Sequence him = himp.owner();
85 for(Sequence needer : him.needs()) {
86 HashSet<Sequence> eq2 = new Walk.EquivalentTo(needer, cache).walk();
87 if (eq2.contains(me)) return true;