1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package io.earcam.instrumental.module.osgi.parser;
20
21 import static java.nio.charset.StandardCharsets.UTF_8;
22
23 import java.io.InputStream;
24
25 import org.antlr.v4.runtime.CharStream;
26 import org.antlr.v4.runtime.BailErrorStrategy;
27 import org.antlr.v4.runtime.CharStreams;
28 import org.antlr.v4.runtime.CommonTokenStream;
29 import org.antlr.v4.runtime.TokenStream;
30 import org.antlr.v4.runtime.tree.ParseTree;
31 import org.antlr.v4.runtime.tree.ParseTreeListener;
32 import org.antlr.v4.runtime.tree.ParseTreeWalker;
33
34 import io.earcam.instrumental.module.osgi.BundleManifestHeaders;
35 import io.earcam.instrumental.module.osgi.parser.ManifestLexer;
36 import io.earcam.instrumental.module.osgi.parser.ManifestParser;
37 import io.earcam.unexceptional.Exceptional;
38 import io.earcam.utilitarian.io.ReplaceAllInputStream;
39
40 final class Parsing {
41
42 static ManifestParser parserFor(BundleManifestHeaders header, String value)
43 {
44 return parserFor(header.header() + ": " + value + "\n");
45 }
46
47
48 static ManifestParser parserFor(String value)
49 {
50 ManifestParser parser = parser(CharStreams.fromString(strip72s(value)));
51
52 parser.removeErrorListeners();
53 return parser;
54 }
55
56
57 private static String strip72s(String value)
58 {
59 return value.replaceAll("\r?\n ", "");
60 }
61
62
63 static ManifestParser parserFor(InputStream value)
64 {
65 ManifestParser parser = parser(Exceptional.apply(CharStreams::fromStream, strip72s(value), UTF_8));
66
67 parser.removeErrorListeners();
68 return parser;
69 }
70
71
72 private static InputStream strip72s(InputStream input)
73 {
74 return new ReplaceAllInputStream(bytes("\n "), new byte[0], new ReplaceAllInputStream(bytes("\r\n "), new byte[0], input));
75 }
76
77
78 private static byte[] bytes(String string)
79 {
80 return string.getBytes(UTF_8);
81 }
82
83
84 static ManifestParser parser(CharStream input)
85 {
86 ManifestLexer lexer = new ManifestLexer(input);
87 TokenStream tokens = new CommonTokenStream(lexer);
88 return new ManifestParser(tokens);
89 }
90
91
92 static ManifestParser failFastParserFor(String value)
93 {
94 ManifestParser parser = parser(CharStreams.fromString(strip72s(value)));
95 parser.setErrorHandler(new BailErrorStrategy());
96 return parser;
97 }
98
99
100 static ManifestParser failFastParserFor(InputStream value)
101 {
102 ManifestParser parser = parser(Exceptional.apply(CharStreams::fromStream, strip72s(value), UTF_8));
103 parser.setErrorHandler(new BailErrorStrategy());
104 return parser;
105 }
106
107
108 static void walk(ParseTree tree, ParseTreeListener listener)
109 {
110 ParseTreeWalker walker = new ParseTreeWalker();
111 walker.walk(listener, tree);
112 }
113
114
115 private Parsing()
116 {}
117 }