Merge "Added implementation of InstanceIdentifier for yang-data-api"
[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             childCopy.setAugmenting(true);
206             correctNodePath(child, target.getPath());
207             correctNodePath(childCopy, target.getPath());
208             try {
209                 target.addChildNode(childCopy);
210             } catch (YangParseException e) {
211
212                 // more descriptive message
213                 throw new YangParseException(augment.getModuleName(), augment.getLine(),
214                     "Failed to perform augmentation: " + e.getMessage());
215             }
216
217         }
218         for (UsesNodeBuilder usesNode : augment.getUsesNodes()) {
219             val copy = CopyUtils.copyUses(usesNode, target);
220             target.addUsesNode(copy);
221         }
222     }
223
224     /**
225      * Add all augment's child nodes to given target.
226      *
227      * @param augment
228      *            builder of augment statement
229      * @param target
230      *            augmentation target choice node
231      */
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);
239         }
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");
244             }
245         }
246     }
247
248     /**
249      * Create new schema path of node based on parent node schema path.
250      *
251      * @param node
252      *            node to correct
253      * @param parentSchemaPath
254      *            schema path of node parent
255      */
256     static def void correctNodePath(SchemaNodeBuilder node, SchemaPath parentSchemaPath) {
257
258         // set correct path
259         val targetNodePath = new ArrayList<QName>(parentSchemaPath.getPath());
260         targetNodePath.add(node.getQName());
261         node.setPath(new SchemaPath(targetNodePath, true));
262
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());
268             }
269         }
270
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());
276             }
277         }
278     }
279
280
281
282     private static def Builder findNode(Builder firstNodeParent, List<QName> path, String moduleName, int line) {
283         var currentName = "";
284         var currentParent = firstNodeParent;
285
286         val max = path.size();
287         var i = 0;
288         while(i < max) {
289             var qname = path.get(i);
290
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);
298                 }
299                 // if not found, search in uses
300                 if (nodeFound == null) {
301                     var found = searchUses(dataNodeContainerParent, currentName);
302                     if(found == null) {
303                         return null;
304                     } else {
305                         currentParent = found;
306                     }
307                 } else {
308                     currentParent = nodeFound;
309                 }
310             } else if (currentParent instanceof ChoiceBuilder) {
311                 val choiceParent = currentParent as ChoiceBuilder;
312                 currentParent = choiceParent.getCaseNodeByName(currentName);
313             } else {
314                 throw new YangParseException(moduleName, line,
315                         "Error in augment parsing: failed to find node " + currentName);
316             }
317
318             // if node in path not found, return null
319             if (currentParent == null) {
320                 return null;
321             }
322             i = i + 1; 
323         }
324         return currentParent;
325     }
326
327     private static def searchNotifications(ModuleBuilder parent, String name) {
328         for(notification : parent.notifications) {
329             if(notification.getQName().localName.equals(name)) {
330                 return notification;
331             }
332         }
333         return null;
334     }
335
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);
343                 return copy;
344             }
345         }
346         return null;
347     }
348     
349     public static def getRpc(ModuleBuilder module,String name) {
350         for(rpc : module.rpcs) {
351             if(name == rpc.QName.localName) {
352                 return rpc;
353             }
354         }
355         return null;
356     }
357     
358     public static def getNotification(ModuleBuilder module,String name) {
359         for(notification : module.notifications) {
360             if(name == notification.QName.localName) {
361                 return notification;
362             }
363         }
364     }
365     
366     private static def nextLevel(List<QName> path){
367         return path.subList(1,path.size)
368     }
369     
370     /**
371      * Find augment target node and perform augmentation.
372      *
373      * @param augment
374      * @param firstNodeParent
375      *            parent of first node in path
376      * @param path
377      *            path to augment target
378      * @return true if augmentation process succeed, false otherwise
379      */
380     public static def boolean processAugmentation(AugmentationSchemaBuilder augment, Builder firstNodeParent,
381         List<QName> path) {
382
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;
386             
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);
395             } else {
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.");
398             }
399             (targetNode as AugmentationTargetBuilder).addAugmentation(augment);
400             augment.setResolved(true);
401             return true;
402         }
403
404         /**
405      * Find node with given name in uses target.
406      *
407      * @param localName
408      *            name of node to find
409      * @param uses
410      *            uses node which target grouping should be searched
411      * @return node with given name if found, null otherwise
412      */
413     private static def DataSchemaNodeBuilder findNodeInUses(String localName, UsesNodeBuilder uses) {
414         for(child : uses.targetChildren) {
415             if (child.getQName().getLocalName().equals(localName)) {
416                 return child;
417             }
418         }
419
420         val target = uses.groupingBuilder;
421         for (child : target.childNodeBuilders) {
422             if (child.getQName().getLocalName().equals(localName)) {
423                 return child;
424             }
425         }
426         for (usesNode : target.usesNodes) {
427             val result = findNodeInUses(localName, usesNode);
428             if (result != null) {
429                 return result;
430             }
431         }
432         return null;
433     }
434
435         /**
436      * Find augment target node in given context and perform augmentation.
437      *
438      * @param augment
439      * @param path
440      *            path to augment target
441      * @param module
442      *            current module
443      * @param prefix
444      *            current prefix of target module
445      * @param context
446      *            SchemaContext containing already resolved modules
447      * @return true if augment process succeed, false otherwise
448      */
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 + ".");
456             }
457
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)) {
464                         currentParent = ntf;
465                     }
466                 }
467             }
468             if (currentParent === null) {
469                 throw new YangParseException(module.getName(), line,
470                     "Error in augment parsing: failed to find node " + currentName + ".");
471             }
472
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);
479                 } else {
480                     throw new YangParseException(augment.getModuleName(), line,
481                         "Error in augment parsing: failed to find node " + currentName);
482                 }
483
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 + ".");
488                 }
489             }
490
491             val oldPath = currentParent.path;
492
493             if (!(currentParent instanceof AugmentationTarget)) {
494                 throw new YangParseException(module.getName(), line,
495                     "Target of type " + currentParent.class + " cannot be augmented.");
496             }
497
498             switch (currentParent) {
499                 case (currentParent instanceof ContainerSchemaNodeImpl): {
500
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);
506                     cb.rebuild();
507                 }
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);
513                     lb.rebuild();
514                     augment.setTargetNodeSchemaPath(new SchemaPath(oldPath.getPath(), oldPath.isAbsolute()));
515                     augment.setResolved(true);
516                 }
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);
522                     chb.rebuild();
523                     augment.setTargetNodeSchemaPath(new SchemaPath(oldPath.getPath(), oldPath.isAbsolute()));
524                     augment.setResolved(true);
525                 }
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);
531                     chcb.rebuild();
532                     augment.setTargetNodeSchemaPath(new SchemaPath(oldPath.getPath(), oldPath.isAbsolute()));
533                     augment.setResolved(true);
534                 }
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);
540                     nb.rebuild();
541                     augment.setTargetNodeSchemaPath(new SchemaPath(oldPath.getPath(), oldPath.isAbsolute()));
542                     augment.setResolved(true);
543                 }
544             }
545             augment.setTargetNodeSchemaPath(new SchemaPath(oldPath.getPath(), oldPath.isAbsolute()));
546             augment.setResolved(true);
547             return true;
548         }
549
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);
559                 }
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);
564             } else {
565                 result = new QName(module.getNamespace(), module.getRevision(), module.getPrefix(), baseString);
566             }
567             return result;
568         }
569
570         /**
571      * Get module in which this node is defined.
572      *
573      * @param node
574      * @return builder of module where this node is defined
575      */
576         public static def ModuleBuilder getParentModule(Builder node) {
577             if (node instanceof ModuleBuilder) {
578                 return node as ModuleBuilder;
579             }
580             var parent = node.getParent();
581             while (!(parent instanceof ModuleBuilder)) {
582                 parent = parent.getParent();
583             }
584             return parent as ModuleBuilder;
585         }
586     }
587