/
Blackthorne.java
356 lines (317 loc) · 12 KB
/
Blackthorne.java
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
/*
* Copyright © 2019 Mark Raynsford <code@io7m.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.blackthorne.api;
import com.io7m.jlexing.core.LexicalPosition;
import com.io7m.junreachable.UnreachableCodeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.function.Function;
import static com.io7m.blackthorne.api.BTParseErrorType.Severity.ERROR;
/**
* Convenience functions.
*/
public final class Blackthorne
{
private static final Logger LOG =
LoggerFactory.getLogger(Blackthorne.class);
private Blackthorne()
{
throw new UnreachableCodeException();
}
/**
* Functor map for handlers.
*
* @param handler The handler
* @param function A function to apply to the result of handlers produced by {@code constructor}
* @param <CT> The type of child handler values
* @param <RT> The type of result values
* @param <RX> The type of mapped result values
*
* @return A new handler
*/
public static <CT, RT, RX> BTElementHandlerType<CT, RX> map(
final BTElementHandlerType<CT, RT> handler,
final Function<RT, RX> function)
{
return handler.map(function);
}
/**
* Type widening for handlers. If {@code RX <: RT}, then any handler that produces a value of
* {@code RX} implicitly produces a value of {@code RT}.
*
* @param handler The handler
* @param <CT> The type of child handler values
* @param <RT> The type of result values
* @param <RX> A subtype of result values
*
* @return A widened handler
*/
@SuppressWarnings("unchecked")
public static <CT, RT, RX extends RT> BTElementHandlerType<CT, RT> widen(
final BTElementHandlerType<CT, RX> handler)
{
return (BTElementHandlerType<CT, RT>) handler;
}
/**
* Functor map for handler constructors.
*
* @param constructor The handler constructor
* @param function A function to apply to the result of handlers produced by {@code
* constructor}
* @param <CT> The type of child handler values
* @param <RT> The type of result values
* @param <RX> The type of mapped result values
*
* @return A new handler constructor
*/
public static <CT, RT, RX> BTElementHandlerConstructorType<CT, RX> mapConstructor(
final BTElementHandlerConstructorType<CT, RT> constructor,
final Function<RT, RX> function)
{
return context -> {
@SuppressWarnings("unchecked") final var newHandler =
(BTElementHandlerType<CT, RT>) constructor.create(context);
return (BTElementHandlerType<CT, RX>) map(newHandler, function);
};
}
/**
* Type widening for handler constructors. If {@code RX <: RT}, then any handler that produces a
* value of {@code RX} implicitly produces a value of {@code RT}.
*
* @param constructor The handler
* @param <CT> The type of child handler values
* @param <RT> The type of result values
* @param <RX> A subtype of result values
*
* @return A widened handler constructor
*/
@SuppressWarnings("unchecked")
public static <CT, RT, RX extends RT> BTElementHandlerConstructorType<CT, RT> widenConstructor(
final BTElementHandlerConstructorType<CT, RX> constructor)
{
return (BTElementHandlerConstructorType<CT, RT>) constructor;
}
/**
* A convenience function for constructing content handlers that produce a scalar value from the
* text content of a single XML element.
*
* @param elementName The name of the element
* @param parser A function that receives text and returns a value of type {@code S}
* @param <S> The type of returned scalar values
*
* @return A content handler constructor
*/
public static <S> BTElementHandlerConstructorType<?, S> forScalar(
final BTQualifiedName elementName,
final BTCharacterHandlerType<S> parser)
{
Objects.requireNonNull(elementName, "elementName");
Objects.requireNonNull(parser, "parser");
return context -> new BTScalarElementHandler<>(elementName, parser);
}
/**
* A convenience function for constructing content handlers that produce a scalar value from the
* text content of a single XML element.
*
* @param namespaceURI The namespace of the element
* @param localName The local element name
* @param parser A function that receives text and returns a value of type {@code S}
* @param <S> The type of returned scalar values
*
* @return A content handler constructor
*/
public static <S> BTElementHandlerConstructorType<?, S> forScalar(
final String namespaceURI,
final String localName,
final BTCharacterHandlerType<S> parser)
{
Objects.requireNonNull(namespaceURI, "namespaceURI");
Objects.requireNonNull(localName, "localName");
Objects.requireNonNull(parser, "parser");
return forScalar(BTQualifiedName.of(namespaceURI, localName), parser);
}
/**
* A convenience function for constructing content handlers that produce a scalar value from the
* text content of a single XML element.
*
* @param elementName The name of the element
* @param parser A function that receives attributes and returns a value of type {@code S}
* @param <S> The type of returned scalar values
*
* @return A content handler constructor
*/
public static <S> BTElementHandlerConstructorType<?, S> forScalarAttribute(
final BTQualifiedName elementName,
final BTAttributesHandlerType<S> parser)
{
Objects.requireNonNull(elementName, "elementName");
Objects.requireNonNull(parser, "parser");
return context -> new BTScalarAttributeHandler<>(elementName, parser);
}
/**
* A convenience function for constructing content handlers that produce a scalar value from the
* text content of a single XML element.
*
* @param namespaceURI The namespace of the element
* @param localName The local element name
* @param parser A function that receives attributes and returns a value of type {@code S}
* @param <S> The type of returned scalar values
*
* @return A content handler constructor
*/
public static <S> BTElementHandlerConstructorType<?, S> forScalarAttribute(
final String namespaceURI,
final String localName,
final BTAttributesHandlerType<S> parser)
{
Objects.requireNonNull(namespaceURI, "namespaceURI");
Objects.requireNonNull(localName, "localName");
Objects.requireNonNull(parser, "parser");
return forScalarAttribute(
BTQualifiedName.of(namespaceURI, localName),
parser);
}
/**
* A convenience function for constructing content handlers that produce lists of values from the
* child elements of a single element. All child elements are expected to be of the same type.
*
* @param elementName The name of the element
* @param childElementName The name of the child element
* @param itemHandler A handler for child elements
* @param ignoreUnrecognized Whether or not unrecognized child elements should be ignored
* @param <S> The type of returned scalar values
*
* @return A content handler constructor
*/
public static <S> BTElementHandlerConstructorType<S, List<S>> forListMono(
final BTQualifiedName elementName,
final BTQualifiedName childElementName,
final BTElementHandlerConstructorType<?, ? extends S> itemHandler,
final BTIgnoreUnrecognizedElements ignoreUnrecognized)
{
Objects.requireNonNull(elementName, "elementName");
Objects.requireNonNull(childElementName, "childElementName");
Objects.requireNonNull(itemHandler, "itemHandler");
return context ->
new BTListMonoHandler<>(
elementName,
childElementName,
itemHandler,
ignoreUnrecognized);
}
/**
* A convenience function for constructing content handlers that produce lists of values from the
* child elements of a single element. Child elements may be of different types, but values
* produced by the content handlers for the child elements must have a common supertype.
*
* @param elementName The name of the element
* @param itemHandlers Handlers for child elements
* @param ignoreUnrecognized Whether or not unrecognized child elements should be ignored
* @param <S> The type of returned scalar values
*
* @return A content handler constructor
*/
public static <S> BTElementHandlerConstructorType<S, List<S>> forListPoly(
final BTQualifiedName elementName,
final Map<BTQualifiedName, BTElementHandlerConstructorType<?, ? extends S>> itemHandlers,
final BTIgnoreUnrecognizedElements ignoreUnrecognized)
{
Objects.requireNonNull(elementName, "elementName");
Objects.requireNonNull(itemHandlers, "itemHandlers");
return context -> new BTListPolyHandler<S>(
elementName,
itemHandlers,
ignoreUnrecognized);
}
/**
* A convenience method to configure and execute a parser.
*
* @param source The source URI
* @param stream The input stream
* @param xmlReaders A supplier of XML readers
* @param rootElements The root element handlers
* @param <T> The type of returned values
*
* @return The parsed value
*
* @throws BTException On parse errors
*/
public static <T> T parse(
final URI source,
final InputStream stream,
final Callable<XMLReader> xmlReaders,
final Map<BTQualifiedName, BTElementHandlerConstructorType<?, T>> rootElements)
throws BTException
{
final var errors =
new ArrayList<BTParseError>(32);
final var contentHandler =
new BTContentHandler<>(source, errors::add, rootElements);
try {
final var reader = xmlReaders.call();
reader.setContentHandler(contentHandler);
reader.setErrorHandler(contentHandler);
final var inputSource = new InputSource(stream);
inputSource.setPublicId(source.toString());
reader.parse(inputSource);
final var resultOpt = contentHandler.result();
if (resultOpt.isEmpty()) {
throw new BTException("Parse failed.", new IOException(), errors);
}
return resultOpt.get();
} catch (final SAXParseException e) {
LOG.error("error encountered during parsing: ", e);
final var position =
LexicalPosition.of(
e.getLineNumber(),
e.getColumnNumber(),
Optional.of(source)
);
errors.add(
BTParseError.builder()
.setLexical(position)
.setSeverity(ERROR)
.setMessage(e.getMessage())
.build()
);
throw new BTException(e.getMessage(), e, errors);
} catch (final Exception e) {
LOG.error("error encountered during parsing: ", e);
final var position =
LexicalPosition.of(-1, -1, Optional.of(source));
errors.add(
BTParseError.builder()
.setLexical(position)
.setSeverity(ERROR)
.setMessage(e.getMessage())
.build()
);
throw new BTException(e.getMessage(), e, errors);
}
}
}