Fixed generated code for augmented nodes.
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / util / ParserUtils.xtend
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.parser.util;
9
10 import java.util.ArrayList;
11 import java.util.Arrays;
12 import java.util.Date;
13 import java.util.List;
14 import java.util.Map;
15 import java.util.TreeMap;
16
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
43
44 public final class ParserUtils {
45
46     private new() {
47     }
48
49     /**
50      * Create new SchemaPath from given path and qname.
51      *
52      * @param schemaPath
53      * @param qname
54      * @return new SchemaPath from given path and qname
55      */
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());
60     }
61
62     /**
63      * Get module import referenced by given prefix.
64      *
65      * @param builder
66      *            module to search
67      * @param prefix
68      *            prefix associated with import
69      * @return ModuleImport based on given prefix
70      */
71     public static def ModuleImport getModuleImport(ModuleBuilder builder, String prefix) {
72         for (ModuleImport mi : builder.getModuleImports()) {
73             if (mi.getPrefix().equals(prefix)) {
74                 return mi;
75
76             }
77         }
78         return null;
79     }
80
81     /**
82      * Find dependent module based on given prefix
83      *
84      * @param modules
85      *            all available modules
86      * @param module
87      *            current module
88      * @param prefix
89      *            target module prefix
90      * @param line
91      *            current line in yang model
92      * @return module builder if found, null otherwise
93      */
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;
98
99         if (prefix.equals(module.getPrefix())) {
100             dependentModule = module;
101         } else {
102             val ModuleImport dependentModuleImport = getModuleImport(module, prefix);
103             if (dependentModuleImport === null) {
104                 throw new YangParseException(module.getName(), line, "No import found with prefix '" + prefix + "'.");
105             }
106             val String dependentModuleName = dependentModuleImport.getModuleName();
107             dependentModuleRevision = dependentModuleImport.getRevision();
108
109             val TreeMap<Date, ModuleBuilder> moduleBuildersByRevision = modules.get(dependentModuleName);
110             if (moduleBuildersByRevision === null) {
111                 return null;
112             }
113             if (dependentModuleRevision === null) {
114                 dependentModule = moduleBuildersByRevision.lastEntry().getValue();
115             } else {
116                 dependentModule = moduleBuildersByRevision.get(dependentModuleRevision);
117             }
118         }
119         return dependentModule;
120     }
121
122     /**
123      * Find module from context based on prefix.
124      *
125      * @param context
126      *            schema context
127      * @param currentModule
128      *            current module
129      * @param prefix
130      *            current prefix used to reference dependent module
131      * @param line
132      *            current line in yang model
133      * @return module based on given prefix if found in context, null otherwise
134      */
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 + "'.");
139         }
140         val modulesByRevision = new TreeMap<Date, Module>();
141
142         val dependentModuleImport = ParserUtils.getModuleImport(currentModule, prefix);
143         if (dependentModuleImport === null) {
144             throw new YangParseException(currentModule.getName(), line, "No import found with prefix '" + prefix + "'.");
145         }
146         val dependentModuleName = dependentModuleImport.getModuleName();
147         val dependentModuleRevision = dependentModuleImport.getRevision();
148
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);
154                 }
155                 modulesByRevision.put(revision, contextModule);
156             }
157         }
158
159         var Module result = null;
160         if (dependentModuleRevision === null) {
161             result = modulesByRevision.get(modulesByRevision.firstKey());
162         } else {
163             result = modulesByRevision.get(dependentModuleRevision);
164         }
165         return result;
166     }
167
168     /**
169      * Parse XPath string.
170      *
171      * @param xpathString
172      *            as String
173      * @return SchemaPath from given String
174      */
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>();
179         var QName name;
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));
185                 } else {
186                     name = new QName(null, null, splittedElement.get(0), splittedElement.get(1));
187                 }
188                 path.add(name);
189             }
190         }
191         return new SchemaPath(path, absolute);
192     }
193
194     /**
195      * Add all augment's child nodes to given target.
196      *
197      * @param augment
198      *            builder of augment statement
199      * @param target
200      *            augmentation target node
201      */
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());
208             try {
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());
214             }
215         }
216         for (UsesNodeBuilder usesNode : augment.getUsesNodes()) {
217             val copy = CopyUtils.copyUses(usesNode, target);
218             target.addUsesNode(copy);
219         }
220     }
221
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);
228             }
229             for (uses : dataNodeChild.getUsesNodes()) {
230                 uses.setParentAugment(augment);
231                 uses.setAugmenting(true);
232             }
233         }
234     }
235
236     /**
237      * Add all augment's child nodes to given target.
238      *
239      * @param augment
240      *            builder of augment statement
241      * @param target
242      *            augmentation target choice node
243      */
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);
251         }
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");
256             }
257         }
258     }
259
260     /**
261      * Create new schema path of node based on parent node schema path.
262      *
263      * @param node
264      *            node to correct
265      * @param parentSchemaPath
266      *            schema path of node parent
267      */
268     static def void correctNodePath(SchemaNodeBuilder node, SchemaPath parentSchemaPath) {
269
270         // set correct path
271         val targetNodePath = new ArrayList<QName>(parentSchemaPath.getPath());
272         targetNodePath.add(node.getQName());
273         node.setPath(new SchemaPath(targetNodePath, true));
274
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());
280             }
281         }
282
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());
288             }
289         }
290     }
291
292
293
294     private static def Builder findNode(Builder firstNodeParent, List<QName> path, String moduleName, int line) {
295         var currentName = "";
296         var currentParent = firstNodeParent;
297
298         val max = path.size();
299         var i = 0;
300         while(i < max) {
301             var qname = path.get(i);
302
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);
310                 }
311                 // if not found, search in uses
312                 if (nodeFound == null) {
313                     var found = searchUses(dataNodeContainerParent, currentName);
314                     if(found == null) {
315                         return null;
316                     } else {
317                         currentParent = found;
318                     }
319                 } else {
320                     currentParent = nodeFound;
321                 }
322             } else if (currentParent instanceof ChoiceBuilder) {
323                 val choiceParent = currentParent as ChoiceBuilder;
324                 currentParent = choiceParent.getCaseNodeByName(currentName);
325             } else {
326                 throw new YangParseException(moduleName, line,
327                         "Error in augment parsing: failed to find node " + currentName);
328             }
329
330             // if node in path not found, return null
331             if (currentParent == null) {
332                 return null;
333             }
334             i = i + 1; 
335         }
336         return currentParent;
337     }
338
339     private static def searchNotifications(ModuleBuilder parent, String name) {
340         for(notification : parent.notifications) {
341             if(notification.getQName().localName.equals(name)) {
342                 return notification;
343             }
344         }
345         return null;
346     }
347
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);
355                 return copy;
356             }
357         }
358         return null;
359     }
360     
361     public static def getRpc(ModuleBuilder module,String name) {
362         for(rpc : module.rpcs) {
363             if(name == rpc.QName.localName) {
364                 return rpc;
365             }
366         }
367         return null;
368     }
369     
370     public static def getNotification(ModuleBuilder module,String name) {
371         for(notification : module.notifications) {
372             if(name == notification.QName.localName) {
373                 return notification;
374             }
375         }
376     }
377     
378     private static def nextLevel(List<QName> path){
379         return path.subList(1,path.size)
380     }
381     
382     /**
383      * Find augment target node and perform augmentation.
384      *
385      * @param augment
386      * @param firstNodeParent
387      *            parent of first node in path
388      * @param path
389      *            path to augment target
390      * @return true if augmentation process succeed, false otherwise
391      */
392     public static def boolean processAugmentation(AugmentationSchemaBuilder augment, Builder firstNodeParent,
393         List<QName> path) {
394
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;
398             
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);
407             } else {
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.");
410             }
411             (targetNode as AugmentationTargetBuilder).addAugmentation(augment);
412             augment.setResolved(true);
413             return true;
414         }
415
416         /**
417      * Find node with given name in uses target.
418      *
419      * @param localName
420      *            name of node to find
421      * @param uses
422      *            uses node which target grouping should be searched
423      * @return node with given name if found, null otherwise
424      */
425     private static def DataSchemaNodeBuilder findNodeInUses(String localName, UsesNodeBuilder uses) {
426         for(child : uses.targetChildren) {
427             if (child.getQName().getLocalName().equals(localName)) {
428                 return child;
429             }
430         }
431
432         val target = uses.groupingBuilder;
433         for (child : target.childNodeBuilders) {
434             if (child.getQName().getLocalName().equals(localName)) {
435                 return child;
436             }
437         }
438         for (usesNode : target.usesNodes) {
439             val result = findNodeInUses(localName, usesNode);
440             if (result != null) {
441                 return result;
442             }
443         }
444         return null;
445     }
446
447         /**
448      * Find augment target node in given context and perform augmentation.
449      *
450      * @param augment
451      * @param path
452      *            path to augment target
453      * @param module
454      *            current module
455      * @param prefix
456      *            current prefix of target module
457      * @param context
458      *            SchemaContext containing already resolved modules
459      * @return true if augment process succeed, false otherwise
460      */
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 + ".");
468             }
469
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)) {
476                         currentParent = ntf;
477                     }
478                 }
479             }
480             if (currentParent === null) {
481                 throw new YangParseException(module.getName(), line,
482                     "Error in augment parsing: failed to find node " + currentName + ".");
483             }
484
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);
491                 } else {
492                     throw new YangParseException(augment.getModuleName(), line,
493                         "Error in augment parsing: failed to find node " + currentName);
494                 }
495
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 + ".");
500                 }
501             }
502
503             val oldPath = currentParent.path;
504
505             if (!(currentParent instanceof AugmentationTarget)) {
506                 throw new YangParseException(module.getName(), line,
507                     "Target of type " + currentParent.class + " cannot be augmented.");
508             }
509
510             switch (currentParent) {
511                 case (currentParent instanceof ContainerSchemaNodeImpl): {
512
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);
518                     cb.rebuild();
519                 }
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);
525                     lb.rebuild();
526                     augment.setTargetNodeSchemaPath(new SchemaPath(oldPath.getPath(), oldPath.isAbsolute()));
527                     augment.setResolved(true);
528                 }
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);
534                     chb.rebuild();
535                     augment.setTargetNodeSchemaPath(new SchemaPath(oldPath.getPath(), oldPath.isAbsolute()));
536                     augment.setResolved(true);
537                 }
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);
543                     chcb.rebuild();
544                     augment.setTargetNodeSchemaPath(new SchemaPath(oldPath.getPath(), oldPath.isAbsolute()));
545                     augment.setResolved(true);
546                 }
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);
552                     nb.rebuild();
553                     augment.setTargetNodeSchemaPath(new SchemaPath(oldPath.getPath(), oldPath.isAbsolute()));
554                     augment.setResolved(true);
555                 }
556             }
557             augment.setTargetNodeSchemaPath(new SchemaPath(oldPath.getPath(), oldPath.isAbsolute()));
558             augment.setResolved(true);
559             return true;
560         }
561
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);
571                 }
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);
576             } else {
577                 result = new QName(module.getNamespace(), module.getRevision(), module.getPrefix(), baseString);
578             }
579             return result;
580         }
581
582         /**
583      * Get module in which this node is defined.
584      *
585      * @param node
586      * @return builder of module where this node is defined
587      */
588         public static def ModuleBuilder getParentModule(Builder node) {
589             if (node instanceof ModuleBuilder) {
590                 return node as ModuleBuilder;
591             }
592             var parent = node.getParent();
593             while (!(parent instanceof ModuleBuilder)) {
594                 parent = parent.getParent();
595             }
596             return parent as ModuleBuilder;
597         }
598     }
599