Fix relative xPath resolution for leafref types
[yangtools.git] / yang / yang-model-util / src / main / java / org / opendaylight / yangtools / yang / model / util / SchemaContextUtil.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. 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 java.util.Objects.requireNonNull;
13
14 import com.google.common.annotations.Beta;
15 import com.google.common.annotations.VisibleForTesting;
16 import com.google.common.base.Splitter;
17 import com.google.common.collect.Iterables;
18 import com.google.common.collect.Lists;
19 import java.util.ArrayDeque;
20 import java.util.ArrayList;
21 import java.util.Arrays;
22 import java.util.Deque;
23 import java.util.HashSet;
24 import java.util.Iterator;
25 import java.util.List;
26 import java.util.Optional;
27 import java.util.Set;
28 import java.util.regex.Pattern;
29 import java.util.stream.Collectors;
30 import org.eclipse.jdt.annotation.NonNull;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.opendaylight.yangtools.yang.common.AbstractQName;
33 import org.opendaylight.yangtools.yang.common.QName;
34 import org.opendaylight.yangtools.yang.common.QNameModule;
35 import org.opendaylight.yangtools.yang.common.UnqualifiedQName;
36 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
37 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
41 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
44 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.Module;
46 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
47 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
48 import org.opendaylight.yangtools.yang.model.api.NotificationNodeContainer;
49 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
50 import org.opendaylight.yangtools.yang.model.api.PathExpression;
51 import org.opendaylight.yangtools.yang.model.api.PathExpression.DerefSteps;
52 import org.opendaylight.yangtools.yang.model.api.PathExpression.LocationPathSteps;
53 import org.opendaylight.yangtools.yang.model.api.PathExpression.Steps;
54 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
55 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
56 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
58 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
59 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
61 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
62 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
63 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
64 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath;
65 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.AxisStep;
66 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.QNameStep;
67 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.Step;
68 import org.opendaylight.yangtools.yang.xpath.api.YangXPathAxis;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
71
72 /**
73  * The Schema Context Util contains support methods for searching through Schema Context modules for specified schema
74  * nodes via Schema Path or Revision Aware XPath. The Schema Context Util is designed as mixin, so it is not
75  * instantiable.
76  */
77 public final class SchemaContextUtil {
78     private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
79     private static final Splitter COLON_SPLITTER = Splitter.on(':');
80     private static final Splitter SLASH_SPLITTER = Splitter.on('/').omitEmptyStrings();
81
82     private SchemaContextUtil() {
83         // Hidden on purpose
84     }
85
86     /**
87      * Method attempts to find DataSchemaNode in Schema Context via specified Schema Path. The returned DataSchemaNode
88      * from method will be the node at the end of the SchemaPath. If the DataSchemaNode is not present in the Schema
89      * Context the method will return {@code null}.
90      *
91      * <p>
92      * In case that Schema Context or Schema Path are not specified correctly (i.e. contains {@code null} values) the
93      * method will throw IllegalArgumentException.
94      *
95      * @param context Schema Context
96      * @param schemaPath Schema Path to search for
97      * @return SchemaNode from the end of the Schema Path or {@code null} if the Node is not present.
98      * @throws NullPointerException if context or schemaPath is null
99      */
100     public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
101         final Iterable<QName> prefixedPath = schemaPath.getPathFromRoot();
102         if (prefixedPath == null) {
103             LOG.debug("Schema path {} has null path", schemaPath);
104             return null;
105         }
106
107         LOG.trace("Looking for path {} in context {}", schemaPath, context);
108         return findNodeInSchemaContext(context, prefixedPath);
109     }
110
111     /**
112      * Attempt to find a DataSchemaNode based on its path from root, similar to
113      * {@link #findDataSchemaNode(SchemaContext, Module, PathExpression)} without requiring an expression.
114      *
115      * @param context Schema Context
116      * @param path Path to search for
117      * @return SchemaNode from the end of the Schema Path or {@code null} if the Node is not present.
118      * @throws NullPointerException if a any argument is null or if the path contains a null element
119      */
120     @Beta
121     public static SchemaNode findDataSchemaNode(final SchemaContext context, final List<QName> path) {
122         return findTargetNode(context, null, YangLocationPath.absolute(
123             path.stream().map(YangXPathAxis.CHILD::asStep).collect(Collectors.toList())));
124     }
125
126     /**
127      * Attempt to find a DataSchemaNode based on its path from root, similar to
128      * {@link #findDataSchemaNode(SchemaContext, Module, PathExpression)} without requiring an expression.
129      *
130      * @param context Schema Context
131      * @param path Path to search for
132      * @return SchemaNode from the end of the Schema Path or {@code null} if the Node is not present.
133      * @throws NullPointerException if a any argument is null or if the path contains a null element
134      */
135     @Beta
136     public static SchemaNode findDataSchemaNode(final SchemaContext context, final QName... path) {
137         return findDataSchemaNode(context, Arrays.asList(path));
138     }
139
140     /**
141      * Method attempts to find DataSchemaNode inside of provided Schema Context
142      * and Yang Module accordingly to Non-conditional Revision Aware XPath. The
143      * specified Module MUST be present in Schema Context otherwise the
144      * operation would fail and return <code>null</code>. <br>
145      * The Revision Aware XPath MUST be specified WITHOUT the conditional
146      * statement (i.e. without [cond]) in path, because in this state the Schema
147      * Context is completely unaware of data state and will be not able to
148      * properly resolve XPath. If the XPath contains condition the method will
149      * return IllegalArgumentException. <br>
150      * If the Revision Aware XPath is correct and desired Data Schema Node is
151      * present in Yang module or in depending module in Schema Context the
152      * method will return specified Data Schema Node, otherwise the operation
153      * will fail and method will return <code>null</code>.
154      *
155      * @param context
156      *            Schema Context
157      * @param module
158      *            Yang Module
159      * @param nonCondXPath
160      *            Non Conditional Revision Aware XPath
161      * @return Returns Data Schema Node for specified Schema Context for given
162      *         Non-conditional Revision Aware XPath, or <code>null</code> if the
163      *         DataSchemaNode is not present in Schema Context.
164      * @throws NullPointerException if any of the arguments is null
165      * @deprecated Use {@link #findDataTreeSchemaNode(SchemaContext, QNameModule, YangLocationPath)} or
166      *             {@link #findDataTreeSchemaNode(SchemaContext, QNameModule, PathExpression)} instead.
167      */
168     // FIXME: This entire method is ill-defined, as the resolution process depends on  where the XPath is defined --
169     //        notably RPCs, actions and notifications modify the data tree temporarily. See sections 6.4.1 and 9.9.2
170     //        of RFC7950.
171     //
172     //        Most notably we need to understand whether the XPath is being resolved in the data tree, or as part of
173     //        a notification/action/RPC, as then the SchemaContext grows tentative nodes ... which could be addressed
174     //        via a derived SchemaContext (i.e. this class would have to have a
175     //
176     //            SchemaContext notificationSchemaContext(SchemaContext delegate, NotificationDefinition notif)
177     //
178     //        which would then be passed in to a method similar to this one. In static contexts, like MD-SAL codegen,
179     //        that feels like an overkill.
180     @Deprecated
181     public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module,
182             final PathExpression nonCondXPath) {
183         requireNonNull(context, "context");
184         requireNonNull(module, "module");
185
186         final String strXPath = nonCondXPath.getOriginalString();
187         checkArgument(strXPath.indexOf('[') == -1, "Revision Aware XPath may not contain a condition");
188         if (nonCondXPath.isAbsolute()) {
189             return findTargetNode(context, xpathToQNamePath(context, module, strXPath));
190         }
191         return null;
192     }
193
194     @Beta
195     public static SchemaNode findDataTreeSchemaNode(final SchemaContext ctx, final QNameModule localModule,
196             final YangLocationPath absPath) {
197         checkArgument(absPath.isAbsolute(), "Unsupported relative path %s", absPath);
198         return findTargetNode(ctx, localModule, absPath);
199     }
200
201     @Beta
202     public static SchemaNode findDataTreeSchemaNode(final SchemaContext ctx, final QNameModule localModule,
203             final PathExpression absPath) {
204         final Steps pathSteps = absPath.getSteps();
205         if (pathSteps instanceof LocationPathSteps) {
206             return findDataTreeSchemaNode(ctx, localModule, ((LocationPathSteps) pathSteps).getLocationPath());
207         }
208
209         // We would need a reference schema node and no, we do not want to use SchemaContext in its SchemaNode capacity
210         checkArgument(!(pathSteps instanceof DerefSteps), "No reference node for steps %s", pathSteps);
211
212         // We are missing proper API alignment, if this ever triggers
213         throw new IllegalStateException("Unsupported path " + pathSteps);
214     }
215
216     /**
217      * Method attempts to find DataSchemaNode inside of provided Schema Context
218      * and Yang Module accordingly to Non-conditional relative Revision Aware
219      * XPath. The specified Module MUST be present in Schema Context otherwise
220      * the operation would fail and return <code>null</code>. <br>
221      * The relative Revision Aware XPath MUST be specified WITHOUT the
222      * conditional statement (i.e. without [cond]) in path, because in this
223      * state the Schema Context is completely unaware of data state and will be
224      * not able to properly resolve XPath. If the XPath contains condition the
225      * method will return IllegalArgumentException. <br>
226      * The Actual Schema Node MUST be specified correctly because from this
227      * Schema Node will search starts. If the Actual Schema Node is not correct
228      * the operation will simply fail, because it will be unable to find desired
229      * DataSchemaNode. <br>
230      * If the Revision Aware XPath doesn't have flag
231      * <code>isAbsolute == false</code> the method will throw
232      * IllegalArgumentException. <br>
233      * If the relative Revision Aware XPath is correct and desired Data Schema
234      * Node is present in Yang module or in depending module in Schema Context
235      * the method will return specified Data Schema Node, otherwise the
236      * operation will fail and method will return <code>null</code>.
237      *
238      * @param context
239      *            Schema Context
240      * @param module
241      *            Yang Module
242      * @param actualSchemaNode
243      *            Actual Schema Node
244      * @param relativeXPath
245      *            Relative Non Conditional Revision Aware XPath
246      * @return DataSchemaNode if is present in specified Schema Context for
247      *         given relative Revision Aware XPath, otherwise will return
248      *         <code>null</code>.
249      * @throws NullPointerException if any argument is null
250      */
251     // FIXME: This entire method is ill-defined, as the resolution process depends on  where the XPath is defined --
252     //        notably RPCs, actions and notifications modify the data tree temporarily. See sections 6.4.1 and 9.9.2
253     //        of RFC7950.
254     //
255     //        Most notably we need to understand whether the XPath is being resolved in the data tree, or as part of
256     //        a notification/action/RPC, as then the SchemaContext grows tentative nodes ... which could be addressed
257     //        via a derived SchemaContext (i.e. this class would have to have a
258     //
259     //            SchemaContext notificationSchemaContext(SchemaContext delegate, NotificationDefinition notif)
260     //
261     //        which would then be passed in to a method similar to this one. In static contexts, like MD-SAL codegen,
262     //        that feels like an overkill.
263     // FIXME: YANGTOOLS-1052: this is a static analysis util, move it to a dedicated class
264     public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
265             final SchemaNode actualSchemaNode, final PathExpression relativeXPath) {
266         checkState(!relativeXPath.isAbsolute(), "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
267                 + "for non relative Revision Aware XPath use findDataSchemaNode method");
268         return resolveRelativeXPath(context, module, relativeXPath.getOriginalString(), actualSchemaNode);
269     }
270
271     /**
272      * Returns parent Yang Module for specified Schema Context in which Schema
273      * Node is declared. If the Schema Node is not present in Schema Context the
274      * operation will return <code>null</code>.
275      *
276      * @param context Schema Context
277      * @param schemaNode Schema Node
278      * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
279      *         return <code>null</code>
280      * @throws NullPointerException if any of the arguments is null
281      */
282     public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
283         final QName qname = schemaNode.getPath().getLastComponent();
284         checkState(qname != null, "Schema Path contains invalid state of path parts. "
285                 + "The Schema Path MUST contain at least ONE QName  which defines namespace and Local name of path.");
286         return context.findModule(qname.getModule()).orElse(null);
287     }
288
289     public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
290         final QName current = path.iterator().next();
291
292         LOG.trace("Looking up module {} in context {}", current, path);
293         final Optional<Module> module = context.findModule(current.getModule());
294         if (module.isEmpty()) {
295             LOG.debug("Module {} not found", current);
296             return null;
297         }
298
299         return findNodeInModule(module.get(), path);
300     }
301
302     /**
303      * Returns NotificationDefinition from Schema Context.
304      *
305      * @param schema SchemaContext in which lookup should be performed.
306      * @param path Schema Path of notification
307      * @return Notification schema or null, if notification is not present in schema context.
308      */
309     @Beta
310     public static @Nullable NotificationDefinition getNotificationSchema(final @NonNull SchemaContext schema,
311             final @NonNull SchemaPath path) {
312         requireNonNull(schema, "Schema context must not be null.");
313         requireNonNull(path, "Schema path must not be null.");
314         for (final NotificationDefinition potential : schema.getNotifications()) {
315             if (path.equals(potential.getPath())) {
316                 return potential;
317             }
318         }
319         return null;
320     }
321
322     /**
323      * Returns RPC Input or Output Data container from RPC definition.
324      *
325      * @param schema SchemaContext in which lookup should be performed.
326      * @param path Schema path of RPC input/output data container
327      * @return Notification schema or null, if notification is not present in schema context.
328      */
329     @Beta
330     public static @Nullable ContainerSchemaNode getRpcDataSchema(final @NonNull SchemaContext schema,
331             final @NonNull SchemaPath path) {
332         requireNonNull(schema, "Schema context must not be null.");
333         requireNonNull(path, "Schema path must not be null.");
334         final Iterator<QName> it = path.getPathFromRoot().iterator();
335         checkArgument(it.hasNext(), "Rpc must have QName.");
336         final QName rpcName = it.next();
337         checkArgument(it.hasNext(), "input or output must be part of path.");
338         final QName inOrOut = it.next();
339         for (final RpcDefinition potential : schema.getOperations()) {
340             if (rpcName.equals(potential.getQName())) {
341                 return SchemaNodeUtils.getRpcDataSchema(potential, inOrOut);
342             }
343         }
344         return null;
345     }
346
347     /**
348      * Extract the identifiers of all modules and submodules which were used to create a particular SchemaContext.
349      *
350      * @param context SchemaContext to be examined
351      * @return Set of ModuleIdentifiers.
352      */
353     public static Set<SourceIdentifier> getConstituentModuleIdentifiers(final SchemaContext context) {
354         final Set<SourceIdentifier> ret = new HashSet<>();
355
356         for (Module module : context.getModules()) {
357             ret.add(moduleToIdentifier(module));
358
359             for (Module submodule : module.getSubmodules()) {
360                 ret.add(moduleToIdentifier(submodule));
361             }
362         }
363
364         return ret;
365     }
366
367     private static SourceIdentifier moduleToIdentifier(final Module module) {
368         return RevisionSourceIdentifier.create(module.getName(), module.getRevision());
369     }
370
371     private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
372         if (!path.iterator().hasNext()) {
373             LOG.debug("No node matching {} found in node {}", path, module);
374             return null;
375         }
376
377         final QName current = path.iterator().next();
378         LOG.trace("Looking for node {} in module {}", current, module);
379
380         SchemaNode foundNode = null;
381         final Iterable<QName> nextPath = nextLevel(path);
382
383         foundNode = module.getDataChildByName(current);
384         if (foundNode != null && nextPath.iterator().hasNext()) {
385             foundNode = findNodeIn(foundNode, nextPath);
386         }
387
388         if (foundNode == null) {
389             foundNode = getGroupingByName(module, current);
390             if (foundNode != null && nextPath.iterator().hasNext()) {
391                 foundNode = findNodeIn(foundNode, nextPath);
392             }
393         }
394
395         if (foundNode == null) {
396             foundNode = getRpcByName(module, current);
397             if (foundNode != null && nextPath.iterator().hasNext()) {
398                 foundNode = findNodeIn(foundNode, nextPath);
399             }
400         }
401
402         if (foundNode == null) {
403             foundNode = getNotificationByName(module, current);
404             if (foundNode != null && nextPath.iterator().hasNext()) {
405                 foundNode = findNodeIn(foundNode, nextPath);
406             }
407         }
408
409         if (foundNode == null) {
410             LOG.debug("No node matching {} found in node {}", path, module);
411         }
412
413         return foundNode;
414     }
415
416     private static SchemaNode findNodeIn(final SchemaNode parent, final Iterable<QName> path) {
417         if (!path.iterator().hasNext()) {
418             LOG.debug("No node matching {} found in node {}", path, parent);
419             return null;
420         }
421
422         final QName current = path.iterator().next();
423         LOG.trace("Looking for node {} in node {}", current, parent);
424
425         SchemaNode foundNode = null;
426         final Iterable<QName> nextPath = nextLevel(path);
427
428         if (parent instanceof DataNodeContainer) {
429             final DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
430
431             foundNode = parentDataNodeContainer.getDataChildByName(current);
432             if (foundNode != null && nextPath.iterator().hasNext()) {
433                 foundNode = findNodeIn(foundNode, nextPath);
434             }
435
436             if (foundNode == null) {
437                 foundNode = getGroupingByName(parentDataNodeContainer, current);
438                 if (foundNode != null && nextPath.iterator().hasNext()) {
439                     foundNode = findNodeIn(foundNode, nextPath);
440                 }
441             }
442         }
443
444         if (foundNode == null && parent instanceof ActionNodeContainer) {
445             foundNode = ((ActionNodeContainer) parent).getActions().stream()
446                     .filter(act -> current.equals(act.getQName())).findFirst().orElse(null);
447             if (foundNode != null && nextPath.iterator().hasNext()) {
448                 foundNode = findNodeIn(foundNode, nextPath);
449             }
450         }
451
452         if (foundNode == null && parent instanceof NotificationNodeContainer) {
453             foundNode = ((NotificationNodeContainer) parent).getNotifications().stream()
454                     .filter(notif -> current.equals(notif.getQName())).findFirst().orElse(null);
455             if (foundNode != null && nextPath.iterator().hasNext()) {
456                 foundNode = findNodeIn(foundNode, nextPath);
457             }
458         }
459
460         if (foundNode == null && parent instanceof OperationDefinition) {
461             final OperationDefinition parentRpcDefinition = (OperationDefinition) parent;
462
463             if (current.getLocalName().equals("input")) {
464                 foundNode = parentRpcDefinition.getInput();
465                 if (foundNode != null && nextPath.iterator().hasNext()) {
466                     foundNode = findNodeIn(foundNode, nextPath);
467                 }
468             }
469
470             if (current.getLocalName().equals("output")) {
471                 foundNode = parentRpcDefinition.getOutput();
472                 if (foundNode != null && nextPath.iterator().hasNext()) {
473                     foundNode = findNodeIn(foundNode, nextPath);
474                 }
475             }
476
477             if (foundNode == null) {
478                 foundNode = getGroupingByName(parentRpcDefinition, current);
479                 if (foundNode != null && nextPath.iterator().hasNext()) {
480                     foundNode = findNodeIn(foundNode, nextPath);
481                 }
482             }
483         }
484
485         if (foundNode == null && parent instanceof ChoiceSchemaNode) {
486             foundNode = ((ChoiceSchemaNode) parent).getCaseNodeByName(current);
487
488             if (foundNode != null && nextPath.iterator().hasNext()) {
489                 foundNode = findNodeIn(foundNode, nextPath);
490             }
491
492             if (foundNode == null) {
493                 // fallback that tries to map into one of the child cases
494                 for (final CaseSchemaNode caseNode : ((ChoiceSchemaNode) parent).getCases().values()) {
495                     final DataSchemaNode maybeChild = caseNode.getDataChildByName(current);
496                     if (maybeChild != null) {
497                         foundNode = findNodeIn(maybeChild, nextPath);
498                         break;
499                     }
500                 }
501             }
502         }
503
504         if (foundNode == null) {
505             LOG.debug("No node matching {} found in node {}", path, parent);
506         }
507
508         return foundNode;
509
510     }
511
512     private static Iterable<QName> nextLevel(final Iterable<QName> path) {
513         return Iterables.skip(path, 1);
514     }
515
516     private static RpcDefinition getRpcByName(final Module module, final QName name) {
517         for (final RpcDefinition rpc : module.getRpcs()) {
518             if (rpc.getQName().equals(name)) {
519                 return rpc;
520             }
521         }
522         return null;
523     }
524
525     private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
526         for (final NotificationDefinition notification : module.getNotifications()) {
527             if (notification.getQName().equals(name)) {
528                 return notification;
529             }
530         }
531         return null;
532     }
533
534     private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
535         for (final GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
536             if (grouping.getQName().equals(name)) {
537                 return grouping;
538             }
539         }
540         return null;
541     }
542
543     private static GroupingDefinition getGroupingByName(final OperationDefinition rpc, final QName name) {
544         for (final GroupingDefinition grouping : rpc.getGroupings()) {
545             if (grouping.getQName().equals(name)) {
546                 return grouping;
547             }
548         }
549         return null;
550     }
551
552     /**
553      * Transforms string representation of XPath to Queue of QNames. The XPath
554      * is split by "/" and for each part of XPath is assigned correct module in
555      * Schema Path. <br>
556      * If Schema Context, Parent Module or XPath string contains
557      * <code>null</code> values, the method will throws IllegalArgumentException
558      *
559      * @param context
560      *            Schema Context
561      * @param parentModule
562      *            Parent Module
563      * @param xpath
564      *            XPath String
565      * @return return a list of QName
566      */
567     private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule,
568             final String xpath) {
569         final List<QName> path = new ArrayList<>();
570         for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
571             path.add(stringPathPartToQName(context, parentModule, pathComponent));
572         }
573         return path;
574     }
575
576     /**
577      * Transforms part of Prefixed Path as java String to QName. <br>
578      * If the string contains module prefix separated by ":" (i.e.
579      * mod:container) this module is provided from from Parent Module list of
580      * imports. If the Prefixed module is present in Schema Context the QName
581      * can be constructed. <br>
582      * If the Prefixed Path Part does not contains prefix the Parent's Module
583      * namespace is taken for construction of QName. <br>
584      *
585      * @param context Schema Context
586      * @param parentModule Parent Module
587      * @param prefixedPathPart Prefixed Path Part string
588      * @return QName from prefixed Path Part String.
589      * @throws NullPointerException if any arguments are null
590      */
591     private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule,
592             final String prefixedPathPart) {
593         requireNonNull(context, "context");
594
595         if (prefixedPathPart.indexOf(':') != -1) {
596             final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
597             final String modulePrefix = prefixedName.next();
598
599             final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
600             checkArgument(module != null, "Failed to resolve xpath: no module found for prefix %s in module %s",
601                     modulePrefix, parentModule.getName());
602
603             return QName.create(module.getQNameModule(), prefixedName.next());
604         }
605
606         return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
607     }
608
609     /**
610      * Method will attempt to resolve and provide Module reference for specified module prefix. Each Yang module could
611      * contains multiple imports which MUST be associated with corresponding module prefix. The method simply looks into
612      * module imports and returns the module that is bounded with specified prefix. If the prefix is not present
613      * in module or the prefixed module is not present in specified Schema Context, the method will return {@code null}.
614      * <br>
615      * If String prefix is the same as prefix of the specified Module the reference to this module is returned.<br>
616      *
617      * @param context Schema Context
618      * @param module Yang Module
619      * @param prefix Module Prefix
620      * @return Module for given prefix in specified Schema Context if is present, otherwise returns <code>null</code>
621      * @throws NullPointerException if any arguments are null
622      */
623     private static Module resolveModuleForPrefix(final SchemaContext context, final Module module,
624             final String prefix) {
625         requireNonNull(context, "context");
626
627         if (prefix.equals(module.getPrefix())) {
628             return module;
629         }
630
631         final Set<ModuleImport> imports = module.getImports();
632         for (final ModuleImport mi : imports) {
633             if (prefix.equals(mi.getPrefix())) {
634                 return context.findModule(mi.getModuleName(), mi.getRevision()).orElse(null);
635             }
636         }
637         return null;
638     }
639
640     /**
641      * Resolve a relative XPath into a set of QNames.
642      *
643      * @param context
644      *            Schema Context
645      * @param module
646      *            Yang Module
647      * @param pathStr
648      *            xPath of leafref
649      * @param actualSchemaNode
650      *            actual schema node
651      * @return target schema node
652      * @throws IllegalArgumentException if any arguments are null
653      */
654     private static @Nullable SchemaNode resolveRelativeXPath(final SchemaContext context, final Module module,
655             final String pathStr, final SchemaNode actualSchemaNode) {
656         checkState(actualSchemaNode.getPath() != null, "Schema Path reference for Leafref cannot be NULL");
657
658         return pathStr.startsWith("deref(") ? resolveDerefPath(context, module, actualSchemaNode, pathStr)
659                 : findTargetNode(context, resolveRelativePath(context, module, actualSchemaNode,
660                     doSplitXPath(pathStr)));
661     }
662
663     private static Iterable<QName> resolveRelativePath(final SchemaContext context, final Module module,
664             final SchemaNode actualSchemaNode, final List<String> steps) {
665         // Find out how many "parent" components there are and trim them
666         final int colCount = normalizeXPath(steps);
667         final List<String> xpaths = colCount == 0 ? steps : steps.subList(colCount, steps.size());
668
669         final List<QName> walkablePath = createWalkablePath(actualSchemaNode.getPath().getPathFromRoot(),
670                 context, colCount);
671
672         if (walkablePath.size() - colCount >= 0) {
673             return Iterables.concat(Iterables.limit(walkablePath, walkablePath.size() - colCount),
674                     Iterables.transform(xpaths, input -> stringPathPartToQName(context, module, input)));
675         }
676         return Iterables.concat(walkablePath,
677                 Iterables.transform(xpaths, input -> stringPathPartToQName(context, module, input)));
678     }
679
680     /**
681      * Return List of qNames that are walkable using xPath. When getting a path from schema node it will return path
682      * with parents like CaseSchemaNode and ChoiceSchemaNode as well if they are parents of the node. We need to get
683      * rid of these in order to find the node that xPath is pointing to. Also we can not remove any node beyond the
684      * amount of "../" because we will not be able to find the correct schema node from schema context
685      *
686      * @param schemaNodePath list of qNames as a path to the leaf of type leafref
687      * @param context        create schema context
688      * @param colCount       amount of "../" in the xPath expression
689      * @return list of QNames as a path where we should be able to find referenced node
690      */
691     private static List<QName> createWalkablePath(final Iterable<QName> schemaNodePath, final SchemaContext context,
692             final int colCount) {
693         final List<Integer> indexToRemove = new ArrayList<>();
694         List<QName> schemaNodePathRet = Lists.newArrayList(schemaNodePath);
695         for (int j = 0, i = schemaNodePathRet.size() - 1; i >= 0 && j != colCount; i--, j++) {
696             final SchemaNode nodeIn = findTargetNode(context, schemaNodePathRet);
697             if (nodeIn instanceof CaseSchemaNode || nodeIn instanceof ChoiceSchemaNode) {
698                 indexToRemove.add(i);
699                 j--;
700             }
701             schemaNodePathRet.remove(i);
702         }
703         schemaNodePathRet = Lists.newArrayList(schemaNodePath);
704         for (int i : indexToRemove) {
705             schemaNodePathRet.remove(i);
706         }
707         return schemaNodePathRet;
708     }
709
710     private static SchemaNode resolveDerefPath(final SchemaContext context, final Module module,
711             final SchemaNode actualSchemaNode, final String xpath) {
712         final int paren = xpath.indexOf(')', 6);
713         checkArgument(paren != -1, "Cannot find matching parentheses in %s", xpath);
714
715         final String derefArg = xpath.substring(6, paren).strip();
716         // Look up the node which we need to reference
717         final SchemaNode derefTarget = findTargetNode(context, resolveRelativePath(context, module, actualSchemaNode,
718             doSplitXPath(derefArg)));
719         checkArgument(derefTarget != null, "Cannot find deref(%s) target node %s in context of %s", derefArg,
720                 actualSchemaNode);
721         checkArgument(derefTarget instanceof TypedDataSchemaNode, "deref(%s) resolved to non-typed %s", derefArg,
722             derefTarget);
723
724         // We have a deref() target, decide what to do about it
725         final TypeDefinition<?> targetType = ((TypedDataSchemaNode) derefTarget).getType();
726         if (targetType instanceof InstanceIdentifierTypeDefinition) {
727             // Static inference breaks down, we cannot determine where this points to
728             // FIXME: dedicated exception, users can recover from it, derive from IAE
729             throw new UnsupportedOperationException("Cannot infer instance-identifier reference " + targetType);
730         }
731
732         // deref() is define only for instance-identifier and leafref types, handle the latter
733         checkArgument(targetType instanceof LeafrefTypeDefinition, "Illegal target type %s", targetType);
734
735         final PathExpression targetPath = ((LeafrefTypeDefinition) targetType).getPathStatement();
736         LOG.debug("Derefencing path {}", targetPath);
737
738         final SchemaNode deref = targetPath.isAbsolute()
739                 ? findTargetNode(context, actualSchemaNode.getQName().getModule(),
740                     ((LocationPathSteps) targetPath.getSteps()).getLocationPath())
741                         : findDataSchemaNodeForRelativeXPath(context, module, actualSchemaNode, targetPath);
742         if (deref == null) {
743             LOG.debug("Path {} could not be derefenced", targetPath);
744             return null;
745         }
746
747         checkArgument(deref instanceof LeafSchemaNode, "Unexpected %s reference in %s", deref, targetPath);
748
749         final List<String> qnames = doSplitXPath(xpath.substring(paren + 1).stripLeading());
750         return findTargetNode(context, resolveRelativePath(context, module, deref, qnames));
751     }
752
753     private static @Nullable SchemaNode findTargetNode(final SchemaContext context, final QNameModule localNamespace,
754             final YangLocationPath path) {
755         final Deque<QName> ret = new ArrayDeque<>();
756         for (Step step : path.getSteps()) {
757             if (step instanceof AxisStep) {
758                 // We only support parent axis steps
759                 final YangXPathAxis axis = ((AxisStep) step).getAxis();
760                 checkState(axis == YangXPathAxis.PARENT, "Unexpected axis %s", axis);
761                 ret.removeLast();
762                 continue;
763             }
764
765             // This has to be a QNameStep
766             checkState(step instanceof QNameStep, "Unhandled step %s in %s", step, path);
767             ret.addLast(resolve(((QNameStep) step).getQName(), localNamespace));
768         }
769
770         return findTargetNode(context, ret);
771     }
772
773     private static @Nullable SchemaNode findTargetNode(final SchemaContext context, final Iterable<QName> qnamePath) {
774         // We do not have enough information about resolution context, hence cannot account for actions, RPCs
775         // and notifications. We therefore attempt to make a best estimate, but this can still fail.
776         final Optional<DataSchemaNode> pureData = context.findDataTreeChild(qnamePath);
777         return pureData.isPresent() ? pureData.get() : findNodeInSchemaContext(context, qnamePath);
778     }
779
780     private static QName resolve(final AbstractQName toResolve, final QNameModule localNamespace) {
781         if (toResolve instanceof QName) {
782             return (QName) toResolve;
783         } else if (toResolve instanceof UnqualifiedQName) {
784             return ((UnqualifiedQName) toResolve).bindTo(localNamespace);
785         } else {
786             throw new IllegalStateException("Unhandled step " + toResolve);
787         }
788     }
789
790     @VisibleForTesting
791     static int normalizeXPath(final List<String> xpath) {
792         LOG.trace("Normalize {}", xpath);
793
794         // We need to make multiple passes here, as the leading XPaths as we can have "../abc/../../def", which really
795         // is "../../def"
796         while (true) {
797             // Next up: count leading ".." components
798             int leadingParents = 0;
799             while (true) {
800                 if (leadingParents == xpath.size()) {
801                     return leadingParents;
802                 }
803                 if (!"..".equals(xpath.get(leadingParents))) {
804                     break;
805                 }
806
807                 ++leadingParents;
808             }
809
810             // Now let's see if there there is a '..' in the rest
811             final int dots = findDots(xpath, leadingParents + 1);
812             if (dots == -1) {
813                 return leadingParents;
814             }
815
816             xpath.remove(dots - 1);
817             xpath.remove(dots - 1);
818             LOG.trace("Next iteration {}", xpath);
819         }
820     }
821
822     private static int findDots(final List<String> xpath, final int startIndex) {
823         for (int i = startIndex; i < xpath.size(); ++i) {
824             if ("..".equals(xpath.get(i))) {
825                 return i;
826             }
827         }
828
829         return -1;
830     }
831
832     private static List<String> doSplitXPath(final String xpath) {
833         return SLASH_SPLITTER.splitToList(xpath);
834     }
835
836     /**
837      * Extracts the base type of node on which schema node points to. If target node is again of type
838      * LeafrefTypeDefinition, methods will be call recursively until it reach concrete type definition.
839      *
840      * @param typeDefinition
841      *            type of node which will be extracted
842      * @param schemaContext
843      *            Schema Context
844      * @param schema
845      *            Schema Node
846      * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null
847      *         is there to preserve backwards compatibility)
848      */
849     public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
850             final SchemaContext schemaContext, final SchemaNode schema) {
851         final PathExpression pathStatement = typeDefinition.getPathStatement();
852         final String pathStr = stripConditionsFromXPathString(pathStatement);
853
854         final DataSchemaNode dataSchemaNode;
855         if (pathStatement.isAbsolute()) {
856             SchemaNode baseSchema = schema;
857             while (baseSchema instanceof DerivableSchemaNode) {
858                 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
859                 if (basePotential.isPresent()) {
860                     baseSchema = basePotential.get();
861                 } else {
862                     break;
863                 }
864             }
865
866             final Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
867             dataSchemaNode = (DataSchemaNode) findTargetNode(schemaContext,
868                 xpathToQNamePath(schemaContext, parentModule, pathStr));
869         } else {
870             Module parentModule = findParentModule(schemaContext, schema);
871             dataSchemaNode = (DataSchemaNode) resolveRelativeXPath(schemaContext, parentModule, pathStr, schema);
872         }
873
874         // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
875         // and current expected behaviour for such cases is to just use pure string
876         // This should throw an exception about incorrect XPath in leafref
877         if (dataSchemaNode == null) {
878             return null;
879         }
880
881         final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
882
883         if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
884             return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
885         }
886
887         return targetTypeDefinition;
888     }
889
890     /**
891      * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qname}. This handle
892      * the case when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other
893      * module as typedef which is then imported to referenced module.
894      *
895      * <p>
896      * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
897      */
898     public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
899             final SchemaContext schemaContext, final QName qname) {
900         final PathExpression pathStatement = typeDefinition.getPathStatement();
901         if (!pathStatement.isAbsolute()) {
902             return null;
903         }
904
905         final Optional<Module> parentModule = schemaContext.findModule(qname.getModule());
906         checkArgument(parentModule.isPresent(), "Failed to find parent module for %s", qname);
907
908         final DataSchemaNode dataSchemaNode = (DataSchemaNode) findTargetNode(schemaContext,
909             xpathToQNamePath(schemaContext, parentModule.get(), stripConditionsFromXPathString(pathStatement)));
910         final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
911         if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
912             return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
913         }
914
915         return targetTypeDefinition;
916     }
917
918     private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
919             final SchemaNode schemaNode) {
920         checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
921         checkArgument(schemaNode instanceof TypedDataSchemaNode, "Unsupported node %s", schemaNode);
922
923         TypeDefinition<?> nodeType = ((TypedDataSchemaNode) schemaNode).getType();
924         if (nodeType.getBaseType() != null) {
925             while (nodeType.getBaseType() != null) {
926                 nodeType = nodeType.getBaseType();
927             }
928
929             return schemaContext.findModule(nodeType.getQName().getModule()).orElse(null);
930         }
931
932         return findParentModule(schemaContext, schemaNode);
933     }
934
935     private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
936
937     /**
938      * Removes conditions from xPath pointed to target node.
939      *
940      * @param pathStatement
941      *            xPath to target node
942      * @return string representation of xPath without conditions
943      */
944     @VisibleForTesting
945     static String stripConditionsFromXPathString(final PathExpression pathStatement) {
946         return STRIP_PATTERN.matcher(pathStatement.getOriginalString()).replaceAll("");
947     }
948
949     /**
950      * Gets the base type of DataSchemaNode value.
951      *
952      * @param node
953      *            a node representing DataSchemaNode
954      * @return concrete type definition of node value
955      */
956     private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
957         checkArgument(node instanceof TypedDataSchemaNode, "Unhandled parameter type %s", node);
958
959         TypeDefinition<?> current = ((TypedDataSchemaNode) node).getType();
960         // TODO: don't we have a utility for this?
961         TypeDefinition<?> base = current.getBaseType();
962         while (base != null) {
963             current = base;
964             base = current.getBaseType();
965         }
966         return current;
967     }
968 }