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