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