893956e49f3f53812ee75316a7ee3d40a94b9016
[yangtools.git] / model / yang-model-util / src / main / java / org / opendaylight / yangtools / yang / model / util / SchemaInferenceStack.java
1 /*
2  * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.model.util;
9
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;
15
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.UnresolvedQName.Unqualified;
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;
70
71 /**
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.
74  *
75  * <p>
76  * This is meant to be a replacement concept for the use of {@link SchemaPath} in various places, notably
77  * in {@link SchemaContextUtil} methods.
78  *
79  * <p>
80  * This class is designed for single-threaded uses and does not make any guarantees around concurrent access.
81  */
82 @Beta
83 public final class SchemaInferenceStack implements Mutable, EffectiveModelContextProvider, LeafrefResolver {
84     /**
85      * Semantic binding of {@link EffectiveStatementInference} produced by {@link SchemaInferenceStack}. Sequence of
86      * {@link #statementPath()} is implementation-specific.
87      */
88     @Beta
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;
94
95         Inference(final @NonNull EffectiveModelContext modelContext, final ArrayDeque<EffectiveStatement<?, ?>> deque,
96                 final ModuleEffectiveStatement currentModule, final int groupingDepth, final boolean clean) {
97             super(modelContext);
98             this.deque = requireNonNull(deque);
99             this.currentModule = currentModule;
100             this.groupingDepth = groupingDepth;
101             this.clean = clean;
102         }
103
104         /**
105          * Create a new stack backed by an effective model and set up to point and specified data tree node.
106          *
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
112          */
113         public static @NonNull Inference ofDataTreePath(final EffectiveModelContext effectiveModel,
114                 final QName... qnames) {
115             return SchemaInferenceStack.ofDataTreePath(effectiveModel, qnames).toInference();
116         }
117
118         @Override
119         public List<EffectiveStatement<?, ?>> statementPath() {
120             return ImmutableList.copyOf(deque.descendingIterator());
121         }
122
123         /**
124          * Convert this inference into a {@link SchemaInferenceStack}.
125          *
126          * @return A new stack
127          */
128         public @NonNull SchemaInferenceStack toSchemaInferenceStack() {
129             return new SchemaInferenceStack(getEffectiveModelContext(), deque, currentModule, groupingDepth, clean);
130         }
131     }
132
133     private final @NonNull EffectiveModelContext effectiveModel;
134     private final ArrayDeque<EffectiveStatement<?, ?>> deque;
135
136     private @Nullable ModuleEffectiveStatement currentModule;
137     private int groupingDepth;
138
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;
142
143     private SchemaInferenceStack(final EffectiveModelContext effectiveModel, final int expectedSize) {
144         deque = new ArrayDeque<>(expectedSize);
145         this.effectiveModel = requireNonNull(effectiveModel);
146         clean = true;
147     }
148
149     private SchemaInferenceStack(final SchemaInferenceStack source) {
150         deque = source.deque.clone();
151         effectiveModel = source.effectiveModel;
152         currentModule = source.currentModule;
153         groupingDepth = source.groupingDepth;
154         clean = source.clean;
155     }
156
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;
164         this.clean = clean;
165     }
166
167     private SchemaInferenceStack(final EffectiveModelContext effectiveModel) {
168         this.effectiveModel = requireNonNull(effectiveModel);
169         deque = new ArrayDeque<>();
170         clean = true;
171     }
172
173     /**
174      * Create a new empty stack backed by an effective model.
175      *
176      * @param effectiveModel EffectiveModelContext to which this stack is attached
177      * @return A new stack
178      * @throws NullPointerException if {@code effectiveModel} is null
179      */
180     public static @NonNull SchemaInferenceStack of(final EffectiveModelContext effectiveModel) {
181         return new SchemaInferenceStack(effectiveModel);
182     }
183
184     /**
185      * Create a new stack backed by an effective model, pointing to specified schema node identified by
186      * {@link Absolute}.
187      *
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
192      */
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);
196         return ret;
197     }
198
199     /**
200      * Create a new stack from an {@link EffectiveStatementInference}.
201      *
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
206      */
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();
214         } else {
215             throw new IllegalArgumentException("Unsupported Inference " + inference);
216         }
217     }
218
219     /**
220      * Create a new stack from an {@link SchemaTreeInference}.
221      *
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
226      */
227     public static @NonNull SchemaInferenceStack ofInference(final SchemaTreeInference inference) {
228         return of(inference.getEffectiveModelContext(), inference.toSchemaNodeIdentifier());
229     }
230
231     /**
232      * Create a new stack backed by an effective model and set up to point and specified data tree node.
233      *
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
238      */
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);
244         }
245         return ret;
246     }
247
248     /**
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.
251      *
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
256      *                                  absolute path.
257      */
258     @Deprecated
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);
264         return ret;
265     }
266
267     /**
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.
271      *
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
276      *                                  absolute path.
277      */
278     @Deprecated
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);
283
284         for (QName step : path.getPathFromRoot()) {
285             try {
286                 ret.enterSchemaTree(step);
287             } catch (IllegalArgumentException schemaEx) {
288                 try {
289                     ret.enterGrouping(step);
290                 } catch (IllegalArgumentException ex) {
291                     ex.addSuppressed(schemaEx);
292                     throw ex;
293                 }
294             }
295         }
296
297         return ret;
298     }
299
300     @Override
301     public EffectiveModelContext getEffectiveModelContext() {
302         return effectiveModel;
303     }
304
305     /**
306      * Create a deep copy of this object.
307      *
308      * @return An isolated copy of this object
309      */
310     public @NonNull SchemaInferenceStack copy() {
311         return new SchemaInferenceStack(this);
312     }
313
314     /**
315      * Check if this stack is empty.
316      *
317      * @return True if this stack has not entered any node.
318      */
319     public boolean isEmpty() {
320         return deque.isEmpty();
321     }
322
323     /**
324      * Return the statement at the top of the stack.
325      *
326      * @return Top statement
327      * @throws IllegalStateException if the stack is empty
328      */
329     public @NonNull EffectiveStatement<?, ?> currentStatement() {
330         return checkNonNullState(deque.peekFirst());
331     }
332
333     /**
334      * Return current module the stack has entered.
335      *
336      * @return Current module
337      * @throws IllegalStateException if the stack is empty
338      */
339     public @NonNull ModuleEffectiveStatement currentModule() {
340         return checkNonNullState(currentModule);
341     }
342
343     /**
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.
346      *
347      * @return False if the stack is empty or contains a statement which is not a {@link SchemaTreeEffectiveStatement},
348      *         true otherwise.
349      */
350     public boolean inInstantiatedContext() {
351         return groupingDepth == 0 && !deque.isEmpty()
352             && deque.stream().allMatch(SchemaTreeEffectiveStatement.class::isInstance);
353     }
354
355     /**
356      * Check if the stack is in a {@code grouping} context.
357      *
358      * @return False if the stack contains a grouping.
359      */
360     public boolean inGrouping() {
361         return groupingDepth != 0;
362     }
363
364     /**
365      * Reset this stack to empty state.
366      */
367     public void clear() {
368         deque.clear();
369         currentModule = null;
370         groupingDepth = 0;
371         clean = true;
372     }
373
374     /**
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.
378      *
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
383      */
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);
388         }
389
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;
394         }
395         exit();
396         throw new IllegalArgumentException("Choice " + nodeIdentifier + " not present");
397     }
398
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();
410                     deque.push(match);
411                     clean = false;
412                     return (ChoiceEffectiveStatement) match;
413                 }
414             }
415         }
416         throw new IllegalArgumentException("Choice " + nodeIdentifier + " not present");
417     }
418
419     /**
420      * Lookup a {@code grouping} by its node identifier and push it to the stack.
421      *
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
426      */
427     public @NonNull GroupingEffectiveStatement enterGrouping(final QName nodeIdentifier) {
428         return pushGrouping(requireNonNull(nodeIdentifier));
429     }
430
431     /**
432      * Lookup a {@code schema tree} child by its node identifier and push it to the stack.
433      *
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
438      */
439     public @NonNull SchemaTreeEffectiveStatement<?> enterSchemaTree(final QName nodeIdentifier) {
440         return pushSchema(requireNonNull(nodeIdentifier));
441     }
442
443     /**
444      * Lookup a {@code schema tree} node by its schema node identifier and push it to the stack.
445      *
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
450      */
451     public @NonNull SchemaTreeEffectiveStatement<?> enterSchemaTree(final SchemaNodeIdentifier nodeIdentifier) {
452         if (nodeIdentifier instanceof Absolute) {
453             clear();
454         }
455
456         final Iterator<QName> it = nodeIdentifier.getNodeIdentifiers().iterator();
457         SchemaTreeEffectiveStatement<?> ret;
458         do {
459             ret = enterSchemaTree(it.next());
460         } while (it.hasNext());
461
462         return ret;
463     }
464
465     /**
466      * Lookup a {@code schema tree} child by its node identifier and push it to the stack.
467      *
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
472      */
473     public @NonNull DataTreeEffectiveStatement<?> enterDataTree(final QName nodeIdentifier) {
474         return pushData(requireNonNull(nodeIdentifier));
475     }
476
477     /**
478      * Lookup a {@code typedef} by its node identifier and push it to the stack.
479      *
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
484      */
485     public @NonNull TypedefEffectiveStatement enterTypedef(final QName nodeIdentifier) {
486         return pushTypedef(requireNonNull(nodeIdentifier));
487     }
488
489     /**
490      * Lookup a {@code rc:yang-data} by the module namespace where it is defined and its template name.
491      *
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
498      */
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");
502
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);
506
507         final YangDataEffectiveStatement ret = module.streamEffectiveSubstatements(YangDataEffectiveStatement.class)
508             .filter(stmt -> templateName.equals(stmt.argument()))
509             .findFirst()
510             .orElseThrow(
511                 () -> new IllegalArgumentException("yang-data " + templateName + " not present in " + namespace));
512         deque.push(ret);
513         currentModule = module;
514         return ret;
515     }
516
517     /**
518      * Pop the current statement from the stack.
519      *
520      * @return Previous statement
521      * @throws NoSuchElementException if this stack is empty
522      */
523     public @NonNull EffectiveStatement<?, ?> exit() {
524         final EffectiveStatement<?, ?> prev = deque.pop();
525         if (prev instanceof GroupingEffectiveStatement) {
526             --groupingDepth;
527         }
528         if (deque.isEmpty()) {
529             currentModule = null;
530             clean = true;
531         }
532         return prev;
533     }
534
535     /**
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.
538      *
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}
543      */
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) {
549             deque.pollFirst();
550             parent = deque.peekFirst();
551         }
552
553         checkState(parent == null || parent instanceof DataTreeAwareEffectiveStatement, "Unexpected parent %s", parent);
554         return (DataTreeEffectiveStatement<?>) child;
555     }
556
557
558     @Override
559     public TypeDefinition<?> resolveLeafref(final LeafrefTypeDefinition type) {
560         final SchemaInferenceStack tmp = copy();
561
562         LeafrefTypeDefinition current = type;
563         while (true) {
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;
570             } else {
571                 return result;
572             }
573         }
574     }
575
576     /**
577      * Resolve a {@link PathExpression}.
578      *
579      * <p>
580      * Note if this method throws, this stack may be in an undefined state.
581      *
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
587      */
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);
594         } else {
595             throw new VerifyException("Unhandled steps " + steps);
596         }
597     }
598
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,
606                 derefStmt);
607
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);
614         }
615
616         // deref() is defined only for instance-identifier and leafref types, handle the latter
617         checkArgument(targetType instanceof LeafrefTypeDefinition, "Illegal target type %s", targetType);
618
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());
625     }
626
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()) {
631             clear();
632         }
633
634         EffectiveStatement<?, ?> current = null;
635         for (Step step : path.getSteps()) {
636             final YangXPathAxis axis = step.getAxis();
637             switch (axis) {
638                 case PARENT:
639                     verify(step instanceof AxisStep, "Unexpected parent step %s", step);
640                     try {
641                         current = exitToDataTree();
642                     } catch (IllegalStateException | NoSuchElementException e) {
643                         throw new IllegalArgumentException("Illegal parent access in " + path, e);
644                     }
645                     break;
646                 case CHILD:
647                     verify(step instanceof QNameStep, "Unexpected child step %s", step);
648                     current = enterChild((QNameStep) step, defaultNamespace);
649                     break;
650                 default:
651                     throw new VerifyException("Unexpected step " + step);
652             }
653         }
654
655         return verifyNotNull(current);
656     }
657
658     private @NonNull EffectiveStatement<?, ?> enterChild(final QNameStep step, final QNameModule defaultNamespace) {
659         final AbstractQName toResolve = step.getQName();
660         final QName qname;
661         if (toResolve instanceof QName) {
662             qname = (QName) toResolve;
663         } else if (toResolve instanceof Unqualified) {
664             checkArgument(defaultNamespace != null, "Can not find target module of step %s", step);
665             qname = ((Unqualified) toResolve).bindTo(defaultNamespace);
666         } else {
667             throw new VerifyException("Unexpected child step QName " + toResolve);
668         }
669         return enterDataTree(qname);
670     }
671
672     /**
673      * Return an {@link Inference} equivalent of current state.
674      *
675      * @return An {@link Inference}
676      */
677     public @NonNull Inference toInference() {
678         return new Inference(effectiveModel, deque.clone(), currentModule, groupingDepth, clean);
679     }
680
681     /**
682      * Return an {@link SchemaTreeInference} equivalent of current state.
683      *
684      * @return An {@link SchemaTreeInference}
685      * @throws IllegalStateException if current state cannot be converted to a {@link SchemaTreeInference}
686      */
687     public @NonNull SchemaTreeInference toSchemaTreeInference() {
688         return DefaultSchemaTreeInference.of(getEffectiveModelContext(), toSchemaNodeIdentifier());
689     }
690
691     /**
692      * Convert current state into an absolute schema node identifier.
693      *
694      * @return Absolute schema node identifier representing current state
695      * @throws IllegalStateException if current state is not instantiated
696      */
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())
701             .build());
702     }
703
704     /**
705      * Convert current state into a SchemaPath.
706      *
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.
710      */
711     @Deprecated
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());
717         }
718         return ret;
719     }
720
721     /**
722      * Return an iterator along {@link SchemaPath#getPathFromRoot()}. This method is a faster equivalent of
723      * {@code toSchemaPath().getPathFromRoot().iterator()}.
724      *
725      * @return An unmodifiable iterator
726      */
727     @Deprecated
728     public @NonNull Iterator<QName> schemaPathIterator() {
729         return Iterators.unmodifiableIterator(simplePathFromRoot());
730     }
731
732     @Override
733     public String toString() {
734         return MoreObjects.toStringHelper(this).add("stack", deque).toString();
735     }
736
737     private @NonNull GroupingEffectiveStatement pushGrouping(final @NonNull QName nodeIdentifier) {
738         final EffectiveStatement<?, ?> parent = deque.peekFirst();
739         return parent != null ? pushGrouping(parent, nodeIdentifier) : pushFirstGrouping(nodeIdentifier);
740     }
741
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()))
746             .findFirst()
747             .orElseThrow(() -> new IllegalArgumentException("Grouping " + nodeIdentifier + " not present"));
748         deque.push(ret);
749         ++groupingDepth;
750         return ret;
751     }
752
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;
757         return ret;
758     }
759
760     private @NonNull SchemaTreeEffectiveStatement<?> pushSchema(final @NonNull QName nodeIdentifier) {
761         final EffectiveStatement<?, ?> parent = deque.peekFirst();
762         return parent != null ? pushSchema(parent, nodeIdentifier) : pushFirstSchema(nodeIdentifier);
763     }
764
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);
769     }
770
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"));
775         deque.push(ret);
776         return ret;
777     }
778
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;
783         return ret;
784     }
785
786     private @NonNull DataTreeEffectiveStatement<?> pushData(final @NonNull QName nodeIdentifier) {
787         final EffectiveStatement<?, ?> parent = deque.peekFirst();
788         return parent != null ? pushData(parent, nodeIdentifier) : pushFirstData(nodeIdentifier);
789     }
790
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);
795     }
796
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"));
801         deque.push(ret);
802         clean = false;
803         return ret;
804     }
805
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;
810         return ret;
811     }
812
813     private @NonNull TypedefEffectiveStatement pushTypedef(final @NonNull QName nodeIdentifier) {
814         final EffectiveStatement<?, ?> parent = deque.peekFirst();
815         return parent != null ? pushTypedef(parent, nodeIdentifier) : pushFirstTypedef(nodeIdentifier);
816     }
817
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"));
822         deque.push(ret);
823         return ret;
824     }
825
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;
830         return ret;
831     }
832
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);
836         return module;
837     }
838
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();
843     }
844
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;
850         });
851     }
852
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
855     // clean flag.
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());
873             } else {
874                 throw new VerifyException("Unexpected statement " + stmt);
875             }
876         }
877
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();
881     }
882
883     private void resolveChoiceSteps(final @NonNull QName nodeIdentifier) {
884         final EffectiveStatement<?, ?> parent = deque.peekFirst();
885         if (parent instanceof ChoiceEffectiveStatement) {
886             resolveChoiceSteps((ChoiceEffectiveStatement) parent, nodeIdentifier);
887         } else {
888             enterSchemaTree(nodeIdentifier);
889         }
890     }
891
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) {
899                     deque.push(caze);
900                     deque.push(found);
901                     return;
902                 }
903             }
904         }
905         throw new VerifyException("Failed to resolve " + nodeIdentifier + " in " + parent);
906     }
907
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);
913             return;
914         }
915
916         final ModuleEffectiveStatement module = getModule(nodeIdentifier);
917         resolveDataTreeSteps(module, nodeIdentifier);
918         currentModule = module;
919     }
920
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
926
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
933             deque.push(found);
934             return;
935         }
936
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);
944                 return;
945             }
946         }
947
948         throw new VerifyException("Failed to resolve " + nodeIdentifier + " in " + parent);
949     }
950
951     private static boolean searchCase(final @NonNull Deque<EffectiveStatement<QName, ?>> result,
952             final @NonNull CaseEffectiveStatement parent, final @NonNull QName nodeIdentifier) {
953         result.push(parent);
954         for (EffectiveStatement<?, ?> stmt : parent.effectiveSubstatements()) {
955             if (stmt instanceof DataTreeEffectiveStatement && nodeIdentifier.equals(stmt.argument())) {
956                 result.push((DataTreeEffectiveStatement<?>) stmt);
957                 return true;
958             }
959             if (stmt instanceof ChoiceEffectiveStatement
960                 && searchChoice(result, (ChoiceEffectiveStatement) stmt, nodeIdentifier)) {
961                 return true;
962             }
963         }
964         result.pop();
965         return false;
966     }
967
968     private static boolean searchChoice(final @NonNull Deque<EffectiveStatement<QName, ?>> result,
969             final @NonNull ChoiceEffectiveStatement parent, final @NonNull QName nodeIdentifier) {
970         result.push(parent);
971         for (EffectiveStatement<?, ?> stmt : parent.effectiveSubstatements()) {
972             if (stmt instanceof CaseEffectiveStatement
973                 && searchCase(result, (CaseEffectiveStatement) stmt, nodeIdentifier)) {
974                 return true;
975             }
976         }
977         result.pop();
978         return false;
979     }
980
981     private static <T> @NonNull T checkNonNullState(final @Nullable T obj) {
982         if (obj == null) {
983             throw new IllegalStateException("Cannot execute on empty stack");
984         }
985         return obj;
986     }
987 }