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.rfc8040.model.api.YangDataEffectiveStatement;
31 import org.opendaylight.yangtools.yang.common.AbstractQName;
32 import org.opendaylight.yangtools.yang.common.QName;
33 import org.opendaylight.yangtools.yang.common.QNameModule;
34 import org.opendaylight.yangtools.yang.common.UnqualifiedQName;
35 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
36 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextProvider;
37 import org.opendaylight.yangtools.yang.model.api.EffectiveStatementInference;
38 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.PathExpression;
40 import org.opendaylight.yangtools.yang.model.api.PathExpression.DerefSteps;
41 import org.opendaylight.yangtools.yang.model.api.PathExpression.LocationPathSteps;
42 import org.opendaylight.yangtools.yang.model.api.PathExpression.Steps;
43 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
44 import org.opendaylight.yangtools.yang.model.api.SchemaTreeInference;
45 import org.opendaylight.yangtools.yang.model.api.TypeAware;
46 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
47 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
49 import org.opendaylight.yangtools.yang.model.api.stmt.CaseEffectiveStatement;
50 import org.opendaylight.yangtools.yang.model.api.stmt.ChoiceEffectiveStatement;
51 import org.opendaylight.yangtools.yang.model.api.stmt.DataTreeAwareEffectiveStatement;
52 import org.opendaylight.yangtools.yang.model.api.stmt.DataTreeEffectiveStatement;
53 import org.opendaylight.yangtools.yang.model.api.stmt.GroupingEffectiveStatement;
54 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
55 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
56 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
57 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeAwareEffectiveStatement;
58 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
59 import org.opendaylight.yangtools.yang.model.api.stmt.TypedefEffectiveStatement;
60 import org.opendaylight.yangtools.yang.model.api.stmt.TypedefNamespace;
61 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
62 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
63 import org.opendaylight.yangtools.yang.model.spi.AbstractEffectiveStatementInference;
64 import org.opendaylight.yangtools.yang.model.spi.DefaultSchemaTreeInference;
65 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath;
66 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.AxisStep;
67 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.QNameStep;
68 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.Step;
69 import org.opendaylight.yangtools.yang.xpath.api.YangXPathAxis;
72 * A state tracking utility for walking {@link EffectiveModelContext}'s contents along schema/grouping namespaces. This
73 * is conceptually a stack, tracking {@link EffectiveStatement}s encountered along traversal.
76 * This is meant to be a replacement concept for the use of {@link SchemaPath} in various places, notably
77 * in {@link SchemaContextUtil} methods.
80 * This class is designed for single-threaded uses and does not make any guarantees around concurrent access.
83 public final class SchemaInferenceStack implements Mutable, EffectiveModelContextProvider, LeafrefResolver {
85 * Semantic binding of {@link EffectiveStatementInference} produced by {@link SchemaInferenceStack}. Sequence of
86 * {@link #statementPath()} is implementation-specific.
89 public static final class Inference extends AbstractEffectiveStatementInference<EffectiveStatement<?, ?>> {
90 private final ArrayDeque<EffectiveStatement<?, ?>> deque;
91 private final ModuleEffectiveStatement currentModule;
92 private final int groupingDepth;
93 private final boolean clean;
95 Inference(final @NonNull EffectiveModelContext modelContext, final ArrayDeque<EffectiveStatement<?, ?>> deque,
96 final ModuleEffectiveStatement currentModule, final int groupingDepth, final boolean clean) {
98 this.deque = requireNonNull(deque);
99 this.currentModule = currentModule;
100 this.groupingDepth = groupingDepth;
105 * Create a new stack backed by an effective model and set up to point and specified data tree node.
107 * @param effectiveModel EffectiveModelContext to which this stack is attached
108 * @param qnames Data tree path qnames
109 * @return A new stack
110 * @throws NullPointerException if any argument is null or path contains a null element
111 * @throws IllegalArgumentException if a path element cannot be found
113 public static @NonNull Inference ofDataTreePath(final EffectiveModelContext effectiveModel,
114 final QName... qnames) {
115 return SchemaInferenceStack.ofDataTreePath(effectiveModel, qnames).toInference();
119 public List<EffectiveStatement<?, ?>> statementPath() {
120 return ImmutableList.copyOf(deque.descendingIterator());
124 * Convert this inference into a {@link SchemaInferenceStack}.
126 * @return A new stack
128 public @NonNull SchemaInferenceStack toSchemaInferenceStack() {
129 return new SchemaInferenceStack(getEffectiveModelContext(), deque, currentModule, groupingDepth, clean);
133 private final @NonNull EffectiveModelContext effectiveModel;
134 private final ArrayDeque<EffectiveStatement<?, ?>> deque;
136 private @Nullable ModuleEffectiveStatement currentModule;
137 private int groupingDepth;
139 // True if there were only steps along grouping and schema tree, hence it is consistent with SchemaNodeIdentifier
140 // False if we have evidence of a data tree lookup succeeding
141 private boolean clean;
143 private SchemaInferenceStack(final EffectiveModelContext effectiveModel, final int expectedSize) {
144 this.deque = new ArrayDeque<>(expectedSize);
145 this.effectiveModel = requireNonNull(effectiveModel);
149 private SchemaInferenceStack(final SchemaInferenceStack source) {
150 this.deque = source.deque.clone();
151 this.effectiveModel = source.effectiveModel;
152 this.currentModule = source.currentModule;
153 this.groupingDepth = source.groupingDepth;
154 this.clean = source.clean;
157 private SchemaInferenceStack(final EffectiveModelContext effectiveModel,
158 final ArrayDeque<EffectiveStatement<?, ?>> deque, final ModuleEffectiveStatement currentModule,
159 final int groupingDepth, final boolean clean) {
160 this.effectiveModel = requireNonNull(effectiveModel);
161 this.deque = deque.clone();
162 this.currentModule = currentModule;
163 this.groupingDepth = groupingDepth;
167 private SchemaInferenceStack(final EffectiveModelContext effectiveModel) {
168 this.effectiveModel = requireNonNull(effectiveModel);
169 this.deque = new ArrayDeque<>();
174 * Create a new empty stack backed by an effective model.
176 * @param effectiveModel EffectiveModelContext to which this stack is attached
177 * @return A new stack
178 * @throws NullPointerException if {@code effectiveModel} is null
180 public static @NonNull SchemaInferenceStack of(final EffectiveModelContext effectiveModel) {
181 return new SchemaInferenceStack(effectiveModel);
185 * Create a new stack backed by an effective model, pointing to specified schema node identified by
188 * @param effectiveModel EffectiveModelContext to which this stack is attached
189 * @return A new stack
190 * @throws NullPointerException if {@code effectiveModel} is null
191 * @throws IllegalArgumentException if {@code path} cannot be resolved in the effective model
193 public static @NonNull SchemaInferenceStack of(final EffectiveModelContext effectiveModel, final Absolute path) {
194 final SchemaInferenceStack ret = new SchemaInferenceStack(effectiveModel);
195 path.getNodeIdentifiers().forEach(ret::enterSchemaTree);
200 * Create a new stack from an {@link EffectiveStatementInference}.
202 * @param inference Inference to use for initialization
203 * @return A new stack
204 * @throws NullPointerException if {@code inference} is null
205 * @throws IllegalArgumentException if {@code inference} implementation is not supported
207 public static @NonNull SchemaInferenceStack ofInference(final EffectiveStatementInference inference) {
208 if (inference.statementPath().isEmpty()) {
209 return new SchemaInferenceStack(inference.getEffectiveModelContext());
210 } else if (inference instanceof SchemaTreeInference) {
211 return ofInference((SchemaTreeInference) inference);
212 } else if (inference instanceof Inference) {
213 return ((Inference) inference).toSchemaInferenceStack();
215 throw new IllegalArgumentException("Unsupported Inference " + inference);
220 * Create a new stack from an {@link SchemaTreeInference}.
222 * @param inference SchemaTreeInference to use for initialization
223 * @return A new stack
224 * @throws NullPointerException if {@code inference} is null
225 * @throws IllegalArgumentException if {@code inference} cannot be resolved to a valid stack
227 public static @NonNull SchemaInferenceStack ofInference(final SchemaTreeInference inference) {
228 return of(inference.getEffectiveModelContext(), inference.toSchemaNodeIdentifier());
232 * Create a new stack backed by an effective model and set up to point and specified data tree node.
234 * @param effectiveModel EffectiveModelContext to which this stack is attached
235 * @return A new stack
236 * @throws NullPointerException if any argument is null or path contains a null element
237 * @throws IllegalArgumentException if a path element cannot be found
239 public static @NonNull SchemaInferenceStack ofDataTreePath(final EffectiveModelContext effectiveModel,
240 final QName... path) {
241 final SchemaInferenceStack ret = new SchemaInferenceStack(effectiveModel);
242 for (QName qname : path) {
243 ret.enterDataTree(qname);
249 * Create a new stack backed by an effective model, pointing to specified schema node identified by an absolute
250 * {@link SchemaPath} and its {@link SchemaPath#getPathFromRoot()} interpreted as a schema node identifier.
252 * @param effectiveModel EffectiveModelContext to which this stack is attached
253 * @return A new stack
254 * @throws NullPointerException {@code effectiveModel} is null
255 * @throws IllegalArgumentException if {@code path} cannot be resolved in the effective model or if it is not an
259 public static @NonNull SchemaInferenceStack ofInstantiatedPath(final EffectiveModelContext effectiveModel,
260 final SchemaPath path) {
261 checkArgument(path.isAbsolute(), "Cannot operate on relative path %s", path);
262 final SchemaInferenceStack ret = new SchemaInferenceStack(effectiveModel);
263 path.getPathFromRoot().forEach(ret::enterSchemaTree);
268 * Create a new stack backed by an effective model, pointing to specified schema node identified by an absolute
269 * {@link SchemaPath} and its {@link SchemaPath#getPathFromRoot()}, interpreted as a series of steps along primarily
270 * schema tree, with grouping namespace being the alternative lookup.
272 * @param effectiveModel EffectiveModelContext to which this stack is attached
273 * @return A new stack
274 * @throws NullPointerException {@code effectiveModel} is null
275 * @throws IllegalArgumentException if {@code path} cannot be resolved in the effective model or if it is not an
279 public static @NonNull SchemaInferenceStack ofSchemaPath(final EffectiveModelContext effectiveModel,
280 final SchemaPath path) {
281 checkArgument(path.isAbsolute(), "Cannot operate on relative path %s", path);
282 final SchemaInferenceStack ret = new SchemaInferenceStack(effectiveModel);
284 for (QName step : path.getPathFromRoot()) {
286 ret.enterSchemaTree(step);
287 } catch (IllegalArgumentException schemaEx) {
289 ret.enterGrouping(step);
290 } catch (IllegalArgumentException ex) {
291 ex.addSuppressed(schemaEx);
301 public EffectiveModelContext getEffectiveModelContext() {
302 return effectiveModel;
306 * Create a deep copy of this object.
308 * @return An isolated copy of this object
310 public @NonNull SchemaInferenceStack copy() {
311 return new SchemaInferenceStack(this);
315 * Check if this stack is empty.
317 * @return True if this stack has not entered any node.
319 public boolean isEmpty() {
320 return deque.isEmpty();
324 * Return the statement at the top of the stack.
326 * @return Top statement
327 * @throws IllegalStateException if the stack is empty
329 public @NonNull EffectiveStatement<?, ?> currentStatement() {
330 return checkNonNullState(deque.peekFirst());
334 * Return current module the stack has entered.
336 * @return Current module
337 * @throws IllegalStateException if the stack is empty
339 public @NonNull ModuleEffectiveStatement currentModule() {
340 return checkNonNullState(currentModule);
344 * Check if the stack is in instantiated context. This indicates the stack is non-empty and there are only schema
345 * tree statements in the stack.
347 * @return False if the stack is empty or contains a statement which is not a {@link SchemaTreeEffectiveStatement},
350 public boolean inInstantiatedContext() {
351 return groupingDepth == 0 && !deque.isEmpty()
352 && deque.stream().allMatch(SchemaTreeEffectiveStatement.class::isInstance);
356 * Check if the stack is in a {@code grouping} context.
358 * @return False if the stack contains a grouping.
360 public boolean inGrouping() {
361 return groupingDepth != 0;
365 * Reset this stack to empty state.
367 public void clear() {
369 currentModule = null;
375 * Lookup a {@code choice} by its node identifier and push it to the stack. This step is very similar to
376 * {@link #enterSchemaTree(QName)}, except it handles the use case where traversal ignores actual {@code case}
377 * intermediate schema tree children.
379 * @param nodeIdentifier Node identifier of the choice to enter
380 * @return Resolved choice
381 * @throws NullPointerException if {@code nodeIdentifier} is null
382 * @throws IllegalArgumentException if the corresponding choice cannot be found
384 public @NonNull ChoiceEffectiveStatement enterChoice(final QName nodeIdentifier) {
385 final EffectiveStatement<?, ?> parent = deque.peek();
386 if (parent instanceof ChoiceEffectiveStatement) {
387 return enterChoice((ChoiceEffectiveStatement) parent, nodeIdentifier);
390 // Fall back to schema tree lookup. Note if it results in non-choice, we rewind before reporting an error
391 final SchemaTreeEffectiveStatement<?> result = enterSchemaTree(nodeIdentifier);
392 if (result instanceof ChoiceEffectiveStatement) {
393 return (ChoiceEffectiveStatement) result;
396 throw new IllegalArgumentException("Choice " + nodeIdentifier + " not present");
399 // choice -> choice transition, we have to deal with intermediate case nodes
400 private @NonNull ChoiceEffectiveStatement enterChoice(final ChoiceEffectiveStatement parent,
401 final QName nodeIdentifier) {
402 for (EffectiveStatement<?, ?> stmt : parent.effectiveSubstatements()) {
403 if (stmt instanceof CaseEffectiveStatement) {
404 final Optional<ChoiceEffectiveStatement> optMatch = ((CaseEffectiveStatement) stmt)
405 .findSchemaTreeNode(nodeIdentifier)
406 .filter(ChoiceEffectiveStatement.class::isInstance)
407 .map(ChoiceEffectiveStatement.class::cast);
408 if (optMatch.isPresent()) {
409 final SchemaTreeEffectiveStatement<?> match = optMatch.orElseThrow();
412 return (ChoiceEffectiveStatement) match;
416 throw new IllegalArgumentException("Choice " + nodeIdentifier + " not present");
420 * Lookup a {@code grouping} by its node identifier and push it to the stack.
422 * @param nodeIdentifier Node identifier of the grouping to enter
423 * @return Resolved grouping
424 * @throws NullPointerException if {@code nodeIdentifier} is null
425 * @throws IllegalArgumentException if the corresponding grouping cannot be found
427 public @NonNull GroupingEffectiveStatement enterGrouping(final QName nodeIdentifier) {
428 return pushGrouping(requireNonNull(nodeIdentifier));
432 * Lookup a {@code schema tree} child by its node identifier and push it to the stack.
434 * @param nodeIdentifier Node identifier of the schema tree child to enter
435 * @return Resolved schema tree child
436 * @throws NullPointerException if {@code nodeIdentifier} is null
437 * @throws IllegalArgumentException if the corresponding child cannot be found
439 public @NonNull SchemaTreeEffectiveStatement<?> enterSchemaTree(final QName nodeIdentifier) {
440 return pushSchema(requireNonNull(nodeIdentifier));
444 * Lookup a {@code schema tree} node by its schema node identifier and push it to the stack.
446 * @param nodeIdentifier Schema node identifier of the schema tree node to enter
447 * @return Resolved schema tree node
448 * @throws NullPointerException if {@code nodeIdentifier} is null
449 * @throws IllegalArgumentException if the corresponding node cannot be found
451 public @NonNull SchemaTreeEffectiveStatement<?> enterSchemaTree(final SchemaNodeIdentifier nodeIdentifier) {
452 if (nodeIdentifier instanceof Absolute) {
456 final Iterator<QName> it = nodeIdentifier.getNodeIdentifiers().iterator();
457 SchemaTreeEffectiveStatement<?> ret;
459 ret = enterSchemaTree(it.next());
460 } while (it.hasNext());
466 * Lookup a {@code schema tree} child by its node identifier and push it to the stack.
468 * @param nodeIdentifier Node identifier of the date tree child to enter
469 * @return Resolved date tree child
470 * @throws NullPointerException if {@code nodeIdentifier} is null
471 * @throws IllegalArgumentException if the corresponding child cannot be found
473 public @NonNull DataTreeEffectiveStatement<?> enterDataTree(final QName nodeIdentifier) {
474 return pushData(requireNonNull(nodeIdentifier));
478 * Lookup a {@code typedef} by its node identifier and push it to the stack.
480 * @param nodeIdentifier Node identifier of the typedef to enter
481 * @return Resolved typedef
482 * @throws NullPointerException if {@code nodeIdentifier} is null
483 * @throws IllegalArgumentException if the corresponding typedef cannot be found
485 public @NonNull TypedefEffectiveStatement enterTypedef(final QName nodeIdentifier) {
486 return pushTypedef(requireNonNull(nodeIdentifier));
490 * Lookup a {@code rc:yang-data} by the module namespace where it is defined and its template name.
492 * @param namespace Module namespace in which to lookup the template
493 * @param name Template name
494 * @return Resolved yang-data
495 * @throws NullPointerException if any argument is null
496 * @throws IllegalArgumentException if the corresponding yang-data cannot be found
497 * @throws IllegalStateException if this stack is not empty
499 public @NonNull YangDataEffectiveStatement enterYangData(final QNameModule namespace, final String name) {
500 final EffectiveStatement<?, ?> parent = deque.peekFirst();
501 checkState(parent == null, "Cannot lookup yang-data in a non-empty stack");
503 final String templateName = requireNonNull(name);
504 final ModuleEffectiveStatement module = effectiveModel.getModuleStatements().get(requireNonNull(namespace));
505 checkArgument(module != null, "Module for %s not found", namespace);
507 final YangDataEffectiveStatement ret = module.streamEffectiveSubstatements(YangDataEffectiveStatement.class)
508 .filter(stmt -> templateName.equals(stmt.argument()))
511 () -> new IllegalArgumentException("yang-data " + templateName + " not present in " + namespace));
513 currentModule = module;
518 * Pop the current statement from the stack.
520 * @return Previous statement
521 * @throws NoSuchElementException if this stack is empty
523 public @NonNull EffectiveStatement<?, ?> exit() {
524 final EffectiveStatement<?, ?> prev = deque.pop();
525 if (prev instanceof GroupingEffectiveStatement) {
528 if (deque.isEmpty()) {
529 currentModule = null;
536 * Pop the current statement from the stack, asserting it is a {@link DataTreeEffectiveStatement} and that
537 * subsequent {@link #enterDataTree(QName)} will find it again.
539 * @return Previous statement
540 * @throws NoSuchElementException if this stack is empty
541 * @throws IllegalStateException if current statement is not a DataTreeEffectiveStatement or if its parent is not
542 * a {@link DataTreeAwareEffectiveStatement}
544 public @NonNull DataTreeEffectiveStatement<?> exitToDataTree() {
545 final EffectiveStatement<?, ?> child = exit();
546 checkState(child instanceof DataTreeEffectiveStatement, "Unexpected current %s", child);
547 EffectiveStatement<?, ?> parent = deque.peekFirst();
548 while (parent instanceof ChoiceEffectiveStatement || parent instanceof CaseEffectiveStatement) {
550 parent = deque.peekFirst();
553 checkState(parent == null || parent instanceof DataTreeAwareEffectiveStatement, "Unexpected parent %s", parent);
554 return (DataTreeEffectiveStatement<?>) child;
559 public TypeDefinition<?> resolveLeafref(final LeafrefTypeDefinition type) {
560 final SchemaInferenceStack tmp = copy();
562 LeafrefTypeDefinition current = type;
564 final EffectiveStatement<?, ?> resolved = tmp.resolvePathExpression(current.getPathStatement());
565 checkState(resolved instanceof TypeAware, "Unexpected result %s resultion of %s", resolved, type);
566 final TypeDefinition<?> result = ((TypedDataSchemaNode) resolved).getType();
567 if (result instanceof LeafrefTypeDefinition) {
568 checkArgument(result != type, "Resolution of %s loops back onto itself via %s", type, current);
569 current = (LeafrefTypeDefinition) result;
577 * Resolve a {@link PathExpression}.
580 * Note if this method throws, this stack may be in an undefined state.
582 * @param path Requested path
583 * @return Resolved schema tree child
584 * @throws NullPointerException if {@code path} is null
585 * @throws IllegalArgumentException if the target node cannot be found
586 * @throws VerifyException if path expression is invalid
588 public @NonNull EffectiveStatement<?, ?> resolvePathExpression(final PathExpression path) {
589 final Steps steps = path.getSteps();
590 if (steps instanceof LocationPathSteps) {
591 return resolveLocationPath(((LocationPathSteps) steps).getLocationPath());
592 } else if (steps instanceof DerefSteps) {
593 return resolveDeref((DerefSteps) steps);
595 throw new VerifyException("Unhandled steps " + steps);
599 private @NonNull EffectiveStatement<?, ?> resolveDeref(final DerefSteps deref) {
600 final EffectiveStatement<?, ?> leafRefSchemaNode = currentStatement();
601 final YangLocationPath.Relative derefArg = deref.getDerefArgument();
602 final EffectiveStatement<?, ?> derefStmt = resolveLocationPath(derefArg);
603 checkArgument(derefStmt != null, "Cannot find deref(%s) target node %s in context of %s",
604 derefArg, leafRefSchemaNode);
605 checkArgument(derefStmt instanceof TypedDataSchemaNode, "deref(%s) resolved to non-typed %s", derefArg,
608 // We have a deref() target, decide what to do about it
609 final TypeDefinition<?> targetType = ((TypedDataSchemaNode) derefStmt).getType();
610 if (targetType instanceof InstanceIdentifierTypeDefinition) {
611 // Static inference breaks down, we cannot determine where this points to
612 // FIXME: dedicated exception, users can recover from it, derive from IAE
613 throw new UnsupportedOperationException("Cannot infer instance-identifier reference " + targetType);
616 // deref() is defined only for instance-identifier and leafref types, handle the latter
617 checkArgument(targetType instanceof LeafrefTypeDefinition, "Illegal target type %s", targetType);
619 final PathExpression dereferencedLeafRefPath = ((LeafrefTypeDefinition) targetType).getPathStatement();
620 EffectiveStatement<?, ?> derefNode = resolvePathExpression(dereferencedLeafRefPath);
621 checkArgument(derefStmt != null, "Can not find target node of dereferenced node %s", derefStmt);
622 checkArgument(derefNode instanceof LeafSchemaNode, "Unexpected %s reference in %s", deref,
623 dereferencedLeafRefPath);
624 return resolveLocationPath(deref.getRelativePath());
627 private @NonNull EffectiveStatement<?, ?> resolveLocationPath(final YangLocationPath path) {
628 // get the default namespace before we clear and loose our deque
629 final QNameModule defaultNamespace = deque.isEmpty() ? null : ((QName) deque.peek().argument()).getModule();
630 if (path.isAbsolute()) {
634 EffectiveStatement<?, ?> current = null;
635 for (Step step : path.getSteps()) {
636 final YangXPathAxis axis = step.getAxis();
639 verify(step instanceof AxisStep, "Unexpected parent step %s", step);
641 current = exitToDataTree();
642 } catch (IllegalStateException | NoSuchElementException e) {
643 throw new IllegalArgumentException("Illegal parent access in " + path, e);
647 verify(step instanceof QNameStep, "Unexpected child step %s", step);
648 current = enterChild((QNameStep) step, defaultNamespace);
651 throw new VerifyException("Unexpected step " + step);
655 return verifyNotNull(current);
658 private @NonNull EffectiveStatement<?, ?> enterChild(final QNameStep step, final QNameModule defaultNamespace) {
659 final AbstractQName toResolve = step.getQName();
661 if (toResolve instanceof QName) {
662 qname = (QName) toResolve;
663 } else if (toResolve instanceof UnqualifiedQName) {
664 checkArgument(defaultNamespace != null, "Can not find target module of step %s", step);
665 qname = ((UnqualifiedQName) toResolve).bindTo(defaultNamespace);
667 throw new VerifyException("Unexpected child step QName " + toResolve);
669 return enterDataTree(qname);
673 * Return an {@link Inference} equivalent of current state.
675 * @return An {@link Inference}
677 public @NonNull Inference toInference() {
678 return new Inference(effectiveModel, deque.clone(), currentModule, groupingDepth, clean);
682 * Return an {@link SchemaTreeInference} equivalent of current state.
684 * @return An {@link SchemaTreeInference}
685 * @throws IllegalStateException if current state cannot be converted to a {@link SchemaTreeInference}
687 public @NonNull SchemaTreeInference toSchemaTreeInference() {
688 return DefaultSchemaTreeInference.of(getEffectiveModelContext(), toSchemaNodeIdentifier());
692 * Convert current state into an absolute schema node identifier.
694 * @return Absolute schema node identifier representing current state
695 * @throws IllegalStateException if current state is not instantiated
697 public @NonNull Absolute toSchemaNodeIdentifier() {
698 checkState(inInstantiatedContext(), "Cannot convert uninstantiated context %s", this);
699 return Absolute.of(ImmutableList.<QName>builderWithExpectedSize(deque.size())
700 .addAll(simplePathFromRoot())
705 * Convert current state into a SchemaPath.
707 * @return Absolute SchemaPath representing current state
708 * @throws IllegalStateException if current state is not instantiated
709 * @deprecated This method is meant only for interoperation with SchemaPath-based APIs.
712 public @NonNull SchemaPath toSchemaPath() {
713 SchemaPath ret = SchemaPath.ROOT;
714 final Iterator<QName> it = simplePathFromRoot();
715 while (it.hasNext()) {
716 ret = ret.createChild(it.next());
722 * Return an iterator along {@link SchemaPath#getPathFromRoot()}. This method is a faster equivalent of
723 * {@code toSchemaPath().getPathFromRoot().iterator()}.
725 * @return An unmodifiable iterator
728 public @NonNull Iterator<QName> schemaPathIterator() {
729 return Iterators.unmodifiableIterator(simplePathFromRoot());
733 public String toString() {
734 return MoreObjects.toStringHelper(this).add("stack", deque).toString();
737 private @NonNull GroupingEffectiveStatement pushGrouping(final @NonNull QName nodeIdentifier) {
738 final EffectiveStatement<?, ?> parent = deque.peekFirst();
739 return parent != null ? pushGrouping(parent, nodeIdentifier) : pushFirstGrouping(nodeIdentifier);
742 private @NonNull GroupingEffectiveStatement pushGrouping(final @NonNull EffectiveStatement<?, ?> parent,
743 final @NonNull QName nodeIdentifier) {
744 final GroupingEffectiveStatement ret = parent.streamEffectiveSubstatements(GroupingEffectiveStatement.class)
745 .filter(stmt -> nodeIdentifier.equals(stmt.argument()))
747 .orElseThrow(() -> new IllegalArgumentException("Grouping " + nodeIdentifier + " not present"));
753 private @NonNull GroupingEffectiveStatement pushFirstGrouping(final @NonNull QName nodeIdentifier) {
754 final ModuleEffectiveStatement module = getModule(nodeIdentifier);
755 final GroupingEffectiveStatement ret = pushGrouping(module, nodeIdentifier);
756 currentModule = module;
760 private @NonNull SchemaTreeEffectiveStatement<?> pushSchema(final @NonNull QName nodeIdentifier) {
761 final EffectiveStatement<?, ?> parent = deque.peekFirst();
762 return parent != null ? pushSchema(parent, nodeIdentifier) : pushFirstSchema(nodeIdentifier);
765 private @NonNull SchemaTreeEffectiveStatement<?> pushSchema(final EffectiveStatement<?, ?> parent,
766 final @NonNull QName nodeIdentifier) {
767 checkState(parent instanceof SchemaTreeAwareEffectiveStatement, "Cannot descend schema tree at %s", parent);
768 return pushSchema((SchemaTreeAwareEffectiveStatement<?, ?>) parent, nodeIdentifier);
771 private @NonNull SchemaTreeEffectiveStatement<?> pushSchema(
772 final @NonNull SchemaTreeAwareEffectiveStatement<?, ?> parent, final @NonNull QName nodeIdentifier) {
773 final SchemaTreeEffectiveStatement<?> ret = parent.findSchemaTreeNode(nodeIdentifier).orElseThrow(
774 () -> new IllegalArgumentException("Schema tree child " + nodeIdentifier + " not present"));
779 private @NonNull SchemaTreeEffectiveStatement<?> pushFirstSchema(final @NonNull QName nodeIdentifier) {
780 final ModuleEffectiveStatement module = getModule(nodeIdentifier);
781 final SchemaTreeEffectiveStatement<?> ret = pushSchema(module, nodeIdentifier);
782 currentModule = module;
786 private @NonNull DataTreeEffectiveStatement<?> pushData(final @NonNull QName nodeIdentifier) {
787 final EffectiveStatement<?, ?> parent = deque.peekFirst();
788 return parent != null ? pushData(parent, nodeIdentifier) : pushFirstData(nodeIdentifier);
791 private @NonNull DataTreeEffectiveStatement<?> pushData(final EffectiveStatement<?, ?> parent,
792 final @NonNull QName nodeIdentifier) {
793 checkState(parent instanceof DataTreeAwareEffectiveStatement, "Cannot descend data tree at %s", parent);
794 return pushData((DataTreeAwareEffectiveStatement<?, ?>) parent, nodeIdentifier);
797 private @NonNull DataTreeEffectiveStatement<?> pushData(final @NonNull DataTreeAwareEffectiveStatement<?, ?> parent,
798 final @NonNull QName nodeIdentifier) {
799 final DataTreeEffectiveStatement<?> ret = parent.findDataTreeNode(nodeIdentifier).orElseThrow(
800 () -> new IllegalArgumentException("Data tree child " + nodeIdentifier + " not present"));
806 private @NonNull DataTreeEffectiveStatement<?> pushFirstData(final @NonNull QName nodeIdentifier) {
807 final ModuleEffectiveStatement module = getModule(nodeIdentifier);
808 final DataTreeEffectiveStatement<?> ret = pushData(module, nodeIdentifier);
809 currentModule = module;
813 private @NonNull TypedefEffectiveStatement pushTypedef(final @NonNull QName nodeIdentifier) {
814 final EffectiveStatement<?, ?> parent = deque.peekFirst();
815 return parent != null ? pushTypedef(parent, nodeIdentifier) : pushFirstTypedef(nodeIdentifier);
818 private @NonNull TypedefEffectiveStatement pushTypedef(final @NonNull EffectiveStatement<?, ?> parent,
819 final @NonNull QName nodeIdentifier) {
820 final TypedefEffectiveStatement ret = parent.get(TypedefNamespace.class, nodeIdentifier)
821 .orElseThrow(() -> new IllegalArgumentException("Typedef " + nodeIdentifier + " not present"));
826 private @NonNull TypedefEffectiveStatement pushFirstTypedef(final @NonNull QName nodeIdentifier) {
827 final ModuleEffectiveStatement module = getModule(nodeIdentifier);
828 final TypedefEffectiveStatement ret = pushTypedef(module, nodeIdentifier);
829 currentModule = module;
833 private @NonNull ModuleEffectiveStatement getModule(final @NonNull QName nodeIdentifier) {
834 final ModuleEffectiveStatement module = effectiveModel.getModuleStatements().get(nodeIdentifier.getModule());
835 checkArgument(module != null, "Module for %s not found", nodeIdentifier);
839 // Unified access to queue iteration for addressing purposes. Since we keep 'logical' steps as executed by user
840 // at this point, conversion to SchemaNodeIdentifier may be needed. We dispatch based on 'clean'.
841 private Iterator<QName> simplePathFromRoot() {
842 return clean ? iterateQNames() : reconstructQNames();
845 private Iterator<QName> iterateQNames() {
846 return Iterators.transform(deque.descendingIterator(), stmt -> {
847 final Object argument = stmt.argument();
848 verify(argument instanceof QName, "Unexpected statement %s", stmt);
849 return (QName) argument;
853 // So there are some data tree steps in the stack... we essentially need to convert a data tree item into a series
854 // of schema tree items. This means at least N searches, but after they are done, we get an opportunity to set the
856 private Iterator<QName> reconstructQNames() {
857 // Let's walk all statements and decipher them into a temporary stack
858 final SchemaInferenceStack tmp = new SchemaInferenceStack(effectiveModel, deque.size());
859 final Iterator<EffectiveStatement<?, ?>> it = deque.descendingIterator();
860 while (it.hasNext()) {
861 final EffectiveStatement<?, ?> stmt = it.next();
862 // Order of checks is significant
863 if (stmt instanceof DataTreeEffectiveStatement) {
864 tmp.resolveDataTreeSteps(((DataTreeEffectiveStatement<?>) stmt).argument());
865 } else if (stmt instanceof ChoiceEffectiveStatement) {
866 tmp.resolveChoiceSteps(((ChoiceEffectiveStatement) stmt).argument());
867 } else if (stmt instanceof SchemaTreeEffectiveStatement) {
868 tmp.enterSchemaTree(((SchemaTreeEffectiveStatement<?> )stmt).argument());
869 } else if (stmt instanceof GroupingEffectiveStatement) {
870 tmp.enterGrouping(((GroupingEffectiveStatement) stmt).argument());
871 } else if (stmt instanceof TypedefEffectiveStatement) {
872 tmp.enterTypedef(((TypedefEffectiveStatement) stmt).argument());
874 throw new VerifyException("Unexpected statement " + stmt);
878 // if the sizes match, we did not jump through hoops. let's remember that for future.
879 clean = deque.size() == tmp.deque.size();
880 return tmp.iterateQNames();
883 private void resolveChoiceSteps(final @NonNull QName nodeIdentifier) {
884 final EffectiveStatement<?, ?> parent = deque.peekFirst();
885 if (parent instanceof ChoiceEffectiveStatement) {
886 resolveChoiceSteps((ChoiceEffectiveStatement) parent, nodeIdentifier);
888 enterSchemaTree(nodeIdentifier);
892 private void resolveChoiceSteps(final @NonNull ChoiceEffectiveStatement parent,
893 final @NonNull QName nodeIdentifier) {
894 for (EffectiveStatement<?, ?> stmt : parent.effectiveSubstatements()) {
895 if (stmt instanceof CaseEffectiveStatement) {
896 final CaseEffectiveStatement caze = (CaseEffectiveStatement) stmt;
897 final SchemaTreeEffectiveStatement<?> found = caze.findSchemaTreeNode(nodeIdentifier).orElse(null);
898 if (found instanceof ChoiceEffectiveStatement) {
905 throw new VerifyException("Failed to resolve " + nodeIdentifier + " in " + parent);
908 private void resolveDataTreeSteps(final @NonNull QName nodeIdentifier) {
909 final EffectiveStatement<?, ?> parent = deque.peekFirst();
910 if (parent != null) {
911 verify(parent instanceof SchemaTreeAwareEffectiveStatement, "Unexpected parent %s", parent);
912 resolveDataTreeSteps((SchemaTreeAwareEffectiveStatement<?, ?>) parent, nodeIdentifier);
916 final ModuleEffectiveStatement module = getModule(nodeIdentifier);
917 resolveDataTreeSteps(module, nodeIdentifier);
918 currentModule = module;
921 private void resolveDataTreeSteps(final @NonNull SchemaTreeAwareEffectiveStatement<?, ?> parent,
922 final @NonNull QName nodeIdentifier) {
923 // The algebra of identifiers in 'schema tree versus data tree':
924 // - data tree parents are always schema tree parents
925 // - data tree children are always schema tree children
927 // that implies that a data tree parent must satisfy schema tree queries with data tree children,
928 // so a successful lookup of 'data tree parent -> child' and 'schema tree parent -> child' has to be the same
929 // for a direct lookup.
930 final SchemaTreeEffectiveStatement<?> found = parent.findSchemaTreeNode(nodeIdentifier).orElse(null);
931 if (found instanceof DataTreeEffectiveStatement) {
932 // ... and it did, we are done
937 // Alright, so now it's down to filtering choice/case statements. For that we keep some globally-reused state
938 // and employ a recursive match.
939 final Deque<EffectiveStatement<QName, ?>> match = new ArrayDeque<>();
940 for (EffectiveStatement<?, ?> stmt : parent.effectiveSubstatements()) {
941 if (stmt instanceof ChoiceEffectiveStatement
942 && searchChoice(match, (ChoiceEffectiveStatement) stmt, nodeIdentifier)) {
943 match.descendingIterator().forEachRemaining(deque::push);
948 throw new VerifyException("Failed to resolve " + nodeIdentifier + " in " + parent);
951 private static boolean searchCase(final @NonNull Deque<EffectiveStatement<QName, ?>> result,
952 final @NonNull CaseEffectiveStatement parent, final @NonNull QName nodeIdentifier) {
954 for (EffectiveStatement<?, ?> stmt : parent.effectiveSubstatements()) {
955 if (stmt instanceof DataTreeEffectiveStatement && nodeIdentifier.equals(stmt.argument())) {
956 result.push((DataTreeEffectiveStatement<?>) stmt);
959 if (stmt instanceof ChoiceEffectiveStatement
960 && searchChoice(result, (ChoiceEffectiveStatement) stmt, nodeIdentifier)) {
968 private static boolean searchChoice(final @NonNull Deque<EffectiveStatement<QName, ?>> result,
969 final @NonNull ChoiceEffectiveStatement parent, final @NonNull QName nodeIdentifier) {
971 for (EffectiveStatement<?, ?> stmt : parent.effectiveSubstatements()) {
972 if (stmt instanceof CaseEffectiveStatement
973 && searchCase(result, (CaseEffectiveStatement) stmt, nodeIdentifier)) {
981 private static <T> @NonNull T checkNonNullState(final @Nullable T obj) {
983 throw new IllegalStateException("Cannot execute on empty stack");