JAL-1807 Bob's JalviewJS prototype first commit
[jalviewjs.git] / src / com / stevesoft / pat / Or.java
1 //
2 // This software is now distributed according to
3 // the Lesser Gnu Public License.  Please see
4 // http://www.gnu.org/copyleft/lesser.txt for
5 // the details.
6 //    -- Happy Computing!
7 //
8 package com.stevesoft.pat;
9
10 import java.util.*;
11
12 /**
13  * This class implements the (?: ... ) extended Pattern. It provides a base
14  * class from which we derive the [ ... ], ( ... ), (?! ... ), and (?= ... )
15  * patterns.
16  */
17 class Or extends Pattern
18 {
19   Vector v;
20
21   Pattern[] pv = null;
22
23   Or()
24   {
25     v = new Vector();
26   }
27
28   String leftForm()
29   {
30     return "(?:";
31   }
32
33   String rightForm()
34   {
35     return ")";
36   }
37
38   String sepForm()
39   {
40     return "|";
41   }
42
43   public Or addOr(Pattern p)
44   {
45     pv = null;
46     v.addElement(p);
47     p.setParent(this);
48     return this;
49   }
50
51   public String toString()
52   {
53     int i;
54     StringBuffer sb = new StringBuffer();
55     sb.append(leftForm());
56     if (v.size() > 0)
57     {
58       sb.append(((Pattern) v.elementAt(0)).toString());
59     }
60     for (i = 1; i < v.size(); i++)
61     {
62       sb.append(sepForm());
63       sb.append(((Pattern) v.elementAt(i)).toString());
64     }
65     sb.append(rightForm());
66     sb.append(nextString());
67     return sb.toString();
68   }
69
70   public int matchInternal(int pos, Pthings pt)
71   {
72     if (pv == null)
73     {
74       pv = new Pattern[v.size()];
75       v.copyInto(pv);
76     }
77     for (int i = 0; i < v.size(); i++)
78     {
79       Pattern p = pv[i]; // (Pattern)v.elementAt(i);
80       int r = p.matchInternal(pos, pt);
81       if (r >= 0)
82       {
83         return r;
84       }
85     }
86     return -1;
87   }
88
89   public patInt minChars()
90   {
91     if (v.size() == 0)
92     {
93       return new patInt(0);
94     }
95     patInt m = ((Pattern) v.elementAt(0)).countMinChars();
96     for (int i = 1; i < v.size(); i++)
97     {
98       Pattern p = (Pattern) v.elementAt(i);
99       m.mineq(p.countMinChars());
100     }
101     return m;
102   }
103
104   public patInt maxChars()
105   {
106     if (v.size() == 0)
107     {
108       return new patInt(0);
109     }
110     patInt m = ((Pattern) v.elementAt(0)).countMaxChars();
111     for (int i = 1; i < v.size(); i++)
112     {
113       Pattern p = (Pattern) v.elementAt(i);
114       m.maxeq(p.countMaxChars());
115     }
116     return m;
117   }
118
119   Pattern clone1(Hashtable h)
120   {
121     Or o = new Or();
122     h.put(this, o);
123     h.put(o, o);
124     for (int i = 0; i < v.size(); i++)
125     {
126       o.v.addElement(((Pattern) v.elementAt(i)).clone(h));
127     }
128     return o;
129   }
130 };