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