2 * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.yang.model.util;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verify;
13 import static com.google.common.base.Verify.verifyNotNull;
14 import static java.util.Objects.requireNonNull;
16 import com.google.common.annotations.Beta;
17 import com.google.common.base.MoreObjects;
18 import com.google.common.base.VerifyException;
19 import com.google.common.collect.ImmutableList;
20 import com.google.common.collect.Iterators;
21 import java.util.ArrayDeque;
22 import java.util.Deque;
23 import java.util.Iterator;
24 import java.util.List;
25 import java.util.NoSuchElementException;
26 import java.util.Optional;
27 import org.eclipse.jdt.annotation.NonNull;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.opendaylight.yangtools.concepts.Mutable;
30 import org.opendaylight.yangtools.yang.common.AbstractQName;
31 import org.opendaylight.yangtools.yang.common.QName;
32 import org.opendaylight.yangtools.yang.common.QNameModule;
33 import org.opendaylight.yangtools.yang.common.UnqualifiedQName;
34 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
35 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextProvider;
36 import org.opendaylight.yangtools.yang.model.api.EffectiveStatementInference;
37 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.PathExpression;
39 import org.opendaylight.yangtools.yang.model.api.PathExpression.DerefSteps;
40 import org.opendaylight.yangtools.yang.model.api.PathExpression.LocationPathSteps;
41 import org.opendaylight.yangtools.yang.model.api.PathExpression.Steps;
42 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
43 import org.opendaylight.yangtools.yang.model.api.SchemaTreeInference;
44 import org.opendaylight.yangtools.yang.model.api.TypeAware;
45 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
46 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
48 import org.opendaylight.yangtools.yang.model.api.stmt.CaseEffectiveStatement;
49 import org.opendaylight.yangtools.yang.model.api.stmt.ChoiceEffectiveStatement;
50 import org.opendaylight.yangtools.yang.model.api.stmt.DataTreeAwareEffectiveStatement;
51 import org.opendaylight.yangtools.yang.model.api.stmt.DataTreeEffectiveStatement;
52 import org.opendaylight.yangtools.yang.model.api.stmt.GroupingEffectiveStatement;
53 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
54 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
55 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
56 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeAwareEffectiveStatement;
57 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
58 import org.opendaylight.yangtools.yang.model.api.stmt.TypedefEffectiveStatement;
59 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
60 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
61 import org.opendaylight.yangtools.yang.model.spi.AbstractEffectiveStatementInference;
62 import org.opendaylight.yangtools.yang.model.spi.DefaultSchemaTreeInference;
63 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath;
64 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.AxisStep;
65 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.QNameStep;
66 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.Step;
67 import org.opendaylight.yangtools.yang.xpath.api.YangXPathAxis;
70 * A state tracking utility for walking {@link EffectiveModelContext}'s contents along schema/grouping namespaces. This
71 * is conceptually a stack, tracking {@link EffectiveStatement}s encountered along traversal.
74 * This is meant to be a replacement concept for the use of {@link SchemaPath} in various places, notably
75 * in {@link SchemaContextUtil} methods.
78 * This class is designed for single-threaded uses and does not make any guarantees around concurrent access.
81 public final class SchemaInferenceStack implements Mutable, EffectiveModelContextProvider, LeafrefResolver {
83 * Semantic binding of {@link EffectiveStatementInference} produced by {@link SchemaInferenceStack}. Sequence of
84 * {@link #statementPath()} is implementation-specific.
87 public static final class Inference extends AbstractEffectiveStatementInference<EffectiveStatement<?, ?>> {
88 private final ArrayDeque<EffectiveStatement<?, ?>> deque;
89 private final ModuleEffectiveStatement currentModule;
90 private final int groupingDepth;
91 private final boolean clean;
93 Inference(final @NonNull EffectiveModelContext modelContext, final ArrayDeque<EffectiveStatement<?, ?>> deque,
94 final ModuleEffectiveStatement currentModule, final int groupingDepth, final boolean clean) {
96 this.deque = requireNonNull(deque);
97 this.currentModule = currentModule;
98 this.groupingDepth = groupingDepth;
103 * Create a new stack backed by an effective model and set up to point and specified data tree node.
105 * @param effectiveModel EffectiveModelContext to which this stack is attached
106 * @param qnames Data tree path qnames
107 * @return A new stack
108 * @throws NullPointerException if any argument is null or path contains a null element
109 * @throws IllegalArgumentException if a path element cannot be found
111 public static @NonNull Inference ofDataTreePath(final EffectiveModelContext effectiveModel,
112 final QName... qnames) {
113 return SchemaInferenceStack.ofDataTreePath(effectiveModel, qnames).toInference();
117 public List<EffectiveStatement<?, ?>> statementPath() {
118 return ImmutableList.copyOf(deque.descendingIterator());
122 * Convert this inference into a {@link SchemaInferenceStack}.
124 * @return A new stack
126 public @NonNull SchemaInferenceStack toSchemaInferenceStack() {
127 return new SchemaInferenceStack(getEffectiveModelContext(), deque, currentModule, groupingDepth, clean);
131 private final @NonNull EffectiveModelContext effectiveModel;
132 private final ArrayDeque<EffectiveStatement<?, ?>> deque;
134 private @Nullable ModuleEffectiveStatement currentModule;
135 private int groupingDepth;
137 // True if there were only steps along grouping and schema tree, hence it is consistent with SchemaNodeIdentifier
138 // False if we have evidence of a data tree lookup succeeding
139 private boolean clean;
141 private SchemaInferenceStack(final EffectiveModelContext effectiveModel, final int expectedSize) {
142 this.deque = new ArrayDeque<>(expectedSize);
143 this.effectiveModel = requireNonNull(effectiveModel);
147 private SchemaInferenceStack(final SchemaInferenceStack source) {
148 this.deque = source.deque.clone();
149 this.effectiveModel = source.effectiveModel;
150 this.currentModule = source.currentModule;
151 this.groupingDepth = source.groupingDepth;
152 this.clean = source.clean;
155 private SchemaInferenceStack(final EffectiveModelContext effectiveModel,
156 final ArrayDeque<EffectiveStatement<?, ?>> deque, final ModuleEffectiveStatement currentModule,
157 final int groupingDepth, final boolean clean) {
158 this.effectiveModel = requireNonNull(effectiveModel);
159 this.deque = deque.clone();
160 this.currentModule = currentModule;
161 this.groupingDepth = groupingDepth;
165 private SchemaInferenceStack(final EffectiveModelContext effectiveModel) {
166 this.effectiveModel = requireNonNull(effectiveModel);
167 this.deque = new ArrayDeque<>();
172 * Create a new empty stack backed by an effective model.
174 * @param effectiveModel EffectiveModelContext to which this stack is attached
175 * @return A new stack
176 * @throws NullPointerException if {@code effectiveModel} is null
178 public static @NonNull SchemaInferenceStack of(final EffectiveModelContext effectiveModel) {
179 return new SchemaInferenceStack(effectiveModel);
183 * Create a new stack backed by an effective model, pointing to specified schema node identified by
186 * @param effectiveModel EffectiveModelContext to which this stack is attached
187 * @return A new stack
188 * @throws NullPointerException if {@code effectiveModel} is null
189 * @throws IllegalArgumentException if {@code path} cannot be resolved in the effective model
191 public static @NonNull SchemaInferenceStack of(final EffectiveModelContext effectiveModel, final Absolute path) {
192 final SchemaInferenceStack ret = new SchemaInferenceStack(effectiveModel);
193 path.getNodeIdentifiers().forEach(ret::enterSchemaTree);
198 * Create a new stack from an {@link EffectiveStatementInference}.
200 * @param inference Inference to use for initialization
201 * @return A new stack
202 * @throws NullPointerException if {@code inference} is null
203 * @throws IllegalArgumentException if {@code inference} implementation is not supported
205 public static @NonNull SchemaInferenceStack ofInference(final EffectiveStatementInference inference) {
206 if (inference.statementPath().isEmpty()) {
207 return new SchemaInferenceStack(inference.getEffectiveModelContext());
208 } else if (inference instanceof SchemaTreeInference) {
209 return ofInference((SchemaTreeInference) inference);
210 } else if (inference instanceof Inference) {
211 return ((Inference) inference).toSchemaInferenceStack();
213 throw new IllegalArgumentException("Unsupported Inference " + inference);
218 * Create a new stack from an {@link SchemaTreeInference}.
220 * @param inference SchemaTreeInference to use for initialization
221 * @return A new stack
222 * @throws NullPointerException if {@code inference} is null
223 * @throws IllegalArgumentException if {@code inference} cannot be resolved to a valid stack
225 public static @NonNull SchemaInferenceStack ofInference(final SchemaTreeInference inference) {
226 return of(inference.getEffectiveModelContext(), inference.toSchemaNodeIdentifier());
230 * Create a new stack backed by an effective model and set up to point and specified data tree node.
232 * @param effectiveModel EffectiveModelContext to which this stack is attached
233 * @return A new stack
234 * @throws NullPointerException if any argument is null or path contains a null element
235 * @throws IllegalArgumentException if a path element cannot be found
237 public static @NonNull SchemaInferenceStack ofDataTreePath(final EffectiveModelContext effectiveModel,
238 final QName... path) {
239 final SchemaInferenceStack ret = new SchemaInferenceStack(effectiveModel);
240 for (QName qname : path) {
241 ret.enterDataTree(qname);
247 * Create a new stack backed by an effective model, pointing to specified schema node identified by an absolute
248 * {@link SchemaPath} and its {@link SchemaPath#getPathFromRoot()}.
250 * @param effectiveModel EffectiveModelContext to which this stack is attached
251 * @return A new stack
252 * @throws NullPointerException {@code effectiveModel} is null
253 * @throws IllegalArgumentException if {@code path} cannot be resolved in the effective model or if it is not an
257 public static @NonNull SchemaInferenceStack ofInstantiatedPath(final EffectiveModelContext effectiveModel,
258 final SchemaPath path) {
259 checkArgument(path.isAbsolute(), "Cannot operate on relative path %s", path);
260 final SchemaInferenceStack ret = new SchemaInferenceStack(effectiveModel);
261 path.getPathFromRoot().forEach(ret::enterSchemaTree);
266 public EffectiveModelContext getEffectiveModelContext() {
267 return effectiveModel;
271 * Create a deep copy of this object.
273 * @return An isolated copy of this object
275 public @NonNull SchemaInferenceStack copy() {
276 return new SchemaInferenceStack(this);
280 * Check if this stack is empty.
282 * @return True if this stack has not entered any node.
284 public boolean isEmpty() {
285 return deque.isEmpty();
289 * Return the statement at the top of the stack.
291 * @return Top statement
292 * @throws IllegalStateException if the stack is empty
294 public @NonNull EffectiveStatement<?, ?> currentStatement() {
295 return checkNonNullState(deque.peekFirst());
299 * Return current module the stack has entered.
301 * @return Current module
302 * @throws IllegalStateException if the stack is empty
304 public @NonNull ModuleEffectiveStatement currentModule() {
305 return checkNonNullState(currentModule);
309 * Check if the stack is in instantiated context. This indicates the stack is non-empty and there are only screma
310 * tree statements in the stack.
312 * @return False if the stack is empty or contains a statement which is not a {@link SchemaTreeEffectiveStatement},
315 public boolean inInstantiatedContext() {
316 return groupingDepth == 0 && !deque.isEmpty()
317 && deque.stream().allMatch(SchemaTreeEffectiveStatement.class::isInstance);
321 * Check if the stack is in a {@code grouping} context.
323 * @return False if the stack contains a grouping.
325 public boolean inGrouping() {
326 return groupingDepth != 0;
330 * Reset this stack to empty state.
332 public void clear() {
334 currentModule = null;
340 * Lookup a {@code choice} by its node identifier and push it to the stack. This step is very similar to
341 * {@link #enterSchemaTree(QName)}, except it handles the use case where traversal ignores actual {@code case}
342 * intermediate schema tree children.
344 * @param nodeIdentifier Node identifier of the choice to enter
345 * @return Resolved choice
346 * @throws NullPointerException if {@code nodeIdentifier} is null
347 * @throws IllegalArgumentException if the corresponding choice cannot be found
349 public @NonNull ChoiceEffectiveStatement enterChoice(final QName nodeIdentifier) {
350 final EffectiveStatement<?, ?> parent = deque.peek();
351 if (parent instanceof ChoiceEffectiveStatement) {
352 return enterChoice((ChoiceEffectiveStatement) parent, nodeIdentifier);
355 // Fall back to schema tree lookup. Note if it results in non-choice, we rewind before reporting an error
356 final SchemaTreeEffectiveStatement<?> result = enterSchemaTree(nodeIdentifier);
357 if (result instanceof ChoiceEffectiveStatement) {
358 return (ChoiceEffectiveStatement) result;
361 throw new IllegalArgumentException("Choice " + nodeIdentifier + " not present");
364 // choice -> choice transition, we have to deal with intermediate case nodes
365 private @NonNull ChoiceEffectiveStatement enterChoice(final ChoiceEffectiveStatement parent,
366 final QName nodeIdentifier) {
367 for (EffectiveStatement<?, ?> stmt : parent.effectiveSubstatements()) {
368 if (stmt instanceof CaseEffectiveStatement) {
369 final Optional<ChoiceEffectiveStatement> optMatch = ((CaseEffectiveStatement) stmt)
370 .findSchemaTreeNode(nodeIdentifier)
371 .filter(ChoiceEffectiveStatement.class::isInstance)
372 .map(ChoiceEffectiveStatement.class::cast);
373 if (optMatch.isPresent()) {
374 final SchemaTreeEffectiveStatement<?> match = optMatch.orElseThrow();
377 return (ChoiceEffectiveStatement) match;
381 throw new IllegalArgumentException("Choice " + nodeIdentifier + " not present");
385 * Lookup a {@code grouping} by its node identifier and push it to the stack.
387 * @param nodeIdentifier Node identifier of the grouping to enter
388 * @return Resolved grouping
389 * @throws NullPointerException if {@code nodeIdentifier} is null
390 * @throws IllegalArgumentException if the corresponding grouping cannot be found
392 public @NonNull GroupingEffectiveStatement enterGrouping(final QName nodeIdentifier) {
393 return pushGrouping(requireNonNull(nodeIdentifier));
397 * Lookup a {@code schema tree} child by its node identifier and push it to the stack.
399 * @param nodeIdentifier Node identifier of the schema tree child to enter
400 * @return Resolved schema tree child
401 * @throws NullPointerException if {@code nodeIdentifier} is null
402 * @throws IllegalArgumentException if the corresponding child cannot be found
404 public @NonNull SchemaTreeEffectiveStatement<?> enterSchemaTree(final QName nodeIdentifier) {
405 return pushSchema(requireNonNull(nodeIdentifier));
409 * Lookup a {@code schema tree} node by its schema node identifier and push it to the stack.
411 * @param nodeIdentifier Schema node identifier of the schema tree node to enter
412 * @return Resolved schema tree node
413 * @throws NullPointerException if {@code nodeIdentifier} is null
414 * @throws IllegalArgumentException if the corresponding node cannot be found
416 public @NonNull SchemaTreeEffectiveStatement<?> enterSchemaTree(final SchemaNodeIdentifier nodeIdentifier) {
417 if (nodeIdentifier instanceof Absolute) {
421 final Iterator<QName> it = nodeIdentifier.getNodeIdentifiers().iterator();
422 SchemaTreeEffectiveStatement<?> ret;
424 ret = enterSchemaTree(it.next());
425 } while (it.hasNext());
431 * Lookup a {@code schema tree} child by its node identifier and push it to the stack.
433 * @param nodeIdentifier Node identifier of the date tree child to enter
434 * @return Resolved date tree child
435 * @throws NullPointerException if {@code nodeIdentifier} is null
436 * @throws IllegalArgumentException if the corresponding child cannot be found
438 public @NonNull DataTreeEffectiveStatement<?> enterDataTree(final QName nodeIdentifier) {
439 return pushData(requireNonNull(nodeIdentifier));
443 * Lookup a {@code typedef} by its node identifier and push it to the stack.
445 * @param nodeIdentifier Node identifier of the typedef to enter
446 * @return Resolved choice
447 * @throws NullPointerException if {@code nodeIdentifier} is null
448 * @throws IllegalArgumentException if the corresponding typedef cannot be found
450 public @NonNull TypedefEffectiveStatement enterTypedef(final QName nodeIdentifier) {
451 return pushTypedef(requireNonNull(nodeIdentifier));
455 * Pop the current statement from the stack.
457 * @return Previous statement
458 * @throws NoSuchElementException if this stack is empty
460 public @NonNull EffectiveStatement<?, ?> exit() {
461 final EffectiveStatement<?, ?> prev = deque.pop();
462 if (prev instanceof GroupingEffectiveStatement) {
465 if (deque.isEmpty()) {
466 currentModule = null;
473 * Pop the current statement from the stack, asserting it is a {@link DataTreeEffectiveStatement} and that
474 * subsequent {@link #enterDataTree(QName)} will find it again.
476 * @return Previous statement
477 * @throws NoSuchElementException if this stack is empty
478 * @throws IllegalStateException if current statement is not a DataTreeEffectiveStatement or if its parent is not
479 * a {@link DataTreeAwareEffectiveStatement}
481 public @NonNull DataTreeEffectiveStatement<?> exitToDataTree() {
482 final EffectiveStatement<?, ?> child = exit();
483 checkState(child instanceof DataTreeEffectiveStatement, "Unexpected current %s", child);
484 EffectiveStatement<?, ?> parent = deque.peekFirst();
485 while (parent instanceof ChoiceEffectiveStatement || parent instanceof CaseEffectiveStatement) {
487 parent = deque.peekFirst();
490 checkState(parent == null || parent instanceof DataTreeAwareEffectiveStatement, "Unexpected parent %s", parent);
491 return (DataTreeEffectiveStatement<?>) child;
496 public TypeDefinition<?> resolveLeafref(final LeafrefTypeDefinition type) {
497 final SchemaInferenceStack tmp = copy();
499 LeafrefTypeDefinition current = type;
501 final EffectiveStatement<?, ?> resolved = tmp.resolvePathExpression(current.getPathStatement());
502 checkState(resolved instanceof TypeAware, "Unexpected result %s resultion of %s", resolved, type);
503 final TypeDefinition<?> result = ((TypedDataSchemaNode) resolved).getType();
504 if (result instanceof LeafrefTypeDefinition) {
505 checkArgument(result != type, "Resolution of %s loops back onto itself via %s", type, current);
506 current = (LeafrefTypeDefinition) result;
514 * Resolve a {@link PathExpression}.
517 * Note if this method throws, this stack may be in an undefined state.
519 * @param path Requested path
520 * @return Resolved schema tree child
521 * @throws NullPointerException if {@code path} is null
522 * @throws IllegalArgumentException if the target node cannot be found
523 * @throws VerifyException if path expression is invalid
525 public @NonNull EffectiveStatement<?, ?> resolvePathExpression(final PathExpression path) {
526 final Steps steps = path.getSteps();
527 if (steps instanceof LocationPathSteps) {
528 return resolveLocationPath(((LocationPathSteps) steps).getLocationPath());
529 } else if (steps instanceof DerefSteps) {
530 return resolveDeref((DerefSteps) steps);
532 throw new VerifyException("Unhandled steps " + steps);
536 private @NonNull EffectiveStatement<?, ?> resolveDeref(final DerefSteps deref) {
537 final EffectiveStatement<?, ?> leafRefSchemaNode = currentStatement();
538 final YangLocationPath.Relative derefArg = deref.getDerefArgument();
539 final EffectiveStatement<?, ?> derefStmt = resolveLocationPath(derefArg);
540 checkArgument(derefStmt != null, "Cannot find deref(%s) target node %s in context of %s",
541 derefArg, leafRefSchemaNode);
542 checkArgument(derefStmt instanceof TypedDataSchemaNode, "deref(%s) resolved to non-typed %s", derefArg,
545 // We have a deref() target, decide what to do about it
546 final TypeDefinition<?> targetType = ((TypedDataSchemaNode) derefStmt).getType();
547 if (targetType instanceof InstanceIdentifierTypeDefinition) {
548 // Static inference breaks down, we cannot determine where this points to
549 // FIXME: dedicated exception, users can recover from it, derive from IAE
550 throw new UnsupportedOperationException("Cannot infer instance-identifier reference " + targetType);
553 // deref() is defined only for instance-identifier and leafref types, handle the latter
554 checkArgument(targetType instanceof LeafrefTypeDefinition, "Illegal target type %s", targetType);
556 final PathExpression dereferencedLeafRefPath = ((LeafrefTypeDefinition) targetType).getPathStatement();
557 EffectiveStatement<?, ?> derefNode = resolvePathExpression(dereferencedLeafRefPath);
558 checkArgument(derefStmt != null, "Can not find target node of dereferenced node %s", derefStmt);
559 checkArgument(derefNode instanceof LeafSchemaNode, "Unexpected %s reference in %s", deref,
560 dereferencedLeafRefPath);
561 return resolveLocationPath(deref.getRelativePath());
564 private @NonNull EffectiveStatement<?, ?> resolveLocationPath(final YangLocationPath path) {
565 // get the default namespace before we clear and loose our deque
566 final QNameModule defaultNamespace = deque.isEmpty() ? null : ((QName) deque.peek().argument()).getModule();
567 if (path.isAbsolute()) {
571 EffectiveStatement<?, ?> current = null;
572 for (Step step : path.getSteps()) {
573 final YangXPathAxis axis = step.getAxis();
576 verify(step instanceof AxisStep, "Unexpected parent step %s", step);
578 current = exitToDataTree();
579 } catch (IllegalStateException | NoSuchElementException e) {
580 throw new IllegalArgumentException("Illegal parent access in " + path, e);
584 verify(step instanceof QNameStep, "Unexpected child step %s", step);
585 current = enterChild((QNameStep) step, defaultNamespace);
588 throw new VerifyException("Unexpected step " + step);
592 return verifyNotNull(current);
595 private @NonNull EffectiveStatement<?, ?> enterChild(final QNameStep step, final QNameModule defaultNamespace) {
596 final AbstractQName toResolve = step.getQName();
598 if (toResolve instanceof QName) {
599 qname = (QName) toResolve;
600 } else if (toResolve instanceof UnqualifiedQName) {
601 checkArgument(defaultNamespace != null, "Can not find target module of step %s", step);
602 qname = ((UnqualifiedQName) toResolve).bindTo(defaultNamespace);
604 throw new VerifyException("Unexpected child step QName " + toResolve);
606 return enterDataTree(qname);
610 * Return an {@link Inference} equivalent of current state.
612 * @return An {@link Inference}
614 public @NonNull Inference toInference() {
615 return new Inference(effectiveModel, deque.clone(), currentModule, groupingDepth, clean);
619 * Return an {@link SchemaTreeInference} equivalent of current state.
621 * @return An {@link SchemaTreeInference}
622 * @throws IllegalStateException if current state cannot be converted to a {@link SchemaTreeInference}
624 public @NonNull SchemaTreeInference toSchemaTreeInference() {
625 return DefaultSchemaTreeInference.of(getEffectiveModelContext(), toSchemaNodeIdentifier());
629 * Convert current state into an absolute schema node identifier.
631 * @return Absolute schema node identifier representing current state
632 * @throws IllegalStateException if current state is not instantiated
634 public @NonNull Absolute toSchemaNodeIdentifier() {
635 checkState(inInstantiatedContext(), "Cannot convert uninstantiated context %s", this);
636 return Absolute.of(ImmutableList.<QName>builderWithExpectedSize(deque.size())
637 .addAll(simplePathFromRoot())
642 * Convert current state into a SchemaPath.
644 * @return Absolute SchemaPath representing current state
645 * @throws IllegalStateException if current state is not instantiated
646 * @deprecated This method is meant only for interoperation with SchemaPath-based APIs.
649 public @NonNull SchemaPath toSchemaPath() {
650 SchemaPath ret = SchemaPath.ROOT;
651 final Iterator<QName> it = simplePathFromRoot();
652 while (it.hasNext()) {
653 ret = ret.createChild(it.next());
659 * Return an iterator along {@link SchemaPath#getPathFromRoot()}. This method is a faster equivalent of
660 * {@code toSchemaPath().getPathFromRoot().iterator()}.
662 * @return An unmodifiable iterator
665 public @NonNull Iterator<QName> schemaPathIterator() {
666 return Iterators.unmodifiableIterator(simplePathFromRoot());
670 public String toString() {
671 return MoreObjects.toStringHelper(this).add("stack", deque).toString();
674 private @NonNull GroupingEffectiveStatement pushGrouping(final @NonNull QName nodeIdentifier) {
675 final EffectiveStatement<?, ?> parent = deque.peekFirst();
676 return parent != null ? pushGrouping(parent, nodeIdentifier) : pushFirstGrouping(nodeIdentifier);
679 private @NonNull GroupingEffectiveStatement pushGrouping(final @NonNull EffectiveStatement<?, ?> parent,
680 final @NonNull QName nodeIdentifier) {
681 final GroupingEffectiveStatement ret = parent.streamEffectiveSubstatements(GroupingEffectiveStatement.class)
682 .filter(stmt -> nodeIdentifier.equals(stmt.argument()))
684 .orElseThrow(() -> new IllegalArgumentException("Grouping " + nodeIdentifier + " not present"));
690 private @NonNull GroupingEffectiveStatement pushFirstGrouping(final @NonNull QName nodeIdentifier) {
691 final ModuleEffectiveStatement module = getModule(nodeIdentifier);
692 final GroupingEffectiveStatement ret = pushGrouping(module, nodeIdentifier);
693 currentModule = module;
697 private @NonNull SchemaTreeEffectiveStatement<?> pushSchema(final @NonNull QName nodeIdentifier) {
698 final EffectiveStatement<?, ?> parent = deque.peekFirst();
699 return parent != null ? pushSchema(parent, nodeIdentifier) : pushFirstSchema(nodeIdentifier);
702 private @NonNull SchemaTreeEffectiveStatement<?> pushSchema(final EffectiveStatement<?, ?> parent,
703 final @NonNull QName nodeIdentifier) {
704 checkState(parent instanceof SchemaTreeAwareEffectiveStatement, "Cannot descend schema tree at %s", parent);
705 return pushSchema((SchemaTreeAwareEffectiveStatement<?, ?>) parent, nodeIdentifier);
708 private @NonNull SchemaTreeEffectiveStatement<?> pushSchema(
709 final @NonNull SchemaTreeAwareEffectiveStatement<?, ?> parent, final @NonNull QName nodeIdentifier) {
710 final SchemaTreeEffectiveStatement<?> ret = parent.findSchemaTreeNode(nodeIdentifier).orElseThrow(
711 () -> new IllegalArgumentException("Schema tree child " + nodeIdentifier + " not present"));
716 private @NonNull SchemaTreeEffectiveStatement<?> pushFirstSchema(final @NonNull QName nodeIdentifier) {
717 final ModuleEffectiveStatement module = getModule(nodeIdentifier);
718 final SchemaTreeEffectiveStatement<?> ret = pushSchema(module, nodeIdentifier);
719 currentModule = module;
723 private @NonNull DataTreeEffectiveStatement<?> pushData(final @NonNull QName nodeIdentifier) {
724 final EffectiveStatement<?, ?> parent = deque.peekFirst();
725 return parent != null ? pushData(parent, nodeIdentifier) : pushFirstData(nodeIdentifier);
728 private @NonNull DataTreeEffectiveStatement<?> pushData(final EffectiveStatement<?, ?> parent,
729 final @NonNull QName nodeIdentifier) {
730 checkState(parent instanceof DataTreeAwareEffectiveStatement, "Cannot descend data tree at %s", parent);
731 return pushData((DataTreeAwareEffectiveStatement<?, ?>) parent, nodeIdentifier);
734 private @NonNull DataTreeEffectiveStatement<?> pushData(final @NonNull DataTreeAwareEffectiveStatement<?, ?> parent,
735 final @NonNull QName nodeIdentifier) {
736 final DataTreeEffectiveStatement<?> ret = parent.findDataTreeNode(nodeIdentifier).orElseThrow(
737 () -> new IllegalArgumentException("Data tree child " + nodeIdentifier + " not present"));
743 private @NonNull DataTreeEffectiveStatement<?> pushFirstData(final @NonNull QName nodeIdentifier) {
744 final ModuleEffectiveStatement module = getModule(nodeIdentifier);
745 final DataTreeEffectiveStatement<?> ret = pushData(module, nodeIdentifier);
746 currentModule = module;
750 private @NonNull TypedefEffectiveStatement pushTypedef(final @NonNull QName nodeIdentifier) {
751 final EffectiveStatement<?, ?> parent = deque.peekFirst();
752 return parent != null ? pushTypedef(parent, nodeIdentifier) : pushFirstTypedef(nodeIdentifier);
755 private @NonNull TypedefEffectiveStatement pushTypedef(final @NonNull EffectiveStatement<?, ?> parent,
756 final @NonNull QName nodeIdentifier) {
757 // TODO: 8.0.0: revisit this once we have TypedefNamespace working
758 final TypedefEffectiveStatement ret = parent.streamEffectiveSubstatements(TypedefEffectiveStatement.class)
759 .filter(stmt -> nodeIdentifier.equals(stmt.argument()))
761 .orElseThrow(() -> new IllegalArgumentException("Grouping " + nodeIdentifier + " not present"));
766 private @NonNull TypedefEffectiveStatement pushFirstTypedef(final @NonNull QName nodeIdentifier) {
767 final ModuleEffectiveStatement module = getModule(nodeIdentifier);
768 final TypedefEffectiveStatement ret = pushTypedef(module, nodeIdentifier);
769 currentModule = module;
773 private @NonNull ModuleEffectiveStatement getModule(final @NonNull QName nodeIdentifier) {
774 final ModuleEffectiveStatement module = effectiveModel.getModuleStatements().get(nodeIdentifier.getModule());
775 checkArgument(module != null, "Module for %s not found", nodeIdentifier);
779 // Unified access to queue iteration for addressing purposes. Since we keep 'logical' steps as executed by user
780 // at this point, conversion to SchemaNodeIdentifier may be needed. We dispatch based on 'clean'.
781 private Iterator<QName> simplePathFromRoot() {
782 return clean ? iterateQNames() : reconstructQNames();
785 private Iterator<QName> iterateQNames() {
786 return Iterators.transform(deque.descendingIterator(), stmt -> {
787 final Object argument = stmt.argument();
788 verify(argument instanceof QName, "Unexpected statement %s", stmt);
789 return (QName) argument;
793 // So there are some data tree steps in the stack... we essentially need to convert a data tree item into a series
794 // of schema tree items. This means at least N searches, but after they are done, we get an opportunity to set the
796 private Iterator<QName> reconstructQNames() {
797 // Let's walk all statements and decipher them into a temporary stack
798 final SchemaInferenceStack tmp = new SchemaInferenceStack(effectiveModel, deque.size());
799 final Iterator<EffectiveStatement<?, ?>> it = deque.descendingIterator();
800 while (it.hasNext()) {
801 final EffectiveStatement<?, ?> stmt = it.next();
802 // Order of checks is significant
803 if (stmt instanceof DataTreeEffectiveStatement) {
804 tmp.resolveDataTreeSteps(((DataTreeEffectiveStatement<?>) stmt).argument());
805 } else if (stmt instanceof ChoiceEffectiveStatement) {
806 tmp.resolveChoiceSteps(((ChoiceEffectiveStatement) stmt).argument());
807 } else if (stmt instanceof SchemaTreeEffectiveStatement) {
808 tmp.enterSchemaTree(((SchemaTreeEffectiveStatement<?> )stmt).argument());
809 } else if (stmt instanceof GroupingEffectiveStatement) {
810 tmp.enterGrouping(((GroupingEffectiveStatement) stmt).argument());
811 } else if (stmt instanceof TypedefEffectiveStatement) {
812 tmp.enterTypedef(((TypedefEffectiveStatement) stmt).argument());
814 throw new VerifyException("Unexpected statement " + stmt);
818 // if the sizes match, we did not jump through hoops. let's remember that for future.
819 clean = deque.size() == tmp.deque.size();
820 return tmp.iterateQNames();
823 private void resolveChoiceSteps(final @NonNull QName nodeIdentifier) {
824 final EffectiveStatement<?, ?> parent = deque.peekFirst();
825 if (parent instanceof ChoiceEffectiveStatement) {
826 resolveChoiceSteps((ChoiceEffectiveStatement) parent, nodeIdentifier);
828 enterSchemaTree(nodeIdentifier);
832 private void resolveChoiceSteps(final @NonNull ChoiceEffectiveStatement parent,
833 final @NonNull QName nodeIdentifier) {
834 for (EffectiveStatement<?, ?> stmt : parent.effectiveSubstatements()) {
835 if (stmt instanceof CaseEffectiveStatement) {
836 final CaseEffectiveStatement caze = (CaseEffectiveStatement) stmt;
837 final SchemaTreeEffectiveStatement<?> found = caze.findSchemaTreeNode(nodeIdentifier).orElse(null);
838 if (found instanceof ChoiceEffectiveStatement) {
845 throw new VerifyException("Failed to resolve " + nodeIdentifier + " in " + parent);
848 private void resolveDataTreeSteps(final @NonNull QName nodeIdentifier) {
849 final EffectiveStatement<?, ?> parent = deque.peekFirst();
850 if (parent != null) {
851 verify(parent instanceof SchemaTreeAwareEffectiveStatement, "Unexpected parent %s", parent);
852 resolveDataTreeSteps((SchemaTreeAwareEffectiveStatement<?, ?>) parent, nodeIdentifier);
856 final ModuleEffectiveStatement module = getModule(nodeIdentifier);
857 resolveDataTreeSteps(module, nodeIdentifier);
858 currentModule = module;
861 private void resolveDataTreeSteps(final @NonNull SchemaTreeAwareEffectiveStatement<?, ?> parent,
862 final @NonNull QName nodeIdentifier) {
863 // The algebra of identifiers in 'schema tree versus data tree':
864 // - data tree parents are always schema tree parents
865 // - data tree children are always schema tree children
867 // that implies that a data tree parent must satisfy schema tree queries with data tree children,
868 // so a successful lookup of 'data tree parent -> child' and 'schema tree parent -> child' has to be the same
869 // for a direct lookup.
870 final SchemaTreeEffectiveStatement<?> found = parent.findSchemaTreeNode(nodeIdentifier).orElse(null);
871 if (found instanceof DataTreeEffectiveStatement) {
872 // ... and it did, we are done
877 // Alright, so now it's down to filtering choice/case statements. For that we keep some globally-reused state
878 // and employ a recursive match.
879 final Deque<EffectiveStatement<QName, ?>> match = new ArrayDeque<>();
880 for (EffectiveStatement<?, ?> stmt : parent.effectiveSubstatements()) {
881 if (stmt instanceof ChoiceEffectiveStatement
882 && searchChoice(match, (ChoiceEffectiveStatement) stmt, nodeIdentifier)) {
883 match.descendingIterator().forEachRemaining(deque::push);
888 throw new VerifyException("Failed to resolve " + nodeIdentifier + " in " + parent);
891 private static boolean searchCase(final @NonNull Deque<EffectiveStatement<QName, ?>> result,
892 final @NonNull CaseEffectiveStatement parent, final @NonNull QName nodeIdentifier) {
894 for (EffectiveStatement<?, ?> stmt : parent.effectiveSubstatements()) {
895 if (stmt instanceof DataTreeEffectiveStatement && nodeIdentifier.equals(stmt.argument())) {
896 result.push((DataTreeEffectiveStatement<?>) stmt);
899 if (stmt instanceof ChoiceEffectiveStatement
900 && searchChoice(result, (ChoiceEffectiveStatement) stmt, nodeIdentifier)) {
908 private static boolean searchChoice(final @NonNull Deque<EffectiveStatement<QName, ?>> result,
909 final @NonNull ChoiceEffectiveStatement parent, final @NonNull QName nodeIdentifier) {
911 for (EffectiveStatement<?, ?> stmt : parent.effectiveSubstatements()) {
912 if (stmt instanceof CaseEffectiveStatement
913 && searchCase(result, (CaseEffectiveStatement) stmt, nodeIdentifier)) {
921 private static <T> @NonNull T checkNonNullState(final @Nullable T obj) {
923 throw new IllegalStateException("Cannot execute on empty stack");