aboutsummaryrefslogtreecommitdiffstats
path: root/bundle-plugin/src/main/java/com/yahoo/container/plugin/osgi/ExportPackageParser.java
blob: b6f29fea87e83ba701c4277194d772870365317e (plain) (blame)
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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.plugin.osgi;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Tony Vaagenes
 * @author ollivir
 */
public class ExportPackageParser {
    public static List<ExportPackages.Export> parseExports(String exportAttribute) {
        ParsingContext p = new ParsingContext(exportAttribute.trim());

        List<ExportPackages.Export> exports = parseExportPackage(p);
        if (exports.isEmpty()) {
            p.fail("Expected a list of exports");
        } else if (p.atEnd() == false) {
            p.fail("Exports not fully processed");
        }
        return exports;
    }

    private static class ParsingContext {
        private enum State {
            Invalid, WantMore, End
        }

        private CharSequence input;
        private int pos;
        private State state;
        private int length;
        private char ch;

        private ParsingContext(CharSequence input) {
            this.input = input;
            this.pos = 0;
        }

        private Optional<String> read(Consumer<ParsingContext> rule) {
            StringBuilder ret = new StringBuilder();

            parse: while (true) {
                if (input.length() < pos + 1) {
                    break;
                }
                ch = input.charAt(pos);
                state = State.WantMore;
                length = ret.length();
                rule.accept(this);

                switch (state) {
                case Invalid:
                    if (ret.length() == 0) {
                        break parse;
                    } else {
                        String printable = Character.isISOControl(ch) ? "#" + Integer.toString((int) ch)
                                : "[" + Character.toString(ch) + "]";
                        pos++;
                        fail("Character " + printable + " was not acceptable");
                    }
                    break;
                case WantMore:
                    ret.append(ch);
                    pos++;
                    break;
                case End:
                    break parse;
                }
            }

            if (ret.length() == 0) {
                return Optional.empty();
            } else {
                return Optional.of(ret.toString());
            }
        }

        private Optional<String> regexp(Pattern pattern) {
            Matcher matcher = pattern.matcher(input);
            matcher.region(pos, input.length());
            if (matcher.lookingAt()) {
                String value = matcher.group();
                pos += value.length();
                return Optional.of(value);
            } else {
                return Optional.empty();
            }
        }

        private Optional<String> exactly(String string) {
            if (input.length() - pos < string.length()) {
                return Optional.empty();
            }
            if (input.subSequence(pos, pos + string.length()).equals(string)) {
                pos += string.length();
                return Optional.of(string);
            }
            return Optional.empty();
        }

        private boolean atEnd() {
            return pos == input.length();
        }

        private void invalid() {
            this.state = State.Invalid;
        }

        private void end() {
            this.state = State.End;
        }

        private void fail(String message) {
            throw new RuntimeException("Failed parsing Export-Package: " + message + " at position " + pos);
        }
    }

    /* ident = ? a valid Java identifier ? */
    private static Optional<String> parseIdent(ParsingContext p) {
        Optional<String> ident = p.read(ctx -> {
            if (ctx.length == 0) {
                if (Character.isJavaIdentifierStart(ctx.ch) == false) {
                    ctx.invalid();
                }
            } else {
                if (Character.isJavaIdentifierPart(ctx.ch) == false) {
                    ctx.end();
                }
            }
        });
        return ident;
    }

    /* stringLiteral = ? sequence of any character except double quotes, control characters or backslash,
         a backslash followed by another backslash, a single or double quote, or one of the letters b,f,n,r or t
         a backslash followed by u followed by four hexadecimal digits ? */
    private static Pattern STRING_LITERAL_PATTERN = Pattern
            .compile("\"(?:[^\"\\p{Cntrl}\\\\]++|\\\\[\\\\'\"bfnrt]|\\\\u[0-9a-fA-F]{4})++\"");

    private static Optional<String> parseStringLiteral(ParsingContext p) {
        return p.regexp(STRING_LITERAL_PATTERN).map(quoted -> quoted.substring(1, quoted.length() - 1));
    }

    /* extended = { \p{Alnum} | '_' | '-' | '.' }+ */
    private static Pattern EXTENDED_PATTERN = Pattern.compile("[\\p{Alnum}_.-]+");

    private static Optional<String> parseExtended(ParsingContext p) {
        return p.regexp(EXTENDED_PATTERN);
    }

    /* argument = extended | stringLiteral | ? failure ? */
    private static String parseArgument(ParsingContext p) {
        Optional<String> argument = parseExtended(p);
        if (argument.isPresent() == false) {
            argument = parseStringLiteral(p);
        }
        if (argument.isPresent() == false) {
            p.fail("Expected an extended token or a string literal");
        }
        return argument.get();
    }

    /*
     * parameter = ( directive | attribute )
     * directive = extended, ':=', argument
     * attribute = extended, '=', argument
     */
    private static Pattern DIRECTIVE_OR_ATTRIBUTE_SEPARATOR_PATTERN = Pattern.compile("\\s*:?=\\s*");

    private static Optional<ExportPackages.Parameter> parseParameter(ParsingContext p) {
        int backtrack = p.pos;
        Optional<String> ext = parseExtended(p);
        if (ext.isPresent()) {
            Optional<String> sep = p.regexp(DIRECTIVE_OR_ATTRIBUTE_SEPARATOR_PATTERN);
            if (sep.isPresent() == false) {
                p.pos = backtrack;
                return Optional.empty();
            }
            String argument = parseArgument(p);
            return Optional.of(new ExportPackages.Parameter(ext.get(), argument));
        } else {
            return Optional.empty();
        }
    }

    /* parameters = parameter, { ';' parameter } */
    private static Pattern PARAMETER_SEPARATOR_PATTERN = Pattern.compile("\\s*;\\s*");

    private static List<ExportPackages.Parameter> parseParameters(ParsingContext p) {
        List<ExportPackages.Parameter> params = new ArrayList<>();
        boolean wantMore = true;
        do {
            Optional<ExportPackages.Parameter> param = parseParameter(p);
            if (param.isPresent()) {
                params.add(param.get());
                wantMore = p.regexp(PARAMETER_SEPARATOR_PATTERN).isPresent();
            } else {
                wantMore = false;
            }
        } while (wantMore);

        return params;
    }

    /* packageName = ident, { '.', ident } */
    private static Optional<String> parsePackageName(ParsingContext p) {
        StringBuilder ret = new StringBuilder();

        boolean wantMore = true;
        do {
            Optional<String> ident = parseIdent(p);
            if (ident.isPresent()) {
                ret.append(ident.get());
                Optional<String> separator = p.exactly(".");
                if (separator.isPresent()) {
                    ret.append(separator.get());
                    wantMore = true;
                } else {
                    wantMore = false;
                }
            } else {
                wantMore = false;
            }
        } while (wantMore);

        if (ret.length() > 0) {
            return Optional.of(ret.toString());
        } else {
            return Optional.empty();
        }
    }

    /* export = packageName, [ ';', ( parameters | export ) ] */
    private static ExportPackages.Export parseExport(ParsingContext p) {
        List<String> exports = new ArrayList<>();

        boolean wantMore = true;
        do {
            if (exports.isEmpty() == false) { // second+ iteration
                List<ExportPackages.Parameter> params = parseParameters(p);
                if (params.isEmpty() == false) {
                    return new ExportPackages.Export(exports, params);
                }
            }

            Optional<String> packageName = parsePackageName(p);
            if (packageName.isPresent()) {
                exports.add(packageName.get());
            } else {
                p.fail(exports.isEmpty() ? "Expected a package name" : "Expected either a package name or a parameter list");
            }

            wantMore = p.regexp(PARAMETER_SEPARATOR_PATTERN).isPresent();
        } while (wantMore);

        return new ExportPackages.Export(exports, new ArrayList<>());
    }

    /* exportPackage = export, { ',', export } */
    private static Pattern EXPORT_SEPARATOR_PATTERN = Pattern.compile("\\s*,\\s*");

    private static List<ExportPackages.Export> parseExportPackage(ParsingContext p) {
        List<ExportPackages.Export> exports = new ArrayList<>();

        boolean wantMore = true;
        do {
            ExportPackages.Export export = parseExport(p);
            if (export.getPackageNames().isEmpty()) {
                wantMore = false;
            } else {
                exports.add(export);
                wantMore = p.regexp(EXPORT_SEPARATOR_PATTERN).isPresent();
            }
        } while (wantMore);

        return exports;
    }
}