Repository navigation
Expand file tree
/
Copy pathParserExtensionRegistry.java
More file actions
270 lines (250 loc) · 13 KB
/
Copy pathParserExtensionRegistry.java
File metadata and controls
270 lines (250 loc) · 13 KB
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
package org.perlonjava.frontend.parser;
import org.perlonjava.runtime.runtimetypes.RuntimeBase;
import org.perlonjava.runtime.runtimetypes.RuntimeArray;
import org.perlonjava.runtime.runtimetypes.RuntimeHash;
import org.perlonjava.runtime.runtimetypes.RuntimeList;
import org.perlonjava.runtime.runtimetypes.RuntimeScalar;
import org.perlonjava.runtime.runtimetypes.RuntimeScalarType;
import java.util.Map;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.concurrent.ConcurrentHashMap;
/** Connects compile-time module imports to lexical parser keyword plugins. */
public final class ParserExtensionRegistry {
@FunctionalInterface
public interface ModuleProvider {
void apply(Parser parser, boolean enabled, RuntimeList arguments);
}
private static final Map<String, ModuleProvider> PROVIDERS = new ConcurrentHashMap<>();
static {
ModuleProvider functionParameters = ParserExtensionRegistry::applyFunctionParameters;
registerModuleProvider("Function::Parameters", functionParameters);
// GraphQL::MaybeTypeCheck delegates Function::Parameters->import::into
// to its caller. That dynamic import is not visible to the incremental
// parser, so mirror the resulting default lexical keyword registration.
registerModuleProvider("GraphQL::MaybeTypeCheck",
(parser, enabled, arguments) -> applyFunctionParameters(parser, enabled, null));
}
private ParserExtensionRegistry() { }
public static void registerModuleProvider(String moduleName, ModuleProvider provider) {
PROVIDERS.put(moduleName, provider);
}
public static void applyModulePragma(
Parser parser, String moduleName, boolean enabled, RuntimeList arguments) {
ModuleProvider provider = PROVIDERS.get(moduleName);
if (provider != null) provider.apply(parser, enabled, arguments);
}
private static void applyFunctionParameters(
Parser parser, boolean enabled, RuntimeList arguments) {
if (!enabled && (arguments == null || arguments.isEmpty())) {
parser.getVisibleParserKeywordPlugins().forEach((keyword, plugin) -> {
if (plugin instanceof FunctionParametersKeywordPlugin) {
parser.removeKeywordPlugin(keyword);
}
});
return;
}
if (arguments == null || arguments.isEmpty()) {
if (enabled) registerDefaults(parser);
return;
}
for (RuntimeBase argument : arguments.elements) {
RuntimeBase value = unwrap(argument);
if (value instanceof RuntimeHash definitions) {
for (var entry : definitions.elements.entrySet()) {
if (enabled) {
parser.registerKeywordPlugin(entry.getKey(),
configuredPlugin(entry.getKey(), entry.getValue()));
} else {
parser.removeKeywordPlugin(entry.getKey());
}
}
continue;
}
String name = argument.toString();
if (":std".equals(name)) {
if (enabled) registerDefaults(parser);
else removeDefaults(parser);
} else if (":modifiers".equals(name)) {
if (enabled) registerModifiers(parser);
else removeModifiers(parser);
} else if (":strict".equals(name) || ":lax".equals(name)) {
if (enabled) registerStrictnessDefaults(parser, ":strict".equals(name));
else removeDefaults(parser);
} else if ("fun".equals(name) || "method".equals(name)) {
if (enabled) parser.registerKeywordPlugin(name,
"fun".equals(name) ? FunctionParametersKeywordPlugin.FUNCTION
: FunctionParametersKeywordPlugin.METHOD);
else parser.removeKeywordPlugin(name);
} else if (!enabled && !name.isEmpty()) {
parser.removeKeywordPlugin(name);
}
}
}
private static void registerDefaults(Parser parser) {
parser.registerKeywordPlugin("fun", FunctionParametersKeywordPlugin.FUNCTION);
parser.registerKeywordPlugin("method", FunctionParametersKeywordPlugin.METHOD);
}
private static void registerStrictnessDefaults(Parser parser, boolean strict) {
parser.registerKeywordPlugin("fun", FunctionParametersKeywordPlugin.configured(
"function", null, 0, strict, true, false, null, List.of(), "optional", true,
null, null, true));
parser.registerKeywordPlugin("method", FunctionParametersKeywordPlugin.configured(
"method", null, 0, strict, true, false, null, List.of(), "optional", true,
null, null, true));
}
private static void removeDefaults(Parser parser) {
parser.removeKeywordPlugin("fun");
parser.removeKeywordPlugin("method");
}
private static void registerModifiers(Parser parser) {
for (String keyword : List.of("before", "after", "around", "augment", "override")) {
parser.registerKeywordPlugin(keyword, configuredPlugin(keyword, new RuntimeScalar(keyword)));
}
}
private static void removeModifiers(Parser parser) {
for (String keyword : List.of("before", "after", "around", "augment", "override")) {
parser.removeKeywordPlugin(keyword);
}
}
private static FunctionParametersKeywordPlugin configuredPlugin(String keyword, RuntimeScalar definition) {
RuntimeBase value = unwrap(definition);
String defaults;
List<String> shift = null;
int optionalInvocantCount = 0;
boolean strict = true;
boolean strictSpecified = false;
boolean checkArgumentTypes = true;
boolean runtime = false;
boolean defaultArguments = true;
boolean types = true;
String namePolicy = "optional";
String installSub = null;
String reifyType = null;
RuntimeScalar reifyTypeCallback = null;
List<String> defaultAttributes = List.of();
if (value instanceof RuntimeHash configuration) {
Set<String> supportedOptions = Set.of(
"defaults", "shift", "invocant", "strict",
"check_argument_count", "check_argument_types", "attributes", "runtime",
"install_sub", "default_arguments", "name", "reify_type", "types");
for (String option : configuration.elements.keySet()) {
if (!supportedOptions.contains(option)) {
throw new IllegalArgumentException("Invalid keyword property: " + option);
}
}
RuntimeBase reifyTypeValue = configuration.elements.get("reify_type");
RuntimeBase reifyTypeBase = unwrap(reifyTypeValue);
if (reifyTypeValue instanceof RuntimeScalar reifyMode
&& reifyMode.type == RuntimeScalarType.CODE) {
reifyTypeCallback = reifyMode;
} else if (reifyTypeBase != null
&& (!(reifyTypeBase instanceof RuntimeScalar reifyMode)
|| !Set.of("auto", "moose").contains(reifyMode.toString()))) {
throw new IllegalArgumentException(
"Invalid reify_type: expected 'auto', 'moose', or a code reference");
}
if (reifyTypeBase instanceof RuntimeScalar reifyTypeScalar) {
reifyType = reifyTypeScalar.toString();
}
RuntimeScalar defaultValue = configuration.elements.get("defaults");
String keywordDefaults = Set.of("method", "classmethod", "before", "after", "around",
"augment", "override").contains(keyword) ? keyword : "function";
defaults = defaultValue == null ? keywordDefaults : defaultValue.toString();
RuntimeScalar shiftValue = configuration.elements.get("shift");
RuntimeBase shiftBase = shiftValue == null ? null : unwrap(shiftValue);
if (shiftBase instanceof RuntimeArray names) {
shift = new ArrayList<>();
for (RuntimeScalar name : names.elements) shift.add(name.toString());
} else if (shiftValue != null) {
shift = List.of(shiftValue.toString());
}
RuntimeScalar invocantValue = configuration.elements.get("invocant");
if (invocantValue != null) optionalInvocantCount = Math.max(0, invocantValue.getInt());
RuntimeScalar strictValue = configuration.elements.get("strict");
if (strictValue != null) {
strict = strictValue.getBoolean();
strictSpecified = true;
}
RuntimeScalar checkArgumentCountValue = configuration.elements.get("check_argument_count");
if (checkArgumentCountValue != null) {
strict = checkArgumentCountValue.getBoolean()
|| (strictSpecified && strict);
strictSpecified = true;
}
RuntimeScalar checkArgumentTypesValue = configuration.elements.get("check_argument_types");
if (checkArgumentTypesValue != null) {
checkArgumentTypes = checkArgumentTypesValue.getBoolean();
}
RuntimeScalar runtimeValue = configuration.elements.get("runtime");
if (runtimeValue != null) {
runtime = runtimeValue.getBoolean();
}
RuntimeScalar installSubValue = configuration.elements.get("install_sub");
if (installSubValue != null && installSubValue.getDefinedBoolean()) {
installSub = installSubValue.toString();
}
RuntimeScalar attributesValue = configuration.elements.get("attributes");
if (attributesValue != null) {
defaultAttributes = parseConfiguredAttributes(attributesValue.toString());
}
RuntimeScalar defaultArgumentsValue = configuration.elements.get("default_arguments");
if (defaultArgumentsValue != null) defaultArguments = defaultArgumentsValue.getBoolean();
RuntimeScalar typesValue = configuration.elements.get("types");
if (typesValue != null) types = typesValue.getBoolean();
RuntimeScalar nameValue = configuration.elements.get("name");
if (nameValue != null) {
namePolicy = nameValue.toString();
if (!Set.of("required", "prohibited", "optional").contains(namePolicy)) {
throw new IllegalArgumentException("Invalid keyword property name: " + namePolicy);
}
}
} else {
defaults = definition.toString();
}
if (defaults.endsWith("_strict") || defaults.endsWith("_lax")) {
if (!strictSpecified) strict = defaults.endsWith("_strict");
defaults = defaults.substring(0, defaults.lastIndexOf('_'));
}
Set<String> modifiers = Set.of("before", "after", "around", "augment", "override");
if (modifiers.contains(defaults)) {
if (installSub == null) installSub = defaults;
// Function::Parameters modifier keywords default to runtime
// installation. Explicit configuration can still select parse-time.
if (!(value instanceof RuntimeHash configuration)
|| !configuration.elements.containsKey("runtime")) runtime = true;
}
if (!Set.of("function", "method", "classmethod", "before", "after", "around",
"augment", "override").contains(defaults)) {
throw new IllegalArgumentException(
"Unsupported Function::Parameters keyword defaults: " + defaults);
}
return FunctionParametersKeywordPlugin.configured(
defaults, shift, optionalInvocantCount, strict, checkArgumentTypes,
runtime, installSub, defaultAttributes, namePolicy, defaultArguments,
reifyType, reifyTypeCallback, types);
}
private static List<String> parseConfiguredAttributes(String source) {
String trimmed = source.trim();
String attributePattern = "[A-Za-z_]\\w*(?:\\([^()]*\\))?";
if (!trimmed.matches("\\s*:\\s*" + attributePattern
+ "(?:\\s*:?\\s*" + attributePattern + ")*\\s*")) {
throw new IllegalArgumentException(
"\"" + source + "\" doesn't look like valid attributes");
}
Matcher matcher = Pattern.compile("[A-Za-z_]\\w*(?:\\([^()]*\\))?").matcher(trimmed);
List<String> attributes = new ArrayList<>();
while (matcher.find()) attributes.add(matcher.group());
return List.copyOf(attributes);
}
private static RuntimeBase unwrap(RuntimeBase value) {
if (value instanceof RuntimeScalar scalar && scalar.value instanceof RuntimeBase nested) {
return nested;
}
return value;
}
}