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