01: package org.kohsuke.rngom.binary;
02:
03: public class PatternBuilder {
04: private final EmptyPattern empty;
05: protected final NotAllowedPattern notAllowed;
06: protected final PatternInterner interner;
07:
08: public PatternBuilder() {
09: empty = new EmptyPattern();
10: notAllowed = new NotAllowedPattern();
11: interner = new PatternInterner();
12: }
13:
14: public PatternBuilder(PatternBuilder parent) {
15: empty = parent.empty;
16: notAllowed = parent.notAllowed;
17: interner = new PatternInterner(parent.interner);
18: }
19:
20: Pattern makeEmpty() {
21: return empty;
22: }
23:
24: Pattern makeNotAllowed() {
25: return notAllowed;
26: }
27:
28: Pattern makeGroup(Pattern p1, Pattern p2) {
29: if (p1 == empty)
30: return p2;
31: if (p2 == empty)
32: return p1;
33: if (p1 == notAllowed || p2 == notAllowed)
34: return notAllowed;
35: if (false && p1 instanceof GroupPattern) {
36: GroupPattern sp = (GroupPattern) p1;
37: return makeGroup(sp.p1, makeGroup(sp.p2, p2));
38: }
39: Pattern p = new GroupPattern(p1, p2);
40: return interner.intern(p);
41: }
42:
43: Pattern makeInterleave(Pattern p1, Pattern p2) {
44: if (p1 == empty)
45: return p2;
46: if (p2 == empty)
47: return p1;
48: if (p1 == notAllowed || p2 == notAllowed)
49: return notAllowed;
50: if (false && p1 instanceof InterleavePattern) {
51: InterleavePattern ip = (InterleavePattern) p1;
52: return makeInterleave(ip.p1, makeInterleave(ip.p2, p2));
53: }
54: if (false) {
55: if (p2 instanceof InterleavePattern) {
56: InterleavePattern ip = (InterleavePattern) p2;
57: if (p1.hashCode() > ip.p1.hashCode())
58: return makeInterleave(ip.p1, makeInterleave(p1,
59: ip.p2));
60: } else if (p1.hashCode() > p2.hashCode())
61: return makeInterleave(p2, p1);
62: }
63: Pattern p = new InterleavePattern(p1, p2);
64: return interner.intern(p);
65: }
66:
67: Pattern makeChoice(Pattern p1, Pattern p2) {
68: if (p1 == empty && p2.isNullable())
69: return p2;
70: if (p2 == empty && p1.isNullable())
71: return p1;
72: Pattern p = new ChoicePattern(p1, p2);
73: return interner.intern(p);
74: }
75:
76: Pattern makeOneOrMore(Pattern p) {
77: if (p == empty || p == notAllowed
78: || p instanceof OneOrMorePattern)
79: return p;
80: Pattern p1 = new OneOrMorePattern(p);
81: return interner.intern(p1);
82: }
83:
84: Pattern makeOptional(Pattern p) {
85: return makeChoice(p, empty);
86: }
87:
88: Pattern makeZeroOrMore(Pattern p) {
89: return makeOptional(makeOneOrMore(p));
90: }
91: }
|