Repository navigation
Expand file tree
/
Copy pathDecodeHelper.java
More file actions
330 lines (302 loc) · 12.9 KB
/
Copy pathDecodeHelper.java
File metadata and controls
330 lines (302 loc) · 12.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
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
package dev.toonformat.jtoon.decoder;
import dev.toonformat.jtoon.Delimiter;
import org.jspecify.annotations.Nullable;
import java.util.List;
import java.util.Map;
import static dev.toonformat.jtoon.util.Constants.BACKSLASH;
import static dev.toonformat.jtoon.util.Constants.DOUBLE_QUOTE;
import static dev.toonformat.jtoon.util.Constants.SPACE;
import static dev.toonformat.jtoon.util.Constants.COLON;
/**
* Handles indentation, depth, conflicts, and validation for other decode classes.
*/
public final class DecodeHelper {
private DecodeHelper() {
throw new UnsupportedOperationException("Utility class cannot be instantiated");
}
/**
* Calculates indentation depth (nesting level) of a line.
* Counts leading spaces in multiples of the configured indent size.
* In strict mode, validates indentation (no tabs, proper multiples).
*
* @param line the line string to parse
* @param context decode an object to deal with lines, delimiter, and options
* @return the depth of a line
*/
public static int getDepth(final String line, final DecodeContext context) {
// Blank lines (including lines with only spaces) have depth 0
if (isBlankLine(line)) {
return 0;
}
return computeLeadingSpaces(line, context) / Math.max(1, context.options.indent());
}
/**
* Computes leading spaces, validates indentation in strict mode,
* and rejects tabs. Single scan for all indentation logic.
*
* @param line the line string to parse
* @param context decode object in order to deal with lines, delimiter and options
* @return amount of leading spaces
*/
private static int computeLeadingSpaces(final String line, final DecodeContext context) {
final int indentSize = context.options.indent();
int leadingSpaces = 0;
int i = 0;
final int lengthOfLine = line.length();
while (i < lengthOfLine) {
final char c = line.charAt(i);
if (c == SPACE.charAt(0)) {
leadingSpaces++;
} else if (c == Delimiter.TAB.getValue()) {
if (context.options.strict()) {
throw new IllegalArgumentException(
"Tab character used in indentation at line " + (context.currentLine + 1));
}
// In non-strict mode treat tab as non-indent and stop.
break;
} else {
break; // reached content
}
i++;
}
if (indentSize > 0 && leadingSpaces > 0 && leadingSpaces % indentSize != 0 && context.options.strict()) {
throw new IllegalArgumentException(
String.format("Non-multiple indentation: %d leadingSpaces with indent=%d at line %d",
leadingSpaces, indentSize, context.currentLine + 1));
}
return leadingSpaces;
}
/**
* Checks if a line is blank (empty or only whitespace).
*
* @param line the line string to parse
* @return true or false depending on if the line is blank or not
*/
static boolean isBlankLine(final String line) {
return line.isBlank();
}
/**
* Finds the index of the first unquoted colon in a line.
* Critical for handling quoted keys like "order:id": value.
*
* @param content the content string to parse
* @return the unquoted colon
*/
static int findUnquotedColon(final String content) {
boolean inQuotes = false;
boolean escaped = false;
for (int i = 0; i < content.length(); i++) {
final char c = content.charAt(i);
if (c == COLON.charAt(0) && !inQuotes) {
return i;
} else if (escaped) {
escaped = false;
} else if (c == BACKSLASH) {
escaped = true;
} else if (c == DOUBLE_QUOTE) {
inQuotes = !inQuotes;
}
}
return -1;
}
/**
* Finds the next non-blank line starting from the given index.
*
* @param startIndex given index
* @param context decode an object to deal with lines, delimiter, and options
* @return index aiming for the next non-blank line
*/
static int findNextNonBlankLine(final int startIndex, final DecodeContext context) {
int index = startIndex;
while (index < context.lines.length && isBlankLine(context.lines[index])) {
index++;
}
return index;
}
/**
* Finds the next non-blank line starting from the given index.
*
* @param finalSegment final segment
* @param existing existing
* @param value value present in a map
* @param context decode an object to deal with lines, delimiter, and options
* @throws IllegalArgumentException in case there's a expansion conflict
*/
static void checkFinalValueConflict(final String finalSegment, @Nullable final Object existing,
final Object value, final DecodeContext context) {
if (existing != null && context.options.strict()) {
// Check for conflicts in strict mode
if (existing instanceof Map && !(value instanceof Map)) {
throw new IllegalArgumentException(
String.format("Path expansion conflict: %s is object, cannot set to %s",
finalSegment, value.getClass().getSimpleName()));
}
if (existing instanceof List && !(value instanceof List)) {
throw new IllegalArgumentException(
String.format("Path expansion conflict: %s is array, cannot set to %s",
finalSegment, value.getClass().getSimpleName()));
}
}
}
/**
* Checks for path expansion conflicts when setting a non-expanded key.
* In strict mode, throws if the key conflicts with an existing expanded path.
*
* @param map map
* @param key present the key in the map
* @param value present value in a map
* @param context decode an object to deal with lines, delimiter, and options
*/
static void checkPathExpansionConflict(final Map<String, Object> map, final String key,
final Object value, final DecodeContext context) {
if (!context.options.strict()) {
return;
}
final Object existing = map.get(key);
checkFinalValueConflict(key, existing, value, context);
}
/**
* Checks for duplicate keys in strict mode.
* Throws if the map already contains the given key and strict mode is enabled.
*
* @param map the map to check
* @param key the key being inserted
* @param context decode context for strict mode check
* @throws IllegalArgumentException if strict mode and key already exists
*/
static void checkDuplicateKey(final Map<String, Object> map, final String key, final DecodeContext context) {
if (context.options.strict() && map.containsKey(key)) {
throw new IllegalArgumentException(
"Duplicate key '" + key + "' at line " + (context.currentLine + 1));
}
}
/**
* Finds the depth of the next non-blank line, skipping blank lines.
*
* @param context decode an object to deal with lines, delimiter and options
* @return the depth of the next non-blank line, or null if none exists
*/
static @Nullable Integer findNextNonBlankLineDepth(final DecodeContext context) {
int nextLineIdx = context.currentLine;
while (nextLineIdx < context.lines.length && isBlankLine(context.lines[nextLineIdx])) {
nextLineIdx++;
}
if (nextLineIdx >= context.lines.length) {
return null;
}
return getDepth(context.lines[nextLineIdx], context);
}
/**
* Checks if a line contains unquoted brackets ({@code [} or {@code ]}).
* Used to detect malformed array header syntax in strict mode.
*
* @param line the line to check
* @return true if unquoted brackets are found
*/
static boolean hasUnquotedBrackets(final String line) {
boolean inQuotes = false;
boolean escaped = false;
for (int i = 0; i < line.length(); i++) {
final char c = line.charAt(i);
if (escaped) {
escaped = false;
} else if (c == BACKSLASH) {
escaped = true;
} else if (c == DOUBLE_QUOTE) {
inQuotes = !inQuotes;
} else if (!inQuotes && (c == '[' || c == ']')) {
return true;
}
}
return false;
}
/**
* In strict mode, rejects a key-value key with unquoted brackets: the line
* did not match the header grammar, so its bracket segment is malformed
* (§6, §14.2). This catches:
* <ul>
* <li>the removed length marker ({@code xs[#2]})</li>
* <li>extra brackets between bracket segment and colon ({@code foo[1][bar]})</li>
* <li>text between bracket segment and colon ({@code foo[2]extra})</li>
* <li>noninteger bracket segment ({@code foo[bar]})</li>
* <li>negative bracket length ({@code items[-1]})</li>
* <li>whitespace between bracket segment and colon/fields segment
* ({@code items[2] :}, {@code items[2] {a,b}:})</li>
* </ul>
*
* @param key the raw key token before the colon
* @param context decode an object to deal with lines, delimiter and options
* @throws IllegalArgumentException in strict mode if the key has unquoted brackets
*/
static void validateKeyHasNoUnquotedBrackets(final String key, final DecodeContext context) {
if (context.options.strict() && hasUnquotedBrackets(key)) {
throw new IllegalArgumentException(
"Invalid array header syntax at line " + (context.currentLine + 1));
}
}
/**
* Validates that there are no multiple primitives at root level in strict mode.
*
* @param context decode an object to deal with lines, delimiter and options
* @throws IllegalArgumentException in case the next depth is equal to 0
*/
static void validateNoMultiplePrimitivesAtRoot(final DecodeContext context) {
int lineIndex = context.currentLine;
while (lineIndex < context.lines.length && isBlankLine(context.lines[lineIndex])) {
lineIndex++;
}
if (lineIndex < context.lines.length) {
final int nextDepth = getDepth(context.lines[lineIndex], context);
if (nextDepth == 0) {
throw new IllegalArgumentException(
"Multiple primitives at root depth in strict mode at line " + (lineIndex + 1));
}
}
}
/**
* Ensures no unconsumed lines remain after the root form was parsed.
* The root form spans the whole document (§5); trailing content must not be
* silently discarded. In strict mode any leftover line is an error. In
* non-strict mode a scalar line outside root primitive position is still an
* error in both modes alike (§5.2), while leftover key-value lines are ignored.
*
* @param context decode an object to deal with lines, delimiter and options
*/
static void validateNoTrailingContent(final DecodeContext context) {
while (context.currentLine < context.lines.length) {
final String line = context.lines[context.currentLine];
if (isBlankLine(line)) {
context.currentLine++;
continue;
}
if (context.options.strict()) {
throw new IllegalArgumentException(
"Unexpected content after root form at line " + (context.currentLine + 1));
}
final int depth = getDepth(line, context);
final String content = line.substring(depth * context.options.indent());
if (findUnquotedColon(content) < 0) {
// Spec §5.2: a scalar line outside root primitive position is
// an error in strict and non-strict mode alike.
throw new FatalDecodeException(
"Bare token line outside root primitive position at line " + (context.currentLine + 1));
}
context.currentLine++;
}
}
/**
* Skips or rejects an over-indented line that jumps past the expected
* depth (§14.2).
*
* @param context decode an object to deal with lines, delimiter, and options
* @param lineDepth the depth of the over-indented line
* @throws IllegalArgumentException in strict mode
*/
static void processOverIndentedLine(final DecodeContext context, final int lineDepth) {
if (context.options.strict()) {
throw new IllegalArgumentException(
"Over-indented line at " + (context.currentLine + 1) + " (depth " + lineDepth + ")");
}
context.currentLine++;
}
}