1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36 package oqube.muse;
37
38 import java.util.regex.Matcher;
39 import java.util.regex.Pattern;
40
41 /***
42 * This abstract class is the base class of all parsing elements
43 * in the Muse parser.
44 *
45 * The behavior of this class is controlled by its {@link parse(String)} method.
46 * This basic implementation is based on properties {@link #matcher} and {@link #next}: if the matcher
47 * matches the input string, then the method {@link #handler()} is called, else
48 * the input string is passed to next matcher in list.
49 *
50 *
51 * matches a given string
52 * @author abailly@oqube.muse.com
53 * @version $Id$
54 */
55 public abstract class AbstractLexer {
56
57
58 protected Matcher matcher;
59
60
61 protected AbstractLexer next;
62
63 public AbstractLexer getNext() {
64 return next;
65 }
66
67 public AbstractLexer setNext(AbstractLexer next) {
68 return this.next = next;
69 }
70
71 /***
72 * Instantiate the lexer with teh given pattern.
73 * @param pattern pattern matched by this lexer.
74 * @see java.util.regex.Pattern
75 */
76 public AbstractLexer(String pattern) {
77 this.matcher = Pattern.compile(pattern).matcher("");
78 }
79
80 /***
81 * Parse the given string.
82 * If string matches pattern, then the handler method is invoked,
83 * else if there is a next lexer in the chain, it gets called.
84 */
85 public void parse(String s) {
86 int i=0;
87 matcher.reset(s);
88 if(matcher.matches())
89 handler();
90 else if(next != null)
91 next.parse(s);
92 }
93
94 /***
95 * Return the matched matcher.
96 * @return first matcher matched in parse method. May be null if
97 * no match was found
98 */
99 public Matcher getMatcher() {
100 return matcher;
101 }
102
103 /***
104 * This method is invoked by the lexer if this lexer matches
105 * the input.
106 */
107 public abstract void handler();
108 }