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