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 setNodeAugmenting(childCopy, augment);
206 correctNodePath(child, target.getPath());
207 correctNodePath(childCopy, target.getPath());
209 target.addChildNode(childCopy);
210 } catch (YangParseException e) {
211 // more descriptive message
212 throw new YangParseException(augment.getModuleName(), augment.getLine(),
213 "Failed to perform augmentation: " + e.getMessage());
216 for (UsesNodeBuilder usesNode : augment.getUsesNodes()) {
217 val copy = CopyUtils.copyUses(usesNode, target);
218 target.addUsesNode(copy);
222 private static def void setNodeAugmenting(DataSchemaNodeBuilder child, AugmentationSchemaBuilder augment) {
223 child.setAugmenting(true);
224 if (child instanceof DataNodeContainerBuilder) {
225 val DataNodeContainerBuilder dataNodeChild = child as DataNodeContainerBuilder;
226 for (inner : dataNodeChild.getChildNodeBuilders()) {
227 setNodeAugmenting(inner, augment);
229 for (uses : dataNodeChild.getUsesNodes()) {
230 uses.setParentAugment(augment);
231 uses.setAugmenting(true);
237 * Add all augment's child nodes to given target.
240 * builder of augment statement
242 * augmentation target choice node
244 public static def void fillAugmentTarget(AugmentationSchemaBuilder augment, ChoiceBuilder target) {
245 for (DataSchemaNodeBuilder builder : augment.getChildNodeBuilders()) {
246 val childCopy = CopyUtils.copy(builder, target, false);
247 setNodeAugmenting(childCopy, augment)
248 correctNodePath(builder, target.getPath());
249 correctNodePath(childCopy, target.getPath());
250 target.addCase(childCopy);
252 for (UsesNodeBuilder usesNode : augment.getUsesNodes()) {
253 if (usesNode !== null) {
254 throw new YangParseException(augment.getModuleName(), augment.getLine(),
255 "Error in augment parsing: cannot augment uses to choice");
261 * Create new schema path of node based on parent node schema path.
265 * @param parentSchemaPath
266 * schema path of node parent
268 static def void correctNodePath(SchemaNodeBuilder node, SchemaPath parentSchemaPath) {
271 val targetNodePath = new ArrayList<QName>(parentSchemaPath.getPath());
272 targetNodePath.add(node.getQName());
273 node.setPath(new SchemaPath(targetNodePath, true));
275 // set correct path for all child nodes
276 if (node instanceof DataNodeContainerBuilder) {
277 val dataNodeContainer = node as DataNodeContainerBuilder;
278 for (DataSchemaNodeBuilder child : dataNodeContainer.getChildNodeBuilders()) {
279 correctNodePath(child, node.getPath());
283 // set correct path for all cases
284 if (node instanceof ChoiceBuilder) {
285 val choiceBuilder = node as ChoiceBuilder;
286 for (ChoiceCaseBuilder choiceCaseBuilder : choiceBuilder.getCases()) {
287 correctNodePath(choiceCaseBuilder, node.getPath());
294 private static def Builder findNode(Builder firstNodeParent, List<QName> path, String moduleName, int line) {
295 var currentName = "";
296 var currentParent = firstNodeParent;
298 val max = path.size();
301 var qname = path.get(i);
303 currentName = qname.getLocalName();
304 if (currentParent instanceof DataNodeContainerBuilder) {
305 var dataNodeContainerParent = currentParent as DataNodeContainerBuilder;
306 var SchemaNodeBuilder nodeFound = dataNodeContainerParent.getDataChildByName(currentName);
307 // if not found, search in notifications
308 if (nodeFound == null && currentParent instanceof ModuleBuilder) {
309 nodeFound = searchNotifications(currentParent as ModuleBuilder, currentName);
311 // if not found, search in uses
312 if (nodeFound == null) {
313 var found = searchUses(dataNodeContainerParent, currentName);
317 currentParent = found;
320 currentParent = nodeFound;
322 } else if (currentParent instanceof ChoiceBuilder) {
323 val choiceParent = currentParent as ChoiceBuilder;
324 currentParent = choiceParent.getCaseNodeByName(currentName);
326 throw new YangParseException(moduleName, line,
327 "Error in augment parsing: failed to find node " + currentName);
330 // if node in path not found, return null
331 if (currentParent == null) {
336 return currentParent;
339 private static def searchNotifications(ModuleBuilder parent, String name) {
340 for(notification : parent.notifications) {
341 if(notification.getQName().localName.equals(name)) {
348 private static def searchUses(DataNodeContainerBuilder dataNodeContainerParent, String name) {
349 var currentName = name;
350 for (unb : dataNodeContainerParent.usesNodes) {
351 val result = findNodeInUses(currentName, unb);
352 if (result != null) {
353 var copy = CopyUtils.copy(result, unb.getParent(), true);
354 unb.getTargetChildren().add(copy);
361 public static def getRpc(ModuleBuilder module,String name) {
362 for(rpc : module.rpcs) {
363 if(name == rpc.QName.localName) {
370 public static def getNotification(ModuleBuilder module,String name) {
371 for(notification : module.notifications) {
372 if(name == notification.QName.localName) {
378 private static def nextLevel(List<QName> path){
379 return path.subList(1,path.size)
383 * Find augment target node and perform augmentation.
386 * @param firstNodeParent
387 * parent of first node in path
389 * path to augment target
390 * @return true if augmentation process succeed, false otherwise
392 public static def boolean processAugmentation(AugmentationSchemaBuilder augment, Builder firstNodeParent,
395 // traverse augment target path and try to reach target node
396 val targetNode = findNode(firstNodeParent,path,augment.moduleName,augment.line);
397 if (targetNode === null) return false;
399 if ((targetNode instanceof DataNodeContainerBuilder)) {
400 val targetDataNodeContainer = targetNode as DataNodeContainerBuilder;
401 augment.setTargetNodeSchemaPath(targetDataNodeContainer.getPath());
402 fillAugmentTarget(augment, targetDataNodeContainer);
403 } else if (targetNode instanceof ChoiceBuilder) {
404 val targetChoiceBuilder = targetNode as ChoiceBuilder;
405 augment.setTargetNodeSchemaPath(targetChoiceBuilder.getPath());
406 fillAugmentTarget(augment, targetChoiceBuilder);
408 throw new YangParseException(augment.getModuleName(), augment.getLine(),
409 "Error in augment parsing: The target node MUST be either a container, list, choice, case, input, output, or notification node.");
411 (targetNode as AugmentationTargetBuilder).addAugmentation(augment);
412 augment.setResolved(true);
417 * Find node with given name in uses target.
420 * name of node to find
422 * uses node which target grouping should be searched
423 * @return node with given name if found, null otherwise
425 private static def DataSchemaNodeBuilder findNodeInUses(String localName, UsesNodeBuilder uses) {
426 for(child : uses.targetChildren) {
427 if (child.getQName().getLocalName().equals(localName)) {
432 val target = uses.groupingBuilder;
433 for (child : target.childNodeBuilders) {
434 if (child.getQName().getLocalName().equals(localName)) {
438 for (usesNode : target.usesNodes) {
439 val result = findNodeInUses(localName, usesNode);
440 if (result != null) {
448 * Find augment target node in given context and perform augmentation.
452 * path to augment target
456 * current prefix of target module
458 * SchemaContext containing already resolved modules
459 * @return true if augment process succeed, false otherwise
461 public static def boolean processAugmentationOnContext(AugmentationSchemaBuilder augment, List<QName> path,
462 ModuleBuilder module, String prefix, SchemaContext context) {
463 val int line = augment.getLine();
464 val Module dependentModule = findModuleFromContext(context, module, prefix, line);
465 if (dependentModule === null) {
466 throw new YangParseException(module.getName(), line,
467 "Error in augment parsing: failed to find module with prefix " + prefix + ".");
470 var currentName = path.get(0).getLocalName();
471 var SchemaNode currentParent = dependentModule.getDataChildByName(currentName);
472 if (currentParent === null) {
473 val notifications = dependentModule.getNotifications();
474 for (NotificationDefinition ntf : notifications) {
475 if (ntf.getQName().getLocalName().equals(currentName)) {
480 if (currentParent === null) {
481 throw new YangParseException(module.getName(), line,
482 "Error in augment parsing: failed to find node " + currentName + ".");
485 for (qname : path.nextLevel) {
486 currentName = qname.getLocalName();
487 if (currentParent instanceof DataNodeContainer) {
488 currentParent = (currentParent as DataNodeContainer).getDataChildByName(currentName);
489 } else if (currentParent instanceof ChoiceNode) {
490 currentParent = (currentParent as ChoiceNode).getCaseNodeByName(currentName);
492 throw new YangParseException(augment.getModuleName(), line,
493 "Error in augment parsing: failed to find node " + currentName);
496 // if node in path not found, return false
497 if (currentParent === null) {
498 throw new YangParseException(module.getName(), line,
499 "Error in augment parsing: failed to find node " + currentName + ".");
503 val oldPath = currentParent.path;
505 if (!(currentParent instanceof AugmentationTarget)) {
506 throw new YangParseException(module.getName(), line,
507 "Target of type " + currentParent.class + " cannot be augmented.");
510 switch (currentParent) {
511 case (currentParent instanceof ContainerSchemaNodeImpl): {
513 // includes container, input and output statement
514 val c = currentParent as ContainerSchemaNodeImpl;
515 val cb = c.toBuilder();
516 fillAugmentTarget(augment, cb);
517 (cb as AugmentationTargetBuilder ).addAugmentation(augment);
520 case (currentParent instanceof ListSchemaNodeImpl): {
521 val l = currentParent as ListSchemaNodeImpl;
522 val lb = l.toBuilder();
523 fillAugmentTarget(augment, lb);
524 (lb as AugmentationTargetBuilder ).addAugmentation(augment);
526 augment.setTargetNodeSchemaPath(new SchemaPath(oldPath.getPath(), oldPath.isAbsolute()));
527 augment.setResolved(true);
529 case (currentParent instanceof ChoiceNodeImpl): {
530 val ch = currentParent as ChoiceNodeImpl;
531 val chb = ch.toBuilder();
532 fillAugmentTarget(augment, chb);
533 (chb as AugmentationTargetBuilder ).addAugmentation(augment);
535 augment.setTargetNodeSchemaPath(new SchemaPath(oldPath.getPath(), oldPath.isAbsolute()));
536 augment.setResolved(true);
538 case (currentParent instanceof ChoiceCaseNodeImpl): {
539 val chc = currentParent as ChoiceCaseNodeImpl;
540 val chcb = chc.toBuilder();
541 fillAugmentTarget(augment, chcb);
542 (chcb as AugmentationTargetBuilder ).addAugmentation(augment);
544 augment.setTargetNodeSchemaPath(new SchemaPath(oldPath.getPath(), oldPath.isAbsolute()));
545 augment.setResolved(true);
547 case (currentParent instanceof NotificationDefinitionImpl): {
548 val nd = currentParent as NotificationDefinitionImpl;
549 val nb = nd.toBuilder();
550 fillAugmentTarget(augment, nb);
551 (nb as AugmentationTargetBuilder ).addAugmentation(augment);
553 augment.setTargetNodeSchemaPath(new SchemaPath(oldPath.getPath(), oldPath.isAbsolute()));
554 augment.setResolved(true);
557 augment.setTargetNodeSchemaPath(new SchemaPath(oldPath.getPath(), oldPath.isAbsolute()));
558 augment.setResolved(true);
562 public static def QName findFullQName(Map<String, TreeMap<Date, ModuleBuilder>> modules,
563 ModuleBuilder module, IdentityrefTypeBuilder idref) {
564 var QName result = null;
565 val String baseString = idref.getBaseString();
566 if (baseString.contains(":")) {
567 val String[] splittedBase = baseString.split(":");
568 if (splittedBase.length > 2) {
569 throw new YangParseException(module.getName(), idref.getLine(),
570 "Failed to parse identityref base: " + baseString);
572 val prefix = splittedBase.get(0);
573 val name = splittedBase.get(1);
574 val dependentModule = findModuleFromBuilders(modules, module, prefix, idref.getLine());
575 result = new QName(dependentModule.getNamespace(), dependentModule.getRevision(), prefix, name);
577 result = new QName(module.getNamespace(), module.getRevision(), module.getPrefix(), baseString);
583 * Get module in which this node is defined.
586 * @return builder of module where this node is defined
588 public static def ModuleBuilder getParentModule(Builder node) {
589 if (node instanceof ModuleBuilder) {
590 return node as ModuleBuilder;
592 var parent = node.getParent();
593 while (!(parent instanceof ModuleBuilder)) {
594 parent = parent.getParent();
596 return parent as ModuleBuilder;