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
|
package org.shedlang.compiler.backends;
import org.pcollections.Empty;
import org.pcollections.PSet;
import java.util.Optional;
import java.util.function.Predicate;
public record NameAllocator<TPrefix>(PSet<String> existingNames) {
public static <TPrefix> NameAllocator<TPrefix> empty() {
return new NameAllocator<>(Empty.set());
}
public Result<TPrefix> allocateName(
TPrefix prefix,
Optional<String> name
) {
var fullName = allocateName(existingNames::contains, prefix, name);
var newAllocator = new NameAllocator<TPrefix>(existingNames.plus(fullName));
return new Result<>(fullName, newAllocator);
}
public Result<TPrefix> allocateFixedName(TPrefix prefix, String name) {
var fullName = allocateFixedName(existingNames::contains, prefix, name);
var newAllocator = new NameAllocator<TPrefix>(existingNames.plus(fullName));
return new Result<>(fullName, newAllocator);
}
public static <TPrefix> String allocateName(
Predicate<String> isUsed,
TPrefix prefix,
Optional<String> name
) {
var fullPrefix = prefix.toString();
if (name.isPresent()) {
fullPrefix += "__" + name.get();
}
var index = 0;
while (true) {
var fullName = fullPrefix + "__" + index;
if (isUsed.test(fullName)) {
index++;
} else {
return fullName;
}
}
}
public static <TPrefix> String allocateFixedName(Predicate<String> isUsed, TPrefix prefix, String name) {
var fullName = prefix + "__" + name;
if (isUsed.test(fullName)) {
throw new RuntimeException("name is already allocated: " + fullName);
}
return fullName;
}
public record Result<TPrefix>(String name, NameAllocator<TPrefix> allocator) {
}
}
|