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