2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.model.util;
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;
14 import com.google.common.annotations.Beta;
15 import com.google.common.annotations.VisibleForTesting;
16 import com.google.common.base.CharMatcher;
17 import com.google.common.base.Splitter;
18 import com.google.common.collect.Iterables;
19 import java.util.ArrayDeque;
20 import java.util.ArrayList;
21 import java.util.Deque;
22 import java.util.HashSet;
23 import java.util.Iterator;
24 import java.util.List;
25 import java.util.Optional;
27 import java.util.regex.Pattern;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.opendaylight.yangtools.yang.common.AbstractQName;
31 import org.opendaylight.yangtools.yang.common.QName;
32 import org.opendaylight.yangtools.yang.common.QNameModule;
33 import org.opendaylight.yangtools.yang.common.UnqualifiedQName;
34 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
35 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
39 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
42 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
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.LocationPathSteps;
51 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
52 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
53 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
55 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
56 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
59 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
60 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
61 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath;
62 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.AxisStep;
63 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.QNameStep;
64 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.ResolvedQNameStep;
65 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.Step;
66 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.UnresolvedQNameStep;
67 import org.opendaylight.yangtools.yang.xpath.api.YangXPathAxis;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
72 * The Schema Context Util contains support methods for searching through Schema Context modules for specified schema
73 * nodes via Schema Path or Revision Aware XPath. The Schema Context Util is designed as mixin, so it is not
76 public final class SchemaContextUtil {
77 private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
78 private static final Splitter COLON_SPLITTER = Splitter.on(':');
79 private static final Splitter SLASH_SPLITTER = Splitter.on('/').omitEmptyStrings();
80 private static final CharMatcher SPACE = CharMatcher.is(' ');
82 private SchemaContextUtil() {
87 * Method attempts to find DataSchemaNode in Schema Context via specified
88 * Schema Path. The returned DataSchemaNode from method will be the node at
89 * the end of the SchemaPath. If the DataSchemaNode is not present in the
90 * Schema Context the method will return <code>null</code>. <br>
91 * In case that Schema Context or Schema Path are not specified correctly
92 * (i.e. contains <code>null</code> values) the method will throw
93 * IllegalArgumentException.
98 * Schema Path to search for
99 * @return SchemaNode from the end of the Schema Path or <code>null</code>
100 * if the Node is not present.
101 * @throws NullPointerException if context or schemaPath is null
103 public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
104 final Iterable<QName> prefixedPath = schemaPath.getPathFromRoot();
105 if (prefixedPath == null) {
106 LOG.debug("Schema path {} has null path", schemaPath);
110 LOG.trace("Looking for path {} in context {}", schemaPath, context);
111 return findNodeInSchemaContext(context, prefixedPath);
115 * Method attempts to find DataSchemaNode inside of provided Schema Context
116 * and Yang Module accordingly to Non-conditional Revision Aware XPath. The
117 * specified Module MUST be present in Schema Context otherwise the
118 * operation would fail and return <code>null</code>. <br>
119 * The Revision Aware XPath MUST be specified WITHOUT the conditional
120 * statement (i.e. without [cond]) in path, because in this state the Schema
121 * Context is completely unaware of data state and will be not able to
122 * properly resolve XPath. If the XPath contains condition the method will
123 * return IllegalArgumentException. <br>
124 * If the Revision Aware XPath is correct and desired Data Schema Node is
125 * present in Yang module or in depending module in Schema Context the
126 * method will return specified Data Schema Node, otherwise the operation
127 * will fail and method will return <code>null</code>.
133 * @param nonCondXPath
134 * Non Conditional Revision Aware XPath
135 * @return Returns Data Schema Node for specified Schema Context for given
136 * Non-conditional Revision Aware XPath, or <code>null</code> if the
137 * DataSchemaNode is not present in Schema Context.
138 * @throws NullPointerException if any of the arguments is null
140 // FIXME: This entire method is ill-defined, as the resolution process depends on where the XPath is defined --
141 // notably RPCs, actions and notifications modify the data tree temporarily. See sections 6.4.1 and 9.9.2
144 // Most notably we need to understand whether the XPath is being resolved in the data tree, or as part of
145 // a notification/action/RPC, as then the SchemaContext grows tentative nodes ... which could be addressed
146 // via a derived SchemaContext (i.e. this class would have to have a
148 // SchemaContext notificationSchemaContext(SchemaContext delegate, NotificationDefinition notif)
150 // which would then be passed in to a method similar to this one. In static contexts, like MD-SAL codegen,
151 // that feels like an overkill.
152 public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module,
153 final PathExpression nonCondXPath) {
154 requireNonNull(context, "context");
155 requireNonNull(module, "module");
157 final String strXPath = nonCondXPath.getOriginalString();
158 checkArgument(strXPath.indexOf('[') == -1, "Revision Aware XPath may not contain a condition");
159 if (nonCondXPath.isAbsolute()) {
160 return findTargetNode(context, xpathToQNamePath(context, module, strXPath));
166 * Method attempts to find DataSchemaNode inside of provided Schema Context
167 * and Yang Module accordingly to Non-conditional relative Revision Aware
168 * XPath. The specified Module MUST be present in Schema Context otherwise
169 * the operation would fail and return <code>null</code>. <br>
170 * The relative Revision Aware XPath MUST be specified WITHOUT the
171 * conditional statement (i.e. without [cond]) in path, because in this
172 * state the Schema Context is completely unaware of data state and will be
173 * not able to properly resolve XPath. If the XPath contains condition the
174 * method will return IllegalArgumentException. <br>
175 * The Actual Schema Node MUST be specified correctly because from this
176 * Schema Node will search starts. If the Actual Schema Node is not correct
177 * the operation will simply fail, because it will be unable to find desired
178 * DataSchemaNode. <br>
179 * If the Revision Aware XPath doesn't have flag
180 * <code>isAbsolute == false</code> the method will throw
181 * IllegalArgumentException. <br>
182 * If the relative Revision Aware XPath is correct and desired Data Schema
183 * Node is present in Yang module or in depending module in Schema Context
184 * the method will return specified Data Schema Node, otherwise the
185 * operation will fail and method will return <code>null</code>.
191 * @param actualSchemaNode
193 * @param relativeXPath
194 * Relative Non Conditional Revision Aware XPath
195 * @return DataSchemaNode if is present in specified Schema Context for
196 * given relative Revision Aware XPath, otherwise will return
198 * @throws NullPointerException if any argument is null
200 // FIXME: This entire method is ill-defined, as the resolution process depends on where the XPath is defined --
201 // notably RPCs, actions and notifications modify the data tree temporarily. See sections 6.4.1 and 9.9.2
204 // Most notably we need to understand whether the XPath is being resolved in the data tree, or as part of
205 // a notification/action/RPC, as then the SchemaContext grows tentative nodes ... which could be addressed
206 // via a derived SchemaContext (i.e. this class would have to have a
208 // SchemaContext notificationSchemaContext(SchemaContext delegate, NotificationDefinition notif)
210 // which would then be passed in to a method similar to this one. In static contexts, like MD-SAL codegen,
211 // that feels like an overkill.
212 // FIXME: YANGTOOLS-1052: this is a static analysis util, move it to yang-model-sa
213 public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
214 final SchemaNode actualSchemaNode, final PathExpression relativeXPath) {
215 checkState(!relativeXPath.isAbsolute(), "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
216 + "for non relative Revision Aware XPath use findDataSchemaNode method");
217 return resolveRelativeXPath(context, module, relativeXPath, actualSchemaNode);
221 * Returns parent Yang Module for specified Schema Context in which Schema
222 * Node is declared. If the Schema Node is not present in Schema Context the
223 * operation will return <code>null</code>.
225 * @param context Schema Context
226 * @param schemaNode Schema Node
227 * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
228 * return <code>null</code>
229 * @throws NullPointerException if any of the arguments is null
231 public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
232 final QName qname = schemaNode.getPath().getLastComponent();
233 checkState(qname != null, "Schema Path contains invalid state of path parts. "
234 + "The Schema Path MUST contain at least ONE QName which defines namespace and Local name of path.");
235 return context.findModule(qname.getModule()).orElse(null);
238 public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
239 final QName current = path.iterator().next();
241 LOG.trace("Looking up module {} in context {}", current, path);
242 final Optional<Module> module = context.findModule(current.getModule());
243 if (!module.isPresent()) {
244 LOG.debug("Module {} not found", current);
248 return findNodeInModule(module.get(), path);
252 * Returns NotificationDefinition from Schema Context.
254 * @param schema SchemaContext in which lookup should be performed.
255 * @param path Schema Path of notification
256 * @return Notification schema or null, if notification is not present in schema context.
259 public static @Nullable NotificationDefinition getNotificationSchema(final @NonNull SchemaContext schema,
260 final @NonNull SchemaPath path) {
261 requireNonNull(schema, "Schema context must not be null.");
262 requireNonNull(path, "Schema path must not be null.");
263 for (final NotificationDefinition potential : schema.getNotifications()) {
264 if (path.equals(potential.getPath())) {
272 * Returns RPC Input or Output Data container from RPC definition.
274 * @param schema SchemaContext in which lookup should be performed.
275 * @param path Schema path of RPC input/output data container
276 * @return Notification schema or null, if notification is not present in schema context.
279 public static @Nullable ContainerSchemaNode getRpcDataSchema(final @NonNull SchemaContext schema,
280 final @NonNull SchemaPath path) {
281 requireNonNull(schema, "Schema context must not be null.");
282 requireNonNull(path, "Schema path must not be null.");
283 final Iterator<QName> it = path.getPathFromRoot().iterator();
284 checkArgument(it.hasNext(), "Rpc must have QName.");
285 final QName rpcName = it.next();
286 checkArgument(it.hasNext(), "input or output must be part of path.");
287 final QName inOrOut = it.next();
288 for (final RpcDefinition potential : schema.getOperations()) {
289 if (rpcName.equals(potential.getQName())) {
290 return SchemaNodeUtils.getRpcDataSchema(potential, inOrOut);
297 * Extract the identifiers of all modules and submodules which were used to create a particular SchemaContext.
299 * @param context SchemaContext to be examined
300 * @return Set of ModuleIdentifiers.
302 public static Set<SourceIdentifier> getConstituentModuleIdentifiers(final SchemaContext context) {
303 final Set<SourceIdentifier> ret = new HashSet<>();
305 for (Module module : context.getModules()) {
306 ret.add(moduleToIdentifier(module));
308 for (Module submodule : module.getSubmodules()) {
309 ret.add(moduleToIdentifier(submodule));
316 private static SourceIdentifier moduleToIdentifier(final Module module) {
317 return RevisionSourceIdentifier.create(module.getName(), module.getRevision());
320 private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
321 if (!path.iterator().hasNext()) {
322 LOG.debug("No node matching {} found in node {}", path, module);
326 final QName current = path.iterator().next();
327 LOG.trace("Looking for node {} in module {}", current, module);
329 SchemaNode foundNode = null;
330 final Iterable<QName> nextPath = nextLevel(path);
332 foundNode = module.getDataChildByName(current);
333 if (foundNode != null && nextPath.iterator().hasNext()) {
334 foundNode = findNodeIn(foundNode, nextPath);
337 if (foundNode == null) {
338 foundNode = getGroupingByName(module, current);
339 if (foundNode != null && nextPath.iterator().hasNext()) {
340 foundNode = findNodeIn(foundNode, nextPath);
344 if (foundNode == null) {
345 foundNode = getRpcByName(module, current);
346 if (foundNode != null && nextPath.iterator().hasNext()) {
347 foundNode = findNodeIn(foundNode, nextPath);
351 if (foundNode == null) {
352 foundNode = getNotificationByName(module, current);
353 if (foundNode != null && nextPath.iterator().hasNext()) {
354 foundNode = findNodeIn(foundNode, nextPath);
358 if (foundNode == null) {
359 LOG.debug("No node matching {} found in node {}", path, module);
365 private static SchemaNode findNodeIn(final SchemaNode parent, final Iterable<QName> path) {
366 if (!path.iterator().hasNext()) {
367 LOG.debug("No node matching {} found in node {}", path, parent);
371 final QName current = path.iterator().next();
372 LOG.trace("Looking for node {} in node {}", current, parent);
374 SchemaNode foundNode = null;
375 final Iterable<QName> nextPath = nextLevel(path);
377 if (parent instanceof DataNodeContainer) {
378 final DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
380 foundNode = parentDataNodeContainer.getDataChildByName(current);
381 if (foundNode != null && nextPath.iterator().hasNext()) {
382 foundNode = findNodeIn(foundNode, nextPath);
385 if (foundNode == null) {
386 foundNode = getGroupingByName(parentDataNodeContainer, current);
387 if (foundNode != null && nextPath.iterator().hasNext()) {
388 foundNode = findNodeIn(foundNode, nextPath);
393 if (foundNode == null && parent instanceof ActionNodeContainer) {
394 foundNode = ((ActionNodeContainer) parent).getActions().stream()
395 .filter(act -> current.equals(act.getQName())).findFirst().orElse(null);
396 if (foundNode != null && nextPath.iterator().hasNext()) {
397 foundNode = findNodeIn(foundNode, nextPath);
401 if (foundNode == null && parent instanceof NotificationNodeContainer) {
402 foundNode = ((NotificationNodeContainer) parent).getNotifications().stream()
403 .filter(notif -> current.equals(notif.getQName())).findFirst().orElse(null);
404 if (foundNode != null && nextPath.iterator().hasNext()) {
405 foundNode = findNodeIn(foundNode, nextPath);
409 if (foundNode == null && parent instanceof OperationDefinition) {
410 final OperationDefinition parentRpcDefinition = (OperationDefinition) parent;
412 if (current.getLocalName().equals("input")) {
413 foundNode = parentRpcDefinition.getInput();
414 if (foundNode != null && nextPath.iterator().hasNext()) {
415 foundNode = findNodeIn(foundNode, nextPath);
419 if (current.getLocalName().equals("output")) {
420 foundNode = parentRpcDefinition.getOutput();
421 if (foundNode != null && nextPath.iterator().hasNext()) {
422 foundNode = findNodeIn(foundNode, nextPath);
426 if (foundNode == null) {
427 foundNode = getGroupingByName(parentRpcDefinition, current);
428 if (foundNode != null && nextPath.iterator().hasNext()) {
429 foundNode = findNodeIn(foundNode, nextPath);
434 if (foundNode == null && parent instanceof ChoiceSchemaNode) {
435 foundNode = ((ChoiceSchemaNode) parent).getCaseNodeByName(current);
437 if (foundNode != null && nextPath.iterator().hasNext()) {
438 foundNode = findNodeIn(foundNode, nextPath);
441 if (foundNode == null) {
442 // fallback that tries to map into one of the child cases
443 for (final CaseSchemaNode caseNode : ((ChoiceSchemaNode) parent).getCases().values()) {
444 final DataSchemaNode maybeChild = caseNode.getDataChildByName(current);
445 if (maybeChild != null) {
446 foundNode = findNodeIn(maybeChild, nextPath);
453 if (foundNode == null) {
454 LOG.debug("No node matching {} found in node {}", path, parent);
461 private static Iterable<QName> nextLevel(final Iterable<QName> path) {
462 return Iterables.skip(path, 1);
465 private static RpcDefinition getRpcByName(final Module module, final QName name) {
466 for (final RpcDefinition rpc : module.getRpcs()) {
467 if (rpc.getQName().equals(name)) {
474 private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
475 for (final NotificationDefinition notification : module.getNotifications()) {
476 if (notification.getQName().equals(name)) {
483 private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
484 for (final GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
485 if (grouping.getQName().equals(name)) {
492 private static GroupingDefinition getGroupingByName(final OperationDefinition rpc, final QName name) {
493 for (final GroupingDefinition grouping : rpc.getGroupings()) {
494 if (grouping.getQName().equals(name)) {
502 * Transforms string representation of XPath to Queue of QNames. The XPath
503 * is split by "/" and for each part of XPath is assigned correct module in
505 * If Schema Context, Parent Module or XPath string contains
506 * <code>null</code> values, the method will throws IllegalArgumentException
510 * @param parentModule
514 * @return return a list of QName
516 private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule,
517 final String xpath) {
518 final List<QName> path = new ArrayList<>();
519 for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
520 path.add(stringPathPartToQName(context, parentModule, pathComponent));
526 * Transforms part of Prefixed Path as java String to QName. <br>
527 * If the string contains module prefix separated by ":" (i.e.
528 * mod:container) this module is provided from from Parent Module list of
529 * imports. If the Prefixed module is present in Schema Context the QName
530 * can be constructed. <br>
531 * If the Prefixed Path Part does not contains prefix the Parent's Module
532 * namespace is taken for construction of QName. <br>
534 * @param context Schema Context
535 * @param parentModule Parent Module
536 * @param prefixedPathPart Prefixed Path Part string
537 * @return QName from prefixed Path Part String.
538 * @throws NullPointerException if any arguments are null
540 private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule,
541 final String prefixedPathPart) {
542 requireNonNull(context, "context");
544 if (prefixedPathPart.indexOf(':') != -1) {
545 final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
546 final String modulePrefix = prefixedName.next();
548 final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
549 checkArgument(module != null, "Failed to resolve xpath: no module found for prefix %s in module %s",
550 modulePrefix, parentModule.getName());
552 return QName.create(module.getQNameModule(), prefixedName.next());
555 return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
559 * Method will attempt to resolve and provide Module reference for specified module prefix. Each Yang module could
560 * contains multiple imports which MUST be associated with corresponding module prefix. The method simply looks into
561 * module imports and returns the module that is bounded with specified prefix. If the prefix is not present
562 * in module or the prefixed module is not present in specified Schema Context, the method will return {@code null}.
564 * If String prefix is the same as prefix of the specified Module the reference to this module is returned.<br>
566 * @param context Schema Context
567 * @param module Yang Module
568 * @param prefix Module Prefix
569 * @return Module for given prefix in specified Schema Context if is present, otherwise returns <code>null</code>
570 * @throws NullPointerException if any arguments are null
572 private static Module resolveModuleForPrefix(final SchemaContext context, final Module module,
573 final String prefix) {
574 requireNonNull(context, "context");
576 if (prefix.equals(module.getPrefix())) {
580 final Set<ModuleImport> imports = module.getImports();
581 for (final ModuleImport mi : imports) {
582 if (prefix.equals(mi.getPrefix())) {
583 return context.findModule(mi.getModuleName(), mi.getRevision()).orElse(null);
590 * Resolve a relative XPath into a set of QNames.
596 * @param relativeXPath
597 * Non conditional Revision Aware Relative XPath
598 * @param actualSchemaNode
600 * @return target schema node
601 * @throws IllegalArgumentException if any arguments are null
603 private static @Nullable SchemaNode resolveRelativeXPath(final SchemaContext context, final Module module,
604 final PathExpression relativeXPath, final SchemaNode actualSchemaNode) {
605 checkState(!relativeXPath.isAbsolute(), "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
606 + "for non relative Revision Aware XPath use findDataSchemaNode method");
607 checkState(actualSchemaNode.getPath() != null, "Schema Path reference for Leafref cannot be NULL");
609 final String orig = relativeXPath.getOriginalString();
610 return orig.startsWith("deref(") ? resolveDerefPath(context, module, actualSchemaNode, orig)
611 : findTargetNode(context, resolveRelativePath(context, module, actualSchemaNode, doSplitXPath(orig)));
614 private static Iterable<QName> resolveRelativePath(final SchemaContext context, final Module module,
615 final SchemaNode actualSchemaNode, final List<String> steps) {
616 // Find out how many "parent" components there are and trim them
617 final int colCount = normalizeXPath(steps);
618 final List<String> xpaths = colCount == 0 ? steps : steps.subList(colCount, steps.size());
620 final Iterable<QName> schemaNodePath = actualSchemaNode.getPath().getPathFromRoot();
621 if (Iterables.size(schemaNodePath) - colCount >= 0) {
622 return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount),
623 Iterables.transform(xpaths, input -> stringPathPartToQName(context, module, input)));
625 return Iterables.concat(schemaNodePath,
626 Iterables.transform(xpaths, input -> stringPathPartToQName(context, module, input)));
629 private static SchemaNode resolveDerefPath(final SchemaContext context, final Module module,
630 final SchemaNode actualSchemaNode, final String xpath) {
631 final int paren = xpath.indexOf(')', 6);
632 checkArgument(paren != -1, "Cannot find matching parentheses in %s", xpath);
634 final String derefArg = SPACE.trimFrom(xpath.substring(6, paren));
635 // Look up the node which we need to reference
636 final SchemaNode derefTarget = findTargetNode(context, resolveRelativePath(context, module, actualSchemaNode,
637 doSplitXPath(derefArg)));
638 checkArgument(derefTarget != null, "Cannot find deref(%s) target node %s in context of %s", derefArg,
640 checkArgument(derefTarget instanceof TypedDataSchemaNode, "deref(%s) resolved to non-typed %s", derefArg,
643 // We have a deref() target, decide what to do about it
644 final TypeDefinition<?> targetType = ((TypedDataSchemaNode) derefTarget).getType();
645 if (targetType instanceof InstanceIdentifierTypeDefinition) {
646 // Static inference breaks down, we cannot determine where this points to
647 // FIXME: dedicated exception, users can recover from it, derive from IAE
648 throw new UnsupportedOperationException("Cannot infer instance-identifier reference " + targetType);
651 // deref() is define only for instance-identifier and leafref types, handle the latter
652 checkArgument(targetType instanceof LeafrefTypeDefinition, "Illegal target type %s", targetType);
654 final PathExpression targetPath = ((LeafrefTypeDefinition) targetType).getPathStatement();
655 LOG.debug("Derefencing path {}", targetPath);
657 final SchemaNode deref = targetPath.isAbsolute()
658 ? findTargetNode(context, actualSchemaNode,
659 ((LocationPathSteps) targetPath.getSteps()).getLocationPath())
660 : findDataSchemaNodeForRelativeXPath(context, module, actualSchemaNode, targetPath);
662 LOG.debug("Path {} could not be derefenced", targetPath);
666 checkArgument(deref instanceof LeafSchemaNode, "Unexpected %s reference in %s", deref, targetPath);
668 final List<String> qnames = doSplitXPath(SPACE.trimLeadingFrom(xpath.substring(paren + 1)));
669 return findTargetNode(context, resolveRelativePath(context, module, deref, qnames));
672 private static @Nullable SchemaNode findTargetNode(final SchemaContext context, final SchemaNode actualSchemaNode,
673 final YangLocationPath path) {
674 final QNameModule defaultModule = actualSchemaNode.getQName().getModule();
675 final Deque<QName> ret = new ArrayDeque<>();
676 for (Step step : path.getSteps()) {
677 if (step instanceof AxisStep) {
678 // We only support parent axis steps
679 final YangXPathAxis axis = ((AxisStep) step).getAxis();
680 checkState(axis == YangXPathAxis.PARENT, "Unexpected axis %s", axis);
685 // This has to be a QNameStep
686 checkState(step instanceof QNameStep, "Unhandled step %s in %s", step, path);
688 if (step instanceof ResolvedQNameStep) {
689 qname = ((ResolvedQNameStep) step).getQName();
690 } else if (step instanceof UnresolvedQNameStep) {
691 final AbstractQName toResolve = ((UnresolvedQNameStep) step).getQName();
692 // TODO: should handle qualified QNames, too? parser should have resolved them when we get here...
693 checkState(toResolve instanceof UnqualifiedQName, "Unhandled qname %s in %s", toResolve, path);
694 qname = QName.create(defaultModule, toResolve.getLocalName());
696 throw new IllegalStateException("Unhandled step " + step);
702 return findTargetNode(context, ret);
705 private static @Nullable SchemaNode findTargetNode(final SchemaContext context, final Iterable<QName> qnamePath) {
706 // We do not have enough information about resolution context, hence cannot account for actions, RPCs
707 // and notifications. We therefore attempt to make a best estimate, but this can still fail.
708 final Optional<DataSchemaNode> pureData = context.findDataTreeChild(qnamePath);
709 return pureData.isPresent() ? pureData.get() : findNodeInSchemaContext(context, qnamePath);
713 static int normalizeXPath(final List<String> xpath) {
714 LOG.trace("Normalize {}", xpath);
716 // We need to make multiple passes here, as the leading XPaths as we can have "../abc/../../def", which really
719 // Next up: count leading ".." components
720 int leadingParents = 0;
722 if (leadingParents == xpath.size()) {
723 return leadingParents;
725 if (!"..".equals(xpath.get(leadingParents))) {
732 // Now let's see if there there is a '..' in the rest
733 final int dots = findDots(xpath, leadingParents + 1);
735 return leadingParents;
738 xpath.remove(dots - 1);
739 xpath.remove(dots - 1);
740 LOG.trace("Next iteration {}", xpath);
744 private static int findDots(final List<String> xpath, final int startIndex) {
745 for (int i = startIndex; i < xpath.size(); ++i) {
746 if ("..".equals(xpath.get(i))) {
754 private static List<String> doSplitXPath(final String xpath) {
755 return SLASH_SPLITTER.splitToList(xpath);
759 * Extracts the base type of node on which schema node points to. If target node is again of type
760 * LeafrefTypeDefinition, methods will be call recursively until it reach concrete type definition.
762 * @param typeDefinition
763 * type of node which will be extracted
764 * @param schemaContext
768 * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null
769 * is there to preserve backwards compatibility)
771 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
772 final SchemaContext schemaContext, final SchemaNode schema) {
773 PathExpression pathStatement = typeDefinition.getPathStatement();
774 pathStatement = new PathExpressionImpl(stripConditionsFromXPathString(pathStatement),
775 pathStatement.isAbsolute());
777 final DataSchemaNode dataSchemaNode;
778 if (pathStatement.isAbsolute()) {
779 SchemaNode baseSchema = schema;
780 while (baseSchema instanceof DerivableSchemaNode) {
781 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
782 if (basePotential.isPresent()) {
783 baseSchema = basePotential.get();
789 Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
790 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule,
793 Module parentModule = findParentModule(schemaContext, schema);
794 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext,
795 parentModule, schema, pathStatement);
798 // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
799 // and current expected behaviour for such cases is to just use pure string
800 // This should throw an exception about incorrect XPath in leafref
801 if (dataSchemaNode == null) {
805 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
807 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
808 return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
811 return targetTypeDefinition;
815 * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qname}. This handle
816 * the case when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other
817 * module as typedef which is then imported to referenced module.
820 * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
822 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
823 final SchemaContext schemaContext, final QName qname) {
824 final PathExpression pathStatement = typeDefinition.getPathStatement();
825 final PathExpression strippedPathStatement = new PathExpressionImpl(
826 stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
827 if (!strippedPathStatement.isAbsolute()) {
831 final Optional<Module> parentModule = schemaContext.findModule(qname.getModule());
832 checkArgument(parentModule.isPresent(), "Failed to find parent module for %s", qname);
834 final DataSchemaNode dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext,
835 parentModule.get(), strippedPathStatement);
836 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
837 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
838 return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
841 return targetTypeDefinition;
844 private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
845 final SchemaNode schemaNode) {
846 checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
847 checkArgument(schemaNode instanceof TypedDataSchemaNode, "Unsupported node %s", schemaNode);
849 TypeDefinition<?> nodeType = ((TypedDataSchemaNode) schemaNode).getType();
850 if (nodeType.getBaseType() != null) {
851 while (nodeType.getBaseType() != null) {
852 nodeType = nodeType.getBaseType();
855 return schemaContext.findModule(nodeType.getQName().getModule()).orElse(null);
858 return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
861 private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
864 * Removes conditions from xPath pointed to target node.
866 * @param pathStatement
867 * xPath to target node
868 * @return string representation of xPath without conditions
871 static String stripConditionsFromXPathString(final PathExpression pathStatement) {
872 return STRIP_PATTERN.matcher(pathStatement.getOriginalString()).replaceAll("");
876 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
879 * a node representing LeafSchemaNode
880 * @return concrete type definition of node value
882 private static TypeDefinition<?> typeDefinition(final LeafSchemaNode node) {
883 TypeDefinition<?> baseType = node.getType();
884 while (baseType.getBaseType() != null) {
885 baseType = baseType.getBaseType();
891 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
894 * a node representing LeafListSchemaNode
895 * @return concrete type definition of node value
897 private static TypeDefinition<?> typeDefinition(final LeafListSchemaNode node) {
898 TypeDefinition<?> baseType = node.getType();
899 while (baseType.getBaseType() != null) {
900 baseType = baseType.getBaseType();
906 * Gets the base type of DataSchemaNode value.
909 * a node representing DataSchemaNode
910 * @return concrete type definition of node value
912 private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
913 if (node instanceof LeafListSchemaNode) {
914 return typeDefinition((LeafListSchemaNode) node);
915 } else if (node instanceof LeafSchemaNode) {
916 return typeDefinition((LeafSchemaNode) node);
918 throw new IllegalArgumentException("Unhandled parameter type: " + node);