forked from tdlib/td
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathUpdateMemoryManager.javash
executable file
·381 lines (328 loc) · 11.6 KB
/
UpdateMemoryManager.javash
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
#!/usr/bin/java --source 21
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.SequencedSet;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class UpdateMemoryManager {
static final Set<String> EXCLUDED_MANAGERS = Set.of("Memory",
"Call",
"DeviceToken",
"LanguagePack",
"Pts",
"Password",
"SecretChats",
"Secure",
"Config",
"Storage",
"FileLoad",
"Parts",
"FileGenerate",
"Resource",
"NetStats",
"DcAuth",
"State",
"PhoneNumber",
"FileDownload",
"FileUpload",
"Alarm"
);
record Manager(Path directory, String name) {
String includePath() {
return directory.toString().substring(2) + "/" + name + "Manager.h";
}
}
public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.err.println("Arguments: PATH");
System.exit(1);
}
var path = Path.of(args[0]);
var telegramPath = path.resolve("td/telegram");
var memoryManager = new Manager(telegramPath, "Memory");
SequencedSet<Manager> managers;
try (var stream = Files.walk(telegramPath, 16)) {
var endNamePattern = "Manager.h";
managers = stream
.filter(Files::isRegularFile)
.filter(p -> p.getFileName().toString().endsWith(endNamePattern))
.map(p -> new Manager(p.getParent(), p.getFileName().toString().substring(0, p.getFileName().toString().length() - endNamePattern.length())))
.filter(name -> !EXCLUDED_MANAGERS.contains(name.name))
.collect(Collectors.toCollection(LinkedHashSet::new));
}
System.out.printf("Found %d managers%n", managers.size());
int fieldsFound = 0;
int updatedManagers = 0;
int totalManagers = 0;
List<Manager> invalidManagers = new ArrayList<>();
for (Manager manager : managers) {
totalManagers++;
var result = updateManagerJson(manager);
if (result != null) {
fieldsFound += result.fieldsFound();
if (result.changed) {
updatedManagers++;
}
} else {
invalidManagers.add(manager);
}
}
updateMemoryManagerJson(memoryManager, managers);
System.out.printf("%n%nDone.%n");
if (!invalidManagers.isEmpty()) {
System.out.printf("%d invalid managers found:%n%s",
invalidManagers.size(),
invalidManagers.stream()
.map(x -> "\t\"" + x.directory + "\": " + x.name + "\n")
.collect(Collectors.joining(", ")));
}
System.out.printf("%d/%d managers updated, %d total fields%n", updatedManagers, totalManagers, fieldsFound);
}
enum FieldType {
WaitFreeHashMap("WaitFreeHashMap", "calc_size"),
WaitFreeHashSet("WaitFreeHashSet", "calc_size"),
Vector("vector", "size"),
FlatHashMap("FlatHashMap", "size"),
FlatHashSet("FlatHashSet", "size")
;
private final String fieldName;
private final String sizeMethodName;
public final Pattern pattern;
FieldType(String fieldName, String sizeMethodName) {
this.fieldName = fieldName;
this.sizeMethodName = sizeMethodName;
this.pattern = Pattern.compile("^ {2}(mutable )?" + fieldName + "(<([^ ]|, )+>)? +(?<field>[a-zA-Z_]+);?[ \t/]*$");
}
Pattern getPattern() {
return pattern;
}
}
record FoundField(FieldType type, String name) {}
record UpdateResult(boolean changed, int fieldsFound) {}
private static UpdateResult updateManagerJson(Manager manager) throws IOException {
Path hFile = manager.directory.resolve(manager.name + "Manager.h");
Path cppFile = manager.directory.resolve(manager.name + "Manager.cpp");
System.out.printf("Updating manager \"%s\" files: [\"%s\", \"%s\"]%n", manager.name, hFile, cppFile);
if (Files.notExists(hFile)) {
System.out.printf("File not found, ignoring manager \"%s\": \"%s\"%n", manager.name, hFile);
return null;
}
if (Files.notExists(cppFile)) {
System.out.printf("File not found, ignoring manager \"%s\": \"%s\"%n", manager.name, cppFile);
return null;
}
List<FoundField> fields = new ArrayList<>();
var hLines = normalizeSourceFile(readSourceFile(hFile));
boolean currentClass = false;
for (String hLine : hLines) {
FoundField field = null;
if (hLine.startsWith("class ")) {
currentClass = hLine.contains(" " + manager.name + "Manager");
}
if (currentClass) {
for (FieldType possibleFieldType : FieldType.values()) {
var m = possibleFieldType.getPattern().matcher(hLine);
if (m.matches()) {
var fieldName = m.group("field");
field = new FoundField(possibleFieldType, fieldName);
break;
}
}
}
if (field != null) {
System.out.println("\tFound field: (%s) %s".formatted(field.type, field.name));
fields.add(field);
}
}
StringBuilder memoryStatsMethod = new StringBuilder();
memoryStatsMethod.append("void %sManager::memory_stats(vector<string> &output) {\n".formatted(manager.name));
memoryStatsMethod.append(fields.stream()
.map(field -> " output.push_back(\"\\\"%s\\\":\"); output.push_back(std::to_string(this->%s.%s()));\n".formatted(field.name, field.name, field.type.sizeMethodName))
.collect(Collectors.joining(" output.push_back(\",\");\n")));
memoryStatsMethod.append("}\n");
List<String> memoryStatsMethodLines = Arrays.asList(memoryStatsMethod.toString().split("\n"));
var cppLines = readSourceFile(cppFile);
var inputCppLines = new ArrayList<>(cppLines);
// Remove the old memory_stats method
var indexOfMemoryStatsStart = -1;
var indexOfMemoryStatsEnd = -1;
for (int i = 0; i < cppLines.size(); i++) {
if (cppLines.get(i).contains("::memory_stats(")) {
indexOfMemoryStatsStart = i;
for (int j = i - 1; j >= 0; j--) {
if (cppLines.get(j).isBlank()) {
indexOfMemoryStatsStart = j;
} else {
break;
}
}
break;
}
}
if (indexOfMemoryStatsStart != -1) {
for (int i = indexOfMemoryStatsStart + 1; i < cppLines.size(); i++) {
if (cppLines.get(i).trim().equals("}")) {
indexOfMemoryStatsEnd = i;
break;
}
}
if (indexOfMemoryStatsEnd == -1) {
throw new IllegalStateException("memory_stats method end not found");
}
cppLines.subList(indexOfMemoryStatsStart, indexOfMemoryStatsEnd + 1).clear();
}
var last = cppLines.removeLast();
cppLines.addAll(memoryStatsMethodLines);
cppLines.add("");
cppLines.addLast(last);
boolean changed = !Objects.equals(inputCppLines, cppLines);
if (changed) {
System.out.printf("\tDone: %s.cpp file has been updated!%n", manager.name);
Files.write(cppFile, cppLines, StandardCharsets.UTF_8);
} else {
System.out.printf("\tDone: %s.cpp file did not change.%n", manager.name);
}
return new UpdateResult(changed, fields.size());
}
private static void updateMemoryManagerJson(Manager manager, SequencedSet<Manager> managers) throws IOException {
Path hFile = manager.directory.resolve(manager.name + "Manager.h");
Path cppFile = manager.directory.resolve(manager.name + "Manager.cpp");
System.out.printf("Updating memory manager \"%s\" files: [\"%s\", \"%s\"]%n", manager.name, hFile, cppFile);
if (Files.notExists(hFile)) {
System.out.printf("File not found for manager \"%s\": \"%s\"%n", manager.name, hFile);
System.exit(1);
return;
}
if (Files.notExists(cppFile)) {
System.out.printf("File not found for manager \"%s\": \"%s\"%n", manager.name, cppFile);
System.exit(1);
return;
}
StringBuilder memoryStatsMethod = new StringBuilder();
memoryStatsMethod.append("void %sManager::print_managers_memory_stats(vector<string> &output) const {\n".formatted(manager.name));
memoryStatsMethod.append(managers.stream()
.map(m -> """
output.push_back("\\"%s_manager_\\":{"); td_->%s_manager_->memory_stats(output); output.push_back("}");
""".formatted(toSnakeCase(m.name), toSnakeCase(m.name)))
.collect(Collectors.joining(" output.push_back(\",\");\n")));
memoryStatsMethod.append("}\n");
List<String> memoryStatsMethodLines = Arrays.asList(memoryStatsMethod.toString().split("\n"));
var cppLines = readSourceFile(cppFile);
var inputCppLines = new ArrayList<>(cppLines);
// Remove the old memory_stats method
var indexOfMemoryStatsStart = -1;
var indexOfMemoryStatsEnd = -1;
for (int i = 0; i < cppLines.size(); i++) {
if (cppLines.get(i).contains("::print_managers_memory_stats(")) {
indexOfMemoryStatsStart = i;
for (int j = i - 1; j >= 0; j--) {
if (cppLines.get(j).isBlank()) {
indexOfMemoryStatsStart = j;
} else {
break;
}
}
break;
}
}
if (indexOfMemoryStatsStart != -1) {
for (int i = indexOfMemoryStatsStart + 1; i < cppLines.size(); i++) {
if (cppLines.get(i).trim().equals("}")) {
indexOfMemoryStatsEnd = i;
break;
}
}
if (indexOfMemoryStatsEnd == -1) {
throw new IllegalStateException("print_managers_memory_stats method end not found");
}
cppLines.subList(indexOfMemoryStatsStart, indexOfMemoryStatsEnd + 1).clear();
}
var last = cppLines.removeLast();
cppLines.addAll(memoryStatsMethodLines);
cppLines.add("");
cppLines.addLast(last);
for (Manager m : managers) {
var mInclude = "#include \"%s\"".formatted(m.includePath());
if (!cppLines.contains(mInclude)) {
System.out.printf("\tMissing include, adding \"" + m.includePath() + "\"%n");
int includeInsertIndex = -1;
for (int i = 0; i < cppLines.size(); i++) {
if (cppLines.get(i).startsWith("#include")) {
includeInsertIndex = i;
}
}
if (includeInsertIndex == -1) {
throw new IllegalStateException("Cannot find a place to put the include");
}
cppLines.add(includeInsertIndex + 1, mInclude);
}
}
boolean changed = !Objects.equals(inputCppLines, cppLines);
if (changed) {
System.out.printf("\tDone: %s.cpp file has been updated!%n", manager.name);
Files.write(cppFile, cppLines, StandardCharsets.UTF_8);
} else {
System.out.printf("\tDone: %s.cpp file did not change.%n", manager.name);
}
}
private static String toSnakeCase(String name) {
var initialChar = name.codePoints()
.limit(1)
.map(Character::toLowerCase);
var restOfString = name.codePoints()
.skip(1)
.flatMap(codePoint -> {
if (Character.isUpperCase(codePoint)) {
return IntStream.of('_', Character.toLowerCase(codePoint));
} else {
return IntStream.of(codePoint);
}
});
var resultStream = IntStream.concat(initialChar, restOfString);
return resultStream.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
}
private static List<String> readSourceFile(Path path) throws IOException {
return Files.readAllLines(path, StandardCharsets.UTF_8);
}
private static List<String> normalizeSourceFile(List<String> lines) throws IOException {
List<String> srcLines = new ArrayList<>(lines);
// Remove empty lines
srcLines.removeIf(String::isBlank);
// Remove unexpected newlines
List<String> srcLinesWithoutNewlines = new ArrayList<>();
StringBuilder buf = new StringBuilder();
for (String srcLine : srcLines) {
if (!buf.isEmpty()) {
buf.append(" ");
}
buf.append(srcLine);
var trimmedLine = srcLine.trim();
if (!trimmedLine.endsWith(">")) {
srcLinesWithoutNewlines.add(buf.toString());
buf.setLength(0);
}
}
if (!buf.isEmpty()) {
srcLinesWithoutNewlines.add(buf.toString());
}
srcLinesWithoutNewlines.replaceAll(p -> {
var commentStart = p.indexOf("//");
if (commentStart >= 0) {
return p.substring(0, commentStart);
} else {
return p;
}
});
return srcLinesWithoutNewlines;
}
}