ceda711cfde74fcfb45769649830302b6424b806
[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.annotations.VisibleForTesting;
18 import com.google.common.base.MoreObjects;
19 import com.google.common.base.VerifyException;
20 import com.google.common.collect.Collections2;
21 import com.google.common.collect.ImmutableList;
22 import com.google.common.collect.Iterables;
23 import com.google.common.collect.Iterators;
24 import java.util.ArrayDeque;
25 import java.util.Collection;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.NoSuchElementException;
29 import java.util.Optional;
30 import org.eclipse.jdt.annotation.NonNull;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.opendaylight.yangtools.concepts.Mutable;
33 import org.opendaylight.yangtools.rfc8040.model.api.YangDataEffectiveStatement;
34 import org.opendaylight.yangtools.yang.common.AbstractQName;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.opendaylight.yangtools.yang.common.QNameModule;
37 import org.opendaylight.yangtools.yang.common.UnresolvedQName.Unqualified;
38 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
39 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextProvider;
40 import org.opendaylight.yangtools.yang.model.api.EffectiveStatementInference;
41 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.PathExpression;
43 import org.opendaylight.yangtools.yang.model.api.PathExpression.DerefSteps;
44 import org.opendaylight.yangtools.yang.model.api.PathExpression.LocationPathSteps;
45 import org.opendaylight.yangtools.yang.model.api.PathExpression.Steps;
46 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
47 import org.opendaylight.yangtools.yang.model.api.SchemaTreeInference;
48 import org.opendaylight.yangtools.yang.model.api.TypeAware;
49 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
50 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
52 import org.opendaylight.yangtools.yang.model.api.stmt.CaseEffectiveStatement;
53 import org.opendaylight.yangtools.yang.model.api.stmt.ChoiceEffectiveStatement;
54 import org.opendaylight.yangtools.yang.model.api.stmt.DataTreeAwareEffectiveStatement;
55 import org.opendaylight.yangtools.yang.model.api.stmt.DataTreeEffectiveStatement;
56 import org.opendaylight.yangtools.yang.model.api.stmt.GroupingEffectiveStatement;
57 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
58 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
59 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
60 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeAwareEffectiveStatement;
61 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
62 import org.opendaylight.yangtools.yang.model.api.stmt.TypedefEffectiveStatement;
63 import org.opendaylight.yangtools.yang.model.api.stmt.TypedefNamespace;
64 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
65 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
66 import org.opendaylight.yangtools.yang.model.spi.AbstractEffectiveStatementInference;
67 import org.opendaylight.yangtools.yang.model.spi.DefaultSchemaTreeInference;
68 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath;
69 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.AxisStep;
70 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.QNameStep;
71 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.Step;
72 import org.opendaylight.yangtools.yang.xpath.api.YangXPathAxis;
73 import org.slf4j.LoggerFactory;
74
75 /**
76  * A state tracking utility for walking {@link EffectiveModelContext}'s contents along schema/grouping namespaces. This
77  * is conceptually a stack, tracking {@link EffectiveStatement}s encountered along traversal.
78  *
79  * <p>
80  * This is meant to be a replacement concept for the use of {@link SchemaPath} in various places, notably
81  * in {@link SchemaContextUtil} methods.
82  *
83  * <p>
84  * This class is designed for single-threaded uses and does not make any guarantees around concurrent access.
85  */
86 @Beta
87 public final class SchemaInferenceStack implements Mutable, EffectiveModelContextProvider, LeafrefResolver {
88     /**
89      * Semantic binding of {@link EffectiveStatementInference} produced by {@link SchemaInferenceStack}. Sequence of
90      * {@link #statementPath()} is implementation-specific.
91      */
92     @Beta
93     public static final class Inference extends AbstractEffectiveStatementInference<EffectiveStatement<?, ?>> {
94         private final ArrayDeque<EffectiveStatement<?, ?>> deque;
95         private final ModuleEffectiveStatement currentModule;
96         private final int groupingDepth;
97         private final boolean clean;
98
99         Inference(final @NonNull EffectiveModelContext modelContext, final ArrayDeque<EffectiveStatement<?, ?>> deque,
100                 final ModuleEffectiveStatement currentModule, final int groupingDepth, final boolean clean) {
101             super(modelContext);
102             this.deque = requireNonNull(deque);
103             this.currentModule = currentModule;
104             this.groupingDepth = groupingDepth;
105             this.clean = clean;
106         }
107
108         /**
109          * Create a new stack backed by an effective model and set up to point and specified data tree node.
110          *
111          * @param effectiveModel EffectiveModelContext to which this stack is attached
112          * @param qnames Data tree path qnames
113          * @return A new stack
114          * @throws NullPointerException if any argument is null or path contains a null element
115          * @throws IllegalArgumentException if a path element cannot be found
116          */
117         public static @NonNull Inference ofDataTreePath(final EffectiveModelContext effectiveModel,
118                 final QName... qnames) {
119             return SchemaInferenceStack.ofDataTreePath(effectiveModel, qnames).toInference();
120         }
121
122         @Override
123         public List<EffectiveStatement<?, ?>> statementPath() {
124             return ImmutableList.copyOf(deque);
125         }
126
127         /**
128          * Convert this inference into a {@link SchemaInferenceStack}.
129          *
130          * @return A new stack
131          */
132         public @NonNull SchemaInferenceStack toSchemaInferenceStack() {
133             return new SchemaInferenceStack(getEffectiveModelContext(), deque, currentModule, groupingDepth, clean);
134         }
135     }
136
137     private static final String VERIFY_DEFAULT_SCHEMA_TREE_INFERENCE_PROP =
138         "org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.verifyDefaultSchemaTreeInference";
139     private static final boolean VERIFY_DEFAULT_SCHEMA_TREE_INFERENCE =
140         Boolean.getBoolean(VERIFY_DEFAULT_SCHEMA_TREE_INFERENCE_PROP);
141
142     static {
143         if (VERIFY_DEFAULT_SCHEMA_TREE_INFERENCE) {
144             LoggerFactory.getLogger(SchemaInferenceStack.class)
145                 .info("SchemaTreeStack.ofInference(DefaultSchemaTreeInference) argument is being verified");
146         }
147     }
148
149     private final @NonNull EffectiveModelContext effectiveModel;
150     private final ArrayDeque<EffectiveStatement<?, ?>> deque;
151
152     private @Nullable ModuleEffectiveStatement currentModule;
153     private int groupingDepth;
154
155     // True if there were only steps along grouping and schema tree, hence it is consistent with SchemaNodeIdentifier
156     // False if we have evidence of a data tree lookup succeeding
157     private boolean clean;
158
159     private SchemaInferenceStack(final EffectiveModelContext effectiveModel, final int expectedSize) {
160         deque = new ArrayDeque<>(expectedSize);
161         this.effectiveModel = requireNonNull(effectiveModel);
162         clean = true;
163     }
164
165     private SchemaInferenceStack(final SchemaInferenceStack source) {
166         deque = source.deque.clone();
167         effectiveModel = source.effectiveModel;
168         currentModule = source.currentModule;
169         groupingDepth = source.groupingDepth;
170         clean = source.clean;
171     }
172
173     private SchemaInferenceStack(final EffectiveModelContext effectiveModel,
174             final ArrayDeque<EffectiveStatement<?, ?>> deque, final ModuleEffectiveStatement currentModule,
175             final int groupingDepth, final boolean clean) {
176         this.effectiveModel = requireNonNull(effectiveModel);
177         this.deque = deque.clone();
178         this.currentModule = currentModule;
179         this.groupingDepth = groupingDepth;
180         this.clean = clean;
181     }
182
183     private SchemaInferenceStack(final EffectiveModelContext effectiveModel) {
184         this.effectiveModel = requireNonNull(effectiveModel);
185         deque = new ArrayDeque<>();
186         clean = true;
187     }
188
189     /**
190      * Create a new empty stack backed by an effective model.
191      *
192      * @param effectiveModel EffectiveModelContext to which this stack is attached
193      * @return A new stack
194      * @throws NullPointerException if {@code effectiveModel} is null
195      */
196     public static @NonNull SchemaInferenceStack of(final EffectiveModelContext effectiveModel) {
197         return new SchemaInferenceStack(effectiveModel);
198     }
199
200     /**
201      * Create a new stack backed by an effective model, pointing to specified schema node identified by
202      * {@link Absolute}.
203      *
204      * @param effectiveModel EffectiveModelContext to which this stack is attached
205      * @return A new stack
206      * @throws NullPointerException if {@code effectiveModel} is null
207      * @throws IllegalArgumentException if {@code path} cannot be resolved in the effective model
208      */
209     public static @NonNull SchemaInferenceStack of(final EffectiveModelContext effectiveModel, final Absolute path) {
210         final SchemaInferenceStack ret = new SchemaInferenceStack(effectiveModel);
211         path.getNodeIdentifiers().forEach(ret::enterSchemaTree);
212         return ret;
213     }
214
215     /**
216      * Create a new stack from an {@link EffectiveStatementInference}.
217      *
218      * @param inference Inference to use for initialization
219      * @return A new stack
220      * @throws NullPointerException if {@code inference} is null
221      * @throws IllegalArgumentException if {@code inference} implementation is not supported
222      */
223     public static @NonNull SchemaInferenceStack ofInference(final EffectiveStatementInference inference) {
224         if (inference.statementPath().isEmpty()) {
225             return new SchemaInferenceStack(inference.getEffectiveModelContext());
226         } else if (inference instanceof SchemaTreeInference sti) {
227             return ofInference(sti);
228         } else if (inference instanceof Inference inf) {
229             return inf.toSchemaInferenceStack();
230         } else {
231             throw new IllegalArgumentException("Unsupported Inference " + inference);
232         }
233     }
234
235     /**
236      * Create a new stack from an {@link SchemaTreeInference}.
237      *
238      * @param inference SchemaTreeInference to use for initialization
239      * @return A new stack
240      * @throws NullPointerException if {@code inference} is null
241      * @throws IllegalArgumentException if {@code inference} cannot be resolved to a valid stack
242      */
243     public static @NonNull SchemaInferenceStack ofInference(final SchemaTreeInference inference) {
244         return inference instanceof DefaultSchemaTreeInference dsti ? ofInference(dsti)
245             : of(inference.getEffectiveModelContext(), inference.toSchemaNodeIdentifier());
246     }
247
248     /**
249      * Create a new stack from an {@link DefaultSchemaTreeInference}. The argument is nominally trusted to be an
250      * accurate representation of the schema tree.
251      *
252      * <p>
253      * Run-time verification of {@code inference} can be enabled by setting the
254      * {@value #VERIFY_DEFAULT_SCHEMA_TREE_INFERENCE_PROP} system property to {@code true}.
255      *
256      * @param inference DefaultSchemaTreeInference to use for initialization
257      * @return A new stack
258      * @throws NullPointerException if {@code inference} is null
259      * @throws IllegalArgumentException if {@code inference} refers to a missing module or when verification is enabled
260      *                                  and it does not match its context's scheam tree
261      */
262     public static @NonNull SchemaInferenceStack ofInference(final DefaultSchemaTreeInference inference) {
263         return VERIFY_DEFAULT_SCHEMA_TREE_INFERENCE ? ofUntrusted(inference) : ofTrusted(inference);
264     }
265
266     private static @NonNull SchemaInferenceStack ofTrusted(final DefaultSchemaTreeInference inference) {
267         final var path = inference.statementPath();
268         final var ret = new SchemaInferenceStack(inference.getEffectiveModelContext(), path.size());
269         ret.currentModule = ret.getModule(path.get(0).argument());
270         ret.deque.addAll(path);
271         return ret;
272     }
273
274     @VisibleForTesting
275     static @NonNull SchemaInferenceStack ofUntrusted(final DefaultSchemaTreeInference inference) {
276         final var ret = of(inference.getEffectiveModelContext(), inference.toSchemaNodeIdentifier());
277         if (!Iterables.elementsEqual(ret.deque, inference.statementPath())) {
278             throw new IllegalArgumentException("Provided " + inference + " is not consistent with resolved path "
279                 + ret.toSchemaTreeInference());
280         }
281         return ret;
282     }
283
284     /**
285      * Create a new stack backed by an effective model and set up to point and specified data tree node.
286      *
287      * @param effectiveModel EffectiveModelContext to which this stack is attached
288      * @return A new stack
289      * @throws NullPointerException if any argument is null or path contains a null element
290      * @throws IllegalArgumentException if a path element cannot be found
291      */
292     public static @NonNull SchemaInferenceStack ofDataTreePath(final EffectiveModelContext effectiveModel,
293             final QName... path) {
294         final SchemaInferenceStack ret = new SchemaInferenceStack(effectiveModel);
295         for (QName qname : path) {
296             ret.enterDataTree(qname);
297         }
298         return ret;
299     }
300
301     /**
302      * Create a new stack backed by an effective model, pointing to specified schema node identified by an absolute
303      * {@link SchemaPath} and its {@link SchemaPath#getPathFromRoot()} interpreted as a schema node identifier.
304      *
305      * @param effectiveModel EffectiveModelContext to which this stack is attached
306      * @return A new stack
307      * @throws NullPointerException {@code effectiveModel} is null
308      * @throws IllegalArgumentException if {@code path} cannot be resolved in the effective model or if it is not an
309      *                                  absolute path.
310      */
311     @Deprecated
312     public static @NonNull SchemaInferenceStack ofInstantiatedPath(final EffectiveModelContext effectiveModel,
313             final SchemaPath path) {
314         checkArgument(path.isAbsolute(), "Cannot operate on relative path %s", path);
315         final SchemaInferenceStack ret = new SchemaInferenceStack(effectiveModel);
316         path.getPathFromRoot().forEach(ret::enterSchemaTree);
317         return ret;
318     }
319
320     /**
321      * Create a new stack backed by an effective model, pointing to specified schema node identified by an absolute
322      * {@link SchemaPath} and its {@link SchemaPath#getPathFromRoot()}, interpreted as a series of steps along primarily
323      * schema tree, with grouping namespace being the alternative lookup.
324      *
325      * @param effectiveModel EffectiveModelContext to which this stack is attached
326      * @return A new stack
327      * @throws NullPointerException {@code effectiveModel} is null
328      * @throws IllegalArgumentException if {@code path} cannot be resolved in the effective model or if it is not an
329      *                                  absolute path.
330      */
331     @Deprecated
332     public static @NonNull SchemaInferenceStack ofSchemaPath(final EffectiveModelContext effectiveModel,
333             final SchemaPath path) {
334         checkArgument(path.isAbsolute(), "Cannot operate on relative path %s", path);
335         final SchemaInferenceStack ret = new SchemaInferenceStack(effectiveModel);
336
337         for (QName step : path.getPathFromRoot()) {
338             try {
339                 ret.enterSchemaTree(step);
340             } catch (IllegalArgumentException schemaEx) {
341                 try {
342                     ret.enterGrouping(step);
343                 } catch (IllegalArgumentException ex) {
344                     ex.addSuppressed(schemaEx);
345                     throw ex;
346                 }
347             }
348         }
349
350         return ret;
351     }
352
353     @Override
354     public EffectiveModelContext getEffectiveModelContext() {
355         return effectiveModel;
356     }
357
358     /**
359      * Create a deep copy of this object.
360      *
361      * @return An isolated copy of this object
362      */
363     public @NonNull SchemaInferenceStack copy() {
364         return new SchemaInferenceStack(this);
365     }
366
367     /**
368      * Check if this stack is empty.
369      *
370      * @return True if this stack has not entered any node.
371      */
372     public boolean isEmpty() {
373         return deque.isEmpty();
374     }
375
376     /**
377      * Return the statement at the top of the stack.
378      *
379      * @return Top statement
380      * @throws IllegalStateException if the stack is empty
381      */
382     public @NonNull EffectiveStatement<?, ?> currentStatement() {
383         return checkNonNullState(deque.peekLast());
384     }
385
386     /**
387      * Return current module the stack has entered.
388      *
389      * @return Current module
390      * @throws IllegalStateException if the stack is empty
391      */
392     public @NonNull ModuleEffectiveStatement currentModule() {
393         return checkNonNullState(currentModule);
394     }
395
396     /**
397      * Check if the stack is in instantiated context. This indicates the stack is non-empty and there are only schema
398      * tree statements in the stack.
399      *
400      * @return False if the stack is empty or contains a statement which is not a {@link SchemaTreeEffectiveStatement},
401      *         true otherwise.
402      */
403     public boolean inInstantiatedContext() {
404         return groupingDepth == 0 && !deque.isEmpty()
405             && deque.stream().allMatch(SchemaTreeEffectiveStatement.class::isInstance);
406     }
407
408     /**
409      * Check if the stack is in a {@code grouping} context.
410      *
411      * @return False if the stack contains a grouping.
412      */
413     public boolean inGrouping() {
414         return groupingDepth != 0;
415     }
416
417     /**
418      * Reset this stack to empty state.
419      */
420     public void clear() {
421         deque.clear();
422         currentModule = null;
423         groupingDepth = 0;
424         clean = true;
425     }
426
427     /**
428      * Lookup a {@code choice} by its node identifier and push it to the stack. This step is very similar to
429      * {@link #enterSchemaTree(QName)}, except it handles the use case where traversal ignores actual {@code case}
430      * intermediate schema tree children.
431      *
432      * @param nodeIdentifier Node identifier of the choice to enter
433      * @return Resolved choice
434      * @throws NullPointerException if {@code nodeIdentifier} is null
435      * @throws IllegalArgumentException if the corresponding choice cannot be found
436      */
437     public @NonNull ChoiceEffectiveStatement enterChoice(final QName nodeIdentifier) {
438         final QName nodeId = requireNonNull(nodeIdentifier);
439         final EffectiveStatement<?, ?> parent = deque.peekLast();
440         if (parent instanceof ChoiceEffectiveStatement choice) {
441             return enterChoice(choice, nodeId);
442         }
443
444         // Fall back to schema tree lookup. Note if it results in non-choice, we rewind before reporting an error
445         final SchemaTreeEffectiveStatement<?> result = enterSchemaTree(nodeId);
446         if (result instanceof ChoiceEffectiveStatement choice) {
447             return choice;
448         }
449         exit();
450
451         if (parent != null) {
452             throw notPresent(parent, "Choice", nodeId);
453         }
454         throw new IllegalArgumentException("Choice " + nodeId + " not present");
455     }
456
457     // choice -> choice transition, we have to deal with intermediate case nodes
458     private @NonNull ChoiceEffectiveStatement enterChoice(final @NonNull ChoiceEffectiveStatement parent,
459             final QName nodeIdentifier) {
460         for (EffectiveStatement<?, ?> stmt : parent.effectiveSubstatements()) {
461             if (stmt instanceof CaseEffectiveStatement caze) {
462                 final Optional<ChoiceEffectiveStatement> optMatch = caze.findSchemaTreeNode(nodeIdentifier)
463                     .filter(ChoiceEffectiveStatement.class::isInstance)
464                     .map(ChoiceEffectiveStatement.class::cast);
465                 if (optMatch.isPresent()) {
466                     final var match = optMatch.orElseThrow();
467                     deque.addLast(match);
468                     clean = false;
469                     return match;
470                 }
471             }
472         }
473         throw notPresent(parent, "Choice", nodeIdentifier);
474     }
475
476     /**
477      * Lookup a {@code grouping} by its node identifier and push it to the stack.
478      *
479      * @param nodeIdentifier Node identifier of the grouping to enter
480      * @return Resolved grouping
481      * @throws NullPointerException if {@code nodeIdentifier} is null
482      * @throws IllegalArgumentException if the corresponding grouping cannot be found
483      */
484     public @NonNull GroupingEffectiveStatement enterGrouping(final QName nodeIdentifier) {
485         return pushGrouping(requireNonNull(nodeIdentifier));
486     }
487
488     /**
489      * Lookup a {@code schema tree} child by its node identifier and push it to the stack.
490      *
491      * @param nodeIdentifier Node identifier of the schema tree child to enter
492      * @return Resolved schema tree child
493      * @throws NullPointerException if {@code nodeIdentifier} is null
494      * @throws IllegalArgumentException if the corresponding child cannot be found
495      */
496     public @NonNull SchemaTreeEffectiveStatement<?> enterSchemaTree(final QName nodeIdentifier) {
497         return pushSchema(requireNonNull(nodeIdentifier));
498     }
499
500     /**
501      * Lookup a {@code schema tree} node by its schema node identifier and push it to the stack.
502      *
503      * @param nodeIdentifier Schema node identifier of the schema tree node to enter
504      * @return Resolved schema tree node
505      * @throws NullPointerException if {@code nodeIdentifier} is null
506      * @throws IllegalArgumentException if the corresponding node cannot be found
507      */
508     public @NonNull SchemaTreeEffectiveStatement<?> enterSchemaTree(final SchemaNodeIdentifier nodeIdentifier) {
509         if (nodeIdentifier instanceof Absolute) {
510             clear();
511         }
512
513         final Iterator<QName> it = nodeIdentifier.getNodeIdentifiers().iterator();
514         SchemaTreeEffectiveStatement<?> ret;
515         do {
516             ret = enterSchemaTree(it.next());
517         } while (it.hasNext());
518
519         return ret;
520     }
521
522     /**
523      * Lookup a {@code schema tree} child by its node identifier and push it to the stack.
524      *
525      * @param nodeIdentifier Node identifier of the date tree child to enter
526      * @return Resolved date tree child
527      * @throws NullPointerException if {@code nodeIdentifier} is null
528      * @throws IllegalArgumentException if the corresponding child cannot be found
529      */
530     public @NonNull DataTreeEffectiveStatement<?> enterDataTree(final QName nodeIdentifier) {
531         return pushData(requireNonNull(nodeIdentifier));
532     }
533
534     /**
535      * Lookup a {@code typedef} by its node identifier and push it to the stack.
536      *
537      * @param nodeIdentifier Node identifier of the typedef to enter
538      * @return Resolved typedef
539      * @throws NullPointerException if {@code nodeIdentifier} is null
540      * @throws IllegalArgumentException if the corresponding typedef cannot be found
541      */
542     public @NonNull TypedefEffectiveStatement enterTypedef(final QName nodeIdentifier) {
543         return pushTypedef(requireNonNull(nodeIdentifier));
544     }
545
546     /**
547      * Lookup a {@code rc:yang-data} by the module namespace where it is defined and its template name.
548      *
549      * @param namespace Module namespace in which to lookup the template
550      * @param name Template name
551      * @return Resolved yang-data
552      * @throws NullPointerException if any argument is null
553      * @throws IllegalArgumentException if the corresponding yang-data cannot be found
554      * @throws IllegalStateException if this stack is not empty
555      */
556     public @NonNull YangDataEffectiveStatement enterYangData(final QNameModule namespace, final String name) {
557         final EffectiveStatement<?, ?> parent = deque.peekLast();
558         checkState(parent == null, "Cannot lookup yang-data in a non-empty stack");
559
560         final String templateName = requireNonNull(name);
561         final ModuleEffectiveStatement module = effectiveModel.getModuleStatements().get(requireNonNull(namespace));
562         checkArgument(module != null, "Module for %s not found", namespace);
563
564         final YangDataEffectiveStatement ret = module.streamEffectiveSubstatements(YangDataEffectiveStatement.class)
565             .filter(stmt -> templateName.equals(stmt.argument()))
566             .findFirst()
567             .orElseThrow(
568                 () -> new IllegalArgumentException("yang-data " + templateName + " not present in " + namespace));
569         deque.addLast(ret);
570         currentModule = module;
571         return ret;
572     }
573
574     /**
575      * Pop the current statement from the stack.
576      *
577      * @return Previous statement
578      * @throws NoSuchElementException if this stack is empty
579      */
580     public @NonNull EffectiveStatement<?, ?> exit() {
581         final EffectiveStatement<?, ?> prev = deque.removeLast();
582         if (prev instanceof GroupingEffectiveStatement) {
583             --groupingDepth;
584         }
585         if (deque.isEmpty()) {
586             currentModule = null;
587             clean = true;
588         }
589         return prev;
590     }
591
592     /**
593      * Pop the current statement from the stack, asserting it is a {@link DataTreeEffectiveStatement} and that
594      * subsequent {@link #enterDataTree(QName)} will find it again.
595      *
596      * @return Previous statement
597      * @throws NoSuchElementException if this stack is empty
598      * @throws IllegalStateException if current statement is not a DataTreeEffectiveStatement or if its parent is not
599      *                               a {@link DataTreeAwareEffectiveStatement}
600      */
601     public @NonNull DataTreeEffectiveStatement<?> exitToDataTree() {
602         final EffectiveStatement<?, ?> child = exit();
603         checkState(child instanceof DataTreeEffectiveStatement, "Unexpected current %s", child);
604         EffectiveStatement<?, ?> parent = deque.peekLast();
605         while (parent instanceof ChoiceEffectiveStatement || parent instanceof CaseEffectiveStatement) {
606             deque.pollLast();
607             parent = deque.peekLast();
608         }
609
610         checkState(parent == null || parent instanceof DataTreeAwareEffectiveStatement, "Unexpected parent %s", parent);
611         return (DataTreeEffectiveStatement<?>) child;
612     }
613
614     @Override
615     public TypeDefinition<?> resolveLeafref(final LeafrefTypeDefinition type) {
616         final SchemaInferenceStack tmp = copy();
617
618         LeafrefTypeDefinition current = type;
619         while (true) {
620             final EffectiveStatement<?, ?> resolved = tmp.resolvePathExpression(current.getPathStatement());
621             checkState(resolved instanceof TypeAware, "Unexpected result %s resultion of %s", resolved, type);
622             final TypeDefinition<?> result = ((TypedDataSchemaNode) resolved).getType();
623             if (result instanceof LeafrefTypeDefinition leafref) {
624                 checkArgument(result != type, "Resolution of %s loops back onto itself via %s", type, current);
625                 current = leafref;
626             } else {
627                 return result;
628             }
629         }
630     }
631
632     /**
633      * Resolve a {@link PathExpression}.
634      *
635      * <p>
636      * Note if this method throws, this stack may be in an undefined state.
637      *
638      * @param path Requested path
639      * @return Resolved schema tree child
640      * @throws NullPointerException if {@code path} is null
641      * @throws IllegalArgumentException if the target node cannot be found
642      * @throws VerifyException if path expression is invalid
643      */
644     public @NonNull EffectiveStatement<?, ?> resolvePathExpression(final PathExpression path) {
645         final Steps steps = path.getSteps();
646         if (steps instanceof LocationPathSteps location) {
647             return resolveLocationPath(location.getLocationPath());
648         } else if (steps instanceof DerefSteps deref) {
649             return resolveDeref(deref);
650         } else {
651             throw new VerifyException("Unhandled steps " + steps);
652         }
653     }
654
655     private @NonNull EffectiveStatement<?, ?> resolveDeref(final DerefSteps deref) {
656         final EffectiveStatement<?, ?> leafRefSchemaNode = currentStatement();
657         final YangLocationPath.Relative derefArg = deref.getDerefArgument();
658         final EffectiveStatement<?, ?> derefStmt = resolveLocationPath(derefArg);
659         checkArgument(derefStmt != null, "Cannot find deref(%s) target node %s in context of %s",
660                 derefArg, leafRefSchemaNode);
661         checkArgument(derefStmt instanceof TypedDataSchemaNode, "deref(%s) resolved to non-typed %s", derefArg,
662                 derefStmt);
663
664         // We have a deref() target, decide what to do about it
665         final TypeDefinition<?> targetType = ((TypedDataSchemaNode) derefStmt).getType();
666         if (targetType instanceof InstanceIdentifierTypeDefinition) {
667             // Static inference breaks down, we cannot determine where this points to
668             // FIXME: dedicated exception, users can recover from it, derive from IAE
669             throw new UnsupportedOperationException("Cannot infer instance-identifier reference " + targetType);
670         }
671
672         // deref() is defined only for instance-identifier and leafref types, handle the latter
673         checkArgument(targetType instanceof LeafrefTypeDefinition, "Illegal target type %s", targetType);
674
675         final PathExpression dereferencedLeafRefPath = ((LeafrefTypeDefinition) targetType).getPathStatement();
676         EffectiveStatement<?, ?> derefNode = resolvePathExpression(dereferencedLeafRefPath);
677         checkArgument(derefStmt != null, "Can not find target node of dereferenced node %s", derefStmt);
678         checkArgument(derefNode instanceof LeafSchemaNode, "Unexpected %s reference in %s", deref,
679                 dereferencedLeafRefPath);
680         return resolveLocationPath(deref.getRelativePath());
681     }
682
683     private @NonNull EffectiveStatement<?, ?> resolveLocationPath(final YangLocationPath path) {
684         // get the default namespace before we clear and loose our deque
685         final QNameModule defaultNamespace = deque.isEmpty() ? null : ((QName) deque.peekLast().argument()).getModule();
686         if (path.isAbsolute()) {
687             clear();
688         }
689
690         EffectiveStatement<?, ?> current = null;
691         for (Step step : path.getSteps()) {
692             final YangXPathAxis axis = step.getAxis();
693             switch (axis) {
694                 case PARENT -> {
695                     verify(step instanceof AxisStep, "Unexpected parent step %s", step);
696                     try {
697                         current = exitToDataTree();
698                     } catch (IllegalStateException | NoSuchElementException e) {
699                         throw new IllegalArgumentException("Illegal parent access in " + path, e);
700                     }
701                 }
702                 case CHILD -> {
703                     verify(step instanceof QNameStep, "Unexpected child step %s", step);
704                     current = enterChild((QNameStep) step, defaultNamespace);
705                 }
706                 default -> throw new VerifyException("Unexpected step " + step);
707             }
708         }
709
710         return verifyNotNull(current);
711     }
712
713     private @NonNull EffectiveStatement<?, ?> enterChild(final QNameStep step, final QNameModule defaultNamespace) {
714         final AbstractQName toResolve = step.getQName();
715         final QName qname;
716         if (toResolve instanceof QName) {
717             qname = (QName) toResolve;
718         } else if (toResolve instanceof Unqualified unqual) {
719             checkArgument(defaultNamespace != null, "Can not find target module of step %s", step);
720             qname = unqual.bindTo(defaultNamespace);
721         } else {
722             throw new VerifyException("Unexpected child step QName " + toResolve);
723         }
724         return enterDataTree(qname);
725     }
726
727     /**
728      * Return an {@link Inference} equivalent of current state.
729      *
730      * @return An {@link Inference}
731      */
732     public @NonNull Inference toInference() {
733         return new Inference(effectiveModel, deque.clone(), currentModule, groupingDepth, clean);
734     }
735
736     /**
737      * Return an {@link SchemaTreeInference} equivalent of current state.
738      *
739      * @return An {@link SchemaTreeInference}
740      * @throws IllegalStateException if current state cannot be converted to a {@link SchemaTreeInference}
741      */
742     public @NonNull SchemaTreeInference toSchemaTreeInference() {
743         checkState(inInstantiatedContext(), "Cannot convert uninstantiated context %s", this);
744         final var cleanDeque = clean ? deque : reconstructSchemaInferenceStack().deque;
745         return DefaultSchemaTreeInference.unsafeOf(getEffectiveModelContext(), cleanDeque.stream()
746             .map(stmt -> (SchemaTreeEffectiveStatement<?>) stmt)
747             .collect(ImmutableList.toImmutableList()));
748     }
749
750     /**
751      * Convert current state into an absolute schema node identifier.
752      *
753      * @return Absolute schema node identifier representing current state
754      * @throws IllegalStateException if current state is not instantiated
755      */
756     public @NonNull Absolute toSchemaNodeIdentifier() {
757         checkState(inInstantiatedContext(), "Cannot convert uninstantiated context %s", this);
758         return Absolute.of(simplePathFromRoot());
759     }
760
761     /**
762      * Convert current state into a SchemaPath.
763      *
764      * @return Absolute SchemaPath representing current state
765      * @throws IllegalStateException if current state is not instantiated
766      * @deprecated This method is meant only for interoperation with SchemaPath-based APIs.
767      */
768     @Deprecated
769     public @NonNull SchemaPath toSchemaPath() {
770         return SchemaPath.create(simplePathFromRoot(), true);
771     }
772
773     /**
774      * Return an iterator along {@link SchemaPath#getPathFromRoot()}. This method is a faster equivalent of
775      * {@code toSchemaPath().getPathFromRoot().iterator()}.
776      *
777      * @return An unmodifiable iterator
778      */
779     @Deprecated
780     public @NonNull Iterator<QName> schemaPathIterator() {
781         return Iterators.unmodifiableIterator(simplePathFromRoot().iterator());
782     }
783
784     @Override
785     public String toString() {
786         return MoreObjects.toStringHelper(this).add("path", deque).toString();
787     }
788
789     private @NonNull GroupingEffectiveStatement pushGrouping(final @NonNull QName nodeIdentifier) {
790         final EffectiveStatement<?, ?> parent = deque.peekLast();
791         return parent != null ? pushGrouping(parent, nodeIdentifier) : pushFirstGrouping(nodeIdentifier);
792     }
793
794     private @NonNull GroupingEffectiveStatement pushGrouping(final @NonNull EffectiveStatement<?, ?> parent,
795             final @NonNull QName nodeIdentifier) {
796         final GroupingEffectiveStatement ret = parent.streamEffectiveSubstatements(GroupingEffectiveStatement.class)
797             .filter(stmt -> nodeIdentifier.equals(stmt.argument()))
798             .findFirst()
799             .orElseThrow(() -> notPresent(parent, "Grouping", nodeIdentifier));
800         deque.addLast(ret);
801         ++groupingDepth;
802         return ret;
803     }
804
805     private @NonNull GroupingEffectiveStatement pushFirstGrouping(final @NonNull QName nodeIdentifier) {
806         final ModuleEffectiveStatement module = getModule(nodeIdentifier);
807         final GroupingEffectiveStatement ret = pushGrouping(module, nodeIdentifier);
808         currentModule = module;
809         return ret;
810     }
811
812     private @NonNull SchemaTreeEffectiveStatement<?> pushSchema(final @NonNull QName nodeIdentifier) {
813         final EffectiveStatement<?, ?> parent = deque.peekLast();
814         return parent != null ? pushSchema(parent, nodeIdentifier) : pushFirstSchema(nodeIdentifier);
815     }
816
817     private @NonNull SchemaTreeEffectiveStatement<?> pushSchema(final EffectiveStatement<?, ?> parent,
818             final @NonNull QName nodeIdentifier) {
819         checkState(parent instanceof SchemaTreeAwareEffectiveStatement, "Cannot descend schema tree at %s", parent);
820         return pushSchema((SchemaTreeAwareEffectiveStatement<?, ?>) parent, nodeIdentifier);
821     }
822
823     private @NonNull SchemaTreeEffectiveStatement<?> pushSchema(
824             final @NonNull SchemaTreeAwareEffectiveStatement<?, ?> parent, final @NonNull QName nodeIdentifier) {
825         final SchemaTreeEffectiveStatement<?> ret = parent.findSchemaTreeNode(nodeIdentifier)
826             .orElseThrow(() -> notPresent(parent, "Schema tree child ", nodeIdentifier));
827         deque.addLast(ret);
828         return ret;
829     }
830
831     private @NonNull SchemaTreeEffectiveStatement<?> pushFirstSchema(final @NonNull QName nodeIdentifier) {
832         final ModuleEffectiveStatement module = getModule(nodeIdentifier);
833         final SchemaTreeEffectiveStatement<?> ret = pushSchema(module, nodeIdentifier);
834         currentModule = module;
835         return ret;
836     }
837
838     private @NonNull DataTreeEffectiveStatement<?> pushData(final @NonNull QName nodeIdentifier) {
839         final EffectiveStatement<?, ?> parent = deque.peekLast();
840         return parent != null ? pushData(parent, nodeIdentifier) : pushFirstData(nodeIdentifier);
841     }
842
843     private @NonNull DataTreeEffectiveStatement<?> pushData(final EffectiveStatement<?, ?> parent,
844             final @NonNull QName nodeIdentifier) {
845         checkState(parent instanceof DataTreeAwareEffectiveStatement, "Cannot descend data tree at %s", parent);
846         return pushData((DataTreeAwareEffectiveStatement<?, ?>) parent, nodeIdentifier);
847     }
848
849     private @NonNull DataTreeEffectiveStatement<?> pushData(final @NonNull DataTreeAwareEffectiveStatement<?, ?> parent,
850             final @NonNull QName nodeIdentifier) {
851         final DataTreeEffectiveStatement<?> ret = parent.findDataTreeNode(nodeIdentifier)
852             .orElseThrow(() -> notPresent(parent, "Data tree child", nodeIdentifier));
853         deque.addLast(ret);
854         clean = false;
855         return ret;
856     }
857
858     private @NonNull DataTreeEffectiveStatement<?> pushFirstData(final @NonNull QName nodeIdentifier) {
859         final ModuleEffectiveStatement module = getModule(nodeIdentifier);
860         final DataTreeEffectiveStatement<?> ret = pushData(module, nodeIdentifier);
861         currentModule = module;
862         return ret;
863     }
864
865     private @NonNull TypedefEffectiveStatement pushTypedef(final @NonNull QName nodeIdentifier) {
866         final EffectiveStatement<?, ?> parent = deque.peekLast();
867         return parent != null ? pushTypedef(parent, nodeIdentifier) : pushFirstTypedef(nodeIdentifier);
868     }
869
870     private @NonNull TypedefEffectiveStatement pushTypedef(final @NonNull EffectiveStatement<?, ?> parent,
871             final @NonNull QName nodeIdentifier) {
872         final TypedefEffectiveStatement ret = parent.get(TypedefNamespace.class, nodeIdentifier)
873             .orElseThrow(() -> notPresent(parent, "Typedef", nodeIdentifier));
874         deque.addLast(ret);
875         return ret;
876     }
877
878     private @NonNull TypedefEffectiveStatement pushFirstTypedef(final @NonNull QName nodeIdentifier) {
879         final ModuleEffectiveStatement module = getModule(nodeIdentifier);
880         final TypedefEffectiveStatement ret = pushTypedef(module, nodeIdentifier);
881         currentModule = module;
882         return ret;
883     }
884
885     private @NonNull ModuleEffectiveStatement getModule(final @NonNull QName nodeIdentifier) {
886         final ModuleEffectiveStatement module = effectiveModel.getModuleStatements().get(nodeIdentifier.getModule());
887         checkArgument(module != null, "Module for %s not found", nodeIdentifier);
888         return module;
889     }
890
891     // Unified access to queue iteration for addressing purposes. Since we keep 'logical' steps as executed by user
892     // at this point, conversion to SchemaNodeIdentifier may be needed. We dispatch based on 'clean'.
893     private Collection<QName> simplePathFromRoot() {
894         return clean ? qnames() : reconstructQNames();
895     }
896
897     private Collection<QName> qnames() {
898         return Collections2.transform(deque, stmt -> {
899             final Object argument = stmt.argument();
900             verify(argument instanceof QName, "Unexpected statement %s", stmt);
901             return (QName) argument;
902         });
903     }
904
905     // So there are some data tree steps in the stack... we essentially need to convert a data tree item into a series
906     // of schema tree items. This means at least N searches, but after they are done, we get an opportunity to set the
907     // clean flag.
908     private Collection<QName> reconstructQNames() {
909         return reconstructSchemaInferenceStack().qnames();
910     }
911
912     private SchemaInferenceStack reconstructSchemaInferenceStack() {
913         // Let's walk all statements and decipher them into a temporary stack
914         final SchemaInferenceStack tmp = new SchemaInferenceStack(effectiveModel, deque.size());
915         final Iterator<EffectiveStatement<?, ?>> it = deque.iterator();
916         while (it.hasNext()) {
917             final EffectiveStatement<?, ?> stmt = it.next();
918             // Order of checks is significant
919             if (stmt instanceof DataTreeEffectiveStatement<?> dataTree) {
920                 tmp.resolveDataTreeSteps(dataTree.argument());
921             } else if (stmt instanceof ChoiceEffectiveStatement choice) {
922                 tmp.resolveChoiceSteps(choice.argument());
923             } else if (stmt instanceof SchemaTreeEffectiveStatement<?> schemaTree) {
924                 tmp.enterSchemaTree(schemaTree.argument());
925             } else if (stmt instanceof GroupingEffectiveStatement grouping) {
926                 tmp.enterGrouping(grouping.argument());
927             } else if (stmt instanceof TypedefEffectiveStatement typedef) {
928                 tmp.enterTypedef(typedef.argument());
929             } else {
930                 throw new VerifyException("Unexpected statement " + stmt);
931             }
932         }
933
934         // if the sizes match, we did not jump through hoops. let's remember that for future.
935         if (deque.size() == tmp.deque.size()) {
936             clean = true;
937             return this;
938         }
939         return tmp;
940     }
941
942     private void resolveChoiceSteps(final @NonNull QName nodeIdentifier) {
943         final EffectiveStatement<?, ?> parent = deque.peekLast();
944         if (parent instanceof ChoiceEffectiveStatement choice) {
945             resolveChoiceSteps(choice, nodeIdentifier);
946         } else {
947             enterSchemaTree(nodeIdentifier);
948         }
949     }
950
951     private void resolveChoiceSteps(final @NonNull ChoiceEffectiveStatement parent,
952             final @NonNull QName nodeIdentifier) {
953         for (EffectiveStatement<?, ?> stmt : parent.effectiveSubstatements()) {
954             if (stmt instanceof CaseEffectiveStatement caze) {
955                 final SchemaTreeEffectiveStatement<?> found = caze.findSchemaTreeNode(nodeIdentifier).orElse(null);
956                 if (found instanceof ChoiceEffectiveStatement) {
957                     deque.addLast(caze);
958                     deque.addLast(found);
959                     return;
960                 }
961             }
962         }
963         throw new VerifyException("Failed to resolve " + nodeIdentifier + " in " + parent);
964     }
965
966     private void resolveDataTreeSteps(final @NonNull QName nodeIdentifier) {
967         final EffectiveStatement<?, ?> parent = deque.peekLast();
968         if (parent != null) {
969             verify(parent instanceof SchemaTreeAwareEffectiveStatement, "Unexpected parent %s", parent);
970             resolveDataTreeSteps((SchemaTreeAwareEffectiveStatement<?, ?>) parent, nodeIdentifier);
971             return;
972         }
973
974         final ModuleEffectiveStatement module = getModule(nodeIdentifier);
975         resolveDataTreeSteps(module, nodeIdentifier);
976         currentModule = module;
977     }
978
979     private void resolveDataTreeSteps(final @NonNull SchemaTreeAwareEffectiveStatement<?, ?> parent,
980             final @NonNull QName nodeIdentifier) {
981         // The algebra of identifiers in 'schema tree versus data tree':
982         // - data tree parents are always schema tree parents
983         // - data tree children are always schema tree children
984
985         // that implies that a data tree parent must satisfy schema tree queries with data tree children,
986         // so a successful lookup of 'data tree parent -> child' and 'schema tree parent -> child' has to be the same
987         // for a direct lookup.
988         final SchemaTreeEffectiveStatement<?> found = parent.findSchemaTreeNode(nodeIdentifier).orElse(null);
989         if (found instanceof DataTreeEffectiveStatement) {
990             // ... and it did, we are done
991             deque.addLast(found);
992             return;
993         }
994
995         // Alright, so now it's down to filtering choice/case statements. For that we keep some globally-reused state
996         // and employ a recursive match.
997         final var match = new ArrayDeque<EffectiveStatement<QName, ?>>();
998         for (EffectiveStatement<?, ?> stmt : parent.effectiveSubstatements()) {
999             if (stmt instanceof ChoiceEffectiveStatement choice && searchChoice(match, choice, nodeIdentifier)) {
1000                 deque.addAll(match);
1001                 return;
1002             }
1003         }
1004
1005         throw new VerifyException("Failed to resolve " + nodeIdentifier + " in " + parent);
1006     }
1007
1008     private static boolean searchCase(final @NonNull ArrayDeque<EffectiveStatement<QName, ?>> result,
1009             final @NonNull CaseEffectiveStatement parent, final @NonNull QName nodeIdentifier) {
1010         result.addLast(parent);
1011         for (EffectiveStatement<?, ?> stmt : parent.effectiveSubstatements()) {
1012             if (stmt instanceof DataTreeEffectiveStatement<?> dataTree && nodeIdentifier.equals(stmt.argument())) {
1013                 result.addLast(dataTree);
1014                 return true;
1015             }
1016             if (stmt instanceof ChoiceEffectiveStatement choice && searchChoice(result, choice, nodeIdentifier)) {
1017                 return true;
1018             }
1019         }
1020         result.removeLast();
1021         return false;
1022     }
1023
1024     private static boolean searchChoice(final @NonNull ArrayDeque<EffectiveStatement<QName, ?>> result,
1025             final @NonNull ChoiceEffectiveStatement parent, final @NonNull QName nodeIdentifier) {
1026         result.addLast(parent);
1027         for (EffectiveStatement<?, ?> stmt : parent.effectiveSubstatements()) {
1028             if (stmt instanceof CaseEffectiveStatement caze && searchCase(result, caze, nodeIdentifier)) {
1029                 return true;
1030             }
1031         }
1032         result.removeLast();
1033         return false;
1034     }
1035
1036     private static <T> @NonNull T checkNonNullState(final @Nullable T obj) {
1037         if (obj == null) {
1038             throw new IllegalStateException("Cannot execute on empty stack");
1039         }
1040         return obj;
1041     }
1042
1043     private static @NonNull IllegalArgumentException notPresent(final @NonNull EffectiveStatement<?, ?> parent,
1044             final @NonNull String name, final QName nodeIdentifier) {
1045         return new IllegalArgumentException(name + " " + nodeIdentifier + " not present in " + describeParent(parent));
1046     }
1047
1048     private static @NonNull String describeParent(final @NonNull EffectiveStatement<?, ?> parent) {
1049         // Add just enough information to be useful without being overly-verbose. Note we want to expose namespace
1050         // information, so that we understand what revisions we are dealing with
1051         if (parent instanceof SchemaTreeEffectiveStatement) {
1052             return "schema parent " + parent.argument();
1053         } else if (parent instanceof GroupingEffectiveStatement) {
1054             return "grouping " + parent.argument();
1055         } else if (parent instanceof ModuleEffectiveStatement module) {
1056             return "module " + module.argument().bindTo(module.localQNameModule());
1057         } else {
1058             // Shorthand for QNames, should provide enough context
1059             final Object arg = parent.argument();
1060             return "parent " + (arg instanceof QName ? arg : parent);
1061         }
1062     }
1063 }