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.parser.util;
10 import java.util.ArrayList;
11 import java.util.Arrays;
12 import java.util.Date;
13 import java.util.List;
15 import java.util.TreeMap;
17 import org.opendaylight.yangtools.yang.common.QName;
18 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
19 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
20 import org.opendaylight.yangtools.yang.model.api.Module;
21 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
22 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
23 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
24 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
25 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
26 import org.opendaylight.yangtools.yang.parser.builder.api.AugmentationSchemaBuilder;
27 import org.opendaylight.yangtools.yang.parser.builder.api.AugmentationTargetBuilder;
28 import org.opendaylight.yangtools.yang.parser.builder.api.Builder;
29 import org.opendaylight.yangtools.yang.parser.builder.api.DataNodeContainerBuilder;
30 import org.opendaylight.yangtools.yang.parser.builder.api.DataSchemaNodeBuilder;
31 import org.opendaylight.yangtools.yang.parser.builder.api.SchemaNodeBuilder;
32 import org.opendaylight.yangtools.yang.parser.builder.api.UsesNodeBuilder;
33 import org.opendaylight.yangtools.yang.parser.builder.impl.ChoiceBuilder;
34 import org.opendaylight.yangtools.yang.parser.builder.impl.ChoiceBuilder.ChoiceNodeImpl;
35 import org.opendaylight.yangtools.yang.parser.builder.impl.ChoiceCaseBuilder;
36 import org.opendaylight.yangtools.yang.parser.builder.impl.ChoiceCaseBuilder.ChoiceCaseNodeImpl;
37 import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder.ContainerSchemaNodeImpl;
38 import org.opendaylight.yangtools.yang.parser.builder.impl.IdentityrefTypeBuilder;
39 import org.opendaylight.yangtools.yang.parser.builder.impl.ListSchemaNodeBuilder.ListSchemaNodeImpl;
40 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
41 import org.opendaylight.yangtools.yang.parser.builder.impl.NotificationBuilder.NotificationDefinitionImpl;
42 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget
44 public final class ParserUtils {
50 * Create new SchemaPath from given path and qname.
54 * @return new SchemaPath from given path and qname
56 public static def SchemaPath createSchemaPath(SchemaPath schemaPath, QName... qname) {
57 val path = new ArrayList<QName>(schemaPath.getPath());
58 path.addAll(Arrays.asList(qname));
59 return new SchemaPath(path, schemaPath.isAbsolute());
63 * Get module import referenced by given prefix.
68 * prefix associated with import
69 * @return ModuleImport based on given prefix
71 public static def ModuleImport getModuleImport(ModuleBuilder builder, String prefix) {
72 for (ModuleImport mi : builder.getModuleImports()) {
73 if (mi.getPrefix().equals(prefix)) {
82 * Find dependent module based on given prefix
85 * all available modules
89 * target module prefix
91 * current line in yang model
92 * @return module builder if found, null otherwise
94 public static def ModuleBuilder findModuleFromBuilders(Map<String, TreeMap<Date, ModuleBuilder>> modules,
95 ModuleBuilder module, String prefix, int line) {
96 var ModuleBuilder dependentModule = null;
97 var Date dependentModuleRevision = null;
99 if (prefix.equals(module.getPrefix())) {
100 dependentModule = module;
102 val ModuleImport dependentModuleImport = getModuleImport(module, prefix);
103 if (dependentModuleImport === null) {
104 throw new YangParseException(module.getName(), line, "No import found with prefix '" + prefix + "'.");
106 val String dependentModuleName = dependentModuleImport.getModuleName();
107 dependentModuleRevision = dependentModuleImport.getRevision();
109 val TreeMap<Date, ModuleBuilder> moduleBuildersByRevision = modules.get(dependentModuleName);
110 if (moduleBuildersByRevision === null) {
113 if (dependentModuleRevision === null) {
114 dependentModule = moduleBuildersByRevision.lastEntry().getValue();
116 dependentModule = moduleBuildersByRevision.get(dependentModuleRevision);
119 return dependentModule;
123 * Find module from context based on prefix.
127 * @param currentModule
130 * current prefix used to reference dependent module
132 * current line in yang model
133 * @return module based on given prefix if found in context, null otherwise
135 public static def Module findModuleFromContext(SchemaContext context, ModuleBuilder currentModule,
136 String prefix, int line) {
137 if (context === null) {
138 throw new YangParseException(currentModule.getName(), line, "Cannot find module with prefix '" + prefix + "'.");
140 val modulesByRevision = new TreeMap<Date, Module>();
142 val dependentModuleImport = ParserUtils.getModuleImport(currentModule, prefix);
143 if (dependentModuleImport === null) {
144 throw new YangParseException(currentModule.getName(), line, "No import found with prefix '" + prefix + "'.");
146 val dependentModuleName = dependentModuleImport.getModuleName();
147 val dependentModuleRevision = dependentModuleImport.getRevision();
149 for (Module contextModule : context.getModules()) {
150 if (contextModule.getName().equals(dependentModuleName)) {
151 var revision = contextModule.getRevision();
152 if (revision === null) {
153 revision = new Date(0L);
155 modulesByRevision.put(revision, contextModule);
159 var Module result = null;
160 if (dependentModuleRevision === null) {
161 result = modulesByRevision.get(modulesByRevision.firstKey());
163 result = modulesByRevision.get(dependentModuleRevision);
169 * Parse XPath string.
173 * @return SchemaPath from given String
175 public static def SchemaPath parseXPathString(String xpathString) {
176 val absolute = xpathString.startsWith("/");
177 val String[] splittedPath = xpathString.split("/");
178 val path = new ArrayList<QName>();
180 for (String pathElement : splittedPath) {
181 if (pathElement.length() > 0) {
182 val String[] splittedElement = pathElement.split(":");
183 if (splittedElement.length == 1) {
184 name = new QName(null, null, null, splittedElement.get(0));
186 name = new QName(null, null, splittedElement.get(0), splittedElement.get(1));
191 return new SchemaPath(path, absolute);
195 * Add all augment's child nodes to given target.
198 * builder of augment statement
200 * augmentation target node
202 public static def void fillAugmentTarget(AugmentationSchemaBuilder augment, DataNodeContainerBuilder target) {
203 for (DataSchemaNodeBuilder child : augment.getChildNodeBuilders()) {
204 val childCopy = CopyUtils.copy(child, target, false);
205 childCopy.setAugmenting(true);
206 correctNodePath(child, target.getPath());
207 correctNodePath(childCopy, target.getPath());
209 target.addChildNode(childCopy);
210 } catch (YangParseException e) {
212 // more descriptive message
213 throw new YangParseException(augment.getModuleName(), augment.getLine(),
214 "Failed to perform augmentation: " + e.getMessage());
218 for (UsesNodeBuilder usesNode : augment.getUsesNodes()) {
219 val copy = CopyUtils.copyUses(usesNode, target);
220 target.addUsesNode(copy);
225 * Add all augment's child nodes to given target.
228 * builder of augment statement
230 * augmentation target choice node
232 public static def void fillAugmentTarget(AugmentationSchemaBuilder augment, ChoiceBuilder target) {
233 for (DataSchemaNodeBuilder builder : augment.getChildNodeBuilders()) {
234 val childCopy = CopyUtils.copy(builder, target, false);
235 childCopy.setAugmenting(true);
236 correctNodePath(builder, target.getPath());
237 correctNodePath(childCopy, target.getPath());
238 target.addCase(childCopy);
240 for (UsesNodeBuilder usesNode : augment.getUsesNodes()) {
241 if (usesNode !== null) {
242 throw new YangParseException(augment.getModuleName(), augment.getLine(),
243 "Error in augment parsing: cannot augment uses to choice");
249 * Create new schema path of node based on parent node schema path.
253 * @param parentSchemaPath
254 * schema path of node parent
256 static def void correctNodePath(SchemaNodeBuilder node, SchemaPath parentSchemaPath) {
259 val targetNodePath = new ArrayList<QName>(parentSchemaPath.getPath());
260 targetNodePath.add(node.getQName());
261 node.setPath(new SchemaPath(targetNodePath, true));
263 // set correct path for all child nodes
264 if (node instanceof DataNodeContainerBuilder) {
265 val dataNodeContainer = node as DataNodeContainerBuilder;
266 for (DataSchemaNodeBuilder child : dataNodeContainer.getChildNodeBuilders()) {
267 correctNodePath(child, node.getPath());
271 // set correct path for all cases
272 if (node instanceof ChoiceBuilder) {
273 val choiceBuilder = node as ChoiceBuilder;
274 for (ChoiceCaseBuilder choiceCaseBuilder : choiceBuilder.getCases()) {
275 correctNodePath(choiceCaseBuilder, node.getPath());
282 private static def Builder findNode(Builder firstNodeParent, List<QName> path, String moduleName, int line) {
283 var currentName = "";
284 var currentParent = firstNodeParent;
286 val max = path.size();
289 var qname = path.get(i);
291 currentName = qname.getLocalName();
292 if (currentParent instanceof DataNodeContainerBuilder) {
293 var dataNodeContainerParent = currentParent as DataNodeContainerBuilder;
294 var SchemaNodeBuilder nodeFound = dataNodeContainerParent.getDataChildByName(currentName);
295 // if not found, search in notifications
296 if (nodeFound == null && currentParent instanceof ModuleBuilder) {
297 nodeFound = searchNotifications(currentParent as ModuleBuilder, currentName);
299 // if not found, search in uses
300 if (nodeFound == null) {
301 var found = searchUses(dataNodeContainerParent, currentName);
305 currentParent = found;
308 currentParent = nodeFound;
310 } else if (currentParent instanceof ChoiceBuilder) {
311 val choiceParent = currentParent as ChoiceBuilder;
312 currentParent = choiceParent.getCaseNodeByName(currentName);
314 throw new YangParseException(moduleName, line,
315 "Error in augment parsing: failed to find node " + currentName);
318 // if node in path not found, return null
319 if (currentParent == null) {
324 return currentParent;
327 private static def searchNotifications(ModuleBuilder parent, String name) {
328 for(notification : parent.notifications) {
329 if(notification.getQName().localName.equals(name)) {
336 private static def searchUses(DataNodeContainerBuilder dataNodeContainerParent, String name) {
337 var currentName = name;
338 for (unb : dataNodeContainerParent.usesNodes) {
339 val result = findNodeInUses(currentName, unb);
340 if (result != null) {
341 var copy = CopyUtils.copy(result, unb.getParent(), true);
342 unb.getTargetChildren().add(copy);
349 public static def getRpc(ModuleBuilder module,String name) {
350 for(rpc : module.rpcs) {
351 if(name == rpc.QName.localName) {
358 public static def getNotification(ModuleBuilder module,String name) {
359 for(notification : module.notifications) {
360 if(name == notification.QName.localName) {
366 private static def nextLevel(List<QName> path){
367 return path.subList(1,path.size)
371 * Find augment target node and perform augmentation.
374 * @param firstNodeParent
375 * parent of first node in path
377 * path to augment target
378 * @return true if augmentation process succeed, false otherwise
380 public static def boolean processAugmentation(AugmentationSchemaBuilder augment, Builder firstNodeParent,
383 // traverse augment target path and try to reach target node
384 val targetNode = findNode(firstNodeParent,path,augment.moduleName,augment.line);
385 if (targetNode === null) return false;
387 if ((targetNode instanceof DataNodeContainerBuilder)) {
388 val targetDataNodeContainer = targetNode as DataNodeContainerBuilder;
389 augment.setTargetNodeSchemaPath(targetDataNodeContainer.getPath());
390 fillAugmentTarget(augment, targetDataNodeContainer);
391 } else if (targetNode instanceof ChoiceBuilder) {
392 val targetChoiceBuilder = targetNode as ChoiceBuilder;
393 augment.setTargetNodeSchemaPath(targetChoiceBuilder.getPath());
394 fillAugmentTarget(augment, targetChoiceBuilder);
396 throw new YangParseException(augment.getModuleName(), augment.getLine(),
397 "Error in augment parsing: The target node MUST be either a container, list, choice, case, input, output, or notification node.");
399 (targetNode as AugmentationTargetBuilder).addAugmentation(augment);
400 augment.setResolved(true);
405 * Find node with given name in uses target.
408 * name of node to find
410 * uses node which target grouping should be searched
411 * @return node with given name if found, null otherwise
413 private static def DataSchemaNodeBuilder findNodeInUses(String localName, UsesNodeBuilder uses) {
414 for(child : uses.targetChildren) {
415 if (child.getQName().getLocalName().equals(localName)) {
420 val target = uses.groupingBuilder;
421 for (child : target.childNodeBuilders) {
422 if (child.getQName().getLocalName().equals(localName)) {
426 for (usesNode : target.usesNodes) {
427 val result = findNodeInUses(localName, usesNode);
428 if (result != null) {
436 * Find augment target node in given context and perform augmentation.
440 * path to augment target
444 * current prefix of target module
446 * SchemaContext containing already resolved modules
447 * @return true if augment process succeed, false otherwise
449 public static def boolean processAugmentationOnContext(AugmentationSchemaBuilder augment, List<QName> path,
450 ModuleBuilder module, String prefix, SchemaContext context) {
451 val int line = augment.getLine();
452 val Module dependentModule = findModuleFromContext(context, module, prefix, line);
453 if (dependentModule === null) {
454 throw new YangParseException(module.getName(), line,
455 "Error in augment parsing: failed to find module with prefix " + prefix + ".");
458 var currentName = path.get(0).getLocalName();
459 var SchemaNode currentParent = dependentModule.getDataChildByName(currentName);
460 if (currentParent === null) {
461 val notifications = dependentModule.getNotifications();
462 for (NotificationDefinition ntf : notifications) {
463 if (ntf.getQName().getLocalName().equals(currentName)) {
468 if (currentParent === null) {
469 throw new YangParseException(module.getName(), line,
470 "Error in augment parsing: failed to find node " + currentName + ".");
473 for (qname : path.nextLevel) {
474 currentName = qname.getLocalName();
475 if (currentParent instanceof DataNodeContainer) {
476 currentParent = (currentParent as DataNodeContainer).getDataChildByName(currentName);
477 } else if (currentParent instanceof ChoiceNode) {
478 currentParent = (currentParent as ChoiceNode).getCaseNodeByName(currentName);
480 throw new YangParseException(augment.getModuleName(), line,
481 "Error in augment parsing: failed to find node " + currentName);
484 // if node in path not found, return false
485 if (currentParent === null) {
486 throw new YangParseException(module.getName(), line,
487 "Error in augment parsing: failed to find node " + currentName + ".");
491 val oldPath = currentParent.path;
493 if (!(currentParent instanceof AugmentationTarget)) {
494 throw new YangParseException(module.getName(), line,
495 "Target of type " + currentParent.class + " cannot be augmented.");
498 switch (currentParent) {
499 case (currentParent instanceof ContainerSchemaNodeImpl): {
501 // includes container, input and output statement
502 val c = currentParent as ContainerSchemaNodeImpl;
503 val cb = c.toBuilder();
504 fillAugmentTarget(augment, cb);
505 (cb as AugmentationTargetBuilder ).addAugmentation(augment);
508 case (currentParent instanceof ListSchemaNodeImpl): {
509 val l = currentParent as ListSchemaNodeImpl;
510 val lb = l.toBuilder();
511 fillAugmentTarget(augment, lb);
512 (lb as AugmentationTargetBuilder ).addAugmentation(augment);
514 augment.setTargetNodeSchemaPath(new SchemaPath(oldPath.getPath(), oldPath.isAbsolute()));
515 augment.setResolved(true);
517 case (currentParent instanceof ChoiceNodeImpl): {
518 val ch = currentParent as ChoiceNodeImpl;
519 val chb = ch.toBuilder();
520 fillAugmentTarget(augment, chb);
521 (chb as AugmentationTargetBuilder ).addAugmentation(augment);
523 augment.setTargetNodeSchemaPath(new SchemaPath(oldPath.getPath(), oldPath.isAbsolute()));
524 augment.setResolved(true);
526 case (currentParent instanceof ChoiceCaseNodeImpl): {
527 val chc = currentParent as ChoiceCaseNodeImpl;
528 val chcb = chc.toBuilder();
529 fillAugmentTarget(augment, chcb);
530 (chcb as AugmentationTargetBuilder ).addAugmentation(augment);
532 augment.setTargetNodeSchemaPath(new SchemaPath(oldPath.getPath(), oldPath.isAbsolute()));
533 augment.setResolved(true);
535 case (currentParent instanceof NotificationDefinitionImpl): {
536 val nd = currentParent as NotificationDefinitionImpl;
537 val nb = nd.toBuilder();
538 fillAugmentTarget(augment, nb);
539 (nb as AugmentationTargetBuilder ).addAugmentation(augment);
541 augment.setTargetNodeSchemaPath(new SchemaPath(oldPath.getPath(), oldPath.isAbsolute()));
542 augment.setResolved(true);
545 augment.setTargetNodeSchemaPath(new SchemaPath(oldPath.getPath(), oldPath.isAbsolute()));
546 augment.setResolved(true);
550 public static def QName findFullQName(Map<String, TreeMap<Date, ModuleBuilder>> modules,
551 ModuleBuilder module, IdentityrefTypeBuilder idref) {
552 var QName result = null;
553 val String baseString = idref.getBaseString();
554 if (baseString.contains(":")) {
555 val String[] splittedBase = baseString.split(":");
556 if (splittedBase.length > 2) {
557 throw new YangParseException(module.getName(), idref.getLine(),
558 "Failed to parse identityref base: " + baseString);
560 val prefix = splittedBase.get(0);
561 val name = splittedBase.get(1);
562 val dependentModule = findModuleFromBuilders(modules, module, prefix, idref.getLine());
563 result = new QName(dependentModule.getNamespace(), dependentModule.getRevision(), prefix, name);
565 result = new QName(module.getNamespace(), module.getRevision(), module.getPrefix(), baseString);
571 * Get module in which this node is defined.
574 * @return builder of module where this node is defined
576 public static def ModuleBuilder getParentModule(Builder node) {
577 if (node instanceof ModuleBuilder) {
578 return node as ModuleBuilder;
580 var parent = node.getParent();
581 while (!(parent instanceof ModuleBuilder)) {
582 parent = parent.getParent();
584 return parent as ModuleBuilder;