-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathHelpers.java
More file actions
271 lines (230 loc) · 8.9 KB
/
Helpers.java
File metadata and controls
271 lines (230 loc) · 8.9 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
271
// SPDX-FileCopyrightText : © 2025-2026 TU Wien <vadl@tuwien.ac.at>
// SPDX-License-Identifier: GPL-3.0-or-later
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package vadl.cli;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.stream.Streams;
import picocli.CommandLine;
import vadl.OpenVadlProperties;
import vadl.configuration.DecoderOptions;
import vadl.configuration.DumpMode;
import vadl.configuration.IssConfiguration;
class Helpers {
}
class VersionProvider implements CommandLine.IVersionProvider {
@Override
public String[] getVersion() {
return new String[] {OpenVadlProperties.getVersion()};
}
}
class IssOptsConverter implements CommandLine.ITypeConverter<IssConfiguration.IssOptsToSkip>,
Iterable<String> {
@Override
public IssConfiguration.IssOptsToSkip convert(String value) {
if (value.equals("help")) {
// Calculate the maximum width of option names
int maxOptionLength = Arrays.stream(IssConfiguration.IssOptsToSkip.values())
.map(opt -> toCliName(opt).length())
.max(Integer::compare)
.orElse(0);
// Define the indentation for descriptions
int descriptionIndent = 6 + maxOptionLength; // 6 accounts for " - " and two spaces
// Print help message for available options
System.out.println("Available optimizations to skip:");
Arrays.stream(IssConfiguration.IssOptsToSkip.values())
.sorted(Comparator.comparing(v -> v.name()))
.forEach(opt ->
printFormattedOption(toCliName(opt), opt.desc, maxOptionLength,
descriptionIndent));
System.exit(0);
}
try {
return IssConfiguration.IssOptsToSkip.valueOf(value.toUpperCase().replace('-', '_'));
} catch (IllegalArgumentException e) {
throw new CommandLine.TypeConversionException(
"\nAvailable options are %s".formatted(
Streams.of(iterator()).sorted().collect(Collectors.joining(", "))
)
);
}
}
@Nonnull
@Override
public Iterator<String> iterator() {
return Arrays.stream(IssConfiguration.IssOptsToSkip.values())
.map(this::toCliName)
.sorted()
.iterator();
}
private String toCliName(IssConfiguration.IssOptsToSkip value) {
return value.name().toLowerCase().replace('_', '-');
}
private static void printFormattedOption(String optionName, String description, int nameWidth,
int descriptionIndent) {
// Split the description into lines
String[] lines = description.split("\n", -1);
// Print the first line with the option name
System.out.printf(" - %-" + nameWidth + "s %s%n", optionName, lines[0]);
// Print subsequent lines with indentation
String format = "%" + (descriptionIndent + 2) + "s%s%n";
for (int i = 1; i < lines.length; i++) {
System.out.printf(format, "", lines[i]);
}
}
}
interface DecoderOpt {
}
record DecoderStrategy(DecoderOptions.Generator generator) implements DecoderOpt {
}
record DecoderSkipOption(DecoderOptions.OptionToSkip option) implements DecoderOpt {
}
record DecoderPenaltyFactor(Double penalty) implements DecoderOpt {
}
record DecoderStatistics(File stats) implements DecoderOpt {
}
class DecoderOptsConverter implements Iterable<String>, CommandLine.ITypeConverter<DecoderOpt> {
static final String KEY_STRATEGY = "strategy";
static final String KEY_SKIP = "skip";
static final String KEY_STATS = "statistics";
static final String KEY_PENALTY_FACTOR = "penalty";
@Override
public DecoderOpt convert(String value) throws Exception {
final String[] fragments = value.split("=", -1);
if (fragments.length != 2) {
throw new CommandLine.TypeConversionException(
"Unable to parse decoder option '%s'".formatted(value));
}
if (KEY_STRATEGY.equals(fragments[0].trim())) {
var val = fragments[1].trim();
var strategy = DecoderOptions.Generator.fromSelector(val);
if (strategy != null) {
return new DecoderStrategy(strategy);
}
throw new CommandLine.TypeConversionException(
"Unable to parse decoder strategy '%s'. Available strategies are: %s".formatted(val,
Arrays.stream(DecoderOptions.Generator.values())
.map(DecoderOptions.Generator::getSelector).toList()));
}
if (KEY_SKIP.equals(fragments[0].trim())) {
var val = fragments[1].trim();
var skipOpt = DecoderOptions.OptionToSkip.fromSelector(val);
if (skipOpt != null) {
return new DecoderSkipOption(skipOpt);
}
throw new CommandLine.TypeConversionException(
"Unable to parse decoder option to skip: '%s'. Available options are: %s".formatted(val,
Arrays.stream(DecoderOptions.OptionToSkip.values())
.map(DecoderOptions.OptionToSkip::getSelector).toList()));
}
if (KEY_STATS.equals(fragments[0].trim())) {
var statFile = new File(fragments[1].trim());
if (!statFile.exists()) {
throw new CommandLine.TypeConversionException(
"Unable to parse decoder option '%s'. Stats file does not exist".formatted(
statFile.getAbsolutePath())
);
}
return new DecoderStatistics(statFile);
}
if (KEY_PENALTY_FACTOR.equals(fragments[0].trim())) {
var val = fragments[1].trim();
if (!StringUtils.isNumeric(val)) {
throw new CommandLine.TypeConversionException(
"Unable to parse decoder option '%s'. Penalty factor is not numeric".formatted(val));
}
return new DecoderPenaltyFactor(Double.parseDouble(val));
}
throw new CommandLine.TypeConversionException(
"Illegal decoder option '%s'. Available options are: %s".formatted(value,
List.of(KEY_SKIP, KEY_STRATEGY)));
}
public static List<String> getOptions() {
final List<String> options = new ArrayList<>();
for (DecoderOptions.Generator generator : DecoderOptions.Generator.values()) {
options.add(
"%n%s=%s (%s)".formatted(KEY_STRATEGY, generator.getSelector(), generator.getDesc()));
}
for (DecoderOptions.OptionToSkip skipOption : DecoderOptions.OptionToSkip.values()) {
options.add(
"%n%s=%s (%s)".formatted(KEY_SKIP, skipOption.getSelector(), skipOption.getDesc()));
}
options.add("%n%s=%f (Penalty factor for occurrence aware decoder generator)".formatted(
KEY_PENALTY_FACTOR, 1.0));
options.add(
"%n%s=%s (Instruction occurrence statistics)".formatted(KEY_STATS, "/insn-stats.json"));
return options;
}
@Nonnull
@Override
public Iterator<String> iterator() {
return getOptions().iterator();
}
}
class DumpModeConverter implements CommandLine.ITypeConverter<DumpMode>, Iterable<String>,
CommandLine.IParameterConsumer {
@Override
public DumpMode convert(String value) {
if (value == null || value.isEmpty()) {
return DumpMode.ALWAYS;
}
try {
return DumpMode.fromString(value);
} catch (IllegalArgumentException e) {
// In case Picocli passes something else or fromString fails
throw new CommandLine.TypeConversionException(
"\nAvailable options are %s".formatted(
Streams.of(iterator()).sorted().collect(Collectors.joining(", "))
)
);
}
}
@Nonnull
@Override
public Iterator<String> iterator() {
return DumpMode.modeStrings.iterator();
}
@Override
public void consumeParameters(Stack<String> args, CommandLine.Model.ArgSpec argSpec,
CommandLine.Model.CommandSpec commandSpec) {
// check if the next argument is bound to the dump mode or some other parameter
String token = args.peek();
// --dump=mode
var idx = token.indexOf('=');
if (idx >= 0) {
args.pop();
var mode = convert(token.substring(idx + 1));
argSpec.setValue(mode);
return;
}
// --dump mode (only if mode is valid)
if (DumpMode.modeStrings.contains(token)) {
args.pop();
var mode = convert(token);
argSpec.setValue(mode);
return;
}
// --dump (flag)
argSpec.setValue(DumpMode.ALWAYS);
}
}