NbtPathArgument .java

net.minecraft.commands.arguments.NbtPathArgument (class, 751 lines): members: SINGLE_QUOTED_KEY_START, ERROR_DATA_TOO_DEEP, ERROR_EXPECTED_LIST, nbtPath.

net.minecraft.commands.argumentsclass751 linescommon21.2 KB

Implements

API Surface (44)

NbtPathArgument nbtPath()
NbtPathArgument.NbtPath getPath(final CommandContext<CommandSourceStack> context, final String name)
NbtPathArgument.NbtPath parse(final StringReader reader)
Collection<String> getExamples()
void getTag(final Tag parent, final List<Tag> output)
void getOrCreateTag(final Tag parent, final Supplier<Tag> child, final List<Tag> output)
Tag createPreferredParentTag()
int setTag(final Tag parent, final Supplier<Tag> toAdd)
int removeTag(final Tag parent)
void getTag(final Tag parent, final List<Tag> output)
void getOrCreateTag(final Tag parent, final Supplier<Tag> child, final List<Tag> output)
Tag createPreferredParentTag()
int setTag(final Tag parent, final Supplier<Tag> toAdd)
int removeTag(final Tag parent)
void getTag(final Tag parent, final List<Tag> output)
void getOrCreateTag(final Tag parent, final Supplier<Tag> child, final List<Tag> output)
Tag createPreferredParentTag()
int setTag(final Tag parent, final Supplier<Tag> toAdd)
int removeTag(final Tag parent)
void getTag(final Tag parent, final List<Tag> output)
void getOrCreateTag(final Tag parent, final Supplier<Tag> child, final List<Tag> output)
Tag createPreferredParentTag()
int setTag(final Tag parent, final Supplier<Tag> toAdd)
int removeTag(final Tag parent)
void getTag(final Tag parent, final List<Tag> output)
void getOrCreateTag(final Tag parent, final Supplier<Tag> child, final List<Tag> output)
Tag createPreferredParentTag()
int setTag(final Tag parent, final Supplier<Tag> toAdd)
int removeTag(final Tag parent)
void getTag(final Tag self, final List<Tag> output)
void getOrCreateTag(final Tag self, final Supplier<Tag> child, final List<Tag> output)
Tag createPreferredParentTag()
int setTag(final Tag parent, final Supplier<Tag> toAdd)
int removeTag(final Tag parent)
NbtPathArgument.NbtPath of(final String string)
List<Tag> get(final Tag tag)
int countMatching(final Tag tag)
List<Tag> getOrCreate(final Tag tag, final Supplier<Tag> newTagValue)
boolean isTooDeep(final Tag tag, final int depth)
int set(final Tag tag, final Tag toAdd)
int insert(final int index, final CompoundTag target, final List<Tag> toInsert)
int remove(final Tag tag)
String toString()
String asString()

Fields & Constants (11)

EXAMPLES
ERROR_INVALID_NODE
ERROR_DATA_TOO_DEEP
ERROR_NOTHING_FOUND
ERROR_EXPECTED_LIST
ERROR_INVALID_INDEX
INDEX_MATCH_START
INDEX_MATCH_END
KEY_MATCH_START
QUOTED_KEY_START
SINGLE_QUOTED_KEY_START

String literals (9)

"foo.bar"
"foo[0]"
"{foo=bar}"
"arguments.nbtpath.node.invalid"
"arguments.nbtpath.too_deep"
"arguments.nbtpath.nothing_found"
"commands.data.modify.expected_list"
"commands.data.modify.invalid_index"
"Failed to parse path "

Full Source

NbtPathArgument.java751 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.commands.arguments;
2
3
import com.google.common.collect.Iterables;
4
import com.google.common.collect.Lists;
5
import com.mojang.brigadier.StringReader;
6
import com.mojang.brigadier.arguments.ArgumentType;
7
import com.mojang.brigadier.context.CommandContext;
8
import com.mojang.brigadier.exceptions.CommandSyntaxException;
9
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
10
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
11
import com.mojang.serialization.Codec;
12
import com.mojang.serialization.DataResult;
13
import it.unimi.dsi.fastutil.objects.Object2IntMap;
14
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
15
import java.util.ArrayList;
16
import java.util.Arrays;
17
import java.util.Collection;
18
import java.util.Collections;
19
import java.util.List;
20
import java.util.function.BiConsumer;
21
import java.util.function.Function;
22
import java.util.function.Predicate;
23
import java.util.function.Supplier;
24
import net.minecraft.commands.CommandSourceStack;
25
import net.minecraft.nbt.CollectionTag;
26
import net.minecraft.nbt.CompoundTag;
27
import net.minecraft.nbt.ListTag;
28
import net.minecraft.nbt.NbtUtils;
29
import net.minecraft.nbt.Tag;
30
import net.minecraft.nbt.TagParser;
31
import net.minecraft.network.chat.Component;
32
import org.apache.commons.lang3.mutable.MutableBoolean;
33
34
public class NbtPathArgument implements ArgumentType<NbtPathArgument.NbtPath> {
35
	private static final Collection<String> EXAMPLES = Arrays.asList("foo", "foo.bar", "foo[0]", "[0]", "[]", "{foo=bar}");
36
	public static final SimpleCommandExceptionType ERROR_INVALID_NODE = new SimpleCommandExceptionType(Component.translatable("arguments.nbtpath.node.invalid"));
37
	public static final SimpleCommandExceptionType ERROR_DATA_TOO_DEEP = new SimpleCommandExceptionType(Component.translatable("arguments.nbtpath.too_deep"));
38
	public static final DynamicCommandExceptionType ERROR_NOTHING_FOUND = new DynamicCommandExceptionType(
39
		path -> Component.translatableEscape("arguments.nbtpath.nothing_found", path)
40
	);
41
	private static final DynamicCommandExceptionType ERROR_EXPECTED_LIST = new DynamicCommandExceptionType(
42
		node -> Component.translatableEscape("commands.data.modify.expected_list", node)
43
	);
44
	private static final DynamicCommandExceptionType ERROR_INVALID_INDEX = new DynamicCommandExceptionType(
45
		node -> Component.translatableEscape("commands.data.modify.invalid_index", node)
46
	);
47
	private static final char INDEX_MATCH_START = '[';
48
	private static final char INDEX_MATCH_END = ']';
49
	private static final char KEY_MATCH_START = '{';
50
	private static final char KEY_MATCH_END = '}';
51
	private static final char QUOTED_KEY_START = '"';
52
	private static final char SINGLE_QUOTED_KEY_START = '\'';
53
54
	public static NbtPathArgument nbtPath() {
55
		return new NbtPathArgument();
56
	}
57
58
	public static NbtPathArgument.NbtPath getPath(final CommandContext<CommandSourceStack> context, final String name) {
59
		return context.getArgument(name, NbtPathArgument.NbtPath.class);
60
	}
61
62
	public NbtPathArgument.NbtPath parse(final StringReader reader) throws CommandSyntaxException {
63
		List<NbtPathArgument.Node> nodes = Lists.newArrayList();
64
		int start = reader.getCursor();
65
		Object2IntMap<NbtPathArgument.Node> nodeToOriginalPosition = new Object2IntOpenHashMap<>();
66
		boolean firstNode = true;
67
68
		while (reader.canRead() && reader.peek() != ' ') {
69
			NbtPathArgument.Node node = parseNode(reader, firstNode);
70
			nodes.add(node);
71
			nodeToOriginalPosition.put(node, reader.getCursor() - start);
72
			firstNode = false;
73
			if (reader.canRead()) {
74
				char next = reader.peek();
75
				if (next != ' ' && next != '[' && next != '{') {
76
					reader.expect('.');
77
				}
78
			}
79
		}
80
81
		return new NbtPathArgument.NbtPath(
82
			reader.getString().substring(start, reader.getCursor()), nodes.toArray(new NbtPathArgument.Node[0]), nodeToOriginalPosition
83
		);
84
	}
85
86
	private static NbtPathArgument.Node parseNode(final StringReader reader, final boolean firstNode) throws CommandSyntaxException {
87
		return switch (reader.peek()) {
88
			case '"', '\'' -> readObjectNode(reader, reader.readString());
89
			case '[' -> {
90
				reader.skip();
91
				int next = reader.peek();
92
				if (next == 123) {
93
					CompoundTag pattern = TagParser.parseCompoundAsArgument(reader);
94
					reader.expect(']');
95
					yield new NbtPathArgument.MatchElementNode(pattern);
96
				} else if (next == 93) {
97
					reader.skip();
98
					yield NbtPathArgument.AllElementsNode.INSTANCE;
99
				} else {
100
					int index = reader.readInt();
101
					reader.expect(']');
102
					yield new NbtPathArgument.IndexedElementNode(index);
103
				}
104
			}
105
			case '{' -> {
106
				if (!firstNode) {
107
					throw ERROR_INVALID_NODE.createWithContext(reader);
108
				}
109
110
				CompoundTag pattern = TagParser.parseCompoundAsArgument(reader);
111
				yield new NbtPathArgument.MatchRootObjectNode(pattern);
112
			}
113
			default -> readObjectNode(reader, readUnquotedName(reader));
114
		};
115
	}
116
117
	private static NbtPathArgument.Node readObjectNode(final StringReader reader, final String name) throws CommandSyntaxException {
118
		if (name.isEmpty()) {
119
			throw ERROR_INVALID_NODE.createWithContext(reader);
120
		} else if (reader.canRead() && reader.peek() == '{') {
121
			CompoundTag pattern = TagParser.parseCompoundAsArgument(reader);
122
			return new NbtPathArgument.MatchObjectNode(name, pattern);
123
		} else {
124
			return new NbtPathArgument.CompoundChildNode(name);
125
		}
126
	}
127
128
	private static String readUnquotedName(final StringReader reader) throws CommandSyntaxException {
129
		int start = reader.getCursor();
130
131
		while (reader.canRead() && isAllowedInUnquotedName(reader.peek())) {
132
			reader.skip();
133
		}
134
135
		if (reader.getCursor() == start) {
136
			throw ERROR_INVALID_NODE.createWithContext(reader);
137
		} else {
138
			return reader.getString().substring(start, reader.getCursor());
139
		}
140
	}
141
142
	@Override
143
	public Collection<String> getExamples() {
144
		return EXAMPLES;
145
	}
146
147
	private static boolean isAllowedInUnquotedName(final char c) {
148
		return c != ' ' && c != '"' && c != '\'' && c != '[' && c != ']' && c != '.' && c != '{' && c != '}';
149
	}
150
151
	private static Predicate<Tag> createTagPredicate(final CompoundTag pattern) {
152
		return tag -> NbtUtils.compareNbt(pattern, tag, true);
153
	}
154
155
	private static class AllElementsNode implements NbtPathArgument.Node {
156
		public static final NbtPathArgument.AllElementsNode INSTANCE = new NbtPathArgument.AllElementsNode();
157
158
		@Override
159
		public void getTag(final Tag parent, final List<Tag> output) {
160
			if (parent instanceof CollectionTag collection) {
161
				Iterables.addAll(output, collection);
162
			}
163
		}
164
165
		@Override
166
		public void getOrCreateTag(final Tag parent, final Supplier<Tag> child, final List<Tag> output) {
167
			if (parent instanceof CollectionTag list) {
168
				if (list.isEmpty()) {
169
					Tag result = child.get();
170
					if (list.addTag(0, result)) {
171
						output.add(result);
172
					}
173
				} else {
174
					Iterables.addAll(output, list);
175
				}
176
			}
177
		}
178
179
		@Override
180
		public Tag createPreferredParentTag() {
181
			return new ListTag();
182
		}
183
184
		@Override
185
		public int setTag(final Tag parent, final Supplier<Tag> toAdd) {
186
			if (!(parent instanceof CollectionTag list)) {
187
				return 0;
188
			} else {
189
				int size = list.size();
190
				if (size == 0) {
191
					list.addTag(0, toAdd.get());
192
					return 1;
193
				}
194
195
				Tag newValue = toAdd.get();
196
				int changedCount = size - (int)list.stream().filter(newValue::equals).count();
197
				if (changedCount == 0) {
198
					return 0;
199
				}
200
201
				list.clear();
202
				if (!list.addTag(0, newValue)) {
203
					return 0;
204
				}
205
206
				for (int i = 1; i < size; i++) {
207
					list.addTag(i, toAdd.get());
208
				}
209
210
				return changedCount;
211
			}
212
		}
213
214
		@Override
215
		public int removeTag(final Tag parent) {
216
			if (parent instanceof CollectionTag list) {
217
				int size = list.size();
218
				if (size > 0) {
219
					list.clear();
220
					return size;
221
				}
222
			}
223
224
			return 0;
225
		}
226
	}
227
228
	private static class CompoundChildNode implements NbtPathArgument.Node {
229
		private final String name;
230
231
		public CompoundChildNode(final String name) {
232
			this.name = name;
233
		}
234
235
		@Override
236
		public void getTag(final Tag parent, final List<Tag> output) {
237
			if (parent instanceof CompoundTag compoundTag) {
238
				Tag result = compoundTag.get(this.name);
239
				if (result != null) {
240
					output.add(result);
241
				}
242
			}
243
		}
244
245
		@Override
246
		public void getOrCreateTag(final Tag parent, final Supplier<Tag> child, final List<Tag> output) {
247
			if (parent instanceof CompoundTag compound) {
248
				Tag result;
249
				if (compound.contains(this.name)) {
250
					result = compound.get(this.name);
251
				} else {
252
					result = child.get();
253
					compound.put(this.name, result);
254
				}
255
256
				output.add(result);
257
			}
258
		}
259
260
		@Override
261
		public Tag createPreferredParentTag() {
262
			return new CompoundTag();
263
		}
264
265
		@Override
266
		public int setTag(final Tag parent, final Supplier<Tag> toAdd) {
267
			if (parent instanceof CompoundTag compound) {
268
				Tag newValue = toAdd.get();
269
				Tag previousValue = compound.put(this.name, newValue);
270
				if (!newValue.equals(previousValue)) {
271
					return 1;
272
				}
273
			}
274
275
			return 0;
276
		}
277
278
		@Override
279
		public int removeTag(final Tag parent) {
280
			if (parent instanceof CompoundTag compound && compound.contains(this.name)) {
281
				compound.remove(this.name);
282
				return 1;
283
			} else {
284
				return 0;
285
			}
286
		}
287
	}
288
289
	private static class IndexedElementNode implements NbtPathArgument.Node {
290
		private final int index;
291
292
		public IndexedElementNode(final int index) {
293
			this.index = index;
294
		}
295
296
		@Override
297
		public void getTag(final Tag parent, final List<Tag> output) {
298
			if (parent instanceof CollectionTag list) {
299
				int size = list.size();
300
				int actualIndex = this.index < 0 ? size + this.index : this.index;
301
				if (0 <= actualIndex && actualIndex < size) {
302
					output.add(list.get(actualIndex));
303
				}
304
			}
305
		}
306
307
		@Override
308
		public void getOrCreateTag(final Tag parent, final Supplier<Tag> child, final List<Tag> output) {
309
			this.getTag(parent, output);
310
		}
311
312
		@Override
313
		public Tag createPreferredParentTag() {
314
			return new ListTag();
315
		}
316
317
		@Override
318
		public int setTag(final Tag parent, final Supplier<Tag> toAdd) {
319
			if (parent instanceof CollectionTag list) {
320
				int size = list.size();
321
				int actualIndex = this.index < 0 ? size + this.index : this.index;
322
				if (0 <= actualIndex && actualIndex < size) {
323
					Tag previousValue = list.get(actualIndex);
324
					Tag newValue = toAdd.get();
325
					if (!newValue.equals(previousValue) && list.setTag(actualIndex, newValue)) {
326
						return 1;
327
					}
328
				}
329
			}
330
331
			return 0;
332
		}
333
334
		@Override
335
		public int removeTag(final Tag parent) {
336
			if (parent instanceof CollectionTag list) {
337
				int size = list.size();
338
				int actualIndex = this.index < 0 ? size + this.index : this.index;
339
				if (0 <= actualIndex && actualIndex < size) {
340
					list.remove(actualIndex);
341
					return 1;
342
				}
343
			}
344
345
			return 0;
346
		}
347
	}
348
349
	private static class MatchElementNode implements NbtPathArgument.Node {
350
		private final CompoundTag pattern;
351
		private final Predicate<Tag> predicate;
352
353
		public MatchElementNode(final CompoundTag pattern) {
354
			this.pattern = pattern;
355
			this.predicate = NbtPathArgument.createTagPredicate(pattern);
356
		}
357
358
		@Override
359
		public void getTag(final Tag parent, final List<Tag> output) {
360
			if (parent instanceof ListTag list) {
361
				list.stream().filter(this.predicate).forEach(output::add);
362
			}
363
		}
364
365
		@Override
366
		public void getOrCreateTag(final Tag parent, final Supplier<Tag> child, final List<Tag> output) {
367
			MutableBoolean foundAnything = new MutableBoolean();
368
			if (parent instanceof ListTag list) {
369
				list.stream().filter(this.predicate).forEach(t -> {
370
					output.add(t);
371
					foundAnything.setTrue();
372
				});
373
				if (foundAnything.isFalse()) {
374
					CompoundTag newTag = this.pattern.copy();
375
					list.add(newTag);
376
					output.add(newTag);
377
				}
378
			}
379
		}
380
381
		@Override
382
		public Tag createPreferredParentTag() {
383
			return new ListTag();
384
		}
385
386
		@Override
387
		public int setTag(final Tag parent, final Supplier<Tag> toAdd) {
388
			int changedCount = 0;
389
			if (parent instanceof ListTag list) {
390
				int size = list.size();
391
				if (size == 0) {
392
					list.add(toAdd.get());
393
					changedCount++;
394
				} else {
395
					for (int i = 0; i < size; i++) {
396
						Tag currentValue = list.get(i);
397
						if (this.predicate.test(currentValue)) {
398
							Tag newValue = toAdd.get();
399
							if (!newValue.equals(currentValue) && list.setTag(i, newValue)) {
400
								changedCount++;
401
							}
402
						}
403
					}
404
				}
405
			}
406
407
			return changedCount;
408
		}
409
410
		@Override
411
		public int removeTag(final Tag parent) {
412
			int changedCount = 0;
413
			if (parent instanceof ListTag list) {
414
				for (int i = list.size() - 1; i >= 0; i--) {
415
					if (this.predicate.test(list.get(i))) {
416
						list.remove(i);
417
						changedCount++;
418
					}
419
				}
420
			}
421
422
			return changedCount;
423
		}
424
	}
425
426
	private static class MatchObjectNode implements NbtPathArgument.Node {
427
		private final String name;
428
		private final CompoundTag pattern;
429
		private final Predicate<Tag> predicate;
430
431
		public MatchObjectNode(final String name, final CompoundTag pattern) {
432
			this.name = name;
433
			this.pattern = pattern;
434
			this.predicate = NbtPathArgument.createTagPredicate(pattern);
435
		}
436
437
		@Override
438
		public void getTag(final Tag parent, final List<Tag> output) {
439
			if (parent instanceof CompoundTag compoundTag) {
440
				Tag result = compoundTag.get(this.name);
441
				if (this.predicate.test(result)) {
442
					output.add(result);
443
				}
444
			}
445
		}
446
447
		@Override
448
		public void getOrCreateTag(final Tag parent, final Supplier<Tag> child, final List<Tag> output) {
449
			if (parent instanceof CompoundTag compound) {
450
				Tag result = compound.get(this.name);
451
				if (result == null) {
452
					result = this.pattern.copy();
453
					compound.put(this.name, result);
454
					output.add(result);
455
				} else if (this.predicate.test(result)) {
456
					output.add(result);
457
				}
458
			}
459
		}
460
461
		@Override
462
		public Tag createPreferredParentTag() {
463
			return new CompoundTag();
464
		}
465
466
		@Override
467
		public int setTag(final Tag parent, final Supplier<Tag> toAdd) {
468
			if (parent instanceof CompoundTag compound) {
469
				Tag currentValue = compound.get(this.name);
470
				if (this.predicate.test(currentValue)) {
471
					Tag newValue = toAdd.get();
472
					if (!newValue.equals(currentValue)) {
473
						compound.put(this.name, newValue);
474
						return 1;
475
					}
476
				}
477
			}
478
479
			return 0;
480
		}
481
482
		@Override
483
		public int removeTag(final Tag parent) {
484
			if (parent instanceof CompoundTag compound) {
485
				Tag current = compound.get(this.name);
486
				if (this.predicate.test(current)) {
487
					compound.remove(this.name);
488
					return 1;
489
				}
490
			}
491
492
			return 0;
493
		}
494
	}
495
496
	private static class MatchRootObjectNode implements NbtPathArgument.Node {
497
		private final Predicate<Tag> predicate;
498
499
		public MatchRootObjectNode(final CompoundTag pattern) {
500
			this.predicate = NbtPathArgument.createTagPredicate(pattern);
501
		}
502
503
		@Override
504
		public void getTag(final Tag self, final List<Tag> output) {
505
			if (self instanceof CompoundTag && this.predicate.test(self)) {
506
				output.add(self);
507
			}
508
		}
509
510
		@Override
511
		public void getOrCreateTag(final Tag self, final Supplier<Tag> child, final List<Tag> output) {
512
			this.getTag(self, output);
513
		}
514
515
		@Override
516
		public Tag createPreferredParentTag() {
517
			return new CompoundTag();
518
		}
519
520
		@Override
521
		public int setTag(final Tag parent, final Supplier<Tag> toAdd) {
522
			return 0;
523
		}
524
525
		@Override
526
		public int removeTag(final Tag parent) {
527
			return 0;
528
		}
529
	}
530
531
	public static class NbtPath {
532
		private final String original;
533
		private final Object2IntMap<NbtPathArgument.Node> nodeToOriginalPosition;
534
		private final NbtPathArgument.Node[] nodes;
535
		public static final Codec<NbtPathArgument.NbtPath> CODEC = Codec.STRING.comapFlatMap(string -> {
536
			try {
537
				NbtPathArgument.NbtPath parsed = new NbtPathArgument().parse(new StringReader(string));
538
				return DataResult.success(parsed);
539
			} catch (CommandSyntaxException e) {
540
				return DataResult.error(() -> "Failed to parse path " + string + ": " + e.getMessage());
541
			}
542
		}, NbtPathArgument.NbtPath::asString);
543
544
		public static NbtPathArgument.NbtPath of(final String string) throws CommandSyntaxException {
545
			return new NbtPathArgument().parse(new StringReader(string));
546
		}
547
548
		public NbtPath(final String original, final NbtPathArgument.Node[] nodes, final Object2IntMap<NbtPathArgument.Node> nodeToOriginalPosition) {
549
			this.original = original;
550
			this.nodes = nodes;
551
			this.nodeToOriginalPosition = nodeToOriginalPosition;
552
		}
553
554
		public List<Tag> get(final Tag tag) throws CommandSyntaxException {
555
			List<Tag> result = Collections.singletonList(tag);
556
557
			for (NbtPathArgument.Node node : this.nodes) {
558
				result = node.get(result);
559
				if (result.isEmpty()) {
560
					throw this.createNotFoundException(node);
561
				}
562
			}
563
564
			return result;
565
		}
566
567
		public int countMatching(final Tag tag) {
568
			List<Tag> result = Collections.singletonList(tag);
569
570
			for (NbtPathArgument.Node node : this.nodes) {
571
				result = node.get(result);
572
				if (result.isEmpty()) {
573
					return 0;
574
				}
575
			}
576
577
			return result.size();
578
		}
579
580
		private List<Tag> getOrCreateParents(final Tag tag) throws CommandSyntaxException {
581
			List<Tag> result = Collections.singletonList(tag);
582
583
			for (int i = 0; i < this.nodes.length - 1; i++) {
584
				NbtPathArgument.Node node = this.nodes[i];
585
				int next = i + 1;
586
				result = node.getOrCreate(result, this.nodes[next]::createPreferredParentTag);
587
				if (result.isEmpty()) {
588
					throw this.createNotFoundException(node);
589
				}
590
			}
591
592
			return result;
593
		}
594
595
		public List<Tag> getOrCreate(final Tag tag, final Supplier<Tag> newTagValue) throws CommandSyntaxException {
596
			List<Tag> result = this.getOrCreateParents(tag);
597
			NbtPathArgument.Node lastNode = this.nodes[this.nodes.length - 1];
598
			return lastNode.getOrCreate(result, newTagValue);
599
		}
600
601
		private static int apply(final List<Tag> targets, final Function<Tag, Integer> operation) {
602
			return targets.stream().map(operation).reduce(0, (a, b) -> a + b);
603
		}
604
605
		public static boolean isTooDeep(final Tag tag, final int depth) {
606
			if (depth >= 512) {
607
				return true;
608
			}
609
610
			if (tag instanceof CompoundTag compound) {
611
				for (Tag child : compound.values()) {
612
					if (isTooDeep(child, depth + 1)) {
613
						return true;
614
					}
615
				}
616
			} else if (tag instanceof ListTag) {
617
				for (Tag listEntry : (ListTag)tag) {
618
					if (isTooDeep(listEntry, depth + 1)) {
619
						return true;
620
					}
621
				}
622
			}
623
624
			return false;
625
		}
626
627
		public int set(final Tag tag, final Tag toAdd) throws CommandSyntaxException {
628
			if (isTooDeep(toAdd, this.estimatePathDepth())) {
629
				throw NbtPathArgument.ERROR_DATA_TOO_DEEP.create();
630
			}
631
632
			Tag firstCopy = toAdd.copy();
633
			List<Tag> result = this.getOrCreateParents(tag);
634
			if (result.isEmpty()) {
635
				return 0;
636
			}
637
638
			NbtPathArgument.Node lastNode = this.nodes[this.nodes.length - 1];
639
			MutableBoolean usedFirstCopy = new MutableBoolean(false);
640
			return apply(result, t -> lastNode.setTag(t, () -> {
641
				if (usedFirstCopy.isFalse()) {
642
					usedFirstCopy.setTrue();
643
					return firstCopy;
644
				} else {
645
					return firstCopy.copy();
646
				}
647
			}));
648
		}
649
650
		private int estimatePathDepth() {
651
			return this.nodes.length;
652
		}
653
654
		public int insert(final int index, final CompoundTag target, final List<Tag> toInsert) throws CommandSyntaxException {
655
			List<Tag> toInsertCopy = new ArrayList<>(toInsert.size());
656
657
			for (Tag tag : toInsert) {
658
				Tag copy = tag.copy();
659
				toInsertCopy.add(copy);
660
				if (isTooDeep(copy, this.estimatePathDepth())) {
661
					throw NbtPathArgument.ERROR_DATA_TOO_DEEP.create();
662
				}
663
			}
664
665
			Collection<Tag> targets = this.getOrCreate(target, ListTag::new);
666
			int modifiedCount = 0;
667
			boolean usedFirst = false;
668
669
			for (Tag targetTag : targets) {
670
				if (!(targetTag instanceof CollectionTag targetList)) {
671
					throw NbtPathArgument.ERROR_EXPECTED_LIST.create(targetTag);
672
				}
673
674
				boolean modified = false;
675
				int actualIndex = index < 0 ? targetList.size() + index + 1 : index;
676
677
				for (Tag sourceTag : toInsertCopy) {
678
					try {
679
						if (targetList.addTag(actualIndex, usedFirst ? sourceTag.copy() : sourceTag)) {
680
							actualIndex++;
681
							modified = true;
682
						}
683
					} catch (IndexOutOfBoundsException e) {
684
						throw NbtPathArgument.ERROR_INVALID_INDEX.create(actualIndex);
685
					}
686
				}
687
688
				usedFirst = true;
689
				modifiedCount += modified ? 1 : 0;
690
			}
691
692
			return modifiedCount;
693
		}
694
695
		public int remove(final Tag tag) {
696
			List<Tag> result = Collections.singletonList(tag);
697
698
			for (int i = 0; i < this.nodes.length - 1; i++) {
699
				result = this.nodes[i].get(result);
700
			}
701
702
			NbtPathArgument.Node lastNode = this.nodes[this.nodes.length - 1];
703
			return apply(result, lastNode::removeTag);
704
		}
705
706
		private CommandSyntaxException createNotFoundException(final NbtPathArgument.Node node) {
707
			int index = this.nodeToOriginalPosition.getInt(node);
708
			return NbtPathArgument.ERROR_NOTHING_FOUND.create(this.original.substring(0, index));
709
		}
710
711
		@Override
712
		public String toString() {
713
			return this.original;
714
		}
715
716
		public String asString() {
717
			return this.original;
718
		}
719
	}
720
721
	private interface Node {
722
		void getTag(Tag parent, final List<Tag> output);
723
724
		void getOrCreateTag(Tag parent, Supplier<Tag> child, final List<Tag> output);
725
726
		Tag createPreferredParentTag();
727
728
		int setTag(Tag parent, Supplier<Tag> toAdd);
729
730
		int removeTag(Tag parent);
731
732
		default List<Tag> get(final List<Tag> tags) {
733
			return this.collect(tags, this::getTag);
734
		}
735
736
		default List<Tag> getOrCreate(final List<Tag> tags, final Supplier<Tag> child) {
737
			return this.collect(tags, (tag, output) -> this.getOrCreateTag(tag, child, output));
738
		}
739
740
		default List<Tag> collect(final List<Tag> tags, final BiConsumer<Tag, List<Tag>> collector) {
741
			List<Tag> result = Lists.newArrayList();
742
743
			for (Tag tag : tags) {
744
				collector.accept(tag, result);
745
			}
746
747
			return result;
748
		}
749
	}
750
}
751

Decompiled Minecraft 26.3 source of NbtPathArgument (net/minecraft/commands/arguments/NbtPathArgument.java) with Mojang official mappings, stored verbatim on the site.