forked from exercism/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathToken.java
More file actions
90 lines (65 loc) · 2.48 KB
/
Token.java
File metadata and controls
90 lines (65 loc) · 2.48 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
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
class Token {
static class OpDefToken extends Token {
static OpDefToken opDefTokenFromString(final String string) {
final String trimmedLine = string.substring(2, string.length() - 2);
final int newOpEnd = trimmedLine.indexOf(" ");
if (newOpEnd == -1) {
throw new IllegalArgumentException("Incomplete operation definition");
}
final Token newOpToken = Token.fromString(trimmedLine.substring(0, newOpEnd)).get(0);
if (!(newOpToken instanceof OpToken)) {
throw new IllegalArgumentException("Cannot redefine numbers");
}
final List<Token> newOpDefTokens = Token.fromString(trimmedLine.substring(newOpEnd + 1));
return new OpDefToken(((OpToken) newOpToken).getOp(), newOpDefTokens);
}
private final String newOp;
private final List<Token> newOpDefTokens;
private OpDefToken(final String newOp, final List<Token> newOpDefTokens) {
this.newOp = newOp;
this.newOpDefTokens = newOpDefTokens;
}
String getNewOp() {
return newOp;
}
List<Token> getNewOpDefTokens() {
return newOpDefTokens;
}
}
static class OpToken extends Token {
private final String op;
OpToken(final String op) {
this.op = op;
}
String getOp() {
return op;
}
}
static class IntToken extends Token {
private final int rawValue;
IntToken(final int rawValue) {
this.rawValue = rawValue;
}
int getRawValue() {
return rawValue;
}
}
static List<Token> fromString(final String string) {
if (string.startsWith(":")) {
return Collections.singletonList(OpDefToken.opDefTokenFromString(string));
} else if (string.matches("[A-z+/*\\-]+(?:-[A-z+/*\\-]+)*")) {
return Collections.singletonList(new OpToken(string.toLowerCase()));
} else if (string.matches("\\d+")) {
return Collections.singletonList(new IntToken(Integer.parseInt(string)));
} else {
return Arrays.stream(string.split(" "))
.map(Token::fromString)
.flatMap(List::stream)
.collect(Collectors.toList());
}
}
}