Debian Codegraph @

native/jpype_module/src/main/java/org/jpype/html/Parser.java

raw symbols SCIP
1 /* ****************************************************************************
2 Licensed under the Apache License, Version 2.0 (the "License");
3 you may not use this file except in compliance with the License.
4 You may obtain a copy of the License at
5
6 http://www.apache.org/licenses/LICENSE-2.0
7
8 Unless required by applicable law or agreed to in writing, software
9 distributed under the License is distributed on an "AS IS" BASIS,
10 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 See the License for the specific language governing permissions and
12 limitations under the License.
13
14 See NOTICE file for details.
15 **************************************************************************** */
16 package org.jpype.html;
17
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.nio.ByteBuffer;
21 import java.nio.channels.Channels;
22 import java.nio.channels.ReadableByteChannel;
23 import java.util.LinkedList;
24 import java.util.ListIterator;
25
26 /**
27 * Generic document parser.
28 *
29 * @param <T>
30 */
31 public class Parser<T>
32 {
33
34 final Grammar grammar;
35 public State state = null;
36 public Token last = null;
37 public Rule lookahead = null;
38 public LinkedList<Entity> stack = new LinkedList<>();
39
40 Parser(Grammar grammar)
41 {
42 this.grammar = grammar;
43 }
44
45 public T parse(InputStream is)
46 {
47 ByteBuffer incoming = ByteBuffer.allocate(1024);
48 ByteBuffer outgoing = ByteBuffer.allocate(1024);
49 ReadableByteChannel channel = Channels.newChannel(is);
50 stack.clear();
51 grammar.start(this);
52 try
53 {
54 while (true)
55 {
56 incoming.position(0);
57 int rc = channel.read(incoming);
58 if (rc < 0)
59 break;
60 int p = incoming.position();
61 incoming.rewind();
62 process(incoming, outgoing, rc);
63 }
64 flushTokens(outgoing);
65 } catch (IOException ex)
66 {
67 throw new RuntimeException(ex);
68 }
69 return (T) grammar.end(this);
70 }
71
72 public T parse(String str)
73 {
74 byte[] b = str.getBytes();
75 ByteBuffer incoming = ByteBuffer.wrap(b);
76 ByteBuffer outgoing = ByteBuffer.allocate(1024);
77 stack.clear();
78 grammar.start(this);
79 process(incoming, outgoing, b.length);
80 flushTokens(outgoing);
81 return (T) grammar.end(this);
82 }
83
84 private void process(ByteBuffer incoming, ByteBuffer outgoing, int rc)
85 {
86 while (incoming.position() < rc)
87 {
88 byte b = incoming.get();
89 Token match = null;
90 for (Token t : state.getTokens())
91 {
92 if (t.matches(b))
93 {
94 match = t;
95 break;
96 }
97 }
98 if (match == null)
99 this.error("Unable to parse " + (char) b);
100 else if (match.runs())
101 {
102 if (last != match)
103 flushTokens(outgoing);
104 if (!outgoing.hasRemaining())
105 flushTokens(outgoing);
106 outgoing.put(b);
107 } else
108 {
109 if (outgoing.position() > 0)
110 flushTokens(outgoing);
111 processToken(match, null);
112 }
113 last = match;
114 }
115 }
116
117 /**
118 * Send all the queue up text to a token.
119 */
120 private void flushTokens(ByteBuffer outgoing)
121 {
122 if (outgoing.position() == 0)
123 return;
124 processToken(last, new String(outgoing.array(), 0, outgoing.position()));
125 outgoing.rewind();
126 }
127
128 /**
129 * Process a token.
130 *
131 * This will add it to the stack and then match the stack with the nearest
132 * rule.
133 *
134 * @param token
135 * @param value
136 */
137 protected void processToken(Token token, String value)
138 {
139 if (token == null)
140 return;
141 Entity entity = add(token, value);
142
143 // Take the next lookahead
144 Rule rule1 = this.lookahead;
145 this.lookahead = null;
146 if (rule1 != null)
147 {
148 // System.out.println(" FORWARD " + rule1);
149 if (rule1.apply(this, entity))
150 {
151 return;
152 }
153 }
154
155 // If not handled then proceed to rules.
156 boolean done = false;
157 while (!done && !stack.isEmpty())
158 {
159 done = true;
160 for (Rule rule : state.getRules())
161 {
162 // System.out.println(" RULE " + rule);
163 if (rule.apply(this, stack.getLast()))
164 {
165 done = false;
166 break;
167 }
168 }
169 }
170 }
171
172 /**
173 * Add a token to the token stack
174 *
175 * @param token
176 * @param object
177 * @return
178 */
179 public Entity add(Token token, String object)
180 {
181 Entity entity = new Entity(token, object);
182 this.stack.add(entity);
183 return entity;
184 }
185
186 public void error(String bad_token)
187 {
188 throw new RuntimeException("bad_token");
189 }
190
191 public interface State
192 {
193
194 Token[] getTokens();
195
196 Rule[] getRules();
197 }
198
199 public interface Token
200 {
201
202 int ordinal();
203
204 public boolean matches(byte b);
205
206 public boolean runs();
207 }
208
209 public interface Rule
210 {
211
212 boolean apply(Parser<?> parser, Entity entity);
213 }
214
215 public interface Grammar
216 {
217
218 /**
219 * Should set the initial state.
220 *
221 * @param p
222 */
223 public void start(Parser p);
224
225 /**
226 * Should check the state of the stack, fail if bad, or return the final
227 * object if good.
228 *
229 * @param p
230 * @return
231 */
232 public Object end(Parser p);
233 }
234
235 /**
236 * Token or text.
237 */
238 public static class Entity
239 {
240
241 public Token token;
242 public Object value;
243
244 private Entity(Token token)
245 {
246 this.token = token;
247 }
248
249 private Entity(Token token, String value)
250 {
251 this.token = token;
252 this.value = value;
253 }
254
255 @Override
256 public String toString()
257 {
258 if (value == null)
259 return token.toString();
260 return value.toString();
261 }
262 }
263
264 //<editor-fold desc="common">
265 /**
266 * Generic matcher for multiple tokens on the stack.
267 */
268 abstract static class MatchRule implements Rule
269 {
270
271 Token[] pattern;
272
273 MatchRule(Token... tokens)
274 {
275 this.pattern = tokens;
276 }
277
278 @Override
279 public boolean apply(Parser parser, Entity entity)
280 {
281 LinkedList<Entity> stack = parser.stack;
282 int n = stack.size();
283 if (n < pattern.length)
284 return false;
285 ListIterator<Entity> iter = stack.listIterator(stack.size());
286 for (int i = 0; i < pattern.length; ++i)
287 {
288 if (!iter.hasPrevious())
289 return false;
290 Entity next = iter.previous();
291 if (next.token != pattern[pattern.length - i - 1])
292 {
293 return false;
294 }
295 }
296 execute(parser);
297 return true;
298 }
299
300 abstract public void execute(Parser parser);
301 }
302
303 //</editor-fold>
304 }