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